@distilled.cloud/core 1.0.0-rc.16 → 1.0.0-rc.18
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/lib/_bundle/aws.js +2 -0
- package/lib/_bundle/aws.js.map +1 -0
- package/lib/_bundle/base.js +5 -0
- package/lib/_bundle/base.js.map +1 -0
- package/lib/_bundle/graphql.js +3 -0
- package/lib/_bundle/graphql.js.map +1 -0
- package/lib/_bundle/rest.js +2 -0
- package/lib/_bundle/rest.js.map +1 -0
- package/lib/_bundle/xml.js +4 -0
- package/lib/_bundle/xml.js.map +1 -0
- package/lib/annotations.d.ts +15 -0
- package/lib/annotations.d.ts.map +1 -0
- package/lib/annotations.js +2 -0
- package/lib/annotations.js.map +1 -0
- package/lib/api.d.ts +15 -0
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js +1 -796
- package/lib/category.d.ts.map +1 -1
- package/lib/category.js +1 -278
- package/lib/chunks.js +1 -11
- package/lib/config.d.ts +54 -13
- package/lib/config.d.ts.map +1 -1
- package/lib/config.js +1 -161
- package/lib/crypto.js +1 -130
- package/lib/debug.d.ts.map +1 -1
- package/lib/debug.js +1 -8
- package/lib/error-category.d.ts.map +1 -1
- package/lib/error-category.js +1 -47
- package/lib/errors.d.ts +2 -13
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +1 -198
- package/lib/graphql.d.ts +14 -0
- package/lib/graphql.d.ts.map +1 -1
- package/lib/graphql.js +1 -1058
- package/lib/graphql.types.js +1 -6
- package/lib/index.d.ts +3 -2
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +1 -15
- package/lib/pagination.d.ts +34 -2
- package/lib/pagination.d.ts.map +1 -1
- package/lib/pagination.js +1 -271
- package/lib/plain-values.js +1 -39
- package/lib/plain-values.js.map +1 -1
- package/lib/protocol-http.d.ts +30 -6
- package/lib/protocol-http.d.ts.map +1 -1
- package/lib/protocol-http.js +1 -812
- package/lib/protocol-rest.d.ts +53 -39
- package/lib/protocol-rest.d.ts.map +1 -1
- package/lib/protocol-rest.js +1 -375
- package/lib/query.js +1 -27
- package/lib/response-validation-strict.js +1 -284
- package/lib/response-validation.d.ts +4 -3
- package/lib/response-validation.d.ts.map +1 -1
- package/lib/response-validation.js +1 -118
- package/lib/retry-after.js +1 -112
- package/lib/retry.js +1 -197
- package/lib/schema-lite-impl.js +1 -341
- package/lib/schema-lite-typed.js +1 -27
- package/lib/schema-lite.js +1 -31
- package/lib/schema.js +1 -220
- package/lib/telemetry-debug.d.ts +14 -0
- package/lib/telemetry-debug.d.ts.map +1 -0
- package/lib/telemetry-debug.js +2 -0
- package/lib/telemetry-debug.js.map +1 -0
- package/lib/telemetry-hooks.d.ts +32 -0
- package/lib/telemetry-hooks.d.ts.map +1 -0
- package/lib/telemetry-hooks.js +2 -0
- package/lib/telemetry-hooks.js.map +1 -0
- package/lib/telemetry-host-rules.d.ts +23 -0
- package/lib/telemetry-host-rules.d.ts.map +1 -0
- package/lib/telemetry-host-rules.js +2 -0
- package/lib/telemetry-host-rules.js.map +1 -0
- package/lib/telemetry-lambda-context.d.ts +17 -0
- package/lib/telemetry-lambda-context.d.ts.map +1 -0
- package/lib/telemetry-lambda-context.js +2 -0
- package/lib/telemetry-lambda-context.js.map +1 -0
- package/lib/telemetry-message-context.d.ts +52 -0
- package/lib/telemetry-message-context.d.ts.map +1 -0
- package/lib/telemetry-message-context.js +2 -0
- package/lib/telemetry-message-context.js.map +1 -0
- package/lib/telemetry-metrics.d.ts +6 -0
- package/lib/telemetry-metrics.d.ts.map +1 -0
- package/lib/telemetry-metrics.js +2 -0
- package/lib/telemetry-metrics.js.map +1 -0
- package/lib/telemetry-name-template.d.ts +13 -0
- package/lib/telemetry-name-template.d.ts.map +1 -0
- package/lib/telemetry-name-template.js +2 -0
- package/lib/telemetry-name-template.js.map +1 -0
- package/lib/telemetry-stream.d.ts +9 -0
- package/lib/telemetry-stream.d.ts.map +1 -0
- package/lib/telemetry-stream.js +2 -0
- package/lib/telemetry-stream.js.map +1 -0
- package/lib/telemetry-xray.d.ts +28 -0
- package/lib/telemetry-xray.d.ts.map +1 -0
- package/lib/telemetry-xray.js +2 -0
- package/lib/telemetry-xray.js.map +1 -0
- package/lib/telemetry.d.ts +269 -0
- package/lib/telemetry.d.ts.map +1 -0
- package/lib/telemetry.js +3 -0
- package/lib/telemetry.js.map +1 -0
- package/lib/trait.js +1 -131
- package/lib/xml.js +1 -323
- package/package.json +1 -3
- package/src/annotations.ts +37 -0
- package/src/api.ts +130 -30
- package/src/category.ts +21 -22
- package/src/config.ts +58 -29
- package/src/debug.ts +9 -6
- package/src/error-category.ts +12 -14
- package/src/errors.ts +7 -7
- package/src/graphql.ts +123 -18
- package/src/index.ts +3 -2
- package/src/pagination.ts +119 -6
- package/src/protocol-http.ts +63 -43
- package/src/protocol-rest.ts +201 -140
- package/src/response-validation.ts +4 -3
- package/src/telemetry-debug.ts +135 -0
- package/src/telemetry-hooks.ts +33 -0
- package/src/telemetry-host-rules.ts +39 -0
- package/src/telemetry-lambda-context.ts +46 -0
- package/src/telemetry-message-context.ts +170 -0
- package/src/telemetry-metrics.ts +69 -0
- package/src/telemetry-name-template.ts +26 -0
- package/src/telemetry-stream.ts +91 -0
- package/src/telemetry-xray.ts +66 -0
- package/src/telemetry.ts +768 -0
- package/lib/api.js.map +0 -1
- package/lib/category.js.map +0 -1
- package/lib/chunks.js.map +0 -1
- package/lib/codegen/boolean-string-enums.d.ts +0 -36
- package/lib/codegen/boolean-string-enums.d.ts.map +0 -1
- package/lib/codegen/boolean-string-enums.js +0 -147
- package/lib/codegen/boolean-string-enums.js.map +0 -1
- package/lib/codegen/chunk.d.ts +0 -7
- package/lib/codegen/chunk.d.ts.map +0 -1
- package/lib/codegen/chunk.js +0 -139
- package/lib/codegen/chunk.js.map +0 -1
- package/lib/codegen/cli.d.ts +0 -80
- package/lib/codegen/cli.d.ts.map +0 -1
- package/lib/codegen/cli.js +0 -166
- package/lib/codegen/cli.js.map +0 -1
- package/lib/codegen/datafy.d.ts +0 -14
- package/lib/codegen/datafy.d.ts.map +0 -1
- package/lib/codegen/datafy.js +0 -853
- package/lib/codegen/datafy.js.map +0 -1
- package/lib/codegen/dedupe.d.ts +0 -5
- package/lib/codegen/dedupe.d.ts.map +0 -1
- package/lib/codegen/dedupe.js +0 -153
- package/lib/codegen/dedupe.js.map +0 -1
- package/lib/codegen/emit.d.ts +0 -125
- package/lib/codegen/emit.d.ts.map +0 -1
- package/lib/codegen/emit.js +0 -99
- package/lib/codegen/emit.js.map +0 -1
- package/lib/codegen/format.d.ts +0 -11
- package/lib/codegen/format.d.ts.map +0 -1
- package/lib/codegen/format.js +0 -32
- package/lib/codegen/format.js.map +0 -1
- package/lib/codegen/generated-at.d.ts +0 -29
- package/lib/codegen/generated-at.d.ts.map +0 -1
- package/lib/codegen/generated-at.js +0 -78
- package/lib/codegen/generated-at.js.map +0 -1
- package/lib/codegen/generator.d.ts +0 -353
- package/lib/codegen/generator.d.ts.map +0 -1
- package/lib/codegen/generator.js +0 -810
- package/lib/codegen/generator.js.map +0 -1
- package/lib/codegen/graph.d.ts +0 -36
- package/lib/codegen/graph.d.ts.map +0 -1
- package/lib/codegen/graph.js +0 -136
- package/lib/codegen/graph.js.map +0 -1
- package/lib/codegen/graphql-client.d.ts +0 -70
- package/lib/codegen/graphql-client.d.ts.map +0 -1
- package/lib/codegen/graphql-client.js +0 -439
- package/lib/codegen/graphql-client.js.map +0 -1
- package/lib/codegen/graphql.d.ts +0 -207
- package/lib/codegen/graphql.d.ts.map +0 -1
- package/lib/codegen/graphql.js +0 -786
- package/lib/codegen/graphql.js.map +0 -1
- package/lib/codegen/latin1.d.ts +0 -3
- package/lib/codegen/latin1.d.ts.map +0 -1
- package/lib/codegen/latin1.js +0 -126
- package/lib/codegen/latin1.js.map +0 -1
- package/lib/codegen/members.d.ts +0 -32
- package/lib/codegen/members.d.ts.map +0 -1
- package/lib/codegen/members.js +0 -62
- package/lib/codegen/members.js.map +0 -1
- package/lib/codegen/model-diff.d.ts +0 -10
- package/lib/codegen/model-diff.d.ts.map +0 -1
- package/lib/codegen/model-diff.js +0 -67
- package/lib/codegen/model-diff.js.map +0 -1
- package/lib/codegen/naming.d.ts +0 -29
- package/lib/codegen/naming.d.ts.map +0 -1
- package/lib/codegen/naming.js +0 -74
- package/lib/codegen/naming.js.map +0 -1
- package/lib/codegen/openapi-cli.d.ts +0 -52
- package/lib/codegen/openapi-cli.d.ts.map +0 -1
- package/lib/codegen/openapi-cli.js +0 -84
- package/lib/codegen/openapi-cli.js.map +0 -1
- package/lib/codegen/openapi.d.ts +0 -209
- package/lib/codegen/openapi.d.ts.map +0 -1
- package/lib/codegen/openapi.js +0 -1548
- package/lib/codegen/openapi.js.map +0 -1
- package/lib/codegen/operations.d.ts +0 -24
- package/lib/codegen/operations.d.ts.map +0 -1
- package/lib/codegen/operations.js +0 -56
- package/lib/codegen/operations.js.map +0 -1
- package/lib/codegen/pagination.d.ts +0 -39
- package/lib/codegen/pagination.d.ts.map +0 -1
- package/lib/codegen/pagination.js +0 -31
- package/lib/codegen/pagination.js.map +0 -1
- package/lib/codegen/patch-audit.d.ts +0 -84
- package/lib/codegen/patch-audit.d.ts.map +0 -1
- package/lib/codegen/patch-audit.js +0 -366
- package/lib/codegen/patch-audit.js.map +0 -1
- package/lib/codegen/patches.d.ts +0 -129
- package/lib/codegen/patches.d.ts.map +0 -1
- package/lib/codegen/patches.js +0 -472
- package/lib/codegen/patches.js.map +0 -1
- package/lib/codegen/prelude.d.ts +0 -15
- package/lib/codegen/prelude.d.ts.map +0 -1
- package/lib/codegen/prelude.js +0 -60
- package/lib/codegen/prelude.js.map +0 -1
- package/lib/codegen/privatize.d.ts +0 -21
- package/lib/codegen/privatize.d.ts.map +0 -1
- package/lib/codegen/privatize.js +0 -176
- package/lib/codegen/privatize.js.map +0 -1
- package/lib/codegen/proto.d.ts +0 -121
- package/lib/codegen/proto.d.ts.map +0 -1
- package/lib/codegen/proto.js +0 -960
- package/lib/codegen/proto.js.map +0 -1
- package/lib/codegen/pure.d.ts +0 -6
- package/lib/codegen/pure.d.ts.map +0 -1
- package/lib/codegen/pure.js +0 -91
- package/lib/codegen/pure.js.map +0 -1
- package/lib/codegen/rewrite-operation-ids.d.ts +0 -154
- package/lib/codegen/rewrite-operation-ids.d.ts.map +0 -1
- package/lib/codegen/rewrite-operation-ids.js +0 -1117
- package/lib/codegen/rewrite-operation-ids.js.map +0 -1
- package/lib/codegen/spec-path.d.ts +0 -16
- package/lib/codegen/spec-path.d.ts.map +0 -1
- package/lib/codegen/spec-path.js +0 -101
- package/lib/codegen/spec-path.js.map +0 -1
- package/lib/codegen/table.d.ts +0 -5
- package/lib/codegen/table.d.ts.map +0 -1
- package/lib/codegen/table.js +0 -249
- package/lib/codegen/table.js.map +0 -1
- package/lib/config.js.map +0 -1
- package/lib/crypto.js.map +0 -1
- package/lib/debug.js.map +0 -1
- package/lib/error-category.js.map +0 -1
- package/lib/errors.js.map +0 -1
- package/lib/graphql.js.map +0 -1
- package/lib/graphql.types.js.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/json-patch.d.ts +0 -58
- package/lib/json-patch.d.ts.map +0 -1
- package/lib/json-patch.js +0 -227
- package/lib/json-patch.js.map +0 -1
- package/lib/pagination.js.map +0 -1
- package/lib/protocol-http.js.map +0 -1
- package/lib/protocol-rest.js.map +0 -1
- package/lib/query.js.map +0 -1
- package/lib/response-validation-strict.js.map +0 -1
- package/lib/response-validation.js.map +0 -1
- package/lib/retry-after.js.map +0 -1
- package/lib/retry.js.map +0 -1
- package/lib/schema-lite-impl.js.map +0 -1
- package/lib/schema-lite-typed.js.map +0 -1
- package/lib/schema-lite.js.map +0 -1
- package/lib/schema.js.map +0 -1
- package/lib/testing.d.ts +0 -40
- package/lib/testing.d.ts.map +0 -1
- package/lib/testing.js +0 -42
- package/lib/testing.js.map +0 -1
- package/lib/trait.js.map +0 -1
- package/lib/xml.js.map +0 -1
- package/src/codegen/boolean-string-enums.ts +0 -155
- package/src/codegen/chunk.ts +0 -147
- package/src/codegen/cli.ts +0 -293
- package/src/codegen/datafy.ts +0 -874
- package/src/codegen/dedupe.ts +0 -173
- package/src/codegen/emit.ts +0 -200
- package/src/codegen/format.ts +0 -49
- package/src/codegen/generated-at.ts +0 -88
- package/src/codegen/generator.ts +0 -1229
- package/src/codegen/graph.ts +0 -151
- package/src/codegen/graphql-client.ts +0 -545
- package/src/codegen/graphql.ts +0 -1145
- package/src/codegen/latin1.ts +0 -131
- package/src/codegen/members.ts +0 -79
- package/src/codegen/model-diff.ts +0 -67
- package/src/codegen/naming.ts +0 -85
- package/src/codegen/openapi-cli.ts +0 -141
- package/src/codegen/openapi.ts +0 -1845
- package/src/codegen/operations.ts +0 -73
- package/src/codegen/pagination.ts +0 -64
- package/src/codegen/patch-audit.ts +0 -480
- package/src/codegen/patches.ts +0 -581
- package/src/codegen/prelude.ts +0 -70
- package/src/codegen/privatize.ts +0 -200
- package/src/codegen/proto.ts +0 -1092
- package/src/codegen/pure.ts +0 -94
- package/src/codegen/rewrite-operation-ids.ts +0 -1219
- package/src/codegen/spec-path.ts +0 -112
- package/src/codegen/table.ts +0 -254
- package/src/json-patch.ts +0 -273
- package/src/testing.ts +0 -74
package/src/codegen/datafy.ts
DELETED
|
@@ -1,874 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Turn a tabled service module into data-described operations (dev-time
|
|
3
|
-
* only; runs after `tableSchemas`; runtime: the "Data operations" region of
|
|
4
|
-
* `@distilled.cloud/core/api`).
|
|
5
|
-
*
|
|
6
|
-
* export const getFile: API.OperationMethod<...> = API.make(() => ({ input: __S(4, __c0, 4), ... }));
|
|
7
|
-
* function __c0(j: number): any { switch (j) { case 4: return S.Struct({ ... }); } }
|
|
8
|
-
* becomes
|
|
9
|
-
* export const getFile: API.OperationMethod<...> = API.op((i: any): any =>
|
|
10
|
-
* i === API.D ? ['{input:#1,...};$3({...})', [__0, __4, ...]] : API.call(getFile, i));
|
|
11
|
-
* function __d0(): any { return ['...', [__0, ...]]; }
|
|
12
|
-
* const __0 = __L.at, __4 = S.Struct, ...;
|
|
13
|
-
*
|
|
14
|
-
* Each schema reached by one operation only moves into that operation's
|
|
15
|
-
* arrow. Schemas reached by several roots (operations, error classes, other
|
|
16
|
-
* module-level code) move into shared holders grouped by the exact set of
|
|
17
|
-
* roots that reach them, so a bundle keeps a holder only when it needs all
|
|
18
|
-
* of it. Unless the caller is about to bundle (and rename imports anyway),
|
|
19
|
-
* schema-library and trait functions get short module-level aliases
|
|
20
|
-
* (`__4 = S.Struct`) so holders list them cheaply and a bundler still drops
|
|
21
|
-
* the unused ones. Thunk bodies (`S.suspend(() => ...)`) become entries of
|
|
22
|
-
* their own. Expressions are encoded in the grammar documented in core/api.
|
|
23
|
-
*
|
|
24
|
-
* Every function a module defines costs heap and an object at import, and
|
|
25
|
-
* its text stays in the heap as module source, so:
|
|
26
|
-
* - a module constant only data reads (`const svc = T.AwsApiService(...)`,
|
|
27
|
-
* the endpoint rules) moves, as written, into the refs of the holder of
|
|
28
|
-
* the roots that reach it, and is built on first use;
|
|
29
|
-
* - a constant expression repeated across holders (the service trait pipe
|
|
30
|
-
* of every input, a base URL) becomes one value entry, `~R:N`, in the
|
|
31
|
-
* holder of the roots that reach it (see `hoistConstants`);
|
|
32
|
-
* - an operation whose name recurs in its strings writes it once, as a
|
|
33
|
-
* stem (`API.named("GetThing", '..."%Request"...', refs)`).
|
|
34
|
-
*
|
|
35
|
-
* Error classes become data too: their `extends` expression is entry 0 of a
|
|
36
|
-
* function that stands in for the class until first use (`API.error`):
|
|
37
|
-
* export class Oops extends S.TaggedError<Oops>()("Oops", { ... }) {}
|
|
38
|
-
* becomes
|
|
39
|
-
* export const Oops = API.error(function Oops(i) {
|
|
40
|
-
* return API.newError(i, new.target, ['$1()("Oops",{...})', [...]]);
|
|
41
|
-
* });
|
|
42
|
-
*/
|
|
43
|
-
import { parseAst } from "rolldown/parseAst";
|
|
44
|
-
|
|
45
|
-
type Node = { readonly type: string; readonly start: number; readonly end: number } & Record<
|
|
46
|
-
string,
|
|
47
|
-
any
|
|
48
|
-
>;
|
|
49
|
-
|
|
50
|
-
const isNode = (v: unknown): v is Node =>
|
|
51
|
-
v !== null && typeof v === "object" && typeof (v as Node).type === "string";
|
|
52
|
-
|
|
53
|
-
const strip = (n: Node): Node => {
|
|
54
|
-
while (
|
|
55
|
-
n.type === "TSAsExpression" ||
|
|
56
|
-
n.type === "TSSatisfiesExpression" ||
|
|
57
|
-
n.type === "TSNonNullExpression" ||
|
|
58
|
-
n.type === "ParenthesizedExpression"
|
|
59
|
-
)
|
|
60
|
-
n = n.expression;
|
|
61
|
-
return n;
|
|
62
|
-
};
|
|
63
|
-
|
|
64
|
-
/** `__S(i, __cK, j)` or `__L.at(__cK, j)` (consts the table pass kept) -> `K:j`, or undefined. */
|
|
65
|
-
const tableRef = (n: Node): string | undefined => {
|
|
66
|
-
if (n.type !== "CallExpression") return undefined;
|
|
67
|
-
const c = n.callee;
|
|
68
|
-
const table = c.type === "Identifier" && c.name === "__S";
|
|
69
|
-
const at = c.type === "MemberExpression" && c.object.name === "__L" && c.property.name === "at";
|
|
70
|
-
if (!table && !at) return undefined;
|
|
71
|
-
const [f, j] = (n.arguments as Node[]).slice(table ? 1 : 0);
|
|
72
|
-
const m = /^__c(\d+)$/.exec(f!.name ?? "");
|
|
73
|
-
if (!m || j!.type !== "Literal") throw new Error("datafy: unexpected __S call");
|
|
74
|
-
return `${m[1]}:${j!.value}`;
|
|
75
|
-
};
|
|
76
|
-
|
|
77
|
-
const walk = (n: unknown, visit: (n: Node) => boolean): void => {
|
|
78
|
-
if (Array.isArray(n)) {
|
|
79
|
-
for (const c of n) walk(c, visit);
|
|
80
|
-
return;
|
|
81
|
-
}
|
|
82
|
-
if (!isNode(n) || !visit(n)) return;
|
|
83
|
-
for (const [key, v] of Object.entries(n))
|
|
84
|
-
if (key !== "type" && v !== null && typeof v === "object") walk(v, visit);
|
|
85
|
-
};
|
|
86
|
-
|
|
87
|
-
const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
88
|
-
|
|
89
|
-
/** Whether `encode` (below) accepts an expression: the grammar's subset of JS. */
|
|
90
|
-
const encodable = (n: Node): boolean => {
|
|
91
|
-
n = strip(n);
|
|
92
|
-
if (tableRef(n)) return true;
|
|
93
|
-
switch (n.type) {
|
|
94
|
-
case "Literal": {
|
|
95
|
-
const v = n.value;
|
|
96
|
-
return (
|
|
97
|
-
typeof v === "string" ||
|
|
98
|
-
typeof v === "boolean" ||
|
|
99
|
-
(typeof v === "number" && Number.isFinite(v)) ||
|
|
100
|
-
(v === null && !n.regex && !n.bigint)
|
|
101
|
-
);
|
|
102
|
-
}
|
|
103
|
-
case "TemplateLiteral":
|
|
104
|
-
return !n.expressions.length;
|
|
105
|
-
case "UnaryExpression":
|
|
106
|
-
return (
|
|
107
|
-
n.operator === "void" ||
|
|
108
|
-
(n.operator === "-" &&
|
|
109
|
-
n.argument.type === "Literal" &&
|
|
110
|
-
typeof n.argument.value === "number")
|
|
111
|
-
);
|
|
112
|
-
case "Identifier":
|
|
113
|
-
return true;
|
|
114
|
-
case "MemberExpression":
|
|
115
|
-
return !n.computed && encodable(n.object);
|
|
116
|
-
case "CallExpression":
|
|
117
|
-
return (
|
|
118
|
-
encodable(n.callee) &&
|
|
119
|
-
(n.arguments as Node[]).every((a) => a.type !== "SpreadElement" && encodable(a))
|
|
120
|
-
);
|
|
121
|
-
case "ObjectExpression":
|
|
122
|
-
return (n.properties as Node[]).every(
|
|
123
|
-
(p) =>
|
|
124
|
-
p.type === "Property" &&
|
|
125
|
-
p.kind === "init" &&
|
|
126
|
-
!p.method &&
|
|
127
|
-
((!p.computed && p.key.type === "Identifier") || p.key.type === "Literal") &&
|
|
128
|
-
encodable(p.value),
|
|
129
|
-
);
|
|
130
|
-
case "ArrayExpression":
|
|
131
|
-
return (n.elements as Array<Node | null>).every(
|
|
132
|
-
(e) => !!e && e.type !== "SpreadElement" && encodable(e),
|
|
133
|
-
);
|
|
134
|
-
case "ArrowFunctionExpression":
|
|
135
|
-
return !n.params.length && n.body.type !== "BlockStatement" && encodable(n.body);
|
|
136
|
-
default:
|
|
137
|
-
return false;
|
|
138
|
-
}
|
|
139
|
-
};
|
|
140
|
-
|
|
141
|
-
/**
|
|
142
|
-
* A JSON string with every non-ASCII character, `;` (the entry separator)
|
|
143
|
-
* and `%` (a holder's stem) escaped: the module source must stay one-byte.
|
|
144
|
-
*/
|
|
145
|
-
const quote = (s: string): string =>
|
|
146
|
-
JSON.stringify(s).replace(
|
|
147
|
-
/[^\x00-\x24\x26-\x3a\x3c-\x7f]/g,
|
|
148
|
-
(c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`,
|
|
149
|
-
);
|
|
150
|
-
|
|
151
|
-
/** Values that get a short module-level alias: namespace members of these imports. */
|
|
152
|
-
const VOCAB = /^(?:S|T|__L)\.[A-Za-z_$][\w$]*$/;
|
|
153
|
-
|
|
154
|
-
/** A data holder being written: its entries and the values they name. */
|
|
155
|
-
class Holder {
|
|
156
|
-
readonly entries: string[] = [];
|
|
157
|
-
readonly refs: string[] = ["__0"];
|
|
158
|
-
readonly refIndex = new Map<string, number>([["__0", 0]]);
|
|
159
|
-
/** node key -> entry index in this holder */
|
|
160
|
-
readonly local = new Map<string, number>();
|
|
161
|
-
readonly name: string;
|
|
162
|
-
/** Written once at the start of the data, `%` in its strings (see `stemOf`). */
|
|
163
|
-
stem?: string;
|
|
164
|
-
constructor(name: string) {
|
|
165
|
-
this.name = name;
|
|
166
|
-
}
|
|
167
|
-
ref(text: string): number {
|
|
168
|
-
let i = this.refIndex.get(text);
|
|
169
|
-
if (i === undefined) {
|
|
170
|
-
i = this.refs.length;
|
|
171
|
-
this.refs.push(text);
|
|
172
|
-
this.refIndex.set(text, i);
|
|
173
|
-
}
|
|
174
|
-
return i;
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
/** `x.annotate({ identifier: "X" })` -> `"X"` (encoded `x@"X"`), else undefined. */
|
|
179
|
-
const identifierOf = (n: Node): string | undefined => {
|
|
180
|
-
const callee = strip(n.callee);
|
|
181
|
-
const [arg] = n.arguments as Node[];
|
|
182
|
-
const props = arg?.type === "ObjectExpression" ? (arg.properties as Node[]) : [];
|
|
183
|
-
const p = props[0];
|
|
184
|
-
return callee.property.name === "annotate" &&
|
|
185
|
-
n.arguments.length === 1 &&
|
|
186
|
-
props.length === 1 &&
|
|
187
|
-
p!.type === "Property" &&
|
|
188
|
-
!p!.computed &&
|
|
189
|
-
p!.key.name === "identifier" &&
|
|
190
|
-
p!.value.type === "Literal" &&
|
|
191
|
-
typeof p!.value.value === "string"
|
|
192
|
-
? p!.value.value
|
|
193
|
-
: undefined;
|
|
194
|
-
};
|
|
195
|
-
|
|
196
|
-
/**
|
|
197
|
-
* The encoded form of an expression with every value named by identifier
|
|
198
|
-
* (`$S.Struct`, `$svc`), and its estimated encoded length; undefined when
|
|
199
|
-
* the expression names a schema entry or holds a thunk (it is not
|
|
200
|
-
* constant). `onNode` sees every expression `encode` visits, children first.
|
|
201
|
-
*/
|
|
202
|
-
const canon = (
|
|
203
|
-
n: Node,
|
|
204
|
-
isNamespace: (n: Node) => boolean,
|
|
205
|
-
onNode?: (n: Node, up: Node | undefined, key: string | undefined, len: number) => void,
|
|
206
|
-
up?: Node,
|
|
207
|
-
): [string, number] | undefined => {
|
|
208
|
-
n = strip(n);
|
|
209
|
-
const go = (x: Node) => canon(x, isNamespace, onNode, n);
|
|
210
|
-
const all = (xs: Node[]) => {
|
|
211
|
-
const parts = xs.map(go);
|
|
212
|
-
return parts.every((p) => p) ? (parts as Array<[string, number]>) : undefined;
|
|
213
|
-
};
|
|
214
|
-
const join = (ps: Array<[string, number]>) => ps.map((p) => p[0]).join(",");
|
|
215
|
-
const width = (ps: Array<[string, number]>) => ps.reduce((a, p) => a + p[1] + 1, 0);
|
|
216
|
-
let out: [string, number] | undefined;
|
|
217
|
-
if (tableRef(n)) out = undefined;
|
|
218
|
-
else
|
|
219
|
-
switch (n.type) {
|
|
220
|
-
case "Literal":
|
|
221
|
-
case "TemplateLiteral":
|
|
222
|
-
case "UnaryExpression": {
|
|
223
|
-
const v =
|
|
224
|
-
n.type === "TemplateLiteral"
|
|
225
|
-
? n.expressions.length
|
|
226
|
-
? undefined
|
|
227
|
-
: quote(n.quasis[0].value.cooked)
|
|
228
|
-
: n.type === "UnaryExpression"
|
|
229
|
-
? n.operator === "void"
|
|
230
|
-
? "u"
|
|
231
|
-
: `-${n.argument.value}`
|
|
232
|
-
: typeof n.value === "string"
|
|
233
|
-
? quote(n.value)
|
|
234
|
-
: String(n.value);
|
|
235
|
-
out = v === undefined ? undefined : [v, v.length];
|
|
236
|
-
break;
|
|
237
|
-
}
|
|
238
|
-
case "Identifier":
|
|
239
|
-
out = n.name === "undefined" ? ["u", 1] : [`$${n.name}`, 3];
|
|
240
|
-
break;
|
|
241
|
-
case "MemberExpression": {
|
|
242
|
-
const obj = strip(n.object);
|
|
243
|
-
if (isNamespace(obj)) out = [`$${obj.name}.${n.property.name}`, 3];
|
|
244
|
-
else {
|
|
245
|
-
const o = go(obj);
|
|
246
|
-
out = o && [`${o[0]}.${n.property.name}`, o[1] + 1 + n.property.name.length];
|
|
247
|
-
}
|
|
248
|
-
break;
|
|
249
|
-
}
|
|
250
|
-
case "CallExpression": {
|
|
251
|
-
const callee = strip(n.callee);
|
|
252
|
-
if (callee.type === "MemberExpression" && !isNamespace(strip(callee.object))) {
|
|
253
|
-
const o = go(callee.object);
|
|
254
|
-
const name = callee.property.name as string;
|
|
255
|
-
const id = identifierOf(n);
|
|
256
|
-
if (id !== undefined) out = o && [`${o[0]}@${quote(id)}`, o[1] + 3 + id.length];
|
|
257
|
-
else {
|
|
258
|
-
const args = all(n.arguments as Node[]);
|
|
259
|
-
out = o &&
|
|
260
|
-
args && [`${o[0]}.${name}(${join(args)})`, o[1] + name.length + 2 + width(args)];
|
|
261
|
-
}
|
|
262
|
-
} else {
|
|
263
|
-
const args = all(n.arguments as Node[]);
|
|
264
|
-
const c = go(callee);
|
|
265
|
-
out = c && args && [`${c[0]}(${join(args)})`, c[1] + 1 + width(args)];
|
|
266
|
-
}
|
|
267
|
-
break;
|
|
268
|
-
}
|
|
269
|
-
case "ObjectExpression": {
|
|
270
|
-
const props = n.properties as Node[];
|
|
271
|
-
const vals = all(props.map((p) => p.value));
|
|
272
|
-
out = vals && [
|
|
273
|
-
`{${props.map((p, i) => `${quote(String(p.key.name ?? p.key.value))}:${vals[i]![0]}`).join(",")}}`,
|
|
274
|
-
props.reduce(
|
|
275
|
-
(a, p, i) => a + String(p.key.name ?? p.key.value).length + 2 + vals[i]![1],
|
|
276
|
-
1,
|
|
277
|
-
),
|
|
278
|
-
];
|
|
279
|
-
break;
|
|
280
|
-
}
|
|
281
|
-
case "ArrayExpression": {
|
|
282
|
-
const els = all(n.elements as Node[]);
|
|
283
|
-
out = els && [`[${join(els)}]`, width(els) + 1];
|
|
284
|
-
break;
|
|
285
|
-
}
|
|
286
|
-
case "ArrowFunctionExpression":
|
|
287
|
-
go(n.body);
|
|
288
|
-
out = undefined;
|
|
289
|
-
break;
|
|
290
|
-
default:
|
|
291
|
-
out = undefined;
|
|
292
|
-
}
|
|
293
|
-
onNode?.(n, up, out?.[0], out?.[1] ?? 0);
|
|
294
|
-
return out;
|
|
295
|
-
};
|
|
296
|
-
|
|
297
|
-
/** An operation's config; a paginated operation's `strategy` argument becomes a member. */
|
|
298
|
-
const configOf = (o: { name: string; config: Node; strategy?: Node }): Node => {
|
|
299
|
-
if (!o.strategy) return o.config;
|
|
300
|
-
const c = strip(o.config);
|
|
301
|
-
if (c.type !== "ObjectExpression") throw new Error(`datafy: ${o.name} config is not an object`);
|
|
302
|
-
const key = { type: "Identifier", start: 0, end: 0, name: "strategy" };
|
|
303
|
-
const member = {
|
|
304
|
-
type: "Property",
|
|
305
|
-
start: 0,
|
|
306
|
-
end: 0,
|
|
307
|
-
kind: "init",
|
|
308
|
-
method: false,
|
|
309
|
-
computed: false,
|
|
310
|
-
key,
|
|
311
|
-
value: o.strategy,
|
|
312
|
-
};
|
|
313
|
-
return { ...c, properties: [...c.properties, member] };
|
|
314
|
-
};
|
|
315
|
-
|
|
316
|
-
/** A constant expression evaluated once per holder and shared by every place that named it. */
|
|
317
|
-
interface Value {
|
|
318
|
-
readonly nodes: Node[];
|
|
319
|
-
readonly holder: Holder;
|
|
320
|
-
j: number;
|
|
321
|
-
/** A module constant moved as written: the code of its initializer, a ref of the holder. */
|
|
322
|
-
readonly code?: string;
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
/** Longest function (source characters) a moved module constant may hold. */
|
|
326
|
-
const MAX_MOVED_FUNCTION = 4000;
|
|
327
|
-
|
|
328
|
-
/** Shortest constant (encoded characters) worth a value entry. */
|
|
329
|
-
const MIN_LEN = 16;
|
|
330
|
-
/** Smallest saving (source characters) worth a value entry: each costs a bundle some indirection. */
|
|
331
|
-
const MIN_SAVING = 64;
|
|
332
|
-
/**
|
|
333
|
-
* What a new holder must save first: about 300 characters of heap, plus the
|
|
334
|
-
* function wrapper every bundle that keeps it pays.
|
|
335
|
-
*/
|
|
336
|
-
const NEW_HOLDER_COST = 3000;
|
|
337
|
-
|
|
338
|
-
/**
|
|
339
|
-
* Common constant expressions (calls and longer strings that name no schema
|
|
340
|
-
* entry) found in more than one place move into value entries: the
|
|
341
|
-
* service trait pipe of every input, base URLs, ... Each lands in the holder of exactly the roots that reach it,
|
|
342
|
-
* so a bundle still keeps only data its operations need. Biggest savings
|
|
343
|
-
* first; a nested expression only counts where its container stays.
|
|
344
|
-
*/
|
|
345
|
-
const hoistConstants = (
|
|
346
|
-
roots: ReadonlyArray<[Node, Holder]>,
|
|
347
|
-
isNamespace: (n: Node) => boolean,
|
|
348
|
-
holderOf: (key: string, create: boolean) => Holder | undefined,
|
|
349
|
-
rootsOf: Map<Holder, string>,
|
|
350
|
-
pinned: ReadonlyMap<string, string>,
|
|
351
|
-
): Value[] => {
|
|
352
|
-
const pinnedUses = new Map<string, Node[]>();
|
|
353
|
-
const parent = new Map<Node, Node>();
|
|
354
|
-
const container = new Map<Node, Holder>();
|
|
355
|
-
const byKey = new Map<string, { len: number; nodes: Node[] }>();
|
|
356
|
-
for (const [root, h] of roots) {
|
|
357
|
-
container.set(strip(root), h);
|
|
358
|
-
canon(root, isNamespace, (n, up, key, len) => {
|
|
359
|
-
if (up) parent.set(n, up);
|
|
360
|
-
if (n.type === "Identifier" && pinned.has(n.name)) {
|
|
361
|
-
let uses = pinnedUses.get(n.name);
|
|
362
|
-
if (!uses) pinnedUses.set(n.name, (uses = []));
|
|
363
|
-
uses.push(n);
|
|
364
|
-
}
|
|
365
|
-
if (key === undefined) return;
|
|
366
|
-
const candidate =
|
|
367
|
-
(len >= MIN_LEN && n.type === "CallExpression" && n.arguments.length > 0) ||
|
|
368
|
-
((n.type === "Literal" || n.type === "TemplateLiteral") && len >= MIN_LEN);
|
|
369
|
-
if (!candidate) return;
|
|
370
|
-
let c = byKey.get(key);
|
|
371
|
-
if (!c) byKey.set(key, (c = { len, nodes: [] }));
|
|
372
|
-
c.nodes.push(n);
|
|
373
|
-
});
|
|
374
|
-
}
|
|
375
|
-
const valueOf = new Map<Node, Value>();
|
|
376
|
-
const liveIn = (n: Node): Holder | undefined => {
|
|
377
|
-
for (let x = n; ;) {
|
|
378
|
-
const p = parent.get(x);
|
|
379
|
-
if (!p) return container.get(x);
|
|
380
|
-
const v = valueOf.get(p);
|
|
381
|
-
if (v) return v.nodes[0] === p ? v.holder : undefined;
|
|
382
|
-
x = p;
|
|
383
|
-
}
|
|
384
|
-
};
|
|
385
|
-
const keyOf = (holders: Iterable<Holder>) => {
|
|
386
|
-
const rs = new Set<number>();
|
|
387
|
-
for (const h of holders) for (const r of rootsOf.get(h)!.split(",")) rs.add(+r);
|
|
388
|
-
return [...rs].sort((a, b) => a - b).join(",");
|
|
389
|
-
};
|
|
390
|
-
// Each moved constant was at least one object at import; the holder it moves to may be new.
|
|
391
|
-
let newHolders = Math.max(0, pinned.size - 1);
|
|
392
|
-
const values: Value[] = [];
|
|
393
|
-
const candidates = [...byKey.values()]
|
|
394
|
-
.filter((c) => c.nodes.length > 1)
|
|
395
|
-
.sort((a, b) => (b.nodes.length - 1) * b.len - (a.nodes.length - 1) * a.len);
|
|
396
|
-
for (const c of candidates) {
|
|
397
|
-
const live: Array<[Node, Holder]> = [];
|
|
398
|
-
for (const n of c.nodes) {
|
|
399
|
-
const h = liveIn(n);
|
|
400
|
-
if (h) live.push([n, h]);
|
|
401
|
-
}
|
|
402
|
-
if (live.length < 2) continue;
|
|
403
|
-
const key = keyOf(live.map(([, h]) => h));
|
|
404
|
-
const existing = holderOf(key, false);
|
|
405
|
-
// A new holder is one more function at import: only as many as moved constants free.
|
|
406
|
-
if (!existing && !newHolders) continue;
|
|
407
|
-
let cost = c.len + (existing ? 0 : NEW_HOLDER_COST);
|
|
408
|
-
const users = new Set<Holder>();
|
|
409
|
-
for (const [, h] of live) {
|
|
410
|
-
cost += h === existing ? 3 : 6;
|
|
411
|
-
users.add(h);
|
|
412
|
-
}
|
|
413
|
-
cost += 6 * [...users].filter((h) => h !== existing).length;
|
|
414
|
-
if (live.length * c.len - cost < MIN_SAVING) continue;
|
|
415
|
-
if (!existing) newHolders--;
|
|
416
|
-
const holder = existing ?? holderOf(key, true)!;
|
|
417
|
-
rootsOf.set(holder, key);
|
|
418
|
-
const v: Value = { nodes: live.map(([n]) => n), holder, j: -1 };
|
|
419
|
-
for (const n of v.nodes) valueOf.set(n, v);
|
|
420
|
-
values.push(v);
|
|
421
|
-
}
|
|
422
|
-
for (const [name, code] of pinned) {
|
|
423
|
-
const live: Array<[Node, Holder]> = [];
|
|
424
|
-
for (const n of pinnedUses.get(name) ?? []) {
|
|
425
|
-
const h = liveIn(n);
|
|
426
|
-
if (h) live.push([n, h]);
|
|
427
|
-
}
|
|
428
|
-
if (!live.length) throw new Error(`datafy: constant ${name} has no live reader`);
|
|
429
|
-
const key = keyOf(live.map(([, h]) => h));
|
|
430
|
-
const holder = holderOf(key, true)!;
|
|
431
|
-
rootsOf.set(holder, key);
|
|
432
|
-
values.push({ nodes: live.map(([n]) => n), holder, j: -1, code });
|
|
433
|
-
}
|
|
434
|
-
return values;
|
|
435
|
-
};
|
|
436
|
-
|
|
437
|
-
const STRING = /"(?:[^"\\]|\\.)*"/g;
|
|
438
|
-
const STEM = /^[\w.-]{4,}$/;
|
|
439
|
-
|
|
440
|
-
/**
|
|
441
|
-
* An operation's name recurs in its strings (`"GetThing"`, `"GetThingRequest"`,
|
|
442
|
-
* `"GetThingOutput"`): the string that saves most when written once as the
|
|
443
|
-
* holder's stem and as `%` everywhere else becomes the stem.
|
|
444
|
-
*/
|
|
445
|
-
const stemOf = (h: Holder): void => {
|
|
446
|
-
const strings = h.entries.flatMap((e) => e.match(STRING) ?? []).map((t) => t.slice(1, -1));
|
|
447
|
-
let best = 0;
|
|
448
|
-
for (const c of new Set(strings)) {
|
|
449
|
-
if (!STEM.test(c)) continue;
|
|
450
|
-
let uses = 0;
|
|
451
|
-
for (const t of strings) uses += t.split(c).length - 1;
|
|
452
|
-
const saving = uses * (c.length - 1) - (c.length + 4);
|
|
453
|
-
if (saving > best) [best, h.stem] = [saving, c];
|
|
454
|
-
}
|
|
455
|
-
const stem = h.stem;
|
|
456
|
-
if (stem)
|
|
457
|
-
for (let j = 0; j < h.entries.length; j++)
|
|
458
|
-
h.entries[j] = h.entries[j]!.replace(STRING, (t) => t.split(stem).join("%"));
|
|
459
|
-
};
|
|
460
|
-
|
|
461
|
-
export const datafyOperations = (
|
|
462
|
-
code: string,
|
|
463
|
-
filename = "generated.ts",
|
|
464
|
-
/**
|
|
465
|
-
* Short module-level aliases for namespace members (`const __4 = S.Struct`).
|
|
466
|
-
* A bundler that is about to rename imports anyway does not need them.
|
|
467
|
-
*/
|
|
468
|
-
{ aliases: aliased = true }: { aliases?: boolean } = {},
|
|
469
|
-
): { code: string; operations: number; holders: number; errors: number } => {
|
|
470
|
-
if (!/\bfunction __S\(/.test(code)) return { code, operations: 0, holders: 0, errors: 0 };
|
|
471
|
-
const program = parseAst(code, { sourceType: "module", lang: "ts" }, filename);
|
|
472
|
-
const body = program.body as unknown as Node[];
|
|
473
|
-
const text = (n: Node) => code.slice(n.start, n.end);
|
|
474
|
-
// `import * as X`: `X.y` is a plain value; any other receiver keeps `this` in calls.
|
|
475
|
-
const namespaces = new Set<string>();
|
|
476
|
-
for (const st of body)
|
|
477
|
-
if (st.type === "ImportDeclaration" && st.importKind !== "type")
|
|
478
|
-
for (const sp of st.specifiers as Node[])
|
|
479
|
-
if (sp.type === "ImportNamespaceSpecifier") namespaces.add(sp.local.name);
|
|
480
|
-
const isNamespace = (n: Node) => n.type === "Identifier" && namespaces.has(n.name);
|
|
481
|
-
// Emitted JS (lib/) gets no type annotations.
|
|
482
|
-
const ts = !filename.endsWith(".js");
|
|
483
|
-
const any = ts ? ": any" : "";
|
|
484
|
-
|
|
485
|
-
// Graph nodes: schemas (`K:j`, from the builders).
|
|
486
|
-
const nodes = new Map<string, Node>();
|
|
487
|
-
const removals: Node[] = [];
|
|
488
|
-
// A root: an operation (`init` is its `API.make(...)` call) or an error
|
|
489
|
-
// class (`init` is its whole statement, `config` its `extends` expression).
|
|
490
|
-
type Op = {
|
|
491
|
-
name: string;
|
|
492
|
-
init: Node;
|
|
493
|
-
paginated: boolean;
|
|
494
|
-
config: Node;
|
|
495
|
-
strategy?: Node;
|
|
496
|
-
error?: { exported: boolean };
|
|
497
|
-
};
|
|
498
|
-
const ops: Op[] = [];
|
|
499
|
-
const errors: Op[] = [];
|
|
500
|
-
const rest: Node[] = [];
|
|
501
|
-
for (const st of body) {
|
|
502
|
-
const cls = st.type === "ExportNamedDeclaration" ? st.declaration : st;
|
|
503
|
-
if (
|
|
504
|
-
cls?.type === "ClassDeclaration" &&
|
|
505
|
-
cls.id &&
|
|
506
|
-
cls.superClass &&
|
|
507
|
-
!cls.body.body.length &&
|
|
508
|
-
!cls.decorators?.length &&
|
|
509
|
-
encodable(cls.superClass)
|
|
510
|
-
) {
|
|
511
|
-
errors.push({
|
|
512
|
-
name: cls.id.name,
|
|
513
|
-
init: st,
|
|
514
|
-
paginated: false,
|
|
515
|
-
config: cls.superClass,
|
|
516
|
-
error: { exported: st !== cls },
|
|
517
|
-
});
|
|
518
|
-
continue;
|
|
519
|
-
}
|
|
520
|
-
if (st.type === "FunctionDeclaration" && /^__c\d+$/.test(st.id?.name ?? "")) {
|
|
521
|
-
const k = st.id.name.slice(3);
|
|
522
|
-
const sw = st.body.body[0] as Node;
|
|
523
|
-
if (sw?.type !== "SwitchStatement") throw new Error(`datafy: ${st.id.name} is not a switch`);
|
|
524
|
-
for (const c of sw.cases as Node[]) {
|
|
525
|
-
const ret = c.consequent[0] as Node;
|
|
526
|
-
if (ret?.type !== "ReturnStatement") throw new Error("datafy: case without return");
|
|
527
|
-
nodes.set(`${k}:${c.test.value}`, ret.argument);
|
|
528
|
-
}
|
|
529
|
-
removals.push(st);
|
|
530
|
-
continue;
|
|
531
|
-
}
|
|
532
|
-
if (st.type === "FunctionDeclaration" && st.id?.name === "__S") {
|
|
533
|
-
removals.push(st);
|
|
534
|
-
continue;
|
|
535
|
-
}
|
|
536
|
-
if (st.type === "VariableDeclaration" && st.declarations.length === 1) {
|
|
537
|
-
const d = st.declarations[0] as Node;
|
|
538
|
-
if (d.id.name === "__s") {
|
|
539
|
-
removals.push(st);
|
|
540
|
-
continue;
|
|
541
|
-
}
|
|
542
|
-
}
|
|
543
|
-
const decl = st.type === "ExportNamedDeclaration" ? st.declaration : st;
|
|
544
|
-
if (decl?.type === "VariableDeclaration" && decl.declarations.length === 1) {
|
|
545
|
-
const d = decl.declarations[0] as Node;
|
|
546
|
-
const init = d.init ? strip(d.init) : undefined;
|
|
547
|
-
if (
|
|
548
|
-
init?.type === "CallExpression" &&
|
|
549
|
-
init.callee.type === "MemberExpression" &&
|
|
550
|
-
init.callee.object.name === "API" &&
|
|
551
|
-
(init.callee.property.name === "make" || init.callee.property.name === "makePaginated")
|
|
552
|
-
) {
|
|
553
|
-
const [fn, strategy] = init.arguments as Node[];
|
|
554
|
-
if (
|
|
555
|
-
fn?.type !== "ArrowFunctionExpression" ||
|
|
556
|
-
fn.params.length ||
|
|
557
|
-
fn.body.type === "BlockStatement"
|
|
558
|
-
)
|
|
559
|
-
throw new Error(`datafy: unexpected operation form in ${d.id.name}`);
|
|
560
|
-
ops.push({
|
|
561
|
-
name: d.id.name,
|
|
562
|
-
init: d.init,
|
|
563
|
-
paginated: init.callee.property.name === "makePaginated",
|
|
564
|
-
config: strip(fn.body),
|
|
565
|
-
strategy,
|
|
566
|
-
});
|
|
567
|
-
continue;
|
|
568
|
-
}
|
|
569
|
-
}
|
|
570
|
-
if (st.type !== "ImportDeclaration") rest.push(st);
|
|
571
|
-
}
|
|
572
|
-
if (!ops.length && !errors.length) return { code, operations: 0, holders: 0, errors: 0 };
|
|
573
|
-
const operations = ops.length;
|
|
574
|
-
// From here on an error class is a root like an operation; its entry 0 is its base class.
|
|
575
|
-
ops.push(...errors);
|
|
576
|
-
|
|
577
|
-
// Module constants only data reads (service traits, endpoint rules, ...)
|
|
578
|
-
// move, as written, into the holder of the roots that reach them.
|
|
579
|
-
const reads = (n: unknown, name: string): number => {
|
|
580
|
-
let count = 0;
|
|
581
|
-
walk(n, (x) => {
|
|
582
|
-
if (x.type === "Identifier" && x.name === name) count++;
|
|
583
|
-
return true;
|
|
584
|
-
});
|
|
585
|
-
return count;
|
|
586
|
-
};
|
|
587
|
-
const dataRoots: unknown[] = [[...nodes.values()], ops.map((o) => [o.config, o.strategy])];
|
|
588
|
-
const pinnable = new Map<string, { st: Node; init: Node }>();
|
|
589
|
-
for (const st of rest) {
|
|
590
|
-
if (st.type !== "VariableDeclaration" || st.kind !== "const" || st.declarations.length !== 1)
|
|
591
|
-
continue;
|
|
592
|
-
const d = st.declarations[0] as Node;
|
|
593
|
-
if (d.id.type !== "Identifier" || !d.init || strip(d.init).type !== "CallExpression") continue;
|
|
594
|
-
if (!/\/\*[@#]__PURE__\*\/\s*$/.test(code.slice(Math.max(0, d.init.start - 20), d.init.start)))
|
|
595
|
-
continue;
|
|
596
|
-
let internal = false;
|
|
597
|
-
walk(d.init, (x) => {
|
|
598
|
-
if (tableRef(x) || (x.type === "Identifier" && /^__[cSs]\d*$/.test(x.name))) internal = true;
|
|
599
|
-
// A first call would parse a big function twice (holder, then itself): it stays.
|
|
600
|
-
if (/Function/.test(x.type) && x.end - x.start > MAX_MOVED_FUNCTION) internal = true;
|
|
601
|
-
return true;
|
|
602
|
-
});
|
|
603
|
-
if (!internal) pinnable.set(d.id.name, { st, init: d.init });
|
|
604
|
-
}
|
|
605
|
-
for (let changed = true; changed;) {
|
|
606
|
-
changed = false;
|
|
607
|
-
for (const [name, c] of pinnable) {
|
|
608
|
-
const outside = rest.some((st) => st !== c.st && reads(st, name) > 0);
|
|
609
|
-
const chained = [...pinnable.keys()].some((other) => reads(c.init, other) > 0);
|
|
610
|
-
if (outside || chained || reads(c.init, name) || !reads(dataRoots, name)) {
|
|
611
|
-
pinnable.delete(name);
|
|
612
|
-
changed = true;
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
}
|
|
616
|
-
const pinned = new Map<string, string>();
|
|
617
|
-
for (const [name, c] of pinnable) {
|
|
618
|
-
pinned.set(name, text(c.init));
|
|
619
|
-
removals.push(c.st);
|
|
620
|
-
}
|
|
621
|
-
const roots = rest.filter((st) => !removals.includes(st));
|
|
622
|
-
|
|
623
|
-
/** Graph nodes an expression names. */
|
|
624
|
-
const refsOf = (n: unknown): Set<string> => {
|
|
625
|
-
const out = new Set<string>();
|
|
626
|
-
walk(n, (x) => {
|
|
627
|
-
const k = tableRef(x);
|
|
628
|
-
if (k) out.add(k);
|
|
629
|
-
return !k;
|
|
630
|
-
});
|
|
631
|
-
return out;
|
|
632
|
-
};
|
|
633
|
-
|
|
634
|
-
// Reachability: which roots reach each node.
|
|
635
|
-
const edges = new Map<string, Set<string>>();
|
|
636
|
-
for (const [k, n] of nodes) edges.set(k, refsOf(n));
|
|
637
|
-
const otherRoots = roots.filter((st) => refsOf(st).size);
|
|
638
|
-
const rootRefs = [...ops.map((o) => refsOf(o.config)), ...otherRoots.map((st) => refsOf(st))];
|
|
639
|
-
const reachedBy = new Map<string, number[]>();
|
|
640
|
-
rootRefs.forEach((start, r) => {
|
|
641
|
-
const seen = new Set<string>();
|
|
642
|
-
const stack = [...start];
|
|
643
|
-
while (stack.length) {
|
|
644
|
-
const k = stack.pop()!;
|
|
645
|
-
if (seen.has(k)) continue;
|
|
646
|
-
seen.add(k);
|
|
647
|
-
if (!nodes.has(k)) throw new Error(`datafy: missing schema ${k}`);
|
|
648
|
-
let list = reachedBy.get(k);
|
|
649
|
-
if (!list) reachedBy.set(k, (list = []));
|
|
650
|
-
list.push(r);
|
|
651
|
-
for (const x of edges.get(k)!) stack.push(x);
|
|
652
|
-
}
|
|
653
|
-
});
|
|
654
|
-
|
|
655
|
-
// Placement: an operation's own holder, or a shared holder per root set.
|
|
656
|
-
const opHolders = ops.map((o) => new Holder(o.name));
|
|
657
|
-
const shared = new Map<string, Holder>();
|
|
658
|
-
const home = new Map<string, Holder>();
|
|
659
|
-
for (const k of nodes.keys()) {
|
|
660
|
-
const rs = reachedBy.get(k);
|
|
661
|
-
if (!rs) continue; // unreachable: dropped
|
|
662
|
-
let h: Holder;
|
|
663
|
-
if (rs.length === 1 && rs[0]! < ops.length) h = opHolders[rs[0]!]!;
|
|
664
|
-
else {
|
|
665
|
-
const key = rs.join(",");
|
|
666
|
-
h = shared.get(key) ?? new Holder(`__d${shared.size}`);
|
|
667
|
-
shared.set(key, h);
|
|
668
|
-
}
|
|
669
|
-
home.set(k, h);
|
|
670
|
-
}
|
|
671
|
-
// Entry indexes: operation config first, then nodes in source order.
|
|
672
|
-
for (const h of opHolders) h.entries.push("");
|
|
673
|
-
for (const [k, h] of home) {
|
|
674
|
-
h.local.set(k, h.entries.length);
|
|
675
|
-
h.entries.push("");
|
|
676
|
-
}
|
|
677
|
-
|
|
678
|
-
// Aliases: `__0` is `at`; other namespace members are numbered on first use.
|
|
679
|
-
const aliases = new Map<string, string>([["__L.at", "__0"]]);
|
|
680
|
-
const alias = (t: string): string => {
|
|
681
|
-
let a = aliases.get(t);
|
|
682
|
-
if (!a) aliases.set(t, (a = `__${aliases.size}`));
|
|
683
|
-
return a;
|
|
684
|
-
};
|
|
685
|
-
|
|
686
|
-
const nodeRef = (k: string, h: Holder): string => {
|
|
687
|
-
const target = home.get(k)!;
|
|
688
|
-
const j = target.local.get(k)!;
|
|
689
|
-
if (target === h) return `#${j}`;
|
|
690
|
-
return `#${h.ref(target.name)}:${j}`;
|
|
691
|
-
};
|
|
692
|
-
|
|
693
|
-
const configs = ops.map(configOf);
|
|
694
|
-
|
|
695
|
-
// Repeated constant expressions become value entries (`~N`, `~R:N`).
|
|
696
|
-
const holderOfKey = (key: string, create: boolean): Holder | undefined => {
|
|
697
|
-
const rs = key.split(",").map(Number);
|
|
698
|
-
if (rs.length === 1 && rs[0]! < ops.length) return opHolders[rs[0]!]!;
|
|
699
|
-
let h = shared.get(key);
|
|
700
|
-
if (!h && create) shared.set(key, (h = new Holder(`__d${shared.size}`)));
|
|
701
|
-
return h;
|
|
702
|
-
};
|
|
703
|
-
const rootsOf = new Map<Holder, string>();
|
|
704
|
-
opHolders.forEach((h, i) => rootsOf.set(h, String(i)));
|
|
705
|
-
for (const [key, h] of shared) rootsOf.set(h, key);
|
|
706
|
-
const exprRoots: Array<[Node, Holder]> = [...home].map(([k, h]) => [nodes.get(k)!, h]);
|
|
707
|
-
configs.forEach((c, i) => exprRoots.push([c, opHolders[i]!]));
|
|
708
|
-
const values = hoistConstants(exprRoots, isNamespace, holderOfKey, rootsOf, pinned);
|
|
709
|
-
for (const v of values) {
|
|
710
|
-
v.j = v.holder.entries.length;
|
|
711
|
-
v.holder.entries.push("");
|
|
712
|
-
}
|
|
713
|
-
const valueOf = new Map<Node, Value>();
|
|
714
|
-
for (const v of values) for (const n of v.nodes) valueOf.set(n, v);
|
|
715
|
-
|
|
716
|
-
const encode = (n: Node, h: Holder, self?: Value): string => {
|
|
717
|
-
const value = (t: string): string => `$${h.ref(aliased && VOCAB.test(t) ? alias(t) : t)}`;
|
|
718
|
-
n = strip(n);
|
|
719
|
-
const v = valueOf.get(n);
|
|
720
|
-
if (v && v !== self) return v.holder === h ? `~${v.j}` : `~${h.ref(v.holder.name)}:${v.j}`;
|
|
721
|
-
const k = tableRef(n);
|
|
722
|
-
if (k) return nodeRef(k, h);
|
|
723
|
-
const enc = (x: Node) => encode(x, h);
|
|
724
|
-
switch (n.type) {
|
|
725
|
-
case "Literal": {
|
|
726
|
-
const v = n.value;
|
|
727
|
-
if (typeof v === "string") return quote(v);
|
|
728
|
-
if (typeof v === "number" && Number.isFinite(v)) return String(v);
|
|
729
|
-
if (typeof v === "boolean") return String(v);
|
|
730
|
-
if (v === null && !n.regex && !n.bigint) return "null";
|
|
731
|
-
throw new Error(`datafy: unsupported literal ${text(n)}`);
|
|
732
|
-
}
|
|
733
|
-
case "TemplateLiteral":
|
|
734
|
-
if (n.expressions.length) throw new Error("datafy: template with expressions");
|
|
735
|
-
return quote(n.quasis[0].value.cooked);
|
|
736
|
-
case "UnaryExpression":
|
|
737
|
-
if (
|
|
738
|
-
n.operator === "-" &&
|
|
739
|
-
n.argument.type === "Literal" &&
|
|
740
|
-
typeof n.argument.value === "number"
|
|
741
|
-
)
|
|
742
|
-
return String(-n.argument.value);
|
|
743
|
-
if (n.operator === "void") return "u";
|
|
744
|
-
throw new Error(`datafy: unsupported unary ${text(n)}`);
|
|
745
|
-
case "Identifier":
|
|
746
|
-
if (n.name === "undefined") return "u";
|
|
747
|
-
return value(n.name);
|
|
748
|
-
case "MemberExpression": {
|
|
749
|
-
if (n.computed) throw new Error(`datafy: computed member ${text(n)}`);
|
|
750
|
-
const obj = strip(n.object);
|
|
751
|
-
// `S.String`, `Retry.Retry`: one value.
|
|
752
|
-
if (isNamespace(obj)) return value(`${obj.name}.${n.property.name}`);
|
|
753
|
-
return `${enc(obj)}.${n.property.name}`;
|
|
754
|
-
}
|
|
755
|
-
case "CallExpression": {
|
|
756
|
-
const args = (n.arguments as Node[]).map((a) => {
|
|
757
|
-
if (a.type === "SpreadElement") throw new Error("datafy: spread argument");
|
|
758
|
-
return enc(a);
|
|
759
|
-
});
|
|
760
|
-
const callee = strip(n.callee);
|
|
761
|
-
// `S.Struct(...)` calls the namespace member as a plain function;
|
|
762
|
-
// `x.pipe(...)` on any other receiver is a method call.
|
|
763
|
-
if (
|
|
764
|
-
callee.type === "MemberExpression" &&
|
|
765
|
-
!callee.computed &&
|
|
766
|
-
!isNamespace(strip(callee.object))
|
|
767
|
-
) {
|
|
768
|
-
// `.annotate({ identifier: "X" })`, on most schemas: `@"X"`.
|
|
769
|
-
const id = identifierOf(n);
|
|
770
|
-
if (id !== undefined) return `${enc(callee.object)}@${quote(id)}`;
|
|
771
|
-
return `${enc(callee.object)}.${callee.property.name}(${args.join(",")})`;
|
|
772
|
-
}
|
|
773
|
-
return `${enc(callee)}(${args.join(",")})`;
|
|
774
|
-
}
|
|
775
|
-
case "ObjectExpression":
|
|
776
|
-
return `{${(n.properties as Node[])
|
|
777
|
-
.map((p) => {
|
|
778
|
-
if (p.type !== "Property" || p.kind !== "init" || p.method)
|
|
779
|
-
throw new Error(`datafy: unsupported property ${text(p)}`);
|
|
780
|
-
let key: string;
|
|
781
|
-
if (!p.computed && p.key.type === "Identifier") key = p.key.name;
|
|
782
|
-
else if (p.key.type === "Literal") key = String(p.key.value);
|
|
783
|
-
else throw new Error(`datafy: unsupported key ${text(p)}`);
|
|
784
|
-
return `${IDENT.test(key) ? key : quote(key)}:${enc(p.value)}`;
|
|
785
|
-
})
|
|
786
|
-
.join(",")}}`;
|
|
787
|
-
case "ArrayExpression":
|
|
788
|
-
return `[${(n.elements as Array<Node | null>)
|
|
789
|
-
.map((e) => {
|
|
790
|
-
if (!e || e.type === "SpreadElement") throw new Error("datafy: array hole or spread");
|
|
791
|
-
return enc(e);
|
|
792
|
-
})
|
|
793
|
-
.join(",")}]`;
|
|
794
|
-
case "ArrowFunctionExpression":
|
|
795
|
-
if (n.params.length || n.body.type === "BlockStatement")
|
|
796
|
-
throw new Error(`datafy: unsupported function ${text(n).slice(0, 80)}`);
|
|
797
|
-
{
|
|
798
|
-
// The body becomes its own entry, so a reader never has to skip it.
|
|
799
|
-
const j = h.entries.length;
|
|
800
|
-
h.entries.push("");
|
|
801
|
-
h.entries[j] = enc(n.body);
|
|
802
|
-
return `>${j}`;
|
|
803
|
-
}
|
|
804
|
-
default:
|
|
805
|
-
throw new Error(`datafy: unsupported ${n.type}: ${text(n).slice(0, 80)}`);
|
|
806
|
-
}
|
|
807
|
-
};
|
|
808
|
-
|
|
809
|
-
for (const [k, h] of home) h.entries[h.local.get(k)!] = encode(nodes.get(k)!, h);
|
|
810
|
-
configs.forEach((c, i) => (opHolders[i]!.entries[0] = encode(c, opHolders[i]!)));
|
|
811
|
-
for (const v of values)
|
|
812
|
-
v.holder.entries[v.j] = v.code ? `$${v.holder.ref(v.code)}` : encode(v.nodes[0]!, v.holder, v);
|
|
813
|
-
|
|
814
|
-
// Operations only: an error class's data is built on every construction.
|
|
815
|
-
for (const h of opHolders.slice(0, operations)) stemOf(h);
|
|
816
|
-
|
|
817
|
-
// The data string is a single-quoted JS literal.
|
|
818
|
-
const literal = (h: Holder) => {
|
|
819
|
-
const data = `'${h.entries.join(";").replace(/[\\']/g, (c) => `\\${c}`)}'`;
|
|
820
|
-
const refs = `[${(aliased ? h.refs : ["__L.at", ...h.refs.slice(1)]).join(", ")}]`;
|
|
821
|
-
return h.stem ? `API.named(${quote(h.stem)}, ${data}, ${refs})` : `[${data}, ${refs}]`;
|
|
822
|
-
};
|
|
823
|
-
|
|
824
|
-
const edits: Array<[number, number, string]> = [];
|
|
825
|
-
for (const st of removals) {
|
|
826
|
-
let end = st.end;
|
|
827
|
-
while (code[end] === "\n") end++;
|
|
828
|
-
edits.push([st.start, end, ""]);
|
|
829
|
-
}
|
|
830
|
-
ops.forEach((o, i) => {
|
|
831
|
-
if (o.error) {
|
|
832
|
-
// A plain function, not an arrow: it is the class (`new`, `instanceof`, `extends`).
|
|
833
|
-
edits.push([
|
|
834
|
-
o.init.start,
|
|
835
|
-
o.init.end,
|
|
836
|
-
`${o.error.exported ? "export " : ""}const ${o.name}${any} = /*@__PURE__*/ API.error(function ${o.name}(i${any})${any} {\n return API.newError(i, new.target, ${literal(opHolders[i]!)});\n});`,
|
|
837
|
-
]);
|
|
838
|
-
return;
|
|
839
|
-
}
|
|
840
|
-
const fn = o.paginated ? "API.opPaginated" : "API.op";
|
|
841
|
-
const marked = /\/\*[@#]__PURE__\*\/\s*$/.test(code.slice(o.init.start - 20, o.init.start));
|
|
842
|
-
edits.push([
|
|
843
|
-
o.init.start,
|
|
844
|
-
o.init.end,
|
|
845
|
-
`${marked ? "" : "/*@__PURE__*/ "}${fn}((i${any})${any} => i === API.D ? ${literal(opHolders[i]!)} : API.call(${o.name}, i))`,
|
|
846
|
-
]);
|
|
847
|
-
});
|
|
848
|
-
// Module-level code that names a schema at import (error classes).
|
|
849
|
-
for (const st of otherRoots)
|
|
850
|
-
walk(st, (n) => {
|
|
851
|
-
const k = tableRef(n);
|
|
852
|
-
if (!k) return true;
|
|
853
|
-
const target = home.get(k)!;
|
|
854
|
-
edits.push([n.start, n.end, `API.schema(${target.name}, ${target.local.get(k)})`]);
|
|
855
|
-
return false;
|
|
856
|
-
});
|
|
857
|
-
|
|
858
|
-
edits.sort((a, b) => b[0] - a[0]);
|
|
859
|
-
let out = code;
|
|
860
|
-
for (const [s, e, t] of edits) out = out.slice(0, s) + t + out.slice(e);
|
|
861
|
-
out = out.replace(/\n*$/, "\n").replace(/^\/\/ Schema table, filled on first reach.*\n/m, "");
|
|
862
|
-
if (shared.size)
|
|
863
|
-
out +=
|
|
864
|
-
"\n// Shared schema data (see `op` in core/api).\n" +
|
|
865
|
-
[...shared.values()]
|
|
866
|
-
.map((h) => `function ${h.name}()${any} {\n return ${literal(h)};\n}\n`)
|
|
867
|
-
.join("");
|
|
868
|
-
// Aliases go right after the imports: error classes reach schemas while the module evaluates.
|
|
869
|
-
const lastImport = [...body].reverse().find((st) => st.type === "ImportDeclaration");
|
|
870
|
-
const at = lastImport ? lastImport.end : 0;
|
|
871
|
-
const decls = aliased ? [...aliases].map(([t, a]) => `const ${a} = ${t};`) : [];
|
|
872
|
-
out = `${out.slice(0, at)}\n${decls.join("\n")}${out.slice(at)}`;
|
|
873
|
-
return { code: out, operations, holders: shared.size, errors: errors.length };
|
|
874
|
-
};
|