@rayfold/server 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +10 -0
  3. package/README.md +70 -0
  4. package/args.d.ts +15 -0
  5. package/args.js +226 -0
  6. package/args.js.map +1 -0
  7. package/batch.d.ts +54 -0
  8. package/batch.js +483 -0
  9. package/batch.js.map +1 -0
  10. package/bindings.d.ts +37 -0
  11. package/bindings.js +284 -0
  12. package/bindings.js.map +1 -0
  13. package/capability-scope.d.ts +8 -0
  14. package/capability-scope.js +19 -0
  15. package/capability-scope.js.map +1 -0
  16. package/capability.d.ts +56 -0
  17. package/capability.js +112 -0
  18. package/capability.js.map +1 -0
  19. package/context.d.ts +74 -0
  20. package/context.js +109 -0
  21. package/context.js.map +1 -0
  22. package/core.d.ts +18 -0
  23. package/core.js +18 -0
  24. package/core.js.map +1 -0
  25. package/cost.d.ts +15 -0
  26. package/cost.js +110 -0
  27. package/cost.js.map +1 -0
  28. package/executor.d.ts +89 -0
  29. package/executor.js +695 -0
  30. package/executor.js.map +1 -0
  31. package/guard.d.ts +33 -0
  32. package/guard.js +65 -0
  33. package/guard.js.map +1 -0
  34. package/http.d.ts +33 -0
  35. package/http.js +379 -0
  36. package/http.js.map +1 -0
  37. package/index.d.ts +8 -0
  38. package/index.js +9 -0
  39. package/index.js.map +1 -0
  40. package/instrumentation.d.ts +36 -0
  41. package/instrumentation.js +2 -0
  42. package/instrumentation.js.map +1 -0
  43. package/live.d.ts +37 -0
  44. package/live.js +240 -0
  45. package/live.js.map +1 -0
  46. package/mcp.d.ts +55 -0
  47. package/mcp.js +314 -0
  48. package/mcp.js.map +1 -0
  49. package/openapi.d.ts +11 -0
  50. package/openapi.js +124 -0
  51. package/openapi.js.map +1 -0
  52. package/package.json +53 -0
  53. package/policy.d.ts +17 -0
  54. package/policy.js +64 -0
  55. package/policy.js.map +1 -0
  56. package/protocol.d.ts +139 -0
  57. package/protocol.js +98 -0
  58. package/protocol.js.map +1 -0
  59. package/server.d.ts +58 -0
  60. package/server.js +79 -0
  61. package/server.js.map +1 -0
  62. package/usage.d.ts +39 -0
  63. package/usage.js +44 -0
  64. package/usage.js.map +1 -0
  65. package/views.d.ts +33 -0
  66. package/views.js +108 -0
  67. package/views.js.map +1 -0
  68. package/wiring.d.ts +16 -0
  69. package/wiring.js +57 -0
  70. package/wiring.js.map +1 -0
  71. package/ws.d.ts +21 -0
  72. package/ws.js +209 -0
  73. package/ws.js.map +1 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,10 @@
1
+ Rayfold
2
+ Copyright 2026 The Rayfold Authors
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ The data in data/gutenberg.json.gz is derived from the Project Gutenberg catalogue
7
+ (https://www.gutenberg.org/ebooks/offline_catalogs.html) and is not covered by this
8
+ project's copyright. See data/README.md for its source. Project Gutenberg is a
9
+ registered trademark of the Project Gutenberg Literary Archive Foundation; Rayfold is
10
+ not affiliated with or endorsed by Project Gutenberg.
package/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # @rayfold/server
2
+
3
+ The Rayfold server for Node.js. Give it a schema and resolvers. It serves batches with pipelining, applies the
4
+ policies, costs and cache rules the schema declares, pushes live-query updates, and can expose REST bindings,
5
+ OpenAPI 3.2 and an MCP endpoint from the same schema.
6
+
7
+ ```sh
8
+ npm install @rayfold/server
9
+ ```
10
+
11
+ ```ts
12
+ import { createRayfoldServer, listen } from "@rayfold/server";
13
+
14
+ interface Book { id: string; title: string; stock: number }
15
+ const books = new Map<string, Book>([["b1", { id: "b1", title: "Dune", stock: 3 }]]);
16
+
17
+ const server = createRayfoldServer({
18
+ schema: `
19
+ entity Book {
20
+ id: ID
21
+ title: String
22
+ stock: Int
23
+ }
24
+ query book(id: ID): Book?
25
+ command restock(id: ID, qty: Int): Book
26
+ `,
27
+ resolvers: {
28
+ Query: {
29
+ book: ({ id }: { id: string }) => books.get(id) ?? null,
30
+ },
31
+ Command: {
32
+ // The returned entity becomes a cache patch, so every client showing Book:b1 updates without refetching.
33
+ restock: ({ id, qty }: { id: string; qty: number }) => {
34
+ const book = books.get(id);
35
+ if (!book) throw new Error(`no book ${id}`);
36
+ book.stock += qty;
37
+ return book;
38
+ },
39
+ },
40
+ },
41
+ });
42
+
43
+ // Commands need a signed-in viewer: turn the request into one (here, a fixed demo token).
44
+ await listen(server, 4000, {
45
+ viewer: (req) => (req.headers.authorization === "Bearer demo" ? { id: "demo-user" } : null),
46
+ });
47
+ ```
48
+
49
+ `POST /rayfold` now answers batches:
50
+
51
+ ```sh
52
+ curl -s localhost:4000/rayfold -H 'content-type: application/rayfold+json' -H 'rayfold-safe: true' \
53
+ -d '{"rayfold":"0.1","ops":[{"id":1,"op":"book","args":{"id":"b1"}}]}'
54
+ ```
55
+
56
+ What else is in the package:
57
+
58
+ | Export | What it does |
59
+ |---|---|
60
+ | `createHttpHandler(server, options)` | The same endpoint as a plain `(req, res)` handler for your own `http` server, Express or Fastify. |
61
+ | `attachWebSocket(server, httpServer)` | Batches and live queries over one WebSocket. |
62
+ | `createBindingHandler(server)` | REST routes from `@http(...)` annotations in the schema. |
63
+ | `openApiFor(server)` | An OpenAPI 3.2 document for those routes. |
64
+ | `createMcpHandler(server)` | The schema as an MCP server: commands become tools, queries become resources. |
65
+
66
+ Security defaults: JSON-only bodies, an Origin check on state-changing requests, a Host check on loopback servers,
67
+ a 1 MiB body limit, nesting and cost limits, and a redacted manifest. See `spec/12-security.md` in the Rayfold
68
+ repository.
69
+
70
+ Apache-2.0.
package/args.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /** Argument validation and coercion at the system boundary. */
2
+ import { type Annotation, type ArgDef, type RayfoldSchemaIR, type TypeRef } from "@rayfold/schema";
3
+ export declare function coerceArgs(ir: RayfoldSchemaIR, defs: ArgDef[], raw: unknown, path: string): Record<string, unknown>;
4
+ /**
5
+ * Declarative value constraints from the schema (spec 01 section 4): `@range(min, max)` on numbers and
6
+ * on string/list lengths. Enforced before any resolver runs, so a bad value never causes a side effect.
7
+ */
8
+ export declare function checkConstraints(annotations: Annotation[], t: TypeRef, v: unknown, path: string): void;
9
+ export declare function coerceValue(ir: RayfoldSchemaIR, t: TypeRef, v: unknown, path: string): unknown;
10
+ export declare function coerceScalar(name: string, v: unknown, path: string): unknown;
11
+ /** Replace `{ "$ref": "id.path" }` objects with values from earlier results. Spec 03 §2. */
12
+ export declare function resolveRefs(value: unknown, lookup: (opId: number, path: string[]) => unknown, at: string): unknown;
13
+ /** Ids of ops referenced by `$ref` anywhere inside `value`. */
14
+ export declare function collectRefs(value: unknown, out?: Set<number>): Set<number>;
15
+ export declare function getPath(value: unknown, path: string[]): unknown;
package/args.js ADDED
@@ -0,0 +1,226 @@
1
+ /** Argument validation and coercion at the system boundary. */
2
+ import { typeRefToString } from "@rayfold/schema";
3
+ import { RayfoldError } from "./protocol.js";
4
+ const MAX_PAGE_FIRST = 200;
5
+ const NUMERIC = new Set(["Int", "Long", "Float", "Decimal"]);
6
+ export function coerceArgs(ir, defs, raw, path) {
7
+ if (raw !== undefined && (raw === null || typeof raw !== "object" || Array.isArray(raw))) {
8
+ throw new RayfoldError("invalid_argument", `${path}: expected an object`);
9
+ }
10
+ const input = (raw ?? {});
11
+ for (const k of Object.keys(input)) {
12
+ if (!defs.some((d) => d.name === k))
13
+ throw new RayfoldError("invalid_argument", `${path}.${k}: unknown argument`);
14
+ }
15
+ const out = {};
16
+ for (const d of defs) {
17
+ const v = input[d.name];
18
+ const p = `${path}.${d.name}`;
19
+ if (v === undefined) {
20
+ if (d.default !== undefined) {
21
+ out[d.name] = coerceValue(ir, d.type, d.default, p);
22
+ continue;
23
+ }
24
+ if (!d.type.nullable)
25
+ throw new RayfoldError("invalid_argument", `${p}: required`);
26
+ continue; // absent stays absent: partial updates (PATCH) depend on the difference from null
27
+ }
28
+ if (v === null) {
29
+ // An explicit null is never replaced by the default: the caller asked for null.
30
+ if (!d.type.nullable)
31
+ throw new RayfoldError("invalid_argument", d.default === undefined ? `${p}: required` : `${p}: must not be null`);
32
+ out[d.name] = null;
33
+ continue;
34
+ }
35
+ out[d.name] = coerceValue(ir, d.type, v, p);
36
+ checkConstraints(d.annotations, d.type, out[d.name], p);
37
+ }
38
+ return out;
39
+ }
40
+ /**
41
+ * Declarative value constraints from the schema (spec 01 section 4): `@range(min, max)` on numbers and
42
+ * on string/list lengths. Enforced before any resolver runs, so a bad value never causes a side effect.
43
+ */
44
+ export function checkConstraints(annotations, t, v, path) {
45
+ if (v === null || v === undefined)
46
+ return;
47
+ const range = annotations.find((a) => a.name === "range");
48
+ if (range) {
49
+ const min = typeof range.args["min"] === "number" ? range.args["min"] : undefined;
50
+ const max = typeof range.args["max"] === "number" ? range.args["max"] : undefined;
51
+ // The declared type decides: a String "1984" is four characters long, a Decimal "10.50" is a value.
52
+ const n = t.kind === "list" ? (Array.isArray(v) ? v.length : undefined)
53
+ : NUMERIC.has(t.name) ? (typeof v === "number" ? v : typeof v === "string" ? Number(v) : undefined)
54
+ : typeof v === "string" ? v.length
55
+ : undefined;
56
+ if (n !== undefined) {
57
+ if (min !== undefined && n < min)
58
+ throw new RayfoldError("invalid_argument", `${path}: must be >= ${min}`);
59
+ if (max !== undefined && n > max)
60
+ throw new RayfoldError("invalid_argument", `${path}: must be <= ${max}`);
61
+ }
62
+ }
63
+ const fmt = annotations.find((a) => a.name === "format");
64
+ const pattern = fmt?.args["pattern"];
65
+ if (typeof pattern === "string" && typeof v === "string" && !new RegExp(pattern).test(v))
66
+ throw new RayfoldError("invalid_argument", `${path}: must match ${pattern}`);
67
+ }
68
+ export function coerceValue(ir, t, v, path) {
69
+ if (v === null || v === undefined) {
70
+ if (t.nullable)
71
+ return null;
72
+ throw new RayfoldError("invalid_argument", `${path}: must not be null`);
73
+ }
74
+ if (t.kind === "list") {
75
+ if (!Array.isArray(v))
76
+ throw new RayfoldError("invalid_argument", `${path}: expected a list`);
77
+ return v.map((x, i) => coerceValue(ir, t.of, x, `${path}.${i}`));
78
+ }
79
+ const def = ir.types[t.name];
80
+ if (!def)
81
+ throw new RayfoldError("internal", `${path}: unknown type ${t.name}`);
82
+ switch (def.kind) {
83
+ case "scalar":
84
+ return coerceScalar(t.name, v, path);
85
+ case "enum":
86
+ if (typeof v !== "string" || !def.values.some((x) => x.name === v)) {
87
+ throw new RayfoldError("invalid_argument", `${path}: expected one of ${def.values.map((x) => x.name).join(", ")}`);
88
+ }
89
+ return v;
90
+ case "input": {
91
+ if (typeof v !== "object" || Array.isArray(v))
92
+ throw new RayfoldError("invalid_argument", `${path}: expected ${t.name}`);
93
+ const obj = coerceArgs(ir, def.fields.map(fieldAsArg), v, path);
94
+ if (t.name === "PageArgs") {
95
+ const first = obj["first"];
96
+ if (typeof first === "number" && first > MAX_PAGE_FIRST)
97
+ obj["first"] = MAX_PAGE_FIRST;
98
+ if (typeof first === "number" && first < 0)
99
+ throw new RayfoldError("invalid_argument", `${path}.first: must be >= 0`);
100
+ const offset = obj["offset"];
101
+ if (typeof offset === "number" && offset < 0)
102
+ throw new RayfoldError("invalid_argument", `${path}.offset: must be >= 0`);
103
+ }
104
+ return obj;
105
+ }
106
+ default:
107
+ throw new RayfoldError("invalid_argument", `${path}: ${typeRefToString(t)} is not an input type`);
108
+ }
109
+ }
110
+ function fieldAsArg(f) {
111
+ const a = { name: f.name, type: f.type, annotations: f.annotations };
112
+ if (f.default !== undefined)
113
+ a.default = f.default;
114
+ return a;
115
+ }
116
+ const RFC3339 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
117
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
118
+ const DECIMAL = /^-?\d+(\.\d+)?$/;
119
+ export function coerceScalar(name, v, path) {
120
+ const bad = (want) => {
121
+ throw new RayfoldError("invalid_argument", `${path}: expected ${want}`);
122
+ };
123
+ switch (name) {
124
+ case "ID":
125
+ if (typeof v === "string" && v.length > 0)
126
+ return v;
127
+ if (typeof v === "number" && Number.isSafeInteger(v))
128
+ return String(v);
129
+ return bad("ID");
130
+ case "String":
131
+ return typeof v === "string" ? v : bad("String");
132
+ case "Int":
133
+ return typeof v === "number" && Number.isInteger(v) && Math.abs(v) <= 2_147_483_647 ? v : bad("Int");
134
+ case "Long":
135
+ if (typeof v === "number" && Number.isSafeInteger(v))
136
+ return v; // larger values lose digits as JSON numbers: send them as text
137
+ if (typeof v === "string" && /^-?\d+$/.test(v))
138
+ return v;
139
+ return bad("Long");
140
+ case "Float":
141
+ return typeof v === "number" && Number.isFinite(v) ? v : bad("Float");
142
+ case "Boolean":
143
+ return typeof v === "boolean" ? v : bad("Boolean");
144
+ case "Decimal":
145
+ if (typeof v === "string" && DECIMAL.test(v))
146
+ return v;
147
+ if (typeof v === "number" && Number.isFinite(v) && DECIMAL.test(String(v)))
148
+ return String(v); // 1e21 would become "1e+21"
149
+ return bad("Decimal");
150
+ case "Instant":
151
+ return typeof v === "string" && RFC3339.test(v) ? v : bad("Instant (RFC 3339)");
152
+ case "Date":
153
+ return typeof v === "string" && DATE.test(v) ? v : bad("Date (YYYY-MM-DD)");
154
+ case "Duration":
155
+ if (typeof v === "number" && v >= 0)
156
+ return v;
157
+ if (typeof v === "string" && /^\d+(ms|s|m|h|d)$/.test(v))
158
+ return v;
159
+ return bad("Duration");
160
+ case "Bytes":
161
+ return typeof v === "string" && /^[A-Za-z0-9_-]*$/.test(v) ? v : bad("Bytes (base64url)");
162
+ case "JSON":
163
+ return v;
164
+ default:
165
+ // user-defined scalar: accept any JSON scalar
166
+ return typeof v === "object" ? bad(`scalar ${name}`) : v;
167
+ }
168
+ }
169
+ /** Replace `{ "$ref": "id.path" }` objects with values from earlier results. Spec 03 §2. */
170
+ export function resolveRefs(value, lookup, at) {
171
+ if (value === null || typeof value !== "object")
172
+ return value;
173
+ if (Array.isArray(value))
174
+ return value.map((x, i) => resolveRefs(x, lookup, `${at}.${i}`));
175
+ const obj = value;
176
+ const ref = obj["$ref"];
177
+ if (typeof ref === "string" && Object.keys(obj).length === 1) {
178
+ const [idText, ...path] = ref.split(".");
179
+ const id = Number(idText);
180
+ if (!Number.isInteger(id) || id <= 0)
181
+ throw new RayfoldError("invalid_argument", `${at}: bad $ref ${JSON.stringify(ref)}`);
182
+ const v = lookup(id, path);
183
+ if (v === undefined)
184
+ throw new RayfoldError("invalid_argument", `${at}: $ref ${ref} resolved to nothing`);
185
+ return v;
186
+ }
187
+ const out = {};
188
+ for (const [k, v] of Object.entries(obj))
189
+ out[k] = resolveRefs(v, lookup, `${at}.${k}`);
190
+ return out;
191
+ }
192
+ /** Ids of ops referenced by `$ref` anywhere inside `value`. */
193
+ export function collectRefs(value, out = new Set()) {
194
+ if (value === null || typeof value !== "object")
195
+ return out;
196
+ if (Array.isArray(value)) {
197
+ value.forEach((x) => collectRefs(x, out));
198
+ return out;
199
+ }
200
+ const obj = value;
201
+ const ref = obj["$ref"];
202
+ if (typeof ref === "string" && Object.keys(obj).length === 1) {
203
+ out.add(Number(ref.split(".")[0]));
204
+ return out;
205
+ }
206
+ for (const v of Object.values(obj))
207
+ collectRefs(v, out);
208
+ return out;
209
+ }
210
+ export function getPath(value, path) {
211
+ let cur = value;
212
+ for (const p of path) {
213
+ if (cur === null || cur === undefined || typeof cur !== "object")
214
+ return undefined;
215
+ if (Array.isArray(cur)) {
216
+ cur = cur[Number(p)];
217
+ continue;
218
+ }
219
+ // own data only: "__proto__", "constructor" and friends are never reachable through a $ref path
220
+ if (!Object.prototype.hasOwnProperty.call(cur, p))
221
+ return undefined;
222
+ cur = cur[p];
223
+ }
224
+ return cur;
225
+ }
226
+ //# sourceMappingURL=args.js.map
package/args.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"args.js","sourceRoot":"","sources":["../src/args.ts"],"names":[],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GAAG,KAAK,CAAC;IAChB,KAAK,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC;QACrB,IAAI,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,SAAS,IAAI,OAAO,GAAG,KAAK,QAAQ;YAAE,OAAO,SAAS,CAAC;QACnF,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;YACvB,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YACrB,SAAS;QACX,CAAC;QACD,gGAAgG;QAChG,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;YAAE,OAAO,SAAS,CAAC;QACpE,GAAG,GAAI,GAA+B,CAAC,CAAC,CAAC,CAAC;IAC5C,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/** Argument validation and coercion at the system boundary. */\nimport { typeRefToString, type Annotation, type ArgDef, type FieldDef, type RayfoldSchemaIR, type TypeRef } from \"@rayfold/schema\";\nimport { RayfoldError } from \"./protocol.ts\";\n\nconst MAX_PAGE_FIRST = 200;\nconst NUMERIC = new Set([\"Int\", \"Long\", \"Float\", \"Decimal\"]);\n\nexport function coerceArgs(ir: RayfoldSchemaIR, defs: ArgDef[], raw: unknown, path: string): Record<string, unknown> {\n if (raw !== undefined && (raw === null || typeof raw !== \"object\" || Array.isArray(raw))) {\n throw new RayfoldError(\"invalid_argument\", `${path}: expected an object`);\n }\n const input = (raw ?? {}) as Record<string, unknown>;\n for (const k of Object.keys(input)) {\n if (!defs.some((d) => d.name === k)) throw new RayfoldError(\"invalid_argument\", `${path}.${k}: unknown argument`);\n }\n const out: Record<string, unknown> = {};\n for (const d of defs) {\n const v = input[d.name];\n const p = `${path}.${d.name}`;\n if (v === undefined) {\n if (d.default !== undefined) {\n out[d.name] = coerceValue(ir, d.type, d.default, p);\n continue;\n }\n if (!d.type.nullable) throw new RayfoldError(\"invalid_argument\", `${p}: required`);\n continue; // absent stays absent: partial updates (PATCH) depend on the difference from null\n }\n if (v === null) {\n // An explicit null is never replaced by the default: the caller asked for null.\n if (!d.type.nullable) throw new RayfoldError(\"invalid_argument\", d.default === undefined ? `${p}: required` : `${p}: must not be null`);\n out[d.name] = null;\n continue;\n }\n out[d.name] = coerceValue(ir, d.type, v, p);\n checkConstraints(d.annotations, d.type, out[d.name], p);\n }\n return out;\n}\n\n/**\n * Declarative value constraints from the schema (spec 01 section 4): `@range(min, max)` on numbers and\n * on string/list lengths. Enforced before any resolver runs, so a bad value never causes a side effect.\n */\nexport function checkConstraints(annotations: Annotation[], t: TypeRef, v: unknown, path: string): void {\n if (v === null || v === undefined) return;\n const range = annotations.find((a) => a.name === \"range\");\n if (range) {\n const min = typeof range.args[\"min\"] === \"number\" ? range.args[\"min\"] : undefined;\n const max = typeof range.args[\"max\"] === \"number\" ? range.args[\"max\"] : undefined;\n // The declared type decides: a String \"1984\" is four characters long, a Decimal \"10.50\" is a value.\n const n =\n t.kind === \"list\" ? (Array.isArray(v) ? v.length : undefined)\n : NUMERIC.has(t.name) ? (typeof v === \"number\" ? v : typeof v === \"string\" ? Number(v) : undefined)\n : typeof v === \"string\" ? v.length\n : undefined;\n if (n !== undefined) {\n if (min !== undefined && n < min) throw new RayfoldError(\"invalid_argument\", `${path}: must be >= ${min}`);\n if (max !== undefined && n > max) throw new RayfoldError(\"invalid_argument\", `${path}: must be <= ${max}`);\n }\n }\n const fmt = annotations.find((a) => a.name === \"format\");\n const pattern = fmt?.args[\"pattern\"];\n if (typeof pattern === \"string\" && typeof v === \"string\" && !new RegExp(pattern).test(v)) throw new RayfoldError(\"invalid_argument\", `${path}: must match ${pattern}`);\n}\n\nexport function coerceValue(ir: RayfoldSchemaIR, t: TypeRef, v: unknown, path: string): unknown {\n if (v === null || v === undefined) {\n if (t.nullable) return null;\n throw new RayfoldError(\"invalid_argument\", `${path}: must not be null`);\n }\n if (t.kind === \"list\") {\n if (!Array.isArray(v)) throw new RayfoldError(\"invalid_argument\", `${path}: expected a list`);\n return v.map((x, i) => coerceValue(ir, t.of, x, `${path}.${i}`));\n }\n const def = ir.types[t.name];\n if (!def) throw new RayfoldError(\"internal\", `${path}: unknown type ${t.name}`);\n switch (def.kind) {\n case \"scalar\":\n return coerceScalar(t.name, v, path);\n case \"enum\":\n if (typeof v !== \"string\" || !def.values.some((x) => x.name === v)) {\n throw new RayfoldError(\"invalid_argument\", `${path}: expected one of ${def.values.map((x) => x.name).join(\", \")}`);\n }\n return v;\n case \"input\": {\n if (typeof v !== \"object\" || Array.isArray(v)) throw new RayfoldError(\"invalid_argument\", `${path}: expected ${t.name}`);\n const obj = coerceArgs(ir, def.fields.map(fieldAsArg), v, path);\n if (t.name === \"PageArgs\") {\n const first = obj[\"first\"];\n if (typeof first === \"number\" && first > MAX_PAGE_FIRST) obj[\"first\"] = MAX_PAGE_FIRST;\n if (typeof first === \"number\" && first < 0) throw new RayfoldError(\"invalid_argument\", `${path}.first: must be >= 0`);\n const offset = obj[\"offset\"];\n if (typeof offset === \"number\" && offset < 0) throw new RayfoldError(\"invalid_argument\", `${path}.offset: must be >= 0`);\n }\n return obj;\n }\n default:\n throw new RayfoldError(\"invalid_argument\", `${path}: ${typeRefToString(t)} is not an input type`);\n }\n}\n\nfunction fieldAsArg(f: FieldDef): ArgDef {\n const a: ArgDef = { name: f.name, type: f.type, annotations: f.annotations };\n if (f.default !== undefined) a.default = f.default;\n return a;\n}\n\nconst RFC3339 = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/;\nconst DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst DECIMAL = /^-?\\d+(\\.\\d+)?$/;\n\nexport function coerceScalar(name: string, v: unknown, path: string): unknown {\n const bad = (want: string): never => {\n throw new RayfoldError(\"invalid_argument\", `${path}: expected ${want}`);\n };\n switch (name) {\n case \"ID\":\n if (typeof v === \"string\" && v.length > 0) return v;\n if (typeof v === \"number\" && Number.isSafeInteger(v)) return String(v);\n return bad(\"ID\");\n case \"String\":\n return typeof v === \"string\" ? v : bad(\"String\");\n case \"Int\":\n return typeof v === \"number\" && Number.isInteger(v) && Math.abs(v) <= 2_147_483_647 ? v : bad(\"Int\");\n case \"Long\":\n if (typeof v === \"number\" && Number.isSafeInteger(v)) return v; // larger values lose digits as JSON numbers: send them as text\n if (typeof v === \"string\" && /^-?\\d+$/.test(v)) return v;\n return bad(\"Long\");\n case \"Float\":\n return typeof v === \"number\" && Number.isFinite(v) ? v : bad(\"Float\");\n case \"Boolean\":\n return typeof v === \"boolean\" ? v : bad(\"Boolean\");\n case \"Decimal\":\n if (typeof v === \"string\" && DECIMAL.test(v)) return v;\n if (typeof v === \"number\" && Number.isFinite(v) && DECIMAL.test(String(v))) return String(v); // 1e21 would become \"1e+21\"\n return bad(\"Decimal\");\n case \"Instant\":\n return typeof v === \"string\" && RFC3339.test(v) ? v : bad(\"Instant (RFC 3339)\");\n case \"Date\":\n return typeof v === \"string\" && DATE.test(v) ? v : bad(\"Date (YYYY-MM-DD)\");\n case \"Duration\":\n if (typeof v === \"number\" && v >= 0) return v;\n if (typeof v === \"string\" && /^\\d+(ms|s|m|h|d)$/.test(v)) return v;\n return bad(\"Duration\");\n case \"Bytes\":\n return typeof v === \"string\" && /^[A-Za-z0-9_-]*$/.test(v) ? v : bad(\"Bytes (base64url)\");\n case \"JSON\":\n return v;\n default:\n // user-defined scalar: accept any JSON scalar\n return typeof v === \"object\" ? bad(`scalar ${name}`) : v;\n }\n}\n\n/** Replace `{ \"$ref\": \"id.path\" }` objects with values from earlier results. Spec 03 §2. */\nexport function resolveRefs(value: unknown, lookup: (opId: number, path: string[]) => unknown, at: string): unknown {\n if (value === null || typeof value !== \"object\") return value;\n if (Array.isArray(value)) return value.map((x, i) => resolveRefs(x, lookup, `${at}.${i}`));\n const obj = value as Record<string, unknown>;\n const ref = obj[\"$ref\"];\n if (typeof ref === \"string\" && Object.keys(obj).length === 1) {\n const [idText, ...path] = ref.split(\".\");\n const id = Number(idText);\n if (!Number.isInteger(id) || id <= 0) throw new RayfoldError(\"invalid_argument\", `${at}: bad $ref ${JSON.stringify(ref)}`);\n const v = lookup(id, path);\n if (v === undefined) throw new RayfoldError(\"invalid_argument\", `${at}: $ref ${ref} resolved to nothing`);\n return v;\n }\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) out[k] = resolveRefs(v, lookup, `${at}.${k}`);\n return out;\n}\n\n/** Ids of ops referenced by `$ref` anywhere inside `value`. */\nexport function collectRefs(value: unknown, out = new Set<number>()): Set<number> {\n if (value === null || typeof value !== \"object\") return out;\n if (Array.isArray(value)) {\n value.forEach((x) => collectRefs(x, out));\n return out;\n }\n const obj = value as Record<string, unknown>;\n const ref = obj[\"$ref\"];\n if (typeof ref === \"string\" && Object.keys(obj).length === 1) {\n out.add(Number(ref.split(\".\")[0]));\n return out;\n }\n for (const v of Object.values(obj)) collectRefs(v, out);\n return out;\n}\n\nexport function getPath(value: unknown, path: string[]): unknown {\n let cur = value;\n for (const p of path) {\n if (cur === null || cur === undefined || typeof cur !== \"object\") return undefined;\n if (Array.isArray(cur)) {\n cur = cur[Number(p)];\n continue;\n }\n // own data only: \"__proto__\", \"constructor\" and friends are never reachable through a $ref path\n if (!Object.prototype.hasOwnProperty.call(cur, p)) return undefined;\n cur = (cur as Record<string, unknown>)[p];\n }\n return cur;\n}\n"]}
package/batch.d.ts ADDED
@@ -0,0 +1,54 @@
1
+ /** Batch scheduling: dependency waves, serial commands, deadlines, idempotency. Spec: spec/03. */
2
+ import type { Instrumentation } from "./instrumentation.js";
3
+ import { type RayfoldSchemaIR } from "@rayfold/schema";
4
+ import { EventBus, type IdempotencyStore } from "./context.js";
5
+ import { type Executor } from "./executor.js";
6
+ import { type Frame, type RequestEnvelope } from "./protocol.js";
7
+ import { type ShapeRegistry } from "./views.js";
8
+ import type { UsageSink } from "./usage.js";
9
+ import { ChangeBus } from "./live.js";
10
+ export interface BatchOptions {
11
+ trustedShapes: boolean;
12
+ budget: number;
13
+ maxOps: number;
14
+ maxDepth: number;
15
+ maxFields: number;
16
+ timing: boolean;
17
+ now: () => number;
18
+ }
19
+ export interface BatchRuntime {
20
+ ir: RayfoldSchemaIR;
21
+ executor: Executor;
22
+ registry: ShapeRegistry;
23
+ idempotency: IdempotencyStore;
24
+ events: EventBus;
25
+ changes: ChangeBus;
26
+ options: BatchOptions;
27
+ instrumentation?: Instrumentation;
28
+ /** Records which operations each client called (spec 11). */
29
+ usage?: UsageSink;
30
+ /** Commands running right now, by idempotency scope and key: a concurrent retry waits for the first, then replays. */
31
+ inflight: Map<string, Promise<void>>;
32
+ }
33
+ export interface ExecuteOptions {
34
+ viewer?: unknown;
35
+ signal?: AbortSignal;
36
+ /**
37
+ * Set by transports whose HTTP method is itself idempotent (PUT, PATCH, DELETE bindings): commands may run
38
+ * without an idempotency key. Never settable from the wire envelope.
39
+ */
40
+ keyOptional?: boolean;
41
+ /** @internal Set by the batch itself: the memo every op of this request shares. Never read from the wire. */
42
+ batchState?: Map<string, unknown>;
43
+ }
44
+ /** Unbounded async queue of frames; `close()` ends iteration once drained. */
45
+ export declare class FrameSink implements AsyncIterable<Frame> {
46
+ private readonly queue;
47
+ private waiting;
48
+ private closed;
49
+ readonly frames: Frame[];
50
+ push(f: Frame): void;
51
+ close(): void;
52
+ [Symbol.asyncIterator](): AsyncIterator<Frame>;
53
+ }
54
+ export declare function executeBatch(rt: BatchRuntime, envelope: RequestEnvelope, opts?: ExecuteOptions): AsyncIterable<Frame>;