{"id":19620598,"url":"https://github.com/bas080/sendscript","last_synced_at":"2026-04-14T21:01:00.407Z","repository":{"id":194546735,"uuid":"691317529","full_name":"bas080/sendscript","owner":"bas080","description":"RPC and no-build with composable function calls in a single payload.","archived":false,"fork":false,"pushed_at":"2026-04-14T17:30:27.000Z","size":397,"stargazers_count":0,"open_issues_count":7,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2026-04-14T19:10:11.616Z","etag":null,"topics":["client-server","json","lisp","rpc"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/sendscript","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bas080.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2023-09-14T00:03:25.000Z","updated_at":"2026-04-14T17:30:25.000Z","dependencies_parsed_at":"2024-01-26T18:25:47.078Z","dependency_job_id":"be8c796a-da7e-440d-aa1e-37a2e232b00a","html_url":"https://github.com/bas080/sendscript","commit_stats":null,"previous_names":["bas080/sendscript"],"tags_count":29,"template":false,"template_full_name":null,"purl":"pkg:github/bas080/sendscript","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bas080%2Fsendscript","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bas080%2Fsendscript/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bas080%2Fsendscript/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bas080%2Fsendscript/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bas080","download_url":"https://codeload.github.com/bas080/sendscript/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bas080%2Fsendscript/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31815080,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-14T18:05:02.291Z","status":"ssl_error","status_checked_at":"2026-04-14T18:05:01.765Z","response_time":153,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["client-server","json","lisp","rpc"],"created_at":"2024-11-11T11:19:23.528Z","updated_at":"2026-04-14T21:01:00.396Z","avatar_url":"https://github.com/bas080.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# SendScript\n\nWrite JS code that you can run on servers, browsers or other clients.\n\n[![NPM](https://img.shields.io/npm/v/sendscript?color=blue\\\u0026style=flat-square)](https://www.npmjs.com/package/sendscript)\n[![100% Code Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen?style=flat-square)](#tests)\n[![Standard Code Style](https://img.shields.io/badge/code_style-standard-brightgreen.svg?style=flat-square)](https://standardjs.com)\n[![License](https://img.shields.io/npm/l/sendscript?color=brightgreen\\\u0026style=flat-square)](./LICENSE.txt)\n\n\u003c!-- toc --\u003e\n\n- [Introduction](#introduction)\n- [Reference](#reference)\n  * [defaultLeafParse](#defaultleafparse)\n  * [Parse](#parse)\n  * [parse](#parse)\n  * [References](#references)\n  * [SchemaNode](#schemanode)\n  * [Schema](#schema)\n  * [defaultLeafStringify](#defaultleafstringify)\n  * [Stringify](#stringify)\n  * [stringify](#stringify)\n- [Socket example](#socket-example)\n  * [Module](#module)\n  * [Server](#server)\n  * [Client](#client)\n- [Repl](#repl)\n- [Promises](#promises)\n  * [.then / .catch](#then--catch)\n  * [await](#await)\n- [TypeScript](#typescript)\n- [Schema and Nested Modules](#schema-and-nested-modules)\n  * [Defining a Nested Module](#defining-a-nested-module)\n- [Validation (using Zod)](#validation-using-zod)\n  * [Validating structured input](#validating-structured-input)\n- [Leaf Serializer](#leaf-serializer)\n  * [Example with superjson](#example-with-superjson)\n- [Changelog](#changelog)\n- [License](#license)\n- [Issues](#issues)\n\n\u003c!-- tocstop --\u003e\n\n## Introduction\n\nThere has been interest in improving APIs by allowing aggregations in a single\nrequest. Examples include\n\n*   [JSON-RPC](https://json-rpc.dev/) which allows you to do multiple requests but\n    it does not allow you to compose the return value of one endpoint to be the\n    input/arguments of another.\n\n*   [GraphQL](https://graphql.org/) is very cool but also introduces a new\n    languages and the tooling that is required to wield it.\n\nWhat SendScript attempts is to allow for very expressive queries and mutations\nto be performed that read and write like ordinary JS. That means that the\nqueries and complete programs that are sent to the server from a client can also\njust run on the server as is. The only limitation being the serialization which\nby default is limited by JSON and could be extended by using more advanced\n(de)serialization libraries.\n\nSendScript produces an intermediate JSON representation of the program. Let's\nsee what that looks like.\n\n```js\nimport Stringify from 'sendscript/stringify.mjs'\nimport references from 'sendscript/references.mjs'\n\nconst { add } = references(['add'])\nconst stringify = Stringify()\n\nconsole.log(stringify(add(1,2)))\n```\n\n```json\n[\"call\",[\"ref\",\"add\"],[[\"leaf\",\"1\"],[\"leaf\",\"2\"]]]\n```\n\nWe can then parse that JSON and it will evaluate down to a value.\n\n```js\nimport Parse from 'sendscript/parse.mjs'\n\nconst module = {\n  add(a, b) {\n    return a + b\n  }\n}\n\nconst parse = Parse(['add'], module)\n\nconst program = '[\"call\",[\"ref\",\"add\"],[1,2]]'\n\nconsole.log(parse(program))\n```\n\n```json\n3\n```\n\nSendScript does more than a simple function call. It supports function\ncomposition and even await.\n\nThis package is nothing more than the absolute core of sendscript. It includes:\n\n*   The `references` function to create stubs to write the programs.\n*   `stringify` which takes the program and returns a JSON string.\n*   `parse` which takes the `stringify` JSON string and a real module and returns\n    the result.\n\nThe naming could use more love and there are many things to solve either in the\ncore or around it. Things like supporting more complex (de)serializers, errors\nand maybe mixing client functions with sendscript programs. Contact me if I have\npiqued your interest.\n\n***\n\nSendScript leaves it up to you to choose HTTP, web-sockets or any other method\nof communication between servers and clients that best fits your needs.\n\n## Reference\n\n\u003c!-- Generated by documentation.js. Update this documentation by updating the source code. --\u003e\n\n### defaultLeafParse\n\nDefault deserializer for leaf nodes.\n\n#### Parameters\n\n*   `text` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**\u0026#x20;\n\nReturns **any**\u0026#x20;\n\n### Parse\n\n#### Parameters\n\n*   `schema` **[Schema](#schema)**\u0026#x20;\n*   `env` **Env** runtime environment for refs\n*   `leafParse`   (optional, default `defaultLeafParse`)\n\nReturns **[parse](#parse)**\u0026#x20;\n\n### parse\n\nParses and executes a serialized program.\n\n#### Parameters\n\n*   `program` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** JSON encoded program\n\nReturns **(any | [Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\\\u003cany\u003e)**\u0026#x20;\n\n### References\n\nBuilds a nested API structure from a schema definition.\n\n#### Parameters\n\n*   `schema` **[Schema](#schema)**\u0026#x20;\n*   `parentPath`   (optional, default `[]`)\n\n\u003c!----\u003e\n\n*   Throws **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** If schema format is invalid\n\nReturns **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** Nested instrumented API object\n\n### SchemaNode\n\nA single schema node.\n\nType: ([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | \\[[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), [Schema](#schema)])\n\n### Schema\n\nA schema defines the structure of the runtime API tree.\n\n*   string → leaf node\n*   \\[name, children] → namespace node\n\nSchema is recursive: nodes can contain nested schemas.\n\nType: [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)\u003c[SchemaNode](#schemanode)\u003e\n\n### defaultLeafStringify\n\nDefault strict serializer for leaf values.\n\nRejects non-JSON-safe values.\n\n#### Parameters\n\n*   `x` **any**\u0026#x20;\n\nReturns **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**\u0026#x20;\n\n### Stringify\n\nCreates a stringify function for SendScript AST structures.\n\n#### Parameters\n\n*   `leafStringify`   (optional, default `defaultLeafStringify`)\n\nReturns **[stringify](#stringify)**\u0026#x20;\n\n### stringify\n\nSerializes a program into a JSON string representation.\n\n#### Parameters\n\n*   `program` **any**\u0026#x20;\n\nReturns **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**\u0026#x20;\n\n## Socket example\n\nFor this example we'll use [socket.io][socket.io].\n\n### Module\n\nWe write a simple module.\n\n```js\n// ./example/math.mjs\n\nexport const add = (a, b) =\u003e a + b\nexport const square = (a) =\u003e a * a\n```\n\n### Server\n\nHere a socket.io server that runs SendScript programs.\n\n```js\n// ./example/server.socket.io.mjs\n\nimport { Server } from 'socket.io'\nimport Parse from 'sendscript/parse.mjs'\nimport * as math from './math.mjs'\n\nconst schema = Object.keys(math)\nconst parse = Parse(schema, math)\nconst server = new Server()\nconst port = process.env.PORT || 3000\n\nserver.on('connection', (socket) =\u003e {\n  socket.on('message', async (program, callback) =\u003e {\n    try {\n      const result = parse(program)\n      callback(null, result) // Pass null as the first argument to indicate success\n    } catch (error) {\n      callback(error) // Pass the error to the callback\n    }\n  })\n})\n\nserver.listen(port)\nprocess.title = 'sendscript'\n```\n\n### Client\n\nNow for a client that sends a program to the server.\n\n```js\n// ./example/client.socket.io.mjs\n\nimport socketClient from 'socket.io-client'\nimport Stringify from 'sendscript/stringify.mjs'\nimport references from 'sendscript/references.mjs'\nimport assert from 'node:assert'\n\nconst { add, square } = references(['add', 'square'])\nconst stringify = Stringify()\n\nconst port = process.env.PORT || 3000\nconst client = socketClient(`http://localhost:${port}`)\n\nconst send = (program) =\u003e {\n  return new Promise((resolve, reject) =\u003e {\n    client.emit('message', stringify(program), (error, result) =\u003e {\n      error ? reject(error) : resolve(result)\n    })\n  })\n}\n\n// The program to be sent over the wire\nconst program = square(add(1, add(add(2, 3), 4)))\n\nconst result = await send(program)\n\nconsole.log('Result: ', result)\n\nassert.equal(result, 100)\n\nprocess.exit(0)\n```\n\nNow we run this server and a client script.\n\n```bash\nset -e\n\n# Run the server\nnode ./example/server.socket.io.mjs\u0026\n\n# Run the client example\nnode ./example/client.socket.io.mjs\n\npkill sendscript\n```\n\n    Result:  100\n\n## Repl\n\nSendscript ships with a barebones (no-dependencies) node-repl script. One can\nrun it by simply typing `sendscript` in their console.\n\n\u003e Use the `DEBUG='*'` to enable all logs or `DEBUG='sendscript:*'` for\n\u003e printingonly sendscript logs.\n\n## Promises\n\n### .then / .catch\n\nSupported since vs `v2.3`.\n\n```js\nconst getOrCreatePost = send(createPost(title).catch(createPost(title)))\n```\n\nYou will likely need to define better helpers that makes it safer to handle\nrejections and work with promises. It is however sensible to have this basic\nbehavior for the sendscript DSL and parser.\n\n### await\n\nSendScript supports async/await seamlessly within a single request. This avoids\nthe performance pitfalls of waterfall-style messaging, which can be especially\nslow on high-latency networks.\n\nWhile it's possible to chain promises manually or use utility functions, native\nasync/await support makes your code more readable, modern, and easier to reason\nabout — aligning SendScript with today’s JavaScript best practices.\n\n```js\nconst userId = 'user-123'\nconst program = {\n  unread: await fetchUnreadMessages(userId),\n  emptyTrash: await emptyTrash(userId),\n  archived: await archiveMessages(selectMessages({ old: true })),\n}\n\nconst result = await send(program)\n```\n\nThis operation is done in a single round-trip. The result is an object with the\ndefined properties and returned values.\n\n## TypeScript\n\nThere is a good use-case to write a module in TypeScript.\n\n1.  Obviously the module would have the benefits that TypeScript offers when\n    coding.\n2.  You can use tools like [typedoc][typedoc] to generate docs from your types to\n    share with consumers of your API.\n3.  You can use the types of the module to coerce your client to adopt the\n    module's type.\n\nLet's say we have this module which we use on the server.\n\n```bash\ncat ./example/typescript/math.ts\n```\n\n```ts\nexport const add = (a: number, b: number) =\u003e a + b\nexport const square = (a: number) =\u003e a * a\n```\n\nWe can then coerce the types of the instrumented stubs.\n\n```bash\ncat ./example/typescript/client.ts\n```\n\n```ts\nimport math  from './math.client.ts'\nimport Stringify from 'sendscript/stringify.mjs'\n\nconst stringify = Stringify()\n\n// The return type of this function matches the type passed as the return of the program.\nasync function send\u003cT\u003e(program: T): Promise\u003cT\u003e {\n  return (await fetch('/api', {\n    method: 'POST',\n    body: stringify(program)\n  })).json()\n}\n\nsend(square(add(1, 2)))\n```\n\nWe'll also generate the docs for this module.\n\n```bash\nnpx typedoc --plugin typedoc-plugin-markdown --out ./example/typescript/docs ./example/typescript/math.ts\n```\n\nYou can see the docs [here](./example/typescript/docs/globals.md)\n\n\u003e \\[!NOTE] Although type coercion on the client side can improve the development\n\u003e experience, it does not represent the actual type. Values are subject to\n\u003e serialization and deserialization.\n\n## Schema and Nested Modules\n\nSendscript allows you to define your API as a **nested object of functions**,\nmaking it easy to organize your DSL into modules and submodules. Each function\nis instrumented so that when serialized, it produces a structured reference that\ncan be safely sent and executed elsewhere.\n\n### Defining a Nested Module\n\nYou can define a schema as **an array of function names**\n\n```js\n\nconst schema = [\n  'help',\n  'version',\n\n  ['math', [\n    'add',\n    'sub'\n  ]],\n  ['vector', [\n    'add',\n    'multiply'\n  ]],\n  ['utils', [\n    'identity',\n    'always'\n  ]],\n})\n```\n\nFunctions are referenced via their **path in the module tree**:\n\n```js\nconst { math, vector } = references(schema)\n\nmath.add(1, vector.length(vector.multiply([1, 2], 3)))\n```\n\n## Validation (using Zod)\n\nSendScript focuses on program serialization and execution. For runtime input\nvalidation, you can use [Zod](https://zod.dev).\n\n### Validating structured input\n\n```js\nconst userSchema = z.object({\n  id: z.string().uuid(),\n  name: z.string(),\n  roles: z.array(z.string()),\n})\n\nexport function createUser(user) {\n  userSchema.parse(user)\n\n  return { success: true }\n}\n```\n\n**Benefits**:\n\n*   Ensures arguments match expected types and shapes.\n*   Throws structured errors that can be propagated to clients.\n*   Works with TypeScript for automatic type inference.\n\n## Leaf Serializer\n\nBy default, SendScript uses JSON for serialization, which limits support to\nprimitives and plain objects/arrays. To support richer JavaScript types like\n`Date`, `RegExp`, `BigInt`, `Map`, `Set`, and `undefined`, you can provide\ncustom serialization functions.\n\nThe `stringify` function accepts an optional `leafSerializer` parameter, and\n`parse` accepts an optional `leafDeserializer` parameter. These functions\ncontrol how non-SendScript values (leaves) are encoded and decoded.\n\n### Example with superjson\n\nHere's how to use [superjson](https://github.com/blitz-js/superjson) to support\nextended types:\n\n```js\nimport SuperJSON from 'superjson'\nimport Stringify from 'sendscript/stringify.mjs'\nimport references from 'sendscript/references.mjs'\nimport Parse from 'sendscript/parse.mjs'\n\nconst leafSerializer = (value) =\u003e {\n  if (value === undefined) return JSON.stringify({ __undefined__: true })\n  return JSON.stringify(SuperJSON.serialize(value))\n}\n\nconst leafDeserializer = (text) =\u003e {\n  const parsed = JSON.parse(text)\n  if (parsed \u0026\u0026 parsed.__undefined__ === true) return undefined\n  return SuperJSON.deserialize(parsed)\n}\n\nconst schema = ['processData']\n\nconst { processData } = references(schema)\nconst stringify = Stringify(leafSerializer)\n\n// Program with Date, RegExp, and other types\nconst program = {\n  createdAt: new Date('2020-01-01T00:00:00.000Z'),\n  pattern: /foo/gi,\n  count: BigInt('9007199254740992'),\n  items: new Set([1, 2, 3]),\n  mapping: new Map([\n    ['a', 1],\n    ['b', 2],\n  ]),\n}\n\n// Serialize with custom leaf serializer\nconst json = stringify(processData(program))\n\n// The environment\nconst env = {\n  processData: (data) =\u003e ({\n    success: true,\n    received: data,\n  }),\n}\n\n// Parse with custom leaf deserializer\nconst parse = Parse(schema, env, leadDeserializer)\n\nconst result = parse(json)\n```\n\nThe leaf wrapper format is `['leaf', serializedPayload]`, making it unambiguous\nand safe from colliding with SendScript operators.\n\n## Changelog\n\nThe [changelog][changelog] is generated using the useful\n[auto-changelog][auto-changelog] project.\n\n```bash\nnpx auto-changelog -p\n```\n\n## License\n\nSee the [LICENSE.txt][license] file for details.\n\n## Issues\n\nSee [issues][issues] for roadmap and known bugs.\n\n[license]: ./LICENSE.txt\n\n[socket.io]: https://socket.io/\n\n[changelog]: ./CHANGELOG.md\n\n[auto-changelog]: https://www.npmjs.com/package/auto-changelog\n\n[typedoc]: https://github.com/TypeStrong/typedoc\n\n[issues]: https://github.com/bas080/sendscript/issues\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbas080%2Fsendscript","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbas080%2Fsendscript","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbas080%2Fsendscript/lists"}