@distilled.cloud/core 1.0.0-rc.15 → 1.0.0-rc.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (318) hide show
  1. package/lib/_bundle/aws.js +2 -0
  2. package/lib/_bundle/aws.js.map +1 -0
  3. package/lib/_bundle/base.js +5 -0
  4. package/lib/_bundle/base.js.map +1 -0
  5. package/lib/_bundle/graphql.js +3 -0
  6. package/lib/_bundle/graphql.js.map +1 -0
  7. package/lib/_bundle/rest.js +2 -0
  8. package/lib/_bundle/rest.js.map +1 -0
  9. package/lib/_bundle/xml.js +4 -0
  10. package/lib/_bundle/xml.js.map +1 -0
  11. package/lib/api.d.ts +118 -13
  12. package/lib/api.d.ts.map +1 -1
  13. package/lib/api.js +1 -188
  14. package/lib/category.d.ts.map +1 -1
  15. package/lib/category.js +1 -278
  16. package/lib/chunks.d.ts +3 -0
  17. package/lib/chunks.d.ts.map +1 -0
  18. package/lib/chunks.js +1 -0
  19. package/lib/codegen/boolean-string-enums.js +36 -36
  20. package/lib/codegen/chunk.d.ts +7 -0
  21. package/lib/codegen/chunk.d.ts.map +1 -0
  22. package/lib/codegen/chunk.js +139 -0
  23. package/lib/codegen/chunk.js.map +1 -0
  24. package/lib/codegen/cli.d.ts.map +1 -1
  25. package/lib/codegen/cli.js +28 -14
  26. package/lib/codegen/cli.js.map +1 -1
  27. package/lib/codegen/datafy.d.ts +14 -0
  28. package/lib/codegen/datafy.d.ts.map +1 -0
  29. package/lib/codegen/datafy.js +853 -0
  30. package/lib/codegen/datafy.js.map +1 -0
  31. package/lib/codegen/dedupe.d.ts +5 -0
  32. package/lib/codegen/dedupe.d.ts.map +1 -0
  33. package/lib/codegen/dedupe.js +153 -0
  34. package/lib/codegen/dedupe.js.map +1 -0
  35. package/lib/codegen/emit.js +56 -56
  36. package/lib/codegen/format.js +18 -18
  37. package/lib/codegen/generated-at.js +29 -29
  38. package/lib/codegen/generator.d.ts.map +1 -1
  39. package/lib/codegen/generator.js +92 -84
  40. package/lib/codegen/generator.js.map +1 -1
  41. package/lib/codegen/graph.js +36 -36
  42. package/lib/codegen/graphql-client.d.ts +2 -0
  43. package/lib/codegen/graphql-client.d.ts.map +1 -1
  44. package/lib/codegen/graphql-client.js +55 -26
  45. package/lib/codegen/graphql-client.js.map +1 -1
  46. package/lib/codegen/graphql.js +113 -113
  47. package/lib/codegen/latin1.d.ts +3 -0
  48. package/lib/codegen/latin1.d.ts.map +1 -0
  49. package/lib/codegen/latin1.js +126 -0
  50. package/lib/codegen/latin1.js.map +1 -0
  51. package/lib/codegen/members.d.ts +7 -0
  52. package/lib/codegen/members.d.ts.map +1 -1
  53. package/lib/codegen/members.js +26 -19
  54. package/lib/codegen/members.js.map +1 -1
  55. package/lib/codegen/model-diff.js +6 -6
  56. package/lib/codegen/naming.js +19 -19
  57. package/lib/codegen/openapi-cli.js +15 -15
  58. package/lib/codegen/openapi.d.ts +17 -0
  59. package/lib/codegen/openapi.d.ts.map +1 -1
  60. package/lib/codegen/openapi.js +323 -169
  61. package/lib/codegen/openapi.js.map +1 -1
  62. package/lib/codegen/operations.js +14 -14
  63. package/lib/codegen/pagination.js +11 -11
  64. package/lib/codegen/patch-audit.js +57 -57
  65. package/lib/codegen/patches.js +79 -79
  66. package/lib/codegen/prelude.js +19 -19
  67. package/lib/codegen/privatize.d.ts +21 -0
  68. package/lib/codegen/privatize.d.ts.map +1 -0
  69. package/lib/codegen/privatize.js +176 -0
  70. package/lib/codegen/privatize.js.map +1 -0
  71. package/lib/codegen/proto.js +25 -25
  72. package/lib/codegen/pure.d.ts +6 -0
  73. package/lib/codegen/pure.d.ts.map +1 -0
  74. package/lib/codegen/pure.js +91 -0
  75. package/lib/codegen/pure.js.map +1 -0
  76. package/lib/codegen/rewrite-operation-ids.js +108 -108
  77. package/lib/codegen/spec-path.js +57 -57
  78. package/lib/codegen/table.d.ts +5 -0
  79. package/lib/codegen/table.d.ts.map +1 -0
  80. package/lib/codegen/table.js +249 -0
  81. package/lib/codegen/table.js.map +1 -0
  82. package/lib/config.d.ts +27 -0
  83. package/lib/config.d.ts.map +1 -0
  84. package/lib/config.js +1 -0
  85. package/lib/crypto.d.ts +76 -0
  86. package/lib/crypto.d.ts.map +1 -0
  87. package/lib/crypto.js +1 -0
  88. package/lib/debug.d.ts +2 -0
  89. package/lib/debug.d.ts.map +1 -0
  90. package/lib/debug.js +1 -0
  91. package/lib/error-category.d.ts +1 -1
  92. package/lib/error-category.d.ts.map +1 -1
  93. package/lib/error-category.js +1 -46
  94. package/lib/errors.d.ts +62 -62
  95. package/lib/errors.d.ts.map +1 -1
  96. package/lib/errors.js +1 -195
  97. package/lib/graphql.d.ts +31 -20
  98. package/lib/graphql.d.ts.map +1 -1
  99. package/lib/graphql.js +1 -1027
  100. package/lib/graphql.types.js +1 -5
  101. package/lib/index.d.ts +3 -2
  102. package/lib/index.d.ts.map +1 -1
  103. package/lib/index.js +1 -15
  104. package/lib/json-patch.d.ts +2 -2
  105. package/lib/json-patch.js +1 -226
  106. package/lib/json-patch.js.map +1 -1
  107. package/lib/pagination.d.ts +9 -25
  108. package/lib/pagination.d.ts.map +1 -1
  109. package/lib/pagination.js +1 -266
  110. package/lib/plain-values.d.ts +10 -0
  111. package/lib/plain-values.d.ts.map +1 -0
  112. package/lib/plain-values.js +2 -0
  113. package/lib/plain-values.js.map +1 -0
  114. package/lib/protocol-http.d.ts +50 -14
  115. package/lib/protocol-http.d.ts.map +1 -1
  116. package/lib/protocol-http.js +1 -639
  117. package/lib/protocol-rest.d.ts +38 -25
  118. package/lib/protocol-rest.d.ts.map +1 -1
  119. package/lib/protocol-rest.js +1 -267
  120. package/lib/query.js +1 -27
  121. package/lib/response-validation-strict.d.ts +48 -0
  122. package/lib/response-validation-strict.d.ts.map +1 -0
  123. package/lib/response-validation-strict.js +1 -0
  124. package/lib/response-validation.d.ts +43 -25
  125. package/lib/response-validation.d.ts.map +1 -1
  126. package/lib/response-validation.js +1 -76
  127. package/lib/retry-after.d.ts +3 -3
  128. package/lib/retry-after.js +1 -112
  129. package/lib/retry.d.ts +48 -29
  130. package/lib/retry.d.ts.map +1 -1
  131. package/lib/retry.js +1 -209
  132. package/lib/schema-lite-impl.d.ts +158 -0
  133. package/lib/schema-lite-impl.d.ts.map +1 -0
  134. package/lib/schema-lite-impl.js +1 -0
  135. package/lib/schema-lite-typed.d.ts +41 -0
  136. package/lib/schema-lite-typed.d.ts.map +1 -0
  137. package/lib/schema-lite-typed.js +2 -0
  138. package/lib/schema-lite-typed.js.map +1 -0
  139. package/lib/schema-lite.d.ts +40 -0
  140. package/lib/schema-lite.d.ts.map +1 -0
  141. package/lib/schema-lite.js +1 -0
  142. package/lib/schema.d.ts +20 -6
  143. package/lib/schema.d.ts.map +1 -1
  144. package/lib/schema.js +1 -48
  145. package/lib/testing.d.ts +3 -2
  146. package/lib/testing.d.ts.map +1 -1
  147. package/lib/testing.js +1 -40
  148. package/lib/testing.js.map +1 -1
  149. package/lib/trait.d.ts +13 -13
  150. package/lib/trait.d.ts.map +1 -1
  151. package/lib/trait.js +1 -131
  152. package/lib/xml.d.ts +1 -1
  153. package/lib/xml.d.ts.map +1 -1
  154. package/lib/xml.js +1 -311
  155. package/package.json +9 -7
  156. package/src/api.ts +1080 -180
  157. package/src/category.ts +33 -33
  158. package/src/chunks.ts +30 -0
  159. package/src/codegen/chunk.ts +147 -0
  160. package/src/codegen/cli.ts +27 -1
  161. package/src/codegen/datafy.ts +874 -0
  162. package/src/codegen/dedupe.ts +173 -0
  163. package/src/codegen/generator.ts +10 -3
  164. package/src/codegen/graphql-client.ts +49 -15
  165. package/src/codegen/latin1.ts +131 -0
  166. package/src/codegen/members.ts +8 -0
  167. package/src/codegen/openapi.ts +194 -3
  168. package/src/codegen/privatize.ts +200 -0
  169. package/src/codegen/pure.ts +94 -0
  170. package/src/codegen/table.ts +254 -0
  171. package/src/config.ts +216 -0
  172. package/src/crypto.ts +202 -0
  173. package/src/debug.ts +8 -0
  174. package/src/error-category.ts +2 -1
  175. package/src/errors.ts +65 -56
  176. package/src/graphql.ts +109 -62
  177. package/src/graphql.types.ts +9 -7
  178. package/src/index.ts +3 -2
  179. package/src/json-patch.ts +2 -2
  180. package/src/pagination.ts +37 -18
  181. package/src/plain-values.ts +41 -0
  182. package/src/protocol-http.ts +378 -145
  183. package/src/protocol-rest.ts +337 -169
  184. package/src/response-validation-strict.ts +327 -0
  185. package/src/response-validation.ts +101 -50
  186. package/src/retry-after.ts +3 -3
  187. package/src/retry.ts +94 -93
  188. package/src/schema-lite-impl.ts +550 -0
  189. package/src/schema-lite-typed.ts +44 -0
  190. package/src/schema-lite.ts +44 -0
  191. package/src/schema.ts +258 -14
  192. package/src/testing.ts +4 -2
  193. package/src/trait.ts +36 -28
  194. package/src/xml.ts +31 -17
  195. package/lib/api.js.map +0 -1
  196. package/lib/category.js.map +0 -1
  197. package/lib/codegen/boolean-string-enums.test.d.ts +0 -2
  198. package/lib/codegen/boolean-string-enums.test.d.ts.map +0 -1
  199. package/lib/codegen/boolean-string-enums.test.js +0 -275
  200. package/lib/codegen/boolean-string-enums.test.js.map +0 -1
  201. package/lib/codegen/defer-naming.test.d.ts +0 -2
  202. package/lib/codegen/defer-naming.test.d.ts.map +0 -1
  203. package/lib/codegen/defer-naming.test.js +0 -105
  204. package/lib/codegen/defer-naming.test.js.map +0 -1
  205. package/lib/codegen/generated-at.test.d.ts +0 -2
  206. package/lib/codegen/generated-at.test.d.ts.map +0 -1
  207. package/lib/codegen/generated-at.test.js +0 -81
  208. package/lib/codegen/generated-at.test.js.map +0 -1
  209. package/lib/codegen/generator.test.d.ts +0 -2
  210. package/lib/codegen/generator.test.d.ts.map +0 -1
  211. package/lib/codegen/generator.test.js +0 -121
  212. package/lib/codegen/generator.test.js.map +0 -1
  213. package/lib/codegen/graphql-client.test.d.ts +0 -2
  214. package/lib/codegen/graphql-client.test.d.ts.map +0 -1
  215. package/lib/codegen/graphql-client.test.js +0 -171
  216. package/lib/codegen/graphql-client.test.js.map +0 -1
  217. package/lib/codegen/openapi-binary.test.d.ts +0 -2
  218. package/lib/codegen/openapi-binary.test.d.ts.map +0 -1
  219. package/lib/codegen/openapi-binary.test.js +0 -67
  220. package/lib/codegen/openapi-binary.test.js.map +0 -1
  221. package/lib/codegen/patch-audit.test.d.ts +0 -2
  222. package/lib/codegen/patch-audit.test.d.ts.map +0 -1
  223. package/lib/codegen/patch-audit.test.js +0 -141
  224. package/lib/codegen/patch-audit.test.js.map +0 -1
  225. package/lib/codegen/patches.test.d.ts +0 -2
  226. package/lib/codegen/patches.test.d.ts.map +0 -1
  227. package/lib/codegen/patches.test.js +0 -155
  228. package/lib/codegen/patches.test.js.map +0 -1
  229. package/lib/codegen/protocol-imports.test.d.ts +0 -2
  230. package/lib/codegen/protocol-imports.test.d.ts.map +0 -1
  231. package/lib/codegen/protocol-imports.test.js +0 -36
  232. package/lib/codegen/protocol-imports.test.js.map +0 -1
  233. package/lib/codegen/rewrite-operation-ids.test.d.ts +0 -2
  234. package/lib/codegen/rewrite-operation-ids.test.d.ts.map +0 -1
  235. package/lib/codegen/rewrite-operation-ids.test.js +0 -451
  236. package/lib/codegen/rewrite-operation-ids.test.js.map +0 -1
  237. package/lib/codegen/untagged-unions.test.d.ts +0 -2
  238. package/lib/codegen/untagged-unions.test.d.ts.map +0 -1
  239. package/lib/codegen/untagged-unions.test.js +0 -80
  240. package/lib/codegen/untagged-unions.test.js.map +0 -1
  241. package/lib/error-category.js.map +0 -1
  242. package/lib/errors.js.map +0 -1
  243. package/lib/fixtures/xml/upstream-validator.json +0 -397
  244. package/lib/graphql.js.map +0 -1
  245. package/lib/graphql.test.d.ts +0 -2
  246. package/lib/graphql.test.d.ts.map +0 -1
  247. package/lib/graphql.test.js +0 -151
  248. package/lib/graphql.test.js.map +0 -1
  249. package/lib/graphql.types.js.map +0 -1
  250. package/lib/index.js.map +0 -1
  251. package/lib/json-patch.test.d.ts +0 -2
  252. package/lib/json-patch.test.d.ts.map +0 -1
  253. package/lib/json-patch.test.js +0 -65
  254. package/lib/json-patch.test.js.map +0 -1
  255. package/lib/pagination.js.map +0 -1
  256. package/lib/pagination.test.d.ts +0 -2
  257. package/lib/pagination.test.d.ts.map +0 -1
  258. package/lib/pagination.test.js +0 -131
  259. package/lib/pagination.test.js.map +0 -1
  260. package/lib/protocol-http.js.map +0 -1
  261. package/lib/protocol-http.test.d.ts +0 -2
  262. package/lib/protocol-http.test.d.ts.map +0 -1
  263. package/lib/protocol-http.test.js +0 -228
  264. package/lib/protocol-http.test.js.map +0 -1
  265. package/lib/protocol-rest.js.map +0 -1
  266. package/lib/protocol-rest.test.d.ts +0 -2
  267. package/lib/protocol-rest.test.d.ts.map +0 -1
  268. package/lib/protocol-rest.test.js +0 -498
  269. package/lib/protocol-rest.test.js.map +0 -1
  270. package/lib/query.js.map +0 -1
  271. package/lib/response-validation.js.map +0 -1
  272. package/lib/response-validation.test.d.ts +0 -2
  273. package/lib/response-validation.test.d.ts.map +0 -1
  274. package/lib/response-validation.test.js +0 -72
  275. package/lib/response-validation.test.js.map +0 -1
  276. package/lib/retry-after.js.map +0 -1
  277. package/lib/retry-after.test.d.ts +0 -2
  278. package/lib/retry-after.test.d.ts.map +0 -1
  279. package/lib/retry-after.test.js +0 -204
  280. package/lib/retry-after.test.js.map +0 -1
  281. package/lib/retry.js.map +0 -1
  282. package/lib/retry.test.d.ts +0 -2
  283. package/lib/retry.test.d.ts.map +0 -1
  284. package/lib/retry.test.js +0 -407
  285. package/lib/retry.test.js.map +0 -1
  286. package/lib/schema.js.map +0 -1
  287. package/lib/sdks.test.d.ts +0 -2
  288. package/lib/sdks.test.d.ts.map +0 -1
  289. package/lib/sdks.test.js +0 -76
  290. package/lib/sdks.test.js.map +0 -1
  291. package/lib/trait.js.map +0 -1
  292. package/lib/xml.js.map +0 -1
  293. package/lib/xml.test.d.ts +0 -2
  294. package/lib/xml.test.d.ts.map +0 -1
  295. package/lib/xml.test.js +0 -210
  296. package/lib/xml.test.js.map +0 -1
  297. package/src/codegen/boolean-string-enums.test.ts +0 -299
  298. package/src/codegen/defer-naming.test.ts +0 -113
  299. package/src/codegen/generated-at.test.ts +0 -89
  300. package/src/codegen/generator.test.ts +0 -137
  301. package/src/codegen/graphql-client.test.ts +0 -189
  302. package/src/codegen/openapi-binary.test.ts +0 -91
  303. package/src/codegen/patch-audit.test.ts +0 -160
  304. package/src/codegen/patches.test.ts +0 -188
  305. package/src/codegen/protocol-imports.test.ts +0 -39
  306. package/src/codegen/rewrite-operation-ids.test.ts +0 -472
  307. package/src/codegen/untagged-unions.test.ts +0 -85
  308. package/src/fixtures/xml/upstream-validator.json +0 -397
  309. package/src/graphql.test.ts +0 -198
  310. package/src/json-patch.test.ts +0 -77
  311. package/src/pagination.test.ts +0 -169
  312. package/src/protocol-http.test.ts +0 -276
  313. package/src/protocol-rest.test.ts +0 -703
  314. package/src/response-validation.test.ts +0 -89
  315. package/src/retry-after.test.ts +0 -267
  316. package/src/retry.test.ts +0 -566
  317. package/src/sdks.test.ts +0 -87
  318. package/src/xml.test.ts +0 -251
@@ -0,0 +1,874 @@
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
+ };