@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.
- package/README.md +175 -21
- package/bin/clients.js +5 -6
- package/bin/installgen.js +5 -9
- package/dist/cli.js +3 -1
- package/dist/emit/csharp/sdk-method.d.ts +18 -1
- package/dist/emit/csharp/sdk-method.js +14 -3
- package/dist/emit/csharp/sdk.js +4 -1
- package/dist/emit/go/sdk-method.d.ts +9 -0
- package/dist/emit/go/sdk-method.js +10 -1
- package/dist/emit/go/sdk.js +4 -3
- package/dist/emit/java/sdk-client.js +1 -0
- package/dist/emit/java/sdk-op.d.ts +6 -1
- package/dist/emit/java/sdk-op.js +15 -3
- package/dist/emit/java/sdk.js +7 -1
- package/dist/emit/python/sdk-method.d.ts +11 -0
- package/dist/emit/python/sdk-method.js +15 -0
- package/dist/emit/python/sdk.js +5 -1
- package/dist/emit/rust/sdk-method.d.ts +12 -1
- package/dist/emit/rust/sdk-method.js +10 -2
- package/dist/emit/rust/sdk.js +4 -1
- package/dist/emit/ts/http.d.ts +8 -0
- package/dist/emit/ts/http.js +48 -3
- package/dist/emit/ts/package.js +1 -0
- package/dist/emit/ts/sdk-types-preamble.js +10 -2
- package/dist/emit/ts/sdk-types.d.ts +0 -5
- package/dist/emit/ts/sdk-types.js +52 -8
- package/dist/emit/ts/sdk.d.ts +3 -1
- package/dist/emit/ts/sdk.js +40 -8
- package/dist/emit/ts/service-map.d.ts +5 -0
- package/dist/emit/ts/service-map.js +10 -1
- package/dist/emit/ts/single-flight-text.d.ts +3 -0
- package/dist/emit/ts/single-flight-text.js +38 -0
- package/dist/emit/ts/tanstack-query.d.ts +3 -2
- package/dist/emit/ts/tanstack-query.js +54 -29
- package/dist/gen/process.js +2 -1
- package/dist/gen/switch-on.constants.d.ts +2 -0
- package/dist/gen/switch-on.constants.js +2 -0
- package/dist/gen/targets.d.ts +4 -3
- package/dist/gen/targets.js +4 -3
- package/dist/ir/invalidate-reads.d.ts +17 -0
- package/dist/ir/invalidate-reads.js +104 -0
- package/dist/ir/load.d.ts +10 -0
- package/dist/ir/load.js +62 -14
- package/dist/ir/read-method.constants.d.ts +2 -0
- package/dist/ir/read-method.constants.js +2 -0
- package/dist/release/load.js +1 -1
- package/dist/runtime/csharp/Config.cs +9 -1
- package/dist/runtime/csharp/Exchange.cs +56 -4
- package/dist/runtime/csharp/Hooks.cs +9 -0
- package/dist/runtime/csharp/Operation.cs +6 -1
- package/dist/runtime/csharp/WsDial.cs +3 -1
- package/dist/runtime/go/config.go +5 -0
- package/dist/runtime/go/hooks.go +70 -0
- package/dist/runtime/go/request.go +6 -2
- package/dist/runtime/go/stream.go +4 -1
- package/dist/runtime/go/ws.go +3 -1
- package/dist/runtime/java/ClientConfig.java +11 -0
- package/dist/runtime/java/Flight.java +2 -12
- package/dist/runtime/java/Hooks.java +45 -0
- package/dist/runtime/java/InvalidateEvent.java +10 -0
- package/dist/runtime/java/InvalidateHook.java +12 -0
- package/dist/runtime/java/InvalidateTarget.java +7 -0
- package/dist/runtime/java/Operation.java +23 -3
- package/dist/runtime/java/Realtime.java +3 -1
- package/dist/runtime/java/WsDial.java +3 -0
- package/dist/runtime/python/config.py +8 -2
- package/dist/runtime/python/exchange.py +3 -1
- package/dist/runtime/python/hooks.py +110 -5
- package/dist/runtime/python/operation.py +2 -0
- package/dist/runtime/python/send_async.py +14 -2
- package/dist/runtime/python/send_sync.py +4 -2
- package/dist/runtime/python/ws.py +5 -1
- package/dist/runtime/rust/config.rs +6 -1
- package/dist/runtime/rust/exchange.rs +15 -3
- package/dist/runtime/rust/hooks.rs +127 -2
- package/dist/runtime/rust/log.rs +11 -3
- package/dist/runtime/rust/request.rs +17 -0
- package/dist/runtime/rust/ws.rs +9 -1
- package/dist/runtime/ts/config.ts +69 -0
- package/dist/runtime/ts/http.ts +12 -10
- package/dist/runtime/ts/request.ts +2 -0
- package/dist/runtime/ts/response.ts +7 -0
- package/dist/runtime/ts/sdk-invalidate.ts +82 -0
- package/dist/runtime/ts/sdk-single-flight.constants.ts +25 -0
- package/dist/runtime/ts/sdk-single-flight.ts +203 -0
- package/dist/runtime/ts/sdk-sse.ts +5 -1
- package/dist/runtime/ts/sdk-ws.ts +9 -3
- package/dist/runtime/ts/sdk.ts +55 -31
- package/dist/runtime/ts/single-flight-batch.ts +184 -0
- package/dist/runtime/ts/single-flight-body.ts +59 -0
- package/dist/runtime/ts/single-flight-run.ts +160 -0
- package/dist/runtime/ts/single-flight.constants.ts +31 -0
- package/dist/runtime/ts/single-flight.ts +158 -0
- package/dist/runtime/ts-tanstack-query/invalidate.ts +96 -92
- package/dist/runtime/ts-tanstack-query/query.ts +140 -168
- package/package.json +10 -18
- package/references/INDEX.md +31 -0
- package/references/cli.md +33 -0
- package/references/configuring.md +29 -0
- package/references/documentation.md +15 -0
- package/references/errors.md +23 -0
- package/references/flags.md +104 -0
- package/references/gates.md +46 -0
- package/references/generate.md +29 -0
- package/references/install-scripts.md +28 -0
- package/references/install.md +38 -0
- package/references/license.md +8 -0
- package/references/mcp.md +76 -0
- package/references/output.md +45 -0
- package/references/overview.md +14 -0
- package/references/release-tooling.md +34 -0
- package/references/release.md +305 -0
- package/references/sdks.md +393 -0
- package/references/start.md +22 -0
- package/references/tdd.md +16 -0
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The TanStack Query adapter the `ts` target writes under `--ts-tanstack-query` (bit 22):
|
|
3
3
|
* `<stem>.tanstack-query.gen.ts`, the vendored modules under `runtime/ts-tanstack-query` joined into one
|
|
4
|
-
* file beside the SDK, plus the types that make its surfaces exact for this document
|
|
4
|
+
* file beside the SDK, plus the types that make its surfaces exact for this document and the
|
|
5
|
+
* `onInvalidate` hook bound to its reads.
|
|
5
6
|
*
|
|
6
7
|
* The vendoring mirrors `http.ts`'s `runtimeSource`, with one difference it cannot share: those modules
|
|
7
8
|
* import only each other, so dropping every sibling import is enough. These import clients' runtime too
|
|
@@ -94,15 +95,25 @@ function readable(ir) {
|
|
|
94
95
|
}
|
|
95
96
|
return out;
|
|
96
97
|
}
|
|
98
|
+
/** Each cacheable read's operationId and its member path, as the client nests it. */
|
|
99
|
+
function readMembers(ns, ops, at = []) {
|
|
100
|
+
return [...ns.entries].flatMap(([name, entry]) => {
|
|
101
|
+
if (entry.kind === "namespace")
|
|
102
|
+
return readMembers(entry.ns, ops, [...at, name]);
|
|
103
|
+
return ops.get(entry.op.id) === true ? [[entry.op.id, [...at, name]]] : [];
|
|
104
|
+
});
|
|
105
|
+
}
|
|
97
106
|
/**
|
|
98
|
-
* `<stem>.tanstack-query.gen.ts`: the vendored adapter, the two key trees read off this document,
|
|
99
|
-
* mapped types that turn them into exact surfaces over the client's own operations
|
|
107
|
+
* `<stem>.tanstack-query.gen.ts`: the vendored adapter, the two key trees read off this document, the
|
|
108
|
+
* mapped types that turn them into exact surfaces over the client's own operations, and the
|
|
109
|
+
* `onInvalidate` hook bound to this API's reads.
|
|
100
110
|
*/
|
|
101
111
|
export function tanstackQueryText(ir, name, stem) {
|
|
102
112
|
const ops = readable(ir);
|
|
103
113
|
const tree = memberTree(ir.tree);
|
|
104
114
|
const queries = treeOf(tree, (op) => ops.get(op.id) === true, ops);
|
|
105
115
|
const mutations = treeOf(tree, (op) => ops.get(op.id) === false, ops);
|
|
116
|
+
const table = readMembers(tree, ops).map(([id, member]) => `\t[${JSON.stringify(id)}, ${JSON.stringify(member)}],`);
|
|
106
117
|
return `${tanstackQuerySource(`${stem}.runtime.gen`)}
|
|
107
118
|
import { serviceMap } from "./${stem}.map.gen.js"
|
|
108
119
|
import type { ${name} } from "./${stem}.client.gen.js"
|
|
@@ -115,42 +126,56 @@ type TanstackMutationTree = ${treeText(mutations)}
|
|
|
115
126
|
|
|
116
127
|
type TreeShape = { readonly [key: string]: TreeShape | 1 }
|
|
117
128
|
|
|
118
|
-
|
|
129
|
+
/** A leaf's factory, by surface: query, mutation, infiniteQuery, queryKey, mutationKey. */
|
|
130
|
+
type Leaf<M> = [QueryFactory<M>, MutationFactory<M>, InfiniteFactory<M>, QueryKeyFactory<M>, MutationKeyFactory]
|
|
131
|
+
|
|
132
|
+
type Surfaced<TOps, TTree extends TreeShape, TLeaf extends number> = {
|
|
119
133
|
[K in Extract<keyof TTree, keyof TOps>]: TTree[K] extends 1
|
|
120
|
-
? TLeaf
|
|
121
|
-
? QueryFactory<TOps[K]>
|
|
122
|
-
: TLeaf extends 1
|
|
123
|
-
? MutationFactory<TOps[K]>
|
|
124
|
-
: TLeaf extends 2
|
|
125
|
-
? InfiniteFactory<TOps[K]>
|
|
126
|
-
: KeyFactory<TOps[K]>
|
|
134
|
+
? Leaf<TOps[K]>[TLeaf]
|
|
127
135
|
: TTree[K] extends TreeShape
|
|
128
136
|
? Surfaced<TOps[K], TTree[K], TLeaf>
|
|
129
137
|
: never
|
|
130
138
|
}
|
|
131
139
|
|
|
132
|
-
|
|
133
|
-
* The TanStack Query factories for this SDK. \`sdk\` may be a client or a thunk for one, which an
|
|
134
|
-
* isomorphic app needs; \`getQueryClient\` is what a successful write invalidates against.
|
|
135
|
-
*/
|
|
136
|
-
export function createQueryHelpers(
|
|
137
|
-
sdk: SdkSource<${name}>,
|
|
138
|
-
options: QueryHelperOptions = {},
|
|
139
|
-
): {
|
|
140
|
+
type Surfaces = {
|
|
140
141
|
infiniteQuery: Surfaced<${name}, TanstackQueryTree, 2>
|
|
141
142
|
mutation: Surfaced<${name}, TanstackMutationTree, 1>
|
|
142
|
-
mutationKey: Surfaced<${name}, TanstackMutationTree,
|
|
143
|
+
mutationKey: Surfaced<${name}, TanstackMutationTree, 4>
|
|
143
144
|
query: Surfaced<${name}, TanstackQueryTree, 0>
|
|
144
145
|
queryKey: Surfaced<${name}, TanstackQueryTree, 3>
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* The TanStack Query factories for this SDK, over the client \`getSdk\` returns, read on every call so an
|
|
150
|
+
* isomorphic app can hand each request its own. Spread a factory's result into TanStack's options.
|
|
151
|
+
*/
|
|
152
|
+
export function createQueryHelpers(getSdk: () => ${name}): Surfaces {
|
|
153
|
+
const helpers = queryHelpers(getSdk, serviceMap as ServiceMap, ${JSON.stringify(name)})
|
|
154
|
+
/* the runtime's surfaces are untyped proxies over this map; these types are the map's own */
|
|
155
|
+
return helpers as unknown as Surfaces
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Each read's operationId and the member path its keys start with. */
|
|
159
|
+
const READ_MEMBERS: ReadonlyMap<string, readonly string[]> = new Map<string, readonly string[]>([
|
|
160
|
+
${table.join("\n")}
|
|
161
|
+
])
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* The hook for \`new ${name}({ onInvalidate: [invalidateQueries(queryClient)] })\`: a write, raw or through
|
|
165
|
+
* \`mutation\`, resolves once the reads it made stale have refetched, and a failing refetch never rejects it.
|
|
166
|
+
*/
|
|
167
|
+
export function invalidateQueries(queryClient: QueryClient): (event: InvalidateEvent) => Promise<void> {
|
|
168
|
+
return invalidationHook(queryClient, ${JSON.stringify(name)}, READ_MEMBERS)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* The \`select\` for \`new ${name}({ singleFlight: { select: activeReads(queryClient) } })\`: a write brings back
|
|
173
|
+
* the active reads it made stale in its single-flight batch, and \`invalidateQueries\` puts them in the cache.
|
|
174
|
+
*/
|
|
175
|
+
export function activeReads<Read extends string>(
|
|
176
|
+
queryClient: QueryClient,
|
|
177
|
+
): (targets: InvalidateTarget<Read>[]) => SingleFlightReadRequest<Read>[] {
|
|
178
|
+
return activeReadsOf(queryClient, ${JSON.stringify(name)}, READ_MEMBERS)
|
|
154
179
|
}
|
|
155
180
|
`;
|
|
156
181
|
}
|
package/dist/gen/process.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The generate CLI's child process (bit 17 phase h): watch mode runs each generation as a fresh `clients`, so
|
|
3
3
|
* nothing one run loads outlives it. The child is the package's own bin on this runtime, which picks the entry as it
|
|
4
|
-
* does for a user (Bun the TypeScript source, a checkout the source
|
|
4
|
+
* does for a user (Bun the TypeScript source, a checkout the source by Node's type stripping, an install the compiled
|
|
5
|
+
* one).
|
|
5
6
|
*/
|
|
6
7
|
import { spawn } from "node:child_process";
|
|
7
8
|
import { fileURLToPath } from "node:url";
|
package/dist/gen/targets.d.ts
CHANGED
|
@@ -14,7 +14,8 @@ export declare const TARGETS: readonly ["cli", "csharp", "go", "java", "mcp", "p
|
|
|
14
14
|
export type Target = (typeof TARGETS)[number];
|
|
15
15
|
/**
|
|
16
16
|
* Each target and the names of its generate function's options, which `--<target>-<option>` carries as strings.
|
|
17
|
-
* `--ts-tanstack-query`
|
|
17
|
+
* `--ts-tanstack-query` and `--ts-single-flight` are the switches that take no value: they turn the TanStack Query
|
|
18
|
+
* adapter and the single-flight handler on.
|
|
18
19
|
*/
|
|
19
20
|
export declare const TARGET_OPTIONS: {
|
|
20
21
|
readonly cli: readonly ["aur", "baseUrl", "binaryName", "description", "envPrefix", "homebrewTap", "homepage", "installUrl", "license", "maintainer", "modulePath", "packages", "repo", "scoopBucket", "version", "wingetFork", "wingetPublisher"];
|
|
@@ -24,7 +25,7 @@ export declare const TARGET_OPTIONS: {
|
|
|
24
25
|
readonly mcp: readonly ["envPrefix", "mcpName", "name", "packageName", "version"];
|
|
25
26
|
readonly python: readonly ["packageName", "version"];
|
|
26
27
|
readonly rust: readonly ["categories", "crateName", "description", "documentation", "homepage", "keywords", "license", "repository", "version"];
|
|
27
|
-
readonly ts: readonly ["name", "packageName", "stem", "tanstackQuery", "version"];
|
|
28
|
+
readonly ts: readonly ["name", "packageName", "singleFlight", "stem", "tanstackQuery", "version"];
|
|
28
29
|
};
|
|
29
30
|
/**
|
|
30
31
|
* The target options that take no value, since their name already says what they turn on
|
|
@@ -34,7 +35,7 @@ export declare const TARGET_OPTIONS: {
|
|
|
34
35
|
*/
|
|
35
36
|
declare const BOOLEAN_OPTIONS: {
|
|
36
37
|
readonly cli: readonly ["aur"];
|
|
37
|
-
readonly ts: readonly ["tanstackQuery"];
|
|
38
|
+
readonly ts: readonly ["singleFlight", "tanstackQuery"];
|
|
38
39
|
};
|
|
39
40
|
/** The switches among `T`'s options: the ones `TargetOptions<T>` types as `"true"` or `"false"`. */
|
|
40
41
|
type BooleanOption<T extends Target> = T extends keyof typeof BOOLEAN_OPTIONS ? (typeof BOOLEAN_OPTIONS)[T][number] : never;
|
package/dist/gen/targets.js
CHANGED
|
@@ -12,7 +12,8 @@ import { authorName } from "../emit/shared/metadata.js";
|
|
|
12
12
|
export const TARGETS = ["cli", "csharp", "go", "java", "mcp", "python", "rust", "ts"];
|
|
13
13
|
/**
|
|
14
14
|
* Each target and the names of its generate function's options, which `--<target>-<option>` carries as strings.
|
|
15
|
-
* `--ts-tanstack-query`
|
|
15
|
+
* `--ts-tanstack-query` and `--ts-single-flight` are the switches that take no value: they turn the TanStack Query
|
|
16
|
+
* adapter and the single-flight handler on.
|
|
16
17
|
*/
|
|
17
18
|
export const TARGET_OPTIONS = {
|
|
18
19
|
cli: [
|
|
@@ -73,7 +74,7 @@ export const TARGET_OPTIONS = {
|
|
|
73
74
|
"repository",
|
|
74
75
|
"version",
|
|
75
76
|
],
|
|
76
|
-
ts: ["name", "packageName", "stem", "tanstackQuery", "version"],
|
|
77
|
+
ts: ["name", "packageName", "singleFlight", "stem", "tanstackQuery", "version"],
|
|
77
78
|
};
|
|
78
79
|
/**
|
|
79
80
|
* The target options that take no value, since their name already says what they turn on
|
|
@@ -83,7 +84,7 @@ export const TARGET_OPTIONS = {
|
|
|
83
84
|
*/
|
|
84
85
|
const BOOLEAN_OPTIONS = {
|
|
85
86
|
cli: ["aur"],
|
|
86
|
-
ts: ["tanstackQuery"],
|
|
87
|
+
ts: ["singleFlight", "tanstackQuery"],
|
|
87
88
|
};
|
|
88
89
|
/** Whether `target`'s option `key` takes no value. */
|
|
89
90
|
export function isBooleanOption(target, key) {
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { IR } from "./model.ts";
|
|
2
|
+
/** One read a write makes stale: its operationId and its own path params, in path order. */
|
|
3
|
+
export type InvalidatedRead = {
|
|
4
|
+
operationId: string;
|
|
5
|
+
params: string[];
|
|
6
|
+
};
|
|
7
|
+
/** Each write's reads, by its operationId, and why any selector resolved to nothing. */
|
|
8
|
+
export type InvalidateReads = {
|
|
9
|
+
reads: Map<string, InvalidatedRead[]>;
|
|
10
|
+
warnings: string[];
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Each write's reads: every selector of its `x-invalidate` resolved to the reads it names, deduped, in selector
|
|
14
|
+
* order. A write is any operation with `x-invalidate` but a read (a stream or a socket counts: it marks on open). A
|
|
15
|
+
* non-GET selector and one no read matches are skipped with a warning; a write left with no reads is not held.
|
|
16
|
+
*/
|
|
17
|
+
export declare function invalidateReads(ir: IR): InvalidateReads;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which reads each write makes stale, resolved once at generation for every emitter: a write's `x-invalidate`
|
|
3
|
+
* selectors are backend route patterns (`GET /users/:id`, `GET /files/*rest`, `GET /docs/:id?`), and a read is an
|
|
4
|
+
* OpenAPI path (`/users/{id}`), so this is the one place the two spellings meet. A runtime then fills each read's
|
|
5
|
+
* params from the write's own and never parses a selector.
|
|
6
|
+
*/
|
|
7
|
+
import { compareCodeUnits } from "../emit/shared/lang.js";
|
|
8
|
+
import { READ_METHOD } from "./read-method.constants.js";
|
|
9
|
+
import { openApiPathParams } from "./slots.js";
|
|
10
|
+
const PARAM = ":";
|
|
11
|
+
const WILDCARD = "*";
|
|
12
|
+
/** A whole-segment OpenAPI param, `{name}`. */
|
|
13
|
+
const BRACED = /^\{([^{}/]+)\}$/;
|
|
14
|
+
/** A segment of fixed text, as a route key spells it. */
|
|
15
|
+
function literal(text) {
|
|
16
|
+
return `=${text}`;
|
|
17
|
+
}
|
|
18
|
+
/** A read: a GET that answers once, never a stream or a connection. */
|
|
19
|
+
function isRead(op) {
|
|
20
|
+
const { realtime, sse, websocket } = op.extensions;
|
|
21
|
+
return op.method === READ_METHOD && !sse && !websocket && !realtime;
|
|
22
|
+
}
|
|
23
|
+
/** The key of a read's OpenAPI path: a whole `{name}` is a param, a wildcard one the rest of the path. */
|
|
24
|
+
function readKey(op) {
|
|
25
|
+
const wildcards = new Set(op.params.path.filter((p) => p.wildcard === true).map((p) => p.name));
|
|
26
|
+
return op.path
|
|
27
|
+
.split("/")
|
|
28
|
+
.map((text) => {
|
|
29
|
+
const name = BRACED.exec(text)?.[1];
|
|
30
|
+
if (name === undefined)
|
|
31
|
+
return literal(text);
|
|
32
|
+
return wildcards.has(name) ? WILDCARD : PARAM;
|
|
33
|
+
})
|
|
34
|
+
.join("/");
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Every key a selector's route pattern spells (`:name`, `{name}`, a trailing `*name` or `*`, or text): an optional
|
|
38
|
+
* `:name?` segment both left out and kept.
|
|
39
|
+
*/
|
|
40
|
+
function selectorKeys(path) {
|
|
41
|
+
const texts = path.split("/");
|
|
42
|
+
let keys = [[]];
|
|
43
|
+
for (const [i, text] of texts.entries()) {
|
|
44
|
+
const isParam = text.length > 1 && text.startsWith(":");
|
|
45
|
+
let segment = literal(text);
|
|
46
|
+
if (text.startsWith("*") && i === texts.length - 1)
|
|
47
|
+
segment = WILDCARD;
|
|
48
|
+
else if (isParam || BRACED.test(text))
|
|
49
|
+
segment = PARAM;
|
|
50
|
+
const kept = keys.map((key) => [...key, segment]);
|
|
51
|
+
keys = isParam && text.endsWith("?") ? [...keys, ...kept] : kept;
|
|
52
|
+
}
|
|
53
|
+
return keys.map((key) => key.join("/"));
|
|
54
|
+
}
|
|
55
|
+
/** The reads whose key is `at`, by operationId. */
|
|
56
|
+
function readsAt(reads, at) {
|
|
57
|
+
return reads
|
|
58
|
+
.filter(({ key }) => key === at)
|
|
59
|
+
.map(({ op }) => op)
|
|
60
|
+
.toSorted((a, b) => compareCodeUnits(a.id, b.id));
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The reads `selector` names, in the order its keys spell them (an optional segment left out first) and by
|
|
64
|
+
* operationId within one key, so a document's path order never reorders them; or why it names none.
|
|
65
|
+
*/
|
|
66
|
+
function resolve(selector, reads) {
|
|
67
|
+
const space = selector.indexOf(" ");
|
|
68
|
+
if (space <= 0)
|
|
69
|
+
return { why: "is not a route selector" };
|
|
70
|
+
const method = selector.slice(0, space).toUpperCase();
|
|
71
|
+
if (method !== READ_METHOD)
|
|
72
|
+
return { why: `names a ${method} route; only ${READ_METHOD} reads are cached` };
|
|
73
|
+
const matched = selectorKeys(selector.slice(space + 1)).flatMap((at) => readsAt(reads, at));
|
|
74
|
+
return matched.length > 0 ? { ops: matched } : { why: `matches no ${READ_METHOD} read` };
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Each write's reads: every selector of its `x-invalidate` resolved to the reads it names, deduped, in selector
|
|
78
|
+
* order. A write is any operation with `x-invalidate` but a read (a stream or a socket counts: it marks on open). A
|
|
79
|
+
* non-GET selector and one no read matches are skipped with a warning; a write left with no reads is not held.
|
|
80
|
+
*/
|
|
81
|
+
export function invalidateReads(ir) {
|
|
82
|
+
const readOps = ir.operations.filter(isRead).map((op) => ({ key: readKey(op), op }));
|
|
83
|
+
const reads = new Map();
|
|
84
|
+
const warnings = [];
|
|
85
|
+
for (const op of ir.operations) {
|
|
86
|
+
const selectors = op.extensions.invalidates ?? [];
|
|
87
|
+
if (selectors.length === 0 || isRead(op))
|
|
88
|
+
continue;
|
|
89
|
+
const seen = new Map();
|
|
90
|
+
for (const selector of selectors) {
|
|
91
|
+
const resolved = resolve(selector, readOps);
|
|
92
|
+
if ("why" in resolved) {
|
|
93
|
+
warnings.push(`${op.id}: x-invalidate ${JSON.stringify(selector)} ${resolved.why}; skipped`);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
for (const read of resolved.ops)
|
|
97
|
+
if (!seen.has(read.id))
|
|
98
|
+
seen.set(read.id, { operationId: read.id, params: openApiPathParams(read.path) });
|
|
99
|
+
}
|
|
100
|
+
if (seen.size > 0)
|
|
101
|
+
reads.set(op.id, [...seen.values()]);
|
|
102
|
+
}
|
|
103
|
+
return { reads, warnings };
|
|
104
|
+
}
|
package/dist/ir/load.d.ts
CHANGED
|
@@ -1,11 +1,21 @@
|
|
|
1
|
+
import type * as Vite from "vite";
|
|
1
2
|
/** Bun's resolver, as the loader uses it: `specifier` resolved from `from` under this process's conditions. */
|
|
2
3
|
export type BunResolver = {
|
|
3
4
|
resolveSync(specifier: string, from: string): string;
|
|
4
5
|
};
|
|
6
|
+
type Importer = (specifier: string) => Promise<Record<string, unknown>>;
|
|
5
7
|
/** `<module>[#export]` as its module path and the export it names, if any. */
|
|
6
8
|
export declare function appRef(ref: string): {
|
|
7
9
|
module: string;
|
|
8
10
|
name: string | undefined;
|
|
9
11
|
};
|
|
12
|
+
/**
|
|
13
|
+
* Node: Vite's SSR runner rooted at the module's directory, one graph shared by the app and its document, so both see
|
|
14
|
+
* one core module (its GRAPH symbol). Each alias matches its specifier exactly, never as a prefix of a longer subpath.
|
|
15
|
+
* The app's Vite config is never applied, and the server holds no handle (no socket, no watcher, no dependency scan),
|
|
16
|
+
* so it is left for the process to end. `vite` is the import, a parameter so its absence can be tested.
|
|
17
|
+
*/
|
|
18
|
+
export declare function viteImporter(path: string, aliases: Record<string, string>, vite?: () => Promise<typeof Vite>): Promise<Importer>;
|
|
10
19
|
/** The OpenAPI document of the app `ref` names, by the app's own core; `cwd` resolves it. One load at a time per process. */
|
|
11
20
|
export declare function loadAppDocument(ref: string, cwd: string): Promise<Record<string, unknown>>;
|
|
21
|
+
export {};
|
package/dist/ir/load.js
CHANGED
|
@@ -11,12 +11,12 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
11
11
|
* document generated by the app's own core, `@workerstack/backend/http/openapi`, resolved from the app as it would be at run
|
|
12
12
|
* time, so gen imports no core itself (H2). The named export, else `app`, else `default`, is the app; the module's
|
|
13
13
|
* `openApi` export, if any, is the document's options (core's GenerateOpenApiOptions), else a bare `info`. On Node
|
|
14
|
-
* the module loads through
|
|
15
|
-
* checkout read from its source by the backend-source condition, refused when this Bun resolves it
|
|
16
|
-
* With no core installed where the app resolves it, the refusal names it.
|
|
14
|
+
* the module loads through Vite's module runner, a core checkout read from its source by alias; on Bun through Bun's
|
|
15
|
+
* own import, a checkout read from its source by the backend-source condition, refused when this Bun resolves it
|
|
16
|
+
* elsewhere (bit 20). With no core installed where the app resolves it, the refusal names it.
|
|
17
17
|
*/
|
|
18
18
|
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
19
|
-
import { dirname, join, relative, resolve } from "node:path";
|
|
19
|
+
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
20
20
|
import { pathToFileURL } from "node:url";
|
|
21
21
|
const CORE = "@workerstack/backend";
|
|
22
22
|
const DEFAULT_OPTIONS = { info: { title: "API", version: "0.0.0" } };
|
|
@@ -63,16 +63,64 @@ function appOf(mod, ref, name) {
|
|
|
63
63
|
const which = name === undefined ? "no `app` or `default` export" : `no export ${JSON.stringify(name)}`;
|
|
64
64
|
throw new Error(`--app ${ref}: ${which} that is a backend app (name one as <module>#<export>)`);
|
|
65
65
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
66
|
+
/** The id of a module that re-exports what its suffix names, as an import from the app's directory would read it. */
|
|
67
|
+
const REEXPORT = "clients-reexport:";
|
|
68
|
+
/** The plugin serving each REEXPORT module: one `export *` of its specifier. */
|
|
69
|
+
const reexports = {
|
|
70
|
+
load: (id) => id.startsWith(`\0${REEXPORT}`) ? `export * from ${JSON.stringify(id.slice(REEXPORT.length + 1))}\n` : null,
|
|
71
|
+
name: "clients-reexport",
|
|
72
|
+
resolveId: (id) => (id.startsWith(REEXPORT) ? `\0${id}` : null),
|
|
73
|
+
};
|
|
74
|
+
/** The characters a RegExp reads as syntax. */
|
|
75
|
+
const REGEX_SYNTAX = /[$()*+.?[\\\]^{|}]/g;
|
|
76
|
+
/** `text` matched literally in a RegExp. */
|
|
77
|
+
function literal(text) {
|
|
78
|
+
return text.replaceAll(REGEX_SYNTAX, String.raw `\$&`);
|
|
79
|
+
}
|
|
80
|
+
/** Vite's server API, or why `generate --app` can't run on Node without it. */
|
|
81
|
+
function loadVite(vite) {
|
|
82
|
+
return vite().catch((error) => {
|
|
83
|
+
if (error.message.startsWith("Cannot find package 'vite' "))
|
|
84
|
+
throw new Error("clients generate --app on Node loads TypeScript through Vite: install vite, or run it with Bun");
|
|
85
|
+
throw error;
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Node: Vite's SSR runner rooted at the module's directory, one graph shared by the app and its document, so both see
|
|
90
|
+
* one core module (its GRAPH symbol). Each alias matches its specifier exactly, never as a prefix of a longer subpath.
|
|
91
|
+
* The app's Vite config is never applied, and the server holds no handle (no socket, no watcher, no dependency scan),
|
|
92
|
+
* so it is left for the process to end. `vite` is the import, a parameter so its absence can be tested.
|
|
93
|
+
*/
|
|
94
|
+
export async function viteImporter(path, aliases, vite = () => import("vite")) {
|
|
95
|
+
const { createServer, createServerModuleRunner } = await loadVite(vite);
|
|
96
|
+
const server = await createServer({
|
|
97
|
+
appType: "custom",
|
|
98
|
+
configFile: false,
|
|
99
|
+
logLevel: "silent",
|
|
100
|
+
// nothing here serves a browser: no dependency scan of the root
|
|
101
|
+
optimizeDeps: { entries: [], noDiscovery: true },
|
|
102
|
+
plugins: [reexports],
|
|
103
|
+
resolve: {
|
|
104
|
+
alias: Object.entries(aliases).map(([find, replacement]) => ({
|
|
105
|
+
find: new RegExp(`^${literal(find)}$`),
|
|
106
|
+
replacement,
|
|
107
|
+
})),
|
|
108
|
+
},
|
|
109
|
+
root: dirname(path),
|
|
110
|
+
server: { middlewareMode: true, watch: null, ws: false },
|
|
111
|
+
});
|
|
112
|
+
// its own source-map hook, not Node's: a stack frame names the app's line even where another hook owns stacks
|
|
113
|
+
const runner = createServerModuleRunner(server.environments.ssr, {
|
|
114
|
+
hmr: false,
|
|
115
|
+
sourcemapInterceptor: "prepareStackTrace",
|
|
116
|
+
});
|
|
117
|
+
// a bare specifier through a module re-exporting it, so Vite resolves it as it resolves the app's own imports
|
|
118
|
+
// (aliased, inlined or externalized alike) and the app and its document share one core
|
|
119
|
+
return (specifier) => runner.import(isAbsolute(specifier) ? specifier : `${REEXPORT}${specifier}`);
|
|
71
120
|
}
|
|
72
|
-
// Bun: its own import, never
|
|
73
|
-
//
|
|
74
|
-
//
|
|
75
|
-
// each must resolve to its source, never to an unbuilt or stale dist/.
|
|
121
|
+
// Bun: its own import, never Vite's runner, whose source-map hook is the class of Error.prepareStackTrace replacer that
|
|
122
|
+
// breaks Bun's captureStackTrace on a non-Error (Vite's follow-redirects; bit 20). A checkout's aliases hold by the
|
|
123
|
+
// backend-source condition instead: each must resolve to its source, never to an unbuilt or stale dist/.
|
|
76
124
|
function bunImporter(bun, path, aliases, ref) {
|
|
77
125
|
const from = dirname(path);
|
|
78
126
|
for (const [specifier, source] of Object.entries(aliases)) {
|
|
@@ -102,7 +150,7 @@ export async function loadAppDocument(ref, cwd) {
|
|
|
102
150
|
const aliases = sourceAliases(root);
|
|
103
151
|
// Bun resolves core's own imports under the backend-source condition, through core's package.json
|
|
104
152
|
const load = bun === undefined
|
|
105
|
-
? await
|
|
153
|
+
? await viteImporter(path, { ...aliases.exports, ...aliases.imports })
|
|
106
154
|
: bunImporter(bun, path, aliases.exports, ref);
|
|
107
155
|
const mod = await load(path);
|
|
108
156
|
const app = appOf(mod, ref, name);
|
package/dist/release/load.js
CHANGED
|
@@ -10,7 +10,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
10
10
|
* Loads a `release.config.ts` the way an installgen config loads: a config outside any install (a fixture dir, a repo
|
|
11
11
|
* that runs `bunx`) has no `node_modules` to resolve `@workerstack/clients/release` from, so that one import is
|
|
12
12
|
* mapped to the running package's own entry while the config is imported (a Node resolve hook, deregistered after;
|
|
13
|
-
* a Bun virtual module).
|
|
13
|
+
* a Bun virtual module). A plain resolve would look in a local install, which is exactly what is missing.
|
|
14
14
|
*/
|
|
15
15
|
import { existsSync, realpathSync } from "node:fs";
|
|
16
16
|
import { dirname, extname, resolve } from "node:path";
|
|
@@ -63,6 +63,13 @@ public sealed record ClientConfig
|
|
|
63
63
|
/// <summary>Asked once per call for a new token after a 401, with the call's token; null or empty keeps the 401.</summary>
|
|
64
64
|
public Func<CancellationToken, Task<string?>>? OnAuthExpired { get; init; }
|
|
65
65
|
|
|
66
|
+
/// <summary>
|
|
67
|
+
/// Run in order once per successful write, each after the last, with what it made stale and the call's token: the
|
|
68
|
+
/// call returns after the last. An event stream or WebSocket runs them when it opens, without waiting. A hook's
|
|
69
|
+
/// error goes to <see cref="OnLog"/> as an error entry and never to the call; the next hook still runs.
|
|
70
|
+
/// </summary>
|
|
71
|
+
public IReadOnlyList<Func<InvalidateEvent, CancellationToken, Task>>? OnInvalidate { get; init; }
|
|
72
|
+
|
|
66
73
|
/// <summary>Told of each call's start, its answer and its error; what it throws is ignored.</summary>
|
|
67
74
|
public Action<LogEntry>? OnLog { get; init; }
|
|
68
75
|
|
|
@@ -83,7 +90,8 @@ public sealed record ClientConfig
|
|
|
83
90
|
builder.Append(", Redirect = ").Append(Redirect);
|
|
84
91
|
builder.Append(", MaxResponseBytes = ").Append(MaxResponseBytes);
|
|
85
92
|
(string Name, bool Set)[] hooks =
|
|
86
|
-
[("OnRequest", OnRequest is not null), ("OnResponse", OnResponse is not null), ("OnAuthExpired", OnAuthExpired is not null), ("
|
|
93
|
+
[("OnRequest", OnRequest is not null), ("OnResponse", OnResponse is not null), ("OnAuthExpired", OnAuthExpired is not null), ("OnInvalidate", OnInvalidate is not null),
|
|
94
|
+
("OnLog", OnLog is not null)];
|
|
87
95
|
builder.Append(", Hooks = [").Append(string.Join(", ", hooks.Where(hook => hook.Set).Select(hook => hook.Name))).Append(']');
|
|
88
96
|
return true;
|
|
89
97
|
}
|
|
@@ -31,8 +31,14 @@ internal sealed class Exchange(Transport client, Operation op, Call call, bool s
|
|
|
31
31
|
private int _redirects;
|
|
32
32
|
private HttpResponseMessage? _live;
|
|
33
33
|
|
|
34
|
-
|
|
35
|
-
|
|
34
|
+
private bool _settled;
|
|
35
|
+
|
|
36
|
+
public async Task<(RawResponse Raw, SdkException? Error)> RunAsync(CancellationToken cancellationToken)
|
|
37
|
+
{
|
|
38
|
+
var done = Done(await BoundedAsync(cancellationToken).ConfigureAwait(false));
|
|
39
|
+
await InvalidatedAsync(cancellationToken).ConfigureAwait(false);
|
|
40
|
+
return done;
|
|
41
|
+
}
|
|
36
42
|
|
|
37
43
|
public async Task<HttpResponseMessage> OpenAsync(CancellationToken cancellationToken)
|
|
38
44
|
{
|
|
@@ -44,6 +50,7 @@ internal sealed class Exchange(Transport client, Operation op, Call call, bool s
|
|
|
44
50
|
throw error;
|
|
45
51
|
}
|
|
46
52
|
call.Read?.Invoke(raw.Headers);
|
|
53
|
+
Detached();
|
|
47
54
|
return _live!;
|
|
48
55
|
}
|
|
49
56
|
catch
|
|
@@ -231,8 +238,8 @@ internal sealed class Exchange(Transport client, Operation op, Call call, bool s
|
|
|
231
238
|
SdkException? error = null;
|
|
232
239
|
if (answer.Status is >= 200 and < 300)
|
|
233
240
|
{
|
|
234
|
-
|
|
235
|
-
|
|
241
|
+
client.Stale.Settle(_meta, op.Invalidates ?? [], Values);
|
|
242
|
+
_settled = true;
|
|
236
243
|
error = answer.Over ? new DecodeException($"the answer exceeds {Max} bytes") : null;
|
|
237
244
|
}
|
|
238
245
|
else
|
|
@@ -244,4 +251,49 @@ internal sealed class Exchange(Transport client, Operation op, Call call, bool s
|
|
|
244
251
|
raw.Fill(answer.Status, answer.Headers, answer.Body, answer.Url);
|
|
245
252
|
return (raw, error);
|
|
246
253
|
}
|
|
254
|
+
|
|
255
|
+
private Dictionary<string, string> Values => op.PathParams.Zip(call.Path).ToDictionary(pair => pair.First, pair => pair.Second);
|
|
256
|
+
|
|
257
|
+
/* a socket's 101: its targets marked stale, and the hooks run detached */
|
|
258
|
+
public void Opened()
|
|
259
|
+
{
|
|
260
|
+
_meta = client.Stale.Begin(op.Method, UrlPath.Expand(op, call.Path));
|
|
261
|
+
client.Stale.Settle(_meta, op.Invalidates ?? [], Values);
|
|
262
|
+
_settled = true;
|
|
263
|
+
Detached();
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/* an open never waits on a hook nor ends its token; InvalidatedAsync never throws */
|
|
267
|
+
private void Detached()
|
|
268
|
+
{
|
|
269
|
+
if (op.Reads is { Length: > 0 } && client.Config.OnInvalidate is { Count: > 0 })
|
|
270
|
+
{
|
|
271
|
+
_ = Task.Run(() => InvalidatedAsync(CancellationToken.None));
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/* each OnInvalidate hook in order after a 2xx, a hook's error logged and never the call's */
|
|
276
|
+
private async Task InvalidatedAsync(CancellationToken token)
|
|
277
|
+
{
|
|
278
|
+
if (!_settled || op.Reads is not { Length: > 0 } reads || client.Config.OnInvalidate is not { Count: > 0 } hooks)
|
|
279
|
+
{
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
var values = Values;
|
|
283
|
+
var targets = reads.Select(read => new InvalidateTarget(read.Op, read.Params
|
|
284
|
+
.Where(name => values.TryGetValue(name, out var value) && value is not ("" or "." or ".."))
|
|
285
|
+
.ToDictionary(name => name, name => values[name], StringComparer.Ordinal))).ToList();
|
|
286
|
+
var e = new InvalidateEvent(op.By ?? "", targets);
|
|
287
|
+
foreach (var hook in hooks)
|
|
288
|
+
{
|
|
289
|
+
try
|
|
290
|
+
{
|
|
291
|
+
await hook(e, token).ConfigureAwait(false);
|
|
292
|
+
}
|
|
293
|
+
catch (Exception error)
|
|
294
|
+
{
|
|
295
|
+
_log.Failed(error);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
247
299
|
}
|
|
@@ -104,6 +104,15 @@ public sealed class ResponseContext
|
|
|
104
104
|
$"ResponseContext {{ Status = {Status}, IsRetry = {IsRetry}, Selector = {Selector}, IsStale = {IsStale}, InvalidatedBy = [{string.Join(", ", InvalidatedBy)}] }}";
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
+
/// <summary>
|
|
108
|
+
/// What each <c>ClientConfig.OnInvalidate</c> hook sees after a successful write: the write's operationId, and every
|
|
109
|
+
/// read its <c>x-invalidate</c> made stale.
|
|
110
|
+
/// </summary>
|
|
111
|
+
public sealed record InvalidateEvent(string By, IReadOnlyList<InvalidateTarget> Targets);
|
|
112
|
+
|
|
113
|
+
/// <summary>One read a write made stale: its operationId, and the write's values for the read's path params it has.</summary>
|
|
114
|
+
public sealed record InvalidateTarget(string OperationId, IReadOnlyDictionary<string, string> Params);
|
|
115
|
+
|
|
107
116
|
internal sealed record CallState(bool IsRetry, string Selector, bool IsStale, IReadOnlyList<string> InvalidatedBy, IDictionary<string, object?> State);
|
|
108
117
|
|
|
109
118
|
internal static class Hooks
|
|
@@ -6,7 +6,12 @@ using System.Text.Json.Serialization.Metadata;
|
|
|
6
6
|
|
|
7
7
|
namespace Http.Runtime;
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
/* By and Reads: a write's operationId and the reads its success makes stale, for ClientConfig.OnInvalidate */
|
|
10
|
+
internal sealed record Operation(
|
|
11
|
+
string Method, string Path, string[] PathParams, bool Idempotent, string? Accept = null, string[]? Invalidates = null, string? By = null, StaleRead[]? Reads = null);
|
|
12
|
+
|
|
13
|
+
/* one read a write makes stale, as the generator resolved it: its operationId and its own path params */
|
|
14
|
+
internal sealed record StaleRead(string Op, string[] Params);
|
|
10
15
|
|
|
11
16
|
internal sealed record Defaults(string? BaseUrl, string AuthHeader, string AuthPrefix, JsonSerializerOptions Json);
|
|
12
17
|
|
|
@@ -50,7 +50,9 @@ internal static class WsDial
|
|
|
50
50
|
x.Raw?.Fill(101, headers, [], SocketUrl(url));
|
|
51
51
|
var stream = Connection(await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false));
|
|
52
52
|
var options = new WebSocketCreationOptions { SubProtocol = chosen, KeepAliveInterval = KeepAlive, KeepAliveTimeout = KeepAlive };
|
|
53
|
-
|
|
53
|
+
var socket = new TypedWebSocket(WebSocket.CreateFromStream(stream, options), chosen, response);
|
|
54
|
+
x.Opened();
|
|
55
|
+
return socket;
|
|
54
56
|
}
|
|
55
57
|
catch
|
|
56
58
|
{
|
|
@@ -24,6 +24,10 @@ import (
|
|
|
24
24
|
//
|
|
25
25
|
// WSKeepalive is a WebSocket's ping interval and pong wait: zero means 20s, negative none.
|
|
26
26
|
//
|
|
27
|
+
// OnInvalidate's hooks run in order once per successful write that makes reads stale, before the
|
|
28
|
+
// call returns and with its context: a stream or socket calls them detached once it opens. A
|
|
29
|
+
// hook's error goes to OnLog and never fails the call.
|
|
30
|
+
//
|
|
27
31
|
// AuthHeaderName and AuthHeaderPrefix are a pair: leave both empty for the API's scheme; set the
|
|
28
32
|
// name and the prefix is yours (empty means none); set only the prefix to keep the scheme's header.
|
|
29
33
|
type Config struct {
|
|
@@ -40,6 +44,7 @@ type Config struct {
|
|
|
40
44
|
OnRequest []func(*RequestContext) error
|
|
41
45
|
OnResponse []func(*ResponseContext) error
|
|
42
46
|
OnLog func(LogEntry)
|
|
47
|
+
OnInvalidate []func(context.Context, InvalidateEvent) error
|
|
43
48
|
MaxResponseBytes int64
|
|
44
49
|
WSKeepalive time.Duration
|
|
45
50
|
|