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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/lib/_bundle/aws.js +2 -0
  2. package/lib/_bundle/aws.js.map +1 -0
  3. package/lib/_bundle/base.js +5 -0
  4. package/lib/_bundle/base.js.map +1 -0
  5. package/lib/_bundle/graphql.js +3 -0
  6. package/lib/_bundle/graphql.js.map +1 -0
  7. package/lib/_bundle/rest.js +2 -0
  8. package/lib/_bundle/rest.js.map +1 -0
  9. package/lib/_bundle/xml.js +4 -0
  10. package/lib/_bundle/xml.js.map +1 -0
  11. package/lib/api.d.ts.map +1 -1
  12. package/lib/api.js +1 -796
  13. package/lib/category.js +1 -278
  14. package/lib/chunks.js +1 -11
  15. package/lib/config.js +1 -161
  16. package/lib/crypto.js +1 -130
  17. package/lib/debug.js +1 -8
  18. package/lib/error-category.js +1 -47
  19. package/lib/errors.js +1 -198
  20. package/lib/graphql.js +1 -1058
  21. package/lib/graphql.types.js +1 -6
  22. package/lib/index.js +0 -15
  23. package/lib/json-patch.js +1 -226
  24. package/lib/json-patch.js.map +1 -1
  25. package/lib/pagination.js +1 -271
  26. package/lib/plain-values.js +1 -39
  27. package/lib/plain-values.js.map +1 -1
  28. package/lib/protocol-http.js +1 -812
  29. package/lib/protocol-rest.js +1 -375
  30. package/lib/query.js +1 -27
  31. package/lib/response-validation-strict.js +1 -284
  32. package/lib/response-validation.js +1 -118
  33. package/lib/retry-after.js +1 -112
  34. package/lib/retry.js +1 -197
  35. package/lib/schema-lite-impl.js +1 -341
  36. package/lib/schema-lite-typed.js +1 -26
  37. package/lib/schema-lite-typed.js.map +1 -1
  38. package/lib/schema-lite.js +1 -31
  39. package/lib/schema.js +1 -220
  40. package/lib/testing.js +1 -41
  41. package/lib/testing.js.map +1 -1
  42. package/lib/trait.js +1 -131
  43. package/lib/xml.js +1 -323
  44. package/package.json +1 -1
  45. package/src/api.ts +7 -6
  46. package/lib/api.js.map +0 -1
  47. package/lib/category.js.map +0 -1
  48. package/lib/chunks.js.map +0 -1
  49. package/lib/config.js.map +0 -1
  50. package/lib/crypto.js.map +0 -1
  51. package/lib/debug.js.map +0 -1
  52. package/lib/error-category.js.map +0 -1
  53. package/lib/errors.js.map +0 -1
  54. package/lib/graphql.js.map +0 -1
  55. package/lib/graphql.types.js.map +0 -1
  56. package/lib/index.js.map +0 -1
  57. package/lib/pagination.js.map +0 -1
  58. package/lib/protocol-http.js.map +0 -1
  59. package/lib/protocol-rest.js.map +0 -1
  60. package/lib/query.js.map +0 -1
  61. package/lib/response-validation-strict.js.map +0 -1
  62. package/lib/response-validation.js.map +0 -1
  63. package/lib/retry-after.js.map +0 -1
  64. package/lib/retry.js.map +0 -1
  65. package/lib/schema-lite-impl.js.map +0 -1
  66. package/lib/schema-lite.js.map +0 -1
  67. package/lib/schema.js.map +0 -1
  68. package/lib/trait.js.map +0 -1
  69. package/lib/xml.js.map +0 -1
package/lib/api.js CHANGED
@@ -1,796 +1 @@
1
- import * as Context from "effect/Context";
2
- import * as Effect from "effect/Effect";
3
- import * as Exit from "effect/Exit";
4
- import * as HttpClient from "effect/http/HttpClient";
5
- import * as Layer from "effect/Layer";
6
- import * as Option from "effect/Option";
7
- import { pipeArguments } from "effect/Pipeable";
8
- import * as Ref from "effect/Ref";
9
- import * as S from "effect/Schema";
10
- import * as Scope from "effect/Scope";
11
- import { SingleShotGen } from "effect/Utils";
12
- import { isThrottling } from "./category.js";
13
- import * as Pagination from "./pagination.js";
14
- import { defaultOptions, resolveServerRetryHintCapMs, serverHintMillis, } from "./retry.js";
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
- export class Protocol extends /*@__PURE__*/ /*@__PURE__*/ Context.Service()("Protocol") {
23
- }
24
- //#endregion
25
- //#region Make
26
-
27
-
28
-
29
-
30
-
31
- export const withValue = (effect, f) => Exit.isExit(effect)
32
- ? Exit.isSuccess(effect)
33
- ? f(effect.value)
34
- : effect
35
- : Effect.flatMap(effect, f);
36
- // NOTE: request/response ASTs are handed to the protocol RAW (Suspend nodes
37
- // included). Pre-resolving Suspends here would drop annotations that sit on
38
- // intermediate nodes -- e.g. a bare-payload response whose payload type is
39
- // itself a suspended schema carries its EnvelopePayloadRoot marker on the
40
- // inner Suspend, and unwrapping it silently degrades decode to the struct
41
- // path. The protocol helpers (core/protocol-http getAnn/getProps) descend
42
- // Suspends themselves, and `Suspend.thunk` memoizes, so raw ASTs cost
43
- // nothing extra.
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
-
53
-
54
-
55
-
56
- const protocolMemoMap = /*@__PURE__*/ Layer.makeMemoMapUnsafe();
57
- const protocolScope = /*@__PURE__*/ Scope.makeUnsafe();
58
- const protocolContexts = /*@__PURE__*/ new WeakMap();
59
- const protocolContext = (layer) => {
60
- const cached = protocolContexts.get(layer);
61
- if (cached)
62
- return Effect.succeed(cached);
63
- return Effect.map(Layer.buildWithMemoMap(layer, protocolMemoMap, protocolScope), (ctx) => {
64
- protocolContexts.set(layer, ctx);
65
- return ctx;
66
- });
67
- };
68
-
69
-
70
-
71
-
72
-
73
- const backoffDelay = (b, attempt, error) => {
74
- const base = Math.min(b.baseMs * b.factor ** attempt, b.capMs);
75
- const jitter = () => Math.random() * (b.jitterMs ?? 0);
76
- if (b.serverHint && error?.retryAfter !== undefined) {
77
- return Effect.map(resolveServerRetryHintCapMs(), (capMs) => {
78
- const hint = serverHintMillis(error, capMs);
79
- return (hint ?? base) + jitter();
80
- });
81
- }
82
- const floored = b.minThrottleMs !== undefined && base < b.minThrottleMs && isThrottling(error)
83
- ? b.minThrottleMs
84
- : base;
85
- return Effect.succeed(floored + jitter());
86
- };
87
- const NO_BACKOFF = { baseMs: 0, factor: 1, capMs: 0 };
88
-
89
-
90
-
91
-
92
-
93
-
94
-
95
-
96
- const applyRetry = (base, retryKey) => retryKey === undefined
97
- ? base
98
- : Effect.catch(base, (error) => Effect.flatMap(Effect.serviceOption(retryKey), (opt) => {
99
- if (Option.isNone(opt))
100
- return retryWith(base, defaultOptions, error);
101
- const policy = opt.value;
102
- if (typeof policy !== "function")
103
- return retryWith(base, policy, error);
104
- return Effect.flatMap(Ref.make(error), (lastError) => retryWith(Effect.tapError(base, (e) => Ref.set(lastError, e)), policy(lastError), error));
105
- }));
106
- const retryWith = (base, opts, error) => {
107
- const keepGoing = opts.while;
108
- if (!keepGoing || !keepGoing(error))
109
- return Effect.fail(error);
110
- if (opts.schedule) {
111
- // Drive the caller's schedule through its own `step`, as Effect.retry
112
- // does, without importing the Schedule module into every bundle: the
113
- // first failure is the schedule's first input; a step that fails means
114
- // the schedule is done.
115
- const schedule = opts.schedule;
116
- return Effect.flatMap(schedule.step, (next) => {
117
- const loop = (e) => !keepGoing(e)
118
- ? Effect.fail(e)
119
- : Effect.clockWith((clock) => Effect.matchEffect(next(clock.currentTimeMillisUnsafe(), e), {
120
- onFailure: () => Effect.fail(e),
121
- onSuccess: ([, delay]) => Effect.flatMap(Effect.sleep(delay), () => Effect.catch(base, loop)),
122
- }));
123
- return loop(error);
124
- });
125
- }
126
- const b = opts.backoff ?? NO_BACKOFF;
127
- const step = (e, n) => !keepGoing(e) || (b.maxRetries !== undefined && n >= b.maxRetries)
128
- ? Effect.fail(e)
129
- : Effect.flatMap(backoffDelay(b, n, e), (ms) => Effect.flatMap(Effect.sleep(ms), () => Effect.catch(base, (next) => step(next, n + 1))));
130
- return step(error, 0);
131
- };
132
- const stateKey = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/api/OperationState");
133
- // Lazily resolve the operation config + schema ASTs on first call, not at
134
- // module-load time. Generated SDKs wrap each request/response schema in
135
- // `Schema.suspend(() => ...)`; forcing them here (rather than when the
136
- // `export const` is evaluated) keeps importing a service module cheap and
137
- // only pays the schema-construction cost for operations that are actually
138
- // called. Memoized so subsequent calls are free.
139
- const prepare = (state) => {
140
- if (state.prepared)
141
- return state.prepared;
142
- const cfg = state.configFn();
143
- return (state.prepared = {
144
- cfg,
145
- config: cfg,
146
- inputAst: cfg.input.ast,
147
- outputAst: cfg.output.ast,
148
- errors: cfg.errors ?? [],
149
- compiled: undefined,
150
- service: undefined,
151
- });
152
- };
153
- const stateOf = (op) => op[stateKey];
154
- const defineState = (op, state) => {
155
- Object.defineProperty(op, stateKey, { value: state });
156
- return state;
157
- };
158
- const runWith = (p, protocol, input) => {
159
- if (protocol.call !== undefined)
160
- return protocol.call(p, input);
161
- const { cfg, inputAst, outputAst, errors } = p;
162
- return Effect.flatMap(HttpClient.HttpClient, (client) => Effect.flatMap(protocol.encode({ input, inputAst, config: cfg }), (request) => Effect.flatMap(client.execute(request), (response) => protocol.decode({ response, outputAst, errors, config: cfg }))));
163
- };
164
- const callOperation = (state, input) => {
165
- // Warm path: the operation is prepared and its protocol built, so the call
166
- // is whatever the protocol returns, with no wrapper effects around it.
167
- const p = state.prepared;
168
- if (p?.service !== undefined)
169
- return applyRetry(runWith(p, p.service, input), p.cfg.retry);
170
- return Effect.suspend(() => {
171
- const prepared = prepare(state);
172
- const call = Effect.flatMap(protocolContext(prepared.cfg.protocol), (protocolCtx) => {
173
- const service = (prepared.service = Context.get(protocolCtx, Protocol));
174
- return runWith(prepared, service, input);
175
- });
176
- return applyRetry(call, prepared.cfg.retry);
177
- });
178
- };
179
-
180
-
181
-
182
-
183
-
184
-
185
-
186
-
187
- const bindContext = (op) => Effect.map(Effect.context(), (context) => (input) =>
188
- // `Context` is contravariant, so `Context<never>` is not assignable
189
- // to the `Context<any>` updateContext expects -- the widening cast is
190
- // sound (the merge only ever adds entries).
191
- Effect.updateContext(op(input), (current) => Context.merge(context, current)));
192
-
193
-
194
-
195
-
196
-
197
-
198
-
199
-
200
-
201
- const OperationProto = /*@__PURE__*/ Object.setPrototypeOf({
202
- [Symbol.iterator]() {
203
- return new SingleShotGen(this.asEffect());
204
- },
205
- pipe() {
206
- return pipeArguments(this.asEffect(), arguments);
207
- },
208
- asEffect() {
209
- return bindContext(this);
210
- },
211
- get input() {
212
- return prepare(stateOf(this)).cfg.input;
213
- },
214
- get output() {
215
- return prepare(stateOf(this)).cfg.output;
216
- },
217
- get errors() {
218
- return prepare(stateOf(this)).cfg.errors ?? [];
219
- },
220
- get operationName() {
221
- return prepare(stateOf(this)).cfg.operationName;
222
- },
223
- get pagination() {
224
- return prepare(stateOf(this)).cfg
225
- .pagination;
226
- },
227
- }, Function.prototype);
228
- const makeOperation = (state, proto) => {
229
- const fn = (input) => callOperation(state, input);
230
- defineState(fn, state);
231
- return Object.setPrototypeOf(fn, proto);
232
- };
233
- export function make(configFn) {
234
- return makeOperation({ configFn }, OperationProto);
235
- }
236
-
237
- const streamsOf = (state, call) => {
238
- const pag = () => prepare(state).cfg.pagination;
239
- // Data operations carry their strategy in the config.
240
- const paginate = state.strategy ??
241
- prepare(state).cfg.strategy ??
242
- Pagination.paginateWithDefaults;
243
- const pages = (input) => paginate(call, input, pag());
244
- const items = (input) => {
245
- const p = pag();
246
- return p.items ? Pagination.extractItems(pages(input), p.items) : pages(input);
247
- };
248
- return { pages, items };
249
- };
250
-
251
-
252
-
253
-
254
-
255
- const streamGetter = (name) => function () {
256
- const fns = streamsOf(stateOf(this), this);
257
- Object.defineProperties(this, {
258
- pages: { value: fns.pages, configurable: true },
259
- items: { value: fns.items, configurable: true },
260
- });
261
- return fns[name];
262
- };
263
- const PaginatedOperationProto = /*@__PURE__*/ Object.create(OperationProto, {
264
- pages: { get: /*@__PURE__*/ streamGetter("pages"), configurable: true },
265
- items: { get: /*@__PURE__*/ streamGetter("items"), configurable: true },
266
- // `yield* operation` returns a fresh context-bound function; give it
267
- // `.pages` / `.items` too (distilled #145). Same fallback (not snapshot)
268
- // semantics as the plain operation.
269
- asEffect: {
270
- value() {
271
- const state = stateOf(this);
272
- return Effect.map(bindContext(this), (call) => Object.assign(call, streamsOf(state, call)));
273
- },
274
- configurable: true,
275
- writable: true,
276
- },
277
- });
278
-
279
-
280
-
281
-
282
-
283
-
284
-
285
- export function makePaginated(configFn, strategy) {
286
- return makeOperation(strategy ? { configFn, strategy } : { configFn }, PaginatedOperationProto);
287
- }
288
- //#endregion
289
- //#region Data operations
290
-
291
-
292
-
293
-
294
-
295
-
296
-
297
-
298
-
299
-
300
-
301
-
302
-
303
-
304
-
305
-
306
-
307
-
308
-
309
-
310
-
311
-
312
-
313
-
314
-
315
-
316
-
317
-
318
-
319
-
320
-
321
-
322
-
323
- export const D = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/api/D");
324
- const sources = /*@__PURE__*/ new WeakMap();
325
- const sourceOf = (fn) => {
326
- let src = sources.get(fn);
327
- if (!src)
328
- sources.set(fn, (src = { fn, c: [] }));
329
- if (!src.e) {
330
- // Called with itself as `this`: a lazy error placeholder finds its data by it.
331
- const [s, r] = fn.call(fn, D);
332
- src.e = s.split(";");
333
- src.r = r;
334
- }
335
- return src;
336
- };
337
-
338
- const schemaOf = (src, j) => (src.c[j] ??= src.r[0]((src.b ??= (k) => evalEntry(src, k)), j));
339
-
340
- export const schema = (fn, j) => schemaOf(sourceOf(fn), j);
341
- const TOKEN = /"(?:[^"\\]|\\.)*"|[\w$.+-]*/y;
342
- const NAME = /[\w$]*/y;
343
- const evalEntry = (src, j) => {
344
- const s = src.e[j];
345
- const r = src.r;
346
- let p = 0;
347
- const tok = (re = NAME) => {
348
- re.lastIndex = p;
349
- const t = re.exec(s)[0];
350
- p += t.length;
351
- return t;
352
- };
353
- const list = (close) => {
354
- const a = [];
355
- if (s[p] === close)
356
- p++;
357
- else
358
- do
359
- a.push(expr());
360
- while (s[p++] !== close);
361
- return a;
362
- };
363
- const expr = () => {
364
- let v;
365
- const c = s[p++];
366
- if (c === "{") {
367
- v = {};
368
- if (s[p] === "}")
369
- p++;
370
- else
371
- do {
372
- const k = tok(TOKEN);
373
- p++;
374
- v[k[0] === '"' ? JSON.parse(k) : k] = expr();
375
- } while (s[p++] !== "}");
376
- }
377
- else if (c === "[")
378
- v = list("]");
379
- else if ("$#~>".includes(c)) {
380
- let h = src;
381
- let k = +tok();
382
- if (s[p] === ":") {
383
- p++;
384
- h = sourceOf(r[k]);
385
- k = +tok();
386
- }
387
- // A value entry is evaluated once, unwrapped.
388
- v =
389
- c === "$"
390
- ? r[k]
391
- : c === ">"
392
- ? () => evalEntry(src, k)
393
- : c === "#"
394
- ? schemaOf(h, k)
395
- : (h.c[k] ??= evalEntry(h, k));
396
- }
397
- else {
398
- p--;
399
- const t = tok(TOKEN);
400
- v = t === "u" ? undefined : JSON.parse(t);
401
- }
402
- for (;;) {
403
- const d = s[p++];
404
- if (d === "(")
405
- v = v(...list(")"));
406
- else if (d === "@")
407
- v = v.annotate({ identifier: JSON.parse(tok(TOKEN)) });
408
- else if (d === ".") {
409
- const name = tok();
410
- v = s[p] === "(" ? (p++, v[name](...list(")"))) : v[name];
411
- }
412
- else
413
- return (p--, v);
414
- }
415
- };
416
- return expr();
417
- };
418
- // A data operation gets its state on first use, from this inherited getter.
419
- // Its descriptors are written inline: nothing keeps them after the prototype is made.
420
- const dataState = function () {
421
- return defineState(this, { configFn: () => evalEntry(sourceOf(this), 0) });
422
- };
423
- let dataProto;
424
- let dataPaginatedProto;
425
-
426
-
427
-
428
-
429
- let definer;
430
-
431
- const defining = (d, f) => {
432
- const outer = definer;
433
- definer = d;
434
- try {
435
- f();
436
- }
437
- finally {
438
- definer = outer;
439
- }
440
- };
441
-
442
-
443
-
444
-
445
- export const named = (stem, data, refs) => [
446
- data.replaceAll("%", stem),
447
- refs,
448
- ];
449
- const asOp = (fn) => Object.setPrototypeOf(fn, (dataProto ??= Object.create(OperationProto, {
450
- [stateKey]: { get: dataState, configurable: true },
451
- })));
452
- const asOpPaginated = (fn) => Object.setPrototypeOf(fn, (dataPaginatedProto ??= Object.create(PaginatedOperationProto, {
453
- [stateKey]: { get: dataState, configurable: true },
454
- })));
455
-
456
- export const op = (fn) => (definer ? definer(fn, 0) : asOp(fn));
457
-
458
- export const opPaginated = (fn) => (definer ? definer(fn, 1) : asOpPaginated(fn));
459
-
460
- export const call = (op, input) => callOperation(stateOf(op), input);
461
-
462
-
463
-
464
-
465
-
466
-
467
-
468
-
469
-
470
-
471
-
472
-
473
-
474
-
475
-
476
-
477
-
478
-
479
- const errorBase = (f) => {
480
- // `f` may be a subclass: find the data class it extends.
481
- while (f && Object.getPrototypeOf(f) !== lazyErrorStatics && !sources.get(f)?.k)
482
- f = Object.getPrototypeOf(f);
483
- if (!f)
484
- return undefined;
485
- const src = sourceOf(f);
486
- if (!src.k) {
487
- const base = evalEntry(src, 0);
488
- src.k = base;
489
- Object.setPrototypeOf(f, base);
490
- Object.setPrototypeOf(f.prototype, base.prototype);
491
- }
492
- return src.k;
493
- };
494
- // The statics of an unbuilt error class: `Function.prototype` members answer
495
- // directly; any other read builds the class, then reads again. Made on first
496
- // use, so bundles without data errors drop it.
497
- let lazyErrorStatics;
498
- const LazyErrorStatics = () => (lazyErrorStatics ??= new Proxy(Object.create(Function.prototype), {
499
- get: (target, key, receiver) => key in target || !errorBase(receiver)
500
- ? Reflect.get(target, key, receiver)
501
- : Reflect.get(receiver, key, receiver),
502
- }));
503
- const asError = (fn) => Object.setPrototypeOf(fn, LazyErrorStatics());
504
-
505
- export const error = (fn) => (definer ? definer(fn, 2) : asError(fn));
506
-
507
-
508
-
509
-
510
- export const newError = (props, newTarget, data) => newTarget ? Reflect.construct(errorBase(newTarget), [props], newTarget) : data;
511
- const define = (svc, fn, kind) => {
512
- if (kind === 2) {
513
- const i = svc.ei++;
514
- if (i >= svc.e.length)
515
- throw new Error(`distilled: ${svc.spec}: error ${i} has no stub`);
516
- svc.ed[i] = fn;
517
- return svc.e[i];
518
- }
519
- const i = svc.oi++;
520
- if (i >= svc.o.length || (svc.kinds[i] === "p") !== (kind === 1))
521
- throw new Error(`distilled: ${svc.spec}: operation ${i} does not match its stub`);
522
- svc.od[i] = fn;
523
- return svc.o[i];
524
- };
525
- const load = (svc) => {
526
- if (svc.od)
527
- return;
528
- svc.od = [];
529
- svc.ed = [];
530
- try {
531
- defining((fn, kind) => define(svc, fn, kind), () => globalThis.process.getBuiltinModule("node:module").createRequire(svc.url)(svc.spec));
532
- }
533
- catch (e) {
534
- svc.od = svc.ed = undefined;
535
- svc.oi = svc.ei = 0;
536
- throw e;
537
- }
538
- if (svc.oi !== svc.o.length || svc.ei !== svc.e.length)
539
- throw new Error(`distilled: ${svc.spec} defined ${svc.oi} of ${svc.o.length} operations and ${svc.ei} of ${svc.e.length} errors (was it imported directly before?)`);
540
- };
541
- const busy = {};
542
- const node = (m) => globalThis.process?.getBuiltinModule?.(m);
543
-
544
- const read = (ix, position, length) => {
545
- const fs = node("node:fs");
546
- if (ix.fd === undefined) {
547
- ix.fd = fs.openSync(ix.file, "r");
548
- queueMicrotask(() => {
549
- fs.closeSync(ix.fd);
550
- ix.fd = undefined;
551
- });
552
- }
553
- const buf = globalThis.Buffer.allocUnsafe(length);
554
- fs.readSync(ix.fd, buf, 0, length, position);
555
- return buf.toString("utf8", 0, length);
556
- };
557
- const indexOf = (file, raw) => {
558
- const importsAt = raw.indexOf("\n") + 1;
559
- const tableAt = raw.indexOf("\n", importsAt) + 1;
560
- return {
561
- file,
562
- raw,
563
- imports: parseInt(raw),
564
- importsAt,
565
- tableAt,
566
- linesAt: raw.indexOf("\n", tableAt) + 1,
567
- importValues: [],
568
- v: [],
569
- };
570
- };
571
- const fileOf = (svc) =>
572
- // A plain POSIX file URL is its path (URL parsing costs ~0.1 ms the first time).
573
- /^file:\/\/\/[^%?#]*$/.test(svc.url) && globalThis.process.platform !== "win32"
574
- ? svc.url.slice(7, svc.url.lastIndexOf("/") + 1) + svc.spec
575
- : node("node:url").fileURLToPath(new URL(svc.spec, svc.url));
576
- const sliced = (svc) => {
577
- if (svc.ix !== undefined)
578
- return svc.ix;
579
- svc.ix = false;
580
- if (svc.at === undefined || svc.od)
581
- return false;
582
- try {
583
- Function("");
584
- const file = fileOf(svc);
585
- svc.ix = indexOf(file, read({ file }, svc.at, svc.len));
586
- svc.od = [];
587
- svc.ed = [];
588
- }
589
- catch { }
590
- return svc.ix;
591
- };
592
-
593
-
594
-
595
-
596
-
597
-
598
-
599
- let primed = false;
600
- const prime = (svc) => {
601
- primed = true;
602
- queueMicrotask(() => {
603
- const ix = sliced(svc);
604
- // The first read of an export through a module namespace is slow.
605
- if (ix && ix.imports > 0)
606
- importOf(svc, ix, 0);
607
- });
608
- };
609
-
610
- const lineOf = (ix, k) => {
611
- const at = ix.tableAt + 5 * k;
612
- return ix.raw.slice(ix.linesAt + parseInt(ix.raw.slice(at, at + 5), 36), ix.linesAt + parseInt(ix.raw.slice(at + 5, at + 10), 36) - 1);
613
- };
614
- const nameOf = (ix, k) => lineOf(ix, k).split("|")[0].split(" ")[3];
615
- const importSpec = (ix, j) => (ix.specs ??= ix.raw.slice(ix.importsAt, ix.tableAt - 1).split(" "))[j].split(":");
616
- const importOf = (svc, ix, j) => {
617
- if (j in ix.importValues)
618
- return ix.importValues[j];
619
- const [, source, name] = importSpec(ix, j);
620
- return (ix.importValues[j] = svc.ns[+source][name]);
621
- };
622
-
623
- const refOf = (svc, ix, j) => j < ix.imports ? importOf(svc, ix, j) : valueOf(svc, ix, j - ix.imports);
624
-
625
-
626
-
627
-
628
-
629
- const evaluate = (svc, ix, k) => {
630
- const [head, fn, depText] = lineOf(ix, k).split("|");
631
- const deps = depText ? depText.split(" ").map((x) => parseInt(x, 36)) : [];
632
- const names = deps.map((j) => j < ix.imports ? importSpec(ix, j)[0] : nameOf(ix, j - ix.imports));
633
- const values = deps.map((j) => refOf(svc, ix, j));
634
- const url = `\n//# sourceURL=${ix.file}#${nameOf(ix, k)}`;
635
- if (fn && fn[0] !== "(") {
636
- const [params, range] = fn.split(";");
637
- const [start, end, expr] = range.split(" ").map((x) => parseInt(x, 36));
638
- return compileBody(ix, names, values, params ? params.split(",") : [], start, end, expr, url);
639
- }
640
- const [, start, end] = head.split(" ").map((x) => parseInt(x, 36));
641
- let text;
642
- if (fn?.[0] === "(") {
643
- // Functions it passes compile on their first call (many never are): it
644
- // reads the text around them only.
645
- const args = fn.slice(1).split(",");
646
- const outer = { names: names.slice(), values: values.slice() };
647
- text = "";
648
- let at = start;
649
- args.forEach((arg, i) => {
650
- const [a, b, bs, be, expr] = arg.split(" ").map((x) => parseInt(x, 36));
651
- const params = arg.split(" ")[5];
652
- let compiled;
653
- names.push(`$lazy${i}`);
654
- values.push(function () {
655
- compiled ??= compileBody(ix, outer.names, outer.values, params ? params.split("+") : [], bs, be, expr, url);
656
- return compiled.apply(this, arguments);
657
- });
658
- text += `${read(ix, at, a - at)}$lazy${i}`;
659
- at = b;
660
- });
661
- text += read(ix, at, end - at);
662
- }
663
- else
664
- text = read(ix, start, end - start);
665
- return Function(...names, `"use strict";return(${text}\n)${url}`)(...values);
666
- };
667
-
668
-
669
-
670
-
671
- const compileBody = (ix, names, values, own, start, end, expr, url) => {
672
- const text = read(ix, start, end - start);
673
- const keep = names.map((n) => !own.includes(n));
674
- return Function(...names.filter((_, i) => keep[i]), ...own,
675
- // A block: the body's own declarations shadow the names in scope, as they did.
676
- `"use strict";${expr ? `return(${text}\n)` : `{${text}\n}`}${url}`).bind(undefined, ...values.filter((_, i) => keep[i]));
677
- };
678
-
679
-
680
-
681
-
682
- const dataFn = (svc, ix, fn) => {
683
- const [stem, range, refs] = fn.slice(1).split(";");
684
- const sp = range.indexOf(" ");
685
- const start = parseInt(range, 36);
686
- const data = read(ix, start, parseInt(range.slice(sp + 1), 36) - start);
687
- const values = [];
688
- if (refs)
689
- for (const x of refs.split(",")) {
690
- const j = parseInt(x, 36);
691
- values.push(j < ix.imports ? importOf(svc, ix, j) : slot(svc, ix, j - ix.imports, false));
692
- }
693
- return [stem ? data.replaceAll("%", stem) : data, values];
694
- };
695
-
696
-
697
-
698
-
699
- const slot = (svc, ix, k, own) => {
700
- if (!own) {
701
- if (k in ix.v)
702
- return ix.v[k] === busy ? undefined : ix.v[k];
703
- const ops = svc.o.length;
704
- if (k < ops)
705
- return (ix.v[k] = svc.o[k]);
706
- if (k < ops + svc.e.length)
707
- return (ix.v[k] = svc.e[k - ops]);
708
- }
709
- const at = ix.tableAt + 5 * k;
710
- const line = ix.raw.slice(ix.linesAt + parseInt(ix.raw.slice(at, at + 5), 36), ix.linesAt + parseInt(ix.raw.slice(at + 5, at + 10), 36) - 1);
711
- const bar = line.indexOf("|");
712
- if (line[bar + 1] === "=") {
713
- const fn = dataFn.bind(undefined, svc, ix, line.slice(bar + 1));
714
- return own ? fn : (ix.v[k] = fn);
715
- }
716
- if (own)
717
- return evaluate(svc, ix, k);
718
- if (line[0] === "1") {
719
- // A function declaration: compiled on its first call, so cycles need no order.
720
- let fn;
721
- return (ix.v[k] = function () {
722
- return (fn ??= evaluate(svc, ix, k)).apply(this, arguments);
723
- });
724
- }
725
- ix.v[k] = busy;
726
- return (ix.v[k] = evaluate(svc, ix, k));
727
- };
728
- const valueOf = (svc, ix, k) => slot(svc, ix, k, false);
729
-
730
- const dataOf = (svc, kind, i) => {
731
- const loaded = kind === 0 ? svc.od : svc.ed;
732
- if (loaded?.[i])
733
- return loaded[i];
734
- const ix = sliced(svc);
735
- if (!ix) {
736
- load(svc);
737
- return (kind === 0 ? svc.od : svc.ed)[i];
738
- }
739
- return ((kind === 0 ? svc.od : svc.ed)[i] = slot(svc, ix, kind === 0 ? i : svc.o.length + i, true));
740
- };
741
-
742
-
743
-
744
-
745
-
746
-
747
- export const lazyService = (url, spec, kinds, ns, at, len) => {
748
- const svc = { url, spec, kinds, ns, at, len, o: [], e: [], oi: 0, ei: 0 };
749
- if (!primed && at !== undefined && !globalThis.process?.env?.NOPRIME)
750
- prime(svc);
751
- return {
752
- o: () => {
753
- const paginated = kinds[svc.o.length] === "p";
754
- const f = function op(x) {
755
- return x === D ? dataOf(svc, 0, svc.o.indexOf(op))(D) : call(op, x);
756
- };
757
- svc.o.push(paginated ? asOpPaginated(f) : asOp(f));
758
- return f;
759
- },
760
- e: (name) => {
761
- // A computed key names the function without a property of its own.
762
- const f = {
763
- [name]: function (x) {
764
- return new.target
765
- ? newError(x, new.target, undefined)
766
- : dataOf(svc, 1, svc.e.indexOf(this))(x);
767
- },
768
- }[name];
769
- svc.e.push(asError(f));
770
- return f;
771
- },
772
- // Destructured once by the stub: each property read makes the error class of that name.
773
- get E() {
774
- const e = this.e;
775
- return new Proxy({}, { get: (_, name) => e(name) });
776
- },
777
- };
778
- };
779
- const namespaceOf = (t) => (t.ns ??= globalThis.process.getBuiltinModule("node:module").createRequire(t.url)(t.spec));
780
- let lazyNamespaceHandler;
781
- export const lazyNamespace = (url, spec) => new Proxy({ url, spec }, (lazyNamespaceHandler ??= {
782
- get: (t, k) => namespaceOf(t)[k],
783
- has: (t, k) => k in namespaceOf(t),
784
- ownKeys: (t) => Reflect.ownKeys(namespaceOf(t)),
785
- getOwnPropertyDescriptor: (t, k) => {
786
- const d = Reflect.getOwnPropertyDescriptor(namespaceOf(t), k);
787
- // The target does not hold these: a proxy may only report them configurable.
788
- return d && { ...d, configurable: true };
789
- },
790
- getPrototypeOf: () => null,
791
- set: () => false,
792
- defineProperty: () => false,
793
- deleteProperty: () => false,
794
- }));
795
- //#endregion
796
- //# sourceMappingURL=api.js.map
1
+ export { api$D as D, api$Protocol as Protocol, api$call as call, api$error as error, api$lazyNamespace as lazyNamespace, api$lazyService as lazyService, api$make as make, api$makePaginated as makePaginated, api$named as named, api$newError as newError, api$op as op, api$opPaginated as opPaginated, api$schema as schema, api$withValue as withValue } from "./_bundle/base.js";