@adhd/apigen-engine-runtime 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs CHANGED
@@ -1,1885 +1,1921 @@
1
- import "ts-morph";
2
1
  import "node:fs";
2
+ import { createRequire as e } from "node:module";
3
3
  import "node:path";
4
- import "ts-json-schema-generator";
5
- import j from "pino";
6
- import $e from "ajv";
7
- import Ae from "ajv-formats";
8
- const x = "$apigen";
9
- class J extends Error {
10
- constructor(t) {
11
- super(t), this.code = "E_DUP_CODEC", this.name = "CodecRegistryError";
12
- }
13
- }
14
- function Oe(e) {
15
- const t = /* @__PURE__ */ new Map();
16
- return {
17
- register(n, r) {
18
- if (t.has(n.id) && !(r != null && r.override))
19
- throw new J(
20
- `E_DUP_CODEC: a codec is already registered for id "${n.id}"`
21
- );
22
- t.set(n.id, n);
23
- },
24
- resolve(n) {
25
- for (const r of t.values())
26
- if (r.matches(n))
27
- return r;
28
- },
29
- get(n) {
30
- return t.get(n);
31
- },
32
- ids() {
33
- return [...t.keys()];
34
- },
35
- freeze() {
36
- const n = new Map(t), r = {
37
- register() {
38
- throw new J(
39
- "E_DUP_CODEC: registry is frozen and cannot accept new codecs"
40
- );
41
- },
42
- resolve(o) {
43
- for (const i of n.values())
44
- if (i.matches(o))
45
- return i;
46
- },
47
- get(o) {
48
- return n.get(o);
49
- },
50
- ids() {
51
- return [...n.keys()];
52
- },
53
- freeze() {
54
- return r;
55
- }
56
- };
57
- return r;
58
- }
59
- };
60
- }
61
- const L = "x-apigen-logical", B = "x-apigen-codec", S = "x-apigen-ctor", M = "x-apigen-tojson", je = "0.1.0";
62
- function G(e, t) {
63
- return {
64
- registry: e,
65
- resolve: (n) => {
66
- throw new Error(
67
- `[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`
68
- );
69
- },
70
- seen: /* @__PURE__ */ new WeakSet(),
71
- path: "",
72
- mode: "strict",
73
- ...t
74
- };
4
+ import t from "pino";
5
+ import n from "ajv";
6
+ import r from "ajv-formats";
7
+ //#region ../apigen-base-logical/src/lib/contracts.ts
8
+ var i = "$apigen", a = class extends Error {
9
+ constructor(e) {
10
+ super(e), this.code = "E_DUP_CODEC", this.name = "CodecRegistryError";
11
+ }
12
+ };
13
+ function o(e) {
14
+ e?.wellKnown;
15
+ let t = /* @__PURE__ */ new Map();
16
+ return {
17
+ register(e, n) {
18
+ if (t.has(e.id) && !n?.override) throw new a(`E_DUP_CODEC: a codec is already registered for id "${e.id}"`);
19
+ t.set(e.id, e);
20
+ },
21
+ resolve(e) {
22
+ for (let n of t.values()) if (n.matches(e)) return n;
23
+ },
24
+ get(e) {
25
+ return t.get(e);
26
+ },
27
+ ids() {
28
+ return [...t.keys()];
29
+ },
30
+ freeze() {
31
+ let e = new Map(t), n = {
32
+ register() {
33
+ throw new a("E_DUP_CODEC: registry is frozen and cannot accept new codecs");
34
+ },
35
+ resolve(t) {
36
+ for (let n of e.values()) if (n.matches(t)) return n;
37
+ },
38
+ get(t) {
39
+ return e.get(t);
40
+ },
41
+ ids() {
42
+ return [...e.keys()];
43
+ },
44
+ freeze() {
45
+ return n;
46
+ }
47
+ };
48
+ return n;
49
+ }
50
+ };
51
+ }
52
+ //#endregion
53
+ //#region ../apigen-base-logical/src/lib/descriptor-ext.ts
54
+ var s = "x-apigen-logical", c = "x-apigen-codec", l = "x-apigen-ctor", u = "x-apigen-tojson", d = "0.1.0";
55
+ //#endregion
56
+ //#region ../apigen-base-logical/src/lib/runmode.ts
57
+ function f(e, t) {
58
+ return {
59
+ registry: e,
60
+ resolve: (e) => {
61
+ throw Error(`[apigen-logical] $ref "${e}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`);
62
+ },
63
+ seen: /* @__PURE__ */ new WeakSet(),
64
+ path: "",
65
+ mode: "strict",
66
+ ...t
67
+ };
68
+ }
69
+ function p(e, t, n) {
70
+ let r = n.registry.resolve(t);
71
+ if (r) return r.encode(e, t, n);
72
+ let i = t.$ref;
73
+ if (typeof i == "string") return p(e, n.resolve(i), n);
74
+ let a = t.oneOf;
75
+ if (Array.isArray(a)) return p(e, ee(e, a, t, n), n);
76
+ let o = t.type;
77
+ if (o === "array") {
78
+ if (!Array.isArray(e)) return v(e, t, n);
79
+ let r = t.items;
80
+ if (!r) return e.map((e) => b(e));
81
+ let i = n.path;
82
+ return Array.isArray(r) ? e.map((e, t) => {
83
+ let a = r[t];
84
+ return a === void 0 ? b(e) : p(e, a, {
85
+ ...n,
86
+ path: `${i}/${t}`
87
+ });
88
+ }) : e.map((e, t) => p(e, r, {
89
+ ...n,
90
+ path: `${i}/${t}`
91
+ }));
92
+ }
93
+ if (o === "object") {
94
+ if (typeof e != "object" || !e || Array.isArray(e)) return v(e, t, n);
95
+ let r = t.properties;
96
+ if (!r) return b(e);
97
+ let i = n.path, a = {};
98
+ for (let [t, o] of Object.entries(r)) {
99
+ let r = e[t];
100
+ r !== void 0 && (a[t] = p(r, o, {
101
+ ...n,
102
+ path: `${i}/${t}`
103
+ }));
104
+ }
105
+ return a;
106
+ }
107
+ return o == null ? v(e, t, n) : b(e);
108
+ }
109
+ function m(e, t, n) {
110
+ let r = n.registry.resolve(t);
111
+ if (r) return r.decode(e, t, n);
112
+ let i = t.$ref;
113
+ if (typeof i == "string") return m(e, n.resolve(i), n);
114
+ let a = t.oneOf;
115
+ if (Array.isArray(a)) return m(e, ee(e, a, t, n), n);
116
+ let o = t.type;
117
+ if (o === "array") {
118
+ if (!Array.isArray(e)) return e;
119
+ let r = t.items;
120
+ if (!r) return e;
121
+ let i = n.path;
122
+ return Array.isArray(r) ? e.map((e, t) => {
123
+ let a = r[t];
124
+ return a === void 0 ? e : m(e, a, {
125
+ ...n,
126
+ path: `${i}/${t}`
127
+ });
128
+ }) : e.map((e, t) => m(e, r, {
129
+ ...n,
130
+ path: `${i}/${t}`
131
+ }));
132
+ }
133
+ if (o === "object") {
134
+ if (typeof e != "object" || !e || Array.isArray(e)) return e;
135
+ let r = t.properties;
136
+ if (!r) return e;
137
+ let i = n.path, a = {};
138
+ for (let [t, o] of Object.entries(r)) {
139
+ let r = e[t];
140
+ r !== void 0 && (a[t] = m(r, o, {
141
+ ...n,
142
+ path: `${i}/${t}`
143
+ }));
144
+ }
145
+ for (let [t, n] of Object.entries(e)) !(t in r) && n !== void 0 && (a[t] = n);
146
+ return a;
147
+ }
148
+ return o == null ? y(e, n) : e;
149
+ }
150
+ function ee(e, t, n, r) {
151
+ let i = n.discriminator;
152
+ if (i?.propertyName) {
153
+ let n = i.propertyName, a = typeof e == "object" && e ? e[n] : void 0;
154
+ if (typeof a == "string") {
155
+ if (i.mapping) {
156
+ let e = i.mapping[a];
157
+ if (e) {
158
+ let n = t.find((t) => t.$ref === e);
159
+ if (n) return n;
160
+ }
161
+ }
162
+ for (let e of t) {
163
+ let t = h(e, r).properties?.[n];
164
+ if (!t) continue;
165
+ let i = t.enum;
166
+ if (t.const === a || Array.isArray(i) && i.includes(a)) return e;
167
+ }
168
+ }
169
+ }
170
+ let a = te(e, t, r);
171
+ if (a) return a;
172
+ let o, s = -1;
173
+ for (let n of t) {
174
+ let t = _(e, h(n, r), r);
175
+ t !== null && t > s && (s = t, o = n);
176
+ }
177
+ return o === void 0 ? t[0] ?? {} : o;
178
+ }
179
+ function h(e, t) {
180
+ let n = e.$ref;
181
+ return typeof n == "string" ? t.resolve(n) : e;
182
+ }
183
+ function g(e) {
184
+ if ("const" in e) return e.const;
185
+ let t = e.enum;
186
+ if (Array.isArray(t) && t.length === 1) return t[0];
187
+ }
188
+ function te(e, t, n) {
189
+ if (typeof e != "object" || !e || Array.isArray(e)) return;
190
+ let r = e, i = t.map((e) => h(e, n)), a = /* @__PURE__ */ new Set();
191
+ for (let e of i) {
192
+ let t = e.properties;
193
+ if (t) for (let [e, n] of Object.entries(t)) g(n) !== void 0 && a.add(e);
194
+ }
195
+ for (let o of a) {
196
+ let a = i.map((e) => {
197
+ let t = e.properties?.[o];
198
+ return t ? g(t) : void 0;
199
+ }), s = a.filter((e) => e !== void 0), c = new Set(s);
200
+ if (s.length < 2 || c.size !== s.length) continue;
201
+ let l = r[o];
202
+ if (l === void 0) continue;
203
+ let u = a.findIndex((e) => e === l);
204
+ if (u !== -1 && _(e, i[u], n) !== null) return t[u];
205
+ }
75
206
  }
76
- function v(e, t, n) {
77
- const r = n.registry.resolve(t);
78
- if (r)
79
- return r.encode(e, t, n);
80
- const o = t.$ref;
81
- if (typeof o == "string") {
82
- const a = n.resolve(o);
83
- return v(e, a, n);
84
- }
85
- const i = t.oneOf;
86
- if (Array.isArray(i)) {
87
- const a = le(e, i, t);
88
- return v(e, a, n);
89
- }
90
- const s = t.type;
91
- if (s === "array") {
92
- if (!Array.isArray(e))
93
- return _(e, t, n);
94
- const a = t.items;
95
- if (!a)
96
- return e.map((c) => w(c));
97
- const f = n.path;
98
- return Array.isArray(a) ? e.map((c, u) => {
99
- const p = a[u];
100
- return p === void 0 ? w(c) : v(c, p, { ...n, path: `${f}/${u}` });
101
- }) : e.map(
102
- (c, u) => v(c, a, { ...n, path: `${f}/${u}` })
103
- );
104
- }
105
- if (s === "object") {
106
- if (e === null || typeof e != "object" || Array.isArray(e))
107
- return _(e, t, n);
108
- const a = t.properties;
109
- if (!a)
110
- return w(e);
111
- const f = n.path, c = {};
112
- for (const [u, p] of Object.entries(a)) {
113
- const d = e[u];
114
- d !== void 0 && (c[u] = v(d, p, {
115
- ...n,
116
- path: `${f}/${u}`
117
- }));
118
- }
119
- return c;
120
- }
121
- return s == null ? _(e, t, n) : w(e);
122
- }
123
- function $(e, t, n) {
124
- const r = n.registry.resolve(t);
125
- if (r)
126
- return r.decode(e, t, n);
127
- const o = t.$ref;
128
- if (typeof o == "string") {
129
- const a = n.resolve(o);
130
- return $(e, a, n);
131
- }
132
- const i = t.oneOf;
133
- if (Array.isArray(i)) {
134
- const a = le(e, i, t);
135
- return $(e, a, n);
136
- }
137
- const s = t.type;
138
- if (s === "array") {
139
- if (!Array.isArray(e))
140
- return e;
141
- const a = t.items;
142
- if (!a)
143
- return e;
144
- const f = n.path;
145
- return Array.isArray(a) ? e.map((c, u) => {
146
- const p = a[u];
147
- return p === void 0 ? c : $(c, p, { ...n, path: `${f}/${u}` });
148
- }) : e.map(
149
- (c, u) => $(c, a, { ...n, path: `${f}/${u}` })
150
- );
151
- }
152
- if (s === "object") {
153
- if (e === null || typeof e != "object" || Array.isArray(e))
154
- return e;
155
- const a = t.properties;
156
- if (!a)
157
- return e;
158
- const f = n.path, c = {};
159
- for (const [u, p] of Object.entries(a)) {
160
- const d = e[u];
161
- d !== void 0 && (c[u] = $(d, p, {
162
- ...n,
163
- path: `${f}/${u}`
164
- }));
165
- }
166
- return c;
167
- }
168
- return s == null ? Ne(e, n) : e;
169
- }
170
- function le(e, t, n, r) {
171
- const o = n.discriminator;
172
- if (o != null && o.propertyName) {
173
- const i = e !== null && typeof e == "object" ? e[o.propertyName] : void 0;
174
- if (typeof i == "string" && o.mapping) {
175
- const s = o.mapping[i];
176
- if (s) {
177
- const a = t.find((f) => f.$ref === s);
178
- if (a)
179
- return a;
180
- }
181
- }
182
- }
183
- return t[0] ?? {};
207
+ function ne(e) {
208
+ if (e === null) return "null";
209
+ if (Array.isArray(e)) return "array";
210
+ let t = typeof e;
211
+ return t === "number" ? Number.isInteger(e) ? "integer" : "number" : t;
184
212
  }
185
213
  function _(e, t, n) {
186
- for (const r of n.registry.ids()) {
187
- const o = n.registry.get(r);
188
- if (o)
189
- try {
190
- const i = o.encode(e, o.schema, n);
191
- return { [x]: r, v: i };
192
- } catch {
193
- }
194
- }
195
- return w(e);
196
- }
197
- function Ne(e, t) {
198
- if (e !== null && typeof e == "object" && !Array.isArray(e) && x in e) {
199
- const n = e, r = n[x], o = t.registry.get(r);
200
- if (o)
201
- return o.decode(n.v, o.schema, t);
202
- }
203
- return e;
204
- }
205
- function w(e) {
206
- if (e === null || typeof e == "string" || typeof e == "number" || typeof e == "boolean")
207
- return e;
208
- if (Array.isArray(e))
209
- return e.map(w);
210
- if (typeof e == "object") {
211
- const t = {};
212
- for (const [n, r] of Object.entries(e))
213
- r !== void 0 && (t[n] = w(r));
214
- return t;
215
- }
216
- return null;
217
- }
218
- function Ee(e) {
219
- return {
220
- encode(t, n, r) {
221
- const o = G(e, r);
222
- return v(t, n, o);
223
- },
224
- decode(t, n, r) {
225
- const o = G(e, r);
226
- return $(t, n, o);
227
- }
228
- };
229
- }
230
- const F = {
231
- id: "date-time",
232
- kind: "scalar",
233
- schema: { type: "string", format: "date-time" },
234
- matches(e) {
235
- return e.type === "string" && e.format === "date-time";
236
- },
237
- encode(e, t, n) {
238
- return e.toISOString();
239
- },
240
- decode(e, t, n) {
241
- if (typeof e != "string") {
242
- if (n.mode === "strict")
243
- throw new TypeError(
244
- `[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`
245
- );
246
- return new Date(String(e));
247
- }
248
- if (n.mode === "strict" && Number.isNaN(new Date(e).getTime()))
249
- throw new TypeError(
250
- `[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`
251
- );
252
- return new Date(e);
253
- }
254
- }, q = {
255
- id: "int64",
256
- kind: "scalar",
257
- schema: { type: "string", format: "int64" },
258
- matches(e) {
259
- return e.type === "string" && e.format === "int64";
260
- },
261
- encode(e, t, n) {
262
- return String(e);
263
- },
264
- decode(e, t, n) {
265
- if (typeof e != "string") {
266
- if (n.mode === "strict")
267
- throw new TypeError(
268
- `[int64] expected a string on the wire at "${n.path}", got ${typeof e}`
269
- );
270
- try {
271
- return BigInt(Math.trunc(Number(e)));
272
- } catch {
273
- return BigInt(0);
274
- }
275
- }
276
- if (n.mode === "strict")
277
- return BigInt(e);
278
- if (/^-?\d+$/.test(e))
279
- try {
280
- return BigInt(e);
281
- } catch {
282
- return BigInt(0);
283
- }
284
- return BigInt(0);
285
- }
286
- }, K = {
287
- id: "decimal",
288
- kind: "scalar",
289
- schema: { type: "string", format: "decimal" },
290
- matches(e) {
291
- return e.type === "string" && e.format === "decimal";
292
- },
293
- encode(e, t, n) {
294
- return e;
295
- },
296
- decode(e, t, n) {
297
- if (typeof e != "string") {
298
- if (n.mode === "strict")
299
- throw new TypeError(
300
- `[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`
301
- );
302
- return String(e);
303
- }
304
- if (n.mode === "strict" && !/^-?\d+(\.\d+)?$/.test(e))
305
- throw new TypeError(
306
- `[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`
307
- );
308
- return e;
309
- }
310
- }, z = {
311
- id: "byte",
312
- kind: "scalar",
313
- schema: { type: "string", format: "byte" },
314
- matches(e) {
315
- return e.type === "string" && e.format === "byte";
316
- },
317
- encode(e, t, n) {
318
- return Buffer.from(e).toString("base64");
319
- },
320
- decode(e, t, n) {
321
- if (typeof e != "string") {
322
- if (n.mode === "strict")
323
- throw new TypeError(
324
- `[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`
325
- );
326
- return new Uint8Array(0);
327
- }
328
- if (n.mode === "strict" && !/^[A-Za-z0-9+/]*={0,2}$/.test(e))
329
- throw new TypeError(
330
- `[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`
331
- );
332
- return new Uint8Array(Buffer.from(e, "base64"));
333
- }
334
- }, _e = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, H = {
335
- id: "uuid",
336
- kind: "scalar",
337
- schema: { type: "string", format: "uuid" },
338
- matches(e) {
339
- return e.type === "string" && e.format === "uuid";
340
- },
341
- encode(e, t, n) {
342
- return e.toLowerCase();
343
- },
344
- decode(e, t, n) {
345
- if (typeof e != "string") {
346
- if (n.mode === "strict")
347
- throw new TypeError(
348
- `[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`
349
- );
350
- return String(e).toLowerCase();
351
- }
352
- if (n.mode === "strict" && !_e.test(e))
353
- throw new TypeError(
354
- `[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`
355
- );
356
- return e;
357
- }
358
- }, T = "NaN", P = "Infinity", D = "-Infinity", ke = /* @__PURE__ */ new Set([
359
- T,
360
- P,
361
- D
362
- ]), W = {
363
- id: "number-special",
364
- kind: "scalar",
365
- schema: { type: "number" },
366
- matches(e) {
367
- return e.type === "number" && e.format === void 0;
368
- },
369
- encode(e, t, n) {
370
- return Number.isNaN(e) ? T : e === 1 / 0 ? P : e === -1 / 0 ? D : e;
371
- },
372
- decode(e, t, n) {
373
- if (typeof e == "number")
374
- return e;
375
- if (typeof e == "string") {
376
- if (e === T)
377
- return NaN;
378
- if (e === P)
379
- return 1 / 0;
380
- if (e === D)
381
- return -1 / 0;
382
- const r = Number(e);
383
- if (!Number.isNaN(r))
384
- return r;
385
- }
386
- if (n.mode === "strict")
387
- throw new TypeError(
388
- `[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...ke].join(", ")}.`
389
- );
390
- return NaN;
391
- }
392
- }, Ie = [
393
- F,
394
- q,
395
- K,
396
- z,
397
- H,
398
- W
214
+ let r = t.oneOf;
215
+ if (Array.isArray(r)) {
216
+ let t = null;
217
+ for (let i of r) {
218
+ let r = _(e, h(i, n), n);
219
+ r !== null && (t === null || r > t) && (t = r);
220
+ }
221
+ return t;
222
+ }
223
+ let i = t.type, a = ne(e);
224
+ if (typeof i == "string") {
225
+ if (!(i === a || i === "number" && a === "integer")) return null;
226
+ } else if (Array.isArray(i) && !i.some((e) => e === a || e === "number" && a === "integer")) return null;
227
+ if (typeof e != "object" || !e || Array.isArray(e)) return +(typeof i == "string");
228
+ let o = e, s = t.required, c = 0;
229
+ if (Array.isArray(s)) {
230
+ for (let e of s) if (typeof e == "string") {
231
+ if (o[e] === void 0) return null;
232
+ c += 2;
233
+ }
234
+ }
235
+ let l = t.properties;
236
+ if (l) {
237
+ for (let e of Object.keys(l)) o[e] !== void 0 && (c += 1);
238
+ for (let e of Object.keys(o)) l[e] === void 0 && --c;
239
+ }
240
+ return c;
241
+ }
242
+ function v(e, t, n) {
243
+ for (let t of n.registry.ids()) {
244
+ let r = n.registry.get(t);
245
+ if (r?.ownsValue?.(e)) return {
246
+ [i]: t,
247
+ v: r.encode(e, r.schema, n)
248
+ };
249
+ }
250
+ if (Array.isArray(e)) return e.map((e) => v(e, {}, n));
251
+ if (re(e)) {
252
+ let t = {};
253
+ for (let [r, i] of Object.entries(e)) i !== void 0 && (t[r] = v(i, {}, n));
254
+ return t;
255
+ }
256
+ return b(e);
257
+ }
258
+ function re(e) {
259
+ if (typeof e != "object" || !e || Array.isArray(e)) return !1;
260
+ let t = Object.getPrototypeOf(e);
261
+ return t === Object.prototype || t === null;
262
+ }
263
+ function y(e, t) {
264
+ if (typeof e == "object" && e && !Array.isArray(e) && "$apigen" in e) {
265
+ let n = e, r = n[i], a = t.registry.get(r);
266
+ if (a) return a.decode(n.v, a.schema, t);
267
+ }
268
+ if (Array.isArray(e)) return e.map((e) => y(e, t));
269
+ if (re(e)) {
270
+ let n = {};
271
+ for (let [r, i] of Object.entries(e)) n[r] = y(i, t);
272
+ return n;
273
+ }
274
+ return e;
275
+ }
276
+ function b(e) {
277
+ if (e === null || typeof e == "string" || typeof e == "number" || typeof e == "boolean") return e;
278
+ if (Array.isArray(e)) return e.map(b);
279
+ if (typeof e == "object") {
280
+ let t = {};
281
+ for (let [n, r] of Object.entries(e)) r !== void 0 && (t[n] = b(r));
282
+ return t;
283
+ }
284
+ return null;
285
+ }
286
+ function ie(e, t) {
287
+ let n = /* @__PURE__ */ new Set(), r = [e];
288
+ for (; r.length > 0;) {
289
+ let e = r.pop();
290
+ if (!e || n.has(e)) continue;
291
+ n.add(e);
292
+ let i = e.$ref;
293
+ if (typeof i == "string") {
294
+ if (t) {
295
+ let e = t[i];
296
+ if (!e) {
297
+ let e = Object.keys(t).join(", ") || "(none)";
298
+ throw Error(`[apigen-logical] $ref "${i}" cannot be resolved. Available $defs: ${e}`);
299
+ }
300
+ r.push(e);
301
+ }
302
+ continue;
303
+ }
304
+ let a = e.oneOf;
305
+ if (Array.isArray(a)) for (let e of a) typeof e == "object" && e && r.push(e);
306
+ let o = e.properties;
307
+ if (o) for (let e of Object.values(o)) r.push(e);
308
+ let s = e.items;
309
+ if (Array.isArray(s)) for (let e of s) typeof e == "object" && e && r.push(e);
310
+ else typeof s == "object" && s && r.push(s);
311
+ let c = e.additionalProperties;
312
+ typeof c == "object" && c && r.push(c);
313
+ let l = e.propertyNames;
314
+ typeof l == "object" && l && r.push(l);
315
+ }
316
+ }
317
+ function ae(e) {
318
+ return {
319
+ encode(t, n, r) {
320
+ return p(t, n, f(e, r));
321
+ },
322
+ decode(t, n, r) {
323
+ return m(t, n, f(e, r));
324
+ }
325
+ };
326
+ }
327
+ //#endregion
328
+ //#region ../apigen-base-logical/src/lib/codecs/date-time.ts
329
+ var x = {
330
+ id: "date-time",
331
+ kind: "scalar",
332
+ schema: {
333
+ type: "string",
334
+ format: "date-time"
335
+ },
336
+ matches(e) {
337
+ return e.type === "string" && e.format === "date-time";
338
+ },
339
+ ownsValue(e) {
340
+ return e instanceof Date;
341
+ },
342
+ encode(e, t, n) {
343
+ return e.toISOString();
344
+ },
345
+ decode(e, t, n) {
346
+ if (typeof e != "string") {
347
+ if (n.mode === "strict") throw TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`);
348
+ return new Date(String(e));
349
+ }
350
+ if (n.mode === "strict" && Number.isNaN(new Date(e).getTime())) throw TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);
351
+ return new Date(e);
352
+ }
353
+ }, S = {
354
+ id: "int64",
355
+ kind: "scalar",
356
+ schema: {
357
+ type: "string",
358
+ format: "int64"
359
+ },
360
+ matches(e) {
361
+ return e.type === "string" && e.format === "int64";
362
+ },
363
+ ownsValue(e) {
364
+ return typeof e == "bigint";
365
+ },
366
+ encode(e, t, n) {
367
+ return String(e);
368
+ },
369
+ decode(e, t, n) {
370
+ if (typeof e != "string") {
371
+ if (n.mode === "strict") throw TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof e}`);
372
+ try {
373
+ return BigInt(Math.trunc(Number(e)));
374
+ } catch {
375
+ return BigInt(0);
376
+ }
377
+ }
378
+ if (n.mode === "strict") return BigInt(e);
379
+ if (/^-?\d+$/.test(e)) try {
380
+ return BigInt(e);
381
+ } catch {
382
+ return BigInt(0);
383
+ }
384
+ return BigInt(0);
385
+ }
386
+ };
387
+ //#endregion
388
+ //#region ../apigen-base-logical/src/lib/codecs/decimal.ts
389
+ function C(e) {
390
+ return e;
391
+ }
392
+ var w = {
393
+ id: "decimal",
394
+ kind: "scalar",
395
+ schema: {
396
+ type: "string",
397
+ format: "decimal"
398
+ },
399
+ matches(e) {
400
+ return e.type === "string" && e.format === "decimal";
401
+ },
402
+ encode(e, t, n) {
403
+ return e;
404
+ },
405
+ decode(e, t, n) {
406
+ if (typeof e != "string") {
407
+ if (n.mode === "strict") throw TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);
408
+ return C(String(e));
409
+ }
410
+ if (n.mode === "strict" && !/^-?\d+(\.\d+)?$/.test(e)) throw TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);
411
+ return C(e);
412
+ }
413
+ }, T = {
414
+ id: "byte",
415
+ kind: "scalar",
416
+ schema: {
417
+ type: "string",
418
+ format: "byte"
419
+ },
420
+ matches(e) {
421
+ return e.type === "string" && e.format === "byte";
422
+ },
423
+ ownsValue(e) {
424
+ return e instanceof Uint8Array;
425
+ },
426
+ encode(e, t, n) {
427
+ return Buffer.from(e).toString("base64");
428
+ },
429
+ decode(e, t, n) {
430
+ if (typeof e != "string") {
431
+ if (n.mode === "strict") throw TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);
432
+ return /* @__PURE__ */ new Uint8Array();
433
+ }
434
+ if (n.mode === "strict" && !/^[A-Za-z0-9+/]*={0,2}$/.test(e)) throw TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);
435
+ return new Uint8Array(Buffer.from(e, "base64"));
436
+ }
437
+ }, oe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, E = {
438
+ id: "uuid",
439
+ kind: "scalar",
440
+ schema: {
441
+ type: "string",
442
+ format: "uuid"
443
+ },
444
+ matches(e) {
445
+ return e.type === "string" && e.format === "uuid";
446
+ },
447
+ encode(e, t, n) {
448
+ return e.toLowerCase();
449
+ },
450
+ decode(e, t, n) {
451
+ if (typeof e != "string") {
452
+ if (n.mode === "strict") throw TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);
453
+ return String(e).toLowerCase();
454
+ }
455
+ if (n.mode === "strict" && !oe.test(e)) throw TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);
456
+ return e;
457
+ }
458
+ }, D = "NaN", O = "Infinity", k = "-Infinity", se = /* @__PURE__ */ new Set([
459
+ D,
460
+ O,
461
+ k
462
+ ]), A = {
463
+ id: "number-special",
464
+ kind: "scalar",
465
+ schema: { type: "number" },
466
+ matches(e) {
467
+ return e.type === "number" && e.format === void 0;
468
+ },
469
+ ownsValue(e) {
470
+ return typeof e == "number" && !Number.isFinite(e);
471
+ },
472
+ encode(e, t, n) {
473
+ return Number.isNaN(e) ? D : e === Infinity ? O : e === -Infinity ? k : e;
474
+ },
475
+ decode(e, t, n) {
476
+ if (typeof e == "number") return e;
477
+ if (typeof e == "string") {
478
+ if (e === D) return NaN;
479
+ if (e === O) return Infinity;
480
+ if (e === k) return -Infinity;
481
+ let t = Number(e);
482
+ if (!Number.isNaN(t)) return t;
483
+ }
484
+ if (n.mode === "strict") throw TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...se].join(", ")}.`);
485
+ return NaN;
486
+ }
487
+ }, ce = [
488
+ x,
489
+ S,
490
+ w,
491
+ T,
492
+ E,
493
+ A
399
494
  ];
400
- function Ce(e, t = {}) {
401
- for (const n of Ie)
402
- e.register(n, { override: t.override ?? !1 });
495
+ function le(e, t = {}) {
496
+ for (let n of ce) e.register(n, { override: t.override ?? !1 });
497
+ }
498
+ //#endregion
499
+ //#region ../apigen-base-logical/src/lib/example.ts
500
+ var ue = 12;
501
+ function de(e, t) {
502
+ let n = /^#\/(definitions|\$defs)\/(.+)$/.exec(e);
503
+ if (!n) return;
504
+ let [, r, i] = n;
505
+ return (r === "$defs" ? t.$defs : t.definitions)?.[decodeURIComponent(i)];
403
506
  }
404
- const xe = 12;
405
- function Se(e, t) {
406
- const n = /^#\/(definitions|\$defs)\/(.+)$/.exec(e);
407
- if (!n)
408
- return;
409
- const [, r, o] = n, i = r === "$defs" ? t.$defs : t.definitions;
410
- return i == null ? void 0 : i[decodeURIComponent(o)];
507
+ function fe(e) {
508
+ return Array.isArray(e) && e.length > 0 ? e[0] : void 0;
411
509
  }
412
- function Y(e) {
413
- return Array.isArray(e) && e.length > 0 ? e[0] : void 0;
510
+ function pe(e) {
511
+ if (Array.isArray(e.type)) return e.type.find((e) => e !== "null") ?? e.type[0];
512
+ if (typeof e.type == "string") return e.type;
513
+ if (e.properties) return "object";
514
+ }
515
+ function me(e) {
516
+ switch (e.format) {
517
+ case "date-time": return "1970-01-01T00:00:00.000Z";
518
+ case "date": return "1970-01-01";
519
+ case "time": return "00:00:00Z";
520
+ case "uuid": return "00000000-0000-0000-0000-000000000000";
521
+ case "email": return "user@example.com";
522
+ case "uri":
523
+ case "url":
524
+ case "uri-reference": return "https://example.com";
525
+ case "hostname": return "example.com";
526
+ case "ipv4": return "127.0.0.1";
527
+ case "ipv6": return "::1";
528
+ case "decimal": return "0";
529
+ case "int64": return "0";
530
+ case "byte": return "";
531
+ default: return "<string>";
532
+ }
533
+ }
534
+ function he(e, t, n) {
535
+ let r = e.properties ?? {}, i = e.required ?? [], a = {};
536
+ for (let e of i) {
537
+ let i = r[e];
538
+ a[e] = i === void 0 ? `<${e}>` : j(i, t, n + 1);
539
+ }
540
+ return a;
541
+ }
542
+ function ge(e, t, n) {
543
+ let r = Array.isArray(e.items) ? e.items[0] : e.items;
544
+ return r ? [j(r, t, n + 1)] : [];
545
+ }
546
+ function j(e, t = e ?? {}, n = 0) {
547
+ if (!e || n > ue) return null;
548
+ if (typeof e.$ref == "string") {
549
+ let r = de(e.$ref, t);
550
+ return r === void 0 ? null : j(r, t, n + 1);
551
+ }
552
+ if (e.const !== void 0) return e.const;
553
+ if (Array.isArray(e.enum) && e.enum.length > 0) return e.enum[0];
554
+ if (Array.isArray(e.allOf) && e.allOf.length > 0) {
555
+ let r = {}, i = [];
556
+ for (let t of e.allOf) {
557
+ Object.assign(r, t.properties ?? {});
558
+ for (let e of t.required ?? []) i.includes(e) || i.push(e);
559
+ }
560
+ return he({
561
+ ...e,
562
+ properties: r,
563
+ required: i
564
+ }, t, n);
565
+ }
566
+ let r = fe(e.oneOf) ?? fe(e.anyOf);
567
+ if (r) return j(r, t, n + 1);
568
+ switch (pe(e)) {
569
+ case "object": return he(e, t, n);
570
+ case "array": return ge(e, t, n);
571
+ case "string": return me(e);
572
+ case "integer":
573
+ case "number": return 0;
574
+ case "boolean": return !1;
575
+ case "null": return null;
576
+ default: return null;
577
+ }
578
+ }
579
+ function _e(e) {
580
+ if (!e) return;
581
+ let t = j(e);
582
+ return `Example: ${JSON.stringify(t)}`;
583
+ }
584
+ x.id, S.id, w.id, T.id, E.id, A.id, Object.freeze({
585
+ typescript: {
586
+ "date-time": {
587
+ encode: "$.toISOString()",
588
+ decode: "new Date($)",
589
+ mode: "native"
590
+ },
591
+ int64: {
592
+ encode: "String($)",
593
+ decode: "BigInt($)",
594
+ mode: "native"
595
+ },
596
+ decimal: {
597
+ encode: "$.toString()",
598
+ decode: "new Decimal($)",
599
+ imports: [],
600
+ dep: {
601
+ name: "decimal.js",
602
+ version: "^10"
603
+ },
604
+ mode: "branded"
605
+ },
606
+ byte: {
607
+ encode: "Buffer.from($).toString('base64')",
608
+ decode: "new Uint8Array(Buffer.from($, 'base64'))",
609
+ mode: "native"
610
+ },
611
+ uuid: {
612
+ encode: "$.toLowerCase()",
613
+ decode: "$",
614
+ mode: "native"
615
+ },
616
+ "number-special": {
617
+ encode: "numToWire($)",
618
+ decode: "wireToNum($)",
619
+ mode: "native"
620
+ }
621
+ },
622
+ python: {
623
+ "date-time": {
624
+ encode: "$.isoformat()",
625
+ decode: "datetime.fromisoformat($)",
626
+ imports: ["from datetime import datetime"],
627
+ mode: "native"
628
+ },
629
+ int64: {
630
+ encode: "str($)",
631
+ decode: "int($)",
632
+ mode: "native"
633
+ },
634
+ decimal: {
635
+ encode: "str($)",
636
+ decode: "Decimal($)",
637
+ imports: ["from decimal import Decimal"],
638
+ mode: "native"
639
+ },
640
+ byte: {
641
+ encode: "b64encode($).decode()",
642
+ decode: "b64decode($)",
643
+ imports: ["from base64 import b64encode, b64decode"],
644
+ mode: "native"
645
+ },
646
+ uuid: {
647
+ encode: "str($)",
648
+ decode: "UUID($)",
649
+ imports: ["from uuid import UUID"],
650
+ mode: "native"
651
+ },
652
+ "number-special": {
653
+ encode: "num_to_wire($)",
654
+ decode: "wire_to_num($)",
655
+ mode: "native"
656
+ }
657
+ },
658
+ rust: {
659
+ "date-time": {
660
+ encode: "__SCAFFOLD_RUST_DATETIME_ENCODE__",
661
+ decode: "__SCAFFOLD_RUST_DATETIME_DECODE__",
662
+ imports: ["use chrono::{DateTime, Utc};"],
663
+ dep: {
664
+ name: "chrono",
665
+ version: "^0.4"
666
+ },
667
+ mode: "lib"
668
+ },
669
+ int64: {
670
+ encode: "__SCAFFOLD_RUST_INT64_ENCODE__",
671
+ decode: "__SCAFFOLD_RUST_INT64_DECODE__",
672
+ imports: ["use serde_with::DisplayFromStr;"],
673
+ dep: {
674
+ name: "serde_with",
675
+ version: "^3"
676
+ },
677
+ mode: "lib"
678
+ },
679
+ decimal: {
680
+ encode: "__SCAFFOLD_RUST_DECIMAL_ENCODE__",
681
+ decode: "__SCAFFOLD_RUST_DECIMAL_DECODE__",
682
+ imports: ["use rust_decimal::Decimal;"],
683
+ dep: {
684
+ name: "rust_decimal",
685
+ version: "^1"
686
+ },
687
+ mode: "lib"
688
+ },
689
+ byte: {
690
+ encode: "__SCAFFOLD_RUST_BYTE_ENCODE__",
691
+ decode: "__SCAFFOLD_RUST_BYTE_DECODE__",
692
+ imports: ["use serde_with::base64::Base64;"],
693
+ dep: {
694
+ name: "serde_with",
695
+ version: "^3"
696
+ },
697
+ mode: "lib"
698
+ },
699
+ uuid: {
700
+ encode: "__SCAFFOLD_RUST_UUID_ENCODE__",
701
+ decode: "__SCAFFOLD_RUST_UUID_DECODE__",
702
+ imports: ["use uuid::Uuid;"],
703
+ dep: {
704
+ name: "uuid",
705
+ version: "^1"
706
+ },
707
+ mode: "lib"
708
+ },
709
+ "number-special": {
710
+ encode: "__SCAFFOLD_RUST_NUMSPECIAL_ENCODE__",
711
+ decode: "__SCAFFOLD_RUST_NUMSPECIAL_DECODE__",
712
+ mode: "native"
713
+ }
714
+ },
715
+ go: {
716
+ "date-time": {
717
+ encode: "__SCAFFOLD_GO_DATETIME_ENCODE__",
718
+ decode: "__SCAFFOLD_GO_DATETIME_DECODE__",
719
+ imports: ["\"time\""],
720
+ mode: "native"
721
+ },
722
+ int64: {
723
+ encode: "__SCAFFOLD_GO_INT64_ENCODE__",
724
+ decode: "__SCAFFOLD_GO_INT64_DECODE__",
725
+ imports: ["\"strconv\""],
726
+ mode: "native"
727
+ },
728
+ decimal: {
729
+ encode: "__SCAFFOLD_GO_DECIMAL_ENCODE__",
730
+ decode: "__SCAFFOLD_GO_DECIMAL_DECODE__",
731
+ imports: ["\"github.com/shopspring/decimal\""],
732
+ dep: {
733
+ name: "github.com/shopspring/decimal",
734
+ version: "v1"
735
+ },
736
+ mode: "lib"
737
+ },
738
+ byte: {
739
+ encode: "__SCAFFOLD_GO_BYTE_ENCODE__",
740
+ decode: "__SCAFFOLD_GO_BYTE_DECODE__",
741
+ imports: ["\"encoding/base64\""],
742
+ mode: "native"
743
+ },
744
+ uuid: {
745
+ encode: "__SCAFFOLD_GO_UUID_ENCODE__",
746
+ decode: "__SCAFFOLD_GO_UUID_DECODE__",
747
+ imports: ["\"github.com/google/uuid\""],
748
+ dep: {
749
+ name: "github.com/google/uuid",
750
+ version: "v1"
751
+ },
752
+ mode: "lib"
753
+ },
754
+ "number-special": {
755
+ encode: "__SCAFFOLD_GO_NUMSPECIAL_ENCODE__",
756
+ decode: "__SCAFFOLD_GO_NUMSPECIAL_DECODE__",
757
+ mode: "native"
758
+ }
759
+ },
760
+ java: {
761
+ "date-time": {
762
+ encode: "$.toString()",
763
+ decode: "Instant.parse($)",
764
+ imports: ["import java.time.Instant;"],
765
+ dep: {
766
+ name: "jackson-datatype-jsr310",
767
+ version: "2.x"
768
+ },
769
+ mode: "lib"
770
+ },
771
+ int64: {
772
+ encode: "@JsonFormat(shape = JsonFormat.Shape.STRING)",
773
+ decode: "@JsonFormat(shape = JsonFormat.Shape.STRING)",
774
+ imports: ["import com.fasterxml.jackson.annotation.JsonFormat;"],
775
+ mode: "native"
776
+ },
777
+ decimal: {
778
+ encode: "@JsonSerialize(using = ToStringSerializer.class)",
779
+ decode: "new BigDecimal($)",
780
+ imports: [
781
+ "import java.math.BigDecimal;",
782
+ "import com.fasterxml.jackson.databind.annotation.JsonSerialize;",
783
+ "import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;"
784
+ ],
785
+ mode: "native"
786
+ },
787
+ byte: {
788
+ encode: "$",
789
+ decode: "$",
790
+ mode: "native"
791
+ },
792
+ uuid: {
793
+ encode: "$.toString()",
794
+ decode: "UUID.fromString($)",
795
+ imports: ["import java.util.UUID;"],
796
+ mode: "native"
797
+ },
798
+ "number-special": {
799
+ encode: "@JsonSerialize(using = NumberSpecialSerializer.class)",
800
+ decode: "@JsonDeserialize(using = NumberSpecialDeserializer.class)",
801
+ imports: ["import com.fasterxml.jackson.databind.annotation.JsonSerialize;", "import com.fasterxml.jackson.databind.annotation.JsonDeserialize;"],
802
+ mode: "native"
803
+ }
804
+ }
805
+ });
806
+ //#endregion
807
+ //#region src/lib/dispatch.ts
808
+ var ve = o();
809
+ le(ve);
810
+ var ye = ae(ve.freeze());
811
+ function be(e, t) {
812
+ return t in (e.input?.properties ?? {});
414
813
  }
415
- function Me(e) {
416
- if (Array.isArray(e.type))
417
- return e.type.find((t) => t !== "null") ?? e.type[0];
418
- if (typeof e.type == "string")
419
- return e.type;
420
- if (e.properties)
421
- return "object";
814
+ function xe(e) {
815
+ let t = e.input?.properties?.data;
816
+ return Object.keys(t?.properties ?? {});
422
817
  }
818
+ function Se(e, t) {
819
+ let n = e.input?.properties?.data?.properties?.[t];
820
+ return n === void 0 ? void 0 : n;
821
+ }
822
+ function Ce(e, t) {
823
+ return t === void 0 || e === void 0 ? e : ye.decode(e, t);
824
+ }
825
+ function M(e, t) {
826
+ let n = t.output;
827
+ return !n || Object.keys(n).length === 0 ? e : ye.encode(e, n);
828
+ }
829
+ async function we(e, t, n, r, i, a) {
830
+ let o = xe(n).map((e) => Ce(a[e], Se(n, e)));
831
+ if (be(n, "session") && t) {
832
+ let a = await t({ session: i.session });
833
+ return M(await e[r](a, ...o), n);
834
+ }
835
+ if (n.hasCtx) {
836
+ let a = t ? await t(i) : void 0;
837
+ return M(await e[r](a, ...o), n);
838
+ }
839
+ return M(await e[r](...o), n);
840
+ }
841
+ //#endregion
842
+ //#region src/lib/invoke.ts
843
+ var N = class {
844
+ constructor() {
845
+ this._map = /* @__PURE__ */ new Map();
846
+ }
847
+ set(e, t) {
848
+ this._map.set(e, t);
849
+ }
850
+ get(e) {
851
+ return this._map.get(e);
852
+ }
853
+ has(e) {
854
+ return this._map.has(e);
855
+ }
856
+ };
857
+ function P(e = []) {
858
+ return async function(t, n, r) {
859
+ let i = r.schemas[t];
860
+ if (!i) throw Error(`apigen/invoke: no schema found for operation "${t}"`);
861
+ return e.reduceRight((e, t) => () => t(n, e), () => we(r.fns, r.createClient, i, t, n.envelope, n.domainArgs))();
862
+ };
863
+ }
864
+ //#endregion
865
+ //#region src/lib/define-middleware.ts
423
866
  function Te(e) {
424
- switch (e.format) {
425
- case "date-time":
426
- return "1970-01-01T00:00:00.000Z";
427
- case "date":
428
- return "1970-01-01";
429
- case "time":
430
- return "00:00:00Z";
431
- case "uuid":
432
- return "00000000-0000-0000-0000-000000000000";
433
- case "email":
434
- return "user@example.com";
435
- case "uri":
436
- case "url":
437
- case "uri-reference":
438
- return "https://example.com";
439
- case "hostname":
440
- return "example.com";
441
- case "ipv4":
442
- return "127.0.0.1";
443
- case "ipv6":
444
- return "::1";
445
- case "decimal":
446
- return "0";
447
- case "int64":
448
- return "0";
449
- case "byte":
450
- return "";
451
- default:
452
- return "<string>";
453
- }
454
- }
455
- function Z(e, t, n) {
456
- const r = e.properties ?? {}, o = e.required ?? [], i = {};
457
- for (const s of o) {
458
- const a = r[s];
459
- i[s] = a !== void 0 ? A(a, t, n + 1) : `<${s}>`;
460
- }
461
- return i;
462
- }
463
- function Pe(e, t, n) {
464
- const r = Array.isArray(e.items) ? e.items[0] : e.items;
465
- return r ? [A(r, t, n + 1)] : [];
466
- }
467
- function A(e, t = e ?? {}, n = 0) {
468
- if (!e || n > xe)
469
- return null;
470
- if (typeof e.$ref == "string") {
471
- const o = Se(e.$ref, t);
472
- return o !== void 0 ? A(o, t, n + 1) : null;
473
- }
474
- if (e.const !== void 0)
475
- return e.const;
476
- if (Array.isArray(e.enum) && e.enum.length > 0)
477
- return e.enum[0];
478
- if (Array.isArray(e.allOf) && e.allOf.length > 0) {
479
- const o = {}, i = [];
480
- for (const s of e.allOf) {
481
- Object.assign(o, s.properties ?? {});
482
- for (const a of s.required ?? [])
483
- i.includes(a) || i.push(a);
484
- }
485
- return Z(
486
- { ...e, properties: o, required: i },
487
- t,
488
- n
489
- );
490
- }
491
- const r = Y(e.oneOf) ?? Y(e.anyOf);
492
- if (r)
493
- return A(r, t, n + 1);
494
- switch (Me(e)) {
495
- case "object":
496
- return Z(e, t, n);
497
- case "array":
498
- return Pe(e, t, n);
499
- case "string":
500
- return Te(e);
501
- case "integer":
502
- case "number":
503
- return 0;
504
- case "boolean":
505
- return !1;
506
- case "null":
507
- return null;
508
- default:
509
- return null;
510
- }
511
- }
512
- function de(e) {
513
- if (!e)
514
- return;
515
- const t = A(e);
516
- return `Example: ${JSON.stringify(t)}`;
517
- }
518
- F.id, // 'date-time'
519
- q.id, // 'int64'
520
- K.id, // 'decimal'
521
- z.id, // 'byte'
522
- H.id, // 'uuid'
523
- W.id;
524
- const ye = Oe();
525
- Ce(ye);
526
- const me = Ee(ye.freeze());
527
- function De(e, t) {
528
- var r;
529
- const n = ((r = e.input) == null ? void 0 : r.properties) ?? {};
530
- return t in n;
867
+ return e;
868
+ }
869
+ //#endregion
870
+ //#region src/lib/event-bus.ts
871
+ var F = class {
872
+ constructor() {
873
+ this.handlers = /* @__PURE__ */ new Map();
874
+ }
875
+ on(e, t) {
876
+ let n = this.handlers.get(e) ?? [];
877
+ return this.handlers.set(e, [...n, t]), () => this.off(e, t);
878
+ }
879
+ off(e, t) {
880
+ let n = this.handlers.get(e);
881
+ if (!n) return;
882
+ let r = n.filter((e) => e !== t);
883
+ r.length === 0 ? this.handlers.delete(e) : this.handlers.set(e, r);
884
+ }
885
+ clear() {
886
+ this.handlers.clear();
887
+ }
888
+ async emit(e) {
889
+ for (let [t, n] of this.handlers) if (Ee(t, e)) for (let t of n) await t(e);
890
+ }
891
+ };
892
+ function Ee(e, t) {
893
+ let [n, r, i] = e.split(":");
894
+ return !(n !== "*" && n !== t.module || r && r !== "*" && r !== t.method || i && i !== "*" && i !== t.lifecycle);
895
+ }
896
+ function I(e, t) {
897
+ for (let n of e) if (n.eventMapping) for (let [e, r] of Object.entries(n.eventMapping)) t.on(e, r);
898
+ }
899
+ //#endregion
900
+ //#region src/lib/build-context.ts
901
+ async function L(e, t, n) {
902
+ let r = { ...t };
903
+ for (let t of e) if (t.createContext) {
904
+ await n.emit({
905
+ module: t.id,
906
+ method: "createContext",
907
+ lifecycle: "start",
908
+ ctx: r
909
+ });
910
+ try {
911
+ let e = await t.createContext(r);
912
+ r = {
913
+ ...r,
914
+ ...e
915
+ }, await n.emit({
916
+ module: t.id,
917
+ method: "createContext",
918
+ lifecycle: "complete",
919
+ ctx: r
920
+ });
921
+ } catch (e) {
922
+ throw await n.emit({
923
+ module: t.id,
924
+ method: "createContext",
925
+ lifecycle: "error",
926
+ ctx: r,
927
+ error: e
928
+ }), e;
929
+ }
930
+ }
931
+ return r;
932
+ }
933
+ e(import.meta.url);
934
+ //#endregion
935
+ //#region ../apigen-core-client/src/lib/get-safety.ts
936
+ var R = /* @__PURE__ */ new Set([
937
+ "string",
938
+ "number",
939
+ "boolean",
940
+ "integer"
941
+ ]);
942
+ function De(e) {
943
+ if (typeof e != "object" || !e) return !1;
944
+ let t = e;
945
+ if (t.$ref !== void 0 || t.oneOf || t.anyOf || t.allOf) return !1;
946
+ let { type: n } = t;
947
+ return typeof n == "string" ? R.has(n) : Array.isArray(n) ? n.every((e) => R.has(e) || e === "null") : Array.isArray(t.enum) && t.enum.length > 0 ? t.enum.every((e) => [
948
+ "string",
949
+ "number",
950
+ "boolean"
951
+ ].includes(typeof e)) : !1;
952
+ }
953
+ function z(e) {
954
+ if (!e || typeof e != "object") return !1;
955
+ let t = e.properties;
956
+ return t === void 0 || typeof t != "object" || !t ? !1 : Object.values(t).every(De);
957
+ }
958
+ //#endregion
959
+ //#region ../apigen-core-client/src/lib/compose-schemas.ts
960
+ function Oe(e) {
961
+ let t = {}, n = (e) => {
962
+ for (let n of ["definitions", "$defs"]) {
963
+ let r = e[n];
964
+ if (r) for (let [e, i] of Object.entries(r)) {
965
+ let r = e.startsWith("#/") ? e : `#/${n}/${e}`;
966
+ t[r] = i;
967
+ }
968
+ }
969
+ };
970
+ for (let t of Object.values(e.schemas)) n(t.input), n(t.output);
971
+ if (Object.keys(t).length !== 0) for (let [n, r] of Object.entries(e.schemas)) try {
972
+ ie(r.input, t), ie(r.output, t);
973
+ } catch (e) {
974
+ throw Error(`[apigen-core-client] Schema validation failed for function "${n}": ${e.message}`);
975
+ }
976
+ }
977
+ function ke(e, t) {
978
+ let n = ["apigen calling convention: all domain parameters go inside a \"data\" envelope — e.g. { \"data\": { ... } }" + (t ? "." : " (an empty object for this zero-parameter tool).")];
979
+ return e.length > 0 && n.push(`Field(s) ${e.map((e) => `"${e}"`).join(", ")} are transport-level envelope metadata, NOT domain data — do not nest them under "data". Over MCP they are read from arguments._meta["x-<pluginId>-<field>"] (default pluginId "adhd"); see @adhd/apigen-engine-naming's envelopeMetaKey/envelopeCliFlag/envelopeEnvVar for the HTTP-header / CLI-flag / env-var equivalents.`), n.join(" ");
980
+ }
981
+ function Ae(e, t, n) {
982
+ Oe(e);
983
+ let r = {};
984
+ for (let [i, a] of Object.entries(e.schemas)) {
985
+ let e = n?.[i] ?? {}, o = a.input.properties ?? {}, s = a.input.required ?? [], c = {}, l = [], u = {};
986
+ for (let n of t) if (n.envelope && e[n.id] !== !1) for (let [e, t] of Object.entries(n.envelope)) c[e] = t, u[e] = n.id, l.includes(e) || l.push(e);
987
+ let d = {
988
+ type: "object",
989
+ properties: o,
990
+ additionalProperties: !1,
991
+ ...s.length > 0 ? { required: s } : {}
992
+ }, f = a.safe === !0 || z(a.input), p = a.input.definitions, m = a.input.$defs;
993
+ r[i] = {
994
+ input: {
995
+ type: "object",
996
+ properties: {
997
+ ...c,
998
+ data: d
999
+ },
1000
+ required: [...l, ...s.length > 0 ? ["data"] : []],
1001
+ additionalProperties: !1,
1002
+ description: ke(Object.keys(c), Object.keys(o).length > 0),
1003
+ ...p ? { definitions: p } : {},
1004
+ ...m ? { $defs: m } : {}
1005
+ },
1006
+ output: a.output,
1007
+ ...a.hasCtx ? { hasCtx: !0 } : {},
1008
+ "x-apigen-safe": f,
1009
+ ...Object.keys(u).length > 0 ? { "x-apigen-envelope": u } : {}
1010
+ };
1011
+ }
1012
+ return r;
1013
+ }
1014
+ //#endregion
1015
+ //#region ../apigen-core-client/src/lib/schema-builders/ts-json-schema.ts
1016
+ var je = { "decimal.js": "Decimal" };
1017
+ function Me(e) {
1018
+ return e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
531
1019
  }
532
- function Ue(e) {
533
- var n, r;
534
- const t = (r = (n = e.input) == null ? void 0 : n.properties) == null ? void 0 : r.data;
535
- return Object.keys((t == null ? void 0 : t.properties) ?? {});
1020
+ Object.entries(je).map(([e, t]) => ({
1021
+ pattern: RegExp(`import\\(["'][^"']*${Me(e)}[^"']*["']\\)\\.\\w+`, "g"),
1022
+ key: t
1023
+ }));
1024
+ //#endregion
1025
+ //#region src/lib/types.ts
1026
+ var B = class extends Error {
1027
+ constructor(e) {
1028
+ super(e), this.name = "ConfigurationError";
1029
+ }
1030
+ };
1031
+ //#endregion
1032
+ //#region src/lib/api-package.ts
1033
+ function V(e) {
1034
+ for (let t of e) for (let e of Object.keys(t.eventMapping ?? {})) {
1035
+ let [n] = e.split(":");
1036
+ if (n !== "*" && n === t.id) throw new B(`Middleware "${t.id}" subscribes to its own events via "${e}". This would cause infinite recursion.`);
1037
+ }
1038
+ }
1039
+ function Ne(e) {
1040
+ let { domainSchemas: t, middlewares: n, overrides: r = {}, strict: i = !1 } = e;
1041
+ V(n);
1042
+ for (let e of Object.keys(r)) if (!(e in t.schemas)) {
1043
+ let t = `Override key "${e}" not found in domain schemas.`;
1044
+ if (i) throw new B(t);
1045
+ console.warn("[apigen-runtime]", t);
1046
+ }
1047
+ let a = new Set(n.map((e) => e.id));
1048
+ for (let [e, t] of Object.entries(r)) for (let n of Object.keys(t ?? {})) if (!a.has(n)) {
1049
+ let t = `Override key "${e}.${n}" does not match any declared middleware id.`;
1050
+ if (i) throw new B(t);
1051
+ console.warn("[apigen-runtime]", t);
1052
+ }
1053
+ let o = Ae(t, n, r), s = new F();
1054
+ return I(n, s), {
1055
+ schemas: o,
1056
+ createClient: async (e) => L(n, e, s),
1057
+ dispose: () => s.clear()
1058
+ };
1059
+ }
1060
+ //#endregion
1061
+ //#region src/lib/logger.ts
1062
+ function Pe(e = {}) {
1063
+ let n = e.level ?? "info", r = typeof e.destination == "string" && e.destination.length > 0, i = !r && !!process.stderr.isTTY, a = e.format ?? (i ? "pretty" : "json"), o = { level: n };
1064
+ if (a === "pretty") return o.transport = {
1065
+ target: "pino-pretty",
1066
+ options: {
1067
+ colorize: !r,
1068
+ translateTime: "SYS:HH:MM:ss.l",
1069
+ ignore: "pid,hostname",
1070
+ ...r ? {
1071
+ destination: e.destination,
1072
+ mkdir: !0
1073
+ } : { destination: 2 }
1074
+ }
1075
+ }, t(o);
1076
+ let s = r ? t.destination({
1077
+ dest: e.destination,
1078
+ mkdir: !0,
1079
+ sync: !0
1080
+ }) : t.destination(2);
1081
+ return t(o, s);
1082
+ }
1083
+ //#endregion
1084
+ //#region src/lib/describe-params.ts
1085
+ function Fe(e) {
1086
+ if (e?.type !== "object" || !e.properties) return;
1087
+ let t = Object.entries(e.properties);
1088
+ if (t.length === 0) return;
1089
+ let n = new Set(e.required ?? []);
1090
+ return `{ ${t.map(([e, t]) => `${e}${n.has(e) ? "" : "?"}: ${H(t)}`).join(", ")} }`;
1091
+ }
1092
+ function Ie(e) {
1093
+ return typeof e == "string" ? `'${e}'` : JSON.stringify(e);
1094
+ }
1095
+ function Le(e) {
1096
+ let t = e.enum ?? [];
1097
+ return t.length === 0 ? "unknown" : t.map(Ie).join("|");
536
1098
  }
537
1099
  function Re(e, t) {
538
- var o, i, s;
539
- const n = (s = (i = (o = e.input) == null ? void 0 : o.properties) == null ? void 0 : i.data) == null ? void 0 : s.properties, r = n == null ? void 0 : n[t];
540
- return r !== void 0 ? r : void 0;
541
- }
542
- function Le(e, t) {
543
- return t === void 0 || e === void 0 ? e : me.decode(e, t);
544
- }
545
- function k(e, t) {
546
- const n = t.output;
547
- return !n || Object.keys(n).length === 0 ? e : me.encode(e, n);
548
- }
549
- async function Be(e, t, n, r, o, i) {
550
- const a = Ue(n).map(
551
- (c) => Le(i[c], Re(n, c))
552
- );
553
- if (De(n, "session") && t) {
554
- const c = await t({ session: o.session }), u = await e[r](c, ...a);
555
- return k(u, n);
556
- }
557
- if (n.hasCtx) {
558
- const c = t ? await t(o) : void 0, u = await e[r](c, ...a);
559
- return k(u, n);
560
- }
561
- const f = await e[r](...a);
562
- return k(f, n);
563
- }
564
- class Fe {
565
- constructor() {
566
- this._map = /* @__PURE__ */ new Map();
567
- }
568
- set(t, n) {
569
- this._map.set(t, n);
570
- }
571
- get(t) {
572
- return this._map.get(t);
573
- }
574
- /** Returns true when the token has a stored value. */
575
- has(t) {
576
- return this._map.has(t);
577
- }
578
- }
579
- function qe(e = []) {
580
- return async function(n, r, o) {
581
- const i = o.schemas[n];
582
- if (!i)
583
- throw new Error(
584
- `apigen/invoke: no schema found for operation "${n}"`
585
- );
586
- const s = () => Be(
587
- o.fns,
588
- o.createClient,
589
- i,
590
- n,
591
- r.envelope,
592
- r.domainArgs
593
- );
594
- return e.reduceRight(
595
- (f, c) => () => c(r, f),
596
- s
597
- )();
598
- };
599
- }
600
- function Xt(e) {
601
- return e;
602
- }
603
- class Ke {
604
- constructor() {
605
- this.handlers = /* @__PURE__ */ new Map();
606
- }
607
- /**
608
- * Register a handler. Returns an unsubscribe function — handlers registered
609
- * per-request/per-package MUST be removed (via the returned fn, {@link off},
610
- * or {@link clear}) or they accumulate for the bus's lifetime.
611
- */
612
- on(t, n) {
613
- const r = this.handlers.get(t) ?? [];
614
- return this.handlers.set(t, [...r, n]), () => this.off(t, n);
615
- }
616
- /** Remove a previously registered handler (no-op if absent). */
617
- off(t, n) {
618
- const r = this.handlers.get(t);
619
- if (!r)
620
- return;
621
- const o = r.filter((i) => i !== n);
622
- o.length === 0 ? this.handlers.delete(t) : this.handlers.set(t, o);
623
- }
624
- /** Remove every handler — call on package/server teardown. */
625
- clear() {
626
- this.handlers.clear();
627
- }
628
- async emit(t) {
629
- for (const [n, r] of this.handlers)
630
- if (ze(n, t))
631
- for (const o of r)
632
- await o(t);
633
- }
634
- }
635
- function ze(e, t) {
636
- const [n, r, o] = e.split(":");
637
- return !(n !== "*" && n !== t.module || r && r !== "*" && r !== t.method || o && o !== "*" && o !== t.lifecycle);
638
- }
639
- function He(e, t) {
640
- for (const n of e)
641
- if (n.eventMapping)
642
- for (const [r, o] of Object.entries(n.eventMapping))
643
- t.on(r, o);
644
- }
645
- async function We(e, t, n) {
646
- let r = { ...t };
647
- for (const o of e)
648
- if (o.createContext) {
649
- await n.emit({
650
- module: o.id,
651
- method: "createContext",
652
- lifecycle: "start",
653
- ctx: r
654
- });
655
- try {
656
- const i = await o.createContext(r);
657
- r = { ...r, ...i }, await n.emit({
658
- module: o.id,
659
- method: "createContext",
660
- lifecycle: "complete",
661
- ctx: r
662
- });
663
- } catch (i) {
664
- throw await n.emit({
665
- module: o.id,
666
- method: "createContext",
667
- lifecycle: "error",
668
- ctx: r,
669
- error: i
670
- }), i;
671
- }
672
- }
673
- return r;
674
- }
675
- function X(e, t) {
676
- const n = /* @__PURE__ */ new Set(), r = [e];
677
- for (; r.length > 0; ) {
678
- const o = r.pop();
679
- if (!o || n.has(o))
680
- continue;
681
- n.add(o);
682
- const i = o.$ref;
683
- if (typeof i == "string") {
684
- if (t) {
685
- const p = t[i];
686
- if (!p) {
687
- const d = Object.keys(t).join(", ") || "(none)";
688
- throw new Error(
689
- `[apigen-logical] $ref "${i}" cannot be resolved. Available $defs: ${d}`
690
- );
691
- }
692
- r.push(p);
693
- }
694
- continue;
695
- }
696
- const s = o.oneOf;
697
- if (Array.isArray(s))
698
- for (const p of s)
699
- typeof p == "object" && p !== null && r.push(p);
700
- const a = o.properties;
701
- if (a)
702
- for (const p of Object.values(a))
703
- r.push(p);
704
- const f = o.items;
705
- if (Array.isArray(f))
706
- for (const p of f)
707
- typeof p == "object" && p !== null && r.push(p);
708
- else
709
- typeof f == "object" && f !== null && r.push(f);
710
- const c = o.additionalProperties;
711
- typeof c == "object" && c !== null && r.push(c);
712
- const u = o.propertyNames;
713
- typeof u == "object" && u !== null && r.push(u);
714
- }
715
- }
716
- const Q = /* @__PURE__ */ new Set(["string", "number", "boolean", "integer"]);
1100
+ return e.map((e) => H(e, t)).join(" | ");
1101
+ }
1102
+ function H(e, t = 0) {
1103
+ if (!e) return "unknown";
1104
+ if (e.type === "array") return `${H(e.items, 0)}[]`;
1105
+ if (e.enum) return Le(e);
1106
+ if (e.$ref) return String(e.$ref).split("/").pop() || "object";
1107
+ let n = e.anyOf ?? e.oneOf;
1108
+ return n ? n.length === 0 ? "unknown" : t >= 2 ? Re(n, t - 1) : "union" : t >= 1 && e.type === "object" ? Fe(e) ?? "object" : e.type ?? "object";
1109
+ }
1110
+ function U(e) {
1111
+ let t = (e?.input ?? {}).properties?.data, n = t?.properties ?? {}, r = new Set(t?.required ?? []), i = Object.entries(n).map(([e, t]) => ({
1112
+ name: e,
1113
+ type: H(t, 2),
1114
+ required: r.has(e)
1115
+ }));
1116
+ return {
1117
+ params: i,
1118
+ text: i.map((e) => `${e.name}${e.required ? "" : "?"}: ${e.type}`).join(", ")
1119
+ };
1120
+ }
1121
+ //#endregion
1122
+ //#region src/lib/coerce-query.ts
1123
+ function ze(e) {
1124
+ let t;
1125
+ return t = Array.isArray(e) ? e : e ? [e] : [], t.find((e) => e === "number" || e === "integer" || e === "boolean");
1126
+ }
1127
+ function Be(e, t) {
1128
+ let n = (t?.input ?? {}).properties?.data?.properties ?? {}, r = { ...e };
1129
+ for (let [e, t] of Object.entries(n)) {
1130
+ let n = r[e];
1131
+ if (typeof n != "string") continue;
1132
+ let i = ze(t?.type);
1133
+ if (i === "number" || i === "integer") {
1134
+ let t = Number(n);
1135
+ !Number.isNaN(t) && n.trim() !== "" && (r[e] = t);
1136
+ } else i === "boolean" && (n === "true" ? r[e] = !0 : n === "false" && (r[e] = !1));
1137
+ }
1138
+ return r;
1139
+ }
1140
+ //#endregion
1141
+ //#region src/lib/fn-table.ts
1142
+ var W = /* @__PURE__ */ new Set([
1143
+ "default",
1144
+ "module.exports",
1145
+ "__esModule"
1146
+ ]);
717
1147
  function Ve(e) {
718
- if (typeof e != "object" || e === null)
719
- return !1;
720
- const t = e;
721
- if (t.$ref !== void 0 || t.oneOf || t.anyOf || t.allOf)
722
- return !1;
723
- const { type: n } = t;
724
- return typeof n == "string" ? Q.has(n) : Array.isArray(n) ? n.every((r) => Q.has(r) || r === "null") : Array.isArray(t.enum) && t.enum.length > 0 ? t.enum.every((r) => ["string", "number", "boolean"].includes(typeof r)) : !1;
725
- }
726
- function Je(e) {
727
- if (!e || typeof e != "object")
728
- return !1;
729
- const t = e.properties;
730
- return t === void 0 || typeof t != "object" || t === null ? !1 : Object.values(t).every(
731
- Ve
732
- );
733
- }
1148
+ let t = {}, n = (e, r) => {
1149
+ for (let [i, a] of Object.entries(e)) if (typeof a == "function") {
1150
+ !W.has(i) && !(i in t) && (t[i] = a);
1151
+ let e = a.name;
1152
+ e && !(e in t) && (t[e] = a);
1153
+ } else a && typeof a == "object" && r < 2 && W.has(i) && n(a, r + 1);
1154
+ };
1155
+ return n(e, 0), t;
1156
+ }
1157
+ //#endregion
1158
+ //#region ../apigen-base-errors/src/lib/errors.ts
1159
+ var He = [
1160
+ "invalid_argument",
1161
+ "unauthenticated",
1162
+ "permission_denied",
1163
+ "not_found",
1164
+ "internal"
1165
+ ], G = class extends Error {
1166
+ constructor(e, t, n) {
1167
+ super(t), this.name = "ApiError", this.code = e, this.details = n, Object.setPrototypeOf(this, new.target.prototype);
1168
+ }
1169
+ toJSON() {
1170
+ let e = {
1171
+ code: this.code,
1172
+ message: this.message
1173
+ };
1174
+ return this.details !== void 0 && (e.details = this.details), e;
1175
+ }
1176
+ };
1177
+ function Ue(e) {
1178
+ return typeof e == "object" && !!e && e.name === "ApiError" && He.includes(e.code) && typeof e.toJSON == "function";
1179
+ }
1180
+ function We(e, t, n = 0) {
1181
+ return e === "before-first-chunk" ? {
1182
+ phase: e,
1183
+ error: t
1184
+ } : {
1185
+ phase: e,
1186
+ error: t,
1187
+ chunksDelivered: n
1188
+ };
1189
+ }
1190
+ //#endregion
1191
+ //#region src/lib/validate-layer.ts
1192
+ var K = new n({ allErrors: !0 });
1193
+ r(K);
1194
+ for (let e of [
1195
+ s,
1196
+ c,
1197
+ l,
1198
+ u,
1199
+ "discriminator"
1200
+ ]) K.addKeyword({
1201
+ keyword: e,
1202
+ valid: !0
1203
+ });
1204
+ K.addFormat("decimal", /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);
734
1205
  function Ge(e) {
735
- const t = {}, n = (r) => {
736
- for (const o of ["definitions", "$defs"]) {
737
- const i = r[o];
738
- if (i)
739
- for (const [s, a] of Object.entries(i)) {
740
- const f = s.startsWith("#/") ? s : `#/${o}/${s}`;
741
- t[f] = a;
742
- }
743
- }
744
- };
745
- for (const r of Object.values(e.schemas))
746
- n(r.input), n(r.output);
747
- if (Object.keys(t).length !== 0)
748
- for (const [r, o] of Object.entries(e.schemas))
749
- try {
750
- X(o.input, t), X(o.output, t);
751
- } catch (i) {
752
- throw new Error(
753
- `[apigen-core-client] Schema validation failed for function "${r}": ${i.message}`
754
- );
755
- }
756
- }
757
- function Ye(e, t) {
758
- const n = [
759
- 'apigen calling convention: all domain parameters go inside a "data" envelope — e.g. { "data": { ... } }' + (t ? "." : " (an empty object for this zero-parameter tool).")
760
- ];
761
- return e.length > 0 && n.push(
762
- `Field(s) ${e.map((r) => `"${r}"`).join(", ")} are transport-level envelope metadata, NOT domain data — do not nest them under "data". Over MCP they are read from arguments._meta["x-<pluginId>-<field>"] (default pluginId "adhd"); see @adhd/apigen-engine-naming's envelopeMetaKey/envelopeCliFlag/envelopeEnvVar for the HTTP-header / CLI-flag / env-var equivalents.`
763
- ), n.join(" ");
764
- }
765
- function Ze(e, t, n) {
766
- Ge(e);
767
- const r = {};
768
- for (const [o, i] of Object.entries(e.schemas)) {
769
- const s = (n == null ? void 0 : n[o]) ?? {}, a = i.input.properties ?? {}, f = i.input.required ?? [], c = {}, u = [], p = {};
770
- for (const h of t)
771
- if (h.envelope && s[h.id] !== !1)
772
- for (const [b, ve] of Object.entries(h.envelope))
773
- c[b] = ve, p[b] = h.id, u.includes(b) || u.push(b);
774
- const d = {
775
- type: "object",
776
- properties: a,
777
- additionalProperties: !1,
778
- ...f.length > 0 ? { required: f } : {}
779
- }, m = i.safe === !0 || Je(i.input), l = i.input.definitions, y = i.input.$defs;
780
- r[o] = {
781
- input: {
782
- type: "object",
783
- properties: { ...c, data: d },
784
- required: [
785
- ...u,
786
- ...f.length > 0 ? ["data"] : []
787
- ],
788
- // BUG-APIGEN-017: reject any property that isn't a declared envelope
789
- // field or the "data" wrapper — no silently-ignored junk params.
790
- additionalProperties: !1,
791
- // BUG-APIGEN-020: document the envelope/data calling convention inline.
792
- description: Ye(
793
- Object.keys(c),
794
- Object.keys(a).length > 0
795
- ),
796
- ...l ? { definitions: l } : {},
797
- ...y ? { $defs: y } : {}
798
- },
799
- output: i.output,
800
- // Carry the ctx-param flag through to dispatch (BUG-APIGEN-001).
801
- ...i.hasCtx ? { hasCtx: !0 } : {},
802
- "x-apigen-safe": m,
803
- // DEBT-APIGEN-ENVELOPE-CAPABILITY-UNWIRED-001: field → pluginId map,
804
- // read by `op-plan.ts`'s `computeEnvelopeFields`. Omitted (not an empty
805
- // object) when no middleware contributed an envelope field, matching
806
- // `x-apigen-safe`'s own "absent means nothing to report" convention.
807
- ...Object.keys(p).length > 0 ? { "x-apigen-envelope": p } : {}
808
- };
809
- }
810
- return r;
811
- }
812
- const Xe = {
813
- "decimal.js": "Decimal"
1206
+ return e.map((e) => `${e.instancePath || "(root)"} ${e.message ?? "failed schema check"}`).join("; ");
1207
+ }
1208
+ function Ke(e, t) {
1209
+ let n = _e(t), r = [`Validation failed: ${Ge(e)}`];
1210
+ return n && r.push(n), r.join(" — ");
1211
+ }
1212
+ var qe = async (e, t) => {
1213
+ let n = e.ctx.get(Je);
1214
+ if (n === void 0) return t();
1215
+ let r = n[e.operation.id];
1216
+ if (r === void 0) return t();
1217
+ let i = {
1218
+ data: e.domainArgs,
1219
+ ...e.envelope
1220
+ }, a = K.compile(r.input);
1221
+ if (!a(i)) {
1222
+ let e = a.errors ?? [];
1223
+ throw new G("invalid_argument", Ke(e, r.input), e);
1224
+ }
1225
+ return t();
1226
+ }, Je = Symbol("ValidateSchemasToken");
1227
+ function Ye(e) {
1228
+ return async function(t, n) {
1229
+ let r = e[t.operation.id];
1230
+ if (r === void 0) return n();
1231
+ let i = {
1232
+ data: t.domainArgs,
1233
+ ...t.envelope
1234
+ }, a = K.compile(r.input);
1235
+ if (!a(i)) {
1236
+ let e = a.errors ?? [];
1237
+ throw new G("invalid_argument", Ke(e, r.input), e);
1238
+ }
1239
+ return n();
1240
+ };
1241
+ }
1242
+ //#endregion
1243
+ //#region src/lib/instance-registry.ts
1244
+ function Xe() {
1245
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (e) => {
1246
+ let t = Math.random() * 16 | 0;
1247
+ return (e === "x" ? t : t & 3 | 8).toString(16);
1248
+ });
1249
+ }
1250
+ var Ze = class {
1251
+ constructor(e = {}) {
1252
+ this._store = /* @__PURE__ */ new Map(), this._sweeper = null, this._defaultTtlMs = e.defaultTtlMs;
1253
+ let t = null;
1254
+ t = e.sweepIntervalMs === 0 ? null : e.sweepIntervalMs === void 0 ? this._defaultTtlMs === void 0 ? null : Math.max(1e3, Math.floor(this._defaultTtlMs / 4)) : e.sweepIntervalMs, t !== null && t > 0 && (this._sweeper = setInterval(() => this._sweep(), t), this._sweeper.unref?.());
1255
+ }
1256
+ create(e, t = [], n) {
1257
+ let r = new e(...t), i = Xe(), a = n ?? this._defaultTtlMs, o = a === void 0 ? null : Date.now() + a;
1258
+ return this._store.set(i, {
1259
+ instance: r,
1260
+ expiresAt: o
1261
+ }), { instanceId: i };
1262
+ }
1263
+ get(e) {
1264
+ let t = this._store.get(e);
1265
+ if (!t) throw Error(`[instance-registry] Unknown instanceId: "${e}"`);
1266
+ if (t.expiresAt !== null && Date.now() > t.expiresAt) throw this._evict(e, t), Error(`[instance-registry] Instance "${e}" has expired`);
1267
+ return t.instance;
1268
+ }
1269
+ async dispatch(e, t, n = []) {
1270
+ let r = this.get(e), i = r[t];
1271
+ if (typeof i != "function") throw Error(`[instance-registry] Method "${t}" not found on instance "${e}"`);
1272
+ return i.call(r, ...n);
1273
+ }
1274
+ async dispose(e) {
1275
+ let t = this._store.get(e);
1276
+ t && (this._store.delete(e), await q(t.instance));
1277
+ }
1278
+ async disposeAll() {
1279
+ this._sweeper !== null && (clearInterval(this._sweeper), this._sweeper = null);
1280
+ let e = [...this._store.entries()];
1281
+ this._store.clear(), await Promise.all(e.map(([, e]) => q(e.instance)));
1282
+ }
1283
+ get size() {
1284
+ return this._store.size;
1285
+ }
1286
+ _sweep() {
1287
+ let e = Date.now();
1288
+ for (let [t, n] of this._store) n.expiresAt !== null && e > n.expiresAt && this._evict(t, n);
1289
+ }
1290
+ _evict(e, t) {
1291
+ this._store.delete(e), q(t.instance);
1292
+ }
814
1293
  };
1294
+ async function q(e) {
1295
+ if (typeof e == "object" && e && "dispose" in e) {
1296
+ let t = e.dispose;
1297
+ typeof t == "function" && await t.call(e);
1298
+ }
1299
+ }
1300
+ //#endregion
1301
+ //#region src/lib/stream.ts
815
1302
  function Qe(e) {
816
- return e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
817
- }
818
- Object.entries(Xe).map(([e, t]) => ({
819
- // Matches: import("...{modSpec}...").<anyMemberName> (single or double quotes)
820
- // The module specifier appears inside an absolute path, so we allow any
821
- // characters between the quote and the specifier, and between the specifier
822
- // and the closing quote. The trailing member accessor (`.default`, `.Decimal`,
823
- // …) is matched generically (`\w+`) rather than anchored to one spelling —
824
- // see the doc comment above for why.
825
- pattern: new RegExp(
826
- `import\\(["'][^"']*${Qe(e)}[^"']*["']\\)\\.\\w+`,
827
- "g"
828
- ),
829
- key: t
830
- }));
831
- class U extends Error {
832
- constructor(t) {
833
- super(t), this.name = "ConfigurationError";
834
- }
835
- }
836
- function et(e) {
837
- for (const t of e)
838
- for (const n of Object.keys(t.eventMapping ?? {})) {
839
- const [r] = n.split(":");
840
- if (r !== "*" && r === t.id)
841
- throw new U(
842
- `Middleware "${t.id}" subscribes to its own events via "${n}". This would cause infinite recursion.`
843
- );
844
- }
845
- }
846
- function Qt(e) {
847
- const {
848
- domainSchemas: t,
849
- middlewares: n,
850
- overrides: r = {},
851
- strict: o = !1
852
- } = e;
853
- et(n);
854
- for (const c of Object.keys(r))
855
- if (!(c in t.schemas)) {
856
- const u = `Override key "${c}" not found in domain schemas.`;
857
- if (o)
858
- throw new U(u);
859
- console.warn("[apigen-runtime]", u);
860
- }
861
- const i = new Set(n.map((c) => c.id));
862
- for (const [c, u] of Object.entries(r))
863
- for (const p of Object.keys(u ?? {}))
864
- if (!i.has(p)) {
865
- const d = `Override key "${c}.${p}" does not match any declared middleware id.`;
866
- if (o)
867
- throw new U(d);
868
- console.warn("[apigen-runtime]", d);
869
- }
870
- const s = Ze(
871
- t,
872
- n,
873
- r
874
- ), a = new Ke();
875
- return He(n, a), { schemas: s, createClient: async (c) => We(n, c, a), dispose: () => a.clear() };
876
- }
877
- function en(e = {}) {
878
- const t = e.level ?? "info", n = typeof e.destination == "string" && e.destination.length > 0, r = !n && !!process.stderr.isTTY, o = e.format ?? (r ? "pretty" : "json"), i = { level: t };
879
- if (o === "pretty")
880
- return i.transport = {
881
- target: "pino-pretty",
882
- options: {
883
- colorize: !n,
884
- translateTime: "SYS:HH:MM:ss.l",
885
- ignore: "pid,hostname",
886
- ...n ? { destination: e.destination, mkdir: !0 } : { destination: 2 }
887
- }
888
- }, j(i);
889
- const s = n ? j.destination({ dest: e.destination, mkdir: !0, sync: !0 }) : j.destination(2);
890
- return j(i, s);
891
- }
892
- function he(e) {
893
- return e ? e.type === "array" ? `${he(e.items)}[]` : e.enum ? "enum" : e.$ref ? String(e.$ref).split("/").pop() || "object" : e.anyOf || e.oneOf ? "union" : e.type ?? "object" : "unknown";
1303
+ let { produce: t, signal: n } = e, r = n ?? new AbortController().signal;
1304
+ return { [Symbol.asyncIterator]() {
1305
+ let e = t(r);
1306
+ return {
1307
+ async next() {
1308
+ return r.aborted ? (await e.return(void 0), {
1309
+ done: !0,
1310
+ value: void 0
1311
+ }) : e.next();
1312
+ },
1313
+ async return(t) {
1314
+ return await e.return(t), {
1315
+ done: !0,
1316
+ value: void 0
1317
+ };
1318
+ },
1319
+ async throw(t) {
1320
+ return await e.throw(t), {
1321
+ done: !0,
1322
+ value: void 0
1323
+ };
1324
+ }
1325
+ };
1326
+ } };
1327
+ }
1328
+ async function $e(e) {
1329
+ let t = [];
1330
+ for await (let n of e) t.push(n);
1331
+ return t;
1332
+ }
1333
+ async function et(e) {
1334
+ let t = [];
1335
+ try {
1336
+ for await (let n of e) t.push(n);
1337
+ return {
1338
+ ok: !0,
1339
+ chunks: t
1340
+ };
1341
+ } catch (e) {
1342
+ let n = Ue(e) ? e : new G("internal", e instanceof Error ? e.message : String(e));
1343
+ return t.length === 0 ? {
1344
+ ok: !1,
1345
+ carrier: We("before-first-chunk", n)
1346
+ } : {
1347
+ ok: !1,
1348
+ carrier: We("after-first-chunk", n, t.length)
1349
+ };
1350
+ }
894
1351
  }
895
1352
  function tt(e) {
896
- var a;
897
- const n = (a = ((e == null ? void 0 : e.input) ?? {}).properties) == null ? void 0 : a.data, r = (n == null ? void 0 : n.properties) ?? {}, o = new Set((n == null ? void 0 : n.required) ?? []), i = Object.entries(r).map(([f, c]) => ({
898
- name: f,
899
- type: he(c),
900
- required: o.has(f)
901
- })), s = i.map((f) => `${f.name}${f.required ? "" : "?"}: ${f.type}`).join(", ");
902
- return { params: i, text: s };
903
- }
904
- function nt(e) {
905
- let t;
906
- return Array.isArray(e) ? t = e : e ? t = [e] : t = [], t.find((n) => n === "number" || n === "integer" || n === "boolean");
907
- }
908
- function tn(e, t) {
909
- var i, s;
910
- const r = ((s = (i = ((t == null ? void 0 : t.input) ?? {}).properties) == null ? void 0 : i.data) == null ? void 0 : s.properties) ?? {}, o = { ...e };
911
- for (const [a, f] of Object.entries(r)) {
912
- const c = o[a];
913
- if (typeof c != "string")
914
- continue;
915
- const u = nt(f == null ? void 0 : f.type);
916
- if (u === "number" || u === "integer") {
917
- const p = Number(c);
918
- !Number.isNaN(p) && c.trim() !== "" && (o[a] = p);
919
- } else
920
- u === "boolean" && (c === "true" ? o[a] = !0 : c === "false" && (o[a] = !1));
921
- }
922
- return o;
923
- }
924
- const ee = /* @__PURE__ */ new Set(["default", "module.exports", "__esModule"]);
925
- function nn(e) {
926
- const t = {}, n = (r, o) => {
927
- for (const [i, s] of Object.entries(r))
928
- if (typeof s == "function") {
929
- !ee.has(i) && !(i in t) && (t[i] = s);
930
- const a = s.name;
931
- a && !(a in t) && (t[a] = s);
932
- } else
933
- s && typeof s == "object" && o < 2 && ee.has(i) && n(s, o + 1);
934
- };
935
- return n(e, 0), t;
936
- }
937
- const rt = [
938
- "invalid_argument",
939
- "unauthenticated",
940
- "permission_denied",
941
- "not_found",
942
- "internal"
943
- ];
944
- class E extends Error {
945
- constructor(t, n, r) {
946
- super(n), this.name = "ApiError", this.code = t, this.details = r, Object.setPrototypeOf(this, new.target.prototype);
947
- }
948
- /** Serialise to a plain object suitable for JSON transport. */
949
- toJSON() {
950
- const t = {
951
- code: this.code,
952
- message: this.message
953
- };
954
- return this.details !== void 0 && (t.details = this.details), t;
955
- }
956
- }
957
- function ge(e) {
958
- return typeof e == "object" && e !== null && e.name === "ApiError" && rt.includes(e.code) && typeof e.toJSON == "function";
959
- }
960
- function te(e, t, n = 0) {
961
- return e === "before-first-chunk" ? { phase: e, error: t } : { phase: e, error: t, chunksDelivered: n };
962
- }
963
- const O = new $e({ allErrors: !0 });
964
- Ae(O);
965
- for (const e of [
966
- L,
967
- B,
968
- S,
969
- M,
970
- "discriminator"
971
- ])
972
- O.addKeyword({ keyword: e, valid: !0 });
973
- O.addFormat("decimal", /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);
1353
+ return typeof e == "object" && !!e && Symbol.asyncIterator in e;
1354
+ }
1355
+ //#endregion
1356
+ //#region src/lib/logical/union-codec.ts
1357
+ var J = class extends Error {
1358
+ constructor(e, t) {
1359
+ super(t), this.name = "UnionCodecError", this.code = e;
1360
+ }
1361
+ };
1362
+ function Y(e) {
1363
+ let t = e.discriminator;
1364
+ if (typeof t != "object" || !t || Array.isArray(t)) return;
1365
+ let n = t;
1366
+ if (typeof n.propertyName != "string") return;
1367
+ let r = n.mapping;
1368
+ if (typeof r == "object" && r && !Array.isArray(r)) return {
1369
+ propertyName: n.propertyName,
1370
+ mapping: r
1371
+ };
1372
+ }
1373
+ function nt(e, t) {
1374
+ let n = e[c];
1375
+ if (typeof n == "string") {
1376
+ let e = t.registry.get(n);
1377
+ if (e) return e;
1378
+ }
1379
+ return t.registry.resolve(e);
1380
+ }
1381
+ function rt(e, t, n) {
1382
+ let r = nt(t, n);
1383
+ return r ? r.encode(e, t, n) : e;
1384
+ }
1385
+ function it(e, t, n) {
1386
+ let r = nt(t, n);
1387
+ return r ? r.decode(e, t, n) : e;
1388
+ }
1389
+ function at(e) {
1390
+ let { id: t, schema: n } = e;
1391
+ return {
1392
+ id: t,
1393
+ kind: "union",
1394
+ schema: n,
1395
+ matches(e) {
1396
+ if (e["x-apigen-logical"] === "union") return !0;
1397
+ let t = e.oneOf;
1398
+ return !Array.isArray(t) || t.length === 0 ? !1 : Y(e) !== void 0;
1399
+ },
1400
+ encode(e, n, r) {
1401
+ let i = Y(n);
1402
+ if (!i) throw new J("E_UNION_NO_DISCRIMINATOR", `[${t}] schema node at "${r.path}" has no discriminator.propertyName; cannot dispatch union branch.`);
1403
+ let { propertyName: a, mapping: o } = i, s = e[a];
1404
+ if (s == null) throw new J("E_UNION_NO_DISCRIMINATOR", `[${t}] value at "${r.path}" is missing the discriminator property "${a}".`);
1405
+ let c = String(s), l = o[c];
1406
+ if (!l) throw new J("E_UNION_UNKNOWN_TAG", `[${t}] discriminator tag "${c}" at "${r.path}" is not in the mapping (known: ${Object.keys(o).join(", ")}).`);
1407
+ return rt(e, r.resolve(l), {
1408
+ ...r,
1409
+ path: `${r.path}[${c}]`
1410
+ });
1411
+ },
1412
+ decode(e, n, r) {
1413
+ if (typeof e != "object" || !e || Array.isArray(e)) {
1414
+ let n;
1415
+ throw n = e === null ? "null" : Array.isArray(e) ? "array" : typeof e, new J("E_UNION_INVALID_WIRE", `[${t}] expected a JSON object on the wire at "${r.path}", got ${n}.`);
1416
+ }
1417
+ let i = e, a = Y(n);
1418
+ if (!a) throw new J("E_UNION_NO_DISCRIMINATOR", `[${t}] schema node at "${r.path}" has no discriminator.propertyName; cannot dispatch union branch.`);
1419
+ let { propertyName: o, mapping: s } = a, c = i[o];
1420
+ if (c == null) throw new J("E_UNION_NO_DISCRIMINATOR", `[${t}] wire object at "${r.path}" is missing the discriminator property "${o}".`);
1421
+ let l = String(c), u = s[l];
1422
+ if (!u) throw new J("E_UNION_UNKNOWN_TAG", `[${t}] discriminator tag "${l}" on the wire at "${r.path}" is not in the mapping (known: ${Object.keys(s).join(", ")}).`);
1423
+ return it(e, r.resolve(u), {
1424
+ ...r,
1425
+ path: `${r.path}[${l}]`
1426
+ });
1427
+ }
1428
+ };
1429
+ }
1430
+ var X = class extends Error {
1431
+ constructor(e, t) {
1432
+ super(t), this.name = "NominalCodecError", this.code = e;
1433
+ }
1434
+ };
974
1435
  function ot(e) {
975
- return e.map(
976
- (t) => `${t.instancePath || "(root)"} ${t.message ?? "failed schema check"}`
977
- ).join("; ");
978
- }
979
- function we(e, t) {
980
- const n = de(t), r = [`Validation failed: ${ot(e)}`];
981
- return n && r.push(n), r.join(" — ");
982
- }
983
- const rn = async (e, t) => {
984
- const n = e.ctx.get(it);
985
- if (n === void 0)
986
- return t();
987
- const r = e.operation.id, o = n[r];
988
- if (o === void 0)
989
- return t();
990
- const i = {
991
- data: e.domainArgs,
992
- ...e.envelope
993
- }, s = O.compile(o.input);
994
- if (!s(i)) {
995
- const f = s.errors ?? [];
996
- throw new E(
997
- "invalid_argument",
998
- we(f, o.input),
999
- f
1000
- );
1001
- }
1002
- return t();
1003
- }, it = Symbol("ValidateSchemasToken");
1436
+ let t = e.properties;
1437
+ return t && typeof t == "object" && !Array.isArray(t) ? t : {};
1438
+ }
1004
1439
  function st(e) {
1005
- return async function(n, r) {
1006
- const o = n.operation.id, i = e[o];
1007
- if (i === void 0)
1008
- return r();
1009
- const s = {
1010
- data: n.domainArgs,
1011
- ...n.envelope
1012
- }, a = O.compile(i.input);
1013
- if (!a(s)) {
1014
- const c = a.errors ?? [];
1015
- throw new E(
1016
- "invalid_argument",
1017
- we(c, i.input),
1018
- c
1019
- );
1020
- }
1021
- return r();
1022
- };
1023
- }
1024
- function at() {
1025
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (e) => {
1026
- const t = Math.random() * 16 | 0;
1027
- return (e === "x" ? t : t & 3 | 8).toString(16);
1028
- });
1029
- }
1030
- class on {
1031
- constructor(t = {}) {
1032
- var r, o;
1033
- this._store = /* @__PURE__ */ new Map(), this._sweeper = null, this._defaultTtlMs = t.defaultTtlMs;
1034
- let n = null;
1035
- t.sweepIntervalMs === 0 ? n = null : t.sweepIntervalMs !== void 0 ? n = t.sweepIntervalMs : this._defaultTtlMs !== void 0 ? n = Math.max(1e3, Math.floor(this._defaultTtlMs / 4)) : n = null, n !== null && n > 0 && (this._sweeper = setInterval(() => this._sweep(), n), (o = (r = this._sweeper).unref) == null || o.call(r));
1036
- }
1037
- // ---------------------------------------------------------------------------
1038
- // create — construct + register
1039
- // ---------------------------------------------------------------------------
1040
- /**
1041
- * Construct an instance of `Ctor` with `args` and store it in the registry.
1042
- *
1043
- * @param Ctor - The class to instantiate.
1044
- * @param args - Constructor arguments (positional).
1045
- * @param ttlMs - Per-entry TTL override. Falls back to `defaultTtlMs`.
1046
- * @returns `{ instanceId }` — pass this to `dispatch()` / `get()`.
1047
- */
1048
- create(t, n = [], r) {
1049
- const o = new t(...n), i = at(), s = r ?? this._defaultTtlMs, a = s !== void 0 ? Date.now() + s : null;
1050
- return this._store.set(i, { instance: o, expiresAt: a }), { instanceId: i };
1051
- }
1052
- // ---------------------------------------------------------------------------
1053
- // get — retrieve a live instance
1054
- // ---------------------------------------------------------------------------
1055
- /**
1056
- * Retrieve the instance stored under `instanceId`.
1057
- *
1058
- * @throws When `instanceId` is unknown or the entry has expired.
1059
- */
1060
- get(t) {
1061
- const n = this._store.get(t);
1062
- if (!n)
1063
- throw new Error(
1064
- `[instance-registry] Unknown instanceId: "${t}"`
1065
- );
1066
- if (n.expiresAt !== null && Date.now() > n.expiresAt)
1067
- throw this._evict(t, n), new Error(
1068
- `[instance-registry] Instance "${t}" has expired`
1069
- );
1070
- return n.instance;
1071
- }
1072
- // ---------------------------------------------------------------------------
1073
- // dispatch — call a method on a live instance
1074
- // ---------------------------------------------------------------------------
1075
- /**
1076
- * Look up `instanceId` and call `method` on it with `args`.
1077
- *
1078
- * @throws When `instanceId` is unknown/expired, or `method` is not a function
1079
- * on the instance.
1080
- */
1081
- async dispatch(t, n, r = []) {
1082
- const o = this.get(t), i = o[n];
1083
- if (typeof i != "function")
1084
- throw new Error(
1085
- `[instance-registry] Method "${n}" not found on instance "${t}"`
1086
- );
1087
- return i.call(o, ...r);
1088
- }
1089
- // ---------------------------------------------------------------------------
1090
- // dispose — explicit teardown
1091
- // ---------------------------------------------------------------------------
1092
- /**
1093
- * Remove `instanceId` from the registry and call `instance.dispose()` if the
1094
- * instance exposes one (opt-in lifecycle hook).
1095
- */
1096
- async dispose(t) {
1097
- const n = this._store.get(t);
1098
- n && (this._store.delete(t), await I(n.instance));
1099
- }
1100
- // ---------------------------------------------------------------------------
1101
- // disposeAll — full teardown
1102
- // ---------------------------------------------------------------------------
1103
- /**
1104
- * Dispose every live instance and stop the background sweeper. Call this
1105
- * when the server is shutting down.
1106
- */
1107
- async disposeAll() {
1108
- this._sweeper !== null && (clearInterval(this._sweeper), this._sweeper = null);
1109
- const t = [...this._store.entries()];
1110
- this._store.clear(), await Promise.all(t.map(([, n]) => I(n.instance)));
1111
- }
1112
- // ---------------------------------------------------------------------------
1113
- // size — diagnostic helper
1114
- // ---------------------------------------------------------------------------
1115
- /** Number of live (non-expired) entries currently in the registry. */
1116
- get size() {
1117
- return this._store.size;
1118
- }
1119
- // ---------------------------------------------------------------------------
1120
- // Internal sweeper
1121
- // ---------------------------------------------------------------------------
1122
- _sweep() {
1123
- const t = Date.now();
1124
- for (const [n, r] of this._store)
1125
- r.expiresAt !== null && t > r.expiresAt && this._evict(n, r);
1126
- }
1127
- _evict(t, n) {
1128
- this._store.delete(t), I(n.instance);
1129
- }
1130
- }
1131
- async function I(e) {
1132
- if (e !== null && typeof e == "object" && "dispose" in e) {
1133
- const t = e.dispose;
1134
- typeof t == "function" && await t.call(e);
1135
- }
1136
- }
1137
- function sn(e) {
1138
- const { produce: t, signal: n } = e, r = n ?? new AbortController().signal;
1139
- return {
1140
- [Symbol.asyncIterator]() {
1141
- const o = t(r);
1142
- return {
1143
- async next() {
1144
- return r.aborted ? (await o.return(void 0), { done: !0, value: void 0 }) : o.next();
1145
- },
1146
- async return(i) {
1147
- return await o.return(i), { done: !0, value: void 0 };
1148
- },
1149
- async throw(i) {
1150
- return await o.throw(i), { done: !0, value: void 0 };
1151
- }
1152
- };
1153
- }
1154
- };
1155
- }
1156
- async function an(e) {
1157
- const t = [];
1158
- for await (const n of e)
1159
- t.push(n);
1160
- return t;
1161
- }
1162
- async function ct(e) {
1163
- const t = [];
1164
- try {
1165
- for await (const n of e)
1166
- t.push(n);
1167
- return { ok: !0, chunks: t };
1168
- } catch (n) {
1169
- const r = ge(n) ? n : new E(
1170
- "internal",
1171
- n instanceof Error ? n.message : String(n)
1172
- );
1173
- return t.length === 0 ? {
1174
- ok: !1,
1175
- carrier: te("before-first-chunk", r)
1176
- } : {
1177
- ok: !1,
1178
- carrier: te("after-first-chunk", r, t.length)
1179
- };
1180
- }
1440
+ let t = e.required;
1441
+ return Array.isArray(t) ? t.filter((e) => typeof e == "string") : [];
1442
+ }
1443
+ function ct(e, t, n) {
1444
+ if (t) {
1445
+ let r = n.registry.resolve(t);
1446
+ if (r) return r.encode(e, t, n);
1447
+ }
1448
+ return e;
1449
+ }
1450
+ function lt(e, t, n) {
1451
+ if (t) {
1452
+ let r = n.registry.resolve(t);
1453
+ if (r) return r.decode(e, t, n);
1454
+ }
1455
+ return e;
1181
1456
  }
1182
1457
  function ut(e) {
1183
- return e !== null && typeof e == "object" && Symbol.asyncIterator in e;
1184
- }
1185
- class g extends Error {
1186
- constructor(t, n) {
1187
- super(n), this.name = "UnionCodecError", this.code = t;
1188
- }
1189
- }
1190
- function C(e) {
1191
- const t = e.discriminator;
1192
- if (t === null || typeof t != "object" || Array.isArray(t))
1193
- return;
1194
- const n = t;
1195
- if (typeof n.propertyName != "string")
1196
- return;
1197
- const r = n.mapping;
1198
- if (!(r === null || typeof r != "object" || Array.isArray(r)))
1199
- return {
1200
- propertyName: n.propertyName,
1201
- mapping: r
1202
- };
1203
- }
1204
- function be(e, t) {
1205
- const n = e[B];
1206
- if (typeof n == "string") {
1207
- const r = t.registry.get(n);
1208
- if (r)
1209
- return r;
1210
- }
1211
- return t.registry.resolve(e);
1212
- }
1213
- function ft(e, t, n) {
1214
- const r = be(t, n);
1215
- return r ? r.encode(e, t, n) : e;
1216
- }
1217
- function pt(e, t, n) {
1218
- const r = be(t, n);
1219
- return r ? r.decode(e, t, n) : e;
1220
- }
1221
- function lt(e) {
1222
- const { id: t, schema: n } = e;
1223
- return {
1224
- id: t,
1225
- kind: "union",
1226
- schema: n,
1227
- /**
1228
- * Structural ownership test: the node carries both `oneOf` (non-empty array)
1229
- * and `discriminator.propertyName`. The `x-apigen-logical:"union"` hint
1230
- * accelerates the match but is advisory — the structure is authoritative.
1231
- */
1232
- matches(r) {
1233
- if (r[L] === "union")
1234
- return !0;
1235
- const o = r.oneOf;
1236
- return !Array.isArray(o) || o.length === 0 ? !1 : C(r) !== void 0;
1237
- },
1238
- encode(r, o, i) {
1239
- const s = C(o);
1240
- if (!s)
1241
- throw new g(
1242
- "E_UNION_NO_DISCRIMINATOR",
1243
- `[${t}] schema node at "${i.path}" has no discriminator.propertyName; cannot dispatch union branch.`
1244
- );
1245
- const { propertyName: a, mapping: f } = s, c = r[a];
1246
- if (c == null)
1247
- throw new g(
1248
- "E_UNION_NO_DISCRIMINATOR",
1249
- `[${t}] value at "${i.path}" is missing the discriminator property "${a}".`
1250
- );
1251
- const u = String(c), p = f[u];
1252
- if (!p)
1253
- throw new g(
1254
- "E_UNION_UNKNOWN_TAG",
1255
- `[${t}] discriminator tag "${u}" at "${i.path}" is not in the mapping (known: ${Object.keys(f).join(", ")}).`
1256
- );
1257
- const d = i.resolve(p);
1258
- return ft(r, d, {
1259
- ...i,
1260
- path: `${i.path}[${u}]`
1261
- });
1262
- },
1263
- decode(r, o, i) {
1264
- if (r === null || typeof r != "object" || Array.isArray(r)) {
1265
- let l;
1266
- throw r === null ? l = "null" : Array.isArray(r) ? l = "array" : l = typeof r, new g(
1267
- "E_UNION_INVALID_WIRE",
1268
- `[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`
1269
- );
1270
- }
1271
- const s = r, a = C(o);
1272
- if (!a)
1273
- throw new g(
1274
- "E_UNION_NO_DISCRIMINATOR",
1275
- `[${t}] schema node at "${i.path}" has no discriminator.propertyName; cannot dispatch union branch.`
1276
- );
1277
- const { propertyName: f, mapping: c } = a, u = s[f];
1278
- if (u == null)
1279
- throw new g(
1280
- "E_UNION_NO_DISCRIMINATOR",
1281
- `[${t}] wire object at "${i.path}" is missing the discriminator property "${f}".`
1282
- );
1283
- const p = String(u), d = c[p];
1284
- if (!d)
1285
- throw new g(
1286
- "E_UNION_UNKNOWN_TAG",
1287
- `[${t}] discriminator tag "${p}" on the wire at "${i.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`
1288
- );
1289
- const m = i.resolve(d);
1290
- return pt(r, m, {
1291
- ...i,
1292
- path: `${i.path}[${p}]`
1293
- });
1294
- }
1295
- };
1296
- }
1297
- const dt = "x-apigen-instances";
1298
- class N extends Error {
1299
- constructor(t, n) {
1300
- super(n), this.name = "NominalCodecError", this.code = t;
1301
- }
1302
- }
1303
- function ne(e) {
1304
- const t = e.properties;
1305
- return t && typeof t == "object" && !Array.isArray(t) ? t : {};
1306
- }
1307
- function yt(e) {
1308
- const t = e.required;
1309
- return Array.isArray(t) ? t.filter((n) => typeof n == "string") : [];
1310
- }
1311
- function re(e, t, n) {
1312
- if (t) {
1313
- const r = n.registry.resolve(t);
1314
- if (r)
1315
- return r.encode(e, t, n);
1316
- }
1317
- return e;
1318
- }
1319
- function mt(e, t, n) {
1320
- if (t) {
1321
- const r = n.registry.resolve(t);
1322
- if (r)
1323
- return r.decode(e, t, n);
1324
- }
1325
- return e;
1326
- }
1327
- function ht(e) {
1328
- const { id: t, schema: n, ctor: r } = e;
1329
- return {
1330
- id: t,
1331
- kind: "nominal",
1332
- schema: n,
1333
- /**
1334
- * Structural ownership test: the node advertises `x-apigen-logical:'nominal'`
1335
- * or carries an `x-apigen-codec` matching this codec's id. Per
1336
- * `[inv:hints-advisory]` these are accelerators; a later structural fallback
1337
- * (object `$def` with `properties`) is the authoritative signal and is
1338
- * handled by the transcoder walk, not by this cheap test.
1339
- */
1340
- matches(o) {
1341
- return o[L] === "nominal" ? !0 : o[B] === t;
1342
- },
1343
- encode(o, i, s) {
1344
- if (o === null || typeof o != "object")
1345
- return o;
1346
- if (s.seen.has(o)) {
1347
- if (s.mode === "strict")
1348
- throw new N(
1349
- "E_NOMINAL_CYCLE",
1350
- `[${t}] cycle detected at "${s.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`
1351
- );
1352
- return null;
1353
- }
1354
- s.seen.add(o);
1355
- try {
1356
- const a = ne(i), f = typeof i[M] == "string" ? i[M] : "toJSON", c = o[f];
1357
- if (typeof c == "function") {
1358
- const l = c.call(o);
1359
- if (l !== null && typeof l == "object" && !Array.isArray(l)) {
1360
- const y = {};
1361
- for (const [h, b] of Object.entries(
1362
- l
1363
- ))
1364
- y[h] = re(b, a[h], {
1365
- ...s,
1366
- path: `${s.path}/${h}`
1367
- });
1368
- return y;
1369
- }
1370
- return l;
1371
- }
1372
- const u = {}, p = Object.keys(a), d = o, m = p.length > 0 ? p : Object.keys(d);
1373
- for (const l of m) {
1374
- const y = d[l];
1375
- y !== void 0 && (u[l] = re(y, a[l], {
1376
- ...s,
1377
- path: `${s.path}/${l}`
1378
- }));
1379
- }
1380
- return u;
1381
- } finally {
1382
- s.seen.delete(o);
1383
- }
1384
- },
1385
- decode(o, i, s) {
1386
- if (o === null || typeof o != "object" || Array.isArray(o)) {
1387
- let u;
1388
- throw o === null ? u = "null" : Array.isArray(o) ? u = "array" : u = typeof o, new N(
1389
- "E_NOMINAL_INVALID_WIRE",
1390
- `[${t}] expected a JSON object on the wire at "${s.path}", got ${u}.`
1391
- );
1392
- }
1393
- const a = o;
1394
- for (const u of yt(i))
1395
- if (!(u in a))
1396
- throw new N(
1397
- "E_NOMINAL_INVALID_WIRE",
1398
- `[${t}] required field "${u}" missing on the wire at "${s.path}".`
1399
- );
1400
- if (i[dt] === !1)
1401
- throw new N(
1402
- "E_NOMINAL_NONRECONSTRUCTABLE",
1403
- `[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`
1404
- );
1405
- const f = ne(i), c = {};
1406
- for (const [u, p] of Object.entries(a))
1407
- c[u] = mt(p, f[u], {
1408
- ...s,
1409
- path: `${s.path}/${u}`
1410
- });
1411
- if (r) {
1412
- const u = typeof i[S] == "string" ? i[S] : "fromJSON", p = r[u];
1413
- if (typeof p == "function")
1414
- return p.call(
1415
- r,
1416
- c
1417
- );
1418
- const d = r;
1419
- return new d(c);
1420
- }
1421
- return c;
1422
- }
1423
- };
1424
- }
1425
- const gt = [
1426
- F,
1427
- q,
1428
- K,
1429
- z,
1430
- H,
1431
- W
1432
- ], wt = {
1433
- type: "object",
1434
- "x-apigen-logical": "nominal",
1435
- "x-apigen-codec": "ts.NominalSentinel"
1436
- }, oe = ht({
1437
- id: "ts.NominalSentinel",
1438
- schema: wt
1439
- }), bt = {
1440
- oneOf: [],
1441
- discriminator: { propertyName: "kind", mapping: {} },
1442
- "x-apigen-logical": "union",
1443
- "x-apigen-codec": "ts.UnionSentinel"
1444
- }, ie = lt({
1445
- id: "ts.UnionSentinel",
1446
- schema: bt
1458
+ let { id: t, schema: n, ctor: r } = e;
1459
+ return {
1460
+ id: t,
1461
+ kind: "nominal",
1462
+ schema: n,
1463
+ matches(e) {
1464
+ return e["x-apigen-logical"] === "nominal" || e[c] === t;
1465
+ },
1466
+ encode(e, n, r) {
1467
+ if (typeof e != "object" || !e) return e;
1468
+ if (r.seen.has(e)) {
1469
+ if (r.mode === "strict") throw new X("E_NOMINAL_CYCLE", `[${t}] cycle detected at "${r.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);
1470
+ return null;
1471
+ }
1472
+ r.seen.add(e);
1473
+ try {
1474
+ let t = ot(n), i = e[typeof n["x-apigen-tojson"] == "string" ? n[u] : "toJSON"];
1475
+ if (typeof i == "function") {
1476
+ let n = i.call(e);
1477
+ if (typeof n == "object" && n && !Array.isArray(n)) {
1478
+ let e = {};
1479
+ for (let [i, a] of Object.entries(n)) e[i] = ct(a, t[i], {
1480
+ ...r,
1481
+ path: `${r.path}/${i}`
1482
+ });
1483
+ return e;
1484
+ }
1485
+ return n;
1486
+ }
1487
+ let a = {}, o = Object.keys(t), s = e, c = o.length > 0 ? o : Object.keys(s);
1488
+ for (let e of c) {
1489
+ let n = s[e];
1490
+ n !== void 0 && (a[e] = ct(n, t[e], {
1491
+ ...r,
1492
+ path: `${r.path}/${e}`
1493
+ }));
1494
+ }
1495
+ return a;
1496
+ } finally {
1497
+ r.seen.delete(e);
1498
+ }
1499
+ },
1500
+ decode(e, n, i) {
1501
+ if (typeof e != "object" || !e || Array.isArray(e)) {
1502
+ let n;
1503
+ throw n = e === null ? "null" : Array.isArray(e) ? "array" : typeof e, new X("E_NOMINAL_INVALID_WIRE", `[${t}] expected a JSON object on the wire at "${i.path}", got ${n}.`);
1504
+ }
1505
+ let a = e;
1506
+ for (let e of st(n)) if (!(e in a)) throw new X("E_NOMINAL_INVALID_WIRE", `[${t}] required field "${e}" missing on the wire at "${i.path}".`);
1507
+ if (n["x-apigen-instances"] === !1) throw new X("E_NOMINAL_NONRECONSTRUCTABLE", `[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);
1508
+ let o = ot(n), s = {};
1509
+ for (let [e, t] of Object.entries(a)) s[e] = lt(t, o[e], {
1510
+ ...i,
1511
+ path: `${i.path}/${e}`
1512
+ });
1513
+ if (r) {
1514
+ let e = typeof n["x-apigen-ctor"] == "string" ? n[l] : "fromJSON", t = r[e];
1515
+ return typeof t == "function" ? t.call(r, s) : new r(s);
1516
+ }
1517
+ return s;
1518
+ }
1519
+ };
1520
+ }
1521
+ //#endregion
1522
+ //#region src/lib/logical/host-ts.ts
1523
+ var dt = [
1524
+ x,
1525
+ S,
1526
+ w,
1527
+ T,
1528
+ E,
1529
+ A
1530
+ ], ft = ut({
1531
+ id: "ts.NominalSentinel",
1532
+ schema: {
1533
+ type: "object",
1534
+ "x-apigen-logical": "nominal",
1535
+ "x-apigen-codec": "ts.NominalSentinel"
1536
+ }
1537
+ }), Z = at({
1538
+ id: "ts.UnionSentinel",
1539
+ schema: {
1540
+ oneOf: [],
1541
+ discriminator: {
1542
+ propertyName: "kind",
1543
+ mapping: {}
1544
+ },
1545
+ "x-apigen-logical": "union",
1546
+ "x-apigen-codec": "ts.UnionSentinel"
1547
+ }
1447
1548
  });
1448
- function vt() {
1449
- const e = [
1450
- // 6 well-known scalars
1451
- ...gt.map((t) => [
1452
- t.id,
1453
- t
1454
- ]),
1455
- // nominal kind sentinel
1456
- [oe.id, oe],
1457
- // union kind sentinel
1458
- [ie.id, ie]
1459
- ];
1460
- return Object.freeze(new Map(e));
1461
- }
1462
- const cn = Object.freeze({
1463
- host: "ts",
1464
- logicalTypeVersion: je,
1465
- codecs: vt()
1549
+ function pt() {
1550
+ let e = [
1551
+ ...dt.map((e) => [e.id, e]),
1552
+ [ft.id, ft],
1553
+ [Z.id, Z]
1554
+ ];
1555
+ return Object.freeze(new Map(e));
1556
+ }
1557
+ var mt = Object.freeze({
1558
+ host: "ts",
1559
+ logicalTypeVersion: d,
1560
+ codecs: pt()
1466
1561
  });
1467
- function un(e, t, n) {
1468
- var s;
1469
- const r = typeof ((s = t == null ? void 0 : t.input) == null ? void 0 : s.description) == "string" ? t.input.description : void 0, o = de(t == null ? void 0 : t.input), i = [n, r, o].filter(
1470
- (a) => typeof a == "string" && a.length > 0
1471
- );
1472
- return i.length > 0 ? i.join(" — ") : e;
1473
- }
1474
- function fn(e) {
1475
- if (!e || typeof e != "object" || Array.isArray(e) || Object.keys(e).length === 0)
1476
- return { outputSchema: void 0, wrapped: !1 };
1477
- const t = e;
1478
- return t.type === "object" ? { outputSchema: t, wrapped: !1 } : {
1479
- outputSchema: {
1480
- type: "object",
1481
- properties: { result: t },
1482
- required: ["result"]
1483
- },
1484
- wrapped: !0
1485
- };
1486
- }
1487
- function pn(e, t) {
1488
- return e ? { result: t } : t && typeof t == "object" && !Array.isArray(t) ? t : void 0;
1489
- }
1490
- const $t = 4, At = 32;
1491
- function R(e) {
1492
- return ge(e) ? e : e instanceof Error ? new E("internal", e.message) : e;
1493
- }
1494
- function Ot(e, t) {
1495
- if (e === "serial" || e === "chained")
1496
- return 1;
1497
- const n = t ?? $t;
1498
- return !Number.isFinite(n) || n < 1 ? 1 : Math.min(Math.floor(n), At);
1499
- }
1500
- function jt() {
1501
- }
1502
- function Nt(e, t) {
1503
- var i;
1504
- if (!e && !t)
1505
- return { signal: void 0, dispose: jt };
1506
- const n = new AbortController(), r = () => {
1507
- n.abort(e == null ? void 0 : e.reason);
1508
- };
1509
- e && (e.aborted ? n.abort(e.reason) : e.addEventListener("abort", r, { once: !0 }));
1510
- let o;
1511
- return t !== void 0 && !n.signal.aborted && (o = setTimeout(() => {
1512
- n.abort(
1513
- new DOMException(
1514
- `apigen/invokeBatch: item timed out after ${t}ms`,
1515
- "TimeoutError"
1516
- )
1517
- );
1518
- }, t), (i = o.unref) == null || i.call(o)), {
1519
- signal: n.signal,
1520
- dispose() {
1521
- e && e.removeEventListener("abort", r), o && clearTimeout(o);
1522
- }
1523
- };
1524
- }
1525
- async function se(e, t, n, r, o, i) {
1526
- const s = Nt(r.signal, i);
1527
- try {
1528
- const a = s.signal ? { ...r, signal: s.signal } : r, f = await e(t, a, o);
1529
- if (ut(f)) {
1530
- const c = await ct(f);
1531
- if (c.ok)
1532
- return { index: n, status: "fulfilled", chunks: c.chunks };
1533
- const u = c.carrier;
1534
- return {
1535
- index: n,
1536
- status: "rejected",
1537
- reason: R(u.error),
1538
- ...u.phase === "after-first-chunk" ? { chunksDelivered: u.chunksDelivered } : {}
1539
- };
1540
- }
1541
- return { index: n, status: "fulfilled", value: f };
1542
- } catch (a) {
1543
- return { index: n, status: "rejected", reason: R(a) };
1544
- } finally {
1545
- s.dispose();
1546
- }
1547
- }
1548
- async function ln(e, t, n, r, o = {}) {
1549
- const i = o.mode ?? "parallel", s = o.onItemError ?? "continue", a = Ot(i, o.concurrency), f = new Array(n.length), c = (l) => ({
1550
- index: l,
1551
- status: "rejected",
1552
- reason: R(
1553
- new Error(
1554
- "apigen/invokeBatch: not attempted — an earlier item failed and " + (i === "chained" ? 'mode is "chained"' : 'onItemError is "abort"')
1555
- )
1556
- )
1557
- });
1558
- if (i === "serial" || i === "chained") {
1559
- let l = !1;
1560
- for (let y = 0; y < n.length; y++) {
1561
- if (l) {
1562
- f[y] = c(y);
1563
- continue;
1564
- }
1565
- const h = await se(
1566
- e,
1567
- t,
1568
- y,
1569
- n[y],
1570
- r,
1571
- o.itemTimeoutMs
1572
- );
1573
- f[y] = h, h.status === "rejected" && (i === "chained" || s === "abort") && (l = !0);
1574
- }
1575
- return f;
1576
- }
1577
- let u = 0, p = !1;
1578
- const d = Math.max(1, Math.min(a, n.length)), m = Array.from({ length: d }, async () => {
1579
- for (; ; ) {
1580
- const l = u++;
1581
- if (l >= n.length)
1582
- return;
1583
- if (p) {
1584
- f[l] = c(l);
1585
- continue;
1586
- }
1587
- const y = await se(
1588
- e,
1589
- t,
1590
- l,
1591
- n[l],
1592
- r,
1593
- o.itemTimeoutMs
1594
- );
1595
- f[l] = y, y.status === "rejected" && s === "abort" && (p = !0);
1596
- }
1597
- });
1598
- return await Promise.all(m), f;
1599
- }
1600
- const ae = /* @__PURE__ */ new Set(["string", "number", "boolean", "integer"]);
1601
- function Et(e) {
1602
- if (typeof e != "object" || e === null)
1603
- return !1;
1604
- const t = e;
1605
- if (t.$ref !== void 0 || t.oneOf || t.anyOf || t.allOf)
1606
- return !1;
1607
- const { type: n } = t;
1608
- return typeof n == "string" ? ae.has(n) : Array.isArray(n) ? n.every((r) => ae.has(r) || r === "null") : Array.isArray(t.enum) && t.enum.length > 0 ? t.enum.every((r) => ["string", "number", "boolean"].includes(typeof r)) : !1;
1609
- }
1610
- function _t(e) {
1611
- if (!e || typeof e != "object")
1612
- return !1;
1613
- const t = e.properties;
1614
- return t === void 0 || typeof t != "object" || t === null ? !1 : Object.values(t).every(
1615
- Et
1616
- );
1617
- }
1618
- const kt = {
1619
- "decimal.js": "Decimal"
1620
- };
1621
- function It(e) {
1622
- return e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1623
- }
1624
- Object.entries(kt).map(([e, t]) => ({
1625
- // Matches: import("...{modSpec}...").<anyMemberName> (single or double quotes)
1626
- // The module specifier appears inside an absolute path, so we allow any
1627
- // characters between the quote and the specifier, and between the specifier
1628
- // and the closing quote. The trailing member accessor (`.default`, `.Decimal`,
1629
- // …) is matched generically (`\w+`) rather than anchored to one spelling —
1630
- // see the doc comment above for why.
1631
- pattern: new RegExp(
1632
- `import\\(["'][^"']*${It(e)}[^"']*["']\\)\\.\\w+`,
1633
- "g"
1634
- ),
1635
- key: t
1636
- }));
1637
- function ce(e) {
1638
- return e.words.join("-");
1639
- }
1640
- function ue(e) {
1641
- return e.words.map(Tt).join("");
1642
- }
1643
- function fe(e) {
1644
- return e.words.join("_");
1645
- }
1646
- function Ct(e, t = {}) {
1647
- var n, r;
1648
- const o = [e.namespace, ...e.path], i = e.safe || _t(e.input) ? "GET" : "POST", s = ((r = (n = t.http) == null ? void 0 : n.verb) == null ? void 0 : r[e.id]) ?? i, a = "/" + o.map((m) => ce(m)).join("/"), f = o.map((m) => fe(m)).join("_"), c = o.map((m) => fe(m)).slice(0, -1).join("."), u = ue(o[o.length - 2] ?? o[0]), p = ue(o[o.length - 1]), d = o.map((m) => ce(m));
1649
- return {
1650
- http: { verb: s, route: a },
1651
- mcp: { name: f },
1652
- grpc: { package: c, service: u, method: p },
1653
- cli: { path: d }
1654
- };
1655
- }
1656
- function xt(e, t) {
1657
- return `x-${e}-${t}`;
1658
- }
1562
+ //#endregion
1563
+ //#region src/lib/tool-description.ts
1564
+ function ht(e, t, n) {
1565
+ let r = [
1566
+ n,
1567
+ typeof t?.input?.description == "string" ? t.input.description : void 0,
1568
+ _e(t?.input)
1569
+ ].filter((e) => typeof e == "string" && e.length > 0);
1570
+ return r.length > 0 ? r.join(" — ") : e;
1571
+ }
1572
+ //#endregion
1573
+ //#region src/lib/mcp-output-schema.ts
1574
+ function gt(e) {
1575
+ if (!e || typeof e != "object" || Array.isArray(e) || Object.keys(e).length === 0) return {
1576
+ outputSchema: void 0,
1577
+ wrapped: !1
1578
+ };
1579
+ let t = e;
1580
+ return t.type === "object" ? {
1581
+ outputSchema: t,
1582
+ wrapped: !0
1583
+ } : {
1584
+ outputSchema: void 0,
1585
+ wrapped: !1
1586
+ };
1587
+ }
1588
+ function _t(e, t) {
1589
+ if (e) return t && typeof t == "object" && !Array.isArray(t) ? t : void 0;
1590
+ }
1591
+ //#endregion
1592
+ //#region src/lib/batch.ts
1593
+ var vt = 4, yt = 32;
1594
+ function Q(e) {
1595
+ return Ue(e) ? e : e instanceof Error ? new G("internal", e.message) : e;
1596
+ }
1597
+ function bt(e, t) {
1598
+ if (e === "serial" || e === "chained") return 1;
1599
+ let n = t ?? 4;
1600
+ return !Number.isFinite(n) || n < 1 ? 1 : Math.min(Math.floor(n), 32);
1601
+ }
1602
+ function xt() {}
1659
1603
  function St(e, t) {
1660
- return `--${e}-${t}`;
1661
- }
1662
- function Mt(e, t) {
1663
- const n = (r) => r.toUpperCase().replace(/-/g, "_");
1664
- return e === "adhd" ? `APIGEN_${n(t)}` : `APIGEN_${n(e)}_${n(t)}`;
1665
- }
1604
+ if (!e && !t) return {
1605
+ signal: void 0,
1606
+ dispose: xt
1607
+ };
1608
+ let n = new AbortController(), r = () => {
1609
+ n.abort(e?.reason);
1610
+ };
1611
+ e && (e.aborted ? n.abort(e.reason) : e.addEventListener("abort", r, { once: !0 }));
1612
+ let i;
1613
+ return t !== void 0 && !n.signal.aborted && (i = setTimeout(() => {
1614
+ n.abort(new DOMException(`apigen/invokeBatch: item timed out after ${t}ms`, "TimeoutError"));
1615
+ }, t), i.unref?.()), {
1616
+ signal: n.signal,
1617
+ dispose() {
1618
+ e && e.removeEventListener("abort", r), i && clearTimeout(i);
1619
+ }
1620
+ };
1621
+ }
1622
+ async function Ct(e, t, n, r, i, a) {
1623
+ let o = St(r.signal, a);
1624
+ try {
1625
+ let a = await e(t, o.signal ? {
1626
+ ...r,
1627
+ signal: o.signal
1628
+ } : r, i);
1629
+ if (tt(a)) {
1630
+ let e = await et(a);
1631
+ if (!e.ok) {
1632
+ let t = e.carrier;
1633
+ return {
1634
+ index: n,
1635
+ status: "rejected",
1636
+ reason: Q(t.error),
1637
+ ...t.phase === "after-first-chunk" ? { chunksDelivered: t.chunksDelivered } : {}
1638
+ };
1639
+ }
1640
+ return {
1641
+ index: n,
1642
+ status: "fulfilled",
1643
+ chunks: e.chunks
1644
+ };
1645
+ }
1646
+ return {
1647
+ index: n,
1648
+ status: "fulfilled",
1649
+ value: a
1650
+ };
1651
+ } catch (e) {
1652
+ return {
1653
+ index: n,
1654
+ status: "rejected",
1655
+ reason: Q(e)
1656
+ };
1657
+ } finally {
1658
+ o.dispose();
1659
+ }
1660
+ }
1661
+ async function wt(e, t, n, r, i = {}) {
1662
+ let a = i.mode ?? "parallel", o = i.onItemError ?? "continue", s = bt(a, i.concurrency), c = Array(n.length), l = (e) => ({
1663
+ index: e,
1664
+ status: "rejected",
1665
+ reason: Q(/* @__PURE__ */ Error("apigen/invokeBatch: not attempted — an earlier item failed and " + (a === "chained" ? "mode is \"chained\"" : "onItemError is \"abort\"")))
1666
+ });
1667
+ if (a === "serial" || a === "chained") {
1668
+ let s = !1;
1669
+ for (let u = 0; u < n.length; u++) {
1670
+ if (s) {
1671
+ c[u] = l(u);
1672
+ continue;
1673
+ }
1674
+ let d = await Ct(e, t, u, n[u], r, i.itemTimeoutMs);
1675
+ c[u] = d, d.status === "rejected" && (a === "chained" || o === "abort") && (s = !0);
1676
+ }
1677
+ return c;
1678
+ }
1679
+ let u = 0, d = !1, f = Math.max(1, Math.min(s, n.length)), p = Array.from({ length: f }, async () => {
1680
+ for (;;) {
1681
+ let a = u++;
1682
+ if (a >= n.length) return;
1683
+ if (d) {
1684
+ c[a] = l(a);
1685
+ continue;
1686
+ }
1687
+ let s = await Ct(e, t, a, n[a], r, i.itemTimeoutMs);
1688
+ c[a] = s, s.status === "rejected" && o === "abort" && (d = !0);
1689
+ }
1690
+ });
1691
+ return await Promise.all(p), c;
1692
+ }
1693
+ //#endregion
1694
+ //#region ../apigen-engine-naming/src/lib/naming.ts
1666
1695
  function Tt(e) {
1667
- return e.length === 0 ? e : e[0].toUpperCase() + e.slice(1);
1696
+ return e.words.join("-");
1668
1697
  }
1669
- function V(e) {
1670
- return e.anyOf ?? e.oneOf;
1671
- }
1672
- function Pt(e) {
1673
- if (!e)
1674
- return !1;
1675
- if (e.type === "array" || e.type === "object")
1676
- return !0;
1677
- const t = V(e);
1678
- if (t) {
1679
- const n = t.filter((r) => r.type !== "null");
1680
- return n.length > 0 && n.every((r) => r.type === "array" || r.type === "object");
1681
- }
1682
- return !1;
1698
+ function Et(e) {
1699
+ return e.words.map(Mt).join("");
1683
1700
  }
1684
1701
  function Dt(e) {
1685
- if (!e)
1686
- return !1;
1687
- if (e.type === "boolean")
1688
- return !0;
1689
- const t = V(e);
1690
- if (t) {
1691
- const n = t.filter((r) => r.type !== "null");
1692
- return n.length > 0 && n.every((r) => r.type === "boolean");
1693
- }
1694
- return !1;
1702
+ return e.words.join("_");
1703
+ }
1704
+ function Ot(e, t = {}) {
1705
+ let n = [e.namespace, ...e.path], r = e.safe || z(e.input) ? "GET" : "POST", i = t.http?.verb?.[e.id] ?? r, a = "/" + n.map((e) => Tt(e)).join("/"), o = n.map((e) => Dt(e)).join("_"), s = n.map((e) => Dt(e)).slice(0, -1).join("."), c = Et(n[n.length - 2] ?? n[0]), l = Et(n[n.length - 1]), u = n.map((e) => Tt(e));
1706
+ return {
1707
+ http: {
1708
+ verb: i,
1709
+ route: a
1710
+ },
1711
+ mcp: { name: o },
1712
+ grpc: {
1713
+ package: s,
1714
+ service: c,
1715
+ method: l
1716
+ },
1717
+ cli: { path: u }
1718
+ };
1719
+ }
1720
+ function kt(e, t) {
1721
+ return `x-${e}-${t}`;
1722
+ }
1723
+ function At(e, t) {
1724
+ return `--${e}-${t}`;
1725
+ }
1726
+ function jt(e, t) {
1727
+ let n = (e) => e.toUpperCase().replace(/-/g, "_");
1728
+ return e === "adhd" ? `APIGEN_${n(t)}` : `APIGEN_${n(e)}_${n(t)}`;
1729
+ }
1730
+ function Mt(e) {
1731
+ return e.length === 0 ? e : e[0].toUpperCase() + e.slice(1);
1732
+ }
1733
+ //#endregion
1734
+ //#region src/lib/op-plan.ts
1735
+ function $(e) {
1736
+ return e.anyOf ?? e.oneOf;
1737
+ }
1738
+ function Nt(e) {
1739
+ if (!e) return !1;
1740
+ if (e.type === "array" || e.type === "object") return !0;
1741
+ let t = $(e);
1742
+ if (t) {
1743
+ let e = t.filter((e) => e.type !== "null");
1744
+ return e.length > 0 && e.every((e) => e.type === "array" || e.type === "object");
1745
+ }
1746
+ return !1;
1695
1747
  }
1696
- function Ut(e) {
1697
- if (!e)
1698
- return !1;
1699
- if (e.type === "number" || e.type === "integer")
1700
- return !0;
1701
- const t = V(e);
1702
- if (t) {
1703
- const n = t.filter((r) => r.type !== "null");
1704
- return n.length > 0 && n.every((r) => r.type === "number" || r.type === "integer");
1705
- }
1706
- return !1;
1748
+ function Pt(e) {
1749
+ if (!e) return !1;
1750
+ if (e.type === "boolean") return !0;
1751
+ let t = $(e);
1752
+ if (t) {
1753
+ let e = t.filter((e) => e.type !== "null");
1754
+ return e.length > 0 && e.every((e) => e.type === "boolean");
1755
+ }
1756
+ return !1;
1757
+ }
1758
+ function Ft(e) {
1759
+ if (!e) return !1;
1760
+ if (e.type === "number" || e.type === "integer") return !0;
1761
+ let t = $(e);
1762
+ if (t) {
1763
+ let e = t.filter((e) => e.type !== "null");
1764
+ return e.length > 0 && e.every((e) => e.type === "number" || e.type === "integer");
1765
+ }
1766
+ return !1;
1707
1767
  }
1708
- function Rt(e) {
1709
- return e.replace(/[A-Z]/g, (t) => "-" + t.toLowerCase());
1768
+ function It(e) {
1769
+ return e.replace(/[A-Z]/g, (e) => "-" + e.toLowerCase());
1710
1770
  }
1711
1771
  function Lt(e) {
1712
- var o, i;
1713
- const t = (i = (o = e.input) == null ? void 0 : o.properties) == null ? void 0 : i.data, n = (t == null ? void 0 : t.properties) ?? {}, r = (t == null ? void 0 : t.required) ?? [];
1714
- return { props: n, required: r };
1772
+ let t = e.input?.properties?.data;
1773
+ return {
1774
+ props: t?.properties ?? {},
1775
+ required: t?.required ?? []
1776
+ };
1715
1777
  }
1716
- function pe(e) {
1717
- return typeof e.handler == "function";
1718
- }
1719
- function Bt(e) {
1720
- var o;
1721
- const t = ((o = e.input) == null ? void 0 : o.properties) ?? {}, n = e["x-apigen-envelope"], r = [];
1722
- for (const i of Object.keys(t)) {
1723
- if (i === "data")
1724
- continue;
1725
- const s = (n == null ? void 0 : n[i]) ?? "adhd", a = xt(s, i);
1726
- r.push({
1727
- field: i,
1728
- pluginId: s,
1729
- httpHeader: a,
1730
- mcpMetaKey: a,
1731
- cliFlag: St(s, i),
1732
- envVar: Mt(s, i)
1733
- });
1734
- }
1735
- return r;
1736
- }
1737
- function Ft(e, t) {
1738
- const n = /* @__PURE__ */ new Map(), { props: r } = Lt(e);
1739
- for (const [o, i] of Object.entries(r)) {
1740
- let s = "string";
1741
- Dt(i) ? s = "boolean" : (Pt(i) || Ut(i)) && (s = "json"), n.set(Rt(o), {
1742
- camelKey: o,
1743
- kind: "domain",
1744
- valueKind: s
1745
- });
1746
- }
1747
- for (const o of t) {
1748
- const i = o.cliFlag.replace(/^--/, "");
1749
- n.set(i, {
1750
- camelKey: o.field,
1751
- kind: "envelope",
1752
- valueKind: "string",
1753
- envVar: o.envVar
1754
- });
1755
- }
1756
- return n;
1757
- }
1758
- function dn(e) {
1759
- const { op: t, schema: n, transport: r, projection: o } = e, i = Ct(t, o), s = n ? Bt(n) : [], a = n ? Ft(n, s) : /* @__PURE__ */ new Map(), f = n ? tt(n).params : void 0, c = {
1760
- op: t,
1761
- transport: r,
1762
- http: i.http,
1763
- mcp: i.mcp,
1764
- cli: i.cli,
1765
- grpc: i.grpc,
1766
- params: f,
1767
- envelope: s,
1768
- cliFlags: a,
1769
- streaming: t.streaming,
1770
- isMount: pe(t)
1771
- };
1772
- if (pe(t)) {
1773
- const u = t.handler;
1774
- c.mountHandler = async (p) => u(p);
1775
- }
1776
- return c;
1777
- }
1778
- function yn(e) {
1779
- const t = e.usePlugins;
1780
- return Array.isArray(t) ? t : [];
1781
- }
1782
- function mn(e) {
1783
- const t = e.useOptions;
1784
- return t && typeof t == "object" ? t : {};
1785
- }
1786
- function qt(e) {
1787
- return async function(n, r) {
1788
- const o = Object.assign(n, { data: n.domainArgs });
1789
- return await e.layer(o, r);
1790
- };
1791
- }
1792
- function hn(e, t) {
1793
- var r;
1794
- const n = [];
1795
- for (const o of t) {
1796
- const i = (r = o.capabilities) == null ? void 0 : r.layer;
1797
- i && n.push(qt(i));
1798
- }
1799
- return n.push(st(e)), qe(n);
1800
- }
1801
- function Kt() {
1802
- const e = /* @__PURE__ */ new Map();
1803
- return {
1804
- get: (t) => e.get(t),
1805
- set: (t, n) => {
1806
- e.set(t, n);
1807
- }
1808
- };
1809
- }
1810
- const zt = {
1811
- input: {
1812
- type: "object",
1813
- properties: { data: { type: "object", properties: {} } }
1814
- },
1815
- output: {}
1816
- };
1817
- async function gn(e, t, n, r) {
1818
- const o = {
1819
- ...n,
1820
- operation: { id: e.op.id },
1821
- ctx: new Fe()
1822
- };
1823
- if (e.isMount) {
1824
- const i = e.mountHandler;
1825
- if (!i)
1826
- throw new Error(
1827
- `apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`
1828
- );
1829
- const s = {
1830
- operation: e.op,
1831
- data: n.domainArgs,
1832
- envelope: n.envelope,
1833
- ctx: Kt(),
1834
- transport: e.transport,
1835
- signal: n.signal ?? new AbortController().signal
1836
- }, a = {
1837
- ...r,
1838
- fns: { [e.op.id]: () => i(s) },
1839
- schemas: { [e.op.id]: zt }
1840
- };
1841
- return t(e.op.id, o, a);
1842
- }
1843
- return t(e.op.id, o, r);
1844
- }
1845
- export {
1846
- $t as BATCH_DEFAULT_CONCURRENCY,
1847
- At as BATCH_MAX_CONCURRENCY,
1848
- Ke as EventBus,
1849
- on as InstanceRegistry,
1850
- Fe as LayerContext,
1851
- g as UnionCodecError,
1852
- it as ValidateSchemasToken,
1853
- gt as WELL_KNOWN_TS_CODECS,
1854
- qt as adaptCoreLayer,
1855
- et as assertNoSelfSubscription,
1856
- We as buildContext,
1857
- nn as buildFnTable,
1858
- fn as buildMcpOutputSchema,
1859
- dn as buildOpPlan,
1860
- un as buildToolDescription,
1861
- tn as coerceQueryParams,
1862
- ct as collectWithPhase,
1863
- Qt as createApiPackage,
1864
- qe as createInvoker,
1865
- en as createLogger,
1866
- hn as createPackageInvoker,
1867
- sn as createStream,
1868
- lt as createUnionCodec,
1869
- Ue as dataParamNames,
1870
- Xt as defineMiddleware,
1871
- tt as describeParams,
1872
- Be as dispatch,
1873
- gn as dispatchForPlan,
1874
- an as drainStream,
1875
- ln as invokeBatch,
1876
- ut as isApiStream,
1877
- st as makeValidateLayer,
1878
- De as needsEnvelopeField,
1879
- mn as readUseOptions,
1880
- yn as readUsePlugins,
1881
- cn as tsHostBinding,
1882
- rn as validateLayer,
1883
- He as wireObservers,
1884
- pn as wrapMcpStructuredContent
1778
+ function Rt(e) {
1779
+ return typeof e.handler == "function";
1780
+ }
1781
+ function zt(e) {
1782
+ let t = e.input?.properties ?? {}, n = e["x-apigen-envelope"], r = [];
1783
+ for (let e of Object.keys(t)) {
1784
+ if (e === "data") continue;
1785
+ let t = n?.[e] ?? "adhd", i = kt(t, e);
1786
+ r.push({
1787
+ field: e,
1788
+ pluginId: t,
1789
+ httpHeader: i,
1790
+ mcpMetaKey: i,
1791
+ cliFlag: At(t, e),
1792
+ envVar: jt(t, e)
1793
+ });
1794
+ }
1795
+ return r;
1796
+ }
1797
+ function Bt(e, t, n, r) {
1798
+ t === n || e.has(t) || e.set(t, {
1799
+ ...r,
1800
+ aliasOf: n
1801
+ });
1802
+ }
1803
+ function Vt(e, t) {
1804
+ let n = /* @__PURE__ */ new Map(), { props: r } = Lt(e);
1805
+ for (let [e, t] of Object.entries(r)) {
1806
+ let r = "string";
1807
+ Pt(t) ? r = "boolean" : (Nt(t) || Ft(t)) && (r = "json");
1808
+ let i = It(e), a = {
1809
+ camelKey: e,
1810
+ kind: "domain",
1811
+ valueKind: r
1812
+ };
1813
+ n.set(i, a), Bt(n, e, i, a);
1814
+ }
1815
+ for (let e of t) {
1816
+ let t = e.cliFlag.replace(/^--/, ""), r = {
1817
+ camelKey: e.field,
1818
+ kind: "envelope",
1819
+ valueKind: "string",
1820
+ envVar: e.envVar
1821
+ };
1822
+ n.set(t, r);
1823
+ }
1824
+ return n;
1825
+ }
1826
+ function Ht(e) {
1827
+ let { op: t, schema: n, transport: r, projection: i } = e, a = Ot(t, i), o = n ? zt(n) : [], s = n ? Vt(n, o) : /* @__PURE__ */ new Map(), c = n ? U(n).params : void 0, l = {
1828
+ op: t,
1829
+ transport: r,
1830
+ http: a.http,
1831
+ mcp: a.mcp,
1832
+ cli: a.cli,
1833
+ grpc: a.grpc,
1834
+ params: c,
1835
+ envelope: o,
1836
+ cliFlags: s,
1837
+ streaming: t.streaming,
1838
+ isMount: Rt(t)
1839
+ };
1840
+ if (Rt(t)) {
1841
+ let e = t.handler;
1842
+ l.mountHandler = async (t) => e(t);
1843
+ }
1844
+ return l;
1845
+ }
1846
+ //#endregion
1847
+ //#region src/lib/package-invoker.ts
1848
+ function Ut(e) {
1849
+ let t = e.usePlugins;
1850
+ return Array.isArray(t) ? t : [];
1851
+ }
1852
+ function Wt(e) {
1853
+ let t = e.exitCode;
1854
+ return typeof t == "function" ? t : void 0;
1855
+ }
1856
+ function Gt(e) {
1857
+ let t = e.useOptions;
1858
+ return t && typeof t == "object" ? t : {};
1859
+ }
1860
+ function Kt(e) {
1861
+ return async function(t, n) {
1862
+ let r = Object.assign(t, { data: t.domainArgs });
1863
+ return await e.layer(r, n);
1864
+ };
1865
+ }
1866
+ function qt(e, t) {
1867
+ let n = [];
1868
+ for (let e of t) {
1869
+ let t = e.capabilities?.layer;
1870
+ t && n.push(Kt(t));
1871
+ }
1872
+ return n.push(Ye(e)), P(n);
1873
+ }
1874
+ //#endregion
1875
+ //#region src/lib/dispatch-for-plan.ts
1876
+ function Jt() {
1877
+ let e = /* @__PURE__ */ new Map();
1878
+ return {
1879
+ get: (t) => e.get(t),
1880
+ set: (t, n) => {
1881
+ e.set(t, n);
1882
+ }
1883
+ };
1884
+ }
1885
+ var Yt = {
1886
+ input: {
1887
+ type: "object",
1888
+ properties: { data: {
1889
+ type: "object",
1890
+ properties: {}
1891
+ } }
1892
+ },
1893
+ output: {}
1885
1894
  };
1895
+ async function Xt(e, t, n, r) {
1896
+ let i = {
1897
+ ...n,
1898
+ operation: { id: e.op.id },
1899
+ ctx: new N()
1900
+ };
1901
+ if (e.isMount) {
1902
+ let a = e.mountHandler;
1903
+ if (!a) throw Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);
1904
+ let o = {
1905
+ operation: e.op,
1906
+ data: n.domainArgs,
1907
+ envelope: n.envelope,
1908
+ ctx: Jt(),
1909
+ transport: e.transport,
1910
+ signal: n.signal ?? new AbortController().signal
1911
+ }, s = {
1912
+ ...r,
1913
+ fns: { [e.op.id]: () => a(o) },
1914
+ schemas: { [e.op.id]: Yt }
1915
+ };
1916
+ return t(e.op.id, i, s);
1917
+ }
1918
+ return t(e.op.id, i, r);
1919
+ }
1920
+ //#endregion
1921
+ export { vt as BATCH_DEFAULT_CONCURRENCY, yt as BATCH_MAX_CONCURRENCY, F as EventBus, Ze as InstanceRegistry, N as LayerContext, J as UnionCodecError, Je as ValidateSchemasToken, dt as WELL_KNOWN_TS_CODECS, Kt as adaptCoreLayer, V as assertNoSelfSubscription, L as buildContext, Ve as buildFnTable, gt as buildMcpOutputSchema, Ht as buildOpPlan, ht as buildToolDescription, Be as coerceQueryParams, et as collectWithPhase, Ne as createApiPackage, P as createInvoker, Pe as createLogger, qt as createPackageInvoker, Qe as createStream, at as createUnionCodec, xe as dataParamNames, Te as defineMiddleware, U as describeParams, we as dispatch, Xt as dispatchForPlan, $e as drainStream, wt as invokeBatch, tt as isApiStream, Ye as makeValidateLayer, be as needsEnvelopeField, Wt as readExitCodeHook, Gt as readUseOptions, Ut as readUsePlugins, mt as tsHostBinding, qe as validateLayer, I as wireObservers, _t as wrapMcpStructuredContent };