@workerstack/clients 1.0.0-rc.30 → 1.0.0-rc.31

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 (115) hide show
  1. package/README.md +175 -21
  2. package/bin/clients.js +5 -6
  3. package/bin/installgen.js +5 -9
  4. package/dist/cli.js +3 -1
  5. package/dist/emit/csharp/sdk-method.d.ts +18 -1
  6. package/dist/emit/csharp/sdk-method.js +14 -3
  7. package/dist/emit/csharp/sdk.js +4 -1
  8. package/dist/emit/go/sdk-method.d.ts +9 -0
  9. package/dist/emit/go/sdk-method.js +10 -1
  10. package/dist/emit/go/sdk.js +4 -3
  11. package/dist/emit/java/sdk-client.js +1 -0
  12. package/dist/emit/java/sdk-op.d.ts +6 -1
  13. package/dist/emit/java/sdk-op.js +15 -3
  14. package/dist/emit/java/sdk.js +7 -1
  15. package/dist/emit/python/sdk-method.d.ts +11 -0
  16. package/dist/emit/python/sdk-method.js +15 -0
  17. package/dist/emit/python/sdk.js +5 -1
  18. package/dist/emit/rust/sdk-method.d.ts +12 -1
  19. package/dist/emit/rust/sdk-method.js +10 -2
  20. package/dist/emit/rust/sdk.js +4 -1
  21. package/dist/emit/ts/http.d.ts +8 -0
  22. package/dist/emit/ts/http.js +48 -3
  23. package/dist/emit/ts/package.js +1 -0
  24. package/dist/emit/ts/sdk-types-preamble.js +10 -2
  25. package/dist/emit/ts/sdk-types.d.ts +0 -5
  26. package/dist/emit/ts/sdk-types.js +52 -8
  27. package/dist/emit/ts/sdk.d.ts +3 -1
  28. package/dist/emit/ts/sdk.js +40 -8
  29. package/dist/emit/ts/service-map.d.ts +5 -0
  30. package/dist/emit/ts/service-map.js +10 -1
  31. package/dist/emit/ts/single-flight-text.d.ts +3 -0
  32. package/dist/emit/ts/single-flight-text.js +38 -0
  33. package/dist/emit/ts/tanstack-query.d.ts +3 -2
  34. package/dist/emit/ts/tanstack-query.js +54 -29
  35. package/dist/gen/process.js +2 -1
  36. package/dist/gen/switch-on.constants.d.ts +2 -0
  37. package/dist/gen/switch-on.constants.js +2 -0
  38. package/dist/gen/targets.d.ts +4 -3
  39. package/dist/gen/targets.js +4 -3
  40. package/dist/ir/invalidate-reads.d.ts +17 -0
  41. package/dist/ir/invalidate-reads.js +104 -0
  42. package/dist/ir/load.d.ts +10 -0
  43. package/dist/ir/load.js +62 -14
  44. package/dist/ir/read-method.constants.d.ts +2 -0
  45. package/dist/ir/read-method.constants.js +2 -0
  46. package/dist/release/load.js +1 -1
  47. package/dist/runtime/csharp/Config.cs +9 -1
  48. package/dist/runtime/csharp/Exchange.cs +56 -4
  49. package/dist/runtime/csharp/Hooks.cs +9 -0
  50. package/dist/runtime/csharp/Operation.cs +6 -1
  51. package/dist/runtime/csharp/WsDial.cs +3 -1
  52. package/dist/runtime/go/config.go +5 -0
  53. package/dist/runtime/go/hooks.go +70 -0
  54. package/dist/runtime/go/request.go +6 -2
  55. package/dist/runtime/go/stream.go +4 -1
  56. package/dist/runtime/go/ws.go +3 -1
  57. package/dist/runtime/java/ClientConfig.java +11 -0
  58. package/dist/runtime/java/Flight.java +2 -12
  59. package/dist/runtime/java/Hooks.java +45 -0
  60. package/dist/runtime/java/InvalidateEvent.java +10 -0
  61. package/dist/runtime/java/InvalidateHook.java +12 -0
  62. package/dist/runtime/java/InvalidateTarget.java +7 -0
  63. package/dist/runtime/java/Operation.java +23 -3
  64. package/dist/runtime/java/Realtime.java +3 -1
  65. package/dist/runtime/java/WsDial.java +3 -0
  66. package/dist/runtime/python/config.py +8 -2
  67. package/dist/runtime/python/exchange.py +3 -1
  68. package/dist/runtime/python/hooks.py +110 -5
  69. package/dist/runtime/python/operation.py +2 -0
  70. package/dist/runtime/python/send_async.py +14 -2
  71. package/dist/runtime/python/send_sync.py +4 -2
  72. package/dist/runtime/python/ws.py +5 -1
  73. package/dist/runtime/rust/config.rs +6 -1
  74. package/dist/runtime/rust/exchange.rs +15 -3
  75. package/dist/runtime/rust/hooks.rs +127 -2
  76. package/dist/runtime/rust/log.rs +11 -3
  77. package/dist/runtime/rust/request.rs +17 -0
  78. package/dist/runtime/rust/ws.rs +9 -1
  79. package/dist/runtime/ts/config.ts +69 -0
  80. package/dist/runtime/ts/http.ts +12 -10
  81. package/dist/runtime/ts/request.ts +2 -0
  82. package/dist/runtime/ts/response.ts +7 -0
  83. package/dist/runtime/ts/sdk-invalidate.ts +82 -0
  84. package/dist/runtime/ts/sdk-single-flight.constants.ts +25 -0
  85. package/dist/runtime/ts/sdk-single-flight.ts +203 -0
  86. package/dist/runtime/ts/sdk-sse.ts +5 -1
  87. package/dist/runtime/ts/sdk-ws.ts +9 -3
  88. package/dist/runtime/ts/sdk.ts +55 -31
  89. package/dist/runtime/ts/single-flight-batch.ts +184 -0
  90. package/dist/runtime/ts/single-flight-body.ts +59 -0
  91. package/dist/runtime/ts/single-flight-run.ts +160 -0
  92. package/dist/runtime/ts/single-flight.constants.ts +31 -0
  93. package/dist/runtime/ts/single-flight.ts +158 -0
  94. package/dist/runtime/ts-tanstack-query/invalidate.ts +96 -92
  95. package/dist/runtime/ts-tanstack-query/query.ts +140 -168
  96. package/package.json +10 -18
  97. package/references/INDEX.md +31 -0
  98. package/references/cli.md +33 -0
  99. package/references/configuring.md +29 -0
  100. package/references/documentation.md +15 -0
  101. package/references/errors.md +23 -0
  102. package/references/flags.md +104 -0
  103. package/references/gates.md +46 -0
  104. package/references/generate.md +29 -0
  105. package/references/install-scripts.md +28 -0
  106. package/references/install.md +38 -0
  107. package/references/license.md +8 -0
  108. package/references/mcp.md +76 -0
  109. package/references/output.md +45 -0
  110. package/references/overview.md +14 -0
  111. package/references/release-tooling.md +34 -0
  112. package/references/release.md +305 -0
  113. package/references/sdks.md +393 -0
  114. package/references/start.md +22 -0
  115. package/references/tdd.md +16 -0
@@ -89,6 +89,20 @@ function framing(op, env) {
89
89
  ["dispatch", key === undefined ? null : pyString(key)],
90
90
  ];
91
91
  }
92
+ /**
93
+ * The `Operation(…)` keywords an `on_invalidate` event comes from: the write's operationId and each read a success
94
+ * makes stale with its own path params; none for a write with no reads, nor a realtime connection, which reconnects.
95
+ */
96
+ function invalidating(op, env) {
97
+ const reads = op.stream === "realtime" ? undefined : env.reads.get(op.id);
98
+ if (reads === undefined || reads.length === 0)
99
+ return [];
100
+ const each = reads.map((read) => `(${pyString(read.operationId)}, ${tuple(read.params.map(pyString))})`);
101
+ return [
102
+ ["by", pyString(op.id)],
103
+ ["reads", tuple(each)],
104
+ ];
105
+ }
92
106
  /** The `Operation(…)` keywords that differ from its defaults, in its field order. */
93
107
  function namedArgs(parts, env) {
94
108
  const { answer, headers, op } = parts;
@@ -103,6 +117,7 @@ function namedArgs(parts, env) {
103
117
  ["shape", shape === null ? null : pyString(shape)],
104
118
  ["idempotent", op.idempotent && op.stream === null ? "True" : null],
105
119
  ["invalidates", op.invalidates.length > 0 ? tuple(op.invalidates.map(pyString)) : null],
120
+ ...invalidating(op, env),
106
121
  ["stream", op.stream === null ? null : pyString(op.stream)],
107
122
  ["headers", headers === null ? null : tuple(headers.read)],
108
123
  ["events", jsonEvents(op, env)],
@@ -8,6 +8,7 @@
8
8
  * is no error-mode option.
9
9
  */
10
10
  import { toIR } from "../../ir/build.js";
11
+ import { invalidateReads } from "../../ir/invalidate-reads.js";
11
12
  import { sdkModel } from "../../ir/sdk-model.js";
12
13
  import { pyDocLines } from "../shared/escape.js";
13
14
  import { compareCodeUnits, NameScope } from "../shared/lang.js";
@@ -124,6 +125,7 @@ function emitPython(document, options, metadata = {}) {
124
125
  ws: model.ops.some((op) => op.stream === "ws"),
125
126
  };
126
127
  const transport = features.realtime ? "AsyncRealtimeTransport" : features.ws ? "AsyncWsTransport" : "AsyncTransport";
128
+ const { reads, warnings } = invalidateReads(ir);
127
129
  const env = {
128
130
  at: { ...at, declTyping: at.typing, typing: new Set() },
129
131
  constants: new NameScope(),
@@ -131,6 +133,7 @@ function emitPython(document, options, metadata = {}) {
131
133
  keyed: errorKey !== null,
132
134
  notices: [],
133
135
  ops: model.opsById,
136
+ reads,
134
137
  transport,
135
138
  typesImports: new Set(),
136
139
  };
@@ -158,7 +161,8 @@ function emitPython(document, options, metadata = {}) {
158
161
  ...Object.fromEntries(Object.entries(runtime).map(([name, source]) => [`${root}/_http/${name}`, source])),
159
162
  };
160
163
  const sorted = Object.fromEntries(Object.entries(files).sort(([a], [b]) => compareCodeUnits(a, b)));
161
- return { files: sorted, notices: env.notices, pkg, plans: client.plans };
164
+ const notices = [...env.notices, ...warnings.map((warning) => `python: ${warning}`)];
165
+ return { files: sorted, notices, pkg, plans: client.plans };
162
166
  }
163
167
  /** The package's files for `document`, by path, and its notices; `metadata` fills pyproject.toml's description fields. */
164
168
  export function generatePythonSdk(document, options = {}, metadata = {}) {
@@ -1,3 +1,13 @@
1
+ /**
2
+ * One operation as a Rust method (G1, Fb1): `(&self, <path params as &str in path order>, <body>?, opts:
3
+ * &<Op>Opts) -> Call<T, S[, <Op>Headers]>`, `S` the client's style (bit 21 i4: `Throw` on the normal client,
4
+ * `Safe` on `client.safe()`, one method for both). The method copies everything into the runtime's
5
+ * `RequestSpec` up front (the body encoded at once) and hands it to `Call` with the run that reads its answer:
6
+ * JSON as its type, none as `()`, text as `String`, binary as `Vec<u8>`; a stream answers as sse.ts, ws.ts and
7
+ * realtime.ts say, an SSE stream in its style, a WebSocket or realtime connection the same on both clients.
8
+ * Spec text reaches the source only through the shared escape layer.
9
+ */
10
+ import type { InvalidatedRead } from "../../ir/invalidate-reads.ts";
1
11
  import { type SdkOp } from "../../ir/sdk-model.ts";
2
12
  import type { RustCallPlan } from "./sdk-plan.ts";
3
13
  import type { RustTypeContext } from "./types.ts";
@@ -7,9 +17,10 @@ export type RustMethod = {
7
17
  readonly decls: readonly (readonly [string, string])[];
8
18
  readonly lines: readonly string[];
9
19
  };
10
- /** What every method of one SDK shares: the type context it hoists into. */
20
+ /** The type context it hoists into, and each write's reads by operationId (`invalidateReads`): its event's targets. */
11
21
  export type MethodEnv = {
12
22
  readonly at: RustTypeContext;
23
+ readonly reads: ReadonlyMap<string, readonly InvalidatedRead[]>;
13
24
  };
14
25
  /** The method of `op` named `name`, its client reached as `client` (`self`, `self.client`), and its `<Op>Opts` and `<Op>Headers`. */
15
26
  export declare function rustMethod(op: SdkOp, name: string, client: string, env: MethodEnv): RustMethod;
@@ -62,6 +62,13 @@ function specLines(op, fields, answer, body) {
62
62
  ...(op.invalidates.length > 0 ? [`spec.invalidates(&[${op.invalidates.map(rustString).join(", ")}]);`] : []),
63
63
  ];
64
64
  }
65
+ /** The `spec.reads` statement of a write whose success stales `reads`: its operationId and each read's own params. */
66
+ function readsLines(op, reads) {
67
+ if (reads === undefined || reads.length === 0)
68
+ return [];
69
+ const each = reads.map((read) => `(${rustString(read.operationId)}, &[${read.params.map(rustString).join(", ")}])`);
70
+ return [`spec.reads(${rustString(op.id)}, &[${each.join(", ")}]);`];
71
+ }
65
72
  /** The method's lines: its signature over `client`, the spec it fills, the `Call` it returns. */
66
73
  function methodLines(parts, client, answer, body) {
67
74
  const { fields, headers, op, opts, path } = parts;
@@ -73,7 +80,7 @@ function methodLines(parts, client, answer, body) {
73
80
  `${empty ? "_opts" : "opts"}: &${opts}`,
74
81
  ];
75
82
  const bound = path.map(([param, local]) => `(${rustString(param.name)}, ${local})`).join(", ");
76
- const statements = specLines(op, fields, answer, body?.lines ?? []);
83
+ const statements = [...specLines(op, fields, answer, body?.lines ?? []), ...parts.reads];
77
84
  const returns = callType(op, answer, headers);
78
85
  return [
79
86
  ...(params.length > 7 ? [" #[allow(clippy::too_many_arguments)]"] : []),
@@ -111,7 +118,8 @@ export function rustMethod(op, name, client, env) {
111
118
  const body = op.body && rustBody(op, op.body, env.at);
112
119
  const answer = answerOf(op, env);
113
120
  const fields = optsFields(op, opts, env.at, answer.stream);
114
- const parts = { fields, headers: responseHeaders(op, env.at), name, op, opts, path };
121
+ const reads = readsLines(op, env.reads.get(op.id));
122
+ const parts = { fields, headers: responseHeaders(op, env.at), name, op, opts, path, reads };
115
123
  const decls = [[opts, optsDecl(op, opts, fields, answer.stream)]];
116
124
  if (parts.headers)
117
125
  decls.push([parts.headers.plan.type, parts.headers.decl]);
@@ -7,6 +7,7 @@
7
7
  * Every `.rs` file carries the generated-code marker.
8
8
  */
9
9
  import { toIR } from "../../ir/build.js";
10
+ import { invalidateReads } from "../../ir/invalidate-reads.js";
10
11
  import { sdkModel } from "../../ir/sdk-model.js";
11
12
  import { lineComment } from "../shared/escape.js";
12
13
  import { compareCodeUnits, rustTypeIdent } from "../shared/lang.js";
@@ -73,7 +74,9 @@ function emitRust(document, options, shipped) {
73
74
  renamed: emitted,
74
75
  what: "component",
75
76
  }));
76
- const client = clientDecls(ir, { at, notices, ops: model.opsById });
77
+ const { reads, warnings } = invalidateReads(ir);
78
+ const client = clientDecls(ir, { at, notices, ops: model.opsById, reads });
79
+ notices.push(...warnings.map((warning) => `rust: ${warning}`));
77
80
  // before the hoisted are read: each key's <Key>Data lands among them; an API without operations answers no error
78
81
  const errorKeys = model.ops.length > 0 ? [rustErrorKeys(model, at)] : [];
79
82
  const hoisted = [...at.decls].sort(([a], [b]) => compareCodeUnits(a, b)).map(([, decl]) => decl);
@@ -14,5 +14,13 @@ export declare const RUNTIME_MODULES: readonly string[];
14
14
  export declare function runtimeFeatures(ir: IR): TsRuntimeFeatures;
15
15
  /** The Standard Webhooks verifier: it imports nothing, so the webhook file that carries it stands alone. */
16
16
  export declare function webhookSource(): string;
17
+ /** The single-flight handler's runtime modules, each after the ones it imports. */
18
+ export declare const SINGLE_FLIGHT_MODULES: readonly string[];
19
+ /**
20
+ * The single-flight handler's runtime, for a file of its own beside the SDK (as the webhook verifier is): its
21
+ * modules joined, their imports of the client's runtime gathered into one import of `<stem>.runtime.gen.js`, so no
22
+ * browser bundle that leaves the file out carries any of it.
23
+ */
24
+ export declare function singleFlightSource(stem: string): string;
17
25
  /** The runtime as one module, with `features`' transports: what `runtime.gen.ts` holds. */
18
26
  export declare function runtimeSource(features: TsRuntimeFeatures): string;
@@ -5,9 +5,11 @@
5
5
  * SSE or realtime API, the WebSocket ones for a WebSocket or realtime API, the realtime ones for a
6
6
  * realtime API, and only the app client ships its own `createClient`. The webhook verifier is no part of it: it ships
7
7
  * in its own file (`webhookSource`), so a receiver bundles nothing else. Both fronts emit it verbatim, so a test that runs the emitted client runs this text.
8
+ * The single-flight handler ships in a file of its own too (`singleFlightSource`), so a browser bundles none of it.
8
9
  */
9
10
  import { readFileSync } from "node:fs";
10
11
  import { sdkModel } from "../../ir/sdk-model.js";
12
+ import { compareCodeUnits } from "../shared/lang.js";
11
13
  /** The app client's runtime: `createClient` and every transport, since it cannot know its routes'. */
12
14
  export const FULL_RUNTIME = { app: true, realtime: true, sse: true, ws: true };
13
15
  /** The runtime modules under `runtime/ts`, each after the ones it imports. */
@@ -32,6 +34,9 @@ export const RUNTIME_MODULES = [
32
34
  "stale",
33
35
  "app-types",
34
36
  "app",
37
+ "sdk-invalidate",
38
+ "sdk-single-flight.constants",
39
+ "sdk-single-flight",
35
40
  "sdk",
36
41
  "sdk-sse",
37
42
  "sdk-ws",
@@ -58,16 +63,56 @@ export function runtimeFeatures(ir) {
58
63
  return { app: false, realtime: streams.has("realtime"), sse: streams.has("sse"), ws: streams.has("ws") };
59
64
  }
60
65
  // an import of a sibling runtime module, on one line or several
61
- const SIBLING_IMPORT = /^import\s+(?:type\s+)?\{[^}]*\}\s+from\s+"\.\/[\w-]+\.ts"\n/gm;
66
+ const SIBLING_IMPORT = /^import\s+(?:type\s+)?\{[^}]*\}\s+from\s+"\.\/[\w.-]+\.ts"\n/gm;
67
+ /** One runtime module's text, as written. */
68
+ function moduleText(name) {
69
+ return readFileSync(new URL(`../../runtime/ts/${name}.ts`, import.meta.url), "utf8");
70
+ }
62
71
  /** One runtime module's source, without its imports of its siblings. */
63
72
  function moduleSource(name) {
64
- const text = readFileSync(new URL(`../../runtime/ts/${name}.ts`, import.meta.url), "utf8");
65
- return text.replaceAll(SIBLING_IMPORT, "").trim();
73
+ return moduleText(name).replaceAll(SIBLING_IMPORT, "").trim();
66
74
  }
67
75
  /** The Standard Webhooks verifier: it imports nothing, so the webhook file that carries it stands alone. */
68
76
  export function webhookSource() {
69
77
  return moduleSource("webhook");
70
78
  }
79
+ /** The single-flight handler's runtime modules, each after the ones it imports. */
80
+ export const SINGLE_FLIGHT_MODULES = [
81
+ "single-flight.constants",
82
+ "single-flight-batch",
83
+ "single-flight-body",
84
+ "single-flight-run",
85
+ "single-flight",
86
+ ];
87
+ // an import of a sibling runtime module, its names and its module captured
88
+ const SIBLING_NAMES = /^import\s+(type\s+)?\{([^}]*)\}\s+from\s+"\.\/([\w.-]+)\.ts"\n/gm;
89
+ // a type-only name of an import list
90
+ const TYPE_PREFIX = /^type /;
91
+ /** The names `text` imports from runtime modules outside `own`, each `type X` when only its type is imported. */
92
+ function runtimeImports(text, own) {
93
+ return [...text.matchAll(SIBLING_NAMES)]
94
+ .filter(([, , , module]) => !own.includes(String(module)))
95
+ .flatMap(([, typeOnly, names]) => String(names)
96
+ .split(",")
97
+ .map((name) => name.trim())
98
+ .filter((name) => name !== "")
99
+ .map((name) => (typeOnly === undefined ? name : `type ${name}`)));
100
+ }
101
+ /** `name` without its `type ` mark. */
102
+ function bare(name) {
103
+ return name.replace(TYPE_PREFIX, "");
104
+ }
105
+ /**
106
+ * The single-flight handler's runtime, for a file of its own beside the SDK (as the webhook verifier is): its
107
+ * modules joined, their imports of the client's runtime gathered into one import of `<stem>.runtime.gen.js`, so no
108
+ * browser bundle that leaves the file out carries any of it.
109
+ */
110
+ export function singleFlightSource(stem) {
111
+ const imported = new Set(SINGLE_FLIGHT_MODULES.flatMap((name) => runtimeImports(moduleText(name), SINGLE_FLIGHT_MODULES)));
112
+ const sorted = [...imported].toSorted((a, b) => compareCodeUnits(bare(a), bare(b)));
113
+ const modules = SINGLE_FLIGHT_MODULES.map(moduleSource).join("\n\n");
114
+ return `import { ${sorted.join(", ")} } from "./${stem}.runtime.gen.js"\n\n${modules}\n`;
115
+ }
71
116
  /** The runtime as one module, with `features`' transports: what `runtime.gen.ts` holds. */
72
117
  export function runtimeSource(features) {
73
118
  return `${runtimeModules(features).map(moduleSource).join("\n\n")}\n`;
@@ -17,6 +17,7 @@ const QUERY_CORE_RANGE = "^5.0.0";
17
17
  // each importable file's kind and the subpath it is exported at; the others are reached through the index
18
18
  const SUBPATHS = {
19
19
  index: ".",
20
+ "single-flight": "./single-flight",
20
21
  "tanstack-query": "./tanstack-query",
21
22
  webhook: "./webhook",
22
23
  };
@@ -11,6 +11,8 @@ export const RESERVED = [
11
11
  "HttpSafe",
12
12
  "HttpStream",
13
13
  "HttpOptions",
14
+ "InvalidateEvent",
15
+ "InvalidateTarget",
14
16
  "Omit",
15
17
  "Promise",
16
18
  "ReadableStream",
@@ -23,6 +25,7 @@ export const RESERVED = [
23
25
  "SDKConfig",
24
26
  "SSEEvent",
25
27
  "SSEEventOf",
28
+ "SingleFlightConfig",
26
29
  "SseOptions",
27
30
  "TypedWebSocket",
28
31
  "Uint8Array",
@@ -31,12 +34,15 @@ export const RESERVED = [
31
34
  ];
32
35
  /** What the types file may import from the runtime module, in the order the import lists them. */
33
36
  const RUNTIME_TYPES = [
37
+ "InvalidateEvent",
38
+ "InvalidateTarget",
34
39
  "RealtimeOptions",
35
40
  "Result",
36
41
  "ResumableConnection",
37
42
  "SDKConfig",
38
43
  "SSEEvent",
39
44
  "SSEEventOf",
45
+ "SingleFlightConfig",
40
46
  "TypedWebSocket",
41
47
  "WsFrame",
42
48
  ];
@@ -47,9 +53,10 @@ const OPTIONS = `export type HttpOptions = {
47
53
  headers?: Record<string, string>
48
54
  idempotencyKey?: string
49
55
  signal?: AbortSignal
56
+ singleFlight?: boolean
50
57
  timeout?: number
51
58
  }
52
- export type SseOptions = Omit<HttpOptions, "idempotencyKey"> & { lastEventId?: string }
59
+ export type SseOptions = Omit<HttpOptions, "idempotencyKey" | "singleFlight"> & { lastEventId?: string }
53
60
  export type WsOptions = { protocols?: string | string[]; reconnectToken?: string }
54
61
  `;
55
62
  // the error envelope, the call and stream shapes, and the safe mirror's opening
@@ -105,7 +112,8 @@ export function shared(features) {
105
112
  ...(features.ws || features.realtime ? ["TypedWebSocket"] : []),
106
113
  ];
107
114
  const realtime = features.realtime
108
- ? `export type RealtimeCallOptions = Omit<HttpOptions, "idempotencyKey" | "timeout"> & RealtimeOptions\n`
115
+ ? 'export type RealtimeCallOptions = Omit<HttpOptions, "idempotencyKey" | "singleFlight" | "timeout"> & ' +
116
+ "RealtimeOptions\n"
109
117
  : "";
110
118
  const rest = "T[K] extends HttpCall<infer I, infer D, infer E, infer H>";
111
119
  const safe = connections.length === 0
@@ -1,8 +1,3 @@
1
- /**
2
- * The `${stem}.types.gen.ts` text: the component schemas, each operation's input, data, error and
3
- * header types, the SDK's config, and the interface its class merges with. Types and runtime meet
4
- * in the member tree, so a renamed member (`state` → `state_`) is renamed in both.
5
- */
6
1
  import type { IR } from "../../ir/model.ts";
7
2
  /**
8
3
  * The component schemas' declared names, clear of `reserved` (the names the emitted file declares
@@ -1,3 +1,9 @@
1
+ /**
2
+ * The `${stem}.types.gen.ts` text: the component schemas, each operation's input, data, error and
3
+ * header types, the SDK's config, and the interface its class merges with. Types and runtime meet
4
+ * in the member tree, so a renamed member (`state` → `state_`) is renamed in both.
5
+ */
6
+ import { invalidateReads } from "../../ir/invalidate-reads.js";
1
7
  import { dispatchKey, irErrorEnvelope, isJsonMedia, mediaEssence, sdkModel, sseEventSchema, sseEvents, } from "../../ir/sdk-model.js";
2
8
  import { bodiesOf } from "../../ir/slots.js";
3
9
  import { blockCommentText, tsString } from "../shared/escape.js";
@@ -209,15 +215,53 @@ export function componentNames(ir, reserved) {
209
215
  }
210
216
  return (schema) => table.get(schema, "Schema");
211
217
  }
212
- /** The config type: `baseURL` optional when the document declares a server, the first one being its default. */
213
- function configText(name, server, runtimeConfig) {
218
+ /** `ids` as a union of string literals in code-unit order, each once. */
219
+ function literalUnion(ids) {
220
+ return [...new Set(ids)].toSorted(compareCodeUnits).map(tsString).join(" | ");
221
+ }
222
+ /**
223
+ * `onInvalidate` with its event narrowed to the API's operationIds: `by` to the writes that invalidate a read, each
224
+ * target to the reads some write invalidates. None for an API whose writes invalidate nothing: no hook is ever called
225
+ * there, so there is nothing to narrow.
226
+ */
227
+ function onInvalidateField(ir) {
228
+ const { reads } = invalidateReads(ir);
229
+ if (reads.size === 0)
230
+ return [];
231
+ const targets = [...reads.values()].flat().map((read) => read.operationId);
232
+ const ids = `${literalUnion(reads.keys())}, ${literalUnion(targets)}`;
233
+ return [
234
+ {
235
+ key: "onInvalidate",
236
+ text: [
237
+ "\t/** The `onInvalidate` hooks, their event narrowed to this API's writes and the reads they make stale. */",
238
+ `\tonInvalidate?: Array<(event: InvalidateEvent<${ids}>) => Promise<void> | void>`,
239
+ ].join("\n"),
240
+ },
241
+ {
242
+ key: "singleFlight",
243
+ text: [
244
+ "\t/** Single flight, its `exclude` and `select` narrowed to this API's writes and the reads they make " +
245
+ "stale. */",
246
+ `\tsingleFlight?: SingleFlightConfig<${ids}>`,
247
+ ].join("\n"),
248
+ },
249
+ ];
250
+ }
251
+ /**
252
+ * The config type: `baseURL` optional when the document declares a server, the first one being its default, and
253
+ * `onInvalidate`'s event narrowed to the API's operationIds when any write invalidates a read.
254
+ */
255
+ function configText(ir, name, runtimeConfig) {
256
+ const server = ir.servers[0];
257
+ const doc = server === undefined ? "" : `\t/** Default: the document's first server, ${blockCommentText(server)} */`;
258
+ const baseURL = server === undefined ? [] : [{ key: "baseURL", text: `${doc}\n\tbaseURL?: string` }];
259
+ const fields = [...baseURL, ...onInvalidateField(ir)];
214
260
  const head = `export type ${name}Config =`;
215
- if (server === undefined)
261
+ if (fields.length === 0)
216
262
  return `${head} ${runtimeConfig}`;
217
- return `${head} Omit<${runtimeConfig}, "baseURL"> & {
218
- /** Default: the document's first server, ${blockCommentText(server)} */
219
- baseURL?: string
220
- }`;
263
+ const omitted = fields.map(({ key }) => tsString(key)).join(" | ");
264
+ return `${head} Omit<${runtimeConfig}, ${omitted}> & {\n${fields.map(({ text }) => text).join("\n")}\n}`;
221
265
  }
222
266
  /** The `${stem}.types.gen.ts` text of `ir` for the SDK `name`, importing the runtime module `runtime`. */
223
267
  export function sdkTypesText(ir, name, runtime) {
@@ -237,7 +281,7 @@ export function sdkTypesText(ir, name, runtime) {
237
281
  const ctx = { ops: model.opsById, resolve: model.resolve, types };
238
282
  const schemas = model.schemaNames.map((schema) => `export type ${types.refName?.(schema)} = ${irToTs(ir.schemas[schema], types)}`);
239
283
  const body = `${schemas.length === 0 ? "" : `${schemas.join("\n")}\n\n`}${webhookTypesText(ir, types)}${shared(runtimeFeatures(ir))}
240
- ${configText(name, ir.servers[0], runtimeConfig)}
284
+ ${configText(ir, name, runtimeConfig)}
241
285
 
242
286
  /** Every operation of the SDK, by its member path. */
243
287
  export interface ${name}Operations {
@@ -2,6 +2,8 @@ export { sdkMemberPaths, serviceMapOf } from "./service-map.ts";
2
2
  export type SdkOptions = {
3
3
  /** the SDK class name, a TypeScript identifier */
4
4
  readonly name: string;
5
+ /** also write `<stem>.single-flight.gen.ts`, a server's handler for a write and its reads in one request */
6
+ readonly singleFlight?: boolean;
5
7
  /** the file-name stem; the name kebab-cased when left out (`TestSDK` → `test-sdk`) */
6
8
  readonly stem?: string;
7
9
  /** also write `<stem>.tanstack-query.gen.ts`; `@tanstack/query-core` is then the consumer's own peer */
@@ -9,7 +11,7 @@ export type SdkOptions = {
9
11
  };
10
12
  /**
11
13
  * The SDK's files, its stem, the document's own version, and what the generation tells its caller: a root group
12
- * renamed off the safe mirror.
14
+ * renamed off the safe mirror, an `x-invalidate` selector that names no read.
13
15
  */
14
16
  export type GeneratedSdk = {
15
17
  readonly files: Readonly<Record<string, string>>;
@@ -5,6 +5,7 @@
5
5
  * `verifyWebhook` on its own so a receiver imports nothing else. Read from the IR alone (H2).
6
6
  */
7
7
  import { toIR } from "../../ir/build.js";
8
+ import { invalidateReads } from "../../ir/invalidate-reads.js";
8
9
  import { tsString } from "../shared/escape.js";
9
10
  import { compareCodeUnits, words } from "../shared/lang.js";
10
11
  import { MIRROR, mirrorNotice } from "../shared/mirror.js";
@@ -12,6 +13,7 @@ import { runtimeFeatures, runtimeSource } from "./http.js";
12
13
  import { RESERVED } from "./sdk-types-preamble.js";
13
14
  import { sdkTypesText } from "./sdk-types.js";
14
15
  import { memberTree, serviceMapText } from "./service-map.js";
16
+ import { singleFlightText } from "./single-flight-text.js";
15
17
  import { tanstackQueryText } from "./tanstack-query.js";
16
18
  import { webhooksText, webhookTypeNames } from "./webhooks.js";
17
19
  export { sdkMemberPaths, serviceMapOf } from "./service-map.js";
@@ -51,7 +53,19 @@ const RUNTIME_EXPORTS = {
51
53
  ws: [],
52
54
  };
53
55
  const RUNTIME_TYPES = {
54
- core: ["ClientConfig", "InvalidationConfig", "LogEntry", "RequestOptions", "Result"],
56
+ core: [
57
+ "ClientConfig",
58
+ "FreshReads",
59
+ "InvalidateEvent",
60
+ "InvalidateTarget",
61
+ "InvalidationConfig",
62
+ "LogEntry",
63
+ "RequestOptions",
64
+ "Result",
65
+ "SingleFlightBatch",
66
+ "SingleFlightConfig",
67
+ "SingleFlightReadRequest",
68
+ ],
55
69
  realtime: [
56
70
  "ConnectionState",
57
71
  "RealtimeOptions",
@@ -113,21 +127,33 @@ function validated(options) {
113
127
  }
114
128
  return { name, stem };
115
129
  }
130
+ /**
131
+ * Why the class casts a config whose `onInvalidate` event is narrowed (sdk-types.ts) to the runtime's, as the
132
+ * constructor's comment lines.
133
+ */
134
+ const NARROWED_CAST = [
135
+ "onInvalidate's hooks and singleFlight's select take only this API's operationIds, all the runtime sends them,",
136
+ "but a callback's parameter is contravariant, so the narrowed config is the runtime's only through a cast",
137
+ ];
116
138
  /**
117
139
  * The class: the runtime's `SDKClient` over the service map, merged with the operations' interface.
118
- * A config without `baseURL` sends to `server`, the document's first one, when it declares any; its auth header
119
- * pair defaults to the API's scheme (`auth`), as every sibling SDK's does.
140
+ * A config without `baseURL` sends to the document's first server, when it declares any; its auth header
141
+ * pair defaults to the API's scheme, as every sibling SDK's does.
120
142
  */
121
- function clientText(name, stem, server, auth) {
143
+ function clientText(name, stem, ir) {
144
+ const server = ir.servers[0];
122
145
  const based = server === undefined ? "config" : `{ ...config, baseURL: config.baseURL ?? ${tsString(server)} }`;
123
- const config = `schemeAuth(${based}, ${tsString(auth.headerName)}, ${tsString(auth.prefix)})`;
146
+ const isNarrowed = invalidateReads(ir).reads.size > 0;
147
+ const cast = isNarrowed ? `${based} as ConstructorParameters<typeof SDKClient>[1]` : based;
148
+ const config = `schemeAuth(${cast}, ${tsString(ir.auth.headerName)}, ${tsString(ir.auth.prefix)})`;
149
+ const reason = isNarrowed ? NARROWED_CAST.map((line) => `\t\t// ${line}\n`).join("") : "";
124
150
  return `import { SDKClient, schemeAuth } from "./${stem}.runtime.gen.js"
125
151
  import { serviceMap } from "./${stem}.map.gen.js"
126
152
  import type { ${name}Config, ${name}Operations, ${name}Safe } from "./${stem}.types.gen.js"
127
153
 
128
154
  export class ${name} extends SDKClient {
129
155
  constructor(config: ${name}Config) {
130
- super(serviceMap, ${config})
156
+ ${reason} super(serviceMap, ${config})
131
157
  }
132
158
  }
133
159
 
@@ -156,9 +182,12 @@ export function generateSdk(document, options) {
156
182
  // memberTree emits the root groups in code-unit order, each renamed in place
157
183
  const emitted = [...memberTree(ir.tree).entries.keys()];
158
184
  const groups = [...ir.tree.entries.keys()].sort(compareCodeUnits);
159
- const notices = groups.flatMap((group, i) => mirrorNotice("ts", MIRROR, group, emitted[i]) ?? []);
185
+ const notices = [
186
+ ...groups.flatMap((group, i) => mirrorNotice("ts", MIRROR, group, emitted[i]) ?? []),
187
+ ...invalidateReads(ir).warnings.map((warning) => `ts: ${warning}`),
188
+ ];
160
189
  const files = {
161
- [`${stem}.client.gen.ts`]: clientText(name, stem, ir.servers[0], ir.auth),
190
+ [`${stem}.client.gen.ts`]: clientText(name, stem, ir),
162
191
  [`${stem}.index.gen.ts`]: indexText(name, stem, features),
163
192
  [`${stem}.map.gen.ts`]: serviceMapText(ir, runtime),
164
193
  [`${stem}.runtime.gen.ts`]: runtimeSource(features),
@@ -169,5 +198,8 @@ export function generateSdk(document, options) {
169
198
  // the index never names it: its text must not vary by option, and it must never name query-core
170
199
  if (options.tanstackQuery === true)
171
200
  files[`${stem}.tanstack-query.gen.ts`] = tanstackQueryText(ir, name, stem);
201
+ // a server's file: the index never names it, so no browser bundle carries the handler
202
+ if (options.singleFlight === true)
203
+ files[`${stem}.single-flight.gen.ts`] = singleFlightText(ir, name, stem);
172
204
  return { files, notices, stem, version: ir.info.version };
173
205
  }
@@ -2,6 +2,7 @@
2
2
  * Where each operation sits on a generated TS client, and the service map the runtime dispatches
3
3
  * by: the resource tree with every member name a client can expose, and one entry per operation.
4
4
  */
5
+ import { type InvalidatedRead } from "../../ir/invalidate-reads.ts";
5
6
  import type { IR, IRNamespace } from "../../ir/model.ts";
6
7
  /** One operation as the runtime's service map holds it (`runtime/ts/sdk.ts` `ServiceEntry`). */
7
8
  type ServiceEntry = {
@@ -9,11 +10,15 @@ type ServiceEntry = {
9
10
  /** the operation declares no success body: a 2xx reads as null, its body only through `raw` */
10
11
  empty?: true;
11
12
  headers?: string[];
13
+ /** the operationId, which `onInvalidate` names a write and its reads by; the member path may be renamed */
14
+ id: string;
12
15
  idempotent?: true;
13
16
  invalidate?: string[];
14
17
  method: string;
15
18
  params?: string[];
16
19
  path: string;
20
+ /** the reads a successful call makes stale, resolved from `invalidate` at generation */
21
+ reads?: InvalidatedRead[];
17
22
  realtime?: true;
18
23
  /** an event stream; `"json"` when its declared event schema is not a string, its JSON events' names when it names them */
19
24
  sse?: "json" | string[] | true;
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Where each operation sits on a generated TS client, and the service map the runtime dispatches
3
+ * by: the resource tree with every member name a client can expose, and one entry per operation.
4
+ */
5
+ import { invalidateReads } from "../../ir/invalidate-reads.js";
1
6
  import { isJsonMedia, mediaEssence, sdkModel, dispatchKey, isJsonEventData, sseEventSchema, sseEvents, } from "../../ir/sdk-model.js";
2
7
  import { openApiPathParams } from "../../ir/slots.js";
3
8
  import { tsString } from "../shared/escape.js";
@@ -98,7 +103,7 @@ function socketEntry(op, resolve) {
98
103
  }
99
104
  /** The service entry of `op`; `success` is its success answer as the SDK model reads it. */
100
105
  function entryOf(op, success, resolve) {
101
- const entry = { method: op.method, path: op.path };
106
+ const entry = { id: op.id, method: op.method, path: op.path };
102
107
  const params = openApiPathParams(op.path);
103
108
  if (params.length > 0)
104
109
  entry.params = params;
@@ -144,6 +149,7 @@ class Identifier {
144
149
  function mapOf(ir, calls) {
145
150
  const model = sdkModel(ir);
146
151
  const ops = model.opsById;
152
+ const { reads } = invalidateReads(ir);
147
153
  const walk = (ns) => {
148
154
  const node = Object.create(null);
149
155
  for (const [key, entry] of ns.entries) {
@@ -153,6 +159,9 @@ function mapOf(ir, calls) {
153
159
  }
154
160
  const op = ops.get(entry.op.id);
155
161
  const value = entryOf(entry.op, op.success, model.resolve);
162
+ const invalidated = reads.get(entry.op.id);
163
+ if (invalidated !== undefined)
164
+ value.reads = invalidated;
156
165
  if (calls && op.stream !== null)
157
166
  value.call = new Identifier(OPERATION_CALLS[op.stream]);
158
167
  node[key] = value;
@@ -0,0 +1,3 @@
1
+ import type { IR } from "../../ir/model.ts";
2
+ /** The single-flight file of the SDK `name` over `ir`; an API with no write that invalidates a read is refused. */
3
+ export declare function singleFlightText(ir: IR, name: string, stem: string): string;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * `<stem>.single-flight.gen.ts`, written under `--ts-single-flight`: `singleFlightHandler` and `runSingleFlight`
3
+ * over the SDK's service map, a server's file of its own (as the webhook verifier is), never named by the index.
4
+ */
5
+ import { invalidateReads } from "../../ir/invalidate-reads.js";
6
+ import { singleFlightSource } from "./http.js";
7
+ // the runtime's declarations a consumer never imports: every one but the public SingleFlight* and Json types
8
+ const INTERNAL = /^export ((?:async )?function |type |const )(?!SingleFlight|Json\b|JsonObject\b)/gm;
9
+ /** The two calls a server imports, typed by the SDK class `name`. */
10
+ function wrappers(name) {
11
+ return `/**
12
+ * A fetch handler that runs one write, then the reads it made stale, in one request: \`{ v: 1, op, input, reads }\`
13
+ * in, \`{ v: 1, write, reads }\` out. Mount it before any proxy of the API, and make \`getSdk\`'s client per request,
14
+ * forwarding only the auth it chooses. The write runs once: this handler adds no retry, the SDK's own hooks may.
15
+ * Set-Cookie headers of the write are copied onto the answer; they only stick when the API shares this site.
16
+ */
17
+ export function singleFlightHandler(
18
+ getSdk: SingleFlightSdk<${name}>,
19
+ options: SingleFlightOptions = {},
20
+ ): (request: Request) => Promise<Response> {
21
+ return handlerOf(serviceMap, getSdk, options)
22
+ }
23
+
24
+ /** The same batch run with no Request or Response: a refusal throws a TypeError, the write's cookies are dropped. */
25
+ export function runSingleFlight(sdk: ${name}, body: Json): Promise<SingleFlightEnvelope> {
26
+ return runFlight(serviceMap, sdk, body)
27
+ }
28
+ `;
29
+ }
30
+ /** The single-flight file of the SDK `name` over `ir`; an API with no write that invalidates a read is refused. */
31
+ export function singleFlightText(ir, name, stem) {
32
+ if (invalidateReads(ir).reads.size === 0)
33
+ throw new Error("generateSdk: singleFlight needs a write whose x-invalidate names a read; this API declares none");
34
+ return `import type { ${name} } from "./${stem}.client.gen.js"
35
+ import { serviceMap } from "./${stem}.map.gen.js"
36
+ ${singleFlightSource(stem).replaceAll(INTERNAL, "$1")}
37
+ ${wrappers(name)}`;
38
+ }
@@ -6,7 +6,8 @@ import type { IR } from "../../ir/model.ts";
6
6
  */
7
7
  export declare function tanstackQuerySource(runtime: string): string;
8
8
  /**
9
- * `<stem>.tanstack-query.gen.ts`: the vendored adapter, the two key trees read off this document, and the
10
- * mapped types that turn them into exact surfaces over the client's own operations.
9
+ * `<stem>.tanstack-query.gen.ts`: the vendored adapter, the two key trees read off this document, the
10
+ * mapped types that turn them into exact surfaces over the client's own operations, and the
11
+ * `onInvalidate` hook bound to this API's reads.
11
12
  */
12
13
  export declare function tanstackQueryText(ir: IR, name: string, stem: string): string;