@fanvue/builder-sdk 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +361 -1
  2. package/dist/bridge/index.d.ts +2 -0
  3. package/dist/bridge/index.js +3 -0
  4. package/dist/bridge-QnF7P4Co.js +336 -0
  5. package/dist/bridge-QnF7P4Co.js.map +1 -0
  6. package/dist/core/index.d.ts +2 -2
  7. package/dist/core/index.js +3 -2
  8. package/dist/core-BhKiA55a.js +2962 -0
  9. package/dist/core-BhKiA55a.js.map +1 -0
  10. package/dist/index-C3CXrRiw.d.ts +1412 -0
  11. package/dist/index-C3CXrRiw.d.ts.map +1 -0
  12. package/dist/index-CEFYZtlb.d.ts +223 -0
  13. package/dist/index-CEFYZtlb.d.ts.map +1 -0
  14. package/dist/{index-pS9wR5yg.d.ts → index-cf3ZMnLJ.d.ts} +524 -901
  15. package/dist/index-cf3ZMnLJ.d.ts.map +1 -0
  16. package/dist/index-v_6Z4Q0u.d.ts +84 -0
  17. package/dist/index-v_6Z4Q0u.d.ts.map +1 -0
  18. package/dist/{core-CvVOMyqr.js → index.cjs-teGsk6HB.js} +1506 -2826
  19. package/dist/index.cjs-teGsk6HB.js.map +1 -0
  20. package/dist/nextjs/embedded-app/index.d.ts +2 -2
  21. package/dist/nextjs/embedded-app/index.js +3 -2
  22. package/dist/nextjs/embedded-app/index.js.map +1 -1
  23. package/dist/nextjs/off-platform/index.d.ts +3 -3
  24. package/dist/nextjs/off-platform/index.d.ts.map +1 -1
  25. package/dist/nextjs/off-platform/index.js +4 -3
  26. package/dist/nextjs/off-platform/index.js.map +1 -1
  27. package/dist/nextjs-CvVhtMdb.js +144 -0
  28. package/dist/nextjs-CvVhtMdb.js.map +1 -0
  29. package/dist/react/index.d.ts +37 -2
  30. package/dist/react/index.d.ts.map +1 -1
  31. package/dist/react/index.js +61 -2
  32. package/dist/react/index.js.map +1 -1
  33. package/package.json +20 -16
  34. package/dist/core-CvVOMyqr.js.map +0 -1
  35. package/dist/index-CweVyIKX.d.ts +0 -48
  36. package/dist/index-CweVyIKX.d.ts.map +0 -1
  37. package/dist/index-pS9wR5yg.d.ts.map +0 -1
  38. package/dist/nextjs-CESI_EiU.js +0 -80
  39. package/dist/nextjs-CESI_EiU.js.map +0 -1
@@ -1,1417 +1,829 @@
1
1
  //#region \0rolldown/runtime.js
2
2
  var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
3
- //#endregion
4
- //#region src/core/constants.ts
5
- /** The `Bearer ` token prefix (includes trailing space). */
6
- const BEARER_PREFIX = "Bearer ";
7
- /** Response header carrying a refreshed session JWT back to the client. */
8
- const HEADER_UPDATED_SESSION = "X-Updated-Session";
9
- //#endregion
10
- //#region src/core/defaults.ts
11
- /** Default OAuth scopes requested during authorization. */
12
- const DEFAULT_SCOPES = "openid offline_access offline";
13
- /** Default OAuth issuer URL for Fanvue authentication. */
14
- const DEFAULT_ISSUER_URL = "https://auth.fanvue.com";
15
- /** Default base URL for the Fanvue API. */
16
- const DEFAULT_API_BASE_URL = "https://api.fanvue.com";
17
- /** Default base URL for the Fanvue platform (embedded authorize-on-behalf). */
18
- const DEFAULT_PLATFORM_URL = "https://www.fanvue.com";
19
- /** The Fanvue API version header value sent with every request. */
20
- const API_VERSION = "2025-06-26";
21
- /**
22
- * Validates that a URL belongs to the `fanvue.com` domain.
23
- *
24
- * @param url - The URL string to validate.
25
- * @throws If the URL is malformed or its hostname is not `fanvue.com`
26
- * (or a subdomain of it).
27
- */
28
- function assertFanvueDomain(url) {
29
- let hostname;
30
- try {
31
- hostname = new URL(url).hostname;
32
- } catch {
33
- throw new Error(`Invalid apiBaseUrl: "${url}" is not a valid URL.`);
34
- }
35
- if (hostname !== "fanvue.com" && !hostname.endsWith(".fanvue.com")) throw new Error(`Invalid apiBaseUrl: "${url}" must be a fanvue.com domain (e.g. https://api.fanvue.com).`);
36
- }
37
- //#endregion
38
- //#region node_modules/.pnpm/neverthrow@8.2.0/node_modules/neverthrow/dist/index.cjs.js
39
- var require_index_cjs = /* @__PURE__ */ __commonJSMin(((exports) => {
40
- const defaultErrorConfig = { withStackTrace: false };
41
- const createNeverThrowError = (message, result, config = defaultErrorConfig) => {
42
- return {
43
- data: result.isOk() ? {
44
- type: "Ok",
45
- value: result.value
46
- } : {
47
- type: "Err",
48
- value: result.error
3
+ Object.freeze({ status: "aborted" });
4
+ function $constructor(name, initializer, params) {
5
+ function init(inst, def) {
6
+ if (!inst._zod) Object.defineProperty(inst, "_zod", {
7
+ value: {
8
+ def,
9
+ constr: _,
10
+ traits: /* @__PURE__ */ new Set()
49
11
  },
50
- message,
51
- stack: config.withStackTrace ? (/* @__PURE__ */ new Error()).stack : void 0
52
- };
53
- };
54
- /******************************************************************************
55
- Copyright (c) Microsoft Corporation.
56
-
57
- Permission to use, copy, modify, and/or distribute this software for any
58
- purpose with or without fee is hereby granted.
59
-
60
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
61
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
62
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
63
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
64
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
65
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
66
- PERFORMANCE OF THIS SOFTWARE.
67
- ***************************************************************************** */
68
- function __awaiter(thisArg, _arguments, P, generator) {
69
- function adopt(value) {
70
- return value instanceof P ? value : new P(function(resolve) {
71
- resolve(value);
72
- });
73
- }
74
- return new (P || (P = Promise))(function(resolve, reject) {
75
- function fulfilled(value) {
76
- try {
77
- step(generator.next(value));
78
- } catch (e) {
79
- reject(e);
80
- }
81
- }
82
- function rejected(value) {
83
- try {
84
- step(generator["throw"](value));
85
- } catch (e) {
86
- reject(e);
87
- }
88
- }
89
- function step(result) {
90
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
91
- }
92
- step((generator = generator.apply(thisArg, _arguments || [])).next());
12
+ enumerable: false
93
13
  });
14
+ if (inst._zod.traits.has(name)) return;
15
+ inst._zod.traits.add(name);
16
+ initializer(inst, def);
17
+ const proto = _.prototype;
18
+ const keys = Object.keys(proto);
19
+ for (let i = 0; i < keys.length; i++) {
20
+ const k = keys[i];
21
+ if (!(k in inst)) inst[k] = proto[k].bind(inst);
22
+ }
94
23
  }
95
- function __values(o) {
96
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
97
- if (m) return m.call(o);
98
- if (o && typeof o.length === "number") return { next: function() {
99
- if (o && i >= o.length) o = void 0;
100
- return {
101
- value: o && o[i++],
102
- done: !o
103
- };
104
- } };
105
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
106
- }
107
- function __await(v) {
108
- return this instanceof __await ? (this.v = v, this) : new __await(v);
24
+ const Parent = params?.Parent ?? Object;
25
+ class Definition extends Parent {}
26
+ Object.defineProperty(Definition, "name", { value: name });
27
+ function _(def) {
28
+ var _a;
29
+ const inst = params?.Parent ? new Definition() : this;
30
+ init(inst, def);
31
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
32
+ for (const fn of inst._zod.deferred) fn();
33
+ return inst;
109
34
  }
110
- function __asyncGenerator(thisArg, _arguments, generator) {
111
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
112
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
113
- return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
114
- return this;
115
- }, i;
116
- function awaitReturn(f) {
117
- return function(v) {
118
- return Promise.resolve(v).then(f, reject);
119
- };
120
- }
121
- function verb(n, f) {
122
- if (g[n]) {
123
- i[n] = function(v) {
124
- return new Promise(function(a, b) {
125
- q.push([
126
- n,
127
- v,
128
- a,
129
- b
130
- ]) > 1 || resume(n, v);
131
- });
132
- };
133
- if (f) i[n] = f(i[n]);
134
- }
135
- }
136
- function resume(n, v) {
137
- try {
138
- step(g[n](v));
139
- } catch (e) {
140
- settle(q[0][3], e);
141
- }
142
- }
143
- function step(r) {
144
- r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
145
- }
146
- function fulfill(value) {
147
- resume("next", value);
148
- }
149
- function reject(value) {
150
- resume("throw", value);
151
- }
152
- function settle(f, v) {
153
- if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
154
- }
35
+ Object.defineProperty(_, "init", { value: init });
36
+ Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => {
37
+ if (params?.Parent && inst instanceof params.Parent) return true;
38
+ return inst?._zod?.traits?.has(name);
39
+ } });
40
+ Object.defineProperty(_, "name", { value: name });
41
+ return _;
42
+ }
43
+ var $ZodAsyncError = class extends Error {
44
+ constructor() {
45
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
155
46
  }
156
- function __asyncDelegator(o) {
157
- var i, p;
158
- return i = {}, verb("next"), verb("throw", function(e) {
159
- throw e;
160
- }), verb("return"), i[Symbol.iterator] = function() {
161
- return this;
162
- }, i;
163
- function verb(n, f) {
164
- i[n] = o[n] ? function(v) {
165
- return (p = !p) ? {
166
- value: __await(o[n](v)),
167
- done: false
168
- } : f ? f(v) : v;
169
- } : f;
170
- }
47
+ };
48
+ var $ZodEncodeError = class extends Error {
49
+ constructor(name) {
50
+ super(`Encountered unidirectional transform during encode: ${name}`);
51
+ this.name = "ZodEncodeError";
171
52
  }
172
- function __asyncValues(o) {
173
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
174
- var m = o[Symbol.asyncIterator], i;
175
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
176
- return this;
177
- }, i);
178
- function verb(n) {
179
- i[n] = o[n] && function(v) {
180
- return new Promise(function(resolve, reject) {
181
- v = o[n](v), settle(resolve, reject, v.done, v.value);
182
- });
183
- };
184
- }
185
- function settle(resolve, reject, d, v) {
186
- Promise.resolve(v).then(function(v) {
187
- resolve({
188
- value: v,
189
- done: d
190
- });
191
- }, reject);
53
+ };
54
+ const globalConfig = {};
55
+ function config(newConfig) {
56
+ if (newConfig) Object.assign(globalConfig, newConfig);
57
+ return globalConfig;
58
+ }
59
+ //#endregion
60
+ //#region node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js
61
+ function getEnumValues(entries) {
62
+ const numericValues = Object.values(entries).filter((v) => typeof v === "number");
63
+ return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
64
+ }
65
+ function jsonStringifyReplacer(_, value) {
66
+ if (typeof value === "bigint") return value.toString();
67
+ return value;
68
+ }
69
+ function cached(getter) {
70
+ return { get value() {
71
+ {
72
+ const value = getter();
73
+ Object.defineProperty(this, "value", { value });
74
+ return value;
192
75
  }
76
+ throw new Error("cached value already set");
77
+ } };
78
+ }
79
+ function nullish(input) {
80
+ return input === null || input === void 0;
81
+ }
82
+ function cleanRegex(source) {
83
+ const start = source.startsWith("^") ? 1 : 0;
84
+ const end = source.endsWith("$") ? source.length - 1 : source.length;
85
+ return source.slice(start, end);
86
+ }
87
+ function floatSafeRemainder(val, step) {
88
+ const valDecCount = (val.toString().split(".")[1] || "").length;
89
+ const stepString = step.toString();
90
+ let stepDecCount = (stepString.split(".")[1] || "").length;
91
+ if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
92
+ const match = stepString.match(/\d?e-(\d?)/);
93
+ if (match?.[1]) stepDecCount = Number.parseInt(match[1]);
193
94
  }
194
- var ResultAsync = class ResultAsync {
195
- constructor(res) {
196
- this._promise = res;
197
- }
198
- static fromSafePromise(promise) {
199
- return new ResultAsync(promise.then((value) => new Ok(value)));
200
- }
201
- static fromPromise(promise, errorFn) {
202
- return new ResultAsync(promise.then((value) => new Ok(value)).catch((e) => new Err(errorFn(e))));
203
- }
204
- static fromThrowable(fn, errorFn) {
205
- return (...args) => {
206
- return new ResultAsync(__awaiter(this, void 0, void 0, function* () {
207
- try {
208
- return new Ok(yield fn(...args));
209
- } catch (error) {
210
- return new Err(errorFn ? errorFn(error) : error);
211
- }
212
- }));
213
- };
214
- }
215
- static combine(asyncResultList) {
216
- return combineResultAsyncList(asyncResultList);
217
- }
218
- static combineWithAllErrors(asyncResultList) {
219
- return combineResultAsyncListWithAllErrors(asyncResultList);
220
- }
221
- map(f) {
222
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
223
- if (res.isErr()) return new Err(res.error);
224
- return new Ok(yield f(res.value));
225
- })));
226
- }
227
- andThrough(f) {
228
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
229
- if (res.isErr()) return new Err(res.error);
230
- const newRes = yield f(res.value);
231
- if (newRes.isErr()) return new Err(newRes.error);
232
- return new Ok(res.value);
233
- })));
234
- }
235
- andTee(f) {
236
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
237
- if (res.isErr()) return new Err(res.error);
238
- try {
239
- yield f(res.value);
240
- } catch (e) {}
241
- return new Ok(res.value);
242
- })));
243
- }
244
- orTee(f) {
245
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
246
- if (res.isOk()) return new Ok(res.value);
247
- try {
248
- yield f(res.error);
249
- } catch (e) {}
250
- return new Err(res.error);
251
- })));
252
- }
253
- mapErr(f) {
254
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
255
- if (res.isOk()) return new Ok(res.value);
256
- return new Err(yield f(res.error));
257
- })));
258
- }
259
- andThen(f) {
260
- return new ResultAsync(this._promise.then((res) => {
261
- if (res.isErr()) return new Err(res.error);
262
- const newValue = f(res.value);
263
- return newValue instanceof ResultAsync ? newValue._promise : newValue;
264
- }));
265
- }
266
- orElse(f) {
267
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
268
- if (res.isErr()) return f(res.error);
269
- return new Ok(res.value);
270
- })));
271
- }
272
- match(ok, _err) {
273
- return this._promise.then((res) => res.match(ok, _err));
274
- }
275
- unwrapOr(t) {
276
- return this._promise.then((res) => res.unwrapOr(t));
277
- }
278
- /**
279
- * @deprecated will be removed in 9.0.0.
280
- *
281
- * You can use `safeTry` without this method.
282
- * @example
283
- * ```typescript
284
- * safeTry(async function* () {
285
- * const okValue = yield* yourResult
286
- * })
287
- * ```
288
- * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
289
- */
290
- safeUnwrap() {
291
- return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
292
- return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
293
- });
294
- }
295
- then(successCallback, failureCallback) {
296
- return this._promise.then(successCallback, failureCallback);
297
- }
298
- [Symbol.asyncIterator]() {
299
- return __asyncGenerator(this, arguments, function* _a() {
300
- const result = yield __await(this._promise);
301
- if (result.isErr()) yield yield __await(errAsync(result.error));
302
- return yield __await(result.value);
303
- });
304
- }
305
- };
306
- function okAsync(value) {
307
- return new ResultAsync(Promise.resolve(new Ok(value)));
308
- }
309
- function errAsync(err) {
310
- return new ResultAsync(Promise.resolve(new Err(err)));
311
- }
312
- const fromPromise = ResultAsync.fromPromise;
313
- const fromSafePromise = ResultAsync.fromSafePromise;
314
- const fromAsyncThrowable = ResultAsync.fromThrowable;
315
- /**
316
- * Short circuits on the FIRST Err value that we find
317
- */
318
- const combineResultList = (resultList) => {
319
- let acc = ok([]);
320
- for (const result of resultList) if (result.isErr()) {
321
- acc = err(result.error);
322
- break;
323
- } else acc.map((list) => list.push(result.value));
324
- return acc;
325
- };
326
- const combineResultAsyncList = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultList);
327
- /**
328
- * Give a list of all the errors we find
329
- */
330
- const combineResultListWithAllErrors = (resultList) => {
331
- let acc = ok([]);
332
- for (const result of resultList) if (result.isErr() && acc.isErr()) acc.error.push(result.error);
333
- else if (result.isErr() && acc.isOk()) acc = err([result.error]);
334
- else if (result.isOk() && acc.isOk()) acc.value.push(result.value);
335
- return acc;
336
- };
337
- const combineResultAsyncListWithAllErrors = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultListWithAllErrors);
338
- exports.Result = void 0;
339
- (function(Result) {
340
- /**
341
- * Wraps a function with a try catch, creating a new function with the same
342
- * arguments but returning `Ok` if successful, `Err` if the function throws
343
- *
344
- * @param fn function to wrap with ok on success or err on failure
345
- * @param errorFn when an error is thrown, this will wrap the error result if provided
346
- */
347
- function fromThrowable(fn, errorFn) {
348
- return (...args) => {
349
- try {
350
- return ok(fn(...args));
351
- } catch (e) {
352
- return err(errorFn ? errorFn(e) : e);
353
- }
354
- };
355
- }
356
- Result.fromThrowable = fromThrowable;
357
- function combine(resultList) {
358
- return combineResultList(resultList);
359
- }
360
- Result.combine = combine;
361
- function combineWithAllErrors(resultList) {
362
- return combineResultListWithAllErrors(resultList);
363
- }
364
- Result.combineWithAllErrors = combineWithAllErrors;
365
- })(exports.Result || (exports.Result = {}));
366
- function ok(value) {
367
- return new Ok(value);
95
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
96
+ return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount;
97
+ }
98
+ const EVALUATING = Symbol("evaluating");
99
+ function defineLazy(object, key, getter) {
100
+ let value = void 0;
101
+ Object.defineProperty(object, key, {
102
+ get() {
103
+ if (value === EVALUATING) return;
104
+ if (value === void 0) {
105
+ value = EVALUATING;
106
+ value = getter();
107
+ }
108
+ return value;
109
+ },
110
+ set(v) {
111
+ Object.defineProperty(object, key, { value: v });
112
+ },
113
+ configurable: true
114
+ });
115
+ }
116
+ function assignProp(target, prop, value) {
117
+ Object.defineProperty(target, prop, {
118
+ value,
119
+ writable: true,
120
+ enumerable: true,
121
+ configurable: true
122
+ });
123
+ }
124
+ function mergeDefs(...defs) {
125
+ const mergedDescriptors = {};
126
+ for (const def of defs) {
127
+ const descriptors = Object.getOwnPropertyDescriptors(def);
128
+ Object.assign(mergedDescriptors, descriptors);
368
129
  }
369
- function err(err) {
370
- return new Err(err);
130
+ return Object.defineProperties({}, mergedDescriptors);
131
+ }
132
+ function esc(str) {
133
+ return JSON.stringify(str);
134
+ }
135
+ function slugify(input) {
136
+ return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
137
+ }
138
+ const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
139
+ function isObject(data) {
140
+ return typeof data === "object" && data !== null && !Array.isArray(data);
141
+ }
142
+ const allowsEval = cached(() => {
143
+ if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false;
144
+ try {
145
+ new Function("");
146
+ return true;
147
+ } catch (_) {
148
+ return false;
371
149
  }
372
- function safeTry(body) {
373
- const n = body().next();
374
- if (n instanceof Promise) return new ResultAsync(n.then((r) => r.value));
375
- return n.value;
150
+ });
151
+ function isPlainObject(o) {
152
+ if (isObject(o) === false) return false;
153
+ const ctor = o.constructor;
154
+ if (ctor === void 0) return true;
155
+ if (typeof ctor !== "function") return true;
156
+ const prot = ctor.prototype;
157
+ if (isObject(prot) === false) return false;
158
+ if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
159
+ return true;
160
+ }
161
+ function shallowClone(o) {
162
+ if (isPlainObject(o)) return { ...o };
163
+ if (Array.isArray(o)) return [...o];
164
+ return o;
165
+ }
166
+ const propertyKeyTypes = new Set([
167
+ "string",
168
+ "number",
169
+ "symbol"
170
+ ]);
171
+ function escapeRegex(str) {
172
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
173
+ }
174
+ function clone(inst, def, params) {
175
+ const cl = new inst._zod.constr(def ?? inst._zod.def);
176
+ if (!def || params?.parent) cl._zod.parent = inst;
177
+ return cl;
178
+ }
179
+ function normalizeParams(_params) {
180
+ const params = _params;
181
+ if (!params) return {};
182
+ if (typeof params === "string") return { error: () => params };
183
+ if (params?.message !== void 0) {
184
+ if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params");
185
+ params.error = params.message;
376
186
  }
377
- var Ok = class {
378
- constructor(value) {
379
- this.value = value;
380
- }
381
- isOk() {
382
- return true;
383
- }
384
- isErr() {
385
- return !this.isOk();
386
- }
387
- map(f) {
388
- return ok(f(this.value));
389
- }
390
- mapErr(_f) {
391
- return ok(this.value);
392
- }
393
- andThen(f) {
394
- return f(this.value);
395
- }
396
- andThrough(f) {
397
- return f(this.value).map((_value) => this.value);
398
- }
399
- andTee(f) {
400
- try {
401
- f(this.value);
402
- } catch (e) {}
403
- return ok(this.value);
404
- }
405
- orTee(_f) {
406
- return ok(this.value);
407
- }
408
- orElse(_f) {
409
- return ok(this.value);
410
- }
411
- asyncAndThen(f) {
412
- return f(this.value);
413
- }
414
- asyncAndThrough(f) {
415
- return f(this.value).map(() => this.value);
416
- }
417
- asyncMap(f) {
418
- return ResultAsync.fromSafePromise(f(this.value));
419
- }
420
- unwrapOr(_v) {
421
- return this.value;
422
- }
423
- match(ok, _err) {
424
- return ok(this.value);
425
- }
426
- safeUnwrap() {
427
- const value = this.value;
428
- return (function* () {
429
- return value;
430
- })();
431
- }
432
- _unsafeUnwrap(_) {
433
- return this.value;
434
- }
435
- _unsafeUnwrapErr(config) {
436
- throw createNeverThrowError("Called `_unsafeUnwrapErr` on an Ok", this, config);
437
- }
438
- *[Symbol.iterator]() {
439
- return this.value;
440
- }
441
- };
442
- var Err = class {
443
- constructor(error) {
444
- this.error = error;
445
- }
446
- isOk() {
447
- return false;
448
- }
449
- isErr() {
450
- return !this.isOk();
451
- }
452
- map(_f) {
453
- return err(this.error);
454
- }
455
- mapErr(f) {
456
- return err(f(this.error));
457
- }
458
- andThrough(_f) {
459
- return err(this.error);
460
- }
461
- andTee(_f) {
462
- return err(this.error);
463
- }
464
- orTee(f) {
465
- try {
466
- f(this.error);
467
- } catch (e) {}
468
- return err(this.error);
469
- }
470
- andThen(_f) {
471
- return err(this.error);
472
- }
473
- orElse(f) {
474
- return f(this.error);
475
- }
476
- asyncAndThen(_f) {
477
- return errAsync(this.error);
478
- }
479
- asyncAndThrough(_f) {
480
- return errAsync(this.error);
481
- }
482
- asyncMap(_f) {
483
- return errAsync(this.error);
484
- }
485
- unwrapOr(v) {
486
- return v;
487
- }
488
- match(_ok, err) {
489
- return err(this.error);
490
- }
491
- safeUnwrap() {
492
- const error = this.error;
493
- return (function* () {
494
- yield err(error);
495
- throw new Error("Do not use this generator out of `safeTry`");
496
- })();
497
- }
498
- _unsafeUnwrap(config) {
499
- throw createNeverThrowError("Called `_unsafeUnwrap` on an Err", this, config);
500
- }
501
- _unsafeUnwrapErr(_) {
502
- return this.error;
503
- }
504
- *[Symbol.iterator]() {
505
- const self = this;
506
- yield self;
507
- return self;
508
- }
509
- };
510
- const fromThrowable = exports.Result.fromThrowable;
511
- exports.Err = Err;
512
- exports.Ok = Ok;
513
- exports.ResultAsync = ResultAsync;
514
- exports.err = err;
515
- exports.errAsync = errAsync;
516
- exports.fromAsyncThrowable = fromAsyncThrowable;
517
- exports.fromPromise = fromPromise;
518
- exports.fromSafePromise = fromSafePromise;
519
- exports.fromThrowable = fromThrowable;
520
- exports.ok = ok;
521
- exports.okAsync = okAsync;
522
- exports.safeTry = safeTry;
523
- }));
524
- if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 "));
525
- const ERR_INVALID_ARG_VALUE = "ERR_INVALID_ARG_VALUE";
526
- const ERR_INVALID_ARG_TYPE = "ERR_INVALID_ARG_TYPE";
527
- function CodedTypeError(message, code, cause) {
528
- const err = new TypeError(message, { cause });
529
- Object.assign(err, { code });
530
- return err;
531
- }
532
- const encoder$1 = new TextEncoder();
533
- const decoder$1 = new TextDecoder();
534
- function buf(input) {
535
- if (typeof input === "string") return encoder$1.encode(input);
536
- return decoder$1.decode(input);
537
- }
538
- let encodeBase64Url;
539
- if (Uint8Array.prototype.toBase64) encodeBase64Url = (input) => {
540
- if (input instanceof ArrayBuffer) input = new Uint8Array(input);
541
- return input.toBase64({
542
- alphabet: "base64url",
543
- omitPadding: true
544
- });
545
- };
546
- else {
547
- const CHUNK_SIZE = 32768;
548
- encodeBase64Url = (input) => {
549
- if (input instanceof ArrayBuffer) input = new Uint8Array(input);
550
- const arr = [];
551
- for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
552
- return btoa(arr.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
187
+ delete params.message;
188
+ if (typeof params.error === "string") return {
189
+ ...params,
190
+ error: () => params.error
553
191
  };
192
+ return params;
554
193
  }
555
- let decodeBase64Url;
556
- if (Uint8Array.fromBase64) decodeBase64Url = (input) => {
557
- try {
558
- return Uint8Array.fromBase64(input, { alphabet: "base64url" });
559
- } catch (cause) {
560
- throw CodedTypeError("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE, cause);
561
- }
562
- };
563
- else decodeBase64Url = (input) => {
564
- try {
565
- const binary = atob(input.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""));
566
- const bytes = new Uint8Array(binary.length);
567
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
568
- return bytes;
569
- } catch (cause) {
570
- throw CodedTypeError("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE, cause);
571
- }
572
- };
573
- function b64u(input) {
574
- if (typeof input === "string") return decodeBase64Url(input);
575
- return encodeBase64Url(input);
576
- }
577
- var OperationProcessingError = class extends Error {
578
- code;
579
- constructor(message, options) {
580
- super(message, options);
581
- this.name = this.constructor.name;
582
- if (options?.code) this.code = options?.code;
583
- Error.captureStackTrace?.(this, this.constructor);
584
- }
585
- };
586
- function OPE(message, code, cause) {
587
- return new OperationProcessingError(message, {
588
- code,
589
- cause
194
+ function optionalKeys(shape) {
195
+ return Object.keys(shape).filter((k) => {
196
+ return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
590
197
  });
591
198
  }
592
- function assertString(input, it, code, cause) {
593
- try {
594
- if (typeof input !== "string") throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE, cause);
595
- if (input.length === 0) throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE, cause);
596
- } catch (err) {
597
- if (code) throw OPE(err.message, code, cause);
598
- throw err;
599
- }
600
- }
601
- function randomBytes() {
602
- return b64u(crypto.getRandomValues(new Uint8Array(32)));
199
+ const NUMBER_FORMAT_RANGES = {
200
+ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
201
+ int32: [-2147483648, 2147483647],
202
+ uint32: [0, 4294967295],
203
+ float32: [-34028234663852886e22, 34028234663852886e22],
204
+ float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
205
+ };
206
+ function pick(schema, mask) {
207
+ const currDef = schema._zod.def;
208
+ const checks = currDef.checks;
209
+ if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements");
210
+ return clone(schema, mergeDefs(schema._zod.def, {
211
+ get shape() {
212
+ const newShape = {};
213
+ for (const key in mask) {
214
+ if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
215
+ if (!mask[key]) continue;
216
+ newShape[key] = currDef.shape[key];
217
+ }
218
+ assignProp(this, "shape", newShape);
219
+ return newShape;
220
+ },
221
+ checks: []
222
+ }));
603
223
  }
604
- function generateRandomCodeVerifier() {
605
- return randomBytes();
224
+ function omit(schema, mask) {
225
+ const currDef = schema._zod.def;
226
+ const checks = currDef.checks;
227
+ if (checks && checks.length > 0) throw new Error(".omit() cannot be used on object schemas containing refinements");
228
+ return clone(schema, mergeDefs(schema._zod.def, {
229
+ get shape() {
230
+ const newShape = { ...schema._zod.def.shape };
231
+ for (const key in mask) {
232
+ if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
233
+ if (!mask[key]) continue;
234
+ delete newShape[key];
235
+ }
236
+ assignProp(this, "shape", newShape);
237
+ return newShape;
238
+ },
239
+ checks: []
240
+ }));
606
241
  }
607
- function generateRandomState() {
608
- return randomBytes();
242
+ function extend(schema, shape) {
243
+ if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object");
244
+ const checks = schema._zod.def.checks;
245
+ if (checks && checks.length > 0) {
246
+ const existingShape = schema._zod.def.shape;
247
+ for (const key in shape) if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
248
+ }
249
+ return clone(schema, mergeDefs(schema._zod.def, { get shape() {
250
+ const _shape = {
251
+ ...schema._zod.def.shape,
252
+ ...shape
253
+ };
254
+ assignProp(this, "shape", _shape);
255
+ return _shape;
256
+ } }));
609
257
  }
610
- async function calculatePKCECodeChallenge(codeVerifier) {
611
- assertString(codeVerifier, "codeVerifier");
612
- return b64u(await crypto.subtle.digest("SHA-256", buf(codeVerifier)));
258
+ function safeExtend(schema, shape) {
259
+ if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
260
+ return clone(schema, mergeDefs(schema._zod.def, { get shape() {
261
+ const _shape = {
262
+ ...schema._zod.def.shape,
263
+ ...shape
264
+ };
265
+ assignProp(this, "shape", _shape);
266
+ return _shape;
267
+ } }));
613
268
  }
614
- URL.parse;
615
- const tokenMatch = "[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+";
616
- const token68Match = "[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}";
617
- const quotedParamMatcher = "(" + tokenMatch + ")\\s*=\\s*\"((?:[^\"\\\\]|\\\\[\\s\\S])*)\"";
618
- const paramMatcher = "(" + tokenMatch + ")\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)";
619
- new RegExp("^[,\\s]*(" + tokenMatch + ")");
620
- new RegExp("^[,\\s]*" + quotedParamMatcher + "[,\\s]*(.*)");
621
- new RegExp("^[,\\s]*" + paramMatcher + "[,\\s]*(.*)");
622
- new RegExp("^(" + token68Match + ")(?:$|[,\\s])(.*)");
623
- //#endregion
624
- //#region src/core/json.ts
625
- var import_index_cjs = require_index_cjs();
626
- const ERROR_RAW_TEXT_MAX_LENGTH = 500;
627
- /**
628
- * Safely parses a JSON string, returning a `Result` instead of throwing.
629
- *
630
- * @param text - The raw text to parse as JSON.
631
- * @returns `ok(parsed)` on success, or `err({ code, rawText, message })` on failure.
632
- */
633
- function safeJsonParse(text) {
634
- try {
635
- return (0, import_index_cjs.ok)(JSON.parse(text));
636
- } catch (e) {
637
- return (0, import_index_cjs.err)({
638
- code: "JSON_PARSE_ERROR",
639
- rawText: text.length > ERROR_RAW_TEXT_MAX_LENGTH ? text.slice(0, ERROR_RAW_TEXT_MAX_LENGTH) + "..." : text,
640
- message: e instanceof Error ? e.message : "Failed to parse JSON"
641
- });
642
- }
269
+ function merge(a, b) {
270
+ return clone(a, mergeDefs(a._zod.def, {
271
+ get shape() {
272
+ const _shape = {
273
+ ...a._zod.def.shape,
274
+ ...b._zod.def.shape
275
+ };
276
+ assignProp(this, "shape", _shape);
277
+ return _shape;
278
+ },
279
+ get catchall() {
280
+ return b._zod.def.catchall;
281
+ },
282
+ checks: []
283
+ }));
643
284
  }
644
- Object.freeze({ status: "aborted" });
645
- function $constructor(name, initializer, params) {
646
- function init(inst, def) {
647
- if (!inst._zod) Object.defineProperty(inst, "_zod", {
648
- value: {
649
- def,
650
- constr: _,
651
- traits: /* @__PURE__ */ new Set()
652
- },
653
- enumerable: false
654
- });
655
- if (inst._zod.traits.has(name)) return;
656
- inst._zod.traits.add(name);
657
- initializer(inst, def);
658
- const proto = _.prototype;
659
- const keys = Object.keys(proto);
660
- for (let i = 0; i < keys.length; i++) {
661
- const k = keys[i];
662
- if (!(k in inst)) inst[k] = proto[k].bind(inst);
663
- }
664
- }
665
- const Parent = params?.Parent ?? Object;
666
- class Definition extends Parent {}
667
- Object.defineProperty(Definition, "name", { value: name });
668
- function _(def) {
669
- var _a;
670
- const inst = params?.Parent ? new Definition() : this;
671
- init(inst, def);
672
- (_a = inst._zod).deferred ?? (_a.deferred = []);
673
- for (const fn of inst._zod.deferred) fn();
674
- return inst;
675
- }
676
- Object.defineProperty(_, "init", { value: init });
677
- Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => {
678
- if (params?.Parent && inst instanceof params.Parent) return true;
679
- return inst?._zod?.traits?.has(name);
680
- } });
681
- Object.defineProperty(_, "name", { value: name });
682
- return _;
285
+ function partial(Class, schema, mask) {
286
+ const checks = schema._zod.def.checks;
287
+ if (checks && checks.length > 0) throw new Error(".partial() cannot be used on object schemas containing refinements");
288
+ return clone(schema, mergeDefs(schema._zod.def, {
289
+ get shape() {
290
+ const oldShape = schema._zod.def.shape;
291
+ const shape = { ...oldShape };
292
+ if (mask) for (const key in mask) {
293
+ if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`);
294
+ if (!mask[key]) continue;
295
+ shape[key] = Class ? new Class({
296
+ type: "optional",
297
+ innerType: oldShape[key]
298
+ }) : oldShape[key];
299
+ }
300
+ else for (const key in oldShape) shape[key] = Class ? new Class({
301
+ type: "optional",
302
+ innerType: oldShape[key]
303
+ }) : oldShape[key];
304
+ assignProp(this, "shape", shape);
305
+ return shape;
306
+ },
307
+ checks: []
308
+ }));
683
309
  }
684
- var $ZodAsyncError = class extends Error {
685
- constructor() {
686
- super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
687
- }
688
- };
689
- var $ZodEncodeError = class extends Error {
690
- constructor(name) {
691
- super(`Encountered unidirectional transform during encode: ${name}`);
692
- this.name = "ZodEncodeError";
693
- }
694
- };
695
- const globalConfig = {};
696
- function config(newConfig) {
697
- if (newConfig) Object.assign(globalConfig, newConfig);
698
- return globalConfig;
310
+ function required(Class, schema, mask) {
311
+ return clone(schema, mergeDefs(schema._zod.def, { get shape() {
312
+ const oldShape = schema._zod.def.shape;
313
+ const shape = { ...oldShape };
314
+ if (mask) for (const key in mask) {
315
+ if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`);
316
+ if (!mask[key]) continue;
317
+ shape[key] = new Class({
318
+ type: "nonoptional",
319
+ innerType: oldShape[key]
320
+ });
321
+ }
322
+ else for (const key in oldShape) shape[key] = new Class({
323
+ type: "nonoptional",
324
+ innerType: oldShape[key]
325
+ });
326
+ assignProp(this, "shape", shape);
327
+ return shape;
328
+ } }));
699
329
  }
700
- //#endregion
701
- //#region node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js
702
- function getEnumValues(entries) {
703
- const numericValues = Object.values(entries).filter((v) => typeof v === "number");
704
- return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
330
+ function aborted(x, startIndex = 0) {
331
+ if (x.aborted === true) return true;
332
+ for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;
333
+ return false;
705
334
  }
706
- function jsonStringifyReplacer(_, value) {
707
- if (typeof value === "bigint") return value.toString();
708
- return value;
335
+ function prefixIssues(path, issues) {
336
+ return issues.map((iss) => {
337
+ var _a;
338
+ (_a = iss).path ?? (_a.path = []);
339
+ iss.path.unshift(path);
340
+ return iss;
341
+ });
709
342
  }
710
- function cached(getter) {
711
- return { get value() {
712
- {
713
- const value = getter();
714
- Object.defineProperty(this, "value", { value });
715
- return value;
716
- }
717
- throw new Error("cached value already set");
718
- } };
343
+ function unwrapMessage(message) {
344
+ return typeof message === "string" ? message : message?.message;
719
345
  }
720
- function nullish(input) {
721
- return input === null || input === void 0;
346
+ function finalizeIssue(iss, ctx, config) {
347
+ const full = {
348
+ ...iss,
349
+ path: iss.path ?? []
350
+ };
351
+ if (!iss.message) full.message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
352
+ delete full.inst;
353
+ delete full.continue;
354
+ if (!ctx?.reportInput) delete full.input;
355
+ return full;
722
356
  }
723
- function cleanRegex(source) {
724
- const start = source.startsWith("^") ? 1 : 0;
725
- const end = source.endsWith("$") ? source.length - 1 : source.length;
726
- return source.slice(start, end);
357
+ function getLengthableOrigin(input) {
358
+ if (Array.isArray(input)) return "array";
359
+ if (typeof input === "string") return "string";
360
+ return "unknown";
727
361
  }
728
- function floatSafeRemainder(val, step) {
729
- const valDecCount = (val.toString().split(".")[1] || "").length;
730
- const stepString = step.toString();
731
- let stepDecCount = (stepString.split(".")[1] || "").length;
732
- if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
733
- const match = stepString.match(/\d?e-(\d?)/);
734
- if (match?.[1]) stepDecCount = Number.parseInt(match[1]);
735
- }
736
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
737
- return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount;
362
+ function issue(...args) {
363
+ const [iss, input, inst] = args;
364
+ if (typeof iss === "string") return {
365
+ message: iss,
366
+ code: "custom",
367
+ input,
368
+ inst
369
+ };
370
+ return { ...iss };
738
371
  }
739
- const EVALUATING = Symbol("evaluating");
740
- function defineLazy(object, key, getter) {
741
- let value = void 0;
742
- Object.defineProperty(object, key, {
743
- get() {
744
- if (value === EVALUATING) return;
745
- if (value === void 0) {
746
- value = EVALUATING;
747
- value = getter();
748
- }
749
- return value;
750
- },
751
- set(v) {
752
- Object.defineProperty(object, key, { value: v });
753
- },
754
- configurable: true
372
+ //#endregion
373
+ //#region node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js
374
+ const initializer$1 = (inst, def) => {
375
+ inst.name = "$ZodError";
376
+ Object.defineProperty(inst, "_zod", {
377
+ value: inst._zod,
378
+ enumerable: false
755
379
  });
756
- }
757
- function assignProp(target, prop, value) {
758
- Object.defineProperty(target, prop, {
759
- value,
760
- writable: true,
761
- enumerable: true,
762
- configurable: true
380
+ Object.defineProperty(inst, "issues", {
381
+ value: def,
382
+ enumerable: false
383
+ });
384
+ inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
385
+ Object.defineProperty(inst, "toString", {
386
+ value: () => inst.message,
387
+ enumerable: false
763
388
  });
389
+ };
390
+ const $ZodError = $constructor("$ZodError", initializer$1);
391
+ const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
392
+ function flattenError(error, mapper = (issue) => issue.message) {
393
+ const fieldErrors = {};
394
+ const formErrors = [];
395
+ for (const sub of error.issues) if (sub.path.length > 0) {
396
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
397
+ fieldErrors[sub.path[0]].push(mapper(sub));
398
+ } else formErrors.push(mapper(sub));
399
+ return {
400
+ formErrors,
401
+ fieldErrors
402
+ };
764
403
  }
765
- function mergeDefs(...defs) {
766
- const mergedDescriptors = {};
767
- for (const def of defs) {
768
- const descriptors = Object.getOwnPropertyDescriptors(def);
769
- Object.assign(mergedDescriptors, descriptors);
404
+ function formatError(error, mapper = (issue) => issue.message) {
405
+ const fieldErrors = { _errors: [] };
406
+ const processError = (error) => {
407
+ for (const issue of error.issues) if (issue.code === "invalid_union" && issue.errors.length) issue.errors.map((issues) => processError({ issues }));
408
+ else if (issue.code === "invalid_key") processError({ issues: issue.issues });
409
+ else if (issue.code === "invalid_element") processError({ issues: issue.issues });
410
+ else if (issue.path.length === 0) fieldErrors._errors.push(mapper(issue));
411
+ else {
412
+ let curr = fieldErrors;
413
+ let i = 0;
414
+ while (i < issue.path.length) {
415
+ const el = issue.path[i];
416
+ if (!(i === issue.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
417
+ else {
418
+ curr[el] = curr[el] || { _errors: [] };
419
+ curr[el]._errors.push(mapper(issue));
420
+ }
421
+ curr = curr[el];
422
+ i++;
423
+ }
424
+ }
425
+ };
426
+ processError(error);
427
+ return fieldErrors;
428
+ }
429
+ /** Format a ZodError as a human-readable string in the following form.
430
+ *
431
+ * From
432
+ *
433
+ * ```ts
434
+ * ZodError {
435
+ * issues: [
436
+ * {
437
+ * expected: 'string',
438
+ * code: 'invalid_type',
439
+ * path: [ 'username' ],
440
+ * message: 'Invalid input: expected string'
441
+ * },
442
+ * {
443
+ * expected: 'number',
444
+ * code: 'invalid_type',
445
+ * path: [ 'favoriteNumbers', 1 ],
446
+ * message: 'Invalid input: expected number'
447
+ * }
448
+ * ];
449
+ * }
450
+ * ```
451
+ *
452
+ * to
453
+ *
454
+ * ```
455
+ * username
456
+ * ✖ Expected number, received string at "username
457
+ * favoriteNumbers[0]
458
+ * ✖ Invalid input: expected number
459
+ * ```
460
+ */
461
+ function toDotPath(_path) {
462
+ const segs = [];
463
+ const path = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
464
+ for (const seg of path) if (typeof seg === "number") segs.push(`[${seg}]`);
465
+ else if (typeof seg === "symbol") segs.push(`[${JSON.stringify(String(seg))}]`);
466
+ else if (/[^\w$]/.test(seg)) segs.push(`[${JSON.stringify(seg)}]`);
467
+ else {
468
+ if (segs.length) segs.push(".");
469
+ segs.push(seg);
770
470
  }
771
- return Object.defineProperties({}, mergedDescriptors);
471
+ return segs.join("");
772
472
  }
773
- function esc(str) {
774
- return JSON.stringify(str);
473
+ function prettifyError(error) {
474
+ const lines = [];
475
+ const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);
476
+ for (const issue of issues) {
477
+ lines.push(`✖ ${issue.message}`);
478
+ if (issue.path?.length) lines.push(` → at ${toDotPath(issue.path)}`);
479
+ }
480
+ return lines.join("\n");
775
481
  }
776
- function slugify(input) {
777
- return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
778
- }
779
- const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
780
- function isObject$1(data) {
781
- return typeof data === "object" && data !== null && !Array.isArray(data);
782
- }
783
- const allowsEval = cached(() => {
784
- if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false;
785
- try {
786
- new Function("");
787
- return true;
788
- } catch (_) {
789
- return false;
482
+ //#endregion
483
+ //#region node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js
484
+ const _parse = (_Err) => (schema, value, _ctx, _params) => {
485
+ const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
486
+ const result = schema._zod.run({
487
+ value,
488
+ issues: []
489
+ }, ctx);
490
+ if (result instanceof Promise) throw new $ZodAsyncError();
491
+ if (result.issues.length) {
492
+ const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
493
+ captureStackTrace(e, _params?.callee);
494
+ throw e;
790
495
  }
791
- });
792
- function isPlainObject(o) {
793
- if (isObject$1(o) === false) return false;
794
- const ctor = o.constructor;
795
- if (ctor === void 0) return true;
796
- if (typeof ctor !== "function") return true;
797
- const prot = ctor.prototype;
798
- if (isObject$1(prot) === false) return false;
799
- if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
800
- return true;
801
- }
802
- function shallowClone(o) {
803
- if (isPlainObject(o)) return { ...o };
804
- if (Array.isArray(o)) return [...o];
805
- return o;
806
- }
807
- const propertyKeyTypes = new Set([
808
- "string",
809
- "number",
810
- "symbol"
811
- ]);
812
- function escapeRegex(str) {
813
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
814
- }
815
- function clone(inst, def, params) {
816
- const cl = new inst._zod.constr(def ?? inst._zod.def);
817
- if (!def || params?.parent) cl._zod.parent = inst;
818
- return cl;
819
- }
820
- function normalizeParams(_params) {
821
- const params = _params;
822
- if (!params) return {};
823
- if (typeof params === "string") return { error: () => params };
824
- if (params?.message !== void 0) {
825
- if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params");
826
- params.error = params.message;
496
+ return result.value;
497
+ };
498
+ const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
499
+ const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
500
+ let result = schema._zod.run({
501
+ value,
502
+ issues: []
503
+ }, ctx);
504
+ if (result instanceof Promise) result = await result;
505
+ if (result.issues.length) {
506
+ const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
507
+ captureStackTrace(e, params?.callee);
508
+ throw e;
827
509
  }
828
- delete params.message;
829
- if (typeof params.error === "string") return {
830
- ...params,
831
- error: () => params.error
510
+ return result.value;
511
+ };
512
+ const _safeParse = (_Err) => (schema, value, _ctx) => {
513
+ const ctx = _ctx ? {
514
+ ..._ctx,
515
+ async: false
516
+ } : { async: false };
517
+ const result = schema._zod.run({
518
+ value,
519
+ issues: []
520
+ }, ctx);
521
+ if (result instanceof Promise) throw new $ZodAsyncError();
522
+ return result.issues.length ? {
523
+ success: false,
524
+ error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
525
+ } : {
526
+ success: true,
527
+ data: result.value
832
528
  };
833
- return params;
834
- }
835
- function optionalKeys(shape) {
836
- return Object.keys(shape).filter((k) => {
837
- return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
838
- });
839
- }
840
- const NUMBER_FORMAT_RANGES = {
841
- safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
842
- int32: [-2147483648, 2147483647],
843
- uint32: [0, 4294967295],
844
- float32: [-34028234663852886e22, 34028234663852886e22],
845
- float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
846
529
  };
847
- function pick(schema, mask) {
848
- const currDef = schema._zod.def;
849
- const checks = currDef.checks;
850
- if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements");
851
- return clone(schema, mergeDefs(schema._zod.def, {
852
- get shape() {
853
- const newShape = {};
854
- for (const key in mask) {
855
- if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
856
- if (!mask[key]) continue;
857
- newShape[key] = currDef.shape[key];
858
- }
859
- assignProp(this, "shape", newShape);
860
- return newShape;
861
- },
862
- checks: []
863
- }));
530
+ const safeParse$1 = /* @__PURE__ */ _safeParse($ZodRealError);
531
+ const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
532
+ const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
533
+ let result = schema._zod.run({
534
+ value,
535
+ issues: []
536
+ }, ctx);
537
+ if (result instanceof Promise) result = await result;
538
+ return result.issues.length ? {
539
+ success: false,
540
+ error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
541
+ } : {
542
+ success: true,
543
+ data: result.value
544
+ };
545
+ };
546
+ const safeParseAsync$1 = /* @__PURE__ */ _safeParseAsync($ZodRealError);
547
+ const _encode = (_Err) => (schema, value, _ctx) => {
548
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
549
+ return _parse(_Err)(schema, value, ctx);
550
+ };
551
+ const _decode = (_Err) => (schema, value, _ctx) => {
552
+ return _parse(_Err)(schema, value, _ctx);
553
+ };
554
+ const _encodeAsync = (_Err) => async (schema, value, _ctx) => {
555
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
556
+ return _parseAsync(_Err)(schema, value, ctx);
557
+ };
558
+ const _decodeAsync = (_Err) => async (schema, value, _ctx) => {
559
+ return _parseAsync(_Err)(schema, value, _ctx);
560
+ };
561
+ const _safeEncode = (_Err) => (schema, value, _ctx) => {
562
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
563
+ return _safeParse(_Err)(schema, value, ctx);
564
+ };
565
+ const _safeDecode = (_Err) => (schema, value, _ctx) => {
566
+ return _safeParse(_Err)(schema, value, _ctx);
567
+ };
568
+ const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
569
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
570
+ return _safeParseAsync(_Err)(schema, value, ctx);
571
+ };
572
+ const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
573
+ return _safeParseAsync(_Err)(schema, value, _ctx);
574
+ };
575
+ //#endregion
576
+ //#region node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js
577
+ const cuid = /^[cC][^\s-]{8,}$/;
578
+ const cuid2 = /^[0-9a-z]+$/;
579
+ const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
580
+ const xid = /^[0-9a-vA-V]{20}$/;
581
+ const ksuid = /^[A-Za-z0-9]{27}$/;
582
+ const nanoid = /^[a-zA-Z0-9_-]{21}$/;
583
+ /** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
584
+ const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
585
+ /** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
586
+ const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
587
+ /** Returns a regex for validating an RFC 9562/4122 UUID.
588
+ *
589
+ * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
590
+ const uuid = (version) => {
591
+ if (!version) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
592
+ return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
593
+ };
594
+ /** Practical email validation */
595
+ const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
596
+ const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
597
+ function emoji() {
598
+ return new RegExp(_emoji$1, "u");
864
599
  }
865
- function omit(schema, mask) {
866
- const currDef = schema._zod.def;
867
- const checks = currDef.checks;
868
- if (checks && checks.length > 0) throw new Error(".omit() cannot be used on object schemas containing refinements");
869
- return clone(schema, mergeDefs(schema._zod.def, {
870
- get shape() {
871
- const newShape = { ...schema._zod.def.shape };
872
- for (const key in mask) {
873
- if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
874
- if (!mask[key]) continue;
875
- delete newShape[key];
876
- }
877
- assignProp(this, "shape", newShape);
878
- return newShape;
879
- },
880
- checks: []
881
- }));
600
+ const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
601
+ const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
602
+ const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
603
+ const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
604
+ const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
605
+ const base64url = /^[A-Za-z0-9_-]*$/;
606
+ const e164 = /^\+[1-9]\d{6,14}$/;
607
+ const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
608
+ const date$1 = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
609
+ function timeSource(args) {
610
+ const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
611
+ return typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
882
612
  }
883
- function extend(schema, shape) {
884
- if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object");
885
- const checks = schema._zod.def.checks;
886
- if (checks && checks.length > 0) {
887
- const existingShape = schema._zod.def.shape;
888
- for (const key in shape) if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
889
- }
890
- return clone(schema, mergeDefs(schema._zod.def, { get shape() {
891
- const _shape = {
892
- ...schema._zod.def.shape,
893
- ...shape
894
- };
895
- assignProp(this, "shape", _shape);
896
- return _shape;
897
- } }));
613
+ function time$1(args) {
614
+ return new RegExp(`^${timeSource(args)}$`);
898
615
  }
899
- function safeExtend(schema, shape) {
900
- if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
901
- return clone(schema, mergeDefs(schema._zod.def, { get shape() {
902
- const _shape = {
903
- ...schema._zod.def.shape,
904
- ...shape
905
- };
906
- assignProp(this, "shape", _shape);
907
- return _shape;
908
- } }));
909
- }
910
- function merge(a, b) {
911
- return clone(a, mergeDefs(a._zod.def, {
912
- get shape() {
913
- const _shape = {
914
- ...a._zod.def.shape,
915
- ...b._zod.def.shape
916
- };
917
- assignProp(this, "shape", _shape);
918
- return _shape;
919
- },
920
- get catchall() {
921
- return b._zod.def.catchall;
922
- },
923
- checks: []
924
- }));
925
- }
926
- function partial(Class, schema, mask) {
927
- const checks = schema._zod.def.checks;
928
- if (checks && checks.length > 0) throw new Error(".partial() cannot be used on object schemas containing refinements");
929
- return clone(schema, mergeDefs(schema._zod.def, {
930
- get shape() {
931
- const oldShape = schema._zod.def.shape;
932
- const shape = { ...oldShape };
933
- if (mask) for (const key in mask) {
934
- if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`);
935
- if (!mask[key]) continue;
936
- shape[key] = Class ? new Class({
937
- type: "optional",
938
- innerType: oldShape[key]
939
- }) : oldShape[key];
940
- }
941
- else for (const key in oldShape) shape[key] = Class ? new Class({
942
- type: "optional",
943
- innerType: oldShape[key]
944
- }) : oldShape[key];
945
- assignProp(this, "shape", shape);
946
- return shape;
947
- },
948
- checks: []
949
- }));
950
- }
951
- function required(Class, schema, mask) {
952
- return clone(schema, mergeDefs(schema._zod.def, { get shape() {
953
- const oldShape = schema._zod.def.shape;
954
- const shape = { ...oldShape };
955
- if (mask) for (const key in mask) {
956
- if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`);
957
- if (!mask[key]) continue;
958
- shape[key] = new Class({
959
- type: "nonoptional",
960
- innerType: oldShape[key]
961
- });
962
- }
963
- else for (const key in oldShape) shape[key] = new Class({
964
- type: "nonoptional",
965
- innerType: oldShape[key]
966
- });
967
- assignProp(this, "shape", shape);
968
- return shape;
969
- } }));
970
- }
971
- function aborted(x, startIndex = 0) {
972
- if (x.aborted === true) return true;
973
- for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;
974
- return false;
975
- }
976
- function prefixIssues(path, issues) {
977
- return issues.map((iss) => {
978
- var _a;
979
- (_a = iss).path ?? (_a.path = []);
980
- iss.path.unshift(path);
981
- return iss;
982
- });
983
- }
984
- function unwrapMessage(message) {
985
- return typeof message === "string" ? message : message?.message;
986
- }
987
- function finalizeIssue(iss, ctx, config) {
988
- const full = {
989
- ...iss,
990
- path: iss.path ?? []
991
- };
992
- if (!iss.message) full.message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
993
- delete full.inst;
994
- delete full.continue;
995
- if (!ctx?.reportInput) delete full.input;
996
- return full;
997
- }
998
- function getLengthableOrigin(input) {
999
- if (Array.isArray(input)) return "array";
1000
- if (typeof input === "string") return "string";
1001
- return "unknown";
1002
- }
1003
- function issue(...args) {
1004
- const [iss, input, inst] = args;
1005
- if (typeof iss === "string") return {
1006
- message: iss,
1007
- code: "custom",
1008
- input,
1009
- inst
1010
- };
1011
- return { ...iss };
616
+ function datetime$1(args) {
617
+ const time = timeSource({ precision: args.precision });
618
+ const opts = ["Z"];
619
+ if (args.local) opts.push("");
620
+ if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
621
+ const timeRegex = `${time}(?:${opts.join("|")})`;
622
+ return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
1012
623
  }
624
+ const string$1 = (params) => {
625
+ const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
626
+ return new RegExp(`^${regex}$`);
627
+ };
628
+ const integer = /^-?\d+$/;
629
+ const number$1 = /^-?\d+(?:\.\d+)?$/;
630
+ const boolean$1 = /^(?:true|false)$/i;
631
+ const lowercase = /^[^A-Z]*$/;
632
+ const uppercase = /^[^a-z]*$/;
1013
633
  //#endregion
1014
- //#region node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js
1015
- const initializer$1 = (inst, def) => {
1016
- inst.name = "$ZodError";
1017
- Object.defineProperty(inst, "_zod", {
1018
- value: inst._zod,
1019
- enumerable: false
634
+ //#region node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js
635
+ const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
636
+ var _a;
637
+ inst._zod ?? (inst._zod = {});
638
+ inst._zod.def = def;
639
+ (_a = inst._zod).onattach ?? (_a.onattach = []);
640
+ });
641
+ const numericOriginMap = {
642
+ number: "number",
643
+ bigint: "bigint",
644
+ object: "date"
645
+ };
646
+ const $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
647
+ $ZodCheck.init(inst, def);
648
+ const origin = numericOriginMap[typeof def.value];
649
+ inst._zod.onattach.push((inst) => {
650
+ const bag = inst._zod.bag;
651
+ const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
652
+ if (def.value < curr) if (def.inclusive) bag.maximum = def.value;
653
+ else bag.exclusiveMaximum = def.value;
1020
654
  });
1021
- Object.defineProperty(inst, "issues", {
1022
- value: def,
1023
- enumerable: false
655
+ inst._zod.check = (payload) => {
656
+ if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return;
657
+ payload.issues.push({
658
+ origin,
659
+ code: "too_big",
660
+ maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
661
+ input: payload.value,
662
+ inclusive: def.inclusive,
663
+ inst,
664
+ continue: !def.abort
665
+ });
666
+ };
667
+ });
668
+ const $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
669
+ $ZodCheck.init(inst, def);
670
+ const origin = numericOriginMap[typeof def.value];
671
+ inst._zod.onattach.push((inst) => {
672
+ const bag = inst._zod.bag;
673
+ const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
674
+ if (def.value > curr) if (def.inclusive) bag.minimum = def.value;
675
+ else bag.exclusiveMinimum = def.value;
1024
676
  });
1025
- inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
1026
- Object.defineProperty(inst, "toString", {
1027
- value: () => inst.message,
1028
- enumerable: false
677
+ inst._zod.check = (payload) => {
678
+ if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return;
679
+ payload.issues.push({
680
+ origin,
681
+ code: "too_small",
682
+ minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
683
+ input: payload.value,
684
+ inclusive: def.inclusive,
685
+ inst,
686
+ continue: !def.abort
687
+ });
688
+ };
689
+ });
690
+ const $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
691
+ $ZodCheck.init(inst, def);
692
+ inst._zod.onattach.push((inst) => {
693
+ var _a;
694
+ (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
1029
695
  });
1030
- };
1031
- const $ZodError = $constructor("$ZodError", initializer$1);
1032
- const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
1033
- function flattenError(error, mapper = (issue) => issue.message) {
1034
- const fieldErrors = {};
1035
- const formErrors = [];
1036
- for (const sub of error.issues) if (sub.path.length > 0) {
1037
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
1038
- fieldErrors[sub.path[0]].push(mapper(sub));
1039
- } else formErrors.push(mapper(sub));
1040
- return {
1041
- formErrors,
1042
- fieldErrors
696
+ inst._zod.check = (payload) => {
697
+ if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check.");
698
+ if (typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0) return;
699
+ payload.issues.push({
700
+ origin: typeof payload.value,
701
+ code: "not_multiple_of",
702
+ divisor: def.value,
703
+ input: payload.value,
704
+ inst,
705
+ continue: !def.abort
706
+ });
1043
707
  };
1044
- }
1045
- function formatError(error, mapper = (issue) => issue.message) {
1046
- const fieldErrors = { _errors: [] };
1047
- const processError = (error) => {
1048
- for (const issue of error.issues) if (issue.code === "invalid_union" && issue.errors.length) issue.errors.map((issues) => processError({ issues }));
1049
- else if (issue.code === "invalid_key") processError({ issues: issue.issues });
1050
- else if (issue.code === "invalid_element") processError({ issues: issue.issues });
1051
- else if (issue.path.length === 0) fieldErrors._errors.push(mapper(issue));
1052
- else {
1053
- let curr = fieldErrors;
1054
- let i = 0;
1055
- while (i < issue.path.length) {
1056
- const el = issue.path[i];
1057
- if (!(i === issue.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
1058
- else {
1059
- curr[el] = curr[el] || { _errors: [] };
1060
- curr[el]._errors.push(mapper(issue));
1061
- }
1062
- curr = curr[el];
1063
- i++;
708
+ });
709
+ const $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
710
+ $ZodCheck.init(inst, def);
711
+ def.format = def.format || "float64";
712
+ const isInt = def.format?.includes("int");
713
+ const origin = isInt ? "int" : "number";
714
+ const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
715
+ inst._zod.onattach.push((inst) => {
716
+ const bag = inst._zod.bag;
717
+ bag.format = def.format;
718
+ bag.minimum = minimum;
719
+ bag.maximum = maximum;
720
+ if (isInt) bag.pattern = integer;
721
+ });
722
+ inst._zod.check = (payload) => {
723
+ const input = payload.value;
724
+ if (isInt) {
725
+ if (!Number.isInteger(input)) {
726
+ payload.issues.push({
727
+ expected: origin,
728
+ format: def.format,
729
+ code: "invalid_type",
730
+ continue: false,
731
+ input,
732
+ inst
733
+ });
734
+ return;
1064
735
  }
1065
- }
1066
- };
1067
- processError(error);
1068
- return fieldErrors;
1069
- }
1070
- //#endregion
1071
- //#region node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js
1072
- const _parse = (_Err) => (schema, value, _ctx, _params) => {
1073
- const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
1074
- const result = schema._zod.run({
1075
- value,
1076
- issues: []
1077
- }, ctx);
1078
- if (result instanceof Promise) throw new $ZodAsyncError();
1079
- if (result.issues.length) {
1080
- const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
1081
- captureStackTrace(e, _params?.callee);
1082
- throw e;
1083
- }
1084
- return result.value;
1085
- };
1086
- const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
1087
- const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
1088
- let result = schema._zod.run({
1089
- value,
1090
- issues: []
1091
- }, ctx);
1092
- if (result instanceof Promise) result = await result;
1093
- if (result.issues.length) {
1094
- const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
1095
- captureStackTrace(e, params?.callee);
1096
- throw e;
1097
- }
1098
- return result.value;
1099
- };
1100
- const _safeParse = (_Err) => (schema, value, _ctx) => {
1101
- const ctx = _ctx ? {
1102
- ..._ctx,
1103
- async: false
1104
- } : { async: false };
1105
- const result = schema._zod.run({
1106
- value,
1107
- issues: []
1108
- }, ctx);
1109
- if (result instanceof Promise) throw new $ZodAsyncError();
1110
- return result.issues.length ? {
1111
- success: false,
1112
- error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
1113
- } : {
1114
- success: true,
1115
- data: result.value
1116
- };
1117
- };
1118
- const safeParse$1 = /* @__PURE__ */ _safeParse($ZodRealError);
1119
- const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
1120
- const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
1121
- let result = schema._zod.run({
1122
- value,
1123
- issues: []
1124
- }, ctx);
1125
- if (result instanceof Promise) result = await result;
1126
- return result.issues.length ? {
1127
- success: false,
1128
- error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
1129
- } : {
1130
- success: true,
1131
- data: result.value
736
+ if (!Number.isSafeInteger(input)) {
737
+ if (input > 0) payload.issues.push({
738
+ input,
739
+ code: "too_big",
740
+ maximum: Number.MAX_SAFE_INTEGER,
741
+ note: "Integers must be within the safe integer range.",
742
+ inst,
743
+ origin,
744
+ inclusive: true,
745
+ continue: !def.abort
746
+ });
747
+ else payload.issues.push({
748
+ input,
749
+ code: "too_small",
750
+ minimum: Number.MIN_SAFE_INTEGER,
751
+ note: "Integers must be within the safe integer range.",
752
+ inst,
753
+ origin,
754
+ inclusive: true,
755
+ continue: !def.abort
756
+ });
757
+ return;
758
+ }
759
+ }
760
+ if (input < minimum) payload.issues.push({
761
+ origin: "number",
762
+ input,
763
+ code: "too_small",
764
+ minimum,
765
+ inclusive: true,
766
+ inst,
767
+ continue: !def.abort
768
+ });
769
+ if (input > maximum) payload.issues.push({
770
+ origin: "number",
771
+ input,
772
+ code: "too_big",
773
+ maximum,
774
+ inclusive: true,
775
+ inst,
776
+ continue: !def.abort
777
+ });
1132
778
  };
1133
- };
1134
- const safeParseAsync$1 = /* @__PURE__ */ _safeParseAsync($ZodRealError);
1135
- const _encode = (_Err) => (schema, value, _ctx) => {
1136
- const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
1137
- return _parse(_Err)(schema, value, ctx);
1138
- };
1139
- const _decode = (_Err) => (schema, value, _ctx) => {
1140
- return _parse(_Err)(schema, value, _ctx);
1141
- };
1142
- const _encodeAsync = (_Err) => async (schema, value, _ctx) => {
1143
- const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
1144
- return _parseAsync(_Err)(schema, value, ctx);
1145
- };
1146
- const _decodeAsync = (_Err) => async (schema, value, _ctx) => {
1147
- return _parseAsync(_Err)(schema, value, _ctx);
1148
- };
1149
- const _safeEncode = (_Err) => (schema, value, _ctx) => {
1150
- const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
1151
- return _safeParse(_Err)(schema, value, ctx);
1152
- };
1153
- const _safeDecode = (_Err) => (schema, value, _ctx) => {
1154
- return _safeParse(_Err)(schema, value, _ctx);
1155
- };
1156
- const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
1157
- const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
1158
- return _safeParseAsync(_Err)(schema, value, ctx);
1159
- };
1160
- const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
1161
- return _safeParseAsync(_Err)(schema, value, _ctx);
1162
- };
1163
- //#endregion
1164
- //#region node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js
1165
- const cuid = /^[cC][^\s-]{8,}$/;
1166
- const cuid2 = /^[0-9a-z]+$/;
1167
- const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
1168
- const xid = /^[0-9a-vA-V]{20}$/;
1169
- const ksuid = /^[A-Za-z0-9]{27}$/;
1170
- const nanoid = /^[a-zA-Z0-9_-]{21}$/;
1171
- /** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
1172
- const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
1173
- /** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
1174
- const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
1175
- /** Returns a regex for validating an RFC 9562/4122 UUID.
1176
- *
1177
- * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
1178
- const uuid = (version) => {
1179
- if (!version) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
1180
- return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
1181
- };
1182
- /** Practical email validation */
1183
- const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
1184
- const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1185
- function emoji() {
1186
- return new RegExp(_emoji$1, "u");
1187
- }
1188
- const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
1189
- const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
1190
- const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
1191
- const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
1192
- const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
1193
- const base64url = /^[A-Za-z0-9_-]*$/;
1194
- const e164 = /^\+[1-9]\d{6,14}$/;
1195
- const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
1196
- const date$1 = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
1197
- function timeSource(args) {
1198
- const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
1199
- return typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
1200
- }
1201
- function time$1(args) {
1202
- return new RegExp(`^${timeSource(args)}$`);
1203
- }
1204
- function datetime$1(args) {
1205
- const time = timeSource({ precision: args.precision });
1206
- const opts = ["Z"];
1207
- if (args.local) opts.push("");
1208
- if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
1209
- const timeRegex = `${time}(?:${opts.join("|")})`;
1210
- return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
1211
- }
1212
- const string$1 = (params) => {
1213
- const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
1214
- return new RegExp(`^${regex}$`);
1215
- };
1216
- const integer = /^-?\d+$/;
1217
- const number$1 = /^-?\d+(?:\.\d+)?$/;
1218
- const boolean$1 = /^(?:true|false)$/i;
1219
- const lowercase = /^[^A-Z]*$/;
1220
- const uppercase = /^[^a-z]*$/;
1221
- //#endregion
1222
- //#region node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js
1223
- const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
1224
- var _a;
1225
- inst._zod ?? (inst._zod = {});
1226
- inst._zod.def = def;
1227
- (_a = inst._zod).onattach ?? (_a.onattach = []);
1228
779
  });
1229
- const numericOriginMap = {
1230
- number: "number",
1231
- bigint: "bigint",
1232
- object: "date"
1233
- };
1234
- const $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
780
+ const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
781
+ var _a;
1235
782
  $ZodCheck.init(inst, def);
1236
- const origin = numericOriginMap[typeof def.value];
783
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
784
+ const val = payload.value;
785
+ return !nullish(val) && val.length !== void 0;
786
+ });
1237
787
  inst._zod.onattach.push((inst) => {
1238
- const bag = inst._zod.bag;
1239
- const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
1240
- if (def.value < curr) if (def.inclusive) bag.maximum = def.value;
1241
- else bag.exclusiveMaximum = def.value;
788
+ const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
789
+ if (def.maximum < curr) inst._zod.bag.maximum = def.maximum;
1242
790
  });
1243
791
  inst._zod.check = (payload) => {
1244
- if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return;
792
+ const input = payload.value;
793
+ if (input.length <= def.maximum) return;
794
+ const origin = getLengthableOrigin(input);
1245
795
  payload.issues.push({
1246
796
  origin,
1247
797
  code: "too_big",
1248
- maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
1249
- input: payload.value,
1250
- inclusive: def.inclusive,
798
+ maximum: def.maximum,
799
+ inclusive: true,
800
+ input,
1251
801
  inst,
1252
802
  continue: !def.abort
1253
803
  });
1254
804
  };
1255
805
  });
1256
- const $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
806
+ const $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
807
+ var _a;
1257
808
  $ZodCheck.init(inst, def);
1258
- const origin = numericOriginMap[typeof def.value];
809
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
810
+ const val = payload.value;
811
+ return !nullish(val) && val.length !== void 0;
812
+ });
1259
813
  inst._zod.onattach.push((inst) => {
1260
- const bag = inst._zod.bag;
1261
- const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
1262
- if (def.value > curr) if (def.inclusive) bag.minimum = def.value;
1263
- else bag.exclusiveMinimum = def.value;
814
+ const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
815
+ if (def.minimum > curr) inst._zod.bag.minimum = def.minimum;
1264
816
  });
1265
817
  inst._zod.check = (payload) => {
1266
- if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return;
818
+ const input = payload.value;
819
+ if (input.length >= def.minimum) return;
820
+ const origin = getLengthableOrigin(input);
1267
821
  payload.issues.push({
1268
822
  origin,
1269
823
  code: "too_small",
1270
- minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
1271
- input: payload.value,
1272
- inclusive: def.inclusive,
1273
- inst,
1274
- continue: !def.abort
1275
- });
1276
- };
1277
- });
1278
- const $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
1279
- $ZodCheck.init(inst, def);
1280
- inst._zod.onattach.push((inst) => {
1281
- var _a;
1282
- (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
1283
- });
1284
- inst._zod.check = (payload) => {
1285
- if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check.");
1286
- if (typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0) return;
1287
- payload.issues.push({
1288
- origin: typeof payload.value,
1289
- code: "not_multiple_of",
1290
- divisor: def.value,
1291
- input: payload.value,
1292
- inst,
1293
- continue: !def.abort
1294
- });
1295
- };
1296
- });
1297
- const $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
1298
- $ZodCheck.init(inst, def);
1299
- def.format = def.format || "float64";
1300
- const isInt = def.format?.includes("int");
1301
- const origin = isInt ? "int" : "number";
1302
- const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
1303
- inst._zod.onattach.push((inst) => {
1304
- const bag = inst._zod.bag;
1305
- bag.format = def.format;
1306
- bag.minimum = minimum;
1307
- bag.maximum = maximum;
1308
- if (isInt) bag.pattern = integer;
1309
- });
1310
- inst._zod.check = (payload) => {
1311
- const input = payload.value;
1312
- if (isInt) {
1313
- if (!Number.isInteger(input)) {
1314
- payload.issues.push({
1315
- expected: origin,
1316
- format: def.format,
1317
- code: "invalid_type",
1318
- continue: false,
1319
- input,
1320
- inst
1321
- });
1322
- return;
1323
- }
1324
- if (!Number.isSafeInteger(input)) {
1325
- if (input > 0) payload.issues.push({
1326
- input,
1327
- code: "too_big",
1328
- maximum: Number.MAX_SAFE_INTEGER,
1329
- note: "Integers must be within the safe integer range.",
1330
- inst,
1331
- origin,
1332
- inclusive: true,
1333
- continue: !def.abort
1334
- });
1335
- else payload.issues.push({
1336
- input,
1337
- code: "too_small",
1338
- minimum: Number.MIN_SAFE_INTEGER,
1339
- note: "Integers must be within the safe integer range.",
1340
- inst,
1341
- origin,
1342
- inclusive: true,
1343
- continue: !def.abort
1344
- });
1345
- return;
1346
- }
1347
- }
1348
- if (input < minimum) payload.issues.push({
1349
- origin: "number",
1350
- input,
1351
- code: "too_small",
1352
- minimum,
1353
- inclusive: true,
1354
- inst,
1355
- continue: !def.abort
1356
- });
1357
- if (input > maximum) payload.issues.push({
1358
- origin: "number",
1359
- input,
1360
- code: "too_big",
1361
- maximum,
1362
- inclusive: true,
1363
- inst,
1364
- continue: !def.abort
1365
- });
1366
- };
1367
- });
1368
- const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
1369
- var _a;
1370
- $ZodCheck.init(inst, def);
1371
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1372
- const val = payload.value;
1373
- return !nullish(val) && val.length !== void 0;
1374
- });
1375
- inst._zod.onattach.push((inst) => {
1376
- const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
1377
- if (def.maximum < curr) inst._zod.bag.maximum = def.maximum;
1378
- });
1379
- inst._zod.check = (payload) => {
1380
- const input = payload.value;
1381
- if (input.length <= def.maximum) return;
1382
- const origin = getLengthableOrigin(input);
1383
- payload.issues.push({
1384
- origin,
1385
- code: "too_big",
1386
- maximum: def.maximum,
1387
- inclusive: true,
1388
- input,
1389
- inst,
1390
- continue: !def.abort
1391
- });
1392
- };
1393
- });
1394
- const $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
1395
- var _a;
1396
- $ZodCheck.init(inst, def);
1397
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1398
- const val = payload.value;
1399
- return !nullish(val) && val.length !== void 0;
1400
- });
1401
- inst._zod.onattach.push((inst) => {
1402
- const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
1403
- if (def.minimum > curr) inst._zod.bag.minimum = def.minimum;
1404
- });
1405
- inst._zod.check = (payload) => {
1406
- const input = payload.value;
1407
- if (input.length >= def.minimum) return;
1408
- const origin = getLengthableOrigin(input);
1409
- payload.issues.push({
1410
- origin,
1411
- code: "too_small",
1412
- minimum: def.minimum,
1413
- inclusive: true,
1414
- input,
824
+ minimum: def.minimum,
825
+ inclusive: true,
826
+ input,
1415
827
  inst,
1416
828
  continue: !def.abort
1417
829
  });
@@ -2130,13 +1542,13 @@ const $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
2130
1542
  }
2131
1543
  return propValues;
2132
1544
  });
2133
- const isObject = isObject$1;
1545
+ const isObject$2 = isObject;
2134
1546
  const catchall = def.catchall;
2135
1547
  let value;
2136
1548
  inst._zod.parse = (payload, ctx) => {
2137
1549
  value ?? (value = _normalized.value);
2138
1550
  const input = payload.value;
2139
- if (!isObject(input)) {
1551
+ if (!isObject$2(input)) {
2140
1552
  payload.issues.push({
2141
1553
  expected: "object",
2142
1554
  code: "invalid_type",
@@ -2230,7 +1642,7 @@ const $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def)
2230
1642
  return (payload, ctx) => fn(shape, payload, ctx);
2231
1643
  };
2232
1644
  let fastpass;
2233
- const isObject = isObject$1;
1645
+ const isObject$1 = isObject;
2234
1646
  const jit = !globalConfig.jitless;
2235
1647
  const fastEnabled = jit && allowsEval.value;
2236
1648
  const catchall = def.catchall;
@@ -2238,7 +1650,7 @@ const $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def)
2238
1650
  inst._zod.parse = (payload, ctx) => {
2239
1651
  value ?? (value = _normalized.value);
2240
1652
  const input = payload.value;
2241
- if (!isObject(input)) {
1653
+ if (!isObject$1(input)) {
2242
1654
  payload.issues.push({
2243
1655
  expected: "object",
2244
1656
  code: "invalid_type",
@@ -2312,6 +1724,61 @@ const $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
2312
1724
  });
2313
1725
  };
2314
1726
  });
1727
+ const $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
1728
+ def.inclusive = false;
1729
+ $ZodUnion.init(inst, def);
1730
+ const _super = inst._zod.parse;
1731
+ defineLazy(inst._zod, "propValues", () => {
1732
+ const propValues = {};
1733
+ for (const option of def.options) {
1734
+ const pv = option._zod.propValues;
1735
+ if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
1736
+ for (const [k, v] of Object.entries(pv)) {
1737
+ if (!propValues[k]) propValues[k] = /* @__PURE__ */ new Set();
1738
+ for (const val of v) propValues[k].add(val);
1739
+ }
1740
+ }
1741
+ return propValues;
1742
+ });
1743
+ const disc = cached(() => {
1744
+ const opts = def.options;
1745
+ const map = /* @__PURE__ */ new Map();
1746
+ for (const o of opts) {
1747
+ const values = o._zod.propValues?.[def.discriminator];
1748
+ if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
1749
+ for (const v of values) {
1750
+ if (map.has(v)) throw new Error(`Duplicate discriminator value "${String(v)}"`);
1751
+ map.set(v, o);
1752
+ }
1753
+ }
1754
+ return map;
1755
+ });
1756
+ inst._zod.parse = (payload, ctx) => {
1757
+ const input = payload.value;
1758
+ if (!isObject(input)) {
1759
+ payload.issues.push({
1760
+ code: "invalid_type",
1761
+ expected: "object",
1762
+ input,
1763
+ inst
1764
+ });
1765
+ return payload;
1766
+ }
1767
+ const opt = disc.value.get(input?.[def.discriminator]);
1768
+ if (opt) return opt._zod.run(payload, ctx);
1769
+ if (def.unionFallback) return _super(payload, ctx);
1770
+ payload.issues.push({
1771
+ code: "invalid_union",
1772
+ errors: [],
1773
+ note: "No matching discriminator",
1774
+ discriminator: def.discriminator,
1775
+ input,
1776
+ path: [def.discriminator],
1777
+ inst
1778
+ });
1779
+ return payload;
1780
+ };
1781
+ });
2315
1782
  const $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
2316
1783
  $ZodType.init(inst, def);
2317
1784
  inst._zod.parse = (payload, ctx) => {
@@ -2411,6 +1878,97 @@ function handleIntersectionResults(result, left, right) {
2411
1878
  result.value = merged.data;
2412
1879
  return result;
2413
1880
  }
1881
+ const $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
1882
+ $ZodType.init(inst, def);
1883
+ inst._zod.parse = (payload, ctx) => {
1884
+ const input = payload.value;
1885
+ if (!isPlainObject(input)) {
1886
+ payload.issues.push({
1887
+ expected: "record",
1888
+ code: "invalid_type",
1889
+ input,
1890
+ inst
1891
+ });
1892
+ return payload;
1893
+ }
1894
+ const proms = [];
1895
+ const values = def.keyType._zod.values;
1896
+ if (values) {
1897
+ payload.value = {};
1898
+ const recordKeys = /* @__PURE__ */ new Set();
1899
+ for (const key of values) if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
1900
+ recordKeys.add(typeof key === "number" ? key.toString() : key);
1901
+ const result = def.valueType._zod.run({
1902
+ value: input[key],
1903
+ issues: []
1904
+ }, ctx);
1905
+ if (result instanceof Promise) proms.push(result.then((result) => {
1906
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
1907
+ payload.value[key] = result.value;
1908
+ }));
1909
+ else {
1910
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
1911
+ payload.value[key] = result.value;
1912
+ }
1913
+ }
1914
+ let unrecognized;
1915
+ for (const key in input) if (!recordKeys.has(key)) {
1916
+ unrecognized = unrecognized ?? [];
1917
+ unrecognized.push(key);
1918
+ }
1919
+ if (unrecognized && unrecognized.length > 0) payload.issues.push({
1920
+ code: "unrecognized_keys",
1921
+ input,
1922
+ inst,
1923
+ keys: unrecognized
1924
+ });
1925
+ } else {
1926
+ payload.value = {};
1927
+ for (const key of Reflect.ownKeys(input)) {
1928
+ if (key === "__proto__") continue;
1929
+ let keyResult = def.keyType._zod.run({
1930
+ value: key,
1931
+ issues: []
1932
+ }, ctx);
1933
+ if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
1934
+ if (typeof key === "string" && number$1.test(key) && keyResult.issues.length) {
1935
+ const retryResult = def.keyType._zod.run({
1936
+ value: Number(key),
1937
+ issues: []
1938
+ }, ctx);
1939
+ if (retryResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
1940
+ if (retryResult.issues.length === 0) keyResult = retryResult;
1941
+ }
1942
+ if (keyResult.issues.length) {
1943
+ if (def.mode === "loose") payload.value[key] = input[key];
1944
+ else payload.issues.push({
1945
+ code: "invalid_key",
1946
+ origin: "record",
1947
+ issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
1948
+ input: key,
1949
+ path: [key],
1950
+ inst
1951
+ });
1952
+ continue;
1953
+ }
1954
+ const result = def.valueType._zod.run({
1955
+ value: input[key],
1956
+ issues: []
1957
+ }, ctx);
1958
+ if (result instanceof Promise) proms.push(result.then((result) => {
1959
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
1960
+ payload.value[keyResult.value] = result.value;
1961
+ }));
1962
+ else {
1963
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
1964
+ payload.value[keyResult.value] = result.value;
1965
+ }
1966
+ }
1967
+ }
1968
+ if (proms.length) return Promise.all(proms).then(() => payload);
1969
+ return payload;
1970
+ };
1971
+ });
2414
1972
  const $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
2415
1973
  $ZodType.init(inst, def);
2416
1974
  const values = getEnumValues(def.entries);
@@ -2429,6 +1987,24 @@ const $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
2429
1987
  return payload;
2430
1988
  };
2431
1989
  });
1990
+ const $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
1991
+ $ZodType.init(inst, def);
1992
+ if (def.values.length === 0) throw new Error("Cannot create literal schema with no valid values");
1993
+ const values = new Set(def.values);
1994
+ inst._zod.values = values;
1995
+ inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
1996
+ inst._zod.parse = (payload, _ctx) => {
1997
+ const input = payload.value;
1998
+ if (values.has(input)) return payload;
1999
+ payload.issues.push({
2000
+ code: "invalid_value",
2001
+ values: def.values,
2002
+ input,
2003
+ inst
2004
+ });
2005
+ return payload;
2006
+ };
2007
+ });
2432
2008
  const $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
2433
2009
  $ZodType.init(inst, def);
2434
2010
  inst._zod.parse = (payload, ctx) => {
@@ -3551,6 +3127,27 @@ const enumProcessor = (schema, _ctx, json, _params) => {
3551
3127
  if (values.every((v) => typeof v === "string")) json.type = "string";
3552
3128
  json.enum = values;
3553
3129
  };
3130
+ const literalProcessor = (schema, ctx, json, _params) => {
3131
+ const def = schema._zod.def;
3132
+ const vals = [];
3133
+ for (const val of def.values) if (val === void 0) {
3134
+ if (ctx.unrepresentable === "throw") throw new Error("Literal `undefined` cannot be represented in JSON Schema");
3135
+ } else if (typeof val === "bigint") if (ctx.unrepresentable === "throw") throw new Error("BigInt literals cannot be represented in JSON Schema");
3136
+ else vals.push(Number(val));
3137
+ else vals.push(val);
3138
+ if (vals.length === 0) {} else if (vals.length === 1) {
3139
+ const val = vals[0];
3140
+ json.type = val === null ? "null" : typeof val;
3141
+ if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") json.enum = [val];
3142
+ else json.const = val;
3143
+ } else {
3144
+ if (vals.every((v) => typeof v === "number")) json.type = "number";
3145
+ if (vals.every((v) => typeof v === "string")) json.type = "string";
3146
+ if (vals.every((v) => typeof v === "boolean")) json.type = "boolean";
3147
+ if (vals.every((v) => v === null)) json.type = "null";
3148
+ json.enum = vals;
3149
+ }
3150
+ };
3554
3151
  const customProcessor = (_schema, ctx, _json, _params) => {
3555
3152
  if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
3556
3153
  };
@@ -3633,6 +3230,39 @@ const intersectionProcessor = (schema, ctx, json, params) => {
3633
3230
  const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
3634
3231
  json.allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]];
3635
3232
  };
3233
+ const recordProcessor = (schema, ctx, _json, params) => {
3234
+ const json = _json;
3235
+ const def = schema._zod.def;
3236
+ json.type = "object";
3237
+ const keyType = def.keyType;
3238
+ const patterns = keyType._zod.bag?.patterns;
3239
+ if (def.mode === "loose" && patterns && patterns.size > 0) {
3240
+ const valueSchema = process(def.valueType, ctx, {
3241
+ ...params,
3242
+ path: [
3243
+ ...params.path,
3244
+ "patternProperties",
3245
+ "*"
3246
+ ]
3247
+ });
3248
+ json.patternProperties = {};
3249
+ for (const pattern of patterns) json.patternProperties[pattern.source] = valueSchema;
3250
+ } else {
3251
+ if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") json.propertyNames = process(def.keyType, ctx, {
3252
+ ...params,
3253
+ path: [...params.path, "propertyNames"]
3254
+ });
3255
+ json.additionalProperties = process(def.valueType, ctx, {
3256
+ ...params,
3257
+ path: [...params.path, "additionalProperties"]
3258
+ });
3259
+ }
3260
+ const keyValues = keyType._zod.values;
3261
+ if (keyValues) {
3262
+ const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
3263
+ if (validKeyValues.length > 0) json.required = validKeyValues;
3264
+ }
3265
+ };
3636
3266
  const nullableProcessor = (schema, ctx, json, params) => {
3637
3267
  const def = schema._zod.def;
3638
3268
  const inner = process(def.innerType, ctx, params);
@@ -3754,8 +3384,8 @@ const parse = /* @__PURE__ */ _parse(ZodRealError);
3754
3384
  const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
3755
3385
  const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
3756
3386
  const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
3757
- const encode$2 = /* @__PURE__ */ _encode(ZodRealError);
3758
- const decode$1 = /* @__PURE__ */ _decode(ZodRealError);
3387
+ const encode = /* @__PURE__ */ _encode(ZodRealError);
3388
+ const decode = /* @__PURE__ */ _decode(ZodRealError);
3759
3389
  const encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
3760
3390
  const decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
3761
3391
  const safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
@@ -3793,8 +3423,8 @@ const ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
3793
3423
  inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
3794
3424
  inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
3795
3425
  inst.spa = inst.safeParseAsync;
3796
- inst.encode = (data, params) => encode$2(inst, data, params);
3797
- inst.decode = (data, params) => decode$1(inst, data, params);
3426
+ inst.encode = (data, params) => encode(inst, data, params);
3427
+ inst.decode = (data, params) => decode(inst, data, params);
3798
3428
  inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
3799
3429
  inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
3800
3430
  inst.safeEncode = (data, params) => safeEncode(inst, data, params);
@@ -3919,6 +3549,9 @@ const ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
3919
3549
  $ZodURL.init(inst, def);
3920
3550
  ZodStringFormat.init(inst, def);
3921
3551
  });
3552
+ function url(params) {
3553
+ return /* @__PURE__ */ _url(ZodURL, params);
3554
+ }
3922
3555
  const ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
3923
3556
  $ZodEmoji.init(inst, def);
3924
3557
  ZodStringFormat.init(inst, def);
@@ -4100,6 +3733,14 @@ function object(shape, params) {
4100
3733
  ...normalizeParams(params)
4101
3734
  });
4102
3735
  }
3736
+ function looseObject(shape, params) {
3737
+ return new ZodObject({
3738
+ type: "object",
3739
+ shape,
3740
+ catchall: unknown(),
3741
+ ...normalizeParams(params)
3742
+ });
3743
+ }
4103
3744
  const ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
4104
3745
  $ZodUnion.init(inst, def);
4105
3746
  ZodType.init(inst, def);
@@ -4113,6 +3754,18 @@ function union(options, params) {
4113
3754
  ...normalizeParams(params)
4114
3755
  });
4115
3756
  }
3757
+ const ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {
3758
+ ZodUnion.init(inst, def);
3759
+ $ZodDiscriminatedUnion.init(inst, def);
3760
+ });
3761
+ function discriminatedUnion(discriminator, options, params) {
3762
+ return new ZodDiscriminatedUnion({
3763
+ type: "union",
3764
+ options,
3765
+ discriminator,
3766
+ ...normalizeParams(params)
3767
+ });
3768
+ }
4116
3769
  const ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
4117
3770
  $ZodIntersection.init(inst, def);
4118
3771
  ZodType.init(inst, def);
@@ -4125,6 +3778,21 @@ function intersection(left, right) {
4125
3778
  right
4126
3779
  });
4127
3780
  }
3781
+ const ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
3782
+ $ZodRecord.init(inst, def);
3783
+ ZodType.init(inst, def);
3784
+ inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params);
3785
+ inst.keyType = def.keyType;
3786
+ inst.valueType = def.valueType;
3787
+ });
3788
+ function record(keyType, valueType, params) {
3789
+ return new ZodRecord({
3790
+ type: "record",
3791
+ keyType,
3792
+ valueType,
3793
+ ...normalizeParams(params)
3794
+ });
3795
+ }
4128
3796
  const ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
4129
3797
  $ZodEnum.init(inst, def);
4130
3798
  ZodType.init(inst, def);
@@ -4162,6 +3830,23 @@ function _enum(values, params) {
4162
3830
  ...normalizeParams(params)
4163
3831
  });
4164
3832
  }
3833
+ const ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
3834
+ $ZodLiteral.init(inst, def);
3835
+ ZodType.init(inst, def);
3836
+ inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params);
3837
+ inst.values = new Set(def.values);
3838
+ Object.defineProperty(inst, "value", { get() {
3839
+ if (def.values.length > 1) throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
3840
+ return def.values[0];
3841
+ } });
3842
+ });
3843
+ function literal(value, params) {
3844
+ return new ZodLiteral({
3845
+ type: "literal",
3846
+ values: Array.isArray(value) ? value : [value],
3847
+ ...normalizeParams(params)
3848
+ });
3849
+ }
4165
3850
  const ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
4166
3851
  $ZodTransform.init(inst, def);
4167
3852
  ZodType.init(inst, def);
@@ -4325,1502 +4010,497 @@ function refine(fn, _params = {}) {
4325
4010
  function superRefine(fn) {
4326
4011
  return /* @__PURE__ */ _superRefine(fn);
4327
4012
  }
4013
+ function preprocess(fn, schema) {
4014
+ return pipe(transform(fn), schema);
4015
+ }
4328
4016
  //#endregion
4329
- //#region src/core/schemas.ts
4330
- /** Zod schema for the raw token response from the OAuth token endpoint. */
4331
- const TokenResponseSchema = object({
4332
- access_token: string(),
4333
- refresh_token: string().nullable().optional().default(null),
4334
- expires_in: number(),
4335
- token_type: string(),
4336
- scope: string().nullable().optional().default(null),
4337
- id_token: string().nullable().optional().default(null)
4338
- });
4339
- /** Zod schema for a Fanvue user profile. */
4340
- const FanvueUserSchema = object({
4341
- uuid: string(),
4342
- email: string(),
4343
- handle: string(),
4344
- displayName: string(),
4345
- isCreator: boolean(),
4346
- avatarUrl: string().nullable(),
4347
- bannerUrl: string().nullable(),
4348
- createdAt: string(),
4349
- updatedAt: string().nullable()
4350
- });
4351
- /** Zod schema for the authorize-on-behalf response from the Fanvue platform. */
4352
- const AuthorizeOnBehalfResponseSchema = object({
4353
- code: string(),
4354
- state: string()
4355
- });
4356
- /** Zod schema for the session JWT payload. */
4357
- const SessionPayloadSchema = object({
4358
- accessToken: string(),
4359
- refreshToken: string().nullable(),
4360
- expiresAt: number(),
4361
- tokenType: string().nullable(),
4362
- scope: string().nullable(),
4363
- idToken: string().nullable(),
4364
- userUuid: string(),
4365
- handle: string(),
4366
- displayName: string(),
4367
- isCreator: boolean(),
4368
- avatarUrl: string().nullable()
4369
- }).passthrough();
4370
- //#endregion
4371
- //#region src/core/oauth.ts
4372
- const CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded";
4373
- const OAUTH_TOKEN_ENDPOINT = "/oauth2/token";
4374
- /**
4375
- * Builds an OAuth 2.0 authorization URL with PKCE parameters.
4376
- *
4377
- * @param config - The OAuth configuration.
4378
- * @param opts - Optional overrides. Pass `state` to use a deterministic state value.
4379
- * @returns The authorization URL, the PKCE code verifier, and the state parameter.
4380
- */
4381
- async function createAuthorizationUrl(config, opts = null) {
4382
- const codeVerifier = generateRandomCodeVerifier();
4383
- const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);
4384
- const state = opts?.state ?? generateRandomState();
4385
- const issuerUrl = config.issuerUrl ?? "https://auth.fanvue.com";
4386
- const scope = config.scopes !== null ? `${DEFAULT_SCOPES} ${config.scopes}`.trim() : DEFAULT_SCOPES;
4387
- const url = new URL(`${issuerUrl}/oauth2/auth`);
4388
- url.searchParams.set("response_type", "code");
4389
- url.searchParams.set("client_id", config.clientId);
4390
- url.searchParams.set("redirect_uri", config.redirectUri);
4391
- url.searchParams.set("scope", scope);
4392
- url.searchParams.set("state", state);
4393
- url.searchParams.set("code_challenge", codeChallenge);
4394
- url.searchParams.set("code_challenge_method", "S256");
4395
- if (config.responseMode !== null) url.searchParams.set("response_mode", config.responseMode);
4396
- if (config.prompt !== null) url.searchParams.set("prompt", config.prompt);
4397
- return {
4398
- url,
4399
- codeVerifier,
4400
- state
4017
+ //#region node_modules/.pnpm/neverthrow@8.2.0/node_modules/neverthrow/dist/index.cjs.js
4018
+ var require_index_cjs = /* @__PURE__ */ __commonJSMin(((exports) => {
4019
+ const defaultErrorConfig = { withStackTrace: false };
4020
+ const createNeverThrowError = (message, result, config = defaultErrorConfig) => {
4021
+ return {
4022
+ data: result.isOk() ? {
4023
+ type: "Ok",
4024
+ value: result.value
4025
+ } : {
4026
+ type: "Err",
4027
+ value: result.error
4028
+ },
4029
+ message,
4030
+ stack: config.withStackTrace ? (/* @__PURE__ */ new Error()).stack : void 0
4031
+ };
4032
+ };
4033
+ /******************************************************************************
4034
+ Copyright (c) Microsoft Corporation.
4035
+
4036
+ Permission to use, copy, modify, and/or distribute this software for any
4037
+ purpose with or without fee is hereby granted.
4038
+
4039
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
4040
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
4041
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
4042
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
4043
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4044
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4045
+ PERFORMANCE OF THIS SOFTWARE.
4046
+ ***************************************************************************** */
4047
+ function __awaiter(thisArg, _arguments, P, generator) {
4048
+ function adopt(value) {
4049
+ return value instanceof P ? value : new P(function(resolve) {
4050
+ resolve(value);
4051
+ });
4052
+ }
4053
+ return new (P || (P = Promise))(function(resolve, reject) {
4054
+ function fulfilled(value) {
4055
+ try {
4056
+ step(generator.next(value));
4057
+ } catch (e) {
4058
+ reject(e);
4059
+ }
4060
+ }
4061
+ function rejected(value) {
4062
+ try {
4063
+ step(generator["throw"](value));
4064
+ } catch (e) {
4065
+ reject(e);
4066
+ }
4067
+ }
4068
+ function step(result) {
4069
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
4070
+ }
4071
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
4072
+ });
4073
+ }
4074
+ function __values(o) {
4075
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
4076
+ if (m) return m.call(o);
4077
+ if (o && typeof o.length === "number") return { next: function() {
4078
+ if (o && i >= o.length) o = void 0;
4079
+ return {
4080
+ value: o && o[i++],
4081
+ done: !o
4082
+ };
4083
+ } };
4084
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
4085
+ }
4086
+ function __await(v) {
4087
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
4088
+ }
4089
+ function __asyncGenerator(thisArg, _arguments, generator) {
4090
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4091
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
4092
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
4093
+ return this;
4094
+ }, i;
4095
+ function awaitReturn(f) {
4096
+ return function(v) {
4097
+ return Promise.resolve(v).then(f, reject);
4098
+ };
4099
+ }
4100
+ function verb(n, f) {
4101
+ if (g[n]) {
4102
+ i[n] = function(v) {
4103
+ return new Promise(function(a, b) {
4104
+ q.push([
4105
+ n,
4106
+ v,
4107
+ a,
4108
+ b
4109
+ ]) > 1 || resume(n, v);
4110
+ });
4111
+ };
4112
+ if (f) i[n] = f(i[n]);
4113
+ }
4114
+ }
4115
+ function resume(n, v) {
4116
+ try {
4117
+ step(g[n](v));
4118
+ } catch (e) {
4119
+ settle(q[0][3], e);
4120
+ }
4121
+ }
4122
+ function step(r) {
4123
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
4124
+ }
4125
+ function fulfill(value) {
4126
+ resume("next", value);
4127
+ }
4128
+ function reject(value) {
4129
+ resume("throw", value);
4130
+ }
4131
+ function settle(f, v) {
4132
+ if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
4133
+ }
4134
+ }
4135
+ function __asyncDelegator(o) {
4136
+ var i, p;
4137
+ return i = {}, verb("next"), verb("throw", function(e) {
4138
+ throw e;
4139
+ }), verb("return"), i[Symbol.iterator] = function() {
4140
+ return this;
4141
+ }, i;
4142
+ function verb(n, f) {
4143
+ i[n] = o[n] ? function(v) {
4144
+ return (p = !p) ? {
4145
+ value: __await(o[n](v)),
4146
+ done: false
4147
+ } : f ? f(v) : v;
4148
+ } : f;
4149
+ }
4150
+ }
4151
+ function __asyncValues(o) {
4152
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4153
+ var m = o[Symbol.asyncIterator], i;
4154
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
4155
+ return this;
4156
+ }, i);
4157
+ function verb(n) {
4158
+ i[n] = o[n] && function(v) {
4159
+ return new Promise(function(resolve, reject) {
4160
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
4161
+ });
4162
+ };
4163
+ }
4164
+ function settle(resolve, reject, d, v) {
4165
+ Promise.resolve(v).then(function(v) {
4166
+ resolve({
4167
+ value: v,
4168
+ done: d
4169
+ });
4170
+ }, reject);
4171
+ }
4172
+ }
4173
+ var ResultAsync = class ResultAsync {
4174
+ constructor(res) {
4175
+ this._promise = res;
4176
+ }
4177
+ static fromSafePromise(promise) {
4178
+ return new ResultAsync(promise.then((value) => new Ok(value)));
4179
+ }
4180
+ static fromPromise(promise, errorFn) {
4181
+ return new ResultAsync(promise.then((value) => new Ok(value)).catch((e) => new Err(errorFn(e))));
4182
+ }
4183
+ static fromThrowable(fn, errorFn) {
4184
+ return (...args) => {
4185
+ return new ResultAsync(__awaiter(this, void 0, void 0, function* () {
4186
+ try {
4187
+ return new Ok(yield fn(...args));
4188
+ } catch (error) {
4189
+ return new Err(errorFn ? errorFn(error) : error);
4190
+ }
4191
+ }));
4192
+ };
4193
+ }
4194
+ static combine(asyncResultList) {
4195
+ return combineResultAsyncList(asyncResultList);
4196
+ }
4197
+ static combineWithAllErrors(asyncResultList) {
4198
+ return combineResultAsyncListWithAllErrors(asyncResultList);
4199
+ }
4200
+ map(f) {
4201
+ return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
4202
+ if (res.isErr()) return new Err(res.error);
4203
+ return new Ok(yield f(res.value));
4204
+ })));
4205
+ }
4206
+ andThrough(f) {
4207
+ return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
4208
+ if (res.isErr()) return new Err(res.error);
4209
+ const newRes = yield f(res.value);
4210
+ if (newRes.isErr()) return new Err(newRes.error);
4211
+ return new Ok(res.value);
4212
+ })));
4213
+ }
4214
+ andTee(f) {
4215
+ return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
4216
+ if (res.isErr()) return new Err(res.error);
4217
+ try {
4218
+ yield f(res.value);
4219
+ } catch (e) {}
4220
+ return new Ok(res.value);
4221
+ })));
4222
+ }
4223
+ orTee(f) {
4224
+ return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
4225
+ if (res.isOk()) return new Ok(res.value);
4226
+ try {
4227
+ yield f(res.error);
4228
+ } catch (e) {}
4229
+ return new Err(res.error);
4230
+ })));
4231
+ }
4232
+ mapErr(f) {
4233
+ return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
4234
+ if (res.isOk()) return new Ok(res.value);
4235
+ return new Err(yield f(res.error));
4236
+ })));
4237
+ }
4238
+ andThen(f) {
4239
+ return new ResultAsync(this._promise.then((res) => {
4240
+ if (res.isErr()) return new Err(res.error);
4241
+ const newValue = f(res.value);
4242
+ return newValue instanceof ResultAsync ? newValue._promise : newValue;
4243
+ }));
4244
+ }
4245
+ orElse(f) {
4246
+ return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
4247
+ if (res.isErr()) return f(res.error);
4248
+ return new Ok(res.value);
4249
+ })));
4250
+ }
4251
+ match(ok, _err) {
4252
+ return this._promise.then((res) => res.match(ok, _err));
4253
+ }
4254
+ unwrapOr(t) {
4255
+ return this._promise.then((res) => res.unwrapOr(t));
4256
+ }
4257
+ /**
4258
+ * @deprecated will be removed in 9.0.0.
4259
+ *
4260
+ * You can use `safeTry` without this method.
4261
+ * @example
4262
+ * ```typescript
4263
+ * safeTry(async function* () {
4264
+ * const okValue = yield* yourResult
4265
+ * })
4266
+ * ```
4267
+ * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
4268
+ */
4269
+ safeUnwrap() {
4270
+ return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
4271
+ return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
4272
+ });
4273
+ }
4274
+ then(successCallback, failureCallback) {
4275
+ return this._promise.then(successCallback, failureCallback);
4276
+ }
4277
+ [Symbol.asyncIterator]() {
4278
+ return __asyncGenerator(this, arguments, function* _a() {
4279
+ const result = yield __await(this._promise);
4280
+ if (result.isErr()) yield yield __await(errAsync(result.error));
4281
+ return yield __await(result.value);
4282
+ });
4283
+ }
4401
4284
  };
4402
- }
4403
- /**
4404
- * Exchanges an authorization code for tokens using the OAuth token endpoint.
4405
- *
4406
- * @param config - The OAuth configuration.
4407
- * @param opts - The authorization code, PKCE code verifier, and optional redirect URI override.
4408
- * @returns A `Result` containing `TokenResponse` on success or `OAuthError` on failure.
4409
- */
4410
- async function exchangeCodeForToken(config, opts) {
4411
- const issuerUrl = config.issuerUrl ?? "https://auth.fanvue.com";
4412
- const body = new URLSearchParams({
4413
- grant_type: "authorization_code",
4414
- code: opts.code,
4415
- redirect_uri: opts.redirectUri ?? config.redirectUri,
4416
- client_id: config.clientId,
4417
- code_verifier: opts.codeVerifier
4418
- });
4419
- let response;
4420
- try {
4421
- response = await fetch(`${issuerUrl}${OAUTH_TOKEN_ENDPOINT}`, {
4422
- method: "POST",
4423
- headers: {
4424
- "Content-Type": CONTENT_TYPE_FORM_URLENCODED,
4425
- Authorization: `Basic ${btoa(`${config.clientId}:${config.clientSecret}`)}`
4426
- },
4427
- body
4428
- });
4429
- } catch (error) {
4430
- return (0, import_index_cjs.err)({
4431
- code: "TOKEN_EXCHANGE_FAILED",
4432
- statusCode: 0,
4433
- message: `Network error during token exchange: ${error instanceof Error ? error.message : String(error)}`
4434
- });
4435
- }
4436
- if (!response.ok) return (0, import_index_cjs.err)({
4437
- code: "TOKEN_EXCHANGE_FAILED",
4438
- statusCode: response.status,
4439
- message: `Token exchange failed: ${response.status} ${response.statusText}`
4440
- });
4441
- const parseResult = safeJsonParse(await response.text());
4442
- if (parseResult.isErr()) {
4443
- const { rawText, message } = parseResult.error;
4444
- return (0, import_index_cjs.err)({
4445
- code: "OAUTH_JSON_PARSE_ERROR",
4446
- rawText,
4447
- message
4448
- });
4449
- }
4450
- const validated = TokenResponseSchema.safeParse(parseResult.value);
4451
- if (!validated.success) return (0, import_index_cjs.err)({
4452
- code: "OAUTH_VALIDATION_ERROR",
4453
- message: validated.error.message
4454
- });
4455
- return (0, import_index_cjs.ok)(validated.data);
4456
- }
4457
- /**
4458
- * Refreshes an access token using a refresh token.
4459
- *
4460
- * @param config - The OAuth configuration.
4461
- * @param refreshToken - The refresh token to use.
4462
- * @returns A `Result` containing `TokenResponse` on success or `OAuthError` on failure.
4463
- */
4464
- async function refreshAccessToken(config, refreshToken) {
4465
- const issuerUrl = config.issuerUrl ?? "https://auth.fanvue.com";
4466
- const body = new URLSearchParams({
4467
- grant_type: "refresh_token",
4468
- refresh_token: refreshToken,
4469
- client_id: config.clientId
4470
- });
4471
- let response;
4472
- try {
4473
- response = await fetch(`${issuerUrl}${OAUTH_TOKEN_ENDPOINT}`, {
4474
- method: "POST",
4475
- headers: {
4476
- "Content-Type": CONTENT_TYPE_FORM_URLENCODED,
4477
- Authorization: `Basic ${btoa(`${config.clientId}:${config.clientSecret}`)}`
4478
- },
4479
- body
4480
- });
4481
- } catch (error) {
4482
- return (0, import_index_cjs.err)({
4483
- code: "TOKEN_REFRESH_FAILED",
4484
- statusCode: 0,
4485
- message: `Network error during token refresh: ${error instanceof Error ? error.message : String(error)}`
4486
- });
4487
- }
4488
- if (!response.ok) return (0, import_index_cjs.err)({
4489
- code: "TOKEN_REFRESH_FAILED",
4490
- statusCode: response.status,
4491
- message: `Token refresh failed: ${response.status} ${response.statusText}`
4492
- });
4493
- const parseResult = safeJsonParse(await response.text());
4494
- if (parseResult.isErr()) {
4495
- const { rawText, message } = parseResult.error;
4496
- return (0, import_index_cjs.err)({
4497
- code: "OAUTH_JSON_PARSE_ERROR",
4498
- rawText,
4499
- message
4500
- });
4501
- }
4502
- const validated = TokenResponseSchema.safeParse(parseResult.value);
4503
- if (!validated.success) return (0, import_index_cjs.err)({
4504
- code: "OAUTH_VALIDATION_ERROR",
4505
- message: validated.error.message
4506
- });
4507
- return (0, import_index_cjs.ok)(validated.data);
4508
- }
4509
- //#endregion
4510
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/lib/buffer_utils.js
4511
- const encoder = new TextEncoder();
4512
- const decoder = new TextDecoder();
4513
- function concat(...buffers) {
4514
- const size = buffers.reduce((acc, { length }) => acc + length, 0);
4515
- const buf = new Uint8Array(size);
4516
- let i = 0;
4517
- for (const buffer of buffers) {
4518
- buf.set(buffer, i);
4519
- i += buffer.length;
4520
- }
4521
- return buf;
4522
- }
4523
- function encode$1(string) {
4524
- const bytes = new Uint8Array(string.length);
4525
- for (let i = 0; i < string.length; i++) {
4526
- const code = string.charCodeAt(i);
4527
- if (code > 127) throw new TypeError("non-ASCII string encountered in encode()");
4528
- bytes[i] = code;
4529
- }
4530
- return bytes;
4531
- }
4532
- //#endregion
4533
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/lib/base64.js
4534
- function encodeBase64(input) {
4535
- if (Uint8Array.prototype.toBase64) return input.toBase64();
4536
- const CHUNK_SIZE = 32768;
4537
- const arr = [];
4538
- for (let i = 0; i < input.length; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
4539
- return btoa(arr.join(""));
4540
- }
4541
- function decodeBase64(encoded) {
4542
- if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded);
4543
- const binary = atob(encoded);
4544
- const bytes = new Uint8Array(binary.length);
4545
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
4546
- return bytes;
4547
- }
4548
- //#endregion
4549
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/util/base64url.js
4550
- function decode(input) {
4551
- if (Uint8Array.fromBase64) return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { alphabet: "base64url" });
4552
- let encoded = input;
4553
- if (encoded instanceof Uint8Array) encoded = decoder.decode(encoded);
4554
- encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
4555
- try {
4556
- return decodeBase64(encoded);
4557
- } catch {
4558
- throw new TypeError("The input to be decoded is not correctly encoded.");
4285
+ function okAsync(value) {
4286
+ return new ResultAsync(Promise.resolve(new Ok(value)));
4559
4287
  }
4560
- }
4561
- function encode(input) {
4562
- let unencoded = input;
4563
- if (typeof unencoded === "string") unencoded = encoder.encode(unencoded);
4564
- if (Uint8Array.prototype.toBase64) return unencoded.toBase64({
4565
- alphabet: "base64url",
4566
- omitPadding: true
4567
- });
4568
- return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
4569
- }
4570
- //#endregion
4571
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/lib/crypto_key.js
4572
- const unusable = (name, prop = "algorithm.name") => /* @__PURE__ */ new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
4573
- const isAlgorithm = (algorithm, name) => algorithm.name === name;
4574
- function getHashLength(hash) {
4575
- return parseInt(hash.name.slice(4), 10);
4576
- }
4577
- function checkHashLength(algorithm, expected) {
4578
- if (getHashLength(algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
4579
- }
4580
- function getNamedCurve(alg) {
4581
- switch (alg) {
4582
- case "ES256": return "P-256";
4583
- case "ES384": return "P-384";
4584
- case "ES512": return "P-521";
4585
- default: throw new Error("unreachable");
4288
+ function errAsync(err) {
4289
+ return new ResultAsync(Promise.resolve(new Err(err)));
4586
4290
  }
4587
- }
4588
- function checkUsage(key, usage) {
4589
- if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
4590
- }
4591
- function checkSigCryptoKey(key, alg, usage) {
4592
- switch (alg) {
4593
- case "HS256":
4594
- case "HS384":
4595
- case "HS512":
4596
- if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC");
4597
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
4598
- break;
4599
- case "RS256":
4600
- case "RS384":
4601
- case "RS512":
4602
- if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5");
4603
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
4604
- break;
4605
- case "PS256":
4606
- case "PS384":
4607
- case "PS512":
4608
- if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS");
4609
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
4610
- break;
4611
- case "Ed25519":
4612
- case "EdDSA":
4613
- if (!isAlgorithm(key.algorithm, "Ed25519")) throw unusable("Ed25519");
4614
- break;
4615
- case "ML-DSA-44":
4616
- case "ML-DSA-65":
4617
- case "ML-DSA-87":
4618
- if (!isAlgorithm(key.algorithm, alg)) throw unusable(alg);
4619
- break;
4620
- case "ES256":
4621
- case "ES384":
4622
- case "ES512": {
4623
- if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA");
4624
- const expected = getNamedCurve(alg);
4625
- if (key.algorithm.namedCurve !== expected) throw unusable(expected, "algorithm.namedCurve");
4291
+ const fromPromise = ResultAsync.fromPromise;
4292
+ const fromSafePromise = ResultAsync.fromSafePromise;
4293
+ const fromAsyncThrowable = ResultAsync.fromThrowable;
4294
+ /**
4295
+ * Short circuits on the FIRST Err value that we find
4296
+ */
4297
+ const combineResultList = (resultList) => {
4298
+ let acc = ok([]);
4299
+ for (const result of resultList) if (result.isErr()) {
4300
+ acc = err(result.error);
4626
4301
  break;
4302
+ } else acc.map((list) => list.push(result.value));
4303
+ return acc;
4304
+ };
4305
+ const combineResultAsyncList = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultList);
4306
+ /**
4307
+ * Give a list of all the errors we find
4308
+ */
4309
+ const combineResultListWithAllErrors = (resultList) => {
4310
+ let acc = ok([]);
4311
+ for (const result of resultList) if (result.isErr() && acc.isErr()) acc.error.push(result.error);
4312
+ else if (result.isErr() && acc.isOk()) acc = err([result.error]);
4313
+ else if (result.isOk() && acc.isOk()) acc.value.push(result.value);
4314
+ return acc;
4315
+ };
4316
+ const combineResultAsyncListWithAllErrors = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultListWithAllErrors);
4317
+ exports.Result = void 0;
4318
+ (function(Result) {
4319
+ /**
4320
+ * Wraps a function with a try catch, creating a new function with the same
4321
+ * arguments but returning `Ok` if successful, `Err` if the function throws
4322
+ *
4323
+ * @param fn function to wrap with ok on success or err on failure
4324
+ * @param errorFn when an error is thrown, this will wrap the error result if provided
4325
+ */
4326
+ function fromThrowable(fn, errorFn) {
4327
+ return (...args) => {
4328
+ try {
4329
+ return ok(fn(...args));
4330
+ } catch (e) {
4331
+ return err(errorFn ? errorFn(e) : e);
4332
+ }
4333
+ };
4627
4334
  }
4628
- default: throw new TypeError("CryptoKey does not support this operation");
4629
- }
4630
- checkUsage(key, usage);
4631
- }
4632
- //#endregion
4633
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/lib/invalid_key_input.js
4634
- function message(msg, actual, ...types) {
4635
- types = types.filter(Boolean);
4636
- if (types.length > 2) {
4637
- const last = types.pop();
4638
- msg += `one of type ${types.join(", ")}, or ${last}.`;
4639
- } else if (types.length === 2) msg += `one of type ${types[0]} or ${types[1]}.`;
4640
- else msg += `of type ${types[0]}.`;
4641
- if (actual == null) msg += ` Received ${actual}`;
4642
- else if (typeof actual === "function" && actual.name) msg += ` Received function ${actual.name}`;
4643
- else if (typeof actual === "object" && actual != null) {
4644
- if (actual.constructor?.name) msg += ` Received an instance of ${actual.constructor.name}`;
4645
- }
4646
- return msg;
4647
- }
4648
- const invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
4649
- const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
4650
- //#endregion
4651
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/util/errors.js
4652
- var JOSEError = class extends Error {
4653
- static code = "ERR_JOSE_GENERIC";
4654
- code = "ERR_JOSE_GENERIC";
4655
- constructor(message, options) {
4656
- super(message, options);
4657
- this.name = this.constructor.name;
4658
- Error.captureStackTrace?.(this, this.constructor);
4659
- }
4660
- };
4661
- var JWTClaimValidationFailed = class extends JOSEError {
4662
- static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
4663
- code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
4664
- claim;
4665
- reason;
4666
- payload;
4667
- constructor(message, payload, claim = "unspecified", reason = "unspecified") {
4668
- super(message, { cause: {
4669
- claim,
4670
- reason,
4671
- payload
4672
- } });
4673
- this.claim = claim;
4674
- this.reason = reason;
4675
- this.payload = payload;
4676
- }
4677
- };
4678
- var JWTExpired = class extends JOSEError {
4679
- static code = "ERR_JWT_EXPIRED";
4680
- code = "ERR_JWT_EXPIRED";
4681
- claim;
4682
- reason;
4683
- payload;
4684
- constructor(message, payload, claim = "unspecified", reason = "unspecified") {
4685
- super(message, { cause: {
4686
- claim,
4687
- reason,
4688
- payload
4689
- } });
4690
- this.claim = claim;
4691
- this.reason = reason;
4692
- this.payload = payload;
4693
- }
4694
- };
4695
- var JOSEAlgNotAllowed = class extends JOSEError {
4696
- static code = "ERR_JOSE_ALG_NOT_ALLOWED";
4697
- code = "ERR_JOSE_ALG_NOT_ALLOWED";
4698
- };
4699
- var JOSENotSupported = class extends JOSEError {
4700
- static code = "ERR_JOSE_NOT_SUPPORTED";
4701
- code = "ERR_JOSE_NOT_SUPPORTED";
4702
- };
4703
- var JWSInvalid = class extends JOSEError {
4704
- static code = "ERR_JWS_INVALID";
4705
- code = "ERR_JWS_INVALID";
4706
- };
4707
- var JWTInvalid = class extends JOSEError {
4708
- static code = "ERR_JWT_INVALID";
4709
- code = "ERR_JWT_INVALID";
4710
- };
4711
- Symbol.asyncIterator;
4712
- var JWSSignatureVerificationFailed = class extends JOSEError {
4713
- static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
4714
- code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
4715
- constructor(message = "signature verification failed", options) {
4716
- super(message, options);
4717
- }
4718
- };
4719
- //#endregion
4720
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/lib/is_key_like.js
4721
- const isCryptoKey = (key) => {
4722
- if (key?.[Symbol.toStringTag] === "CryptoKey") return true;
4723
- try {
4724
- return key instanceof CryptoKey;
4725
- } catch {
4726
- return false;
4727
- }
4728
- };
4729
- const isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
4730
- const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
4731
- //#endregion
4732
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/lib/helpers.js
4733
- function assertNotSet(value, name) {
4734
- if (value) throw new TypeError(`${name} can only be called once`);
4735
- }
4736
- function decodeBase64url(value, label, ErrorClass) {
4737
- try {
4738
- return decode(value);
4739
- } catch {
4740
- throw new ErrorClass(`Failed to base64url decode the ${label}`);
4741
- }
4742
- }
4743
- //#endregion
4744
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/lib/type_checks.js
4745
- const isObjectLike = (value) => typeof value === "object" && value !== null;
4746
- function isObject(input) {
4747
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") return false;
4748
- if (Object.getPrototypeOf(input) === null) return true;
4749
- let proto = input;
4750
- while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto);
4751
- return Object.getPrototypeOf(input) === proto;
4752
- }
4753
- function isDisjoint(...headers) {
4754
- const sources = headers.filter(Boolean);
4755
- if (sources.length === 0 || sources.length === 1) return true;
4756
- let acc;
4757
- for (const header of sources) {
4758
- const parameters = Object.keys(header);
4759
- if (!acc || acc.size === 0) {
4760
- acc = new Set(parameters);
4761
- continue;
4335
+ Result.fromThrowable = fromThrowable;
4336
+ function combine(resultList) {
4337
+ return combineResultList(resultList);
4762
4338
  }
4763
- for (const parameter of parameters) {
4764
- if (acc.has(parameter)) return false;
4765
- acc.add(parameter);
4339
+ Result.combine = combine;
4340
+ function combineWithAllErrors(resultList) {
4341
+ return combineResultListWithAllErrors(resultList);
4766
4342
  }
4343
+ Result.combineWithAllErrors = combineWithAllErrors;
4344
+ })(exports.Result || (exports.Result = {}));
4345
+ function ok(value) {
4346
+ return new Ok(value);
4767
4347
  }
4768
- return true;
4769
- }
4770
- const isJWK = (key) => isObject(key) && typeof key.kty === "string";
4771
- const isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
4772
- const isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
4773
- const isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
4774
- //#endregion
4775
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/lib/signing.js
4776
- function checkKeyLength(alg, key) {
4777
- if (alg.startsWith("RS") || alg.startsWith("PS")) {
4778
- const { modulusLength } = key.algorithm;
4779
- if (typeof modulusLength !== "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
4780
- }
4781
- }
4782
- function subtleAlgorithm(alg, algorithm) {
4783
- const hash = `SHA-${alg.slice(-3)}`;
4784
- switch (alg) {
4785
- case "HS256":
4786
- case "HS384":
4787
- case "HS512": return {
4788
- hash,
4789
- name: "HMAC"
4790
- };
4791
- case "PS256":
4792
- case "PS384":
4793
- case "PS512": return {
4794
- hash,
4795
- name: "RSA-PSS",
4796
- saltLength: parseInt(alg.slice(-3), 10) >> 3
4797
- };
4798
- case "RS256":
4799
- case "RS384":
4800
- case "RS512": return {
4801
- hash,
4802
- name: "RSASSA-PKCS1-v1_5"
4803
- };
4804
- case "ES256":
4805
- case "ES384":
4806
- case "ES512": return {
4807
- hash,
4808
- name: "ECDSA",
4809
- namedCurve: algorithm.namedCurve
4810
- };
4811
- case "Ed25519":
4812
- case "EdDSA": return { name: "Ed25519" };
4813
- case "ML-DSA-44":
4814
- case "ML-DSA-65":
4815
- case "ML-DSA-87": return { name: alg };
4816
- default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
4817
- }
4818
- }
4819
- async function getSigKey(alg, key, usage) {
4820
- if (key instanceof Uint8Array) {
4821
- if (!alg.startsWith("HS")) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
4822
- return crypto.subtle.importKey("raw", key, {
4823
- hash: `SHA-${alg.slice(-3)}`,
4824
- name: "HMAC"
4825
- }, false, [usage]);
4826
- }
4827
- checkSigCryptoKey(key, alg, usage);
4828
- return key;
4829
- }
4830
- async function sign(alg, key, data) {
4831
- const cryptoKey = await getSigKey(alg, key, "sign");
4832
- checkKeyLength(alg, cryptoKey);
4833
- const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);
4834
- return new Uint8Array(signature);
4835
- }
4836
- async function verify(alg, key, signature, data) {
4837
- const cryptoKey = await getSigKey(alg, key, "verify");
4838
- checkKeyLength(alg, cryptoKey);
4839
- const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
4840
- try {
4841
- return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
4842
- } catch {
4843
- return false;
4348
+ function err(err) {
4349
+ return new Err(err);
4844
4350
  }
4845
- }
4846
- //#endregion
4847
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/lib/jwk_to_key.js
4848
- const unsupportedAlg = "Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value";
4849
- function subtleMapping(jwk) {
4850
- let algorithm;
4851
- let keyUsages;
4852
- switch (jwk.kty) {
4853
- case "AKP":
4854
- switch (jwk.alg) {
4855
- case "ML-DSA-44":
4856
- case "ML-DSA-65":
4857
- case "ML-DSA-87":
4858
- algorithm = { name: jwk.alg };
4859
- keyUsages = jwk.priv ? ["sign"] : ["verify"];
4860
- break;
4861
- default: throw new JOSENotSupported(unsupportedAlg);
4862
- }
4863
- break;
4864
- case "RSA":
4865
- switch (jwk.alg) {
4866
- case "PS256":
4867
- case "PS384":
4868
- case "PS512":
4869
- algorithm = {
4870
- name: "RSA-PSS",
4871
- hash: `SHA-${jwk.alg.slice(-3)}`
4872
- };
4873
- keyUsages = jwk.d ? ["sign"] : ["verify"];
4874
- break;
4875
- case "RS256":
4876
- case "RS384":
4877
- case "RS512":
4878
- algorithm = {
4879
- name: "RSASSA-PKCS1-v1_5",
4880
- hash: `SHA-${jwk.alg.slice(-3)}`
4881
- };
4882
- keyUsages = jwk.d ? ["sign"] : ["verify"];
4883
- break;
4884
- case "RSA-OAEP":
4885
- case "RSA-OAEP-256":
4886
- case "RSA-OAEP-384":
4887
- case "RSA-OAEP-512":
4888
- algorithm = {
4889
- name: "RSA-OAEP",
4890
- hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
4891
- };
4892
- keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
4893
- break;
4894
- default: throw new JOSENotSupported(unsupportedAlg);
4895
- }
4896
- break;
4897
- case "EC":
4898
- switch (jwk.alg) {
4899
- case "ES256":
4900
- case "ES384":
4901
- case "ES512":
4902
- algorithm = {
4903
- name: "ECDSA",
4904
- namedCurve: {
4905
- ES256: "P-256",
4906
- ES384: "P-384",
4907
- ES512: "P-521"
4908
- }[jwk.alg]
4909
- };
4910
- keyUsages = jwk.d ? ["sign"] : ["verify"];
4911
- break;
4912
- case "ECDH-ES":
4913
- case "ECDH-ES+A128KW":
4914
- case "ECDH-ES+A192KW":
4915
- case "ECDH-ES+A256KW":
4916
- algorithm = {
4917
- name: "ECDH",
4918
- namedCurve: jwk.crv
4919
- };
4920
- keyUsages = jwk.d ? ["deriveBits"] : [];
4921
- break;
4922
- default: throw new JOSENotSupported(unsupportedAlg);
4923
- }
4924
- break;
4925
- case "OKP":
4926
- switch (jwk.alg) {
4927
- case "Ed25519":
4928
- case "EdDSA":
4929
- algorithm = { name: "Ed25519" };
4930
- keyUsages = jwk.d ? ["sign"] : ["verify"];
4931
- break;
4932
- case "ECDH-ES":
4933
- case "ECDH-ES+A128KW":
4934
- case "ECDH-ES+A192KW":
4935
- case "ECDH-ES+A256KW":
4936
- algorithm = { name: jwk.crv };
4937
- keyUsages = jwk.d ? ["deriveBits"] : [];
4938
- break;
4939
- default: throw new JOSENotSupported(unsupportedAlg);
4940
- }
4941
- break;
4942
- default: throw new JOSENotSupported("Invalid or unsupported JWK \"kty\" (Key Type) Parameter value");
4351
+ function safeTry(body) {
4352
+ const n = body().next();
4353
+ if (n instanceof Promise) return new ResultAsync(n.then((r) => r.value));
4354
+ return n.value;
4943
4355
  }
4944
- return {
4945
- algorithm,
4946
- keyUsages
4356
+ var Ok = class {
4357
+ constructor(value) {
4358
+ this.value = value;
4359
+ }
4360
+ isOk() {
4361
+ return true;
4362
+ }
4363
+ isErr() {
4364
+ return !this.isOk();
4365
+ }
4366
+ map(f) {
4367
+ return ok(f(this.value));
4368
+ }
4369
+ mapErr(_f) {
4370
+ return ok(this.value);
4371
+ }
4372
+ andThen(f) {
4373
+ return f(this.value);
4374
+ }
4375
+ andThrough(f) {
4376
+ return f(this.value).map((_value) => this.value);
4377
+ }
4378
+ andTee(f) {
4379
+ try {
4380
+ f(this.value);
4381
+ } catch (e) {}
4382
+ return ok(this.value);
4383
+ }
4384
+ orTee(_f) {
4385
+ return ok(this.value);
4386
+ }
4387
+ orElse(_f) {
4388
+ return ok(this.value);
4389
+ }
4390
+ asyncAndThen(f) {
4391
+ return f(this.value);
4392
+ }
4393
+ asyncAndThrough(f) {
4394
+ return f(this.value).map(() => this.value);
4395
+ }
4396
+ asyncMap(f) {
4397
+ return ResultAsync.fromSafePromise(f(this.value));
4398
+ }
4399
+ unwrapOr(_v) {
4400
+ return this.value;
4401
+ }
4402
+ match(ok, _err) {
4403
+ return ok(this.value);
4404
+ }
4405
+ safeUnwrap() {
4406
+ const value = this.value;
4407
+ return (function* () {
4408
+ return value;
4409
+ })();
4410
+ }
4411
+ _unsafeUnwrap(_) {
4412
+ return this.value;
4413
+ }
4414
+ _unsafeUnwrapErr(config) {
4415
+ throw createNeverThrowError("Called `_unsafeUnwrapErr` on an Ok", this, config);
4416
+ }
4417
+ *[Symbol.iterator]() {
4418
+ return this.value;
4419
+ }
4947
4420
  };
4948
- }
4949
- async function jwkToKey(jwk) {
4950
- if (!jwk.alg) throw new TypeError("\"alg\" argument is required when \"jwk.alg\" is not present");
4951
- const { algorithm, keyUsages } = subtleMapping(jwk);
4952
- const keyData = { ...jwk };
4953
- if (keyData.kty !== "AKP") delete keyData.alg;
4954
- delete keyData.use;
4955
- return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
4956
- }
4957
- //#endregion
4958
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/lib/normalize_key.js
4959
- const unusableForAlg = "given KeyObject instance cannot be used for this algorithm";
4960
- let cache;
4961
- const handleJWK = async (key, jwk, alg, freeze = false) => {
4962
- cache ||= /* @__PURE__ */ new WeakMap();
4963
- let cached = cache.get(key);
4964
- if (cached?.[alg]) return cached[alg];
4965
- const cryptoKey = await jwkToKey({
4966
- ...jwk,
4967
- alg
4968
- });
4969
- if (freeze) Object.freeze(key);
4970
- if (!cached) cache.set(key, { [alg]: cryptoKey });
4971
- else cached[alg] = cryptoKey;
4972
- return cryptoKey;
4973
- };
4974
- const handleKeyObject = (keyObject, alg) => {
4975
- cache ||= /* @__PURE__ */ new WeakMap();
4976
- let cached = cache.get(keyObject);
4977
- if (cached?.[alg]) return cached[alg];
4978
- const isPublic = keyObject.type === "public";
4979
- const extractable = isPublic ? true : false;
4980
- let cryptoKey;
4981
- if (keyObject.asymmetricKeyType === "x25519") {
4982
- switch (alg) {
4983
- case "ECDH-ES":
4984
- case "ECDH-ES+A128KW":
4985
- case "ECDH-ES+A192KW":
4986
- case "ECDH-ES+A256KW": break;
4987
- default: throw new TypeError(unusableForAlg);
4421
+ var Err = class {
4422
+ constructor(error) {
4423
+ this.error = error;
4424
+ }
4425
+ isOk() {
4426
+ return false;
4427
+ }
4428
+ isErr() {
4429
+ return !this.isOk();
4988
4430
  }
4989
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
4990
- }
4991
- if (keyObject.asymmetricKeyType === "ed25519") {
4992
- if (alg !== "EdDSA" && alg !== "Ed25519") throw new TypeError(unusableForAlg);
4993
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
4994
- }
4995
- switch (keyObject.asymmetricKeyType) {
4996
- case "ml-dsa-44":
4997
- case "ml-dsa-65":
4998
- case "ml-dsa-87":
4999
- if (alg !== keyObject.asymmetricKeyType.toUpperCase()) throw new TypeError(unusableForAlg);
5000
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
5001
- }
5002
- if (keyObject.asymmetricKeyType === "rsa") {
5003
- let hash;
5004
- switch (alg) {
5005
- case "RSA-OAEP":
5006
- hash = "SHA-1";
5007
- break;
5008
- case "RS256":
5009
- case "PS256":
5010
- case "RSA-OAEP-256":
5011
- hash = "SHA-256";
5012
- break;
5013
- case "RS384":
5014
- case "PS384":
5015
- case "RSA-OAEP-384":
5016
- hash = "SHA-384";
5017
- break;
5018
- case "RS512":
5019
- case "PS512":
5020
- case "RSA-OAEP-512":
5021
- hash = "SHA-512";
5022
- break;
5023
- default: throw new TypeError(unusableForAlg);
4431
+ map(_f) {
4432
+ return err(this.error);
5024
4433
  }
5025
- if (alg.startsWith("RSA-OAEP")) return keyObject.toCryptoKey({
5026
- name: "RSA-OAEP",
5027
- hash
5028
- }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
5029
- cryptoKey = keyObject.toCryptoKey({
5030
- name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
5031
- hash
5032
- }, extractable, [isPublic ? "verify" : "sign"]);
5033
- }
5034
- if (keyObject.asymmetricKeyType === "ec") {
5035
- const namedCurve = new Map([
5036
- ["prime256v1", "P-256"],
5037
- ["secp384r1", "P-384"],
5038
- ["secp521r1", "P-521"]
5039
- ]).get(keyObject.asymmetricKeyDetails?.namedCurve);
5040
- if (!namedCurve) throw new TypeError(unusableForAlg);
5041
- const expectedCurve = {
5042
- ES256: "P-256",
5043
- ES384: "P-384",
5044
- ES512: "P-521"
5045
- };
5046
- if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) cryptoKey = keyObject.toCryptoKey({
5047
- name: "ECDSA",
5048
- namedCurve
5049
- }, extractable, [isPublic ? "verify" : "sign"]);
5050
- if (alg.startsWith("ECDH-ES")) cryptoKey = keyObject.toCryptoKey({
5051
- name: "ECDH",
5052
- namedCurve
5053
- }, extractable, isPublic ? [] : ["deriveBits"]);
5054
- }
5055
- if (!cryptoKey) throw new TypeError(unusableForAlg);
5056
- if (!cached) cache.set(keyObject, { [alg]: cryptoKey });
5057
- else cached[alg] = cryptoKey;
5058
- return cryptoKey;
5059
- };
5060
- async function normalizeKey(key, alg) {
5061
- if (key instanceof Uint8Array) return key;
5062
- if (isCryptoKey(key)) return key;
5063
- if (isKeyObject(key)) {
5064
- if (key.type === "secret") return key.export();
5065
- if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") try {
5066
- return handleKeyObject(key, alg);
5067
- } catch (err) {
5068
- if (err instanceof TypeError) throw err;
4434
+ mapErr(f) {
4435
+ return err(f(this.error));
5069
4436
  }
5070
- return handleJWK(key, key.export({ format: "jwk" }), alg);
5071
- }
5072
- if (isJWK(key)) {
5073
- if (key.k) return decode(key.k);
5074
- return handleJWK(key, key, alg, true);
5075
- }
5076
- throw new Error("unreachable");
5077
- }
5078
- //#endregion
5079
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/lib/validate_crit.js
5080
- function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
5081
- if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected");
5082
- if (!protectedHeader || protectedHeader.crit === void 0) return /* @__PURE__ */ new Set();
5083
- if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) throw new Err("\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present");
5084
- let recognized;
5085
- if (recognizedOption !== void 0) recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
5086
- else recognized = recognizedDefault;
5087
- for (const parameter of protectedHeader.crit) {
5088
- if (!recognized.has(parameter)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
5089
- if (joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
5090
- if (recognized.get(parameter) && protectedHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
5091
- }
5092
- return new Set(protectedHeader.crit);
5093
- }
5094
- //#endregion
5095
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/lib/validate_algorithms.js
5096
- function validateAlgorithms(option, algorithms) {
5097
- if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) throw new TypeError(`"${option}" option must be an array of strings`);
5098
- if (!algorithms) return;
5099
- return new Set(algorithms);
5100
- }
5101
- //#endregion
5102
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/lib/check_key_type.js
5103
- const tag = (key) => key?.[Symbol.toStringTag];
5104
- const jwkMatchesOp = (alg, key, usage) => {
5105
- if (key.use !== void 0) {
5106
- let expected;
5107
- switch (usage) {
5108
- case "sign":
5109
- case "verify":
5110
- expected = "sig";
5111
- break;
5112
- case "encrypt":
5113
- case "decrypt":
5114
- expected = "enc";
5115
- break;
4437
+ andThrough(_f) {
4438
+ return err(this.error);
5116
4439
  }
5117
- if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
5118
- }
5119
- if (key.alg !== void 0 && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
5120
- if (Array.isArray(key.key_ops)) {
5121
- let expectedKeyOp;
5122
- switch (true) {
5123
- case usage === "sign" || usage === "verify":
5124
- case alg === "dir":
5125
- case alg.includes("CBC-HS"):
5126
- expectedKeyOp = usage;
5127
- break;
5128
- case alg.startsWith("PBES2"):
5129
- expectedKeyOp = "deriveBits";
5130
- break;
5131
- case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
5132
- if (!alg.includes("GCM") && alg.endsWith("KW")) expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
5133
- else expectedKeyOp = usage;
5134
- break;
5135
- case usage === "encrypt" && alg.startsWith("RSA"):
5136
- expectedKeyOp = "wrapKey";
5137
- break;
5138
- case usage === "decrypt":
5139
- expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
5140
- break;
4440
+ andTee(_f) {
4441
+ return err(this.error);
5141
4442
  }
5142
- if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
5143
- }
5144
- return true;
5145
- };
5146
- const symmetricTypeCheck = (alg, key, usage) => {
5147
- if (key instanceof Uint8Array) return;
5148
- if (isJWK(key)) {
5149
- if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return;
5150
- throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
5151
- }
5152
- if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
5153
- if (key.type !== "secret") throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
5154
- };
5155
- const asymmetricTypeCheck = (alg, key, usage) => {
5156
- if (isJWK(key)) switch (usage) {
5157
- case "decrypt":
5158
- case "sign":
5159
- if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return;
5160
- throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
5161
- case "encrypt":
5162
- case "verify":
5163
- if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return;
5164
- throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
5165
- }
5166
- if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
5167
- if (key.type === "secret") throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
5168
- if (key.type === "public") switch (usage) {
5169
- case "sign": throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
5170
- case "decrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
5171
- }
5172
- if (key.type === "private") switch (usage) {
5173
- case "verify": throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
5174
- case "encrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
5175
- }
5176
- };
5177
- function checkKeyType(alg, key, usage) {
5178
- switch (alg.substring(0, 2)) {
5179
- case "A1":
5180
- case "A2":
5181
- case "di":
5182
- case "HS":
5183
- case "PB":
5184
- symmetricTypeCheck(alg, key, usage);
5185
- break;
5186
- default: asymmetricTypeCheck(alg, key, usage);
5187
- }
5188
- }
5189
- //#endregion
5190
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/jws/flattened/verify.js
5191
- async function flattenedVerify(jws, key, options) {
5192
- if (!isObject(jws)) throw new JWSInvalid("Flattened JWS must be an object");
5193
- if (jws.protected === void 0 && jws.header === void 0) throw new JWSInvalid("Flattened JWS must have either of the \"protected\" or \"header\" members");
5194
- if (jws.protected !== void 0 && typeof jws.protected !== "string") throw new JWSInvalid("JWS Protected Header incorrect type");
5195
- if (jws.payload === void 0) throw new JWSInvalid("JWS Payload missing");
5196
- if (typeof jws.signature !== "string") throw new JWSInvalid("JWS Signature missing or incorrect type");
5197
- if (jws.header !== void 0 && !isObject(jws.header)) throw new JWSInvalid("JWS Unprotected Header incorrect type");
5198
- let parsedProt = {};
5199
- if (jws.protected) try {
5200
- const protectedHeader = decode(jws.protected);
5201
- parsedProt = JSON.parse(decoder.decode(protectedHeader));
5202
- } catch {
5203
- throw new JWSInvalid("JWS Protected Header is invalid");
5204
- }
5205
- if (!isDisjoint(parsedProt, jws.header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
5206
- const joseHeader = {
5207
- ...parsedProt,
5208
- ...jws.header
5209
- };
5210
- const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
5211
- let b64 = true;
5212
- if (extensions.has("b64")) {
5213
- b64 = parsedProt.b64;
5214
- if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
5215
- }
5216
- const { alg } = joseHeader;
5217
- if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
5218
- const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
5219
- if (algorithms && !algorithms.has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed");
5220
- if (b64) {
5221
- if (typeof jws.payload !== "string") throw new JWSInvalid("JWS Payload must be a string");
5222
- } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
5223
- let resolvedKey = false;
5224
- if (typeof key === "function") {
5225
- key = await key(parsedProt, jws);
5226
- resolvedKey = true;
5227
- }
5228
- checkKeyType(alg, key, "verify");
5229
- const data = concat(jws.protected !== void 0 ? encode$1(jws.protected) : new Uint8Array(), encode$1("."), typeof jws.payload === "string" ? b64 ? encode$1(jws.payload) : encoder.encode(jws.payload) : jws.payload);
5230
- const signature = decodeBase64url(jws.signature, "signature", JWSInvalid);
5231
- const k = await normalizeKey(key, alg);
5232
- if (!await verify(alg, k, signature, data)) throw new JWSSignatureVerificationFailed();
5233
- let payload;
5234
- if (b64) payload = decodeBase64url(jws.payload, "payload", JWSInvalid);
5235
- else if (typeof jws.payload === "string") payload = encoder.encode(jws.payload);
5236
- else payload = jws.payload;
5237
- const result = { payload };
5238
- if (jws.protected !== void 0) result.protectedHeader = parsedProt;
5239
- if (jws.header !== void 0) result.unprotectedHeader = jws.header;
5240
- if (resolvedKey) return {
5241
- ...result,
5242
- key: k
5243
- };
5244
- return result;
5245
- }
5246
- //#endregion
5247
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/jws/compact/verify.js
5248
- async function compactVerify(jws, key, options) {
5249
- if (jws instanceof Uint8Array) jws = decoder.decode(jws);
5250
- if (typeof jws !== "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
5251
- const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
5252
- if (length !== 3) throw new JWSInvalid("Invalid Compact JWS");
5253
- const verified = await flattenedVerify({
5254
- payload,
5255
- protected: protectedHeader,
5256
- signature
5257
- }, key, options);
5258
- const result = {
5259
- payload: verified.payload,
5260
- protectedHeader: verified.protectedHeader
5261
- };
5262
- if (typeof key === "function") return {
5263
- ...result,
5264
- key: verified.key
5265
- };
5266
- return result;
5267
- }
5268
- //#endregion
5269
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/lib/jwt_claims_set.js
5270
- const epoch = (date) => Math.floor(date.getTime() / 1e3);
5271
- const minute = 60;
5272
- const hour = minute * 60;
5273
- const day = hour * 24;
5274
- const week = day * 7;
5275
- const year = day * 365.25;
5276
- const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
5277
- function secs(str) {
5278
- const matched = REGEX.exec(str);
5279
- if (!matched || matched[4] && matched[1]) throw new TypeError("Invalid time period format");
5280
- const value = parseFloat(matched[2]);
5281
- const unit = matched[3].toLowerCase();
5282
- let numericDate;
5283
- switch (unit) {
5284
- case "sec":
5285
- case "secs":
5286
- case "second":
5287
- case "seconds":
5288
- case "s":
5289
- numericDate = Math.round(value);
5290
- break;
5291
- case "minute":
5292
- case "minutes":
5293
- case "min":
5294
- case "mins":
5295
- case "m":
5296
- numericDate = Math.round(value * minute);
5297
- break;
5298
- case "hour":
5299
- case "hours":
5300
- case "hr":
5301
- case "hrs":
5302
- case "h":
5303
- numericDate = Math.round(value * hour);
5304
- break;
5305
- case "day":
5306
- case "days":
5307
- case "d":
5308
- numericDate = Math.round(value * day);
5309
- break;
5310
- case "week":
5311
- case "weeks":
5312
- case "w":
5313
- numericDate = Math.round(value * week);
5314
- break;
5315
- default:
5316
- numericDate = Math.round(value * year);
5317
- break;
5318
- }
5319
- if (matched[1] === "-" || matched[4] === "ago") return -numericDate;
5320
- return numericDate;
5321
- }
5322
- function validateInput(label, input) {
5323
- if (!Number.isFinite(input)) throw new TypeError(`Invalid ${label} input`);
5324
- return input;
5325
- }
5326
- const normalizeTyp = (value) => {
5327
- if (value.includes("/")) return value.toLowerCase();
5328
- return `application/${value.toLowerCase()}`;
5329
- };
5330
- const checkAudiencePresence = (audPayload, audOption) => {
5331
- if (typeof audPayload === "string") return audOption.includes(audPayload);
5332
- if (Array.isArray(audPayload)) return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
5333
- return false;
5334
- };
5335
- function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
5336
- let payload;
5337
- try {
5338
- payload = JSON.parse(decoder.decode(encodedPayload));
5339
- } catch {}
5340
- if (!isObject(payload)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
5341
- const { typ } = options;
5342
- if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", payload, "typ", "check_failed");
5343
- const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
5344
- const presenceCheck = [...requiredClaims];
5345
- if (maxTokenAge !== void 0) presenceCheck.push("iat");
5346
- if (audience !== void 0) presenceCheck.push("aud");
5347
- if (subject !== void 0) presenceCheck.push("sub");
5348
- if (issuer !== void 0) presenceCheck.push("iss");
5349
- for (const claim of new Set(presenceCheck.reverse())) if (!(claim in payload)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
5350
- if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) throw new JWTClaimValidationFailed("unexpected \"iss\" claim value", payload, "iss", "check_failed");
5351
- if (subject && payload.sub !== subject) throw new JWTClaimValidationFailed("unexpected \"sub\" claim value", payload, "sub", "check_failed");
5352
- if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) throw new JWTClaimValidationFailed("unexpected \"aud\" claim value", payload, "aud", "check_failed");
5353
- let tolerance;
5354
- switch (typeof options.clockTolerance) {
5355
- case "string":
5356
- tolerance = secs(options.clockTolerance);
5357
- break;
5358
- case "number":
5359
- tolerance = options.clockTolerance;
5360
- break;
5361
- case "undefined":
5362
- tolerance = 0;
5363
- break;
5364
- default: throw new TypeError("Invalid clockTolerance option type");
5365
- }
5366
- const { currentDate } = options;
5367
- const now = epoch(currentDate || /* @__PURE__ */ new Date());
5368
- if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") throw new JWTClaimValidationFailed("\"iat\" claim must be a number", payload, "iat", "invalid");
5369
- if (payload.nbf !== void 0) {
5370
- if (typeof payload.nbf !== "number") throw new JWTClaimValidationFailed("\"nbf\" claim must be a number", payload, "nbf", "invalid");
5371
- if (payload.nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", payload, "nbf", "check_failed");
5372
- }
5373
- if (payload.exp !== void 0) {
5374
- if (typeof payload.exp !== "number") throw new JWTClaimValidationFailed("\"exp\" claim must be a number", payload, "exp", "invalid");
5375
- if (payload.exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", payload, "exp", "check_failed");
5376
- }
5377
- if (maxTokenAge) {
5378
- const age = now - payload.iat;
5379
- const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
5380
- if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", payload, "iat", "check_failed");
5381
- if (age < 0 - tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", payload, "iat", "check_failed");
5382
- }
5383
- return payload;
5384
- }
5385
- var JWTClaimsBuilder = class {
5386
- #payload;
5387
- constructor(payload) {
5388
- if (!isObject(payload)) throw new TypeError("JWT Claims Set MUST be an object");
5389
- this.#payload = structuredClone(payload);
5390
- }
5391
- data() {
5392
- return encoder.encode(JSON.stringify(this.#payload));
5393
- }
5394
- get iss() {
5395
- return this.#payload.iss;
5396
- }
5397
- set iss(value) {
5398
- this.#payload.iss = value;
5399
- }
5400
- get sub() {
5401
- return this.#payload.sub;
5402
- }
5403
- set sub(value) {
5404
- this.#payload.sub = value;
5405
- }
5406
- get aud() {
5407
- return this.#payload.aud;
5408
- }
5409
- set aud(value) {
5410
- this.#payload.aud = value;
5411
- }
5412
- set jti(value) {
5413
- this.#payload.jti = value;
5414
- }
5415
- set nbf(value) {
5416
- if (typeof value === "number") this.#payload.nbf = validateInput("setNotBefore", value);
5417
- else if (value instanceof Date) this.#payload.nbf = validateInput("setNotBefore", epoch(value));
5418
- else this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value);
5419
- }
5420
- set exp(value) {
5421
- if (typeof value === "number") this.#payload.exp = validateInput("setExpirationTime", value);
5422
- else if (value instanceof Date) this.#payload.exp = validateInput("setExpirationTime", epoch(value));
5423
- else this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value);
5424
- }
5425
- set iat(value) {
5426
- if (value === void 0) this.#payload.iat = epoch(/* @__PURE__ */ new Date());
5427
- else if (value instanceof Date) this.#payload.iat = validateInput("setIssuedAt", epoch(value));
5428
- else if (typeof value === "string") this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value));
5429
- else this.#payload.iat = validateInput("setIssuedAt", value);
5430
- }
5431
- };
5432
- //#endregion
5433
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/jwt/verify.js
5434
- async function jwtVerify(jwt, key, options) {
5435
- const verified = await compactVerify(jwt, key, options);
5436
- if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
5437
- const result = {
5438
- payload: validateClaimsSet(verified.protectedHeader, verified.payload, options),
5439
- protectedHeader: verified.protectedHeader
5440
- };
5441
- if (typeof key === "function") return {
5442
- ...result,
5443
- key: verified.key
5444
- };
5445
- return result;
5446
- }
5447
- //#endregion
5448
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/jws/flattened/sign.js
5449
- var FlattenedSign = class {
5450
- #payload;
5451
- #protectedHeader;
5452
- #unprotectedHeader;
5453
- constructor(payload) {
5454
- if (!(payload instanceof Uint8Array)) throw new TypeError("payload must be an instance of Uint8Array");
5455
- this.#payload = payload;
5456
- }
5457
- setProtectedHeader(protectedHeader) {
5458
- assertNotSet(this.#protectedHeader, "setProtectedHeader");
5459
- this.#protectedHeader = protectedHeader;
5460
- return this;
5461
- }
5462
- setUnprotectedHeader(unprotectedHeader) {
5463
- assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader");
5464
- this.#unprotectedHeader = unprotectedHeader;
5465
- return this;
5466
- }
5467
- async sign(key, options) {
5468
- if (!this.#protectedHeader && !this.#unprotectedHeader) throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
5469
- if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
5470
- const joseHeader = {
5471
- ...this.#protectedHeader,
5472
- ...this.#unprotectedHeader
5473
- };
5474
- const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader);
5475
- let b64 = true;
5476
- if (extensions.has("b64")) {
5477
- b64 = this.#protectedHeader.b64;
5478
- if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
4443
+ orTee(f) {
4444
+ try {
4445
+ f(this.error);
4446
+ } catch (e) {}
4447
+ return err(this.error);
5479
4448
  }
5480
- const { alg } = joseHeader;
5481
- if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
5482
- checkKeyType(alg, key, "sign");
5483
- let payloadS;
5484
- let payloadB;
5485
- if (b64) {
5486
- payloadS = encode(this.#payload);
5487
- payloadB = encode$1(payloadS);
5488
- } else {
5489
- payloadB = this.#payload;
5490
- payloadS = "";
4449
+ andThen(_f) {
4450
+ return err(this.error);
5491
4451
  }
5492
- let protectedHeaderString;
5493
- let protectedHeaderBytes;
5494
- if (this.#protectedHeader) {
5495
- protectedHeaderString = encode(JSON.stringify(this.#protectedHeader));
5496
- protectedHeaderBytes = encode$1(protectedHeaderString);
5497
- } else {
5498
- protectedHeaderString = "";
5499
- protectedHeaderBytes = new Uint8Array();
4452
+ orElse(f) {
4453
+ return f(this.error);
5500
4454
  }
5501
- const data = concat(protectedHeaderBytes, encode$1("."), payloadB);
5502
- const jws = {
5503
- signature: encode(await sign(alg, await normalizeKey(key, alg), data)),
5504
- payload: payloadS
5505
- };
5506
- if (this.#unprotectedHeader) jws.header = this.#unprotectedHeader;
5507
- if (this.#protectedHeader) jws.protected = protectedHeaderString;
5508
- return jws;
5509
- }
5510
- };
5511
- //#endregion
5512
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/jws/compact/sign.js
5513
- var CompactSign = class {
5514
- #flattened;
5515
- constructor(payload) {
5516
- this.#flattened = new FlattenedSign(payload);
5517
- }
5518
- setProtectedHeader(protectedHeader) {
5519
- this.#flattened.setProtectedHeader(protectedHeader);
5520
- return this;
5521
- }
5522
- async sign(key, options) {
5523
- const jws = await this.#flattened.sign(key, options);
5524
- if (jws.payload === void 0) throw new TypeError("use the flattened module for creating JWS with b64: false");
5525
- return `${jws.protected}.${jws.payload}.${jws.signature}`;
5526
- }
5527
- };
5528
- //#endregion
5529
- //#region node_modules/.pnpm/jose@6.2.1/node_modules/jose/dist/webapi/jwt/sign.js
5530
- var SignJWT = class {
5531
- #protectedHeader;
5532
- #jwt;
5533
- constructor(payload = {}) {
5534
- this.#jwt = new JWTClaimsBuilder(payload);
5535
- }
5536
- setIssuer(issuer) {
5537
- this.#jwt.iss = issuer;
5538
- return this;
5539
- }
5540
- setSubject(subject) {
5541
- this.#jwt.sub = subject;
5542
- return this;
5543
- }
5544
- setAudience(audience) {
5545
- this.#jwt.aud = audience;
5546
- return this;
5547
- }
5548
- setJti(jwtId) {
5549
- this.#jwt.jti = jwtId;
5550
- return this;
5551
- }
5552
- setNotBefore(input) {
5553
- this.#jwt.nbf = input;
5554
- return this;
5555
- }
5556
- setExpirationTime(input) {
5557
- this.#jwt.exp = input;
5558
- return this;
5559
- }
5560
- setIssuedAt(input) {
5561
- this.#jwt.iat = input;
5562
- return this;
5563
- }
5564
- setProtectedHeader(protectedHeader) {
5565
- this.#protectedHeader = protectedHeader;
5566
- return this;
5567
- }
5568
- async sign(key, options) {
5569
- const sig = new CompactSign(this.#jwt.data());
5570
- sig.setProtectedHeader(this.#protectedHeader);
5571
- if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
5572
- return sig.sign(key, options);
5573
- }
5574
- };
5575
- //#endregion
5576
- //#region src/core/session.ts
5577
- /**
5578
- * Creates a signed JWT containing the given session payload.
5579
- *
5580
- * @param secret - The secret key used to sign the JWT.
5581
- * @param payload - The session data to embed in the token.
5582
- * @param expiresIn - How long until the token expires (e.g., `"30d"`), or `null` for the default (`"30d"`).
5583
- * @returns The signed JWT string.
5584
- */
5585
- async function createSessionJwt(secret, payload, expiresIn = null) {
5586
- const key = new TextEncoder().encode(secret);
5587
- return new SignJWT({ ...payload }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(expiresIn ?? "30d").sign(key);
5588
- }
5589
- /**
5590
- * Verifies a session JWT and returns the validated session payload.
5591
- *
5592
- * @param secret - The secret key used to verify the JWT signature.
5593
- * @param token - The JWT string to verify.
5594
- * @returns A {@link Result} containing the validated {@link SessionPayload}, or a {@link SessionVerifyError}.
5595
- */
5596
- async function verifySessionJwt(secret, token) {
5597
- const key = new TextEncoder().encode(secret);
5598
- let payload;
5599
- try {
5600
- payload = (await jwtVerify(token, key)).payload;
5601
- } catch (e) {
5602
- return (0, import_index_cjs.err)({
5603
- code: "JWT_VERIFY_FAILED",
5604
- message: e instanceof Error ? e.message : "JWT verification failed"
5605
- });
5606
- }
5607
- const parsed = SessionPayloadSchema.safeParse(payload);
5608
- if (!parsed.success) return (0, import_index_cjs.err)({
5609
- code: "SESSION_VALIDATION_ERROR",
5610
- message: parsed.error.message
5611
- });
5612
- return (0, import_index_cjs.ok)(parsed.data);
5613
- }
5614
- //#endregion
5615
- //#region src/core/embedded.ts
5616
- const AUTHORIZE_ON_BEHALF_PATH = "/api/v1/app-integrations/authorize-on-behalf";
5617
- const SESSION_TOKEN_QUERY_PARAM = "token";
5618
- const THEME_QUERY_PARAM = "theme";
5619
- /**
5620
- * Extracts the embedded session token from a URL.
5621
- *
5622
- * When Fanvue opens an embedded app, it loads the app's embed URL with a
5623
- * short-lived session token appended as a `?token=` query parameter.
5624
- *
5625
- * @param url - The URL to read the token from (e.g. `window.location.href`).
5626
- * @returns The session token, or `null` when absent or the URL is malformed.
5627
- */
5628
- function getSessionTokenFromUrl(url) {
5629
- let parsed;
5630
- try {
5631
- parsed = new URL(url);
5632
- } catch {
5633
- return null;
5634
- }
5635
- const token = parsed.searchParams.get(SESSION_TOKEN_QUERY_PARAM);
5636
- return token !== null && token.length > 0 ? token : null;
5637
- }
5638
- /**
5639
- * Extracts the creator's active colour scheme from a URL.
5640
- *
5641
- * When Fanvue opens an embedded app, it appends the creator's resolved colour
5642
- * scheme as a `?theme=` query parameter (`light` or `dark`), letting the app
5643
- * theme-match Fanvue.
5644
- *
5645
- * @param url - The URL to read the theme from (e.g. `window.location.href`).
5646
- * @returns The {@link FanvueTheme}, or `null` when absent, unrecognised, or the
5647
- * URL is malformed (e.g. the app was opened outside Fanvue).
5648
- */
5649
- function getThemeFromUrl(url) {
5650
- let parsed;
5651
- try {
5652
- parsed = new URL(url);
5653
- } catch {
5654
- return null;
5655
- }
5656
- const theme = parsed.searchParams.get(THEME_QUERY_PARAM);
5657
- return theme === "light" || theme === "dark" ? theme : null;
5658
- }
5659
- /**
5660
- * Requests an authorization code from the Fanvue platform on behalf of the
5661
- * creator currently using the embedded app.
5662
- *
5663
- * This is the "authorize" half of the delegated flow: the platform verifies
5664
- * the session token, runs the OAuth authorize as the creator, and returns the
5665
- * resulting authorization code. The PKCE verifier and client secret never
5666
- * leave the caller — only the challenge is sent.
5667
- *
5668
- * Most apps should use {@link exchangeSessionToken}, which composes this with
5669
- * the code exchange.
5670
- *
5671
- * @param config - The embedded auth configuration.
5672
- * @param sessionToken - The short-lived session token received in the iframe.
5673
- * @param opts - The PKCE code challenge and state to bind the code to.
5674
- * @returns A `Result` containing the authorization code on success or
5675
- * {@link EmbeddedAuthError} on failure.
5676
- */
5677
- async function requestAuthorizationCodeOnBehalf(config, sessionToken, opts) {
5678
- const platformUrl = config.platformUrl ?? "https://www.fanvue.com";
5679
- let response;
5680
- try {
5681
- response = await fetch(`${platformUrl}${AUTHORIZE_ON_BEHALF_PATH}`, {
5682
- method: "POST",
5683
- headers: {
5684
- "Content-Type": "application/json",
5685
- Authorization: `Bearer ${sessionToken}`
5686
- },
5687
- body: JSON.stringify({
5688
- code_challenge: opts.codeChallenge,
5689
- code_challenge_method: "S256",
5690
- state: opts.state
5691
- })
5692
- });
5693
- } catch (error) {
5694
- return (0, import_index_cjs.err)({
5695
- code: "AUTHORIZE_ON_BEHALF_FAILED",
5696
- statusCode: 0,
5697
- message: `Network error during authorize-on-behalf: ${error instanceof Error ? error.message : String(error)}`
5698
- });
5699
- }
5700
- if (response.status === 401) return (0, import_index_cjs.err)({
5701
- code: "SESSION_TOKEN_REJECTED",
5702
- statusCode: response.status,
5703
- message: "The platform rejected the session token. Session tokens expire after ~60 seconds — reopen the embedded surface to receive a fresh one."
5704
- });
5705
- if (response.status === 403) return (0, import_index_cjs.err)({
5706
- code: "CONSENT_REQUIRED",
5707
- statusCode: response.status,
5708
- message: "The creator has not approved (or has revoked) consent for this app. Consent is granted on the Fanvue consent screen when the surface is opened."
5709
- });
5710
- if (!response.ok) return (0, import_index_cjs.err)({
5711
- code: "AUTHORIZE_ON_BEHALF_FAILED",
5712
- statusCode: response.status,
5713
- message: `authorize-on-behalf failed: ${response.status} ${response.statusText}`
5714
- });
5715
- const parseResult = safeJsonParse(await response.text());
5716
- if (parseResult.isErr()) {
5717
- const { rawText, message } = parseResult.error;
5718
- return (0, import_index_cjs.err)({
5719
- code: "EMBEDDED_JSON_PARSE_ERROR",
5720
- rawText,
5721
- message
5722
- });
5723
- }
5724
- const validated = AuthorizeOnBehalfResponseSchema.safeParse(parseResult.value);
5725
- if (!validated.success) return (0, import_index_cjs.err)({
5726
- code: "EMBEDDED_VALIDATION_ERROR",
5727
- message: validated.error.message
5728
- });
5729
- if (validated.data.state !== opts.state) return (0, import_index_cjs.err)({
5730
- code: "AUTHORIZE_STATE_MISMATCH",
5731
- message: "authorize-on-behalf returned a different state than was sent."
5732
- });
5733
- return (0, import_index_cjs.ok)({ code: validated.data.code });
5734
- }
5735
- /**
5736
- * Exchanges an embedded session token for OAuth access and refresh tokens.
5737
- *
5738
- * Runs the complete delegated authorize-on-behalf flow:
5739
- *
5740
- * 1. Generates a PKCE verifier/challenge pair and a random `state`.
5741
- * 2. Asks the Fanvue platform to authorize as the creator
5742
- * ({@link requestAuthorizationCodeOnBehalf}).
5743
- * 3. Exchanges the returned code at the token endpoint using the client
5744
- * secret and PKCE verifier.
5745
- *
5746
- * Must run server-side: it uses the client secret. The session token should
5747
- * be used promptly — it expires after ~60 seconds.
5748
- *
5749
- * @param config - The embedded auth configuration. `redirectUri` must be a
5750
- * redirect URI registered on the OAuth client (it is never visited; it only
5751
- * binds the authorization code).
5752
- * @param sessionToken - The short-lived session token received in the iframe.
5753
- * @returns A `Result` containing {@link TokenResponse} on success or an
5754
- * {@link EmbeddedAuthError} / {@link OAuthError} on failure.
5755
- */
5756
- async function exchangeSessionToken(config, sessionToken) {
5757
- const codeVerifier = generateRandomCodeVerifier();
5758
- const codeResult = await requestAuthorizationCodeOnBehalf(config, sessionToken, {
5759
- codeChallenge: await calculatePKCECodeChallenge(codeVerifier),
5760
- state: generateRandomState()
5761
- });
5762
- if (codeResult.isErr()) return (0, import_index_cjs.err)(codeResult.error);
5763
- return exchangeCodeForToken(config, {
5764
- code: codeResult.value.code,
5765
- codeVerifier,
5766
- redirectUri: null
5767
- });
5768
- }
5769
- //#endregion
5770
- //#region src/core/client.ts
5771
- /**
5772
- * Creates a new {@link FanvueClient} for making authenticated requests to the Fanvue API.
5773
- *
5774
- * @param accessToken - The OAuth access token to authenticate requests.
5775
- * @param apiBaseUrl - The base URL for the Fanvue API, or `null` to use the default.
5776
- * @returns A {@link FanvueClient} instance.
5777
- */
5778
- function createFanvueClient(accessToken, apiBaseUrl) {
5779
- if (apiBaseUrl != null) assertFanvueDomain(apiBaseUrl);
5780
- const baseUrl = apiBaseUrl ?? "https://api.fanvue.com";
5781
- async function fetchApi(path) {
5782
- let response;
5783
- try {
5784
- response = await fetch(`${baseUrl}${path}`, { headers: {
5785
- Authorization: `Bearer ${accessToken}`,
5786
- "X-Fanvue-API-Version": API_VERSION
5787
- } });
5788
- } catch (error) {
5789
- return (0, import_index_cjs.err)({
5790
- code: "API_REQUEST_FAILED",
5791
- statusCode: 0,
5792
- message: `Network error: ${error instanceof Error ? error.message : String(error)}`
5793
- });
4455
+ asyncAndThen(_f) {
4456
+ return errAsync(this.error);
5794
4457
  }
5795
- if (!response.ok) return (0, import_index_cjs.err)({
5796
- code: "API_REQUEST_FAILED",
5797
- statusCode: response.status,
5798
- message: `API request failed: ${response.status} ${response.statusText}`
5799
- });
5800
- const parseResult = safeJsonParse(await response.text());
5801
- if (parseResult.isErr()) {
5802
- const { rawText, message } = parseResult.error;
5803
- return (0, import_index_cjs.err)({
5804
- code: "API_JSON_PARSE_ERROR",
5805
- rawText,
5806
- message
5807
- });
4458
+ asyncAndThrough(_f) {
4459
+ return errAsync(this.error);
5808
4460
  }
5809
- return (0, import_index_cjs.ok)(parseResult.value);
5810
- }
5811
- async function getCurrentUser() {
5812
- const result = await fetchApi("/users/me");
5813
- if (result.isErr()) return (0, import_index_cjs.err)(result.error);
5814
- const validated = FanvueUserSchema.safeParse(result.value);
5815
- if (!validated.success) return (0, import_index_cjs.err)({
5816
- code: "API_VALIDATION_ERROR",
5817
- message: validated.error.message
5818
- });
5819
- return (0, import_index_cjs.ok)(validated.data);
5820
- }
5821
- return { getCurrentUser };
5822
- }
4461
+ asyncMap(_f) {
4462
+ return errAsync(this.error);
4463
+ }
4464
+ unwrapOr(v) {
4465
+ return v;
4466
+ }
4467
+ match(_ok, err) {
4468
+ return err(this.error);
4469
+ }
4470
+ safeUnwrap() {
4471
+ const error = this.error;
4472
+ return (function* () {
4473
+ yield err(error);
4474
+ throw new Error("Do not use this generator out of `safeTry`");
4475
+ })();
4476
+ }
4477
+ _unsafeUnwrap(config) {
4478
+ throw createNeverThrowError("Called `_unsafeUnwrap` on an Err", this, config);
4479
+ }
4480
+ _unsafeUnwrapErr(_) {
4481
+ return this.error;
4482
+ }
4483
+ *[Symbol.iterator]() {
4484
+ const self = this;
4485
+ yield self;
4486
+ return self;
4487
+ }
4488
+ };
4489
+ const fromThrowable = exports.Result.fromThrowable;
4490
+ exports.Err = Err;
4491
+ exports.Ok = Ok;
4492
+ exports.ResultAsync = ResultAsync;
4493
+ exports.err = err;
4494
+ exports.errAsync = errAsync;
4495
+ exports.fromAsyncThrowable = fromAsyncThrowable;
4496
+ exports.fromPromise = fromPromise;
4497
+ exports.fromSafePromise = fromSafePromise;
4498
+ exports.fromThrowable = fromThrowable;
4499
+ exports.ok = ok;
4500
+ exports.okAsync = okAsync;
4501
+ exports.safeTry = safeTry;
4502
+ }));
5823
4503
  //#endregion
5824
- export { assertFanvueDomain as C, DEFAULT_SCOPES as S, HEADER_UPDATED_SESSION as T, safeJsonParse as _, requestAuthorizationCodeOnBehalf as a, DEFAULT_ISSUER_URL as b, createAuthorizationUrl as c, AuthorizeOnBehalfResponseSchema as d, FanvueUserSchema as f, string as g, object as h, getThemeFromUrl as i, exchangeCodeForToken as l, TokenResponseSchema as m, exchangeSessionToken as n, createSessionJwt as o, SessionPayloadSchema as p, getSessionTokenFromUrl as r, verifySessionJwt as s, createFanvueClient as t, refreshAccessToken as u, API_VERSION as v, BEARER_PREFIX as w, DEFAULT_PLATFORM_URL as x, DEFAULT_API_BASE_URL as y };
4504
+ export { discriminatedUnion as a, number as c, record as d, string as f, prettifyError as g, url as h, boolean as i, object as l, unknown as m, _enum as n, literal as o, union as p, array as r, looseObject as s, require_index_cjs as t, preprocess as u };
5825
4505
 
5826
- //# sourceMappingURL=core-CvVOMyqr.js.map
4506
+ //# sourceMappingURL=index.cjs-teGsk6HB.js.map