@rivetkit/engine-api-full 2.0.37 → 2.0.39

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 (51) hide show
  1. package/dist/browser/cjs/index.js +5 -130
  2. package/dist/browser/cjs/serialization.js +5 -130
  3. package/dist/browser/esm/index.js +5 -130
  4. package/dist/browser/esm/serialization.js +5 -130
  5. package/dist/node/{index.js → cjs/index.js} +5 -130
  6. package/dist/node/{serialization.js → cjs/serialization.js} +5 -147
  7. package/dist/node/esm/core.js +2317 -0
  8. package/dist/node/esm/index.js +4218 -0
  9. package/dist/node/esm/serialization.js +1925 -0
  10. package/package.json +13 -4
  11. package/types/api/types/Actor.d.ts +1 -1
  12. package/types/api/types/RunnerConfigResponse.d.ts +1 -1
  13. package/types/api/types/index.d.ts +0 -17
  14. package/types/serialization/types/Actor.d.ts +1 -2
  15. package/types/serialization/types/RunnerConfigResponse.d.ts +1 -2
  16. package/types/serialization/types/index.d.ts +0 -17
  17. package/types/api/types/ActorError.d.ts +0 -20
  18. package/types/api/types/ActorErrorCrashed.d.ts +0 -11
  19. package/types/api/types/ActorErrorCrashedCrashed.d.ts +0 -9
  20. package/types/api/types/ActorErrorRunnerConnectionLost.d.ts +0 -11
  21. package/types/api/types/ActorErrorRunnerConnectionLostRunnerConnectionLost.d.ts +0 -10
  22. package/types/api/types/ActorErrorRunnerDrainingTimeout.d.ts +0 -11
  23. package/types/api/types/ActorErrorRunnerDrainingTimeoutRunnerDrainingTimeout.d.ts +0 -10
  24. package/types/api/types/ActorErrorRunnerNoResponse.d.ts +0 -11
  25. package/types/api/types/ActorErrorRunnerNoResponseRunnerNoResponse.d.ts +0 -10
  26. package/types/api/types/ActorErrorRunnerPoolError.d.ts +0 -11
  27. package/types/api/types/RunnerPoolError.d.ts +0 -14
  28. package/types/api/types/RunnerPoolErrorServerlessConnectionError.d.ts +0 -11
  29. package/types/api/types/RunnerPoolErrorServerlessConnectionErrorServerlessConnectionError.d.ts +0 -9
  30. package/types/api/types/RunnerPoolErrorServerlessHttpError.d.ts +0 -11
  31. package/types/api/types/RunnerPoolErrorServerlessHttpErrorServerlessHttpError.d.ts +0 -10
  32. package/types/api/types/RunnerPoolErrorServerlessInvalidPayload.d.ts +0 -11
  33. package/types/api/types/RunnerPoolErrorServerlessInvalidPayloadServerlessInvalidPayload.d.ts +0 -9
  34. package/types/serialization/types/ActorError.d.ts +0 -15
  35. package/types/serialization/types/ActorErrorCrashed.d.ts +0 -13
  36. package/types/serialization/types/ActorErrorCrashedCrashed.d.ts +0 -12
  37. package/types/serialization/types/ActorErrorRunnerConnectionLost.d.ts +0 -13
  38. package/types/serialization/types/ActorErrorRunnerConnectionLostRunnerConnectionLost.d.ts +0 -13
  39. package/types/serialization/types/ActorErrorRunnerDrainingTimeout.d.ts +0 -13
  40. package/types/serialization/types/ActorErrorRunnerDrainingTimeoutRunnerDrainingTimeout.d.ts +0 -13
  41. package/types/serialization/types/ActorErrorRunnerNoResponse.d.ts +0 -13
  42. package/types/serialization/types/ActorErrorRunnerNoResponseRunnerNoResponse.d.ts +0 -13
  43. package/types/serialization/types/ActorErrorRunnerPoolError.d.ts +0 -13
  44. package/types/serialization/types/RunnerPoolError.d.ts +0 -13
  45. package/types/serialization/types/RunnerPoolErrorServerlessConnectionError.d.ts +0 -13
  46. package/types/serialization/types/RunnerPoolErrorServerlessConnectionErrorServerlessConnectionError.d.ts +0 -12
  47. package/types/serialization/types/RunnerPoolErrorServerlessHttpError.d.ts +0 -13
  48. package/types/serialization/types/RunnerPoolErrorServerlessHttpErrorServerlessHttpError.d.ts +0 -13
  49. package/types/serialization/types/RunnerPoolErrorServerlessInvalidPayload.d.ts +0 -13
  50. package/types/serialization/types/RunnerPoolErrorServerlessInvalidPayloadServerlessInvalidPayload.d.ts +0 -12
  51. /package/dist/node/{core.js → cjs/core.js} +0 -0
@@ -0,0 +1,2317 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // src/core/fetcher/stream-wrappers/Node18UniversalStreamWrapper.ts
12
+ var Node18UniversalStreamWrapper_exports = {};
13
+ __export(Node18UniversalStreamWrapper_exports, {
14
+ Node18UniversalStreamWrapper: () => Node18UniversalStreamWrapper
15
+ });
16
+ var Node18UniversalStreamWrapper;
17
+ var init_Node18UniversalStreamWrapper = __esm({
18
+ "src/core/fetcher/stream-wrappers/Node18UniversalStreamWrapper.ts"() {
19
+ "use strict";
20
+ Node18UniversalStreamWrapper = class _Node18UniversalStreamWrapper {
21
+ readableStream;
22
+ reader;
23
+ events;
24
+ paused;
25
+ resumeCallback;
26
+ encoding;
27
+ constructor(readableStream) {
28
+ this.readableStream = readableStream;
29
+ this.reader = this.readableStream.getReader();
30
+ this.events = {
31
+ data: [],
32
+ end: [],
33
+ error: [],
34
+ readable: [],
35
+ close: [],
36
+ pause: [],
37
+ resume: []
38
+ };
39
+ this.paused = false;
40
+ this.resumeCallback = null;
41
+ this.encoding = null;
42
+ }
43
+ on(event, callback) {
44
+ var _a;
45
+ (_a = this.events[event]) == null ? void 0 : _a.push(callback);
46
+ }
47
+ off(event, callback) {
48
+ var _a;
49
+ this.events[event] = (_a = this.events[event]) == null ? void 0 : _a.filter((cb) => cb !== callback);
50
+ }
51
+ pipe(dest) {
52
+ this.on("data", async (chunk) => {
53
+ if (dest instanceof _Node18UniversalStreamWrapper) {
54
+ dest._write(chunk);
55
+ } else if (dest instanceof WritableStream) {
56
+ const writer = dest.getWriter();
57
+ writer.write(chunk).then(() => writer.releaseLock());
58
+ } else {
59
+ dest.write(chunk);
60
+ }
61
+ });
62
+ this.on("end", async () => {
63
+ if (dest instanceof _Node18UniversalStreamWrapper) {
64
+ dest._end();
65
+ } else if (dest instanceof WritableStream) {
66
+ const writer = dest.getWriter();
67
+ writer.close();
68
+ } else {
69
+ dest.end();
70
+ }
71
+ });
72
+ this.on("error", async (error) => {
73
+ if (dest instanceof _Node18UniversalStreamWrapper) {
74
+ dest._error(error);
75
+ } else if (dest instanceof WritableStream) {
76
+ const writer = dest.getWriter();
77
+ writer.abort(error);
78
+ } else {
79
+ dest.destroy(error);
80
+ }
81
+ });
82
+ this._startReading();
83
+ return dest;
84
+ }
85
+ pipeTo(dest) {
86
+ return this.pipe(dest);
87
+ }
88
+ unpipe(dest) {
89
+ this.off("data", async (chunk) => {
90
+ if (dest instanceof _Node18UniversalStreamWrapper) {
91
+ dest._write(chunk);
92
+ } else if (dest instanceof WritableStream) {
93
+ const writer = dest.getWriter();
94
+ writer.write(chunk).then(() => writer.releaseLock());
95
+ } else {
96
+ dest.write(chunk);
97
+ }
98
+ });
99
+ this.off("end", async () => {
100
+ if (dest instanceof _Node18UniversalStreamWrapper) {
101
+ dest._end();
102
+ } else if (dest instanceof WritableStream) {
103
+ const writer = dest.getWriter();
104
+ writer.close();
105
+ } else {
106
+ dest.end();
107
+ }
108
+ });
109
+ this.off("error", async (error) => {
110
+ if (dest instanceof _Node18UniversalStreamWrapper) {
111
+ dest._error(error);
112
+ } else if (dest instanceof WritableStream) {
113
+ const writer = dest.getWriter();
114
+ writer.abort(error);
115
+ } else {
116
+ dest.destroy(error);
117
+ }
118
+ });
119
+ }
120
+ destroy(error) {
121
+ this.reader.cancel(error).then(() => {
122
+ this._emit("close");
123
+ }).catch((err) => {
124
+ this._emit("error", err);
125
+ });
126
+ }
127
+ pause() {
128
+ this.paused = true;
129
+ this._emit("pause");
130
+ }
131
+ resume() {
132
+ if (this.paused) {
133
+ this.paused = false;
134
+ this._emit("resume");
135
+ if (this.resumeCallback) {
136
+ this.resumeCallback();
137
+ this.resumeCallback = null;
138
+ }
139
+ }
140
+ }
141
+ get isPaused() {
142
+ return this.paused;
143
+ }
144
+ async read() {
145
+ if (this.paused) {
146
+ await new Promise((resolve) => {
147
+ this.resumeCallback = resolve;
148
+ });
149
+ }
150
+ const { done, value } = await this.reader.read();
151
+ if (done) {
152
+ return void 0;
153
+ }
154
+ return value;
155
+ }
156
+ setEncoding(encoding) {
157
+ this.encoding = encoding;
158
+ }
159
+ async text() {
160
+ const chunks = [];
161
+ while (true) {
162
+ const { done, value } = await this.reader.read();
163
+ if (done) {
164
+ break;
165
+ }
166
+ if (value) {
167
+ chunks.push(value);
168
+ }
169
+ }
170
+ const decoder = new TextDecoder(this.encoding || "utf-8");
171
+ return decoder.decode(await new Blob(chunks).arrayBuffer());
172
+ }
173
+ async json() {
174
+ const text = await this.text();
175
+ return JSON.parse(text);
176
+ }
177
+ _write(chunk) {
178
+ this._emit("data", chunk);
179
+ }
180
+ _end() {
181
+ this._emit("end");
182
+ }
183
+ _error(error) {
184
+ this._emit("error", error);
185
+ }
186
+ _emit(event, data) {
187
+ if (this.events[event]) {
188
+ for (const callback of this.events[event] || []) {
189
+ callback(data);
190
+ }
191
+ }
192
+ }
193
+ async _startReading() {
194
+ try {
195
+ this._emit("readable");
196
+ while (true) {
197
+ if (this.paused) {
198
+ await new Promise((resolve) => {
199
+ this.resumeCallback = resolve;
200
+ });
201
+ }
202
+ const { done, value } = await this.reader.read();
203
+ if (done) {
204
+ this._emit("end");
205
+ this._emit("close");
206
+ break;
207
+ }
208
+ if (value) {
209
+ this._emit("data", value);
210
+ }
211
+ }
212
+ } catch (error) {
213
+ this._emit("error", error);
214
+ }
215
+ }
216
+ [Symbol.asyncIterator]() {
217
+ return {
218
+ next: async () => {
219
+ if (this.paused) {
220
+ await new Promise((resolve) => {
221
+ this.resumeCallback = resolve;
222
+ });
223
+ }
224
+ const { done, value } = await this.reader.read();
225
+ if (done) {
226
+ return { done: true, value: void 0 };
227
+ }
228
+ return { done: false, value };
229
+ },
230
+ [Symbol.asyncIterator]() {
231
+ return this;
232
+ }
233
+ };
234
+ }
235
+ };
236
+ }
237
+ });
238
+
239
+ // src/core/fetcher/stream-wrappers/UndiciStreamWrapper.ts
240
+ var UndiciStreamWrapper_exports = {};
241
+ __export(UndiciStreamWrapper_exports, {
242
+ UndiciStreamWrapper: () => UndiciStreamWrapper
243
+ });
244
+ var UndiciStreamWrapper;
245
+ var init_UndiciStreamWrapper = __esm({
246
+ "src/core/fetcher/stream-wrappers/UndiciStreamWrapper.ts"() {
247
+ "use strict";
248
+ UndiciStreamWrapper = class _UndiciStreamWrapper {
249
+ readableStream;
250
+ reader;
251
+ events;
252
+ paused;
253
+ resumeCallback;
254
+ encoding;
255
+ constructor(readableStream) {
256
+ this.readableStream = readableStream;
257
+ this.reader = this.readableStream.getReader();
258
+ this.events = {
259
+ data: [],
260
+ end: [],
261
+ error: [],
262
+ readable: [],
263
+ close: [],
264
+ pause: [],
265
+ resume: []
266
+ };
267
+ this.paused = false;
268
+ this.resumeCallback = null;
269
+ this.encoding = null;
270
+ }
271
+ on(event, callback) {
272
+ var _a;
273
+ (_a = this.events[event]) == null ? void 0 : _a.push(callback);
274
+ }
275
+ off(event, callback) {
276
+ var _a;
277
+ this.events[event] = (_a = this.events[event]) == null ? void 0 : _a.filter((cb) => cb !== callback);
278
+ }
279
+ pipe(dest) {
280
+ this.on("data", (chunk) => {
281
+ if (dest instanceof _UndiciStreamWrapper) {
282
+ dest._write(chunk);
283
+ } else {
284
+ const writer = dest.getWriter();
285
+ writer.write(chunk).then(() => writer.releaseLock());
286
+ }
287
+ });
288
+ this.on("end", () => {
289
+ if (dest instanceof _UndiciStreamWrapper) {
290
+ dest._end();
291
+ } else {
292
+ const writer = dest.getWriter();
293
+ writer.close();
294
+ }
295
+ });
296
+ this.on("error", (error) => {
297
+ if (dest instanceof _UndiciStreamWrapper) {
298
+ dest._error(error);
299
+ } else {
300
+ const writer = dest.getWriter();
301
+ writer.abort(error);
302
+ }
303
+ });
304
+ this._startReading();
305
+ return dest;
306
+ }
307
+ pipeTo(dest) {
308
+ return this.pipe(dest);
309
+ }
310
+ unpipe(dest) {
311
+ this.off("data", (chunk) => {
312
+ if (dest instanceof _UndiciStreamWrapper) {
313
+ dest._write(chunk);
314
+ } else {
315
+ const writer = dest.getWriter();
316
+ writer.write(chunk).then(() => writer.releaseLock());
317
+ }
318
+ });
319
+ this.off("end", () => {
320
+ if (dest instanceof _UndiciStreamWrapper) {
321
+ dest._end();
322
+ } else {
323
+ const writer = dest.getWriter();
324
+ writer.close();
325
+ }
326
+ });
327
+ this.off("error", (error) => {
328
+ if (dest instanceof _UndiciStreamWrapper) {
329
+ dest._error(error);
330
+ } else {
331
+ const writer = dest.getWriter();
332
+ writer.abort(error);
333
+ }
334
+ });
335
+ }
336
+ destroy(error) {
337
+ this.reader.cancel(error).then(() => {
338
+ this._emit("close");
339
+ }).catch((err) => {
340
+ this._emit("error", err);
341
+ });
342
+ }
343
+ pause() {
344
+ this.paused = true;
345
+ this._emit("pause");
346
+ }
347
+ resume() {
348
+ if (this.paused) {
349
+ this.paused = false;
350
+ this._emit("resume");
351
+ if (this.resumeCallback) {
352
+ this.resumeCallback();
353
+ this.resumeCallback = null;
354
+ }
355
+ }
356
+ }
357
+ get isPaused() {
358
+ return this.paused;
359
+ }
360
+ async read() {
361
+ if (this.paused) {
362
+ await new Promise((resolve) => {
363
+ this.resumeCallback = resolve;
364
+ });
365
+ }
366
+ const { done, value } = await this.reader.read();
367
+ if (done) {
368
+ return void 0;
369
+ }
370
+ return value;
371
+ }
372
+ setEncoding(encoding) {
373
+ this.encoding = encoding;
374
+ }
375
+ async text() {
376
+ const chunks = [];
377
+ while (true) {
378
+ const { done, value } = await this.reader.read();
379
+ if (done) {
380
+ break;
381
+ }
382
+ if (value) {
383
+ chunks.push(value);
384
+ }
385
+ }
386
+ const decoder = new TextDecoder(this.encoding || "utf-8");
387
+ return decoder.decode(await new Blob(chunks).arrayBuffer());
388
+ }
389
+ async json() {
390
+ const text = await this.text();
391
+ return JSON.parse(text);
392
+ }
393
+ _write(chunk) {
394
+ this._emit("data", chunk);
395
+ }
396
+ _end() {
397
+ this._emit("end");
398
+ }
399
+ _error(error) {
400
+ this._emit("error", error);
401
+ }
402
+ _emit(event, data) {
403
+ if (this.events[event]) {
404
+ for (const callback of this.events[event] || []) {
405
+ callback(data);
406
+ }
407
+ }
408
+ }
409
+ async _startReading() {
410
+ try {
411
+ this._emit("readable");
412
+ while (true) {
413
+ if (this.paused) {
414
+ await new Promise((resolve) => {
415
+ this.resumeCallback = resolve;
416
+ });
417
+ }
418
+ const { done, value } = await this.reader.read();
419
+ if (done) {
420
+ this._emit("end");
421
+ this._emit("close");
422
+ break;
423
+ }
424
+ if (value) {
425
+ this._emit("data", value);
426
+ }
427
+ }
428
+ } catch (error) {
429
+ this._emit("error", error);
430
+ }
431
+ }
432
+ [Symbol.asyncIterator]() {
433
+ return {
434
+ next: async () => {
435
+ if (this.paused) {
436
+ await new Promise((resolve) => {
437
+ this.resumeCallback = resolve;
438
+ });
439
+ }
440
+ const { done, value } = await this.reader.read();
441
+ if (done) {
442
+ return { done: true, value: void 0 };
443
+ }
444
+ return { done: false, value };
445
+ },
446
+ [Symbol.asyncIterator]() {
447
+ return this;
448
+ }
449
+ };
450
+ }
451
+ };
452
+ }
453
+ });
454
+
455
+ // src/core/fetcher/stream-wrappers/NodePre18StreamWrapper.ts
456
+ var NodePre18StreamWrapper_exports = {};
457
+ __export(NodePre18StreamWrapper_exports, {
458
+ NodePre18StreamWrapper: () => NodePre18StreamWrapper
459
+ });
460
+ var NodePre18StreamWrapper;
461
+ var init_NodePre18StreamWrapper = __esm({
462
+ "src/core/fetcher/stream-wrappers/NodePre18StreamWrapper.ts"() {
463
+ "use strict";
464
+ NodePre18StreamWrapper = class {
465
+ readableStream;
466
+ encoding;
467
+ constructor(readableStream) {
468
+ this.readableStream = readableStream;
469
+ }
470
+ on(event, callback) {
471
+ this.readableStream.on(event, callback);
472
+ }
473
+ off(event, callback) {
474
+ this.readableStream.off(event, callback);
475
+ }
476
+ pipe(dest) {
477
+ this.readableStream.pipe(dest);
478
+ return dest;
479
+ }
480
+ pipeTo(dest) {
481
+ return this.pipe(dest);
482
+ }
483
+ unpipe(dest) {
484
+ if (dest) {
485
+ this.readableStream.unpipe(dest);
486
+ } else {
487
+ this.readableStream.unpipe();
488
+ }
489
+ }
490
+ destroy(error) {
491
+ this.readableStream.destroy(error);
492
+ }
493
+ pause() {
494
+ this.readableStream.pause();
495
+ }
496
+ resume() {
497
+ this.readableStream.resume();
498
+ }
499
+ get isPaused() {
500
+ return this.readableStream.isPaused();
501
+ }
502
+ async read() {
503
+ return new Promise((resolve, reject) => {
504
+ const chunk = this.readableStream.read();
505
+ if (chunk) {
506
+ resolve(chunk);
507
+ } else {
508
+ this.readableStream.once("readable", () => {
509
+ const chunk2 = this.readableStream.read();
510
+ resolve(chunk2);
511
+ });
512
+ this.readableStream.once("error", reject);
513
+ }
514
+ });
515
+ }
516
+ setEncoding(encoding) {
517
+ this.readableStream.setEncoding(encoding);
518
+ this.encoding = encoding;
519
+ }
520
+ async text() {
521
+ const chunks = [];
522
+ const encoder = new TextEncoder();
523
+ this.readableStream.setEncoding(this.encoding || "utf-8");
524
+ for await (const chunk of this.readableStream) {
525
+ chunks.push(encoder.encode(chunk));
526
+ }
527
+ const decoder = new TextDecoder(this.encoding || "utf-8");
528
+ return decoder.decode(Buffer.concat(chunks));
529
+ }
530
+ async json() {
531
+ const text = await this.text();
532
+ return JSON.parse(text);
533
+ }
534
+ [Symbol.asyncIterator]() {
535
+ const readableStream = this.readableStream;
536
+ const iterator = readableStream[Symbol.asyncIterator]();
537
+ return {
538
+ async next() {
539
+ const { value, done } = await iterator.next();
540
+ return { value, done };
541
+ },
542
+ [Symbol.asyncIterator]() {
543
+ return this;
544
+ }
545
+ };
546
+ }
547
+ };
548
+ }
549
+ });
550
+
551
+ // src/core/json.ts
552
+ var toJson = (value, replacer, space) => {
553
+ return JSON.stringify(value, replacer, space);
554
+ };
555
+
556
+ // src/core/fetcher/createRequestUrl.ts
557
+ import qs from "qs";
558
+ function createRequestUrl(baseUrl, queryParameters) {
559
+ return Object.keys(queryParameters ?? {}).length > 0 ? `${baseUrl}?${qs.stringify(queryParameters, { arrayFormat: "repeat" })}` : baseUrl;
560
+ }
561
+
562
+ // src/core/runtime/runtime.ts
563
+ var RUNTIME = evaluateRuntime();
564
+ function evaluateRuntime() {
565
+ var _a, _b, _c, _d, _e;
566
+ const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
567
+ if (isBrowser) {
568
+ return {
569
+ type: "browser",
570
+ version: window.navigator.userAgent
571
+ };
572
+ }
573
+ const isCloudflare = typeof globalThis !== "undefined" && ((_a = globalThis == null ? void 0 : globalThis.navigator) == null ? void 0 : _a.userAgent) === "Cloudflare-Workers";
574
+ if (isCloudflare) {
575
+ return {
576
+ type: "workerd"
577
+ };
578
+ }
579
+ const isEdgeRuntime = typeof EdgeRuntime === "string";
580
+ if (isEdgeRuntime) {
581
+ return {
582
+ type: "edge-runtime"
583
+ };
584
+ }
585
+ const isWebWorker = typeof self === "object" && // @ts-ignore
586
+ typeof (self == null ? void 0 : self.importScripts) === "function" && (((_b = self.constructor) == null ? void 0 : _b.name) === "DedicatedWorkerGlobalScope" || ((_c = self.constructor) == null ? void 0 : _c.name) === "ServiceWorkerGlobalScope" || ((_d = self.constructor) == null ? void 0 : _d.name) === "SharedWorkerGlobalScope");
587
+ if (isWebWorker) {
588
+ return {
589
+ type: "web-worker"
590
+ };
591
+ }
592
+ const isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined";
593
+ if (isDeno) {
594
+ return {
595
+ type: "deno",
596
+ version: Deno.version.deno
597
+ };
598
+ }
599
+ const isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
600
+ if (isBun) {
601
+ return {
602
+ type: "bun",
603
+ version: Bun.version
604
+ };
605
+ }
606
+ const isNode = typeof process !== "undefined" && "version" in process && !!process.version && "versions" in process && !!((_e = process.versions) == null ? void 0 : _e.node);
607
+ if (isNode) {
608
+ return {
609
+ type: "node",
610
+ version: process.versions.node,
611
+ parsedVersion: Number(process.versions.node.split(".")[0])
612
+ };
613
+ }
614
+ const isReactNative = typeof navigator !== "undefined" && (navigator == null ? void 0 : navigator.product) === "ReactNative";
615
+ if (isReactNative) {
616
+ return {
617
+ type: "react-native"
618
+ };
619
+ }
620
+ return {
621
+ type: "unknown"
622
+ };
623
+ }
624
+
625
+ // src/core/fetcher/getFetchFn.ts
626
+ async function getFetchFn() {
627
+ if (RUNTIME.type === "node" && RUNTIME.parsedVersion != null && RUNTIME.parsedVersion >= 18) {
628
+ return fetch;
629
+ }
630
+ if (RUNTIME.type === "node") {
631
+ return (await import("node-fetch")).default;
632
+ }
633
+ if (typeof fetch == "function") {
634
+ return fetch;
635
+ }
636
+ return (await import("node-fetch")).default;
637
+ }
638
+
639
+ // src/core/fetcher/getRequestBody.ts
640
+ async function getRequestBody({ body, type }) {
641
+ if (type.includes("json")) {
642
+ return toJson(body);
643
+ } else {
644
+ return body;
645
+ }
646
+ }
647
+
648
+ // src/core/fetcher/stream-wrappers/chooseStreamWrapper.ts
649
+ async function chooseStreamWrapper(responseBody) {
650
+ if (RUNTIME.type === "node" && RUNTIME.parsedVersion != null && RUNTIME.parsedVersion >= 18) {
651
+ return new (await Promise.resolve().then(() => (init_Node18UniversalStreamWrapper(), Node18UniversalStreamWrapper_exports))).Node18UniversalStreamWrapper(
652
+ responseBody
653
+ );
654
+ } else if (RUNTIME.type !== "node" && typeof fetch === "function") {
655
+ return new (await Promise.resolve().then(() => (init_UndiciStreamWrapper(), UndiciStreamWrapper_exports))).UndiciStreamWrapper(responseBody);
656
+ } else {
657
+ return new (await Promise.resolve().then(() => (init_NodePre18StreamWrapper(), NodePre18StreamWrapper_exports))).NodePre18StreamWrapper(responseBody);
658
+ }
659
+ }
660
+
661
+ // src/core/fetcher/getResponseBody.ts
662
+ async function getResponseBody(response, responseType) {
663
+ if (response.body != null && responseType === "blob") {
664
+ return await response.blob();
665
+ } else if (response.body != null && responseType === "arrayBuffer") {
666
+ return await response.arrayBuffer();
667
+ } else if (response.body != null && responseType === "sse") {
668
+ return response.body;
669
+ } else if (response.body != null && responseType === "streaming") {
670
+ return chooseStreamWrapper(response.body);
671
+ } else if (response.body != null && responseType === "text") {
672
+ return await response.text();
673
+ } else {
674
+ const text = await response.text();
675
+ if (text.length > 0) {
676
+ try {
677
+ let responseBody = JSON.parse(text);
678
+ return responseBody;
679
+ } catch (err) {
680
+ return {
681
+ ok: false,
682
+ error: {
683
+ reason: "non-json",
684
+ statusCode: response.status,
685
+ rawBody: text
686
+ }
687
+ };
688
+ }
689
+ } else {
690
+ return void 0;
691
+ }
692
+ }
693
+ }
694
+
695
+ // src/core/fetcher/signals.ts
696
+ var TIMEOUT = "timeout";
697
+ function getTimeoutSignal(timeoutMs) {
698
+ const controller = new AbortController();
699
+ const abortId = setTimeout(() => controller.abort(TIMEOUT), timeoutMs);
700
+ return { signal: controller.signal, abortId };
701
+ }
702
+ function anySignal(...args) {
703
+ const signals = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;
704
+ const controller = new AbortController();
705
+ for (const signal of signals) {
706
+ if (signal.aborted) {
707
+ controller.abort(signal == null ? void 0 : signal.reason);
708
+ break;
709
+ }
710
+ signal.addEventListener("abort", () => controller.abort(signal == null ? void 0 : signal.reason), {
711
+ signal: controller.signal
712
+ });
713
+ }
714
+ return controller.signal;
715
+ }
716
+
717
+ // src/core/fetcher/makeRequest.ts
718
+ var makeRequest = async (fetchFn, url, method, headers, requestBody, timeoutMs, abortSignal, withCredentials, duplex) => {
719
+ const signals = [];
720
+ let timeoutAbortId = void 0;
721
+ if (timeoutMs != null) {
722
+ const { signal, abortId } = getTimeoutSignal(timeoutMs);
723
+ timeoutAbortId = abortId;
724
+ signals.push(signal);
725
+ }
726
+ if (abortSignal != null) {
727
+ signals.push(abortSignal);
728
+ }
729
+ let newSignals = anySignal(signals);
730
+ const response = await fetchFn(url, {
731
+ method,
732
+ headers,
733
+ body: requestBody,
734
+ signal: newSignals,
735
+ credentials: withCredentials ? "include" : void 0,
736
+ // @ts-ignore
737
+ duplex
738
+ });
739
+ if (timeoutAbortId != null) {
740
+ clearTimeout(timeoutAbortId);
741
+ }
742
+ return response;
743
+ };
744
+
745
+ // src/core/fetcher/requestWithRetries.ts
746
+ var INITIAL_RETRY_DELAY = 1e3;
747
+ var MAX_RETRY_DELAY = 6e4;
748
+ var DEFAULT_MAX_RETRIES = 2;
749
+ var JITTER_FACTOR = 0.2;
750
+ function addJitter(delay) {
751
+ const jitterMultiplier = 1 + (Math.random() * 2 - 1) * JITTER_FACTOR;
752
+ return delay * jitterMultiplier;
753
+ }
754
+ async function requestWithRetries(requestFn, maxRetries = DEFAULT_MAX_RETRIES) {
755
+ let response = await requestFn();
756
+ for (let i = 0; i < maxRetries; ++i) {
757
+ if ([408, 429].includes(response.status) || response.status >= 500) {
758
+ const baseDelay = Math.min(INITIAL_RETRY_DELAY * Math.pow(2, i), MAX_RETRY_DELAY);
759
+ const delayWithJitter = addJitter(baseDelay);
760
+ await new Promise((resolve) => setTimeout(resolve, delayWithJitter));
761
+ response = await requestFn();
762
+ } else {
763
+ break;
764
+ }
765
+ }
766
+ return response;
767
+ }
768
+
769
+ // src/core/fetcher/Fetcher.ts
770
+ async function fetcherImpl(args) {
771
+ const headers = {};
772
+ if (args.body !== void 0 && args.contentType != null) {
773
+ headers["Content-Type"] = args.contentType;
774
+ }
775
+ if (args.headers != null) {
776
+ for (const [key, value] of Object.entries(args.headers)) {
777
+ if (value != null) {
778
+ headers[key] = value;
779
+ }
780
+ }
781
+ }
782
+ const url = createRequestUrl(args.url, args.queryParameters);
783
+ const requestBody = await getRequestBody({
784
+ body: args.body,
785
+ type: args.requestType === "json" ? "json" : "other"
786
+ });
787
+ const fetchFn = await getFetchFn();
788
+ try {
789
+ const response = await requestWithRetries(
790
+ async () => makeRequest(
791
+ fetchFn,
792
+ url,
793
+ args.method,
794
+ headers,
795
+ requestBody,
796
+ args.timeoutMs,
797
+ args.abortSignal,
798
+ args.withCredentials,
799
+ args.duplex
800
+ ),
801
+ args.maxRetries
802
+ );
803
+ const responseBody = await getResponseBody(response, args.responseType);
804
+ if (response.status >= 200 && response.status < 400) {
805
+ return {
806
+ ok: true,
807
+ body: responseBody,
808
+ headers: response.headers
809
+ };
810
+ } else {
811
+ return {
812
+ ok: false,
813
+ error: {
814
+ reason: "status-code",
815
+ statusCode: response.status,
816
+ body: responseBody
817
+ }
818
+ };
819
+ }
820
+ } catch (error) {
821
+ if (args.abortSignal != null && args.abortSignal.aborted) {
822
+ return {
823
+ ok: false,
824
+ error: {
825
+ reason: "unknown",
826
+ errorMessage: "The user aborted a request"
827
+ }
828
+ };
829
+ } else if (error instanceof Error && error.name === "AbortError") {
830
+ return {
831
+ ok: false,
832
+ error: {
833
+ reason: "timeout"
834
+ }
835
+ };
836
+ } else if (error instanceof Error) {
837
+ return {
838
+ ok: false,
839
+ error: {
840
+ reason: "unknown",
841
+ errorMessage: error.message
842
+ }
843
+ };
844
+ }
845
+ return {
846
+ ok: false,
847
+ error: {
848
+ reason: "unknown",
849
+ errorMessage: toJson(error)
850
+ }
851
+ };
852
+ }
853
+ }
854
+ var fetcher = fetcherImpl;
855
+
856
+ // src/core/fetcher/getHeader.ts
857
+ function getHeader(headers, header) {
858
+ for (const [headerKey, headerValue] of Object.entries(headers)) {
859
+ if (headerKey.toLowerCase() === header.toLowerCase()) {
860
+ return headerValue;
861
+ }
862
+ }
863
+ return void 0;
864
+ }
865
+
866
+ // src/core/fetcher/Supplier.ts
867
+ var Supplier = {
868
+ get: async (supplier) => {
869
+ if (typeof supplier === "function") {
870
+ return supplier();
871
+ } else {
872
+ return supplier;
873
+ }
874
+ }
875
+ };
876
+
877
+ // src/core/auth/BasicAuth.ts
878
+ import { Base64 } from "js-base64";
879
+ var BASIC_AUTH_HEADER_PREFIX = /^Basic /i;
880
+ var BasicAuth = {
881
+ toAuthorizationHeader: (basicAuth) => {
882
+ if (basicAuth == null) {
883
+ return void 0;
884
+ }
885
+ const token = Base64.encode(`${basicAuth.username}:${basicAuth.password}`);
886
+ return `Basic ${token}`;
887
+ },
888
+ fromAuthorizationHeader: (header) => {
889
+ const credentials = header.replace(BASIC_AUTH_HEADER_PREFIX, "");
890
+ const decoded = Base64.decode(credentials);
891
+ const [username, password] = decoded.split(":", 2);
892
+ if (username == null || password == null) {
893
+ throw new Error("Invalid basic auth");
894
+ }
895
+ return {
896
+ username,
897
+ password
898
+ };
899
+ }
900
+ };
901
+
902
+ // src/core/auth/BearerToken.ts
903
+ var BEARER_AUTH_HEADER_PREFIX = /^Bearer /i;
904
+ var BearerToken = {
905
+ toAuthorizationHeader: (token) => {
906
+ if (token == null) {
907
+ return void 0;
908
+ }
909
+ return `Bearer ${token}`;
910
+ },
911
+ fromAuthorizationHeader: (header) => {
912
+ return header.replace(BEARER_AUTH_HEADER_PREFIX, "").trim();
913
+ }
914
+ };
915
+
916
+ // src/core/schemas/index.ts
917
+ var schemas_exports = {};
918
+ __export(schemas_exports, {
919
+ JsonError: () => JsonError,
920
+ ParseError: () => ParseError,
921
+ any: () => any,
922
+ bigint: () => bigint,
923
+ boolean: () => boolean,
924
+ booleanLiteral: () => booleanLiteral,
925
+ date: () => date,
926
+ discriminant: () => discriminant,
927
+ enum_: () => enum_,
928
+ getObjectLikeUtils: () => getObjectLikeUtils,
929
+ getObjectUtils: () => getObjectUtils,
930
+ getSchemaUtils: () => getSchemaUtils,
931
+ isProperty: () => isProperty,
932
+ lazy: () => lazy,
933
+ lazyObject: () => lazyObject,
934
+ list: () => list,
935
+ number: () => number,
936
+ object: () => object,
937
+ objectWithoutOptionalProperties: () => objectWithoutOptionalProperties,
938
+ optional: () => optional,
939
+ property: () => property,
940
+ record: () => record,
941
+ set: () => set,
942
+ string: () => string,
943
+ stringLiteral: () => stringLiteral,
944
+ transform: () => transform,
945
+ undiscriminatedUnion: () => undiscriminatedUnion,
946
+ union: () => union,
947
+ unknown: () => unknown,
948
+ withParsedProperties: () => withParsedProperties
949
+ });
950
+
951
+ // src/core/schemas/Schema.ts
952
+ var SchemaType = {
953
+ BIGINT: "bigint",
954
+ DATE: "date",
955
+ ENUM: "enum",
956
+ LIST: "list",
957
+ STRING_LITERAL: "stringLiteral",
958
+ BOOLEAN_LITERAL: "booleanLiteral",
959
+ OBJECT: "object",
960
+ ANY: "any",
961
+ BOOLEAN: "boolean",
962
+ NUMBER: "number",
963
+ STRING: "string",
964
+ UNKNOWN: "unknown",
965
+ RECORD: "record",
966
+ SET: "set",
967
+ UNION: "union",
968
+ UNDISCRIMINATED_UNION: "undiscriminatedUnion",
969
+ NULLABLE: "nullable",
970
+ OPTIONAL: "optional",
971
+ OPTIONAL_NULLABLE: "optionalNullable"
972
+ };
973
+
974
+ // src/core/schemas/utils/getErrorMessageForIncorrectType.ts
975
+ function getErrorMessageForIncorrectType(value, expectedType) {
976
+ return `Expected ${expectedType}. Received ${getTypeAsString(value)}.`;
977
+ }
978
+ function getTypeAsString(value) {
979
+ if (Array.isArray(value)) {
980
+ return "list";
981
+ }
982
+ if (value === null) {
983
+ return "null";
984
+ }
985
+ if (value instanceof BigInt) {
986
+ return "BigInt";
987
+ }
988
+ switch (typeof value) {
989
+ case "string":
990
+ return `"${value}"`;
991
+ case "bigint":
992
+ case "number":
993
+ case "boolean":
994
+ case "undefined":
995
+ return `${value}`;
996
+ }
997
+ return typeof value;
998
+ }
999
+
1000
+ // src/core/schemas/utils/maybeSkipValidation.ts
1001
+ function maybeSkipValidation(schema) {
1002
+ return {
1003
+ ...schema,
1004
+ json: transformAndMaybeSkipValidation(schema.json),
1005
+ parse: transformAndMaybeSkipValidation(schema.parse)
1006
+ };
1007
+ }
1008
+ function transformAndMaybeSkipValidation(transform2) {
1009
+ return (value, opts) => {
1010
+ const transformed = transform2(value, opts);
1011
+ const { skipValidation = false } = opts ?? {};
1012
+ if (!transformed.ok && skipValidation) {
1013
+ console.warn(
1014
+ [
1015
+ "Failed to validate.",
1016
+ ...transformed.errors.map(
1017
+ (error) => " - " + (error.path.length > 0 ? `${error.path.join(".")}: ${error.message}` : error.message)
1018
+ )
1019
+ ].join("\n")
1020
+ );
1021
+ return {
1022
+ ok: true,
1023
+ value
1024
+ };
1025
+ } else {
1026
+ return transformed;
1027
+ }
1028
+ };
1029
+ }
1030
+
1031
+ // src/core/schemas/builders/schema-utils/stringifyValidationErrors.ts
1032
+ function stringifyValidationError(error) {
1033
+ if (error.path.length === 0) {
1034
+ return error.message;
1035
+ }
1036
+ return `${error.path.join(" -> ")}: ${error.message}`;
1037
+ }
1038
+
1039
+ // src/core/schemas/builders/schema-utils/JsonError.ts
1040
+ var JsonError = class _JsonError extends Error {
1041
+ constructor(errors) {
1042
+ super(errors.map(stringifyValidationError).join("; "));
1043
+ this.errors = errors;
1044
+ Object.setPrototypeOf(this, _JsonError.prototype);
1045
+ }
1046
+ };
1047
+
1048
+ // src/core/schemas/builders/schema-utils/ParseError.ts
1049
+ var ParseError = class _ParseError extends Error {
1050
+ constructor(errors) {
1051
+ super(errors.map(stringifyValidationError).join("; "));
1052
+ this.errors = errors;
1053
+ Object.setPrototypeOf(this, _ParseError.prototype);
1054
+ }
1055
+ };
1056
+
1057
+ // src/core/schemas/builders/schema-utils/getSchemaUtils.ts
1058
+ function getSchemaUtils(schema) {
1059
+ return {
1060
+ nullable: () => nullable(schema),
1061
+ optional: () => optional(schema),
1062
+ optionalNullable: () => optionalNullable(schema),
1063
+ transform: (transformer) => transform(schema, transformer),
1064
+ parseOrThrow: (raw, opts) => {
1065
+ const parsed = schema.parse(raw, opts);
1066
+ if (parsed.ok) {
1067
+ return parsed.value;
1068
+ }
1069
+ throw new ParseError(parsed.errors);
1070
+ },
1071
+ jsonOrThrow: (parsed, opts) => {
1072
+ const raw = schema.json(parsed, opts);
1073
+ if (raw.ok) {
1074
+ return raw.value;
1075
+ }
1076
+ throw new JsonError(raw.errors);
1077
+ }
1078
+ };
1079
+ }
1080
+ function nullable(schema) {
1081
+ const baseSchema = {
1082
+ parse: (raw, opts) => {
1083
+ if (raw == null) {
1084
+ return {
1085
+ ok: true,
1086
+ value: null
1087
+ };
1088
+ }
1089
+ return schema.parse(raw, opts);
1090
+ },
1091
+ json: (parsed, opts) => {
1092
+ if (parsed == null) {
1093
+ return {
1094
+ ok: true,
1095
+ value: null
1096
+ };
1097
+ }
1098
+ return schema.json(parsed, opts);
1099
+ },
1100
+ getType: () => SchemaType.NULLABLE
1101
+ };
1102
+ return {
1103
+ ...baseSchema,
1104
+ ...getSchemaUtils(baseSchema)
1105
+ };
1106
+ }
1107
+ function optional(schema) {
1108
+ const baseSchema = {
1109
+ parse: (raw, opts) => {
1110
+ if (raw == null) {
1111
+ return {
1112
+ ok: true,
1113
+ value: void 0
1114
+ };
1115
+ }
1116
+ return schema.parse(raw, opts);
1117
+ },
1118
+ json: (parsed, opts) => {
1119
+ if ((opts == null ? void 0 : opts.omitUndefined) && parsed === void 0) {
1120
+ return {
1121
+ ok: true,
1122
+ value: void 0
1123
+ };
1124
+ }
1125
+ if (parsed == null) {
1126
+ return {
1127
+ ok: true,
1128
+ value: null
1129
+ };
1130
+ }
1131
+ return schema.json(parsed, opts);
1132
+ },
1133
+ getType: () => SchemaType.OPTIONAL
1134
+ };
1135
+ return {
1136
+ ...baseSchema,
1137
+ ...getSchemaUtils(baseSchema)
1138
+ };
1139
+ }
1140
+ function optionalNullable(schema) {
1141
+ const baseSchema = {
1142
+ parse: (raw, opts) => {
1143
+ if (raw === void 0) {
1144
+ return {
1145
+ ok: true,
1146
+ value: void 0
1147
+ };
1148
+ }
1149
+ if (raw === null) {
1150
+ return {
1151
+ ok: true,
1152
+ value: null
1153
+ };
1154
+ }
1155
+ return schema.parse(raw, opts);
1156
+ },
1157
+ json: (parsed, opts) => {
1158
+ if (parsed === void 0) {
1159
+ return {
1160
+ ok: true,
1161
+ value: void 0
1162
+ };
1163
+ }
1164
+ if (parsed === null) {
1165
+ return {
1166
+ ok: true,
1167
+ value: null
1168
+ };
1169
+ }
1170
+ return schema.json(parsed, opts);
1171
+ },
1172
+ getType: () => SchemaType.OPTIONAL_NULLABLE
1173
+ };
1174
+ return {
1175
+ ...baseSchema,
1176
+ ...getSchemaUtils(baseSchema)
1177
+ };
1178
+ }
1179
+ function transform(schema, transformer) {
1180
+ const baseSchema = {
1181
+ parse: (raw, opts) => {
1182
+ const parsed = schema.parse(raw, opts);
1183
+ if (!parsed.ok) {
1184
+ return parsed;
1185
+ }
1186
+ return {
1187
+ ok: true,
1188
+ value: transformer.transform(parsed.value)
1189
+ };
1190
+ },
1191
+ json: (transformed, opts) => {
1192
+ const parsed = transformer.untransform(transformed);
1193
+ return schema.json(parsed, opts);
1194
+ },
1195
+ getType: () => schema.getType()
1196
+ };
1197
+ return {
1198
+ ...baseSchema,
1199
+ ...getSchemaUtils(baseSchema)
1200
+ };
1201
+ }
1202
+
1203
+ // src/core/schemas/builders/bigint/bigint.ts
1204
+ function bigint() {
1205
+ const baseSchema = {
1206
+ parse: (raw, { breadcrumbsPrefix = [] } = {}) => {
1207
+ if (typeof raw === "bigint") {
1208
+ return {
1209
+ ok: true,
1210
+ value: raw
1211
+ };
1212
+ }
1213
+ if (typeof raw === "number") {
1214
+ return {
1215
+ ok: true,
1216
+ value: BigInt(raw)
1217
+ };
1218
+ }
1219
+ return {
1220
+ ok: false,
1221
+ errors: [
1222
+ {
1223
+ path: breadcrumbsPrefix,
1224
+ message: getErrorMessageForIncorrectType(raw, "bigint | number")
1225
+ }
1226
+ ]
1227
+ };
1228
+ },
1229
+ json: (bigint2, { breadcrumbsPrefix = [] } = {}) => {
1230
+ if (typeof bigint2 !== "bigint") {
1231
+ return {
1232
+ ok: false,
1233
+ errors: [
1234
+ {
1235
+ path: breadcrumbsPrefix,
1236
+ message: getErrorMessageForIncorrectType(bigint2, "bigint")
1237
+ }
1238
+ ]
1239
+ };
1240
+ }
1241
+ return {
1242
+ ok: true,
1243
+ value: bigint2
1244
+ };
1245
+ },
1246
+ getType: () => SchemaType.BIGINT
1247
+ };
1248
+ return {
1249
+ ...maybeSkipValidation(baseSchema),
1250
+ ...getSchemaUtils(baseSchema)
1251
+ };
1252
+ }
1253
+
1254
+ // src/core/schemas/builders/date/date.ts
1255
+ var ISO_8601_REGEX = /^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
1256
+ function date() {
1257
+ const baseSchema = {
1258
+ parse: (raw, { breadcrumbsPrefix = [] } = {}) => {
1259
+ if (typeof raw !== "string") {
1260
+ return {
1261
+ ok: false,
1262
+ errors: [
1263
+ {
1264
+ path: breadcrumbsPrefix,
1265
+ message: getErrorMessageForIncorrectType(raw, "string")
1266
+ }
1267
+ ]
1268
+ };
1269
+ }
1270
+ if (!ISO_8601_REGEX.test(raw)) {
1271
+ return {
1272
+ ok: false,
1273
+ errors: [
1274
+ {
1275
+ path: breadcrumbsPrefix,
1276
+ message: getErrorMessageForIncorrectType(raw, "ISO 8601 date string")
1277
+ }
1278
+ ]
1279
+ };
1280
+ }
1281
+ return {
1282
+ ok: true,
1283
+ value: new Date(raw)
1284
+ };
1285
+ },
1286
+ json: (date2, { breadcrumbsPrefix = [] } = {}) => {
1287
+ if (date2 instanceof Date) {
1288
+ return {
1289
+ ok: true,
1290
+ value: date2.toISOString()
1291
+ };
1292
+ } else {
1293
+ return {
1294
+ ok: false,
1295
+ errors: [
1296
+ {
1297
+ path: breadcrumbsPrefix,
1298
+ message: getErrorMessageForIncorrectType(date2, "Date object")
1299
+ }
1300
+ ]
1301
+ };
1302
+ }
1303
+ },
1304
+ getType: () => SchemaType.DATE
1305
+ };
1306
+ return {
1307
+ ...maybeSkipValidation(baseSchema),
1308
+ ...getSchemaUtils(baseSchema)
1309
+ };
1310
+ }
1311
+
1312
+ // src/core/schemas/utils/createIdentitySchemaCreator.ts
1313
+ function createIdentitySchemaCreator(schemaType, validate) {
1314
+ return () => {
1315
+ const baseSchema = {
1316
+ parse: validate,
1317
+ json: validate,
1318
+ getType: () => schemaType
1319
+ };
1320
+ return {
1321
+ ...maybeSkipValidation(baseSchema),
1322
+ ...getSchemaUtils(baseSchema)
1323
+ };
1324
+ };
1325
+ }
1326
+
1327
+ // src/core/schemas/builders/enum/enum.ts
1328
+ function enum_(values) {
1329
+ const validValues = new Set(values);
1330
+ const schemaCreator = createIdentitySchemaCreator(
1331
+ SchemaType.ENUM,
1332
+ (value, { allowUnrecognizedEnumValues, breadcrumbsPrefix = [] } = {}) => {
1333
+ if (typeof value !== "string") {
1334
+ return {
1335
+ ok: false,
1336
+ errors: [
1337
+ {
1338
+ path: breadcrumbsPrefix,
1339
+ message: getErrorMessageForIncorrectType(value, "string")
1340
+ }
1341
+ ]
1342
+ };
1343
+ }
1344
+ if (!validValues.has(value) && !allowUnrecognizedEnumValues) {
1345
+ return {
1346
+ ok: false,
1347
+ errors: [
1348
+ {
1349
+ path: breadcrumbsPrefix,
1350
+ message: getErrorMessageForIncorrectType(value, "enum")
1351
+ }
1352
+ ]
1353
+ };
1354
+ }
1355
+ return {
1356
+ ok: true,
1357
+ value
1358
+ };
1359
+ }
1360
+ );
1361
+ return schemaCreator();
1362
+ }
1363
+
1364
+ // src/core/schemas/builders/lazy/lazy.ts
1365
+ function lazy(getter) {
1366
+ const baseSchema = constructLazyBaseSchema(getter);
1367
+ return {
1368
+ ...baseSchema,
1369
+ ...getSchemaUtils(baseSchema)
1370
+ };
1371
+ }
1372
+ function constructLazyBaseSchema(getter) {
1373
+ return {
1374
+ parse: (raw, opts) => getMemoizedSchema(getter).parse(raw, opts),
1375
+ json: (parsed, opts) => getMemoizedSchema(getter).json(parsed, opts),
1376
+ getType: () => getMemoizedSchema(getter).getType()
1377
+ };
1378
+ }
1379
+ function getMemoizedSchema(getter) {
1380
+ const castedGetter = getter;
1381
+ if (castedGetter.__zurg_memoized == null) {
1382
+ castedGetter.__zurg_memoized = getter();
1383
+ }
1384
+ return castedGetter.__zurg_memoized;
1385
+ }
1386
+
1387
+ // src/core/schemas/utils/entries.ts
1388
+ function entries(object2) {
1389
+ return Object.entries(object2);
1390
+ }
1391
+
1392
+ // src/core/schemas/utils/filterObject.ts
1393
+ function filterObject(obj, keysToInclude) {
1394
+ const keysToIncludeSet = new Set(keysToInclude);
1395
+ return Object.entries(obj).reduce(
1396
+ (acc, [key, value]) => {
1397
+ if (keysToIncludeSet.has(key)) {
1398
+ acc[key] = value;
1399
+ }
1400
+ return acc;
1401
+ },
1402
+ {}
1403
+ );
1404
+ }
1405
+
1406
+ // src/core/schemas/utils/isPlainObject.ts
1407
+ function isPlainObject(value) {
1408
+ if (typeof value !== "object" || value === null) {
1409
+ return false;
1410
+ }
1411
+ if (Object.getPrototypeOf(value) === null) {
1412
+ return true;
1413
+ }
1414
+ let proto = value;
1415
+ while (Object.getPrototypeOf(proto) !== null) {
1416
+ proto = Object.getPrototypeOf(proto);
1417
+ }
1418
+ return Object.getPrototypeOf(value) === proto;
1419
+ }
1420
+
1421
+ // src/core/schemas/utils/keys.ts
1422
+ function keys(object2) {
1423
+ return Object.keys(object2);
1424
+ }
1425
+
1426
+ // src/core/schemas/utils/partition.ts
1427
+ function partition(items, predicate) {
1428
+ const trueItems = [], falseItems = [];
1429
+ for (const item of items) {
1430
+ if (predicate(item)) {
1431
+ trueItems.push(item);
1432
+ } else {
1433
+ falseItems.push(item);
1434
+ }
1435
+ }
1436
+ return [trueItems, falseItems];
1437
+ }
1438
+
1439
+ // src/core/schemas/builders/object-like/getObjectLikeUtils.ts
1440
+ function getObjectLikeUtils(schema) {
1441
+ return {
1442
+ withParsedProperties: (properties) => withParsedProperties(schema, properties)
1443
+ };
1444
+ }
1445
+ function withParsedProperties(objectLike, properties) {
1446
+ const objectSchema = {
1447
+ parse: (raw, opts) => {
1448
+ const parsedObject = objectLike.parse(raw, opts);
1449
+ if (!parsedObject.ok) {
1450
+ return parsedObject;
1451
+ }
1452
+ const additionalProperties = Object.entries(properties).reduce(
1453
+ (processed, [key, value]) => {
1454
+ return {
1455
+ ...processed,
1456
+ [key]: typeof value === "function" ? value(parsedObject.value) : value
1457
+ };
1458
+ },
1459
+ {}
1460
+ );
1461
+ return {
1462
+ ok: true,
1463
+ value: {
1464
+ ...parsedObject.value,
1465
+ ...additionalProperties
1466
+ }
1467
+ };
1468
+ },
1469
+ json: (parsed, opts) => {
1470
+ if (!isPlainObject(parsed)) {
1471
+ return {
1472
+ ok: false,
1473
+ errors: [
1474
+ {
1475
+ path: (opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [],
1476
+ message: getErrorMessageForIncorrectType(parsed, "object")
1477
+ }
1478
+ ]
1479
+ };
1480
+ }
1481
+ const addedPropertyKeys = new Set(Object.keys(properties));
1482
+ const parsedWithoutAddedProperties = filterObject(
1483
+ parsed,
1484
+ Object.keys(parsed).filter((key) => !addedPropertyKeys.has(key))
1485
+ );
1486
+ return objectLike.json(parsedWithoutAddedProperties, opts);
1487
+ },
1488
+ getType: () => objectLike.getType()
1489
+ };
1490
+ return {
1491
+ ...objectSchema,
1492
+ ...getSchemaUtils(objectSchema),
1493
+ ...getObjectLikeUtils(objectSchema)
1494
+ };
1495
+ }
1496
+
1497
+ // src/core/schemas/builders/object/property.ts
1498
+ function property(rawKey, valueSchema) {
1499
+ return {
1500
+ rawKey,
1501
+ valueSchema,
1502
+ isProperty: true
1503
+ };
1504
+ }
1505
+ function isProperty(maybeProperty) {
1506
+ return maybeProperty.isProperty;
1507
+ }
1508
+
1509
+ // src/core/schemas/builders/object/object.ts
1510
+ function object(schemas) {
1511
+ const baseSchema = {
1512
+ _getRawProperties: () => Object.entries(schemas).map(
1513
+ ([parsedKey, propertySchema]) => isProperty(propertySchema) ? propertySchema.rawKey : parsedKey
1514
+ ),
1515
+ _getParsedProperties: () => keys(schemas),
1516
+ parse: (raw, opts) => {
1517
+ const rawKeyToProperty = {};
1518
+ const requiredKeys = [];
1519
+ for (const [parsedKey, schemaOrObjectProperty] of entries(schemas)) {
1520
+ const rawKey = isProperty(schemaOrObjectProperty) ? schemaOrObjectProperty.rawKey : parsedKey;
1521
+ const valueSchema = isProperty(schemaOrObjectProperty) ? schemaOrObjectProperty.valueSchema : schemaOrObjectProperty;
1522
+ const property2 = {
1523
+ rawKey,
1524
+ parsedKey,
1525
+ valueSchema
1526
+ };
1527
+ rawKeyToProperty[rawKey] = property2;
1528
+ if (isSchemaRequired(valueSchema)) {
1529
+ requiredKeys.push(rawKey);
1530
+ }
1531
+ }
1532
+ return validateAndTransformObject({
1533
+ value: raw,
1534
+ requiredKeys,
1535
+ getProperty: (rawKey) => {
1536
+ const property2 = rawKeyToProperty[rawKey];
1537
+ if (property2 == null) {
1538
+ return void 0;
1539
+ }
1540
+ return {
1541
+ transformedKey: property2.parsedKey,
1542
+ transform: (propertyValue) => property2.valueSchema.parse(propertyValue, {
1543
+ ...opts,
1544
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], rawKey]
1545
+ })
1546
+ };
1547
+ },
1548
+ unrecognizedObjectKeys: opts == null ? void 0 : opts.unrecognizedObjectKeys,
1549
+ skipValidation: opts == null ? void 0 : opts.skipValidation,
1550
+ breadcrumbsPrefix: opts == null ? void 0 : opts.breadcrumbsPrefix,
1551
+ omitUndefined: opts == null ? void 0 : opts.omitUndefined
1552
+ });
1553
+ },
1554
+ json: (parsed, opts) => {
1555
+ const requiredKeys = [];
1556
+ for (const [parsedKey, schemaOrObjectProperty] of entries(schemas)) {
1557
+ const valueSchema = isProperty(schemaOrObjectProperty) ? schemaOrObjectProperty.valueSchema : schemaOrObjectProperty;
1558
+ if (isSchemaRequired(valueSchema)) {
1559
+ requiredKeys.push(parsedKey);
1560
+ }
1561
+ }
1562
+ return validateAndTransformObject({
1563
+ value: parsed,
1564
+ requiredKeys,
1565
+ getProperty: (parsedKey) => {
1566
+ const property2 = schemas[parsedKey];
1567
+ if (property2 == null) {
1568
+ return void 0;
1569
+ }
1570
+ if (isProperty(property2)) {
1571
+ return {
1572
+ transformedKey: property2.rawKey,
1573
+ transform: (propertyValue) => property2.valueSchema.json(propertyValue, {
1574
+ ...opts,
1575
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], parsedKey]
1576
+ })
1577
+ };
1578
+ } else {
1579
+ return {
1580
+ transformedKey: parsedKey,
1581
+ transform: (propertyValue) => property2.json(propertyValue, {
1582
+ ...opts,
1583
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], parsedKey]
1584
+ })
1585
+ };
1586
+ }
1587
+ },
1588
+ unrecognizedObjectKeys: opts == null ? void 0 : opts.unrecognizedObjectKeys,
1589
+ skipValidation: opts == null ? void 0 : opts.skipValidation,
1590
+ breadcrumbsPrefix: opts == null ? void 0 : opts.breadcrumbsPrefix,
1591
+ omitUndefined: opts == null ? void 0 : opts.omitUndefined
1592
+ });
1593
+ },
1594
+ getType: () => SchemaType.OBJECT
1595
+ };
1596
+ return {
1597
+ ...maybeSkipValidation(baseSchema),
1598
+ ...getSchemaUtils(baseSchema),
1599
+ ...getObjectLikeUtils(baseSchema),
1600
+ ...getObjectUtils(baseSchema)
1601
+ };
1602
+ }
1603
+ function validateAndTransformObject({
1604
+ value,
1605
+ requiredKeys,
1606
+ getProperty,
1607
+ unrecognizedObjectKeys = "fail",
1608
+ skipValidation = false,
1609
+ breadcrumbsPrefix = []
1610
+ }) {
1611
+ if (!isPlainObject(value)) {
1612
+ return {
1613
+ ok: false,
1614
+ errors: [
1615
+ {
1616
+ path: breadcrumbsPrefix,
1617
+ message: getErrorMessageForIncorrectType(value, "object")
1618
+ }
1619
+ ]
1620
+ };
1621
+ }
1622
+ const missingRequiredKeys = new Set(requiredKeys);
1623
+ const errors = [];
1624
+ const transformed = {};
1625
+ for (const [preTransformedKey, preTransformedItemValue] of Object.entries(value)) {
1626
+ const property2 = getProperty(preTransformedKey);
1627
+ if (property2 != null) {
1628
+ missingRequiredKeys.delete(preTransformedKey);
1629
+ const value2 = property2.transform(preTransformedItemValue);
1630
+ if (value2.ok) {
1631
+ transformed[property2.transformedKey] = value2.value;
1632
+ } else {
1633
+ transformed[preTransformedKey] = preTransformedItemValue;
1634
+ errors.push(...value2.errors);
1635
+ }
1636
+ } else {
1637
+ switch (unrecognizedObjectKeys) {
1638
+ case "fail":
1639
+ errors.push({
1640
+ path: [...breadcrumbsPrefix, preTransformedKey],
1641
+ message: `Unexpected key "${preTransformedKey}"`
1642
+ });
1643
+ break;
1644
+ case "strip":
1645
+ break;
1646
+ case "passthrough":
1647
+ transformed[preTransformedKey] = preTransformedItemValue;
1648
+ break;
1649
+ }
1650
+ }
1651
+ }
1652
+ errors.push(
1653
+ ...requiredKeys.filter((key) => missingRequiredKeys.has(key)).map((key) => ({
1654
+ path: breadcrumbsPrefix,
1655
+ message: `Missing required key "${key}"`
1656
+ }))
1657
+ );
1658
+ if (errors.length === 0 || skipValidation) {
1659
+ return {
1660
+ ok: true,
1661
+ value: transformed
1662
+ };
1663
+ } else {
1664
+ return {
1665
+ ok: false,
1666
+ errors
1667
+ };
1668
+ }
1669
+ }
1670
+ function getObjectUtils(schema) {
1671
+ return {
1672
+ extend: (extension) => {
1673
+ const baseSchema = {
1674
+ _getParsedProperties: () => [...schema._getParsedProperties(), ...extension._getParsedProperties()],
1675
+ _getRawProperties: () => [...schema._getRawProperties(), ...extension._getRawProperties()],
1676
+ parse: (raw, opts) => {
1677
+ return validateAndTransformExtendedObject({
1678
+ extensionKeys: extension._getRawProperties(),
1679
+ value: raw,
1680
+ transformBase: (rawBase) => schema.parse(rawBase, opts),
1681
+ transformExtension: (rawExtension) => extension.parse(rawExtension, opts)
1682
+ });
1683
+ },
1684
+ json: (parsed, opts) => {
1685
+ return validateAndTransformExtendedObject({
1686
+ extensionKeys: extension._getParsedProperties(),
1687
+ value: parsed,
1688
+ transformBase: (parsedBase) => schema.json(parsedBase, opts),
1689
+ transformExtension: (parsedExtension) => extension.json(parsedExtension, opts)
1690
+ });
1691
+ },
1692
+ getType: () => SchemaType.OBJECT
1693
+ };
1694
+ return {
1695
+ ...baseSchema,
1696
+ ...getSchemaUtils(baseSchema),
1697
+ ...getObjectLikeUtils(baseSchema),
1698
+ ...getObjectUtils(baseSchema)
1699
+ };
1700
+ },
1701
+ passthrough: () => {
1702
+ const baseSchema = {
1703
+ _getParsedProperties: () => schema._getParsedProperties(),
1704
+ _getRawProperties: () => schema._getRawProperties(),
1705
+ parse: (raw, opts) => {
1706
+ const transformed = schema.parse(raw, { ...opts, unrecognizedObjectKeys: "passthrough" });
1707
+ if (!transformed.ok) {
1708
+ return transformed;
1709
+ }
1710
+ return {
1711
+ ok: true,
1712
+ value: {
1713
+ ...raw,
1714
+ ...transformed.value
1715
+ }
1716
+ };
1717
+ },
1718
+ json: (parsed, opts) => {
1719
+ const transformed = schema.json(parsed, { ...opts, unrecognizedObjectKeys: "passthrough" });
1720
+ if (!transformed.ok) {
1721
+ return transformed;
1722
+ }
1723
+ return {
1724
+ ok: true,
1725
+ value: {
1726
+ ...parsed,
1727
+ ...transformed.value
1728
+ }
1729
+ };
1730
+ },
1731
+ getType: () => SchemaType.OBJECT
1732
+ };
1733
+ return {
1734
+ ...baseSchema,
1735
+ ...getSchemaUtils(baseSchema),
1736
+ ...getObjectLikeUtils(baseSchema),
1737
+ ...getObjectUtils(baseSchema)
1738
+ };
1739
+ }
1740
+ };
1741
+ }
1742
+ function validateAndTransformExtendedObject({
1743
+ extensionKeys,
1744
+ value,
1745
+ transformBase,
1746
+ transformExtension
1747
+ }) {
1748
+ const extensionPropertiesSet = new Set(extensionKeys);
1749
+ const [extensionProperties, baseProperties] = partition(
1750
+ keys(value),
1751
+ (key) => extensionPropertiesSet.has(key)
1752
+ );
1753
+ const transformedBase = transformBase(filterObject(value, baseProperties));
1754
+ const transformedExtension = transformExtension(filterObject(value, extensionProperties));
1755
+ if (transformedBase.ok && transformedExtension.ok) {
1756
+ return {
1757
+ ok: true,
1758
+ value: {
1759
+ ...transformedBase.value,
1760
+ ...transformedExtension.value
1761
+ }
1762
+ };
1763
+ } else {
1764
+ return {
1765
+ ok: false,
1766
+ errors: [
1767
+ ...transformedBase.ok ? [] : transformedBase.errors,
1768
+ ...transformedExtension.ok ? [] : transformedExtension.errors
1769
+ ]
1770
+ };
1771
+ }
1772
+ }
1773
+ function isSchemaRequired(schema) {
1774
+ return !isSchemaOptional(schema);
1775
+ }
1776
+ function isSchemaOptional(schema) {
1777
+ switch (schema.getType()) {
1778
+ case SchemaType.ANY:
1779
+ case SchemaType.UNKNOWN:
1780
+ case SchemaType.OPTIONAL:
1781
+ case SchemaType.OPTIONAL_NULLABLE:
1782
+ return true;
1783
+ default:
1784
+ return false;
1785
+ }
1786
+ }
1787
+
1788
+ // src/core/schemas/builders/object/objectWithoutOptionalProperties.ts
1789
+ function objectWithoutOptionalProperties(schemas) {
1790
+ return object(schemas);
1791
+ }
1792
+
1793
+ // src/core/schemas/builders/lazy/lazyObject.ts
1794
+ function lazyObject(getter) {
1795
+ const baseSchema = {
1796
+ ...constructLazyBaseSchema(getter),
1797
+ _getRawProperties: () => getMemoizedSchema(getter)._getRawProperties(),
1798
+ _getParsedProperties: () => getMemoizedSchema(getter)._getParsedProperties()
1799
+ };
1800
+ return {
1801
+ ...baseSchema,
1802
+ ...getSchemaUtils(baseSchema),
1803
+ ...getObjectLikeUtils(baseSchema),
1804
+ ...getObjectUtils(baseSchema)
1805
+ };
1806
+ }
1807
+
1808
+ // src/core/schemas/builders/list/list.ts
1809
+ function list(schema) {
1810
+ const baseSchema = {
1811
+ parse: (raw, opts) => validateAndTransformArray(
1812
+ raw,
1813
+ (item, index) => schema.parse(item, {
1814
+ ...opts,
1815
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], `[${index}]`]
1816
+ })
1817
+ ),
1818
+ json: (parsed, opts) => validateAndTransformArray(
1819
+ parsed,
1820
+ (item, index) => schema.json(item, {
1821
+ ...opts,
1822
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], `[${index}]`]
1823
+ })
1824
+ ),
1825
+ getType: () => SchemaType.LIST
1826
+ };
1827
+ return {
1828
+ ...maybeSkipValidation(baseSchema),
1829
+ ...getSchemaUtils(baseSchema)
1830
+ };
1831
+ }
1832
+ function validateAndTransformArray(value, transformItem) {
1833
+ if (!Array.isArray(value)) {
1834
+ return {
1835
+ ok: false,
1836
+ errors: [
1837
+ {
1838
+ message: getErrorMessageForIncorrectType(value, "list"),
1839
+ path: []
1840
+ }
1841
+ ]
1842
+ };
1843
+ }
1844
+ const maybeValidItems = value.map((item, index) => transformItem(item, index));
1845
+ return maybeValidItems.reduce(
1846
+ (acc, item) => {
1847
+ if (acc.ok && item.ok) {
1848
+ return {
1849
+ ok: true,
1850
+ value: [...acc.value, item.value]
1851
+ };
1852
+ }
1853
+ const errors = [];
1854
+ if (!acc.ok) {
1855
+ errors.push(...acc.errors);
1856
+ }
1857
+ if (!item.ok) {
1858
+ errors.push(...item.errors);
1859
+ }
1860
+ return {
1861
+ ok: false,
1862
+ errors
1863
+ };
1864
+ },
1865
+ { ok: true, value: [] }
1866
+ );
1867
+ }
1868
+
1869
+ // src/core/schemas/builders/literals/stringLiteral.ts
1870
+ function stringLiteral(literal) {
1871
+ const schemaCreator = createIdentitySchemaCreator(
1872
+ SchemaType.STRING_LITERAL,
1873
+ (value, { breadcrumbsPrefix = [] } = {}) => {
1874
+ if (value === literal) {
1875
+ return {
1876
+ ok: true,
1877
+ value: literal
1878
+ };
1879
+ } else {
1880
+ return {
1881
+ ok: false,
1882
+ errors: [
1883
+ {
1884
+ path: breadcrumbsPrefix,
1885
+ message: getErrorMessageForIncorrectType(value, `"${literal}"`)
1886
+ }
1887
+ ]
1888
+ };
1889
+ }
1890
+ }
1891
+ );
1892
+ return schemaCreator();
1893
+ }
1894
+
1895
+ // src/core/schemas/builders/literals/booleanLiteral.ts
1896
+ function booleanLiteral(literal) {
1897
+ const schemaCreator = createIdentitySchemaCreator(
1898
+ SchemaType.BOOLEAN_LITERAL,
1899
+ (value, { breadcrumbsPrefix = [] } = {}) => {
1900
+ if (value === literal) {
1901
+ return {
1902
+ ok: true,
1903
+ value: literal
1904
+ };
1905
+ } else {
1906
+ return {
1907
+ ok: false,
1908
+ errors: [
1909
+ {
1910
+ path: breadcrumbsPrefix,
1911
+ message: getErrorMessageForIncorrectType(value, `${literal.toString()}`)
1912
+ }
1913
+ ]
1914
+ };
1915
+ }
1916
+ }
1917
+ );
1918
+ return schemaCreator();
1919
+ }
1920
+
1921
+ // src/core/schemas/builders/primitives/any.ts
1922
+ var any = createIdentitySchemaCreator(SchemaType.ANY, (value) => ({ ok: true, value }));
1923
+
1924
+ // src/core/schemas/builders/primitives/boolean.ts
1925
+ var boolean = createIdentitySchemaCreator(
1926
+ SchemaType.BOOLEAN,
1927
+ (value, { breadcrumbsPrefix = [] } = {}) => {
1928
+ if (typeof value === "boolean") {
1929
+ return {
1930
+ ok: true,
1931
+ value
1932
+ };
1933
+ } else {
1934
+ return {
1935
+ ok: false,
1936
+ errors: [
1937
+ {
1938
+ path: breadcrumbsPrefix,
1939
+ message: getErrorMessageForIncorrectType(value, "boolean")
1940
+ }
1941
+ ]
1942
+ };
1943
+ }
1944
+ }
1945
+ );
1946
+
1947
+ // src/core/schemas/builders/primitives/number.ts
1948
+ var number = createIdentitySchemaCreator(
1949
+ SchemaType.NUMBER,
1950
+ (value, { breadcrumbsPrefix = [] } = {}) => {
1951
+ if (typeof value === "number") {
1952
+ return {
1953
+ ok: true,
1954
+ value
1955
+ };
1956
+ } else {
1957
+ return {
1958
+ ok: false,
1959
+ errors: [
1960
+ {
1961
+ path: breadcrumbsPrefix,
1962
+ message: getErrorMessageForIncorrectType(value, "number")
1963
+ }
1964
+ ]
1965
+ };
1966
+ }
1967
+ }
1968
+ );
1969
+
1970
+ // src/core/schemas/builders/primitives/string.ts
1971
+ var string = createIdentitySchemaCreator(
1972
+ SchemaType.STRING,
1973
+ (value, { breadcrumbsPrefix = [] } = {}) => {
1974
+ if (typeof value === "string") {
1975
+ return {
1976
+ ok: true,
1977
+ value
1978
+ };
1979
+ } else {
1980
+ return {
1981
+ ok: false,
1982
+ errors: [
1983
+ {
1984
+ path: breadcrumbsPrefix,
1985
+ message: getErrorMessageForIncorrectType(value, "string")
1986
+ }
1987
+ ]
1988
+ };
1989
+ }
1990
+ }
1991
+ );
1992
+
1993
+ // src/core/schemas/builders/primitives/unknown.ts
1994
+ var unknown = createIdentitySchemaCreator(SchemaType.UNKNOWN, (value) => ({ ok: true, value }));
1995
+
1996
+ // src/core/schemas/builders/record/record.ts
1997
+ function record(keySchema, valueSchema) {
1998
+ const baseSchema = {
1999
+ parse: (raw, opts) => {
2000
+ return validateAndTransformRecord({
2001
+ value: raw,
2002
+ isKeyNumeric: keySchema.getType() === SchemaType.NUMBER,
2003
+ transformKey: (key) => keySchema.parse(key, {
2004
+ ...opts,
2005
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], `${key} (key)`]
2006
+ }),
2007
+ transformValue: (value, key) => valueSchema.parse(value, {
2008
+ ...opts,
2009
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], `${key}`]
2010
+ }),
2011
+ breadcrumbsPrefix: opts == null ? void 0 : opts.breadcrumbsPrefix
2012
+ });
2013
+ },
2014
+ json: (parsed, opts) => {
2015
+ return validateAndTransformRecord({
2016
+ value: parsed,
2017
+ isKeyNumeric: keySchema.getType() === SchemaType.NUMBER,
2018
+ transformKey: (key) => keySchema.json(key, {
2019
+ ...opts,
2020
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], `${key} (key)`]
2021
+ }),
2022
+ transformValue: (value, key) => valueSchema.json(value, {
2023
+ ...opts,
2024
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], `${key}`]
2025
+ }),
2026
+ breadcrumbsPrefix: opts == null ? void 0 : opts.breadcrumbsPrefix
2027
+ });
2028
+ },
2029
+ getType: () => SchemaType.RECORD
2030
+ };
2031
+ return {
2032
+ ...maybeSkipValidation(baseSchema),
2033
+ ...getSchemaUtils(baseSchema)
2034
+ };
2035
+ }
2036
+ function validateAndTransformRecord({
2037
+ value,
2038
+ isKeyNumeric,
2039
+ transformKey,
2040
+ transformValue,
2041
+ breadcrumbsPrefix = []
2042
+ }) {
2043
+ if (!isPlainObject(value)) {
2044
+ return {
2045
+ ok: false,
2046
+ errors: [
2047
+ {
2048
+ path: breadcrumbsPrefix,
2049
+ message: getErrorMessageForIncorrectType(value, "object")
2050
+ }
2051
+ ]
2052
+ };
2053
+ }
2054
+ return entries(value).reduce(
2055
+ (accPromise, [stringKey, value2]) => {
2056
+ if (value2 === void 0) {
2057
+ return accPromise;
2058
+ }
2059
+ const acc = accPromise;
2060
+ let key = stringKey;
2061
+ if (isKeyNumeric) {
2062
+ const numberKey = stringKey.length > 0 ? Number(stringKey) : NaN;
2063
+ if (!isNaN(numberKey)) {
2064
+ key = numberKey;
2065
+ }
2066
+ }
2067
+ const transformedKey = transformKey(key);
2068
+ const transformedValue = transformValue(value2, key);
2069
+ if (acc.ok && transformedKey.ok && transformedValue.ok) {
2070
+ return {
2071
+ ok: true,
2072
+ value: {
2073
+ ...acc.value,
2074
+ [transformedKey.value]: transformedValue.value
2075
+ }
2076
+ };
2077
+ }
2078
+ const errors = [];
2079
+ if (!acc.ok) {
2080
+ errors.push(...acc.errors);
2081
+ }
2082
+ if (!transformedKey.ok) {
2083
+ errors.push(...transformedKey.errors);
2084
+ }
2085
+ if (!transformedValue.ok) {
2086
+ errors.push(...transformedValue.errors);
2087
+ }
2088
+ return {
2089
+ ok: false,
2090
+ errors
2091
+ };
2092
+ },
2093
+ { ok: true, value: {} }
2094
+ );
2095
+ }
2096
+
2097
+ // src/core/schemas/builders/set/set.ts
2098
+ function set(schema) {
2099
+ const listSchema = list(schema);
2100
+ const baseSchema = {
2101
+ parse: (raw, opts) => {
2102
+ const parsedList = listSchema.parse(raw, opts);
2103
+ if (parsedList.ok) {
2104
+ return {
2105
+ ok: true,
2106
+ value: new Set(parsedList.value)
2107
+ };
2108
+ } else {
2109
+ return parsedList;
2110
+ }
2111
+ },
2112
+ json: (parsed, opts) => {
2113
+ if (!(parsed instanceof Set)) {
2114
+ return {
2115
+ ok: false,
2116
+ errors: [
2117
+ {
2118
+ path: (opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [],
2119
+ message: getErrorMessageForIncorrectType(parsed, "Set")
2120
+ }
2121
+ ]
2122
+ };
2123
+ }
2124
+ const jsonList = listSchema.json([...parsed], opts);
2125
+ return jsonList;
2126
+ },
2127
+ getType: () => SchemaType.SET
2128
+ };
2129
+ return {
2130
+ ...maybeSkipValidation(baseSchema),
2131
+ ...getSchemaUtils(baseSchema)
2132
+ };
2133
+ }
2134
+
2135
+ // src/core/schemas/builders/undiscriminated-union/undiscriminatedUnion.ts
2136
+ function undiscriminatedUnion(schemas) {
2137
+ const baseSchema = {
2138
+ parse: (raw, opts) => {
2139
+ return validateAndTransformUndiscriminatedUnion(
2140
+ (schema, opts2) => schema.parse(raw, opts2),
2141
+ schemas,
2142
+ opts
2143
+ );
2144
+ },
2145
+ json: (parsed, opts) => {
2146
+ return validateAndTransformUndiscriminatedUnion(
2147
+ (schema, opts2) => schema.json(parsed, opts2),
2148
+ schemas,
2149
+ opts
2150
+ );
2151
+ },
2152
+ getType: () => SchemaType.UNDISCRIMINATED_UNION
2153
+ };
2154
+ return {
2155
+ ...maybeSkipValidation(baseSchema),
2156
+ ...getSchemaUtils(baseSchema)
2157
+ };
2158
+ }
2159
+ function validateAndTransformUndiscriminatedUnion(transform2, schemas, opts) {
2160
+ const errors = [];
2161
+ for (const [index, schema] of schemas.entries()) {
2162
+ const transformed = transform2(schema, { ...opts, skipValidation: false });
2163
+ if (transformed.ok) {
2164
+ return transformed;
2165
+ } else {
2166
+ for (const error of transformed.errors) {
2167
+ errors.push({
2168
+ path: error.path,
2169
+ message: `[Variant ${index}] ${error.message}`
2170
+ });
2171
+ }
2172
+ }
2173
+ }
2174
+ return {
2175
+ ok: false,
2176
+ errors
2177
+ };
2178
+ }
2179
+
2180
+ // src/core/schemas/builders/union/discriminant.ts
2181
+ function discriminant(parsedDiscriminant, rawDiscriminant) {
2182
+ return {
2183
+ parsedDiscriminant,
2184
+ rawDiscriminant
2185
+ };
2186
+ }
2187
+
2188
+ // src/core/schemas/builders/union/union.ts
2189
+ function union(discriminant2, union2) {
2190
+ const rawDiscriminant = typeof discriminant2 === "string" ? discriminant2 : discriminant2.rawDiscriminant;
2191
+ const parsedDiscriminant = typeof discriminant2 === "string" ? discriminant2 : discriminant2.parsedDiscriminant;
2192
+ const discriminantValueSchema = enum_(keys(union2));
2193
+ const baseSchema = {
2194
+ parse: (raw, opts) => {
2195
+ return transformAndValidateUnion({
2196
+ value: raw,
2197
+ discriminant: rawDiscriminant,
2198
+ transformedDiscriminant: parsedDiscriminant,
2199
+ transformDiscriminantValue: (discriminantValue) => discriminantValueSchema.parse(discriminantValue, {
2200
+ allowUnrecognizedEnumValues: opts == null ? void 0 : opts.allowUnrecognizedUnionMembers,
2201
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], rawDiscriminant]
2202
+ }),
2203
+ getAdditionalPropertiesSchema: (discriminantValue) => union2[discriminantValue],
2204
+ allowUnrecognizedUnionMembers: opts == null ? void 0 : opts.allowUnrecognizedUnionMembers,
2205
+ transformAdditionalProperties: (additionalProperties, additionalPropertiesSchema) => additionalPropertiesSchema.parse(additionalProperties, opts),
2206
+ breadcrumbsPrefix: opts == null ? void 0 : opts.breadcrumbsPrefix
2207
+ });
2208
+ },
2209
+ json: (parsed, opts) => {
2210
+ return transformAndValidateUnion({
2211
+ value: parsed,
2212
+ discriminant: parsedDiscriminant,
2213
+ transformedDiscriminant: rawDiscriminant,
2214
+ transformDiscriminantValue: (discriminantValue) => discriminantValueSchema.json(discriminantValue, {
2215
+ allowUnrecognizedEnumValues: opts == null ? void 0 : opts.allowUnrecognizedUnionMembers,
2216
+ breadcrumbsPrefix: [...(opts == null ? void 0 : opts.breadcrumbsPrefix) ?? [], parsedDiscriminant]
2217
+ }),
2218
+ getAdditionalPropertiesSchema: (discriminantValue) => union2[discriminantValue],
2219
+ allowUnrecognizedUnionMembers: opts == null ? void 0 : opts.allowUnrecognizedUnionMembers,
2220
+ transformAdditionalProperties: (additionalProperties, additionalPropertiesSchema) => additionalPropertiesSchema.json(additionalProperties, opts),
2221
+ breadcrumbsPrefix: opts == null ? void 0 : opts.breadcrumbsPrefix
2222
+ });
2223
+ },
2224
+ getType: () => SchemaType.UNION
2225
+ };
2226
+ return {
2227
+ ...maybeSkipValidation(baseSchema),
2228
+ ...getSchemaUtils(baseSchema),
2229
+ ...getObjectLikeUtils(baseSchema)
2230
+ };
2231
+ }
2232
+ function transformAndValidateUnion({
2233
+ value,
2234
+ discriminant: discriminant2,
2235
+ transformedDiscriminant,
2236
+ transformDiscriminantValue,
2237
+ getAdditionalPropertiesSchema,
2238
+ allowUnrecognizedUnionMembers = false,
2239
+ transformAdditionalProperties,
2240
+ breadcrumbsPrefix = []
2241
+ }) {
2242
+ if (!isPlainObject(value)) {
2243
+ return {
2244
+ ok: false,
2245
+ errors: [
2246
+ {
2247
+ path: breadcrumbsPrefix,
2248
+ message: getErrorMessageForIncorrectType(value, "object")
2249
+ }
2250
+ ]
2251
+ };
2252
+ }
2253
+ const { [discriminant2]: discriminantValue, ...additionalProperties } = value;
2254
+ if (discriminantValue == null) {
2255
+ return {
2256
+ ok: false,
2257
+ errors: [
2258
+ {
2259
+ path: breadcrumbsPrefix,
2260
+ message: `Missing discriminant ("${discriminant2}")`
2261
+ }
2262
+ ]
2263
+ };
2264
+ }
2265
+ const transformedDiscriminantValue = transformDiscriminantValue(discriminantValue);
2266
+ if (!transformedDiscriminantValue.ok) {
2267
+ return {
2268
+ ok: false,
2269
+ errors: transformedDiscriminantValue.errors
2270
+ };
2271
+ }
2272
+ const additionalPropertiesSchema = getAdditionalPropertiesSchema(transformedDiscriminantValue.value);
2273
+ if (additionalPropertiesSchema == null) {
2274
+ if (allowUnrecognizedUnionMembers) {
2275
+ return {
2276
+ ok: true,
2277
+ value: {
2278
+ [transformedDiscriminant]: transformedDiscriminantValue.value,
2279
+ ...additionalProperties
2280
+ }
2281
+ };
2282
+ } else {
2283
+ return {
2284
+ ok: false,
2285
+ errors: [
2286
+ {
2287
+ path: [...breadcrumbsPrefix, discriminant2],
2288
+ message: "Unexpected discriminant value"
2289
+ }
2290
+ ]
2291
+ };
2292
+ }
2293
+ }
2294
+ const transformedAdditionalProperties = transformAdditionalProperties(
2295
+ additionalProperties,
2296
+ additionalPropertiesSchema
2297
+ );
2298
+ if (!transformedAdditionalProperties.ok) {
2299
+ return transformedAdditionalProperties;
2300
+ }
2301
+ return {
2302
+ ok: true,
2303
+ value: {
2304
+ [transformedDiscriminant]: discriminantValue,
2305
+ ...transformedAdditionalProperties.value
2306
+ }
2307
+ };
2308
+ }
2309
+ export {
2310
+ BasicAuth,
2311
+ BearerToken,
2312
+ RUNTIME,
2313
+ Supplier,
2314
+ fetcher,
2315
+ getHeader,
2316
+ schemas_exports as serialization
2317
+ };