@stdout-design/cli 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,3246 +1,10 @@
1
1
  #!/usr/bin/env bun
2
- import { createRequire } from "node:module";
3
- import { Command } from "commander";
4
- import { AppError, ErrorCode, importTemplateForBatch, loadConfig, openCache, runBatch, zodToJsonSchemaShape } from "@stdout-design/core";
5
- import path from "node:path";
6
- import { execSync, spawnSync } from "node:child_process";
7
- import { existsSync, readFileSync } from "node:fs";
8
- import { resolveCommand } from "package-manager-detector/commands";
9
- import { detect } from "package-manager-detector/detect";
10
- import { cp, mkdir, writeFile } from "node:fs/promises";
11
- import { pathToFileURL } from "node:url";
12
- //#region src/lib/display.ts
13
- const formatBytes = (bytes) => {
14
- if (bytes < 1024) return `${bytes} B`;
15
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
16
- if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
17
- return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
18
- };
19
- const formatCacheStats = (stats) => {
20
- return [
21
- "",
22
- "Cache Statistics",
23
- "━━━━━━━━━━━━━━━━",
24
- ` Location: ${stats.cacheDir}`,
25
- ` Compiled: ${stats.compiled.entries} entries (in-memory compile cache)`,
26
- ` Pixel: ${stats.pixels.entries} entries`,
27
- ` Disk used: ${formatBytes(stats.pixels.sizeBytes)}`,
28
- ` Disk limit: ${formatBytes(stats.pixels.maxSizeBytes)}`,
29
- ""
30
- ].join("\n");
31
- };
32
- const formatManifestSummary = (manifest) => {
33
- const { completedCount, totalCount, succeeded, failed } = manifest;
34
- const cacheHits = succeeded.filter((s) => s.cacheHit).length;
35
- const lines = [
36
- "",
37
- "Batch Render Complete",
38
- "━━━━━━━━━━━━━━━━━━━━",
39
- ` Status: ${manifest.status}`,
40
- ` Total: ${totalCount}`,
41
- ` Completed: ${completedCount}`,
42
- ` Cache: ${cacheHits} hits, ${succeeded.length - cacheHits} renders`,
43
- ` Failed: ${failed.length}`,
44
- ""
45
- ];
46
- if (succeeded.length > 0 && succeeded.length <= 10) {
47
- lines.push("Output files:");
48
- for (const entry of succeeded) lines.push(` ${entry.outputPath}`);
49
- lines.push("");
50
- }
51
- if (failed.length > 0) {
52
- lines.push("Failures:");
53
- for (const f of failed) lines.push(` Row ${f.rowIndex}, ${f.locale}, ${f.preset}: ${f.error}`);
54
- lines.push("");
55
- }
56
- return lines.join("\n");
57
- };
58
- const formatError$1 = (error) => {
59
- if (error instanceof Error) return `Error: ${error.message}`;
60
- return `Error: ${String(error)}`;
61
- };
62
- const formatCacheCleanResult = (freedBytes) => `Cache cleared. Freed ${formatBytes(freedBytes)}.`;
63
- //#endregion
64
- //#region src/commands/cache.ts
65
- const cacheStats = async (rootDir, options) => {
66
- const cache = await openCache(rootDir ?? process.cwd());
67
- const stats = await cache.stats();
68
- cache.close();
69
- if (options.json) console.log(JSON.stringify(stats, null, 2));
70
- else console.log(formatCacheStats(stats));
71
- };
72
- const cacheClean = async (rootDir, options) => {
73
- const cache = await openCache(rootDir ?? process.cwd());
74
- const result = await cache.clean();
75
- cache.close();
76
- if (options.json) console.log(JSON.stringify(result));
77
- else console.log(formatCacheCleanResult(result.freedBytes));
78
- };
79
- //#endregion
80
- //#region src/commands/dev.ts
81
- const findWebUiDist = () => {
82
- try {
83
- const pkgJsonPath = createRequire(import.meta.url).resolve("@stdout-design/web-ui/package.json");
84
- const pkgDir = path.dirname(pkgJsonPath);
85
- return path.join(pkgDir, "dist");
86
- } catch {}
87
- };
88
- const dev = async (rootDir, options) => {
89
- const { startStandaloneServer } = await import("@stdout-design/dev-server").catch(() => {
90
- throw new Error([
91
- "studio dev requires a scaffolded project with @stdout-design/dev-server installed.",
92
- "Run `studio init` to create one, or install it manually:",
93
- "",
94
- " bun add @stdout-design/dev-server",
95
- "",
96
- "See https://stdout.design/docs for more information."
97
- ].join("\n"));
98
- });
99
- const resolvedRoot = rootDir ?? process.cwd();
100
- const port = Number(options.port ?? "3000");
101
- const webUiDist = findWebUiDist();
102
- console.log(`Starting studio dev server for ${resolvedRoot}...`);
103
- await startStandaloneServer({
104
- port,
105
- rootDir: resolvedRoot,
106
- webUiDist
107
- });
108
- };
109
- //#endregion
110
- //#region src/commands/init/git.ts
111
- const isInsideGitRepo = (dir) => {
112
- let current = path.resolve(dir);
113
- for (;;) {
114
- if (existsSync(path.join(current, ".git"))) return true;
115
- const parent = path.dirname(current);
116
- if (parent === current) break;
117
- current = parent;
118
- }
119
- return false;
120
- };
121
- const tryGitInit = (dir) => {
122
- try {
123
- execSync("git --version", { stdio: "ignore" });
124
- } catch {
125
- return false;
126
- }
127
- if (existsSync(path.join(dir, ".git")) || isInsideGitRepo(path.dirname(dir))) return false;
128
- try {
129
- execSync("git init", {
130
- cwd: dir,
131
- stdio: "ignore"
132
- });
133
- execSync("git checkout -b main", {
134
- cwd: dir,
135
- stdio: "ignore"
136
- });
137
- execSync("git add .", {
138
- cwd: dir,
139
- stdio: "ignore"
140
- });
141
- execSync("git commit -m \"Initial commit from stdout-design\"", {
142
- cwd: dir,
143
- stdio: "ignore"
144
- });
145
- return true;
146
- } catch {
147
- if (existsSync(path.join(dir, ".git"))) try {
148
- execSync("rm -rf .git", {
149
- cwd: dir,
150
- stdio: "ignore"
151
- });
152
- } catch {}
153
- return false;
154
- }
155
- };
156
- //#endregion
157
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/core.js
158
- var _a$1;
159
- function $constructor(name, initializer, params) {
160
- function init(inst, def) {
161
- if (!inst._zod) Object.defineProperty(inst, "_zod", {
162
- value: {
163
- def,
164
- constr: _,
165
- traits: /* @__PURE__ */ new Set()
166
- },
167
- enumerable: false
168
- });
169
- if (inst._zod.traits.has(name)) return;
170
- inst._zod.traits.add(name);
171
- initializer(inst, def);
172
- const proto = _.prototype;
173
- const keys = Object.keys(proto);
174
- for (let i = 0; i < keys.length; i++) {
175
- const k = keys[i];
176
- if (!(k in inst)) inst[k] = proto[k].bind(inst);
177
- }
178
- }
179
- const Parent = params?.Parent ?? Object;
180
- class Definition extends Parent {}
181
- Object.defineProperty(Definition, "name", { value: name });
182
- function _(def) {
183
- var _a;
184
- const inst = params?.Parent ? new Definition() : this;
185
- init(inst, def);
186
- (_a = inst._zod).deferred ?? (_a.deferred = []);
187
- for (const fn of inst._zod.deferred) fn();
188
- return inst;
189
- }
190
- Object.defineProperty(_, "init", { value: init });
191
- Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => {
192
- if (params?.Parent && inst instanceof params.Parent) return true;
193
- return inst?._zod?.traits?.has(name);
194
- } });
195
- Object.defineProperty(_, "name", { value: name });
196
- return _;
197
- }
198
- var $ZodAsyncError = class extends Error {
199
- constructor() {
200
- super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
201
- }
202
- };
203
- var $ZodEncodeError = class extends Error {
204
- constructor(name) {
205
- super(`Encountered unidirectional transform during encode: ${name}`);
206
- this.name = "ZodEncodeError";
207
- }
208
- };
209
- (_a$1 = globalThis).__zod_globalConfig ?? (_a$1.__zod_globalConfig = {});
210
- const globalConfig = globalThis.__zod_globalConfig;
211
- function config(newConfig) {
212
- if (newConfig) Object.assign(globalConfig, newConfig);
213
- return globalConfig;
214
- }
215
- //#endregion
216
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/util.js
217
- function jsonStringifyReplacer(_, value) {
218
- if (typeof value === "bigint") return value.toString();
219
- return value;
220
- }
221
- function nullish(input) {
222
- return input === null || input === void 0;
223
- }
224
- function cleanRegex(source) {
225
- const start = source.startsWith("^") ? 1 : 0;
226
- const end = source.endsWith("$") ? source.length - 1 : source.length;
227
- return source.slice(start, end);
228
- }
229
- const EVALUATING = /* @__PURE__*/ Symbol("evaluating");
230
- function defineLazy(object, key, getter) {
231
- let value = void 0;
232
- Object.defineProperty(object, key, {
233
- get() {
234
- if (value === EVALUATING) return;
235
- if (value === void 0) {
236
- value = EVALUATING;
237
- value = getter();
238
- }
239
- return value;
240
- },
241
- set(v) {
242
- Object.defineProperty(object, key, { value: v });
243
- },
244
- configurable: true
245
- });
246
- }
247
- function mergeDefs(...defs) {
248
- const mergedDescriptors = {};
249
- for (const def of defs) {
250
- const descriptors = Object.getOwnPropertyDescriptors(def);
251
- Object.assign(mergedDescriptors, descriptors);
252
- }
253
- return Object.defineProperties({}, mergedDescriptors);
254
- }
255
- function slugify(input) {
256
- return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
257
- }
258
- const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
259
- function isObject(data) {
260
- return typeof data === "object" && data !== null && !Array.isArray(data);
261
- }
262
- function isPlainObject(o) {
263
- if (isObject(o) === false) return false;
264
- const ctor = o.constructor;
265
- if (ctor === void 0) return true;
266
- if (typeof ctor !== "function") return true;
267
- const prot = ctor.prototype;
268
- if (isObject(prot) === false) return false;
269
- if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
270
- return true;
271
- }
272
- function shallowClone(o) {
273
- if (isPlainObject(o)) return { ...o };
274
- if (Array.isArray(o)) return [...o];
275
- if (o instanceof Map) return new Map(o);
276
- if (o instanceof Set) return new Set(o);
277
- return o;
278
- }
279
- function escapeRegex(str) {
280
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
281
- }
282
- function clone(inst, def, params) {
283
- const cl = new inst._zod.constr(def ?? inst._zod.def);
284
- if (!def || params?.parent) cl._zod.parent = inst;
285
- return cl;
286
- }
287
- function normalizeParams(_params) {
288
- const params = _params;
289
- if (!params) return {};
290
- if (typeof params === "string") return { error: () => params };
291
- if (params?.message !== void 0) {
292
- if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params");
293
- params.error = params.message;
294
- }
295
- delete params.message;
296
- if (typeof params.error === "string") return {
297
- ...params,
298
- error: () => params.error
299
- };
300
- return params;
301
- }
302
- Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, -Number.MAX_VALUE, Number.MAX_VALUE;
303
- function aborted(x, startIndex = 0) {
304
- if (x.aborted === true) return true;
305
- for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;
306
- return false;
307
- }
308
- function explicitlyAborted(x, startIndex = 0) {
309
- if (x.aborted === true) return true;
310
- for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue === false) return true;
311
- return false;
312
- }
313
- function prefixIssues(path, issues) {
314
- return issues.map((iss) => {
315
- var _a;
316
- (_a = iss).path ?? (_a.path = []);
317
- iss.path.unshift(path);
318
- return iss;
319
- });
320
- }
321
- function unwrapMessage(message) {
322
- return typeof message === "string" ? message : message?.message;
323
- }
324
- function finalizeIssue(iss, ctx, config) {
325
- const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
326
- const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
327
- rest.path ?? (rest.path = []);
328
- rest.message = message;
329
- if (ctx?.reportInput) rest.input = _input;
330
- return rest;
331
- }
332
- function getLengthableOrigin(input) {
333
- if (Array.isArray(input)) return "array";
334
- if (typeof input === "string") return "string";
335
- return "unknown";
336
- }
337
- function issue(...args) {
338
- const [iss, input, inst] = args;
339
- if (typeof iss === "string") return {
340
- message: iss,
341
- code: "custom",
342
- input,
343
- inst
344
- };
345
- return { ...iss };
346
- }
347
- //#endregion
348
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/errors.js
349
- const initializer$1 = (inst, def) => {
350
- inst.name = "$ZodError";
351
- Object.defineProperty(inst, "_zod", {
352
- value: inst._zod,
353
- enumerable: false
354
- });
355
- Object.defineProperty(inst, "issues", {
356
- value: def,
357
- enumerable: false
358
- });
359
- inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
360
- Object.defineProperty(inst, "toString", {
361
- value: () => inst.message,
362
- enumerable: false
363
- });
364
- };
365
- const $ZodError = $constructor("$ZodError", initializer$1);
366
- const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
367
- function flattenError(error, mapper = (issue) => issue.message) {
368
- const fieldErrors = {};
369
- const formErrors = [];
370
- for (const sub of error.issues) if (sub.path.length > 0) {
371
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
372
- fieldErrors[sub.path[0]].push(mapper(sub));
373
- } else formErrors.push(mapper(sub));
374
- return {
375
- formErrors,
376
- fieldErrors
377
- };
378
- }
379
- function formatError(error, mapper = (issue) => issue.message) {
380
- const fieldErrors = { _errors: [] };
381
- const processError = (error, path = []) => {
382
- for (const issue of error.issues) if (issue.code === "invalid_union" && issue.errors.length) issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
383
- else if (issue.code === "invalid_key") processError({ issues: issue.issues }, [...path, ...issue.path]);
384
- else if (issue.code === "invalid_element") processError({ issues: issue.issues }, [...path, ...issue.path]);
385
- else {
386
- const fullpath = [...path, ...issue.path];
387
- if (fullpath.length === 0) fieldErrors._errors.push(mapper(issue));
388
- else {
389
- let curr = fieldErrors;
390
- let i = 0;
391
- while (i < fullpath.length) {
392
- const el = fullpath[i];
393
- if (!(i === fullpath.length - 1)) curr[el] = curr[el] || { _errors: [] };
394
- else {
395
- curr[el] = curr[el] || { _errors: [] };
396
- curr[el]._errors.push(mapper(issue));
397
- }
398
- curr = curr[el];
399
- i++;
400
- }
401
- }
402
- }
403
- };
404
- processError(error);
405
- return fieldErrors;
406
- }
407
- //#endregion
408
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/parse.js
409
- const _parse = (_Err) => (schema, value, _ctx, _params) => {
410
- const ctx = _ctx ? {
411
- ..._ctx,
412
- async: false
413
- } : { async: false };
414
- const result = schema._zod.run({
415
- value,
416
- issues: []
417
- }, ctx);
418
- if (result instanceof Promise) throw new $ZodAsyncError();
419
- if (result.issues.length) {
420
- const e = new ((_params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
421
- captureStackTrace(e, _params?.callee);
422
- throw e;
423
- }
424
- return result.value;
425
- };
426
- const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
427
- const ctx = _ctx ? {
428
- ..._ctx,
429
- async: true
430
- } : { async: true };
431
- let result = schema._zod.run({
432
- value,
433
- issues: []
434
- }, ctx);
435
- if (result instanceof Promise) result = await result;
436
- if (result.issues.length) {
437
- const e = new ((params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
438
- captureStackTrace(e, params?.callee);
439
- throw e;
440
- }
441
- return result.value;
442
- };
443
- const _safeParse = (_Err) => (schema, value, _ctx) => {
444
- const ctx = _ctx ? {
445
- ..._ctx,
446
- async: false
447
- } : { async: false };
448
- const result = schema._zod.run({
449
- value,
450
- issues: []
451
- }, ctx);
452
- if (result instanceof Promise) throw new $ZodAsyncError();
453
- return result.issues.length ? {
454
- success: false,
455
- error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
456
- } : {
457
- success: true,
458
- data: result.value
459
- };
460
- };
461
- const safeParse$1 = /* @__PURE__*/ _safeParse($ZodRealError);
462
- const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
463
- const ctx = _ctx ? {
464
- ..._ctx,
465
- async: true
466
- } : { async: true };
467
- let result = schema._zod.run({
468
- value,
469
- issues: []
470
- }, ctx);
471
- if (result instanceof Promise) result = await result;
472
- return result.issues.length ? {
473
- success: false,
474
- error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
475
- } : {
476
- success: true,
477
- data: result.value
478
- };
479
- };
480
- const safeParseAsync$1 = /* @__PURE__*/ _safeParseAsync($ZodRealError);
481
- const _encode = (_Err) => (schema, value, _ctx) => {
482
- const ctx = _ctx ? {
483
- ..._ctx,
484
- direction: "backward"
485
- } : { direction: "backward" };
486
- return _parse(_Err)(schema, value, ctx);
487
- };
488
- const _decode = (_Err) => (schema, value, _ctx) => {
489
- return _parse(_Err)(schema, value, _ctx);
490
- };
491
- const _encodeAsync = (_Err) => async (schema, value, _ctx) => {
492
- const ctx = _ctx ? {
493
- ..._ctx,
494
- direction: "backward"
495
- } : { direction: "backward" };
496
- return _parseAsync(_Err)(schema, value, ctx);
497
- };
498
- const _decodeAsync = (_Err) => async (schema, value, _ctx) => {
499
- return _parseAsync(_Err)(schema, value, _ctx);
500
- };
501
- const _safeEncode = (_Err) => (schema, value, _ctx) => {
502
- const ctx = _ctx ? {
503
- ..._ctx,
504
- direction: "backward"
505
- } : { direction: "backward" };
506
- return _safeParse(_Err)(schema, value, ctx);
507
- };
508
- const _safeDecode = (_Err) => (schema, value, _ctx) => {
509
- return _safeParse(_Err)(schema, value, _ctx);
510
- };
511
- const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
512
- const ctx = _ctx ? {
513
- ..._ctx,
514
- direction: "backward"
515
- } : { direction: "backward" };
516
- return _safeParseAsync(_Err)(schema, value, ctx);
517
- };
518
- const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
519
- return _safeParseAsync(_Err)(schema, value, _ctx);
520
- };
521
- //#endregion
522
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/regexes.js
523
- /**
524
- * @deprecated CUID v1 is deprecated by its authors due to information leakage
525
- * (timestamps embedded in the id). Use {@link cuid2} instead.
526
- * See https://github.com/paralleldrive/cuid.
527
- */
528
- const cuid = /^[cC][0-9a-z]{6,}$/;
529
- const cuid2 = /^[0-9a-z]+$/;
530
- const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
531
- const xid = /^[0-9a-vA-V]{20}$/;
532
- const ksuid = /^[A-Za-z0-9]{27}$/;
533
- const nanoid = /^[a-zA-Z0-9_-]{21}$/;
534
- /** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
535
- 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)?)?)$/;
536
- /** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
537
- 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})$/;
538
- /** Returns a regex for validating an RFC 9562/4122 UUID.
539
- *
540
- * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
541
- const uuid = (version) => {
542
- 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)$/;
543
- 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})$`);
544
- };
545
- /** Practical email validation */
546
- const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
547
- const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
548
- function emoji() {
549
- return new RegExp(_emoji$1, "u");
550
- }
551
- 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])$/;
552
- 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}|:))$/;
553
- 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])$/;
554
- 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])$/;
555
- const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
556
- const base64url = /^[A-Za-z0-9_-]*$/;
557
- const httpProtocol = /^https?$/;
558
- const e164 = /^\+[1-9]\d{6,14}$/;
559
- 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])))`;
560
- const date$1 = /*@__PURE__*/ new RegExp(`^${dateSource}$`);
561
- function timeSource(args) {
562
- const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
563
- 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+)?)?`;
564
- }
565
- function time$1(args) {
566
- return new RegExp(`^${timeSource(args)}$`);
567
- }
568
- function datetime$1(args) {
569
- const time = timeSource({ precision: args.precision });
570
- const opts = ["Z"];
571
- if (args.local) opts.push("");
572
- if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
573
- const timeRegex = `${time}(?:${opts.join("|")})`;
574
- return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
575
- }
576
- const string$1 = (params) => {
577
- const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
578
- return new RegExp(`^${regex}$`);
579
- };
580
- const lowercase = /^[^A-Z]*$/;
581
- const uppercase = /^[^a-z]*$/;
582
- //#endregion
583
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/checks.js
584
- const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => {
585
- var _a;
586
- inst._zod ?? (inst._zod = {});
587
- inst._zod.def = def;
588
- (_a = inst._zod).onattach ?? (_a.onattach = []);
589
- });
590
- const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => {
591
- var _a;
592
- $ZodCheck.init(inst, def);
593
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
594
- const val = payload.value;
595
- return !nullish(val) && val.length !== void 0;
596
- });
597
- inst._zod.onattach.push((inst) => {
598
- const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
599
- if (def.maximum < curr) inst._zod.bag.maximum = def.maximum;
600
- });
601
- inst._zod.check = (payload) => {
602
- const input = payload.value;
603
- if (input.length <= def.maximum) return;
604
- const origin = getLengthableOrigin(input);
605
- payload.issues.push({
606
- origin,
607
- code: "too_big",
608
- maximum: def.maximum,
609
- inclusive: true,
610
- input,
611
- inst,
612
- continue: !def.abort
613
- });
614
- };
615
- });
616
- const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => {
617
- var _a;
618
- $ZodCheck.init(inst, def);
619
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
620
- const val = payload.value;
621
- return !nullish(val) && val.length !== void 0;
622
- });
623
- inst._zod.onattach.push((inst) => {
624
- const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
625
- if (def.minimum > curr) inst._zod.bag.minimum = def.minimum;
626
- });
627
- inst._zod.check = (payload) => {
628
- const input = payload.value;
629
- if (input.length >= def.minimum) return;
630
- const origin = getLengthableOrigin(input);
631
- payload.issues.push({
632
- origin,
633
- code: "too_small",
634
- minimum: def.minimum,
635
- inclusive: true,
636
- input,
637
- inst,
638
- continue: !def.abort
639
- });
640
- };
641
- });
642
- const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => {
643
- var _a;
644
- $ZodCheck.init(inst, def);
645
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
646
- const val = payload.value;
647
- return !nullish(val) && val.length !== void 0;
648
- });
649
- inst._zod.onattach.push((inst) => {
650
- const bag = inst._zod.bag;
651
- bag.minimum = def.length;
652
- bag.maximum = def.length;
653
- bag.length = def.length;
654
- });
655
- inst._zod.check = (payload) => {
656
- const input = payload.value;
657
- const length = input.length;
658
- if (length === def.length) return;
659
- const origin = getLengthableOrigin(input);
660
- const tooBig = length > def.length;
661
- payload.issues.push({
662
- origin,
663
- ...tooBig ? {
664
- code: "too_big",
665
- maximum: def.length
666
- } : {
667
- code: "too_small",
668
- minimum: def.length
669
- },
670
- inclusive: true,
671
- exact: true,
672
- input: payload.value,
673
- inst,
674
- continue: !def.abort
675
- });
676
- };
677
- });
678
- const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => {
679
- var _a, _b;
680
- $ZodCheck.init(inst, def);
681
- inst._zod.onattach.push((inst) => {
682
- const bag = inst._zod.bag;
683
- bag.format = def.format;
684
- if (def.pattern) {
685
- bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
686
- bag.patterns.add(def.pattern);
687
- }
688
- });
689
- if (def.pattern) (_a = inst._zod).check ?? (_a.check = (payload) => {
690
- def.pattern.lastIndex = 0;
691
- if (def.pattern.test(payload.value)) return;
692
- payload.issues.push({
693
- origin: "string",
694
- code: "invalid_format",
695
- format: def.format,
696
- input: payload.value,
697
- ...def.pattern ? { pattern: def.pattern.toString() } : {},
698
- inst,
699
- continue: !def.abort
700
- });
701
- });
702
- else (_b = inst._zod).check ?? (_b.check = () => {});
703
- });
704
- const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => {
705
- $ZodCheckStringFormat.init(inst, def);
706
- inst._zod.check = (payload) => {
707
- def.pattern.lastIndex = 0;
708
- if (def.pattern.test(payload.value)) return;
709
- payload.issues.push({
710
- origin: "string",
711
- code: "invalid_format",
712
- format: "regex",
713
- input: payload.value,
714
- pattern: def.pattern.toString(),
715
- inst,
716
- continue: !def.abort
717
- });
718
- };
719
- });
720
- const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => {
721
- def.pattern ?? (def.pattern = lowercase);
722
- $ZodCheckStringFormat.init(inst, def);
723
- });
724
- const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => {
725
- def.pattern ?? (def.pattern = uppercase);
726
- $ZodCheckStringFormat.init(inst, def);
727
- });
728
- const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => {
729
- $ZodCheck.init(inst, def);
730
- const escapedRegex = escapeRegex(def.includes);
731
- const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
732
- def.pattern = pattern;
733
- inst._zod.onattach.push((inst) => {
734
- const bag = inst._zod.bag;
735
- bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
736
- bag.patterns.add(pattern);
737
- });
738
- inst._zod.check = (payload) => {
739
- if (payload.value.includes(def.includes, def.position)) return;
740
- payload.issues.push({
741
- origin: "string",
742
- code: "invalid_format",
743
- format: "includes",
744
- includes: def.includes,
745
- input: payload.value,
746
- inst,
747
- continue: !def.abort
748
- });
749
- };
750
- });
751
- const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => {
752
- $ZodCheck.init(inst, def);
753
- const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
754
- def.pattern ?? (def.pattern = pattern);
755
- inst._zod.onattach.push((inst) => {
756
- const bag = inst._zod.bag;
757
- bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
758
- bag.patterns.add(pattern);
759
- });
760
- inst._zod.check = (payload) => {
761
- if (payload.value.startsWith(def.prefix)) return;
762
- payload.issues.push({
763
- origin: "string",
764
- code: "invalid_format",
765
- format: "starts_with",
766
- prefix: def.prefix,
767
- input: payload.value,
768
- inst,
769
- continue: !def.abort
770
- });
771
- };
772
- });
773
- const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => {
774
- $ZodCheck.init(inst, def);
775
- const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
776
- def.pattern ?? (def.pattern = pattern);
777
- inst._zod.onattach.push((inst) => {
778
- const bag = inst._zod.bag;
779
- bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
780
- bag.patterns.add(pattern);
781
- });
782
- inst._zod.check = (payload) => {
783
- if (payload.value.endsWith(def.suffix)) return;
784
- payload.issues.push({
785
- origin: "string",
786
- code: "invalid_format",
787
- format: "ends_with",
788
- suffix: def.suffix,
789
- input: payload.value,
790
- inst,
791
- continue: !def.abort
792
- });
793
- };
794
- });
795
- const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => {
796
- $ZodCheck.init(inst, def);
797
- inst._zod.check = (payload) => {
798
- payload.value = def.tx(payload.value);
799
- };
800
- });
801
- //#endregion
802
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/versions.js
803
- const version = {
804
- major: 4,
805
- minor: 4,
806
- patch: 3
807
- };
808
- //#endregion
809
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/schemas.js
810
- const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
811
- var _a;
812
- inst ?? (inst = {});
813
- inst._zod.def = def;
814
- inst._zod.bag = inst._zod.bag || {};
815
- inst._zod.version = version;
816
- const checks = [...inst._zod.def.checks ?? []];
817
- if (inst._zod.traits.has("$ZodCheck")) checks.unshift(inst);
818
- for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst);
819
- if (checks.length === 0) {
820
- (_a = inst._zod).deferred ?? (_a.deferred = []);
821
- inst._zod.deferred?.push(() => {
822
- inst._zod.run = inst._zod.parse;
823
- });
824
- } else {
825
- const runChecks = (payload, checks, ctx) => {
826
- let isAborted = aborted(payload);
827
- let asyncResult;
828
- for (const ch of checks) {
829
- if (ch._zod.def.when) {
830
- if (explicitlyAborted(payload)) continue;
831
- if (!ch._zod.def.when(payload)) continue;
832
- } else if (isAborted) continue;
833
- const currLen = payload.issues.length;
834
- const _ = ch._zod.check(payload);
835
- if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError();
836
- if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
837
- await _;
838
- if (payload.issues.length === currLen) return;
839
- if (!isAborted) isAborted = aborted(payload, currLen);
840
- });
841
- else {
842
- if (payload.issues.length === currLen) continue;
843
- if (!isAborted) isAborted = aborted(payload, currLen);
844
- }
845
- }
846
- if (asyncResult) return asyncResult.then(() => {
847
- return payload;
848
- });
849
- return payload;
850
- };
851
- const handleCanaryResult = (canary, payload, ctx) => {
852
- if (aborted(canary)) {
853
- canary.aborted = true;
854
- return canary;
855
- }
856
- const checkResult = runChecks(payload, checks, ctx);
857
- if (checkResult instanceof Promise) {
858
- if (ctx.async === false) throw new $ZodAsyncError();
859
- return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
860
- }
861
- return inst._zod.parse(checkResult, ctx);
862
- };
863
- inst._zod.run = (payload, ctx) => {
864
- if (ctx.skipChecks) return inst._zod.parse(payload, ctx);
865
- if (ctx.direction === "backward") {
866
- const canary = inst._zod.parse({
867
- value: payload.value,
868
- issues: []
869
- }, {
870
- ...ctx,
871
- skipChecks: true
872
- });
873
- if (canary instanceof Promise) return canary.then((canary) => {
874
- return handleCanaryResult(canary, payload, ctx);
875
- });
876
- return handleCanaryResult(canary, payload, ctx);
877
- }
878
- const result = inst._zod.parse(payload, ctx);
879
- if (result instanceof Promise) {
880
- if (ctx.async === false) throw new $ZodAsyncError();
881
- return result.then((result) => runChecks(result, checks, ctx));
882
- }
883
- return runChecks(result, checks, ctx);
884
- };
885
- }
886
- defineLazy(inst, "~standard", () => ({
887
- validate: (value) => {
888
- try {
889
- const r = safeParse$1(inst, value);
890
- return r.success ? { value: r.data } : { issues: r.error?.issues };
891
- } catch (_) {
892
- return safeParseAsync$1(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
893
- }
894
- },
895
- vendor: "zod",
896
- version: 1
897
- }));
898
- });
899
- const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => {
900
- $ZodType.init(inst, def);
901
- inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string$1(inst._zod.bag);
902
- inst._zod.parse = (payload, _) => {
903
- if (def.coerce) try {
904
- payload.value = String(payload.value);
905
- } catch (_) {}
906
- if (typeof payload.value === "string") return payload;
907
- payload.issues.push({
908
- expected: "string",
909
- code: "invalid_type",
910
- input: payload.value,
911
- inst
912
- });
913
- return payload;
914
- };
915
- });
916
- const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => {
917
- $ZodCheckStringFormat.init(inst, def);
918
- $ZodString.init(inst, def);
919
- });
920
- const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => {
921
- def.pattern ?? (def.pattern = guid);
922
- $ZodStringFormat.init(inst, def);
923
- });
924
- const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => {
925
- if (def.version) {
926
- const v = {
927
- v1: 1,
928
- v2: 2,
929
- v3: 3,
930
- v4: 4,
931
- v5: 5,
932
- v6: 6,
933
- v7: 7,
934
- v8: 8
935
- }[def.version];
936
- if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`);
937
- def.pattern ?? (def.pattern = uuid(v));
938
- } else def.pattern ?? (def.pattern = uuid());
939
- $ZodStringFormat.init(inst, def);
940
- });
941
- const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => {
942
- def.pattern ?? (def.pattern = email);
943
- $ZodStringFormat.init(inst, def);
944
- });
945
- const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => {
946
- $ZodStringFormat.init(inst, def);
947
- inst._zod.check = (payload) => {
948
- try {
949
- const trimmed = payload.value.trim();
950
- if (!def.normalize && def.protocol?.source === httpProtocol.source) {
951
- if (!/^https?:\/\//i.test(trimmed)) {
952
- payload.issues.push({
953
- code: "invalid_format",
954
- format: "url",
955
- note: "Invalid URL format",
956
- input: payload.value,
957
- inst,
958
- continue: !def.abort
959
- });
960
- return;
961
- }
962
- }
963
- const url = new URL(trimmed);
964
- if (def.hostname) {
965
- def.hostname.lastIndex = 0;
966
- if (!def.hostname.test(url.hostname)) payload.issues.push({
967
- code: "invalid_format",
968
- format: "url",
969
- note: "Invalid hostname",
970
- pattern: def.hostname.source,
971
- input: payload.value,
972
- inst,
973
- continue: !def.abort
974
- });
975
- }
976
- if (def.protocol) {
977
- def.protocol.lastIndex = 0;
978
- if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) payload.issues.push({
979
- code: "invalid_format",
980
- format: "url",
981
- note: "Invalid protocol",
982
- pattern: def.protocol.source,
983
- input: payload.value,
984
- inst,
985
- continue: !def.abort
986
- });
987
- }
988
- if (def.normalize) payload.value = url.href;
989
- else payload.value = trimmed;
990
- return;
991
- } catch (_) {
992
- payload.issues.push({
993
- code: "invalid_format",
994
- format: "url",
995
- input: payload.value,
996
- inst,
997
- continue: !def.abort
998
- });
999
- }
1000
- };
1001
- });
1002
- const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => {
1003
- def.pattern ?? (def.pattern = emoji());
1004
- $ZodStringFormat.init(inst, def);
1005
- });
1006
- const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => {
1007
- def.pattern ?? (def.pattern = nanoid);
1008
- $ZodStringFormat.init(inst, def);
1009
- });
1010
- /**
1011
- * @deprecated CUID v1 is deprecated by its authors due to information leakage
1012
- * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.
1013
- * See https://github.com/paralleldrive/cuid.
1014
- */
1015
- const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => {
1016
- def.pattern ?? (def.pattern = cuid);
1017
- $ZodStringFormat.init(inst, def);
1018
- });
1019
- const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => {
1020
- def.pattern ?? (def.pattern = cuid2);
1021
- $ZodStringFormat.init(inst, def);
1022
- });
1023
- const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => {
1024
- def.pattern ?? (def.pattern = ulid);
1025
- $ZodStringFormat.init(inst, def);
1026
- });
1027
- const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => {
1028
- def.pattern ?? (def.pattern = xid);
1029
- $ZodStringFormat.init(inst, def);
1030
- });
1031
- const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => {
1032
- def.pattern ?? (def.pattern = ksuid);
1033
- $ZodStringFormat.init(inst, def);
1034
- });
1035
- const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => {
1036
- def.pattern ?? (def.pattern = datetime$1(def));
1037
- $ZodStringFormat.init(inst, def);
1038
- });
1039
- const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => {
1040
- def.pattern ?? (def.pattern = date$1);
1041
- $ZodStringFormat.init(inst, def);
1042
- });
1043
- const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => {
1044
- def.pattern ?? (def.pattern = time$1(def));
1045
- $ZodStringFormat.init(inst, def);
1046
- });
1047
- const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => {
1048
- def.pattern ?? (def.pattern = duration$1);
1049
- $ZodStringFormat.init(inst, def);
1050
- });
1051
- const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => {
1052
- def.pattern ?? (def.pattern = ipv4);
1053
- $ZodStringFormat.init(inst, def);
1054
- inst._zod.bag.format = `ipv4`;
1055
- });
1056
- const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => {
1057
- def.pattern ?? (def.pattern = ipv6);
1058
- $ZodStringFormat.init(inst, def);
1059
- inst._zod.bag.format = `ipv6`;
1060
- inst._zod.check = (payload) => {
1061
- try {
1062
- new URL(`http://[${payload.value}]`);
1063
- } catch {
1064
- payload.issues.push({
1065
- code: "invalid_format",
1066
- format: "ipv6",
1067
- input: payload.value,
1068
- inst,
1069
- continue: !def.abort
1070
- });
1071
- }
1072
- };
1073
- });
1074
- const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => {
1075
- def.pattern ?? (def.pattern = cidrv4);
1076
- $ZodStringFormat.init(inst, def);
1077
- });
1078
- const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => {
1079
- def.pattern ?? (def.pattern = cidrv6);
1080
- $ZodStringFormat.init(inst, def);
1081
- inst._zod.check = (payload) => {
1082
- const parts = payload.value.split("/");
1083
- try {
1084
- if (parts.length !== 2) throw new Error();
1085
- const [address, prefix] = parts;
1086
- if (!prefix) throw new Error();
1087
- const prefixNum = Number(prefix);
1088
- if (`${prefixNum}` !== prefix) throw new Error();
1089
- if (prefixNum < 0 || prefixNum > 128) throw new Error();
1090
- new URL(`http://[${address}]`);
1091
- } catch {
1092
- payload.issues.push({
1093
- code: "invalid_format",
1094
- format: "cidrv6",
1095
- input: payload.value,
1096
- inst,
1097
- continue: !def.abort
1098
- });
1099
- }
1100
- };
1101
- });
1102
- function isValidBase64(data) {
1103
- if (data === "") return true;
1104
- if (/\s/.test(data)) return false;
1105
- if (data.length % 4 !== 0) return false;
1106
- try {
1107
- atob(data);
1108
- return true;
1109
- } catch {
1110
- return false;
1111
- }
1112
- }
1113
- const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => {
1114
- def.pattern ?? (def.pattern = base64);
1115
- $ZodStringFormat.init(inst, def);
1116
- inst._zod.bag.contentEncoding = "base64";
1117
- inst._zod.check = (payload) => {
1118
- if (isValidBase64(payload.value)) return;
1119
- payload.issues.push({
1120
- code: "invalid_format",
1121
- format: "base64",
1122
- input: payload.value,
1123
- inst,
1124
- continue: !def.abort
1125
- });
1126
- };
1127
- });
1128
- function isValidBase64URL(data) {
1129
- if (!base64url.test(data)) return false;
1130
- const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
1131
- return isValidBase64(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
1132
- }
1133
- const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => {
1134
- def.pattern ?? (def.pattern = base64url);
1135
- $ZodStringFormat.init(inst, def);
1136
- inst._zod.bag.contentEncoding = "base64url";
1137
- inst._zod.check = (payload) => {
1138
- if (isValidBase64URL(payload.value)) return;
1139
- payload.issues.push({
1140
- code: "invalid_format",
1141
- format: "base64url",
1142
- input: payload.value,
1143
- inst,
1144
- continue: !def.abort
1145
- });
1146
- };
1147
- });
1148
- const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => {
1149
- def.pattern ?? (def.pattern = e164);
1150
- $ZodStringFormat.init(inst, def);
1151
- });
1152
- function isValidJWT(token, algorithm = null) {
1153
- try {
1154
- const tokensParts = token.split(".");
1155
- if (tokensParts.length !== 3) return false;
1156
- const [header] = tokensParts;
1157
- if (!header) return false;
1158
- const parsedHeader = JSON.parse(atob(header));
1159
- if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false;
1160
- if (!parsedHeader.alg) return false;
1161
- if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false;
1162
- return true;
1163
- } catch {
1164
- return false;
1165
- }
1166
- }
1167
- const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => {
1168
- $ZodStringFormat.init(inst, def);
1169
- inst._zod.check = (payload) => {
1170
- if (isValidJWT(payload.value, def.alg)) return;
1171
- payload.issues.push({
1172
- code: "invalid_format",
1173
- format: "jwt",
1174
- input: payload.value,
1175
- inst,
1176
- continue: !def.abort
1177
- });
1178
- };
1179
- });
1180
- function handleArrayResult(result, final, index) {
1181
- if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));
1182
- final.value[index] = result.value;
1183
- }
1184
- const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => {
1185
- $ZodType.init(inst, def);
1186
- inst._zod.parse = (payload, ctx) => {
1187
- const input = payload.value;
1188
- if (!Array.isArray(input)) {
1189
- payload.issues.push({
1190
- expected: "array",
1191
- code: "invalid_type",
1192
- input,
1193
- inst
1194
- });
1195
- return payload;
1196
- }
1197
- payload.value = Array(input.length);
1198
- const proms = [];
1199
- for (let i = 0; i < input.length; i++) {
1200
- const item = input[i];
1201
- const result = def.element._zod.run({
1202
- value: item,
1203
- issues: []
1204
- }, ctx);
1205
- if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i)));
1206
- else handleArrayResult(result, payload, i);
1207
- }
1208
- if (proms.length) return Promise.all(proms).then(() => payload);
1209
- return payload;
1210
- };
1211
- });
1212
- function handleUnionResults(results, final, inst, ctx) {
1213
- for (const result of results) if (result.issues.length === 0) {
1214
- final.value = result.value;
1215
- return final;
1216
- }
1217
- const nonaborted = results.filter((r) => !aborted(r));
1218
- if (nonaborted.length === 1) {
1219
- final.value = nonaborted[0].value;
1220
- return nonaborted[0];
1221
- }
1222
- final.issues.push({
1223
- code: "invalid_union",
1224
- input: final.value,
1225
- inst,
1226
- errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
1227
- });
1228
- return final;
1229
- }
1230
- const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => {
1231
- $ZodType.init(inst, def);
1232
- defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
1233
- defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
1234
- defineLazy(inst._zod, "values", () => {
1235
- if (def.options.every((o) => o._zod.values)) return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
1236
- });
1237
- defineLazy(inst._zod, "pattern", () => {
1238
- if (def.options.every((o) => o._zod.pattern)) {
1239
- const patterns = def.options.map((o) => o._zod.pattern);
1240
- return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
1241
- }
1242
- });
1243
- const first = def.options.length === 1 ? def.options[0]._zod.run : null;
1244
- inst._zod.parse = (payload, ctx) => {
1245
- if (first) return first(payload, ctx);
1246
- let async = false;
1247
- const results = [];
1248
- for (const option of def.options) {
1249
- const result = option._zod.run({
1250
- value: payload.value,
1251
- issues: []
1252
- }, ctx);
1253
- if (result instanceof Promise) {
1254
- results.push(result);
1255
- async = true;
1256
- } else {
1257
- if (result.issues.length === 0) return result;
1258
- results.push(result);
1259
- }
1260
- }
1261
- if (!async) return handleUnionResults(results, payload, inst, ctx);
1262
- return Promise.all(results).then((results) => {
1263
- return handleUnionResults(results, payload, inst, ctx);
1264
- });
1265
- };
1266
- });
1267
- const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => {
1268
- $ZodType.init(inst, def);
1269
- inst._zod.parse = (payload, ctx) => {
1270
- const input = payload.value;
1271
- const left = def.left._zod.run({
1272
- value: input,
1273
- issues: []
1274
- }, ctx);
1275
- const right = def.right._zod.run({
1276
- value: input,
1277
- issues: []
1278
- }, ctx);
1279
- if (left instanceof Promise || right instanceof Promise) return Promise.all([left, right]).then(([left, right]) => {
1280
- return handleIntersectionResults(payload, left, right);
1281
- });
1282
- return handleIntersectionResults(payload, left, right);
1283
- };
1284
- });
1285
- function mergeValues(a, b) {
1286
- if (a === b) return {
1287
- valid: true,
1288
- data: a
1289
- };
1290
- if (a instanceof Date && b instanceof Date && +a === +b) return {
1291
- valid: true,
1292
- data: a
1293
- };
1294
- if (isPlainObject(a) && isPlainObject(b)) {
1295
- const bKeys = Object.keys(b);
1296
- const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
1297
- const newObj = {
1298
- ...a,
1299
- ...b
1300
- };
1301
- for (const key of sharedKeys) {
1302
- const sharedValue = mergeValues(a[key], b[key]);
1303
- if (!sharedValue.valid) return {
1304
- valid: false,
1305
- mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
1306
- };
1307
- newObj[key] = sharedValue.data;
1308
- }
1309
- return {
1310
- valid: true,
1311
- data: newObj
1312
- };
1313
- }
1314
- if (Array.isArray(a) && Array.isArray(b)) {
1315
- if (a.length !== b.length) return {
1316
- valid: false,
1317
- mergeErrorPath: []
1318
- };
1319
- const newArray = [];
1320
- for (let index = 0; index < a.length; index++) {
1321
- const itemA = a[index];
1322
- const itemB = b[index];
1323
- const sharedValue = mergeValues(itemA, itemB);
1324
- if (!sharedValue.valid) return {
1325
- valid: false,
1326
- mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
1327
- };
1328
- newArray.push(sharedValue.data);
1329
- }
1330
- return {
1331
- valid: true,
1332
- data: newArray
1333
- };
1334
- }
1335
- return {
1336
- valid: false,
1337
- mergeErrorPath: []
1338
- };
1339
- }
1340
- function handleIntersectionResults(result, left, right) {
1341
- const unrecKeys = /* @__PURE__ */ new Map();
1342
- let unrecIssue;
1343
- for (const iss of left.issues) if (iss.code === "unrecognized_keys") {
1344
- unrecIssue ?? (unrecIssue = iss);
1345
- for (const k of iss.keys) {
1346
- if (!unrecKeys.has(k)) unrecKeys.set(k, {});
1347
- unrecKeys.get(k).l = true;
1348
- }
1349
- } else result.issues.push(iss);
1350
- for (const iss of right.issues) if (iss.code === "unrecognized_keys") for (const k of iss.keys) {
1351
- if (!unrecKeys.has(k)) unrecKeys.set(k, {});
1352
- unrecKeys.get(k).r = true;
1353
- }
1354
- else result.issues.push(iss);
1355
- const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
1356
- if (bothKeys.length && unrecIssue) result.issues.push({
1357
- ...unrecIssue,
1358
- keys: bothKeys
1359
- });
1360
- if (aborted(result)) return result;
1361
- const merged = mergeValues(left.value, right.value);
1362
- if (!merged.valid) throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
1363
- result.value = merged.data;
1364
- return result;
1365
- }
1366
- const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => {
1367
- $ZodType.init(inst, def);
1368
- inst._zod.optin = "optional";
1369
- inst._zod.parse = (payload, ctx) => {
1370
- if (ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name);
1371
- const _out = def.transform(payload.value, payload);
1372
- if (ctx.async) return (_out instanceof Promise ? _out : Promise.resolve(_out)).then((output) => {
1373
- payload.value = output;
1374
- payload.fallback = true;
1375
- return payload;
1376
- });
1377
- if (_out instanceof Promise) throw new $ZodAsyncError();
1378
- payload.value = _out;
1379
- payload.fallback = true;
1380
- return payload;
1381
- };
1382
- });
1383
- function handleOptionalResult(result, input) {
1384
- if (input === void 0 && (result.issues.length || result.fallback)) return {
1385
- issues: [],
1386
- value: void 0
1387
- };
1388
- return result;
1389
- }
1390
- const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => {
1391
- $ZodType.init(inst, def);
1392
- inst._zod.optin = "optional";
1393
- inst._zod.optout = "optional";
1394
- defineLazy(inst._zod, "values", () => {
1395
- return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0;
1396
- });
1397
- defineLazy(inst._zod, "pattern", () => {
1398
- const pattern = def.innerType._zod.pattern;
1399
- return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
1400
- });
1401
- inst._zod.parse = (payload, ctx) => {
1402
- if (def.innerType._zod.optin === "optional") {
1403
- const input = payload.value;
1404
- const result = def.innerType._zod.run(payload, ctx);
1405
- if (result instanceof Promise) return result.then((r) => handleOptionalResult(r, input));
1406
- return handleOptionalResult(result, input);
1407
- }
1408
- if (payload.value === void 0) return payload;
1409
- return def.innerType._zod.run(payload, ctx);
1410
- };
1411
- });
1412
- const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => {
1413
- $ZodOptional.init(inst, def);
1414
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1415
- defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
1416
- inst._zod.parse = (payload, ctx) => {
1417
- return def.innerType._zod.run(payload, ctx);
1418
- };
1419
- });
1420
- const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => {
1421
- $ZodType.init(inst, def);
1422
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
1423
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1424
- defineLazy(inst._zod, "pattern", () => {
1425
- const pattern = def.innerType._zod.pattern;
1426
- return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
1427
- });
1428
- defineLazy(inst._zod, "values", () => {
1429
- return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0;
1430
- });
1431
- inst._zod.parse = (payload, ctx) => {
1432
- if (payload.value === null) return payload;
1433
- return def.innerType._zod.run(payload, ctx);
1434
- };
1435
- });
1436
- const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => {
1437
- $ZodType.init(inst, def);
1438
- inst._zod.optin = "optional";
1439
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1440
- inst._zod.parse = (payload, ctx) => {
1441
- if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
1442
- if (payload.value === void 0) {
1443
- payload.value = def.defaultValue;
1444
- /**
1445
- * $ZodDefault returns the default value immediately in forward direction.
1446
- * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */
1447
- return payload;
1448
- }
1449
- const result = def.innerType._zod.run(payload, ctx);
1450
- if (result instanceof Promise) return result.then((result) => handleDefaultResult(result, def));
1451
- return handleDefaultResult(result, def);
1452
- };
1453
- });
1454
- function handleDefaultResult(payload, def) {
1455
- if (payload.value === void 0) payload.value = def.defaultValue;
1456
- return payload;
1457
- }
1458
- const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => {
1459
- $ZodType.init(inst, def);
1460
- inst._zod.optin = "optional";
1461
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1462
- inst._zod.parse = (payload, ctx) => {
1463
- if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
1464
- if (payload.value === void 0) payload.value = def.defaultValue;
1465
- return def.innerType._zod.run(payload, ctx);
1466
- };
1467
- });
1468
- const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => {
1469
- $ZodType.init(inst, def);
1470
- defineLazy(inst._zod, "values", () => {
1471
- const v = def.innerType._zod.values;
1472
- return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
1473
- });
1474
- inst._zod.parse = (payload, ctx) => {
1475
- const result = def.innerType._zod.run(payload, ctx);
1476
- if (result instanceof Promise) return result.then((result) => handleNonOptionalResult(result, inst));
1477
- return handleNonOptionalResult(result, inst);
1478
- };
1479
- });
1480
- function handleNonOptionalResult(payload, inst) {
1481
- if (!payload.issues.length && payload.value === void 0) payload.issues.push({
1482
- code: "invalid_type",
1483
- expected: "nonoptional",
1484
- input: payload.value,
1485
- inst
1486
- });
1487
- return payload;
1488
- }
1489
- const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => {
1490
- $ZodType.init(inst, def);
1491
- inst._zod.optin = "optional";
1492
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1493
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1494
- inst._zod.parse = (payload, ctx) => {
1495
- if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
1496
- const result = def.innerType._zod.run(payload, ctx);
1497
- if (result instanceof Promise) return result.then((result) => {
1498
- payload.value = result.value;
1499
- if (result.issues.length) {
1500
- payload.value = def.catchValue({
1501
- ...payload,
1502
- error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
1503
- input: payload.value
1504
- });
1505
- payload.issues = [];
1506
- payload.fallback = true;
1507
- }
1508
- return payload;
1509
- });
1510
- payload.value = result.value;
1511
- if (result.issues.length) {
1512
- payload.value = def.catchValue({
1513
- ...payload,
1514
- error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
1515
- input: payload.value
1516
- });
1517
- payload.issues = [];
1518
- payload.fallback = true;
1519
- }
1520
- return payload;
1521
- };
1522
- });
1523
- const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => {
1524
- $ZodType.init(inst, def);
1525
- defineLazy(inst._zod, "values", () => def.in._zod.values);
1526
- defineLazy(inst._zod, "optin", () => def.in._zod.optin);
1527
- defineLazy(inst._zod, "optout", () => def.out._zod.optout);
1528
- defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
1529
- inst._zod.parse = (payload, ctx) => {
1530
- if (ctx.direction === "backward") {
1531
- const right = def.out._zod.run(payload, ctx);
1532
- if (right instanceof Promise) return right.then((right) => handlePipeResult(right, def.in, ctx));
1533
- return handlePipeResult(right, def.in, ctx);
1534
- }
1535
- const left = def.in._zod.run(payload, ctx);
1536
- if (left instanceof Promise) return left.then((left) => handlePipeResult(left, def.out, ctx));
1537
- return handlePipeResult(left, def.out, ctx);
1538
- };
1539
- });
1540
- function handlePipeResult(left, next, ctx) {
1541
- if (left.issues.length) {
1542
- left.aborted = true;
1543
- return left;
1544
- }
1545
- return next._zod.run({
1546
- value: left.value,
1547
- issues: left.issues,
1548
- fallback: left.fallback
1549
- }, ctx);
1550
- }
1551
- const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => {
1552
- $ZodType.init(inst, def);
1553
- defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
1554
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1555
- defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
1556
- defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
1557
- inst._zod.parse = (payload, ctx) => {
1558
- if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
1559
- const result = def.innerType._zod.run(payload, ctx);
1560
- if (result instanceof Promise) return result.then(handleReadonlyResult);
1561
- return handleReadonlyResult(result);
1562
- };
1563
- });
1564
- function handleReadonlyResult(payload) {
1565
- payload.value = Object.freeze(payload.value);
1566
- return payload;
1567
- }
1568
- const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => {
1569
- $ZodCheck.init(inst, def);
1570
- $ZodType.init(inst, def);
1571
- inst._zod.parse = (payload, _) => {
1572
- return payload;
1573
- };
1574
- inst._zod.check = (payload) => {
1575
- const input = payload.value;
1576
- const r = def.fn(input);
1577
- if (r instanceof Promise) return r.then((r) => handleRefineResult(r, payload, input, inst));
1578
- handleRefineResult(r, payload, input, inst);
1579
- };
1580
- });
1581
- function handleRefineResult(result, payload, input, inst) {
1582
- if (!result) {
1583
- const _iss = {
1584
- code: "custom",
1585
- input,
1586
- inst,
1587
- path: [...inst._zod.def.path ?? []],
1588
- continue: !inst._zod.def.abort
1589
- };
1590
- if (inst._zod.def.params) _iss.params = inst._zod.def.params;
1591
- payload.issues.push(issue(_iss));
1592
- }
1593
- }
1594
- //#endregion
1595
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/registries.js
1596
- var _a;
1597
- var $ZodRegistry = class {
1598
- constructor() {
1599
- this._map = /* @__PURE__ */ new WeakMap();
1600
- this._idmap = /* @__PURE__ */ new Map();
1601
- }
1602
- add(schema, ..._meta) {
1603
- const meta = _meta[0];
1604
- this._map.set(schema, meta);
1605
- if (meta && typeof meta === "object" && "id" in meta) this._idmap.set(meta.id, schema);
1606
- return this;
1607
- }
1608
- clear() {
1609
- this._map = /* @__PURE__ */ new WeakMap();
1610
- this._idmap = /* @__PURE__ */ new Map();
1611
- return this;
1612
- }
1613
- remove(schema) {
1614
- const meta = this._map.get(schema);
1615
- if (meta && typeof meta === "object" && "id" in meta) this._idmap.delete(meta.id);
1616
- this._map.delete(schema);
1617
- return this;
1618
- }
1619
- get(schema) {
1620
- const p = schema._zod.parent;
1621
- if (p) {
1622
- const pm = { ...this.get(p) ?? {} };
1623
- delete pm.id;
1624
- const f = {
1625
- ...pm,
1626
- ...this._map.get(schema)
1627
- };
1628
- return Object.keys(f).length ? f : void 0;
1629
- }
1630
- return this._map.get(schema);
1631
- }
1632
- has(schema) {
1633
- return this._map.has(schema);
1634
- }
1635
- };
1636
- function registry() {
1637
- return new $ZodRegistry();
1638
- }
1639
- (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
1640
- const globalRegistry = globalThis.__zod_globalRegistry;
1641
- //#endregion
1642
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/api.js
1643
- // @__NO_SIDE_EFFECTS__
1644
- function _string(Class, params) {
1645
- return new Class({
1646
- type: "string",
1647
- ...normalizeParams(params)
1648
- });
1649
- }
1650
- // @__NO_SIDE_EFFECTS__
1651
- function _email(Class, params) {
1652
- return new Class({
1653
- type: "string",
1654
- format: "email",
1655
- check: "string_format",
1656
- abort: false,
1657
- ...normalizeParams(params)
1658
- });
1659
- }
1660
- // @__NO_SIDE_EFFECTS__
1661
- function _guid(Class, params) {
1662
- return new Class({
1663
- type: "string",
1664
- format: "guid",
1665
- check: "string_format",
1666
- abort: false,
1667
- ...normalizeParams(params)
1668
- });
1669
- }
1670
- // @__NO_SIDE_EFFECTS__
1671
- function _uuid(Class, params) {
1672
- return new Class({
1673
- type: "string",
1674
- format: "uuid",
1675
- check: "string_format",
1676
- abort: false,
1677
- ...normalizeParams(params)
1678
- });
1679
- }
1680
- // @__NO_SIDE_EFFECTS__
1681
- function _uuidv4(Class, params) {
1682
- return new Class({
1683
- type: "string",
1684
- format: "uuid",
1685
- check: "string_format",
1686
- abort: false,
1687
- version: "v4",
1688
- ...normalizeParams(params)
1689
- });
1690
- }
1691
- // @__NO_SIDE_EFFECTS__
1692
- function _uuidv6(Class, params) {
1693
- return new Class({
1694
- type: "string",
1695
- format: "uuid",
1696
- check: "string_format",
1697
- abort: false,
1698
- version: "v6",
1699
- ...normalizeParams(params)
1700
- });
1701
- }
1702
- // @__NO_SIDE_EFFECTS__
1703
- function _uuidv7(Class, params) {
1704
- return new Class({
1705
- type: "string",
1706
- format: "uuid",
1707
- check: "string_format",
1708
- abort: false,
1709
- version: "v7",
1710
- ...normalizeParams(params)
1711
- });
1712
- }
1713
- // @__NO_SIDE_EFFECTS__
1714
- function _url(Class, params) {
1715
- return new Class({
1716
- type: "string",
1717
- format: "url",
1718
- check: "string_format",
1719
- abort: false,
1720
- ...normalizeParams(params)
1721
- });
1722
- }
1723
- // @__NO_SIDE_EFFECTS__
1724
- function _emoji(Class, params) {
1725
- return new Class({
1726
- type: "string",
1727
- format: "emoji",
1728
- check: "string_format",
1729
- abort: false,
1730
- ...normalizeParams(params)
1731
- });
1732
- }
1733
- // @__NO_SIDE_EFFECTS__
1734
- function _nanoid(Class, params) {
1735
- return new Class({
1736
- type: "string",
1737
- format: "nanoid",
1738
- check: "string_format",
1739
- abort: false,
1740
- ...normalizeParams(params)
1741
- });
1742
- }
1743
- /**
1744
- * @deprecated CUID v1 is deprecated by its authors due to information leakage
1745
- * (timestamps embedded in the id). Use {@link _cuid2} instead.
1746
- * See https://github.com/paralleldrive/cuid.
1747
- */
1748
- // @__NO_SIDE_EFFECTS__
1749
- function _cuid(Class, params) {
1750
- return new Class({
1751
- type: "string",
1752
- format: "cuid",
1753
- check: "string_format",
1754
- abort: false,
1755
- ...normalizeParams(params)
1756
- });
1757
- }
1758
- // @__NO_SIDE_EFFECTS__
1759
- function _cuid2(Class, params) {
1760
- return new Class({
1761
- type: "string",
1762
- format: "cuid2",
1763
- check: "string_format",
1764
- abort: false,
1765
- ...normalizeParams(params)
1766
- });
1767
- }
1768
- // @__NO_SIDE_EFFECTS__
1769
- function _ulid(Class, params) {
1770
- return new Class({
1771
- type: "string",
1772
- format: "ulid",
1773
- check: "string_format",
1774
- abort: false,
1775
- ...normalizeParams(params)
1776
- });
1777
- }
1778
- // @__NO_SIDE_EFFECTS__
1779
- function _xid(Class, params) {
1780
- return new Class({
1781
- type: "string",
1782
- format: "xid",
1783
- check: "string_format",
1784
- abort: false,
1785
- ...normalizeParams(params)
1786
- });
1787
- }
1788
- // @__NO_SIDE_EFFECTS__
1789
- function _ksuid(Class, params) {
1790
- return new Class({
1791
- type: "string",
1792
- format: "ksuid",
1793
- check: "string_format",
1794
- abort: false,
1795
- ...normalizeParams(params)
1796
- });
1797
- }
1798
- // @__NO_SIDE_EFFECTS__
1799
- function _ipv4(Class, params) {
1800
- return new Class({
1801
- type: "string",
1802
- format: "ipv4",
1803
- check: "string_format",
1804
- abort: false,
1805
- ...normalizeParams(params)
1806
- });
1807
- }
1808
- // @__NO_SIDE_EFFECTS__
1809
- function _ipv6(Class, params) {
1810
- return new Class({
1811
- type: "string",
1812
- format: "ipv6",
1813
- check: "string_format",
1814
- abort: false,
1815
- ...normalizeParams(params)
1816
- });
1817
- }
1818
- // @__NO_SIDE_EFFECTS__
1819
- function _cidrv4(Class, params) {
1820
- return new Class({
1821
- type: "string",
1822
- format: "cidrv4",
1823
- check: "string_format",
1824
- abort: false,
1825
- ...normalizeParams(params)
1826
- });
1827
- }
1828
- // @__NO_SIDE_EFFECTS__
1829
- function _cidrv6(Class, params) {
1830
- return new Class({
1831
- type: "string",
1832
- format: "cidrv6",
1833
- check: "string_format",
1834
- abort: false,
1835
- ...normalizeParams(params)
1836
- });
1837
- }
1838
- // @__NO_SIDE_EFFECTS__
1839
- function _base64(Class, params) {
1840
- return new Class({
1841
- type: "string",
1842
- format: "base64",
1843
- check: "string_format",
1844
- abort: false,
1845
- ...normalizeParams(params)
1846
- });
1847
- }
1848
- // @__NO_SIDE_EFFECTS__
1849
- function _base64url(Class, params) {
1850
- return new Class({
1851
- type: "string",
1852
- format: "base64url",
1853
- check: "string_format",
1854
- abort: false,
1855
- ...normalizeParams(params)
1856
- });
1857
- }
1858
- // @__NO_SIDE_EFFECTS__
1859
- function _e164(Class, params) {
1860
- return new Class({
1861
- type: "string",
1862
- format: "e164",
1863
- check: "string_format",
1864
- abort: false,
1865
- ...normalizeParams(params)
1866
- });
1867
- }
1868
- // @__NO_SIDE_EFFECTS__
1869
- function _jwt(Class, params) {
1870
- return new Class({
1871
- type: "string",
1872
- format: "jwt",
1873
- check: "string_format",
1874
- abort: false,
1875
- ...normalizeParams(params)
1876
- });
1877
- }
1878
- // @__NO_SIDE_EFFECTS__
1879
- function _isoDateTime(Class, params) {
1880
- return new Class({
1881
- type: "string",
1882
- format: "datetime",
1883
- check: "string_format",
1884
- offset: false,
1885
- local: false,
1886
- precision: null,
1887
- ...normalizeParams(params)
1888
- });
1889
- }
1890
- // @__NO_SIDE_EFFECTS__
1891
- function _isoDate(Class, params) {
1892
- return new Class({
1893
- type: "string",
1894
- format: "date",
1895
- check: "string_format",
1896
- ...normalizeParams(params)
1897
- });
1898
- }
1899
- // @__NO_SIDE_EFFECTS__
1900
- function _isoTime(Class, params) {
1901
- return new Class({
1902
- type: "string",
1903
- format: "time",
1904
- check: "string_format",
1905
- precision: null,
1906
- ...normalizeParams(params)
1907
- });
1908
- }
1909
- // @__NO_SIDE_EFFECTS__
1910
- function _isoDuration(Class, params) {
1911
- return new Class({
1912
- type: "string",
1913
- format: "duration",
1914
- check: "string_format",
1915
- ...normalizeParams(params)
1916
- });
1917
- }
1918
- // @__NO_SIDE_EFFECTS__
1919
- function _maxLength(maximum, params) {
1920
- return new $ZodCheckMaxLength({
1921
- check: "max_length",
1922
- ...normalizeParams(params),
1923
- maximum
1924
- });
1925
- }
1926
- // @__NO_SIDE_EFFECTS__
1927
- function _minLength(minimum, params) {
1928
- return new $ZodCheckMinLength({
1929
- check: "min_length",
1930
- ...normalizeParams(params),
1931
- minimum
1932
- });
1933
- }
1934
- // @__NO_SIDE_EFFECTS__
1935
- function _length(length, params) {
1936
- return new $ZodCheckLengthEquals({
1937
- check: "length_equals",
1938
- ...normalizeParams(params),
1939
- length
1940
- });
1941
- }
1942
- // @__NO_SIDE_EFFECTS__
1943
- function _regex(pattern, params) {
1944
- return new $ZodCheckRegex({
1945
- check: "string_format",
1946
- format: "regex",
1947
- ...normalizeParams(params),
1948
- pattern
1949
- });
1950
- }
1951
- // @__NO_SIDE_EFFECTS__
1952
- function _lowercase(params) {
1953
- return new $ZodCheckLowerCase({
1954
- check: "string_format",
1955
- format: "lowercase",
1956
- ...normalizeParams(params)
1957
- });
1958
- }
1959
- // @__NO_SIDE_EFFECTS__
1960
- function _uppercase(params) {
1961
- return new $ZodCheckUpperCase({
1962
- check: "string_format",
1963
- format: "uppercase",
1964
- ...normalizeParams(params)
1965
- });
1966
- }
1967
- // @__NO_SIDE_EFFECTS__
1968
- function _includes(includes, params) {
1969
- return new $ZodCheckIncludes({
1970
- check: "string_format",
1971
- format: "includes",
1972
- ...normalizeParams(params),
1973
- includes
1974
- });
1975
- }
1976
- // @__NO_SIDE_EFFECTS__
1977
- function _startsWith(prefix, params) {
1978
- return new $ZodCheckStartsWith({
1979
- check: "string_format",
1980
- format: "starts_with",
1981
- ...normalizeParams(params),
1982
- prefix
1983
- });
1984
- }
1985
- // @__NO_SIDE_EFFECTS__
1986
- function _endsWith(suffix, params) {
1987
- return new $ZodCheckEndsWith({
1988
- check: "string_format",
1989
- format: "ends_with",
1990
- ...normalizeParams(params),
1991
- suffix
1992
- });
1993
- }
1994
- // @__NO_SIDE_EFFECTS__
1995
- function _overwrite(tx) {
1996
- return new $ZodCheckOverwrite({
1997
- check: "overwrite",
1998
- tx
1999
- });
2000
- }
2001
- // @__NO_SIDE_EFFECTS__
2002
- function _normalize(form) {
2003
- return /* @__PURE__ */ _overwrite((input) => input.normalize(form));
2004
- }
2005
- // @__NO_SIDE_EFFECTS__
2006
- function _trim() {
2007
- return /* @__PURE__ */ _overwrite((input) => input.trim());
2008
- }
2009
- // @__NO_SIDE_EFFECTS__
2010
- function _toLowerCase() {
2011
- return /* @__PURE__ */ _overwrite((input) => input.toLowerCase());
2012
- }
2013
- // @__NO_SIDE_EFFECTS__
2014
- function _toUpperCase() {
2015
- return /* @__PURE__ */ _overwrite((input) => input.toUpperCase());
2016
- }
2017
- // @__NO_SIDE_EFFECTS__
2018
- function _slugify() {
2019
- return /* @__PURE__ */ _overwrite((input) => slugify(input));
2020
- }
2021
- // @__NO_SIDE_EFFECTS__
2022
- function _array(Class, element, params) {
2023
- return new Class({
2024
- type: "array",
2025
- element,
2026
- ...normalizeParams(params)
2027
- });
2028
- }
2029
- // @__NO_SIDE_EFFECTS__
2030
- function _refine(Class, fn, _params) {
2031
- return new Class({
2032
- type: "custom",
2033
- check: "custom",
2034
- fn,
2035
- ...normalizeParams(_params)
2036
- });
2037
- }
2038
- // @__NO_SIDE_EFFECTS__
2039
- function _superRefine(fn, params) {
2040
- const ch = /* @__PURE__ */ _check((payload) => {
2041
- payload.addIssue = (issue$2) => {
2042
- if (typeof issue$2 === "string") payload.issues.push(issue(issue$2, payload.value, ch._zod.def));
2043
- else {
2044
- const _issue = issue$2;
2045
- if (_issue.fatal) _issue.continue = false;
2046
- _issue.code ?? (_issue.code = "custom");
2047
- _issue.input ?? (_issue.input = payload.value);
2048
- _issue.inst ?? (_issue.inst = ch);
2049
- _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
2050
- payload.issues.push(issue(_issue));
2051
- }
2052
- };
2053
- return fn(payload.value, payload);
2054
- }, params);
2055
- return ch;
2056
- }
2057
- // @__NO_SIDE_EFFECTS__
2058
- function _check(fn, params) {
2059
- const ch = new $ZodCheck({
2060
- check: "custom",
2061
- ...normalizeParams(params)
2062
- });
2063
- ch._zod.check = fn;
2064
- return ch;
2065
- }
2066
- //#endregion
2067
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js
2068
- function initializeContext(params) {
2069
- let target = params?.target ?? "draft-2020-12";
2070
- if (target === "draft-4") target = "draft-04";
2071
- if (target === "draft-7") target = "draft-07";
2072
- return {
2073
- processors: params.processors ?? {},
2074
- metadataRegistry: params?.metadata ?? globalRegistry,
2075
- target,
2076
- unrepresentable: params?.unrepresentable ?? "throw",
2077
- override: params?.override ?? (() => {}),
2078
- io: params?.io ?? "output",
2079
- counter: 0,
2080
- seen: /* @__PURE__ */ new Map(),
2081
- cycles: params?.cycles ?? "ref",
2082
- reused: params?.reused ?? "inline",
2083
- external: params?.external ?? void 0
2084
- };
2085
- }
2086
- function process$1(schema, ctx, _params = {
2087
- path: [],
2088
- schemaPath: []
2089
- }) {
2090
- var _a;
2091
- const def = schema._zod.def;
2092
- const seen = ctx.seen.get(schema);
2093
- if (seen) {
2094
- seen.count++;
2095
- if (_params.schemaPath.includes(schema)) seen.cycle = _params.path;
2096
- return seen.schema;
2097
- }
2098
- const result = {
2099
- schema: {},
2100
- count: 1,
2101
- cycle: void 0,
2102
- path: _params.path
2103
- };
2104
- ctx.seen.set(schema, result);
2105
- const overrideSchema = schema._zod.toJSONSchema?.();
2106
- if (overrideSchema) result.schema = overrideSchema;
2107
- else {
2108
- const params = {
2109
- ..._params,
2110
- schemaPath: [..._params.schemaPath, schema],
2111
- path: _params.path
2112
- };
2113
- if (schema._zod.processJSONSchema) schema._zod.processJSONSchema(ctx, result.schema, params);
2114
- else {
2115
- const _json = result.schema;
2116
- const processor = ctx.processors[def.type];
2117
- if (!processor) throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
2118
- processor(schema, ctx, _json, params);
2119
- }
2120
- const parent = schema._zod.parent;
2121
- if (parent) {
2122
- if (!result.ref) result.ref = parent;
2123
- process$1(parent, ctx, params);
2124
- ctx.seen.get(parent).isParent = true;
2125
- }
2126
- }
2127
- const meta = ctx.metadataRegistry.get(schema);
2128
- if (meta) Object.assign(result.schema, meta);
2129
- if (ctx.io === "input" && isTransforming(schema)) {
2130
- delete result.schema.examples;
2131
- delete result.schema.default;
2132
- }
2133
- if (ctx.io === "input" && "_prefault" in result.schema) (_a = result.schema).default ?? (_a.default = result.schema._prefault);
2134
- delete result.schema._prefault;
2135
- return ctx.seen.get(schema).schema;
2136
- }
2137
- function extractDefs(ctx, schema) {
2138
- const root = ctx.seen.get(schema);
2139
- if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
2140
- const idToSchema = /* @__PURE__ */ new Map();
2141
- for (const entry of ctx.seen.entries()) {
2142
- const id = ctx.metadataRegistry.get(entry[0])?.id;
2143
- if (id) {
2144
- const existing = idToSchema.get(id);
2145
- if (existing && existing !== entry[0]) throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
2146
- idToSchema.set(id, entry[0]);
2147
- }
2148
- }
2149
- const makeURI = (entry) => {
2150
- const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
2151
- if (ctx.external) {
2152
- const externalId = ctx.external.registry.get(entry[0])?.id;
2153
- const uriGenerator = ctx.external.uri ?? ((id) => id);
2154
- if (externalId) return { ref: uriGenerator(externalId) };
2155
- const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
2156
- entry[1].defId = id;
2157
- return {
2158
- defId: id,
2159
- ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}`
2160
- };
2161
- }
2162
- if (entry[1] === root) return { ref: "#" };
2163
- const defUriPrefix = `#/${defsSegment}/`;
2164
- const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
2165
- return {
2166
- defId,
2167
- ref: defUriPrefix + defId
2168
- };
2169
- };
2170
- const extractToDef = (entry) => {
2171
- if (entry[1].schema.$ref) return;
2172
- const seen = entry[1];
2173
- const { ref, defId } = makeURI(entry);
2174
- seen.def = { ...seen.schema };
2175
- if (defId) seen.defId = defId;
2176
- const schema = seen.schema;
2177
- for (const key in schema) delete schema[key];
2178
- schema.$ref = ref;
2179
- };
2180
- if (ctx.cycles === "throw") for (const entry of ctx.seen.entries()) {
2181
- const seen = entry[1];
2182
- if (seen.cycle) throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
2
+ import{createRequire}from"node:module";import{Command}from"commander";import{AppError,ErrorCode,importTemplateForBatch,loadConfig,openCache,runBatch,zodToJsonSchemaShape}from"@stdout-design/core";import path from"node:path";import{execSync,spawnSync}from"node:child_process";import{existsSync,readFileSync}from"node:fs";import{resolveCommand}from"package-manager-detector/commands";import{detect}from"package-manager-detector/detect";import{cp,mkdir,writeFile}from"node:fs/promises";import{pathToFileURL}from"node:url";const formatBytes=bytes=>bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KB`:bytes<1024*1024*1024?`${(bytes/(1024*1024)).toFixed(1)} MB`:`${(bytes/(1024*1024*1024)).toFixed(2)} GB`,formatCacheStats=stats=>[``,`Cache Statistics`,`━━━━━━━━━━━━━━━━`,` Location: ${stats.cacheDir}`,` Compiled: ${stats.compiled.entries} entries (in-memory compile cache)`,` Pixel: ${stats.pixels.entries} entries`,` Disk used: ${formatBytes(stats.pixels.sizeBytes)}`,` Disk limit: ${formatBytes(stats.pixels.maxSizeBytes)}`,``].join(`
3
+ `),formatManifestSummary=manifest=>{let{completedCount,totalCount,succeeded,failed}=manifest,cacheHits=succeeded.filter(s=>s.cacheHit).length,lines=[``,`Batch Render Complete`,`━━━━━━━━━━━━━━━━━━━━`,` Status: ${manifest.status}`,` Total: ${totalCount}`,` Completed: ${completedCount}`,` Cache: ${cacheHits} hits, ${succeeded.length-cacheHits} renders`,` Failed: ${failed.length}`,``];if(succeeded.length>0&&succeeded.length<=10){lines.push(`Output files:`);for(let entry of succeeded)lines.push(` ${entry.outputPath}`);lines.push(``)}if(failed.length>0){lines.push(`Failures:`);for(let f of failed)lines.push(` Row ${f.rowIndex}, ${f.locale}, ${f.preset}: ${f.error}`);lines.push(``)}return lines.join(`
4
+ `)},formatError$1=error=>error instanceof Error?`Error: ${error.message}`:`Error: ${String(error)}`,formatCacheCleanResult=freedBytes=>`Cache cleared. Freed ${formatBytes(freedBytes)}.`,cacheStats=async(rootDir,options)=>{let cache=await openCache(rootDir??process.cwd()),stats=await cache.stats();cache.close(),options.json?console.log(JSON.stringify(stats,null,2)):console.log(formatCacheStats(stats))},cacheClean=async(rootDir,options)=>{let cache=await openCache(rootDir??process.cwd()),result=await cache.clean();cache.close(),options.json?console.log(JSON.stringify(result)):console.log(formatCacheCleanResult(result.freedBytes))},findWebUiDist=()=>{try{let pkgJsonPath=createRequire(import.meta.url).resolve(`@stdout-design/web-ui/package.json`),pkgDir=path.dirname(pkgJsonPath);return path.join(pkgDir,`dist`)}catch{}},dev=async(rootDir,options)=>{let{startStandaloneServer}=await import(`@stdout-design/dev-server`).catch(()=>{throw Error([`studio dev requires a scaffolded project with @stdout-design/dev-server installed.`,"Run `studio init` to create one, or install it manually:",``,` bun add @stdout-design/dev-server`,``,`See https://stdout.design/docs for more information.`].join(`
5
+ `))}),resolvedRoot=rootDir??process.cwd(),port=Number(options.port??`3000`),webUiDist=findWebUiDist();console.log(`Starting studio dev server for ${resolvedRoot}...`),await startStandaloneServer({port,rootDir:resolvedRoot,webUiDist})},isInsideGitRepo=dir=>{let current=path.resolve(dir);for(;;){if(existsSync(path.join(current,`.git`)))return!0;let parent=path.dirname(current);if(parent===current)break;current=parent}return!1},tryGitInit=dir=>{try{execSync(`git --version`,{stdio:`ignore`})}catch{return!1}if(existsSync(path.join(dir,`.git`))||isInsideGitRepo(path.dirname(dir)))return!1;try{return execSync(`git init`,{cwd:dir,stdio:`ignore`}),execSync(`git checkout -b main`,{cwd:dir,stdio:`ignore`}),execSync(`git add .`,{cwd:dir,stdio:`ignore`}),execSync(`git commit -m "Initial commit from stdout-design"`,{cwd:dir,stdio:`ignore`}),!0}catch{if(existsSync(path.join(dir,`.git`)))try{execSync(`rm -rf .git`,{cwd:dir,stdio:`ignore`})}catch{}return!1}};var _a$1;function $constructor(name,initializer,params){function init(inst,def){if(inst._zod||Object.defineProperty(inst,"_zod",{value:{def,constr:_,traits:new Set},enumerable:!1}),inst._zod.traits.has(name))return;inst._zod.traits.add(name),initializer(inst,def);let proto=_.prototype,keys=Object.keys(proto);for(let i=0;i<keys.length;i++){let k=keys[i];k in inst||(inst[k]=proto[k].bind(inst))}}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){var _a;let inst=params?.Parent?new Definition:this;init(inst,def),(_a=inst._zod).deferred??(_a.deferred=[]);for(let fn of inst._zod.deferred)fn();return inst}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:inst=>params?.Parent&&inst instanceof params.Parent?!0:inst?._zod?.traits?.has(name)}),Object.defineProperty(_,"name",{value:name}),_}var $ZodAsyncError=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},$ZodEncodeError=class extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`),this.name=`ZodEncodeError`}};(_a$1=globalThis).__zod_globalConfig??(_a$1.__zod_globalConfig={});const globalConfig=globalThis.__zod_globalConfig;function config(newConfig){return newConfig&&Object.assign(globalConfig,newConfig),globalConfig}function jsonStringifyReplacer(_,value){return typeof value==`bigint`?value.toString():value}function nullish(input){return input==null}function cleanRegex(source){let start=+!!source.startsWith(`^`),end=source.endsWith(`$`)?source.length-1:source.length;return source.slice(start,end)}const EVALUATING=Symbol(`evaluating`);function defineLazy(object,key,getter){let value;Object.defineProperty(object,key,{get(){if(value!==EVALUATING)return value===void 0&&(value=EVALUATING,value=getter()),value},set(v){Object.defineProperty(object,key,{value:v})},configurable:!0})}function mergeDefs(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const captureStackTrace=`captureStackTrace`in Error?Error.captureStackTrace:(..._args)=>{};function isObject(data){return typeof data==`object`&&!!data&&!Array.isArray(data)}function isPlainObject(o){if(isObject(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0||typeof ctor!=`function`)return!0;let prot=ctor.prototype;return!(isObject(prot)===!1||Object.prototype.hasOwnProperty.call(prot,`isPrototypeOf`)===!1)}function shallowClone(o){return isPlainObject(o)?{...o}:Array.isArray(o)?[...o]:o instanceof Map?new Map(o):o instanceof Set?new Set(o):o}function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function clone(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);return(!def||params?.parent)&&(cl._zod.parent=inst),cl}function normalizeParams(_params){let params=_params;if(!params)return{};if(typeof params==`string`)return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");params.error=params.message}return delete params.message,typeof params.error==`string`?{...params,error:()=>params.error}:params}-Number.MAX_VALUE,Number.MAX_VALUE;function aborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue!==!0)return!0;return!1}function explicitlyAborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue===!1)return!0;return!1}function prefixIssues(path,issues){return issues.map(iss=>{var _a;return(_a=iss).path??(_a.path=[]),iss.path.unshift(path),iss})}function unwrapMessage(message){return typeof message==`string`?message:message?.message}function finalizeIssue(iss,ctx,config){let message=iss.message?iss.message:unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config.customError?.(iss))??unwrapMessage(config.localeError?.(iss))??`Invalid input`,{inst:_inst,continue:_continue,input:_input,...rest}=iss;return rest.path??=[],rest.message=message,ctx?.reportInput&&(rest.input=_input),rest}function getLengthableOrigin(input){return Array.isArray(input)?`array`:typeof input==`string`?`string`:`unknown`}function issue(...args){let[iss,input,inst]=args;return typeof iss==`string`?{message:iss,code:`custom`,input,inst}:{...iss}}const initializer$1=(inst,def)=>{inst.name=`$ZodError`,Object.defineProperty(inst,"_zod",{value:inst._zod,enumerable:!1}),Object.defineProperty(inst,"issues",{value:def,enumerable:!1}),inst.message=JSON.stringify(def,jsonStringifyReplacer,2),Object.defineProperty(inst,"toString",{value:()=>inst.message,enumerable:!1})},$ZodError=$constructor(`$ZodError`,initializer$1),$ZodRealError=$constructor(`$ZodError`,initializer$1,{Parent:Error});function flattenError(error,mapper=issue=>issue.message){let fieldErrors={},formErrors=[];for(let sub of error.issues)sub.path.length>0?(fieldErrors[sub.path[0]]=fieldErrors[sub.path[0]]||[],fieldErrors[sub.path[0]].push(mapper(sub))):formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError(error,mapper=issue=>issue.message){let fieldErrors={_errors:[]},processError=(error,path=[])=>{for(let issue of error.issues)if(issue.code===`invalid_union`&&issue.errors.length)issue.errors.map(issues=>processError({issues},[...path,...issue.path]));else if(issue.code===`invalid_key`)processError({issues:issue.issues},[...path,...issue.path]);else if(issue.code===`invalid_element`)processError({issues:issue.issues},[...path,...issue.path]);else{let fullpath=[...path,...issue.path];if(fullpath.length===0)fieldErrors._errors.push(mapper(issue));else{let curr=fieldErrors,i=0;for(;i<fullpath.length;){let el=fullpath[i];i===fullpath.length-1?(curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue))):curr[el]=curr[el]||{_errors:[]},curr=curr[el],i++}}}};return processError(error),fieldErrors}const _parse=_Err=>(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;if(result.issues.length){let e=new((_params?.Err)??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,_params?.callee),e}return result.value},_parseAsync=_Err=>async(schema,value,_ctx,params)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise&&(result=await result),result.issues.length){let e=new((params?.Err)??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,params?.callee),e}return result.value},_safeParse=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;return result.issues.length?{success:!1,error:new(_Err??$ZodError)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParse$1=_safeParse($ZodRealError),_safeParseAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);return result instanceof Promise&&(result=await result),result.issues.length?{success:!1,error:new _Err(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParseAsync$1=_safeParseAsync($ZodRealError),_encode=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:`backward`}:{direction:`backward`};return _parse(_Err)(schema,value,ctx)},_decode=_Err=>(schema,value,_ctx)=>_parse(_Err)(schema,value,_ctx),_encodeAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:`backward`}:{direction:`backward`};return _parseAsync(_Err)(schema,value,ctx)},_decodeAsync=_Err=>async(schema,value,_ctx)=>_parseAsync(_Err)(schema,value,_ctx),_safeEncode=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:`backward`}:{direction:`backward`};return _safeParse(_Err)(schema,value,ctx)},_safeDecode=_Err=>(schema,value,_ctx)=>_safeParse(_Err)(schema,value,_ctx),_safeEncodeAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:`backward`}:{direction:`backward`};return _safeParseAsync(_Err)(schema,value,ctx)},_safeDecodeAsync=_Err=>async(schema,value,_ctx)=>_safeParseAsync(_Err)(schema,value,_ctx),cuid=/^[cC][0-9a-z]{6,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration$1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,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})$/,uuid=version=>version?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})$`):/^([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)$/,email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function emoji(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}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])$/,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}|:))$/,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])$/,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])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^[A-Za-z0-9_-]*$/,httpProtocol=/^https?$/,e164=/^\+[1-9]\d{6,14}$/,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])))`,date$1=RegExp(`^${dateSource}$`);function timeSource(args){let hhmm=`(?:[01]\\d|2[0-3]):[0-5]\\d`;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+)?)?`}function time$1(args){return RegExp(`^${timeSource(args)}$`)}function datetime$1(args){let time=timeSource({precision:args.precision}),opts=[`Z`];args.local&&opts.push(``),args.offset&&opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let timeRegex=`${time}(?:${opts.join(`|`)})`;return RegExp(`^${dateSource}T(?:${timeRegex})$`)}const string$1=params=>{let regex=params?`[\\s\\S]{${params?.minimum??0},${params?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${regex}$`)},lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/,$ZodCheck=$constructor(`$ZodCheck`,(inst,def)=>{var _a;inst._zod??={},inst._zod.def=def,(_a=inst._zod).onattach??(_a.onattach=[])}),$ZodCheckMaxLength=$constructor(`$ZodCheckMaxLength`,(inst,def)=>{var _a;$ZodCheck.init(inst,def),(_a=inst._zod.def).when??(_a.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst=>{let curr=inst._zod.bag.maximum??1/0;def.maximum<curr&&(inst._zod.bag.maximum=def.maximum)}),inst._zod.check=payload=>{let input=payload.value;if(input.length<=def.maximum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:`too_big`,maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinLength=$constructor(`$ZodCheckMinLength`,(inst,def)=>{var _a;$ZodCheck.init(inst,def),(_a=inst._zod.def).when??(_a.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst=>{let curr=inst._zod.bag.minimum??-1/0;def.minimum>curr&&(inst._zod.bag.minimum=def.minimum)}),inst._zod.check=payload=>{let input=payload.value;if(input.length>=def.minimum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:`too_small`,minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckLengthEquals=$constructor(`$ZodCheckLengthEquals`,(inst,def)=>{var _a;$ZodCheck.init(inst,def),(_a=inst._zod.def).when??(_a.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst=>{let bag=inst._zod.bag;bag.minimum=def.length,bag.maximum=def.length,bag.length=def.length}),inst._zod.check=payload=>{let input=payload.value,length=input.length;if(length===def.length)return;let origin=getLengthableOrigin(input),tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:`too_big`,maximum:def.length}:{code:`too_small`,minimum:def.length},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStringFormat=$constructor(`$ZodCheckStringFormat`,(inst,def)=>{var _a,_b;$ZodCheck.init(inst,def),inst._zod.onattach.push(inst=>{let bag=inst._zod.bag;bag.format=def.format,def.pattern&&(bag.patterns??=new Set,bag.patterns.add(def.pattern))}),def.pattern?(_a=inst._zod).check??(_a.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:`string`,code:`invalid_format`,format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})}):(_b=inst._zod).check??(_b.check=()=>{})}),$ZodCheckRegex=$constructor(`$ZodCheckRegex`,(inst,def)=>{$ZodCheckStringFormat.init(inst,def),inst._zod.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}}),$ZodCheckLowerCase=$constructor(`$ZodCheckLowerCase`,(inst,def)=>{def.pattern??=lowercase,$ZodCheckStringFormat.init(inst,def)}),$ZodCheckUpperCase=$constructor(`$ZodCheckUpperCase`,(inst,def)=>{def.pattern??=uppercase,$ZodCheckStringFormat.init(inst,def)}),$ZodCheckIncludes=$constructor(`$ZodCheckIncludes`,(inst,def)=>{$ZodCheck.init(inst,def);let escapedRegex=escapeRegex(def.includes),pattern=new RegExp(typeof def.position==`number`?`^.{${def.position}}${escapedRegex}`:escapedRegex);def.pattern=pattern,inst._zod.onattach.push(inst=>{let bag=inst._zod.bag;bag.patterns??=new Set,bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.includes(def.includes,def.position)||payload.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:def.includes,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStartsWith=$constructor(`$ZodCheckStartsWith`,(inst,def)=>{$ZodCheck.init(inst,def);let pattern=RegExp(`^${escapeRegex(def.prefix)}.*`);def.pattern??=pattern,inst._zod.onattach.push(inst=>{let bag=inst._zod.bag;bag.patterns??=new Set,bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.startsWith(def.prefix)||payload.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckEndsWith=$constructor(`$ZodCheckEndsWith`,(inst,def)=>{$ZodCheck.init(inst,def);let pattern=RegExp(`.*${escapeRegex(def.suffix)}$`);def.pattern??=pattern,inst._zod.onattach.push(inst=>{let bag=inst._zod.bag;bag.patterns??=new Set,bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.endsWith(def.suffix)||payload.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckOverwrite=$constructor(`$ZodCheckOverwrite`,(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=payload=>{payload.value=def.tx(payload.value)}}),version={major:4,minor:4,patch:3},$ZodType=$constructor(`$ZodType`,(inst,def)=>{var _a;inst??={},inst._zod.def=def,inst._zod.bag=inst._zod.bag||{},inst._zod.version=version;let checks=[...inst._zod.def.checks??[]];inst._zod.traits.has(`$ZodCheck`)&&checks.unshift(inst);for(let ch of checks)for(let fn of ch._zod.onattach)fn(inst);if(checks.length===0)(_a=inst._zod).deferred??(_a.deferred=[]),inst._zod.deferred?.push(()=>{inst._zod.run=inst._zod.parse});else{let runChecks=(payload,checks,ctx)=>{let isAborted=aborted(payload),asyncResult;for(let ch of checks){if(ch._zod.def.when){if(explicitlyAborted(payload)||!ch._zod.def.when(payload))continue}else if(isAborted)continue;let currLen=payload.issues.length,_=ch._zod.check(payload);if(_ instanceof Promise&&ctx?.async===!1)throw new $ZodAsyncError;if(asyncResult||_ instanceof Promise)asyncResult=(asyncResult??Promise.resolve()).then(async()=>{await _,payload.issues.length!==currLen&&(isAborted||=aborted(payload,currLen))});else{if(payload.issues.length===currLen)continue;isAborted||=aborted(payload,currLen)}}return asyncResult?asyncResult.then(()=>payload):payload},handleCanaryResult=(canary,payload,ctx)=>{if(aborted(canary))return canary.aborted=!0,canary;let checkResult=runChecks(payload,checks,ctx);if(checkResult instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return checkResult.then(checkResult=>inst._zod.parse(checkResult,ctx))}return inst._zod.parse(checkResult,ctx)};inst._zod.run=(payload,ctx)=>{if(ctx.skipChecks)return inst._zod.parse(payload,ctx);if(ctx.direction===`backward`){let canary=inst._zod.parse({value:payload.value,issues:[]},{...ctx,skipChecks:!0});return canary instanceof Promise?canary.then(canary=>handleCanaryResult(canary,payload,ctx)):handleCanaryResult(canary,payload,ctx)}let result=inst._zod.parse(payload,ctx);if(result instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return result.then(result=>runChecks(result,checks,ctx))}return runChecks(result,checks,ctx)}}defineLazy(inst,`~standard`,()=>({validate:value=>{try{let r=safeParse$1(inst,value);return r.success?{value:r.data}:{issues:r.error?.issues}}catch{return safeParseAsync$1(inst,value).then(r=>r.success?{value:r.data}:{issues:r.error?.issues})}},vendor:`zod`,version:1}))}),$ZodString=$constructor(`$ZodString`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=[...inst?._zod.bag?.patterns??[]].pop()??string$1(inst._zod.bag),inst._zod.parse=(payload,_)=>{if(def.coerce)try{payload.value=String(payload.value)}catch{}return typeof payload.value==`string`||payload.issues.push({expected:`string`,code:`invalid_type`,input:payload.value,inst}),payload}}),$ZodStringFormat=$constructor(`$ZodStringFormat`,(inst,def)=>{$ZodCheckStringFormat.init(inst,def),$ZodString.init(inst,def)}),$ZodGUID=$constructor(`$ZodGUID`,(inst,def)=>{def.pattern??=guid,$ZodStringFormat.init(inst,def)}),$ZodUUID=$constructor(`$ZodUUID`,(inst,def)=>{if(def.version){let v={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[def.version];if(v===void 0)throw Error(`Invalid UUID version: "${def.version}"`);def.pattern??=uuid(v)}else def.pattern??=uuid();$ZodStringFormat.init(inst,def)}),$ZodEmail=$constructor(`$ZodEmail`,(inst,def)=>{def.pattern??=email,$ZodStringFormat.init(inst,def)}),$ZodURL=$constructor(`$ZodURL`,(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{try{let trimmed=payload.value.trim();if(!def.normalize&&def.protocol?.source===httpProtocol.source&&!/^https?:\/\//i.test(trimmed)){payload.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:payload.value,inst,continue:!def.abort});return}let url=new URL(trimmed);def.hostname&&(def.hostname.lastIndex=0,def.hostname.test(url.hostname)||payload.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:def.hostname.source,input:payload.value,inst,continue:!def.abort})),def.protocol&&(def.protocol.lastIndex=0,def.protocol.test(url.protocol.endsWith(`:`)?url.protocol.slice(0,-1):url.protocol)||payload.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:def.protocol.source,input:payload.value,inst,continue:!def.abort})),def.normalize?payload.value=url.href:payload.value=trimmed;return}catch{payload.issues.push({code:`invalid_format`,format:`url`,input:payload.value,inst,continue:!def.abort})}}}),$ZodEmoji=$constructor(`$ZodEmoji`,(inst,def)=>{def.pattern??=emoji(),$ZodStringFormat.init(inst,def)}),$ZodNanoID=$constructor(`$ZodNanoID`,(inst,def)=>{def.pattern??=nanoid,$ZodStringFormat.init(inst,def)}),$ZodCUID=$constructor(`$ZodCUID`,(inst,def)=>{def.pattern??=cuid,$ZodStringFormat.init(inst,def)}),$ZodCUID2=$constructor(`$ZodCUID2`,(inst,def)=>{def.pattern??=cuid2,$ZodStringFormat.init(inst,def)}),$ZodULID=$constructor(`$ZodULID`,(inst,def)=>{def.pattern??=ulid,$ZodStringFormat.init(inst,def)}),$ZodXID=$constructor(`$ZodXID`,(inst,def)=>{def.pattern??=xid,$ZodStringFormat.init(inst,def)}),$ZodKSUID=$constructor(`$ZodKSUID`,(inst,def)=>{def.pattern??=ksuid,$ZodStringFormat.init(inst,def)}),$ZodISODateTime=$constructor(`$ZodISODateTime`,(inst,def)=>{def.pattern??=datetime$1(def),$ZodStringFormat.init(inst,def)}),$ZodISODate=$constructor(`$ZodISODate`,(inst,def)=>{def.pattern??=date$1,$ZodStringFormat.init(inst,def)}),$ZodISOTime=$constructor(`$ZodISOTime`,(inst,def)=>{def.pattern??=time$1(def),$ZodStringFormat.init(inst,def)}),$ZodISODuration=$constructor(`$ZodISODuration`,(inst,def)=>{def.pattern??=duration$1,$ZodStringFormat.init(inst,def)}),$ZodIPv4=$constructor(`$ZodIPv4`,(inst,def)=>{def.pattern??=ipv4,$ZodStringFormat.init(inst,def),inst._zod.bag.format=`ipv4`}),$ZodIPv6=$constructor(`$ZodIPv6`,(inst,def)=>{def.pattern??=ipv6,$ZodStringFormat.init(inst,def),inst._zod.bag.format=`ipv6`,inst._zod.check=payload=>{try{new URL(`http://[${payload.value}]`)}catch{payload.issues.push({code:`invalid_format`,format:`ipv6`,input:payload.value,inst,continue:!def.abort})}}}),$ZodCIDRv4=$constructor(`$ZodCIDRv4`,(inst,def)=>{def.pattern??=cidrv4,$ZodStringFormat.init(inst,def)}),$ZodCIDRv6=$constructor(`$ZodCIDRv6`,(inst,def)=>{def.pattern??=cidrv6,$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{let parts=payload.value.split(`/`);try{if(parts.length!==2)throw Error();let[address,prefix]=parts;if(!prefix)throw Error();let prefixNum=Number(prefix);if(`${prefixNum}`!==prefix||prefixNum<0||prefixNum>128)throw Error();new URL(`http://[${address}]`)}catch{payload.issues.push({code:`invalid_format`,format:`cidrv6`,input:payload.value,inst,continue:!def.abort})}}});function isValidBase64(data){if(data===``)return!0;if(/\s/.test(data)||data.length%4!=0)return!1;try{return atob(data),!0}catch{return!1}}const $ZodBase64=$constructor(`$ZodBase64`,(inst,def)=>{def.pattern??=base64,$ZodStringFormat.init(inst,def),inst._zod.bag.contentEncoding=`base64`,inst._zod.check=payload=>{isValidBase64(payload.value)||payload.issues.push({code:`invalid_format`,format:`base64`,input:payload.value,inst,continue:!def.abort})}});function isValidBase64URL(data){if(!base64url.test(data))return!1;let base64=data.replace(/[-_]/g,c=>c===`-`?`+`:`/`);return isValidBase64(base64.padEnd(Math.ceil(base64.length/4)*4,`=`))}const $ZodBase64URL=$constructor(`$ZodBase64URL`,(inst,def)=>{def.pattern??=base64url,$ZodStringFormat.init(inst,def),inst._zod.bag.contentEncoding=`base64url`,inst._zod.check=payload=>{isValidBase64URL(payload.value)||payload.issues.push({code:`invalid_format`,format:`base64url`,input:payload.value,inst,continue:!def.abort})}}),$ZodE164=$constructor(`$ZodE164`,(inst,def)=>{def.pattern??=e164,$ZodStringFormat.init(inst,def)});function isValidJWT(token,algorithm=null){try{let tokensParts=token.split(`.`);if(tokensParts.length!==3)return!1;let[header]=tokensParts;if(!header)return!1;let parsedHeader=JSON.parse(atob(header));return!(`typ`in parsedHeader&&parsedHeader?.typ!==`JWT`||!parsedHeader.alg||algorithm&&(!(`alg`in parsedHeader)||parsedHeader.alg!==algorithm))}catch{return!1}}const $ZodJWT=$constructor(`$ZodJWT`,(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidJWT(payload.value,def.alg)||payload.issues.push({code:`invalid_format`,format:`jwt`,input:payload.value,inst,continue:!def.abort})}});function handleArrayResult(result,final,index){result.issues.length&&final.issues.push(...prefixIssues(index,result.issues)),final.value[index]=result.value}const $ZodArray=$constructor(`$ZodArray`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!Array.isArray(input))return payload.issues.push({expected:`array`,code:`invalid_type`,input,inst}),payload;payload.value=Array(input.length);let proms=[];for(let i=0;i<input.length;i++){let item=input[i],result=def.element._zod.run({value:item,issues:[]},ctx);result instanceof Promise?proms.push(result.then(result=>handleArrayResult(result,payload,i))):handleArrayResult(result,payload,i)}return proms.length?Promise.all(proms).then(()=>payload):payload}});function handleUnionResults(results,final,inst,ctx){for(let result of results)if(result.issues.length===0)return final.value=result.value,final;let nonaborted=results.filter(r=>!aborted(r));return nonaborted.length===1?(final.value=nonaborted[0].value,nonaborted[0]):(final.issues.push({code:`invalid_union`,input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}),final)}const $ZodUnion=$constructor(`$ZodUnion`,(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,`optin`,()=>def.options.some(o=>o._zod.optin===`optional`)?`optional`:void 0),defineLazy(inst._zod,`optout`,()=>def.options.some(o=>o._zod.optout===`optional`)?`optional`:void 0),defineLazy(inst._zod,`values`,()=>{if(def.options.every(o=>o._zod.values))return new Set(def.options.flatMap(option=>Array.from(option._zod.values)))}),defineLazy(inst._zod,`pattern`,()=>{if(def.options.every(o=>o._zod.pattern)){let patterns=def.options.map(o=>o._zod.pattern);return RegExp(`^(${patterns.map(p=>cleanRegex(p.source)).join(`|`)})$`)}});let first=def.options.length===1?def.options[0]._zod.run:null;inst._zod.parse=(payload,ctx)=>{if(first)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)results.push(result),async=!0;else{if(result.issues.length===0)return result;results.push(result)}}return async?Promise.all(results).then(results=>handleUnionResults(results,payload,inst,ctx)):handleUnionResults(results,payload,inst,ctx)}}),$ZodIntersection=$constructor(`$ZodIntersection`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value,left=def.left._zod.run({value:input,issues:[]},ctx),right=def.right._zod.run({value:input,issues:[]},ctx);return left instanceof Promise||right instanceof Promise?Promise.all([left,right]).then(([left,right])=>handleIntersectionResults(payload,left,right)):handleIntersectionResults(payload,left,right)}});function mergeValues(a,b){if(a===b||a instanceof Date&&b instanceof Date&&+a==+b)return{valid:!0,data:a};if(isPlainObject(a)&&isPlainObject(b)){let bKeys=Object.keys(b),sharedKeys=Object.keys(a).filter(key=>bKeys.indexOf(key)!==-1),newObj={...a,...b};for(let key of sharedKeys){let sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[key,...sharedValue.mergeErrorPath]};newObj[key]=sharedValue.data}return{valid:!0,data:newObj}}if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return{valid:!1,mergeErrorPath:[]};let newArray=[];for(let index=0;index<a.length;index++){let itemA=a[index],itemB=b[index],sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[index,...sharedValue.mergeErrorPath]};newArray.push(sharedValue.data)}return{valid:!0,data:newArray}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(result,left,right){let unrecKeys=new Map,unrecIssue;for(let iss of left.issues)if(iss.code===`unrecognized_keys`){unrecIssue??=iss;for(let k of iss.keys)unrecKeys.has(k)||unrecKeys.set(k,{}),unrecKeys.get(k).l=!0}else result.issues.push(iss);for(let iss of right.issues)if(iss.code===`unrecognized_keys`)for(let k of iss.keys)unrecKeys.has(k)||unrecKeys.set(k,{}),unrecKeys.get(k).r=!0;else result.issues.push(iss);let bothKeys=[...unrecKeys].filter(([,f])=>f.l&&f.r).map(([k])=>k);if(bothKeys.length&&unrecIssue&&result.issues.push({...unrecIssue,keys:bothKeys}),aborted(result))return result;let merged=mergeValues(left.value,right.value);if(!merged.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);return result.value=merged.data,result}const $ZodTransform=$constructor(`$ZodTransform`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin=`optional`,inst._zod.parse=(payload,ctx)=>{if(ctx.direction===`backward`)throw new $ZodEncodeError(inst.constructor.name);let _out=def.transform(payload.value,payload);if(ctx.async)return(_out instanceof Promise?_out:Promise.resolve(_out)).then(output=>(payload.value=output,payload.fallback=!0,payload));if(_out instanceof Promise)throw new $ZodAsyncError;return payload.value=_out,payload.fallback=!0,payload}});function handleOptionalResult(result,input){return input===void 0&&(result.issues.length||result.fallback)?{issues:[],value:void 0}:result}const $ZodOptional=$constructor(`$ZodOptional`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin=`optional`,inst._zod.optout=`optional`,defineLazy(inst._zod,`values`,()=>def.innerType._zod.values?new Set([...def.innerType._zod.values,void 0]):void 0),defineLazy(inst._zod,`pattern`,()=>{let pattern=def.innerType._zod.pattern;return pattern?RegExp(`^(${cleanRegex(pattern.source)})?$`):void 0}),inst._zod.parse=(payload,ctx)=>{if(def.innerType._zod.optin===`optional`){let input=payload.value,result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(r=>handleOptionalResult(r,input)):handleOptionalResult(result,input)}return payload.value===void 0?payload:def.innerType._zod.run(payload,ctx)}}),$ZodExactOptional=$constructor(`$ZodExactOptional`,(inst,def)=>{$ZodOptional.init(inst,def),defineLazy(inst._zod,`values`,()=>def.innerType._zod.values),defineLazy(inst._zod,`pattern`,()=>def.innerType._zod.pattern),inst._zod.parse=(payload,ctx)=>def.innerType._zod.run(payload,ctx)}),$ZodNullable=$constructor(`$ZodNullable`,(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,`optin`,()=>def.innerType._zod.optin),defineLazy(inst._zod,`optout`,()=>def.innerType._zod.optout),defineLazy(inst._zod,`pattern`,()=>{let pattern=def.innerType._zod.pattern;return pattern?RegExp(`^(${cleanRegex(pattern.source)}|null)$`):void 0}),defineLazy(inst._zod,`values`,()=>def.innerType._zod.values?new Set([...def.innerType._zod.values,null]):void 0),inst._zod.parse=(payload,ctx)=>payload.value===null?payload:def.innerType._zod.run(payload,ctx)}),$ZodDefault=$constructor(`$ZodDefault`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin=`optional`,defineLazy(inst._zod,`values`,()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction===`backward`)return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)return payload.value=def.defaultValue,payload;let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result=>handleDefaultResult(result,def)):handleDefaultResult(result,def)}});function handleDefaultResult(payload,def){return payload.value===void 0&&(payload.value=def.defaultValue),payload}const $ZodPrefault=$constructor(`$ZodPrefault`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin=`optional`,defineLazy(inst._zod,`values`,()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>(ctx.direction===`backward`||payload.value===void 0&&(payload.value=def.defaultValue),def.innerType._zod.run(payload,ctx))}),$ZodNonOptional=$constructor(`$ZodNonOptional`,(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,`values`,()=>{let v=def.innerType._zod.values;return v?new Set([...v].filter(x=>x!==void 0)):void 0}),inst._zod.parse=(payload,ctx)=>{let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result=>handleNonOptionalResult(result,inst)):handleNonOptionalResult(result,inst)}});function handleNonOptionalResult(payload,inst){return!payload.issues.length&&payload.value===void 0&&payload.issues.push({code:`invalid_type`,expected:`nonoptional`,input:payload.value,inst}),payload}const $ZodCatch=$constructor(`$ZodCatch`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin=`optional`,defineLazy(inst._zod,`optout`,()=>def.innerType._zod.optout),defineLazy(inst._zod,`values`,()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction===`backward`)return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result=>(payload.value=result.value,result.issues.length&&(payload.value=def.catchValue({...payload,error:{issues:result.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[],payload.fallback=!0),payload)):(payload.value=result.value,result.issues.length&&(payload.value=def.catchValue({...payload,error:{issues:result.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[],payload.fallback=!0),payload)}}),$ZodPipe=$constructor(`$ZodPipe`,(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,`values`,()=>def.in._zod.values),defineLazy(inst._zod,`optin`,()=>def.in._zod.optin),defineLazy(inst._zod,`optout`,()=>def.out._zod.optout),defineLazy(inst._zod,`propValues`,()=>def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if(ctx.direction===`backward`){let right=def.out._zod.run(payload,ctx);return right instanceof Promise?right.then(right=>handlePipeResult(right,def.in,ctx)):handlePipeResult(right,def.in,ctx)}let left=def.in._zod.run(payload,ctx);return left instanceof Promise?left.then(left=>handlePipeResult(left,def.out,ctx)):handlePipeResult(left,def.out,ctx)}});function handlePipeResult(left,next,ctx){return left.issues.length?(left.aborted=!0,left):next._zod.run({value:left.value,issues:left.issues,fallback:left.fallback},ctx)}const $ZodReadonly=$constructor(`$ZodReadonly`,(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,`propValues`,()=>def.innerType._zod.propValues),defineLazy(inst._zod,`values`,()=>def.innerType._zod.values),defineLazy(inst._zod,`optin`,()=>def.innerType?._zod?.optin),defineLazy(inst._zod,`optout`,()=>def.innerType?._zod?.optout),inst._zod.parse=(payload,ctx)=>{if(ctx.direction===`backward`)return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(handleReadonlyResult):handleReadonlyResult(result)}});function handleReadonlyResult(payload){return payload.value=Object.freeze(payload.value),payload}const $ZodCustom=$constructor(`$ZodCustom`,(inst,def)=>{$ZodCheck.init(inst,def),$ZodType.init(inst,def),inst._zod.parse=(payload,_)=>payload,inst._zod.check=payload=>{let input=payload.value,r=def.fn(input);if(r instanceof Promise)return r.then(r=>handleRefineResult(r,payload,input,inst));handleRefineResult(r,payload,input,inst)}});function handleRefineResult(result,payload,input,inst){if(!result){let _iss={code:`custom`,input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};inst._zod.def.params&&(_iss.params=inst._zod.def.params),payload.issues.push(issue(_iss))}}var _a,$ZodRegistry=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(schema,..._meta){let meta=_meta[0];return this._map.set(schema,meta),meta&&typeof meta==`object`&&`id`in meta&&this._idmap.set(meta.id,schema),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(schema){let meta=this._map.get(schema);return meta&&typeof meta==`object`&&`id`in meta&&this._idmap.delete(meta.id),this._map.delete(schema),this}get(schema){let p=schema._zod.parent;if(p){let pm={...this.get(p)??{}};delete pm.id;let f={...pm,...this._map.get(schema)};return Object.keys(f).length?f:void 0}return this._map.get(schema)}has(schema){return this._map.has(schema)}};function registry(){return new $ZodRegistry}(_a=globalThis).__zod_globalRegistry??(_a.__zod_globalRegistry=registry());const globalRegistry=globalThis.__zod_globalRegistry;function _string(Class,params){return new Class({type:`string`,...normalizeParams(params)})}function _email(Class,params){return new Class({type:`string`,format:`email`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _guid(Class,params){return new Class({type:`string`,format:`guid`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _uuid(Class,params){return new Class({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _uuidv4(Class,params){return new Class({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...normalizeParams(params)})}function _uuidv6(Class,params){return new Class({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...normalizeParams(params)})}function _uuidv7(Class,params){return new Class({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...normalizeParams(params)})}function _url(Class,params){return new Class({type:`string`,format:`url`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _emoji(Class,params){return new Class({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _nanoid(Class,params){return new Class({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _cuid(Class,params){return new Class({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _cuid2(Class,params){return new Class({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _ulid(Class,params){return new Class({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _xid(Class,params){return new Class({type:`string`,format:`xid`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _ksuid(Class,params){return new Class({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _ipv4(Class,params){return new Class({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _ipv6(Class,params){return new Class({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _cidrv4(Class,params){return new Class({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _cidrv6(Class,params){return new Class({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _base64(Class,params){return new Class({type:`string`,format:`base64`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _base64url(Class,params){return new Class({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _e164(Class,params){return new Class({type:`string`,format:`e164`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _jwt(Class,params){return new Class({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _isoDateTime(Class,params){return new Class({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...normalizeParams(params)})}function _isoDate(Class,params){return new Class({type:`string`,format:`date`,check:`string_format`,...normalizeParams(params)})}function _isoTime(Class,params){return new Class({type:`string`,format:`time`,check:`string_format`,precision:null,...normalizeParams(params)})}function _isoDuration(Class,params){return new Class({type:`string`,format:`duration`,check:`string_format`,...normalizeParams(params)})}function _maxLength(maximum,params){return new $ZodCheckMaxLength({check:`max_length`,...normalizeParams(params),maximum})}function _minLength(minimum,params){return new $ZodCheckMinLength({check:`min_length`,...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:`length_equals`,...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:`string_format`,format:`regex`,...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:`string_format`,format:`lowercase`,...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:`string_format`,format:`uppercase`,...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:`string_format`,format:`includes`,...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:`string_format`,format:`starts_with`,...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:`string_format`,format:`ends_with`,...normalizeParams(params),suffix})}function _overwrite(tx){return new $ZodCheckOverwrite({check:`overwrite`,tx})}function _normalize(form){return _overwrite(input=>input.normalize(form))}function _trim(){return _overwrite(input=>input.trim())}function _toLowerCase(){return _overwrite(input=>input.toLowerCase())}function _toUpperCase(){return _overwrite(input=>input.toUpperCase())}function _slugify(){return _overwrite(input=>slugify(input))}function _array(Class,element,params){return new Class({type:`array`,element,...normalizeParams(params)})}function _refine(Class,fn,_params){return new Class({type:`custom`,check:`custom`,fn,...normalizeParams(_params)})}function _superRefine(fn,params){let ch=_check(payload=>(payload.addIssue=issue$2=>{if(typeof issue$2==`string`)payload.issues.push(issue(issue$2,payload.value,ch._zod.def));else{let _issue=issue$2;_issue.fatal&&(_issue.continue=!1),_issue.code??=`custom`,_issue.input??=payload.value,_issue.inst??=ch,_issue.continue??=!ch._zod.def.abort,payload.issues.push(issue(_issue))}},fn(payload.value,payload)),params);return ch}function _check(fn,params){let ch=new $ZodCheck({check:`custom`,...normalizeParams(params)});return ch._zod.check=fn,ch}function initializeContext(params){let target=params?.target??`draft-2020-12`;return target===`draft-4`&&(target=`draft-04`),target===`draft-7`&&(target=`draft-07`),{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??`throw`,override:params?.override??(()=>{}),io:params?.io??`output`,counter:0,seen:new Map,cycles:params?.cycles??`ref`,reused:params?.reused??`inline`,external:params?.external??void 0}}function process$1(schema,ctx,_params={path:[],schemaPath:[]}){var _a;let def=schema._zod.def,seen=ctx.seen.get(schema);if(seen)return seen.count++,_params.schemaPath.includes(schema)&&(seen.cycle=_params.path),seen.schema;let result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema,result);let overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema)schema._zod.processJSONSchema(ctx,result.schema,params);else{let _json=result.schema,processor=ctx.processors[def.type];if(!processor)throw Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);processor(schema,ctx,_json,params)}let parent=schema._zod.parent;parent&&(result.ref||=parent,process$1(parent,ctx,params),ctx.seen.get(parent).isParent=!0)}let meta=ctx.metadataRegistry.get(schema);return meta&&Object.assign(result.schema,meta),ctx.io===`input`&&isTransforming(schema)&&(delete result.schema.examples,delete result.schema.default),ctx.io===`input`&&`_prefault`in result.schema&&((_a=result.schema).default??(_a.default=result.schema._prefault)),delete result.schema._prefault,ctx.seen.get(schema).schema}function extractDefs(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw Error(`Unprocessed schema. This is a bug in Zod.`);let idToSchema=new Map;for(let entry of ctx.seen.entries()){let id=ctx.metadataRegistry.get(entry[0])?.id;if(id){let existing=idToSchema.get(id);if(existing&&existing!==entry[0])throw Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);idToSchema.set(id,entry[0])}}let makeURI=entry=>{let defsSegment=ctx.target===`draft-2020-12`?`$defs`:`definitions`;if(ctx.external){let externalId=ctx.external.registry.get(entry[0])?.id,uriGenerator=ctx.external.uri??(id=>id);if(externalId)return{ref:uriGenerator(externalId)};let id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;return entry[1].defId=id,{defId:id,ref:`${uriGenerator(`__shared`)}#/${defsSegment}/${id}`}}if(entry[1]===root)return{ref:`#`};let defUriPrefix=`#/${defsSegment}/`,defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+defId}},extractToDef=entry=>{if(entry[1].schema.$ref)return;let seen=entry[1],{ref,defId}=makeURI(entry);seen.def={...seen.schema},defId&&(seen.defId=defId);let schema=seen.schema;for(let key in schema)delete schema[key];schema.$ref=ref};if(ctx.cycles===`throw`)for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.cycle)throw Error(`Cycle detected: #/${seen.cycle?.join(`/`)}/<root>
2183
6
 
2184
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
2185
- }
2186
- for (const entry of ctx.seen.entries()) {
2187
- const seen = entry[1];
2188
- if (schema === entry[0]) {
2189
- extractToDef(entry);
2190
- continue;
2191
- }
2192
- if (ctx.external) {
2193
- const ext = ctx.external.registry.get(entry[0])?.id;
2194
- if (schema !== entry[0] && ext) {
2195
- extractToDef(entry);
2196
- continue;
2197
- }
2198
- }
2199
- if (ctx.metadataRegistry.get(entry[0])?.id) {
2200
- extractToDef(entry);
2201
- continue;
2202
- }
2203
- if (seen.cycle) {
2204
- extractToDef(entry);
2205
- continue;
2206
- }
2207
- if (seen.count > 1) {
2208
- if (ctx.reused === "ref") {
2209
- extractToDef(entry);
2210
- continue;
2211
- }
2212
- }
2213
- }
2214
- }
2215
- function finalize(ctx, schema) {
2216
- const root = ctx.seen.get(schema);
2217
- if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
2218
- const flattenRef = (zodSchema) => {
2219
- const seen = ctx.seen.get(zodSchema);
2220
- if (seen.ref === null) return;
2221
- const schema = seen.def ?? seen.schema;
2222
- const _cached = { ...schema };
2223
- const ref = seen.ref;
2224
- seen.ref = null;
2225
- if (ref) {
2226
- flattenRef(ref);
2227
- const refSeen = ctx.seen.get(ref);
2228
- const refSchema = refSeen.schema;
2229
- if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
2230
- schema.allOf = schema.allOf ?? [];
2231
- schema.allOf.push(refSchema);
2232
- } else Object.assign(schema, refSchema);
2233
- Object.assign(schema, _cached);
2234
- if (zodSchema._zod.parent === ref) for (const key in schema) {
2235
- if (key === "$ref" || key === "allOf") continue;
2236
- if (!(key in _cached)) delete schema[key];
2237
- }
2238
- if (refSchema.$ref && refSeen.def) for (const key in schema) {
2239
- if (key === "$ref" || key === "allOf") continue;
2240
- if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) delete schema[key];
2241
- }
2242
- }
2243
- const parent = zodSchema._zod.parent;
2244
- if (parent && parent !== ref) {
2245
- flattenRef(parent);
2246
- const parentSeen = ctx.seen.get(parent);
2247
- if (parentSeen?.schema.$ref) {
2248
- schema.$ref = parentSeen.schema.$ref;
2249
- if (parentSeen.def) for (const key in schema) {
2250
- if (key === "$ref" || key === "allOf") continue;
2251
- if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) delete schema[key];
2252
- }
2253
- }
2254
- }
2255
- ctx.override({
2256
- zodSchema,
2257
- jsonSchema: schema,
2258
- path: seen.path ?? []
2259
- });
2260
- };
2261
- for (const entry of [...ctx.seen.entries()].reverse()) flattenRef(entry[0]);
2262
- const result = {};
2263
- if (ctx.target === "draft-2020-12") result.$schema = "https://json-schema.org/draft/2020-12/schema";
2264
- else if (ctx.target === "draft-07") result.$schema = "http://json-schema.org/draft-07/schema#";
2265
- else if (ctx.target === "draft-04") result.$schema = "http://json-schema.org/draft-04/schema#";
2266
- else if (ctx.target === "openapi-3.0") {}
2267
- if (ctx.external?.uri) {
2268
- const id = ctx.external.registry.get(schema)?.id;
2269
- if (!id) throw new Error("Schema is missing an `id` property");
2270
- result.$id = ctx.external.uri(id);
2271
- }
2272
- Object.assign(result, root.def ?? root.schema);
2273
- const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
2274
- if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id;
2275
- const defs = ctx.external?.defs ?? {};
2276
- for (const entry of ctx.seen.entries()) {
2277
- const seen = entry[1];
2278
- if (seen.def && seen.defId) {
2279
- if (seen.def.id === seen.defId) delete seen.def.id;
2280
- defs[seen.defId] = seen.def;
2281
- }
2282
- }
2283
- if (ctx.external) {} else if (Object.keys(defs).length > 0) if (ctx.target === "draft-2020-12") result.$defs = defs;
2284
- else result.definitions = defs;
2285
- try {
2286
- const finalized = JSON.parse(JSON.stringify(result));
2287
- Object.defineProperty(finalized, "~standard", {
2288
- value: {
2289
- ...schema["~standard"],
2290
- jsonSchema: {
2291
- input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
2292
- output: createStandardJSONSchemaMethod(schema, "output", ctx.processors)
2293
- }
2294
- },
2295
- enumerable: false,
2296
- writable: false
2297
- });
2298
- return finalized;
2299
- } catch (_err) {
2300
- throw new Error("Error converting schema to JSON.");
2301
- }
2302
- }
2303
- function isTransforming(_schema, _ctx) {
2304
- const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() };
2305
- if (ctx.seen.has(_schema)) return false;
2306
- ctx.seen.add(_schema);
2307
- const def = _schema._zod.def;
2308
- if (def.type === "transform") return true;
2309
- if (def.type === "array") return isTransforming(def.element, ctx);
2310
- if (def.type === "set") return isTransforming(def.valueType, ctx);
2311
- if (def.type === "lazy") return isTransforming(def.getter(), ctx);
2312
- if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") return isTransforming(def.innerType, ctx);
2313
- if (def.type === "intersection") return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
2314
- if (def.type === "record" || def.type === "map") return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
2315
- if (def.type === "pipe") {
2316
- if (_schema._zod.traits.has("$ZodCodec")) return true;
2317
- return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
2318
- }
2319
- if (def.type === "object") {
2320
- for (const key in def.shape) if (isTransforming(def.shape[key], ctx)) return true;
2321
- return false;
2322
- }
2323
- if (def.type === "union") {
2324
- for (const option of def.options) if (isTransforming(option, ctx)) return true;
2325
- return false;
2326
- }
2327
- if (def.type === "tuple") {
2328
- for (const item of def.items) if (isTransforming(item, ctx)) return true;
2329
- if (def.rest && isTransforming(def.rest, ctx)) return true;
2330
- return false;
2331
- }
2332
- return false;
2333
- }
2334
- /**
2335
- * Creates a toJSONSchema method for a schema instance.
2336
- * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.
2337
- */
2338
- const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
2339
- const ctx = initializeContext({
2340
- ...params,
2341
- processors
2342
- });
2343
- process$1(schema, ctx);
2344
- extractDefs(ctx, schema);
2345
- return finalize(ctx, schema);
2346
- };
2347
- const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
2348
- const { libraryOptions, target } = params ?? {};
2349
- const ctx = initializeContext({
2350
- ...libraryOptions ?? {},
2351
- target,
2352
- io,
2353
- processors
2354
- });
2355
- process$1(schema, ctx);
2356
- extractDefs(ctx, schema);
2357
- return finalize(ctx, schema);
2358
- };
2359
- //#endregion
2360
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js
2361
- const formatMap = {
2362
- guid: "uuid",
2363
- url: "uri",
2364
- datetime: "date-time",
2365
- json_string: "json-string",
2366
- regex: ""
2367
- };
2368
- const stringProcessor = (schema, ctx, _json, _params) => {
2369
- const json = _json;
2370
- json.type = "string";
2371
- const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag;
2372
- if (typeof minimum === "number") json.minLength = minimum;
2373
- if (typeof maximum === "number") json.maxLength = maximum;
2374
- if (format) {
2375
- json.format = formatMap[format] ?? format;
2376
- if (json.format === "") delete json.format;
2377
- if (format === "time") delete json.format;
2378
- }
2379
- if (contentEncoding) json.contentEncoding = contentEncoding;
2380
- if (patterns && patterns.size > 0) {
2381
- const regexes = [...patterns];
2382
- if (regexes.length === 1) json.pattern = regexes[0].source;
2383
- else if (regexes.length > 1) json.allOf = [...regexes.map((regex) => ({
2384
- ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
2385
- pattern: regex.source
2386
- }))];
2387
- }
2388
- };
2389
- const customProcessor = (_schema, ctx, _json, _params) => {
2390
- if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
2391
- };
2392
- const transformProcessor = (_schema, ctx, _json, _params) => {
2393
- if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
2394
- };
2395
- const arrayProcessor = (schema, ctx, _json, params) => {
2396
- const json = _json;
2397
- const def = schema._zod.def;
2398
- const { minimum, maximum } = schema._zod.bag;
2399
- if (typeof minimum === "number") json.minItems = minimum;
2400
- if (typeof maximum === "number") json.maxItems = maximum;
2401
- json.type = "array";
2402
- json.items = process$1(def.element, ctx, {
2403
- ...params,
2404
- path: [...params.path, "items"]
2405
- });
2406
- };
2407
- const unionProcessor = (schema, ctx, json, params) => {
2408
- const def = schema._zod.def;
2409
- const isExclusive = def.inclusive === false;
2410
- const options = def.options.map((x, i) => process$1(x, ctx, {
2411
- ...params,
2412
- path: [
2413
- ...params.path,
2414
- isExclusive ? "oneOf" : "anyOf",
2415
- i
2416
- ]
2417
- }));
2418
- if (isExclusive) json.oneOf = options;
2419
- else json.anyOf = options;
2420
- };
2421
- const intersectionProcessor = (schema, ctx, json, params) => {
2422
- const def = schema._zod.def;
2423
- const a = process$1(def.left, ctx, {
2424
- ...params,
2425
- path: [
2426
- ...params.path,
2427
- "allOf",
2428
- 0
2429
- ]
2430
- });
2431
- const b = process$1(def.right, ctx, {
2432
- ...params,
2433
- path: [
2434
- ...params.path,
2435
- "allOf",
2436
- 1
2437
- ]
2438
- });
2439
- const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
2440
- json.allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]];
2441
- };
2442
- const nullableProcessor = (schema, ctx, json, params) => {
2443
- const def = schema._zod.def;
2444
- const inner = process$1(def.innerType, ctx, params);
2445
- const seen = ctx.seen.get(schema);
2446
- if (ctx.target === "openapi-3.0") {
2447
- seen.ref = def.innerType;
2448
- json.nullable = true;
2449
- } else json.anyOf = [inner, { type: "null" }];
2450
- };
2451
- const nonoptionalProcessor = (schema, ctx, _json, params) => {
2452
- const def = schema._zod.def;
2453
- process$1(def.innerType, ctx, params);
2454
- const seen = ctx.seen.get(schema);
2455
- seen.ref = def.innerType;
2456
- };
2457
- const defaultProcessor = (schema, ctx, json, params) => {
2458
- const def = schema._zod.def;
2459
- process$1(def.innerType, ctx, params);
2460
- const seen = ctx.seen.get(schema);
2461
- seen.ref = def.innerType;
2462
- json.default = JSON.parse(JSON.stringify(def.defaultValue));
2463
- };
2464
- const prefaultProcessor = (schema, ctx, json, params) => {
2465
- const def = schema._zod.def;
2466
- process$1(def.innerType, ctx, params);
2467
- const seen = ctx.seen.get(schema);
2468
- seen.ref = def.innerType;
2469
- if (ctx.io === "input") json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
2470
- };
2471
- const catchProcessor = (schema, ctx, json, params) => {
2472
- const def = schema._zod.def;
2473
- process$1(def.innerType, ctx, params);
2474
- const seen = ctx.seen.get(schema);
2475
- seen.ref = def.innerType;
2476
- let catchValue;
2477
- try {
2478
- catchValue = def.catchValue(void 0);
2479
- } catch {
2480
- throw new Error("Dynamic catch values are not supported in JSON Schema");
2481
- }
2482
- json.default = catchValue;
2483
- };
2484
- const pipeProcessor = (schema, ctx, _json, params) => {
2485
- const def = schema._zod.def;
2486
- const inIsTransform = def.in._zod.traits.has("$ZodTransform");
2487
- const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
2488
- process$1(innerType, ctx, params);
2489
- const seen = ctx.seen.get(schema);
2490
- seen.ref = innerType;
2491
- };
2492
- const readonlyProcessor = (schema, ctx, json, params) => {
2493
- const def = schema._zod.def;
2494
- process$1(def.innerType, ctx, params);
2495
- const seen = ctx.seen.get(schema);
2496
- seen.ref = def.innerType;
2497
- json.readOnly = true;
2498
- };
2499
- const optionalProcessor = (schema, ctx, _json, params) => {
2500
- const def = schema._zod.def;
2501
- process$1(def.innerType, ctx, params);
2502
- const seen = ctx.seen.get(schema);
2503
- seen.ref = def.innerType;
2504
- };
2505
- //#endregion
2506
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/iso.js
2507
- const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
2508
- $ZodISODateTime.init(inst, def);
2509
- ZodStringFormat.init(inst, def);
2510
- });
2511
- function datetime(params) {
2512
- return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params);
2513
- }
2514
- const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => {
2515
- $ZodISODate.init(inst, def);
2516
- ZodStringFormat.init(inst, def);
2517
- });
2518
- function date(params) {
2519
- return /* @__PURE__ */ _isoDate(ZodISODate, params);
2520
- }
2521
- const ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => {
2522
- $ZodISOTime.init(inst, def);
2523
- ZodStringFormat.init(inst, def);
2524
- });
2525
- function time(params) {
2526
- return /* @__PURE__ */ _isoTime(ZodISOTime, params);
2527
- }
2528
- const ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => {
2529
- $ZodISODuration.init(inst, def);
2530
- ZodStringFormat.init(inst, def);
2531
- });
2532
- function duration(params) {
2533
- return /* @__PURE__ */ _isoDuration(ZodISODuration, params);
2534
- }
2535
- //#endregion
2536
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/errors.js
2537
- const initializer = (inst, issues) => {
2538
- $ZodError.init(inst, issues);
2539
- inst.name = "ZodError";
2540
- Object.defineProperties(inst, {
2541
- format: { value: (mapper) => formatError(inst, mapper) },
2542
- flatten: { value: (mapper) => flattenError(inst, mapper) },
2543
- addIssue: { value: (issue) => {
2544
- inst.issues.push(issue);
2545
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
2546
- } },
2547
- addIssues: { value: (issues) => {
2548
- inst.issues.push(...issues);
2549
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
2550
- } },
2551
- isEmpty: { get() {
2552
- return inst.issues.length === 0;
2553
- } }
2554
- });
2555
- };
2556
- const ZodRealError = /*@__PURE__*/ $constructor("ZodError", initializer, { Parent: Error });
2557
- //#endregion
2558
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/parse.js
2559
- const parse = /* @__PURE__ */ _parse(ZodRealError);
2560
- const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
2561
- const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
2562
- const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
2563
- const encode = /* @__PURE__ */ _encode(ZodRealError);
2564
- const decode = /* @__PURE__ */ _decode(ZodRealError);
2565
- const encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
2566
- const decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
2567
- const safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
2568
- const safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
2569
- const safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
2570
- const safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
2571
- //#endregion
2572
- //#region ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/schemas.js
2573
- const _installedGroups = /* @__PURE__ */ new WeakMap();
2574
- function _installLazyMethods(inst, group, methods) {
2575
- const proto = Object.getPrototypeOf(inst);
2576
- let installed = _installedGroups.get(proto);
2577
- if (!installed) {
2578
- installed = /* @__PURE__ */ new Set();
2579
- _installedGroups.set(proto, installed);
2580
- }
2581
- if (installed.has(group)) return;
2582
- installed.add(group);
2583
- for (const key in methods) {
2584
- const fn = methods[key];
2585
- Object.defineProperty(proto, key, {
2586
- configurable: true,
2587
- enumerable: false,
2588
- get() {
2589
- const bound = fn.bind(this);
2590
- Object.defineProperty(this, key, {
2591
- configurable: true,
2592
- writable: true,
2593
- enumerable: true,
2594
- value: bound
2595
- });
2596
- return bound;
2597
- },
2598
- set(v) {
2599
- Object.defineProperty(this, key, {
2600
- configurable: true,
2601
- writable: true,
2602
- enumerable: true,
2603
- value: v
2604
- });
2605
- }
2606
- });
2607
- }
2608
- }
2609
- const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
2610
- $ZodType.init(inst, def);
2611
- Object.assign(inst["~standard"], { jsonSchema: {
2612
- input: createStandardJSONSchemaMethod(inst, "input"),
2613
- output: createStandardJSONSchemaMethod(inst, "output")
2614
- } });
2615
- inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
2616
- inst.def = def;
2617
- inst.type = def.type;
2618
- Object.defineProperty(inst, "_def", { value: def });
2619
- inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
2620
- inst.safeParse = (data, params) => safeParse(inst, data, params);
2621
- inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
2622
- inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
2623
- inst.spa = inst.safeParseAsync;
2624
- inst.encode = (data, params) => encode(inst, data, params);
2625
- inst.decode = (data, params) => decode(inst, data, params);
2626
- inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
2627
- inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
2628
- inst.safeEncode = (data, params) => safeEncode(inst, data, params);
2629
- inst.safeDecode = (data, params) => safeDecode(inst, data, params);
2630
- inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params);
2631
- inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params);
2632
- _installLazyMethods(inst, "ZodType", {
2633
- check(...chks) {
2634
- const def = this.def;
2635
- return this.clone(mergeDefs(def, { checks: [...def.checks ?? [], ...chks.map((ch) => typeof ch === "function" ? { _zod: {
2636
- check: ch,
2637
- def: { check: "custom" },
2638
- onattach: []
2639
- } } : ch)] }), { parent: true });
2640
- },
2641
- with(...chks) {
2642
- return this.check(...chks);
2643
- },
2644
- clone(def, params) {
2645
- return clone(this, def, params);
2646
- },
2647
- brand() {
2648
- return this;
2649
- },
2650
- register(reg, meta) {
2651
- reg.add(this, meta);
2652
- return this;
2653
- },
2654
- refine(check, params) {
2655
- return this.check(refine(check, params));
2656
- },
2657
- superRefine(refinement, params) {
2658
- return this.check(superRefine(refinement, params));
2659
- },
2660
- overwrite(fn) {
2661
- return this.check(/* @__PURE__ */ _overwrite(fn));
2662
- },
2663
- optional() {
2664
- return optional(this);
2665
- },
2666
- exactOptional() {
2667
- return exactOptional(this);
2668
- },
2669
- nullable() {
2670
- return nullable(this);
2671
- },
2672
- nullish() {
2673
- return optional(nullable(this));
2674
- },
2675
- nonoptional(params) {
2676
- return nonoptional(this, params);
2677
- },
2678
- array() {
2679
- return array(this);
2680
- },
2681
- or(arg) {
2682
- return union([this, arg]);
2683
- },
2684
- and(arg) {
2685
- return intersection(this, arg);
2686
- },
2687
- transform(tx) {
2688
- return pipe(this, transform(tx));
2689
- },
2690
- default(d) {
2691
- return _default(this, d);
2692
- },
2693
- prefault(d) {
2694
- return prefault(this, d);
2695
- },
2696
- catch(params) {
2697
- return _catch(this, params);
2698
- },
2699
- pipe(target) {
2700
- return pipe(this, target);
2701
- },
2702
- readonly() {
2703
- return readonly(this);
2704
- },
2705
- describe(description) {
2706
- const cl = this.clone();
2707
- globalRegistry.add(cl, { description });
2708
- return cl;
2709
- },
2710
- meta(...args) {
2711
- if (args.length === 0) return globalRegistry.get(this);
2712
- const cl = this.clone();
2713
- globalRegistry.add(cl, args[0]);
2714
- return cl;
2715
- },
2716
- isOptional() {
2717
- return this.safeParse(void 0).success;
2718
- },
2719
- isNullable() {
2720
- return this.safeParse(null).success;
2721
- },
2722
- apply(fn) {
2723
- return fn(this);
2724
- }
2725
- });
2726
- Object.defineProperty(inst, "description", {
2727
- get() {
2728
- return globalRegistry.get(inst)?.description;
2729
- },
2730
- configurable: true
2731
- });
2732
- return inst;
2733
- });
2734
- /** @internal */
2735
- const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => {
2736
- $ZodString.init(inst, def);
2737
- ZodType.init(inst, def);
2738
- inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params);
2739
- const bag = inst._zod.bag;
2740
- inst.format = bag.format ?? null;
2741
- inst.minLength = bag.minimum ?? null;
2742
- inst.maxLength = bag.maximum ?? null;
2743
- _installLazyMethods(inst, "_ZodString", {
2744
- regex(...args) {
2745
- return this.check(/* @__PURE__ */ _regex(...args));
2746
- },
2747
- includes(...args) {
2748
- return this.check(/* @__PURE__ */ _includes(...args));
2749
- },
2750
- startsWith(...args) {
2751
- return this.check(/* @__PURE__ */ _startsWith(...args));
2752
- },
2753
- endsWith(...args) {
2754
- return this.check(/* @__PURE__ */ _endsWith(...args));
2755
- },
2756
- min(...args) {
2757
- return this.check(/* @__PURE__ */ _minLength(...args));
2758
- },
2759
- max(...args) {
2760
- return this.check(/* @__PURE__ */ _maxLength(...args));
2761
- },
2762
- length(...args) {
2763
- return this.check(/* @__PURE__ */ _length(...args));
2764
- },
2765
- nonempty(...args) {
2766
- return this.check(/* @__PURE__ */ _minLength(1, ...args));
2767
- },
2768
- lowercase(params) {
2769
- return this.check(/* @__PURE__ */ _lowercase(params));
2770
- },
2771
- uppercase(params) {
2772
- return this.check(/* @__PURE__ */ _uppercase(params));
2773
- },
2774
- trim() {
2775
- return this.check(/* @__PURE__ */ _trim());
2776
- },
2777
- normalize(...args) {
2778
- return this.check(/* @__PURE__ */ _normalize(...args));
2779
- },
2780
- toLowerCase() {
2781
- return this.check(/* @__PURE__ */ _toLowerCase());
2782
- },
2783
- toUpperCase() {
2784
- return this.check(/* @__PURE__ */ _toUpperCase());
2785
- },
2786
- slugify() {
2787
- return this.check(/* @__PURE__ */ _slugify());
2788
- }
2789
- });
2790
- });
2791
- const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => {
2792
- $ZodString.init(inst, def);
2793
- _ZodString.init(inst, def);
2794
- inst.email = (params) => inst.check(/* @__PURE__ */ _email(ZodEmail, params));
2795
- inst.url = (params) => inst.check(/* @__PURE__ */ _url(ZodURL, params));
2796
- inst.jwt = (params) => inst.check(/* @__PURE__ */ _jwt(ZodJWT, params));
2797
- inst.emoji = (params) => inst.check(/* @__PURE__ */ _emoji(ZodEmoji, params));
2798
- inst.guid = (params) => inst.check(/* @__PURE__ */ _guid(ZodGUID, params));
2799
- inst.uuid = (params) => inst.check(/* @__PURE__ */ _uuid(ZodUUID, params));
2800
- inst.uuidv4 = (params) => inst.check(/* @__PURE__ */ _uuidv4(ZodUUID, params));
2801
- inst.uuidv6 = (params) => inst.check(/* @__PURE__ */ _uuidv6(ZodUUID, params));
2802
- inst.uuidv7 = (params) => inst.check(/* @__PURE__ */ _uuidv7(ZodUUID, params));
2803
- inst.nanoid = (params) => inst.check(/* @__PURE__ */ _nanoid(ZodNanoID, params));
2804
- inst.guid = (params) => inst.check(/* @__PURE__ */ _guid(ZodGUID, params));
2805
- inst.cuid = (params) => inst.check(/* @__PURE__ */ _cuid(ZodCUID, params));
2806
- inst.cuid2 = (params) => inst.check(/* @__PURE__ */ _cuid2(ZodCUID2, params));
2807
- inst.ulid = (params) => inst.check(/* @__PURE__ */ _ulid(ZodULID, params));
2808
- inst.base64 = (params) => inst.check(/* @__PURE__ */ _base64(ZodBase64, params));
2809
- inst.base64url = (params) => inst.check(/* @__PURE__ */ _base64url(ZodBase64URL, params));
2810
- inst.xid = (params) => inst.check(/* @__PURE__ */ _xid(ZodXID, params));
2811
- inst.ksuid = (params) => inst.check(/* @__PURE__ */ _ksuid(ZodKSUID, params));
2812
- inst.ipv4 = (params) => inst.check(/* @__PURE__ */ _ipv4(ZodIPv4, params));
2813
- inst.ipv6 = (params) => inst.check(/* @__PURE__ */ _ipv6(ZodIPv6, params));
2814
- inst.cidrv4 = (params) => inst.check(/* @__PURE__ */ _cidrv4(ZodCIDRv4, params));
2815
- inst.cidrv6 = (params) => inst.check(/* @__PURE__ */ _cidrv6(ZodCIDRv6, params));
2816
- inst.e164 = (params) => inst.check(/* @__PURE__ */ _e164(ZodE164, params));
2817
- inst.datetime = (params) => inst.check(datetime(params));
2818
- inst.date = (params) => inst.check(date(params));
2819
- inst.time = (params) => inst.check(time(params));
2820
- inst.duration = (params) => inst.check(duration(params));
2821
- });
2822
- function string(params) {
2823
- return /* @__PURE__ */ _string(ZodString, params);
2824
- }
2825
- const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => {
2826
- $ZodStringFormat.init(inst, def);
2827
- _ZodString.init(inst, def);
2828
- });
2829
- const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => {
2830
- $ZodEmail.init(inst, def);
2831
- ZodStringFormat.init(inst, def);
2832
- });
2833
- const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => {
2834
- $ZodGUID.init(inst, def);
2835
- ZodStringFormat.init(inst, def);
2836
- });
2837
- const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => {
2838
- $ZodUUID.init(inst, def);
2839
- ZodStringFormat.init(inst, def);
2840
- });
2841
- const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => {
2842
- $ZodURL.init(inst, def);
2843
- ZodStringFormat.init(inst, def);
2844
- });
2845
- const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => {
2846
- $ZodEmoji.init(inst, def);
2847
- ZodStringFormat.init(inst, def);
2848
- });
2849
- const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => {
2850
- $ZodNanoID.init(inst, def);
2851
- ZodStringFormat.init(inst, def);
2852
- });
2853
- /**
2854
- * @deprecated CUID v1 is deprecated by its authors due to information leakage
2855
- * (timestamps embedded in the id). Use {@link ZodCUID2} instead.
2856
- * See https://github.com/paralleldrive/cuid.
2857
- */
2858
- const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => {
2859
- $ZodCUID.init(inst, def);
2860
- ZodStringFormat.init(inst, def);
2861
- });
2862
- const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => {
2863
- $ZodCUID2.init(inst, def);
2864
- ZodStringFormat.init(inst, def);
2865
- });
2866
- const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => {
2867
- $ZodULID.init(inst, def);
2868
- ZodStringFormat.init(inst, def);
2869
- });
2870
- const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => {
2871
- $ZodXID.init(inst, def);
2872
- ZodStringFormat.init(inst, def);
2873
- });
2874
- const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => {
2875
- $ZodKSUID.init(inst, def);
2876
- ZodStringFormat.init(inst, def);
2877
- });
2878
- const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => {
2879
- $ZodIPv4.init(inst, def);
2880
- ZodStringFormat.init(inst, def);
2881
- });
2882
- const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => {
2883
- $ZodIPv6.init(inst, def);
2884
- ZodStringFormat.init(inst, def);
2885
- });
2886
- const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => {
2887
- $ZodCIDRv4.init(inst, def);
2888
- ZodStringFormat.init(inst, def);
2889
- });
2890
- const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => {
2891
- $ZodCIDRv6.init(inst, def);
2892
- ZodStringFormat.init(inst, def);
2893
- });
2894
- const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => {
2895
- $ZodBase64.init(inst, def);
2896
- ZodStringFormat.init(inst, def);
2897
- });
2898
- const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => {
2899
- $ZodBase64URL.init(inst, def);
2900
- ZodStringFormat.init(inst, def);
2901
- });
2902
- const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => {
2903
- $ZodE164.init(inst, def);
2904
- ZodStringFormat.init(inst, def);
2905
- });
2906
- const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => {
2907
- $ZodJWT.init(inst, def);
2908
- ZodStringFormat.init(inst, def);
2909
- });
2910
- const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => {
2911
- $ZodArray.init(inst, def);
2912
- ZodType.init(inst, def);
2913
- inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params);
2914
- inst.element = def.element;
2915
- _installLazyMethods(inst, "ZodArray", {
2916
- min(n, params) {
2917
- return this.check(/* @__PURE__ */ _minLength(n, params));
2918
- },
2919
- nonempty(params) {
2920
- return this.check(/* @__PURE__ */ _minLength(1, params));
2921
- },
2922
- max(n, params) {
2923
- return this.check(/* @__PURE__ */ _maxLength(n, params));
2924
- },
2925
- length(n, params) {
2926
- return this.check(/* @__PURE__ */ _length(n, params));
2927
- },
2928
- unwrap() {
2929
- return this.element;
2930
- }
2931
- });
2932
- });
2933
- function array(element, params) {
2934
- return /* @__PURE__ */ _array(ZodArray, element, params);
2935
- }
2936
- const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => {
2937
- $ZodUnion.init(inst, def);
2938
- ZodType.init(inst, def);
2939
- inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params);
2940
- inst.options = def.options;
2941
- });
2942
- function union(options, params) {
2943
- return new ZodUnion({
2944
- type: "union",
2945
- options,
2946
- ...normalizeParams(params)
2947
- });
2948
- }
2949
- const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => {
2950
- $ZodIntersection.init(inst, def);
2951
- ZodType.init(inst, def);
2952
- inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params);
2953
- });
2954
- function intersection(left, right) {
2955
- return new ZodIntersection({
2956
- type: "intersection",
2957
- left,
2958
- right
2959
- });
2960
- }
2961
- const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => {
2962
- $ZodTransform.init(inst, def);
2963
- ZodType.init(inst, def);
2964
- inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params);
2965
- inst._zod.parse = (payload, _ctx) => {
2966
- if (_ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name);
2967
- payload.addIssue = (issue$1) => {
2968
- if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, def));
2969
- else {
2970
- const _issue = issue$1;
2971
- if (_issue.fatal) _issue.continue = false;
2972
- _issue.code ?? (_issue.code = "custom");
2973
- _issue.input ?? (_issue.input = payload.value);
2974
- _issue.inst ?? (_issue.inst = inst);
2975
- payload.issues.push(issue(_issue));
2976
- }
2977
- };
2978
- const output = def.transform(payload.value, payload);
2979
- if (output instanceof Promise) return output.then((output) => {
2980
- payload.value = output;
2981
- payload.fallback = true;
2982
- return payload;
2983
- });
2984
- payload.value = output;
2985
- payload.fallback = true;
2986
- return payload;
2987
- };
2988
- });
2989
- function transform(fn) {
2990
- return new ZodTransform({
2991
- type: "transform",
2992
- transform: fn
2993
- });
2994
- }
2995
- const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => {
2996
- $ZodOptional.init(inst, def);
2997
- ZodType.init(inst, def);
2998
- inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
2999
- inst.unwrap = () => inst._zod.def.innerType;
3000
- });
3001
- function optional(innerType) {
3002
- return new ZodOptional({
3003
- type: "optional",
3004
- innerType
3005
- });
3006
- }
3007
- const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => {
3008
- $ZodExactOptional.init(inst, def);
3009
- ZodType.init(inst, def);
3010
- inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
3011
- inst.unwrap = () => inst._zod.def.innerType;
3012
- });
3013
- function exactOptional(innerType) {
3014
- return new ZodExactOptional({
3015
- type: "optional",
3016
- innerType
3017
- });
3018
- }
3019
- const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => {
3020
- $ZodNullable.init(inst, def);
3021
- ZodType.init(inst, def);
3022
- inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params);
3023
- inst.unwrap = () => inst._zod.def.innerType;
3024
- });
3025
- function nullable(innerType) {
3026
- return new ZodNullable({
3027
- type: "nullable",
3028
- innerType
3029
- });
3030
- }
3031
- const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => {
3032
- $ZodDefault.init(inst, def);
3033
- ZodType.init(inst, def);
3034
- inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params);
3035
- inst.unwrap = () => inst._zod.def.innerType;
3036
- inst.removeDefault = inst.unwrap;
3037
- });
3038
- function _default(innerType, defaultValue) {
3039
- return new ZodDefault({
3040
- type: "default",
3041
- innerType,
3042
- get defaultValue() {
3043
- return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
3044
- }
3045
- });
3046
- }
3047
- const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => {
3048
- $ZodPrefault.init(inst, def);
3049
- ZodType.init(inst, def);
3050
- inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params);
3051
- inst.unwrap = () => inst._zod.def.innerType;
3052
- });
3053
- function prefault(innerType, defaultValue) {
3054
- return new ZodPrefault({
3055
- type: "prefault",
3056
- innerType,
3057
- get defaultValue() {
3058
- return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
3059
- }
3060
- });
3061
- }
3062
- const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => {
3063
- $ZodNonOptional.init(inst, def);
3064
- ZodType.init(inst, def);
3065
- inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params);
3066
- inst.unwrap = () => inst._zod.def.innerType;
3067
- });
3068
- function nonoptional(innerType, params) {
3069
- return new ZodNonOptional({
3070
- type: "nonoptional",
3071
- innerType,
3072
- ...normalizeParams(params)
3073
- });
3074
- }
3075
- const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => {
3076
- $ZodCatch.init(inst, def);
3077
- ZodType.init(inst, def);
3078
- inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params);
3079
- inst.unwrap = () => inst._zod.def.innerType;
3080
- inst.removeCatch = inst.unwrap;
3081
- });
3082
- function _catch(innerType, catchValue) {
3083
- return new ZodCatch({
3084
- type: "catch",
3085
- innerType,
3086
- catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
3087
- });
3088
- }
3089
- const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => {
3090
- $ZodPipe.init(inst, def);
3091
- ZodType.init(inst, def);
3092
- inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params);
3093
- inst.in = def.in;
3094
- inst.out = def.out;
3095
- });
3096
- function pipe(in_, out) {
3097
- return new ZodPipe({
3098
- type: "pipe",
3099
- in: in_,
3100
- out
3101
- });
3102
- }
3103
- const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => {
3104
- $ZodReadonly.init(inst, def);
3105
- ZodType.init(inst, def);
3106
- inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params);
3107
- inst.unwrap = () => inst._zod.def.innerType;
3108
- });
3109
- function readonly(innerType) {
3110
- return new ZodReadonly({
3111
- type: "readonly",
3112
- innerType
3113
- });
3114
- }
3115
- const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => {
3116
- $ZodCustom.init(inst, def);
3117
- ZodType.init(inst, def);
3118
- inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params);
3119
- });
3120
- function refine(fn, _params = {}) {
3121
- return /* @__PURE__ */ _refine(ZodCustom, fn, _params);
3122
- }
3123
- function superRefine(fn, params) {
3124
- return /* @__PURE__ */ _superRefine(fn, params);
3125
- }
3126
- //#endregion
3127
- //#region src/commands/init/validate.ts
3128
- const projectNameSchema = string().min(1, "Project name cannot be empty.").max(214, "Project name must be 214 characters or fewer.").regex(/^[a-z0-9][a-z0-9._-]*$/u, "Project name must start with a lowercase letter or number, and can only contain letters, numbers, dots, hyphens, and underscores.").refine((val) => !/[._-]$/u.test(val), "Project name must not end with a dot, hyphen, or underscore.").refine((val) => !/__/u.test(val), "Project name must not contain consecutive underscores.").refine((val) => !/[._-]{2,}/u.test(val), "Project name must not contain consecutive dots, hyphens, or underscores.");
3129
- const validateProjectName = (name) => {
3130
- const result = projectNameSchema.safeParse(name);
3131
- if (!result.success) return result.error.issues[0]?.message ?? "Invalid project name.";
3132
- return null;
3133
- };
3134
- //#endregion
3135
- //#region src/commands/init/prompts.ts
3136
- const isCI = () => process.env.CI === "true" || process.env.CI === "1" || process.env.CIRCLECI === "true" || Boolean(process.env.GITHUB_ACTIONS) || Boolean(process.env.GITLAB_CI);
3137
- const ciOrYes = (options) => options?.yes === true || isCI();
3138
- const promptOrSkip = async (prompt, clack) => {
3139
- const result = await prompt(clack);
3140
- if (clack.isCancel(result)) {
3141
- clack.cancel("Cancelled.");
3142
- process.exit(0);
3143
- }
3144
- return result;
3145
- };
3146
- const collectPrompts = async (clack, projectDir, options) => {
3147
- const cwd = process.cwd();
3148
- let resolvedDir;
3149
- let projectName;
3150
- if (projectDir) {
3151
- resolvedDir = path.resolve(cwd, projectDir);
3152
- projectName = path.basename(resolvedDir);
3153
- } else if (ciOrYes(options)) {
3154
- projectName = "studio-project";
3155
- resolvedDir = path.resolve(cwd, projectName);
3156
- } else {
3157
- projectName = (await promptOrSkip((p) => p.text({
3158
- defaultValue: "studio-project",
3159
- message: "What's your project name?",
3160
- validate: (value) => {
3161
- const trimmed = value.trim();
3162
- if (trimmed.length === 0) return "Please enter a project name.";
3163
- return validateProjectName(trimmed);
3164
- }
3165
- }), clack)).trim();
3166
- resolvedDir = path.resolve(cwd, projectName);
3167
- }
3168
- if (!ciOrYes(options) && existsSync(resolvedDir)) {
3169
- if (!await promptOrSkip((p) => p.confirm({
3170
- initialValue: false,
3171
- message: `Directory "${projectName}" already exists. Overwrite?`
3172
- }), clack)) {
3173
- clack.cancel("Cancelled.");
3174
- process.exit(0);
3175
- }
3176
- }
3177
- const templates = ciOrYes(options) ? ["bento-feature"] : await promptOrSkip((p) => p.multiselect({
3178
- message: "Which templates would you like to scaffold?",
3179
- options: [{
3180
- hint: "Apple-style feature card",
3181
- label: "Bento Feature",
3182
- value: "bento-feature"
3183
- }]
3184
- }), clack);
3185
- const locales = ciOrYes(options) ? ["en", "ar"] : await promptOrSkip((p) => p.multiselect({
3186
- message: "Which locales would you like to include?",
3187
- options: [{
3188
- label: "English",
3189
- value: "en"
3190
- }, {
3191
- label: "Arabic",
3192
- value: "ar"
3193
- }]
3194
- }), clack);
3195
- const alreadyInGitRepo = isInsideGitRepo(path.dirname(resolvedDir));
3196
- let wantsGit = !alreadyInGitRepo && ciOrYes(options);
3197
- if (!alreadyInGitRepo && !ciOrYes(options)) wantsGit = await promptOrSkip((p) => p.confirm({
3198
- initialValue: true,
3199
- message: "Initialize a git repository?"
3200
- }), clack);
3201
- const shouldInstall = ciOrYes(options) ? true : await promptOrSkip((p) => p.confirm({
3202
- initialValue: true,
3203
- message: "Install dependencies?"
3204
- }), clack);
3205
- return {
3206
- locales,
3207
- projectName,
3208
- resolvedDir,
3209
- shouldInstall,
3210
- templates,
3211
- wantsGit
3212
- };
3213
- };
3214
- //#endregion
3215
- //#region src/commands/init/version.ts
3216
- const getScaffoldVersion = () => {
3217
- try {
3218
- return createRequire(import.meta.url)("@stdout-design/cli/package.json").version;
3219
- } catch {
3220
- return "latest";
3221
- }
3222
- };
3223
- //#endregion
3224
- //#region src/commands/init/scaffold.ts
3225
- const getDefaults = () => ({
3226
- defaultPreset: "instagram-square",
3227
- presets: [{
3228
- height: 1080,
3229
- id: "instagram-square",
3230
- platform: "instagram",
3231
- width: 1080
3232
- }, {
3233
- height: 1200,
3234
- id: "x-card",
3235
- platform: "x",
3236
- width: 1200
3237
- }],
3238
- templates: { "bento-feature": {
3239
- componentPath: "./templates/bento-feature",
3240
- description: "Apple-style bento feature card."
3241
- } }
3242
- });
3243
- const getConfigTemplate = (version) => `import type { StudioConfig } from "@stdout-design/cli";
7
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1&&ctx.reused===`ref`){extractToDef(entry);continue}}}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw Error(`Unprocessed schema. This is a bug in Zod.`);let flattenRef=zodSchema=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema=seen.def??seen.schema,_cached={...schema},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target===`draft-07`||ctx.target===`draft-04`||ctx.target===`openapi-3.0`)?(schema.allOf=schema.allOf??[],schema.allOf.push(refSchema)):Object.assign(schema,refSchema),Object.assign(schema,_cached),zodSchema._zod.parent===ref)for(let key in schema)key===`$ref`||key===`allOf`||key in _cached||delete schema[key];if(refSchema.$ref&&refSeen.def)for(let key in schema)key===`$ref`||key===`allOf`||key in refSeen.def&&JSON.stringify(schema[key])===JSON.stringify(refSeen.def[key])&&delete schema[key]}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref&&(schema.$ref=parentSeen.schema.$ref,parentSeen.def))for(let key in schema)key===`$ref`||key===`allOf`||key in parentSeen.def&&JSON.stringify(schema[key])===JSON.stringify(parentSeen.def[key])&&delete schema[key]}ctx.override({zodSchema,jsonSchema:schema,path:seen.path??[]})};for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);let result={};if(ctx.target===`draft-2020-12`?result.$schema=`https://json-schema.org/draft/2020-12/schema`:ctx.target===`draft-07`?result.$schema=`http://json-schema.org/draft-07/schema#`:ctx.target===`draft-04`?result.$schema=`http://json-schema.org/draft-04/schema#`:ctx.target,ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}Object.assign(result,root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema)?.id;rootMetaId!==void 0&&result.id===rootMetaId&&delete result.id;let defs=ctx.external?.defs??{};for(let entry of ctx.seen.entries()){let seen=entry[1];seen.def&&seen.defId&&(seen.def.id===seen.defId&&delete seen.def.id,defs[seen.defId]=seen.def)}ctx.external||Object.keys(defs).length>0&&(ctx.target===`draft-2020-12`?result.$defs=defs:result.definitions=defs);try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema[`~standard`],jsonSchema:{input:createStandardJSONSchemaMethod(schema,`input`,ctx.processors),output:createStandardJSONSchemaMethod(schema,`output`,ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch{throw Error(`Error converting schema to JSON.`)}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type===`transform`)return!0;if(def.type===`array`)return isTransforming(def.element,ctx);if(def.type===`set`)return isTransforming(def.valueType,ctx);if(def.type===`lazy`)return isTransforming(def.getter(),ctx);if(def.type===`promise`||def.type===`optional`||def.type===`nonoptional`||def.type===`nullable`||def.type===`readonly`||def.type==="default"||def.type===`prefault`)return isTransforming(def.innerType,ctx);if(def.type===`intersection`)return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type===`record`||def.type===`map`)return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type===`pipe`)return _schema._zod.traits.has(`$ZodCodec`)?!0:isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type===`object`){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type===`union`){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type===`tuple`){for(let item of def.items)if(isTransforming(item,ctx))return!0;return!!(def.rest&&isTransforming(def.rest,ctx))}return!1}const createToJSONSchemaMethod=(schema,processors={})=>params=>{let ctx=initializeContext({...params,processors});return process$1(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>params=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return process$1(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},formatMap={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},stringProcessor=(schema,ctx,_json,_params)=>{let json=_json;json.type=`string`;let{minimum,maximum,format,patterns,contentEncoding}=schema._zod.bag;if(typeof minimum==`number`&&(json.minLength=minimum),typeof maximum==`number`&&(json.maxLength=maximum),format&&(json.format=formatMap[format]??format,json.format===``&&delete json.format,format===`time`&&delete json.format),contentEncoding&&(json.contentEncoding=contentEncoding),patterns&&patterns.size>0){let regexes=[...patterns];regexes.length===1?json.pattern=regexes[0].source:regexes.length>1&&(json.allOf=[...regexes.map(regex=>({...ctx.target===`draft-07`||ctx.target===`draft-04`||ctx.target===`openapi-3.0`?{type:`string`}:{},pattern:regex.source}))])}},customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},arrayProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,{minimum,maximum}=schema._zod.bag;typeof minimum==`number`&&(json.minItems=minimum),typeof maximum==`number`&&(json.maxItems=maximum),json.type=`array`,json.items=process$1(def.element,ctx,{...params,path:[...params.path,`items`]})},unionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>process$1(x,ctx,{...params,path:[...params.path,isExclusive?`oneOf`:`anyOf`,i]}));isExclusive?json.oneOf=options:json.anyOf=options},intersectionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,a=process$1(def.left,ctx,{...params,path:[...params.path,`allOf`,0]}),b=process$1(def.right,ctx,{...params,path:[...params.path,`allOf`,1]}),isSimpleIntersection=val=>`allOf`in val&&Object.keys(val).length===1;json.allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]]},nullableProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,inner=process$1(def.innerType,ctx,params),seen=ctx.seen.get(schema);ctx.target===`openapi-3.0`?(seen.ref=def.innerType,json.nullable=!0):json.anyOf=[inner,{type:`null`}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process$1(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},defaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process$1(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.default=JSON.parse(JSON.stringify(def.defaultValue))},prefaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process$1(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,ctx.io===`input`&&(json._prefault=JSON.parse(JSON.stringify(def.defaultValue)))},catchProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process$1(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}json.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,inIsTransform=def.in._zod.traits.has(`$ZodTransform`),innerType=ctx.io===`input`?inIsTransform?def.out:def.in:def.out;process$1(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process$1(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.readOnly=!0},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process$1(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},ZodISODateTime=$constructor(`ZodISODateTime`,(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)});function datetime(params){return _isoDateTime(ZodISODateTime,params)}const ZodISODate=$constructor(`ZodISODate`,(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)});function date(params){return _isoDate(ZodISODate,params)}const ZodISOTime=$constructor(`ZodISOTime`,(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)});function time(params){return _isoTime(ZodISOTime,params)}const ZodISODuration=$constructor(`ZodISODuration`,(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)});function duration(params){return _isoDuration(ZodISODuration,params)}const ZodRealError=$constructor(`ZodError`,(inst,issues)=>{$ZodError.init(inst,issues),inst.name=`ZodError`,Object.defineProperties(inst,{format:{value:mapper=>formatError(inst,mapper)},flatten:{value:mapper=>flattenError(inst,mapper)},addIssue:{value:issue=>{inst.issues.push(issue),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},addIssues:{value:issues=>{inst.issues.push(...issues),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return inst.issues.length===0}}})},{Parent:Error}),parse=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse=_safeParse(ZodRealError),safeParseAsync=_safeParseAsync(ZodRealError),encode=_encode(ZodRealError),decode=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError),_installedGroups=new WeakMap;function _installLazyMethods(inst,group,methods){let proto=Object.getPrototypeOf(inst),installed=_installedGroups.get(proto);if(installed||(installed=new Set,_installedGroups.set(proto,installed)),!installed.has(group)){installed.add(group);for(let key in methods){let fn=methods[key];Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let bound=fn.bind(this);return Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable:!0,value:bound}),bound},set(v){Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable:!0,value:v})}})}}}const ZodType=$constructor(`ZodType`,(inst,def)=>($ZodType.init(inst,def),Object.assign(inst[`~standard`],{jsonSchema:{input:createStandardJSONSchemaMethod(inst,`input`),output:createStandardJSONSchemaMethod(inst,`output`)}}),inst.toJSONSchema=createToJSONSchemaMethod(inst,{}),inst.def=def,inst.type=def.type,Object.defineProperty(inst,"_def",{value:def}),inst.parse=(data,params)=>parse(inst,data,params,{callee:inst.parse}),inst.safeParse=(data,params)=>safeParse(inst,data,params),inst.parseAsync=async(data,params)=>parseAsync(inst,data,params,{callee:inst.parseAsync}),inst.safeParseAsync=async(data,params)=>safeParseAsync(inst,data,params),inst.spa=inst.safeParseAsync,inst.encode=(data,params)=>encode(inst,data,params),inst.decode=(data,params)=>decode(inst,data,params),inst.encodeAsync=async(data,params)=>encodeAsync(inst,data,params),inst.decodeAsync=async(data,params)=>decodeAsync(inst,data,params),inst.safeEncode=(data,params)=>safeEncode(inst,data,params),inst.safeDecode=(data,params)=>safeDecode(inst,data,params),inst.safeEncodeAsync=async(data,params)=>safeEncodeAsync(inst,data,params),inst.safeDecodeAsync=async(data,params)=>safeDecodeAsync(inst,data,params),_installLazyMethods(inst,`ZodType`,{check(...chks){let def=this.def;return this.clone(mergeDefs(def,{checks:[...def.checks??[],...chks.map(ch=>typeof ch==`function`?{_zod:{check:ch,def:{check:`custom`},onattach:[]}}:ch)]}),{parent:!0})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta){return reg.add(this,meta),this},refine(check,params){return this.check(refine(check,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn){return fn(this)}}),Object.defineProperty(inst,"description",{get(){return globalRegistry.get(inst)?.description},configurable:!0}),inst)),_ZodString=$constructor(`_ZodString`,(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,params);let bag=inst._zod.bag;inst.format=bag.format??null,inst.minLength=bag.minimum??null,inst.maxLength=bag.maximum??null,_installLazyMethods(inst,`_ZodString`,{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})}),ZodString=$constructor(`ZodString`,(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def),inst.email=params=>inst.check(_email(ZodEmail,params)),inst.url=params=>inst.check(_url(ZodURL,params)),inst.jwt=params=>inst.check(_jwt(ZodJWT,params)),inst.emoji=params=>inst.check(_emoji(ZodEmoji,params)),inst.guid=params=>inst.check(_guid(ZodGUID,params)),inst.uuid=params=>inst.check(_uuid(ZodUUID,params)),inst.uuidv4=params=>inst.check(_uuidv4(ZodUUID,params)),inst.uuidv6=params=>inst.check(_uuidv6(ZodUUID,params)),inst.uuidv7=params=>inst.check(_uuidv7(ZodUUID,params)),inst.nanoid=params=>inst.check(_nanoid(ZodNanoID,params)),inst.guid=params=>inst.check(_guid(ZodGUID,params)),inst.cuid=params=>inst.check(_cuid(ZodCUID,params)),inst.cuid2=params=>inst.check(_cuid2(ZodCUID2,params)),inst.ulid=params=>inst.check(_ulid(ZodULID,params)),inst.base64=params=>inst.check(_base64(ZodBase64,params)),inst.base64url=params=>inst.check(_base64url(ZodBase64URL,params)),inst.xid=params=>inst.check(_xid(ZodXID,params)),inst.ksuid=params=>inst.check(_ksuid(ZodKSUID,params)),inst.ipv4=params=>inst.check(_ipv4(ZodIPv4,params)),inst.ipv6=params=>inst.check(_ipv6(ZodIPv6,params)),inst.cidrv4=params=>inst.check(_cidrv4(ZodCIDRv4,params)),inst.cidrv6=params=>inst.check(_cidrv6(ZodCIDRv6,params)),inst.e164=params=>inst.check(_e164(ZodE164,params)),inst.datetime=params=>inst.check(datetime(params)),inst.date=params=>inst.check(date(params)),inst.time=params=>inst.check(time(params)),inst.duration=params=>inst.check(duration(params))});function string(params){return _string(ZodString,params)}const ZodStringFormat=$constructor(`ZodStringFormat`,(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodEmail=$constructor(`ZodEmail`,(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)}),ZodGUID=$constructor(`ZodGUID`,(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodUUID=$constructor(`ZodUUID`,(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodURL=$constructor(`ZodURL`,(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)}),ZodEmoji=$constructor(`ZodEmoji`,(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)}),ZodNanoID=$constructor(`ZodNanoID`,(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCUID=$constructor(`ZodCUID`,(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCUID2=$constructor(`ZodCUID2`,(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)}),ZodULID=$constructor(`ZodULID`,(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodXID=$constructor(`ZodXID`,(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodKSUID=$constructor(`ZodKSUID`,(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodIPv4=$constructor(`ZodIPv4`,(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)}),ZodIPv6=$constructor(`ZodIPv6`,(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCIDRv4=$constructor(`ZodCIDRv4`,(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCIDRv6=$constructor(`ZodCIDRv6`,(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)}),ZodBase64=$constructor(`ZodBase64`,(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)}),ZodBase64URL=$constructor(`ZodBase64URL`,(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)}),ZodE164=$constructor(`ZodE164`,(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)}),ZodJWT=$constructor(`ZodJWT`,(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)}),ZodArray=$constructor(`ZodArray`,(inst,def)=>{$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,params),inst.element=def.element,_installLazyMethods(inst,`ZodArray`,{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}})});function array(element,params){return _array(ZodArray,element,params)}const ZodUnion=$constructor(`ZodUnion`,(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});function union(options,params){return new ZodUnion({type:`union`,options,...normalizeParams(params)})}const ZodIntersection=$constructor(`ZodIntersection`,(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>intersectionProcessor(inst,ctx,json,params)});function intersection(left,right){return new ZodIntersection({type:`intersection`,left,right})}const ZodTransform=$constructor(`ZodTransform`,(inst,def)=>{$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction===`backward`)throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=issue$1=>{if(typeof issue$1==`string`)payload.issues.push(issue(issue$1,payload.value,def));else{let _issue=issue$1;_issue.fatal&&(_issue.continue=!1),_issue.code??=`custom`,_issue.input??=payload.value,_issue.inst??=inst,payload.issues.push(issue(_issue))}};let output=def.transform(payload.value,payload);return output instanceof Promise?output.then(output=>(payload.value=output,payload.fallback=!0,payload)):(payload.value=output,payload.fallback=!0,payload)}});function transform(fn){return new ZodTransform({type:`transform`,transform:fn})}const ZodOptional=$constructor(`ZodOptional`,(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:`optional`,innerType})}const ZodExactOptional=$constructor(`ZodExactOptional`,(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function exactOptional(innerType){return new ZodExactOptional({type:`optional`,innerType})}const ZodNullable=$constructor(`ZodNullable`,(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:`nullable`,innerType})}const ZodDefault=$constructor(`ZodDefault`,(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});function _default(innerType,defaultValue){return new ZodDefault({type:`default`,innerType,get defaultValue(){return typeof defaultValue==`function`?defaultValue():shallowClone(defaultValue)}})}const ZodPrefault=$constructor(`ZodPrefault`,(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>prefaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:`prefault`,innerType,get defaultValue(){return typeof defaultValue==`function`?defaultValue():shallowClone(defaultValue)}})}const ZodNonOptional=$constructor(`ZodNonOptional`,(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:`nonoptional`,innerType,...normalizeParams(params)})}const ZodCatch=$constructor(`ZodCatch`,(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});function _catch(innerType,catchValue){return new ZodCatch({type:`catch`,innerType,catchValue:typeof catchValue==`function`?catchValue:()=>catchValue})}const ZodPipe=$constructor(`ZodPipe`,(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:`pipe`,in:in_,out})}const ZodReadonly=$constructor(`ZodReadonly`,(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:`readonly`,innerType})}const ZodCustom=$constructor(`ZodCustom`,(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)});function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}const projectNameSchema=string().min(1,`Project name cannot be empty.`).max(214,`Project name must be 214 characters or fewer.`).regex(/^[a-z0-9][a-z0-9._-]*$/u,`Project name must start with a lowercase letter or number, and can only contain letters, numbers, dots, hyphens, and underscores.`).refine(val=>!/[._-]$/u.test(val),`Project name must not end with a dot, hyphen, or underscore.`).refine(val=>!/__/u.test(val),`Project name must not contain consecutive underscores.`).refine(val=>!/[._-]{2,}/u.test(val),`Project name must not contain consecutive dots, hyphens, or underscores.`),validateProjectName=name=>{let result=projectNameSchema.safeParse(name);return result.success?null:result.error.issues[0]?.message??`Invalid project name.`},isCI=()=>process.env.CI===`true`||process.env.CI===`1`||process.env.CIRCLECI===`true`||!!process.env.GITHUB_ACTIONS||!!process.env.GITLAB_CI,ciOrYes=options=>options?.yes===!0||isCI(),promptOrSkip=async(prompt,clack)=>{let result=await prompt(clack);return clack.isCancel(result)&&(clack.cancel(`Cancelled.`),process.exit(0)),result},collectPrompts=async(clack,projectDir,options)=>{let cwd=process.cwd(),resolvedDir,projectName;projectDir?(resolvedDir=path.resolve(cwd,projectDir),projectName=path.basename(resolvedDir)):ciOrYes(options)?(projectName=`studio-project`,resolvedDir=path.resolve(cwd,projectName)):(projectName=(await promptOrSkip(p=>p.text({defaultValue:`studio-project`,message:`What's your project name?`,validate:value=>{let trimmed=value.trim();return trimmed.length===0?`Please enter a project name.`:validateProjectName(trimmed)}}),clack)).trim(),resolvedDir=path.resolve(cwd,projectName)),!ciOrYes(options)&&existsSync(resolvedDir)&&(await promptOrSkip(p=>p.confirm({initialValue:!1,message:`Directory "${projectName}" already exists. Overwrite?`}),clack)||(clack.cancel(`Cancelled.`),process.exit(0)));let templates=ciOrYes(options)?[`bento-feature`]:await promptOrSkip(p=>p.multiselect({message:`Which templates would you like to scaffold?`,options:[{hint:`Apple-style feature card`,label:`Bento Feature`,value:`bento-feature`}]}),clack),locales=ciOrYes(options)?[`en`,`ar`]:await promptOrSkip(p=>p.multiselect({message:`Which locales would you like to include?`,options:[{label:`English`,value:`en`},{label:`Arabic`,value:`ar`}]}),clack),alreadyInGitRepo=isInsideGitRepo(path.dirname(resolvedDir)),wantsGit=!alreadyInGitRepo&&ciOrYes(options);!alreadyInGitRepo&&!ciOrYes(options)&&(wantsGit=await promptOrSkip(p=>p.confirm({initialValue:!0,message:`Initialize a git repository?`}),clack));let shouldInstall=ciOrYes(options)?!0:await promptOrSkip(p=>p.confirm({initialValue:!0,message:`Install dependencies?`}),clack);return{locales,projectName,resolvedDir,shouldInstall,templates,wantsGit}},getScaffoldVersion=()=>{try{return createRequire(import.meta.url)(`@stdout-design/cli/package.json`).version}catch{return`latest`}},getDefaults=()=>({defaultPreset:`instagram-square`,presets:[{height:1080,id:`instagram-square`,platform:`instagram`,width:1080},{height:1200,id:`x-card`,platform:`x`,width:1200}],templates:{"bento-feature":{componentPath:`./templates/bento-feature`,description:`Apple-style bento feature card.`}}}),getConfigTemplate=version=>`import type { StudioConfig } from "@stdout-design/cli";
3244
8
 
3245
9
  const config: StudioConfig = {
3246
10
  scaffoldVersion: "${version}",
@@ -3259,444 +23,9 @@ const config: StudioConfig = {
3259
23
  };
3260
24
 
3261
25
  export default config;
3262
- `;
3263
- const getPkgJson = (name, version) => ({
3264
- name,
3265
- private: true,
3266
- type: "module",
3267
- scripts: {
3268
- build: "studio build",
3269
- dev: "studio dev",
3270
- export: "studio export"
3271
- },
3272
- dependencies: {
3273
- "@stdout-design/cli": `^${version}`,
3274
- "@stdout-design/dev-server": "^0.2.0",
3275
- "@stdout-design/web-ui": "^0.2.0",
3276
- "@types/react": "^19.2.17"
3277
- }
3278
- });
3279
- const resolveTemplateDir = () => {
3280
- const fromDist = path.resolve(import.meta.dirname, "../template");
3281
- if (existsSync(path.resolve(fromDist, "tsconfig.json"))) return fromDist;
3282
- return path.resolve(import.meta.dirname, "../../../template");
3283
- };
3284
- const resolveTemplatesDir = () => path.resolve(resolveTemplateDir(), "templates");
3285
- const copyStaticAssets = async (dir) => {
3286
- const base = resolveTemplateDir();
3287
- await Promise.all([
3288
- cp(path.resolve(base, "tsconfig.json"), path.resolve(dir, "tsconfig.json")),
3289
- cp(path.resolve(base, "gitignore"), path.resolve(dir, ".gitignore")),
3290
- cp(path.resolve(base, "types.d.ts"), path.resolve(dir, "types.d.ts"))
3291
- ]);
3292
- };
3293
- const generateConfig = async (dir, version) => {
3294
- await writeFile(path.resolve(dir, "studio.config.ts"), getConfigTemplate(version));
3295
- };
3296
- const generatePackageJson = async (dir, projectName, version) => {
3297
- await writeFile(path.resolve(dir, "package.json"), JSON.stringify(getPkgJson(projectName, version), null, 2));
3298
- };
3299
- const copyTemplateFiles = async (dir, templates) => {
3300
- if (templates.length === 0) return;
3301
- const dstTemplatesDir = path.resolve(dir, "templates");
3302
- await mkdir(dstTemplatesDir, { recursive: true });
3303
- const srcTemplatesDir = resolveTemplatesDir();
3304
- for (const template of templates) if (!existsSync(path.resolve(srcTemplatesDir, `${template}.tsx`))) throw new Error(`Template "${template}" not found at templates/${template}.tsx`);
3305
- await Promise.all(templates.map((template) => cp(path.resolve(srcTemplatesDir, `${template}.tsx`), path.resolve(dstTemplatesDir, `${template}.tsx`))));
3306
- };
3307
- const createLocaleFiles = async (dir, locales) => {
3308
- if (locales.length === 0) return;
3309
- const localesDir = path.resolve(dir, "locales");
3310
- await mkdir(localesDir, { recursive: true });
3311
- const localeData = {
3312
- ar: { title: "التطبيق المميز" },
3313
- en: { title: "Featured App" }
3314
- };
3315
- await Promise.all(locales.map((locale) => writeFile(path.resolve(localesDir, `${locale}.json`), JSON.stringify(localeData[locale] ?? { title: "Featured App" }, null, 2))));
3316
- };
3317
- const scaffold = async (dir, options) => {
3318
- if (options.projectName.trim().length === 0) throw new Error("Project name cannot be empty.");
3319
- const version = getScaffoldVersion();
3320
- if (!existsSync(dir)) await mkdir(dir, { recursive: true });
3321
- await copyStaticAssets(dir);
3322
- await generateConfig(dir, version);
3323
- await generatePackageJson(dir, options.projectName, version);
3324
- await copyTemplateFiles(dir, options.templates);
3325
- await createLocaleFiles(dir, options.locales);
3326
- };
3327
- //#endregion
3328
- //#region src/commands/init.ts
3329
- const detectPackageManager = async (cwd) => {
3330
- const detected = await detect({ cwd });
3331
- if (detected) return detected.name;
3332
- return "npm";
3333
- };
3334
- const runInstall = (dir, pm) => {
3335
- const resolved = resolveCommand(pm, "install", []);
3336
- if (!resolved) return;
3337
- const { command, args } = resolved;
3338
- spawnSync(command, args, {
3339
- cwd: dir,
3340
- stdio: "inherit"
3341
- });
3342
- };
3343
- const init = async (projectDir, options) => {
3344
- const { intro, outro, spinner } = await import("@clack/prompts");
3345
- intro("studio init");
3346
- const cwd = process.cwd();
3347
- if (existsSync(path.resolve(cwd, projectDir ?? ".", "studio.config.ts"))) {
3348
- console.log("studio.config.ts already exists — skipping scaffold.");
3349
- outro("Done");
3350
- return;
3351
- }
3352
- const collected = await collectPrompts(await import("@clack/prompts"), projectDir, options);
3353
- const s = spinner();
3354
- s.start("Creating project...");
3355
- await scaffold(collected.resolvedDir, {
3356
- git: collected.wantsGit,
3357
- install: collected.shouldInstall,
3358
- locales: collected.locales,
3359
- projectName: collected.projectName,
3360
- templates: collected.templates
3361
- });
3362
- s.stop("Project created");
3363
- if (collected.wantsGit) {
3364
- const gitSpinner = spinner();
3365
- gitSpinner.start("Initializing git...");
3366
- const initialized = tryGitInit(collected.resolvedDir);
3367
- gitSpinner.stop(initialized ? "Git initialized" : "Git repo already exists or git is not available");
3368
- }
3369
- const pm = await detectPackageManager(cwd);
3370
- if (collected.shouldInstall) {
3371
- const installSpinner = spinner();
3372
- installSpinner.start("Installing dependencies...");
3373
- runInstall(collected.resolvedDir, pm);
3374
- installSpinner.stop("Dependencies installed");
3375
- }
3376
- console.log("");
3377
- console.log(` Created project at ${collected.resolvedDir}`);
3378
- console.log("");
3379
- console.log(" Next steps:");
3380
- console.log(` cd ${path.relative(cwd, collected.resolvedDir) || "."}`);
3381
- console.log(` ${pm} run dev`);
3382
- console.log("");
3383
- outro("Done");
3384
- };
3385
- //#endregion
3386
- //#region src/commands/lint.ts
3387
- const lint = (_rootDir) => {
3388
- console.error("Lint command not yet implemented. Coming in a future release.");
3389
- process.exit(1);
3390
- };
3391
- //#endregion
3392
- //#region src/lib/prop-parser.ts
3393
- const coerceValue = (value, type, _items) => {
3394
- switch (type) {
3395
- case "number": {
3396
- const n = Number(value);
3397
- return Number.isNaN(n) ? value : n;
3398
- }
3399
- case "boolean":
3400
- if (value === "true" || value === "1") return true;
3401
- if (value === "false" || value === "0") return false;
3402
- return value;
3403
- case "array":
3404
- if (value.startsWith("[") && value.endsWith("]")) try {
3405
- return JSON.parse(value);
3406
- } catch {
3407
- return value.split(",").map((s) => s.trim());
3408
- }
3409
- return value.split(",").map((s) => s.trim());
3410
- default: return value;
3411
- }
3412
- };
3413
- const parsePropArgs = (args, schema) => {
3414
- const props = {};
3415
- const properties = schema.properties ?? {};
3416
- for (const arg of args) {
3417
- const eqIndex = arg.indexOf("=");
3418
- if (eqIndex === -1) {
3419
- props[arg] = true;
3420
- continue;
3421
- }
3422
- const key = arg.slice(0, eqIndex);
3423
- const value = arg.slice(eqIndex + 1);
3424
- const field = properties[key];
3425
- props[key] = field ? coerceValue(value, field.type, field.items) : value;
3426
- }
3427
- return props;
3428
- };
3429
- const mergeDefaultProps = (schema, props) => {
3430
- const properties = schema.properties ?? {};
3431
- const merged = {};
3432
- for (const [key, field] of Object.entries(properties)) if (field.default !== void 0) merged[key] = field.default;
3433
- return {
3434
- ...merged,
3435
- ...props
3436
- };
3437
- };
3438
- //#endregion
3439
- //#region src/lib/suggest.ts
3440
- const levenshteinDistance = (a, b) => {
3441
- const aLen = a.length;
3442
- const bLen = b.length;
3443
- if (aLen === 0) return bLen;
3444
- if (bLen === 0) return aLen;
3445
- let prev = Array.from({ length: aLen + 1 }, (_, j) => j);
3446
- let curr = Array.from({ length: aLen + 1 }).fill(0);
3447
- for (let j = 1; j <= bLen; j += 1) {
3448
- curr[0] = j;
3449
- for (let i = 1; i <= aLen; i += 1) {
3450
- const cost = b[j - 1] === a[i - 1] ? 0 : 1;
3451
- curr[i] = Math.min((prev[i] ?? 0) + 1, (curr[i - 1] ?? 0) + 1, (prev[i - 1] ?? 0) + cost);
3452
- }
3453
- const tmp = prev;
3454
- prev = curr;
3455
- curr = tmp;
3456
- }
3457
- return prev[aLen] ?? 0;
3458
- };
3459
- const suggestClosest = (input, candidates, maxDistance = 3) => {
3460
- let best;
3461
- let bestDistance = Infinity;
3462
- for (const candidate of candidates) {
3463
- const dist = levenshteinDistance(input.toLowerCase(), candidate.toLowerCase());
3464
- if (dist < bestDistance && dist <= maxDistance) {
3465
- bestDistance = dist;
3466
- best = candidate;
3467
- }
3468
- }
3469
- return best;
3470
- };
3471
- //#endregion
3472
- //#region src/commands/resolver.ts
3473
- const resolveTemplate = (config, templateId) => {
3474
- const entry = config.templates[templateId];
3475
- if (!entry) {
3476
- const candidates = Object.keys(config.templates);
3477
- const suggestion = suggestClosest(templateId, candidates);
3478
- const hint = suggestion ? ` Did you mean "${suggestion}"?` : "";
3479
- throw new AppError(ErrorCode.TEMPLATE_NOT_FOUND, `Template "${templateId}" not found in studio.config.ts.${hint}`, {
3480
- availableTemplates: candidates,
3481
- templateId
3482
- });
3483
- }
3484
- return {
3485
- componentPath: entry.componentPath,
3486
- templateId
3487
- };
3488
- };
3489
- const resolveBatchOptions = (config, options) => {
3490
- const presetIds = options?.preset ? options.preset.split(",").map((s) => s.trim()) : config.presets.map((p) => p.id);
3491
- const localeIds = options?.locale ? options.locale.split(",").map((s) => s.trim()) : void 0;
3492
- return {
3493
- concurrency: Number(options?.concurrency ?? "4"),
3494
- dataFile: options?.data,
3495
- failFast: options?.failFast,
3496
- locales: localeIds,
3497
- outDir: options?.outDir ?? config.outDir ?? "out",
3498
- presets: presetIds
3499
- };
3500
- };
3501
- //#endregion
3502
- //#region src/commands/render.ts
3503
- const render = async (templateId, propArgs, options) => {
3504
- const rootDir = process.cwd();
3505
- const config = await loadConfig(rootDir);
3506
- const { module } = await importTemplateForBatch(rootDir, resolveTemplate(config, templateId).componentPath, templateId);
3507
- const schema = zodToJsonSchemaShape(module.propsSchema);
3508
- const mergedProps = mergeDefaultProps(schema, parsePropArgs(propArgs, schema));
3509
- const batchOpts = resolveBatchOptions(config, options);
3510
- const { manifest } = await runBatch({
3511
- baseProps: mergedProps,
3512
- concurrency: batchOpts.concurrency,
3513
- dataFile: batchOpts.dataFile,
3514
- failFast: batchOpts.failFast,
3515
- locales: batchOpts.locales,
3516
- outDir: batchOpts.outDir,
3517
- presets: batchOpts.presets,
3518
- rootDir,
3519
- rows: batchOpts.dataFile ? void 0 : [{}],
3520
- templateId
3521
- });
3522
- if (options.json) console.log(JSON.stringify(manifest, null, 2));
3523
- else console.log(formatManifestSummary(manifest));
3524
- if (manifest.failed.length > 0) process.exit(1);
3525
- };
3526
- //#endregion
3527
- //#region src/commands/init/deps.ts
3528
- const updatePackageJsonDeps = (contents, currentVersion) => {
3529
- const pkg = JSON.parse(contents);
3530
- const deps = pkg.dependencies ??= {};
3531
- const currentRange = `^${currentVersion}`;
3532
- if (deps["@stdout-design/cli"] === currentRange) return {
3533
- changed: false,
3534
- updated: contents
3535
- };
3536
- deps["@stdout-design/cli"] = currentRange;
3537
- return {
3538
- changed: true,
3539
- updated: JSON.stringify(pkg, null, 2)
3540
- };
3541
- };
3542
- //#endregion
3543
- //#region src/commands/init/merge-config.ts
3544
- const mergePresets = (existing, defaults, deprecatedPresetIds) => {
3545
- const existingIds = new Set(existing.presets.map((p) => p.id));
3546
- const addedPresets = [];
3547
- const presets = [...existing.presets];
3548
- for (const defaultPreset of defaults.presets) if (!existingIds.has(defaultPreset.id)) {
3549
- const marked = deprecatedPresetIds.has(defaultPreset.id) ? {
3550
- ...defaultPreset,
3551
- deprecated: true
3552
- } : { ...defaultPreset };
3553
- presets.push(marked);
3554
- addedPresets.push(defaultPreset.id);
3555
- }
3556
- const presetsWithDeprecation = presets.map((p) => deprecatedPresetIds.has(p.id) && !p.deprecated ? {
3557
- ...p,
3558
- deprecated: true
3559
- } : p);
3560
- return {
3561
- addedPresets,
3562
- deprecatedPresets: [...new Set(presetsWithDeprecation.filter((p) => p.deprecated).map((p) => p.id))],
3563
- presets: presetsWithDeprecation
3564
- };
3565
- };
3566
- const mergeTemplates = (existing, defaults) => {
3567
- const addedTemplates = [];
3568
- const templates = { ...existing.templates };
3569
- for (const [key, template] of Object.entries(defaults.templates)) if (!(key in templates)) {
3570
- templates[key] = { ...template };
3571
- addedTemplates.push(key);
3572
- }
3573
- return {
3574
- addedTemplates,
3575
- templates
3576
- };
3577
- };
3578
- const resolveDefaultPreset = (presets, existing, defaults) => {
3579
- const mergedIds = new Set(presets.map((p) => p.id));
3580
- const current = existing.defaultPreset;
3581
- if (current && mergedIds.has(current)) return current;
3582
- return defaults.defaultPreset ?? defaults.presets[0]?.id;
3583
- };
3584
- const mergeConfig = (existing, defaults, currentVersion, deprecatedPresetIds) => {
3585
- const oldVersion = existing.scaffoldVersion ?? null;
3586
- const { presets, addedPresets, deprecatedPresets } = mergePresets(existing, defaults, deprecatedPresetIds);
3587
- const { templates, addedTemplates } = mergeTemplates(existing, defaults);
3588
- return {
3589
- config: {
3590
- ...existing,
3591
- defaultPreset: resolveDefaultPreset(presets, existing, defaults),
3592
- presets,
3593
- scaffoldVersion: currentVersion,
3594
- templates
3595
- },
3596
- summary: {
3597
- addedPresets,
3598
- addedTemplates,
3599
- deprecatedPresets,
3600
- newVersion: currentVersion,
3601
- oldVersion
3602
- }
3603
- };
3604
- };
3605
- //#endregion
3606
- //#region src/commands/update.ts
3607
- const DEPRECATED_PRESET_IDS = /* @__PURE__ */ new Set();
3608
- const serializeConfig = (config) => `import type { StudioConfig } from "@stdout-design/cli";
26
+ `,getPkgJson=(name,version)=>({name,private:!0,type:`module`,scripts:{build:`studio build`,dev:`studio dev`,export:`studio export`},dependencies:{"@stdout-design/cli":`^${version}`,"@stdout-design/dev-server":`^0.2.0`,"@stdout-design/web-ui":`^0.2.0`,"@types/react":`^19.2.17`}}),resolveTemplateDir=()=>{let fromDist=path.resolve(import.meta.dirname,`../template`);return existsSync(path.resolve(fromDist,`tsconfig.json`))?fromDist:path.resolve(import.meta.dirname,`../../../template`)},resolveTemplatesDir=()=>path.resolve(resolveTemplateDir(),`templates`),copyStaticAssets=async dir=>{let base=resolveTemplateDir();await Promise.all([cp(path.resolve(base,`tsconfig.json`),path.resolve(dir,`tsconfig.json`)),cp(path.resolve(base,`gitignore`),path.resolve(dir,`.gitignore`)),cp(path.resolve(base,`types.d.ts`),path.resolve(dir,`types.d.ts`))])},generateConfig=async(dir,version)=>{await writeFile(path.resolve(dir,`studio.config.ts`),getConfigTemplate(version))},generatePackageJson=async(dir,projectName,version)=>{await writeFile(path.resolve(dir,`package.json`),JSON.stringify(getPkgJson(projectName,version),null,2))},copyTemplateFiles=async(dir,templates)=>{if(templates.length===0)return;let dstTemplatesDir=path.resolve(dir,`templates`);await mkdir(dstTemplatesDir,{recursive:!0});let srcTemplatesDir=resolveTemplatesDir();for(let template of templates)if(!existsSync(path.resolve(srcTemplatesDir,`${template}.tsx`)))throw Error(`Template "${template}" not found at templates/${template}.tsx`);await Promise.all(templates.map(template=>cp(path.resolve(srcTemplatesDir,`${template}.tsx`),path.resolve(dstTemplatesDir,`${template}.tsx`))))},createLocaleFiles=async(dir,locales)=>{if(locales.length===0)return;let localesDir=path.resolve(dir,`locales`);await mkdir(localesDir,{recursive:!0});let localeData={ar:{title:`التطبيق المميز`},en:{title:`Featured App`}};await Promise.all(locales.map(locale=>writeFile(path.resolve(localesDir,`${locale}.json`),JSON.stringify(localeData[locale]??{title:`Featured App`},null,2))))},scaffold=async(dir,options)=>{if(options.projectName.trim().length===0)throw Error(`Project name cannot be empty.`);let version=getScaffoldVersion();existsSync(dir)||await mkdir(dir,{recursive:!0}),await copyStaticAssets(dir),await generateConfig(dir,version),await generatePackageJson(dir,options.projectName,version),await copyTemplateFiles(dir,options.templates),await createLocaleFiles(dir,options.locales)},detectPackageManager=async cwd=>{let detected=await detect({cwd});return detected?detected.name:`npm`},runInstall=(dir,pm)=>{let resolved=resolveCommand(pm,`install`,[]);if(!resolved)return;let{command,args}=resolved;spawnSync(command,args,{cwd:dir,stdio:`inherit`})},init=async(projectDir,options)=>{let{intro,outro,spinner}=await import(`@clack/prompts`);intro(`studio init`);let cwd=process.cwd();if(existsSync(path.resolve(cwd,projectDir??`.`,`studio.config.ts`))){console.log(`studio.config.ts already exists — skipping scaffold.`),outro(`Done`);return}let collected=await collectPrompts(await import(`@clack/prompts`),projectDir,options),s=spinner();if(s.start(`Creating project...`),await scaffold(collected.resolvedDir,{git:collected.wantsGit,install:collected.shouldInstall,locales:collected.locales,projectName:collected.projectName,templates:collected.templates}),s.stop(`Project created`),collected.wantsGit){let gitSpinner=spinner();gitSpinner.start(`Initializing git...`);let initialized=tryGitInit(collected.resolvedDir);gitSpinner.stop(initialized?`Git initialized`:`Git repo already exists or git is not available`)}let pm=await detectPackageManager(cwd);if(collected.shouldInstall){let installSpinner=spinner();installSpinner.start(`Installing dependencies...`),runInstall(collected.resolvedDir,pm),installSpinner.stop(`Dependencies installed`)}console.log(``),console.log(` Created project at ${collected.resolvedDir}`),console.log(``),console.log(` Next steps:`),console.log(` cd ${path.relative(cwd,collected.resolvedDir)||`.`}`),console.log(` ${pm} run dev`),console.log(``),outro(`Done`)},lint=_rootDir=>{console.error(`Lint command not yet implemented. Coming in a future release.`),process.exit(1)},coerceValue=(value,type,_items)=>{switch(type){case`number`:{let n=Number(value);return Number.isNaN(n)?value:n}case`boolean`:return value===`true`||value===`1`?!0:value===`false`||value===`0`?!1:value;case`array`:if(value.startsWith(`[`)&&value.endsWith(`]`))try{return JSON.parse(value)}catch{return value.split(`,`).map(s=>s.trim())}return value.split(`,`).map(s=>s.trim());default:return value}},parsePropArgs=(args,schema)=>{let props={},properties=schema.properties??{};for(let arg of args){let eqIndex=arg.indexOf(`=`);if(eqIndex===-1){props[arg]=!0;continue}let key=arg.slice(0,eqIndex),value=arg.slice(eqIndex+1),field=properties[key];props[key]=field?coerceValue(value,field.type,field.items):value}return props},mergeDefaultProps=(schema,props)=>{let properties=schema.properties??{},merged={};for(let[key,field]of Object.entries(properties))field.default!==void 0&&(merged[key]=field.default);return{...merged,...props}},levenshteinDistance=(a,b)=>{let aLen=a.length,bLen=b.length;if(aLen===0)return bLen;if(bLen===0)return aLen;let prev=Array.from({length:aLen+1},(_,j)=>j),curr=Array.from({length:aLen+1}).fill(0);for(let j=1;j<=bLen;j+=1){curr[0]=j;for(let i=1;i<=aLen;i+=1){let cost=b[j-1]===a[i-1]?0:1;curr[i]=Math.min((prev[i]??0)+1,(curr[i-1]??0)+1,(prev[i-1]??0)+cost)}let tmp=prev;prev=curr,curr=tmp}return prev[aLen]??0},suggestClosest=(input,candidates,maxDistance=3)=>{let best,bestDistance=1/0;for(let candidate of candidates){let dist=levenshteinDistance(input.toLowerCase(),candidate.toLowerCase());dist<bestDistance&&dist<=maxDistance&&(bestDistance=dist,best=candidate)}return best},resolveTemplate=(config,templateId)=>{let entry=config.templates[templateId];if(!entry){let candidates=Object.keys(config.templates),suggestion=suggestClosest(templateId,candidates),hint=suggestion?` Did you mean "${suggestion}"?`:``;throw new AppError(ErrorCode.TEMPLATE_NOT_FOUND,`Template "${templateId}" not found in studio.config.ts.${hint}`,{availableTemplates:candidates,templateId})}return{componentPath:entry.componentPath,templateId}},resolveBatchOptions=(config,options)=>{let presetIds=options?.preset?options.preset.split(`,`).map(s=>s.trim()):config.presets.map(p=>p.id),localeIds=options?.locale?options.locale.split(`,`).map(s=>s.trim()):void 0;return{concurrency:Number(options?.concurrency??`4`),dataFile:options?.data,failFast:options?.failFast,locales:localeIds,outDir:options?.outDir??config.outDir??`out`,presets:presetIds}},render=async(templateId,propArgs,options)=>{let rootDir=process.cwd(),config=await loadConfig(rootDir),{module}=await importTemplateForBatch(rootDir,resolveTemplate(config,templateId).componentPath,templateId),schema=zodToJsonSchemaShape(module.propsSchema),mergedProps=mergeDefaultProps(schema,parsePropArgs(propArgs,schema)),batchOpts=resolveBatchOptions(config,options),{manifest}=await runBatch({baseProps:mergedProps,concurrency:batchOpts.concurrency,dataFile:batchOpts.dataFile,failFast:batchOpts.failFast,locales:batchOpts.locales,outDir:batchOpts.outDir,presets:batchOpts.presets,rootDir,rows:batchOpts.dataFile?void 0:[{}],templateId});options.json?console.log(JSON.stringify(manifest,null,2)):console.log(formatManifestSummary(manifest)),manifest.failed.length>0&&process.exit(1)},updatePackageJsonDeps=(contents,currentVersion)=>{let pkg=JSON.parse(contents),deps=pkg.dependencies??={},currentRange=`^${currentVersion}`;return deps[`@stdout-design/cli`]===currentRange?{changed:!1,updated:contents}:(deps[`@stdout-design/cli`]=currentRange,{changed:!0,updated:JSON.stringify(pkg,null,2)})},mergePresets=(existing,defaults,deprecatedPresetIds)=>{let existingIds=new Set(existing.presets.map(p=>p.id)),addedPresets=[],presets=[...existing.presets];for(let defaultPreset of defaults.presets)if(!existingIds.has(defaultPreset.id)){let marked=deprecatedPresetIds.has(defaultPreset.id)?{...defaultPreset,deprecated:!0}:{...defaultPreset};presets.push(marked),addedPresets.push(defaultPreset.id)}let presetsWithDeprecation=presets.map(p=>deprecatedPresetIds.has(p.id)&&!p.deprecated?{...p,deprecated:!0}:p);return{addedPresets,deprecatedPresets:[...new Set(presetsWithDeprecation.filter(p=>p.deprecated).map(p=>p.id))],presets:presetsWithDeprecation}},mergeTemplates=(existing,defaults)=>{let addedTemplates=[],templates={...existing.templates};for(let[key,template]of Object.entries(defaults.templates))key in templates||(templates[key]={...template},addedTemplates.push(key));return{addedTemplates,templates}},resolveDefaultPreset=(presets,existing,defaults)=>{let mergedIds=new Set(presets.map(p=>p.id)),current=existing.defaultPreset;return current&&mergedIds.has(current)?current:defaults.defaultPreset??defaults.presets[0]?.id},mergeConfig=(existing,defaults,currentVersion,deprecatedPresetIds)=>{let oldVersion=existing.scaffoldVersion??null,{presets,addedPresets,deprecatedPresets}=mergePresets(existing,defaults,deprecatedPresetIds),{templates,addedTemplates}=mergeTemplates(existing,defaults);return{config:{...existing,defaultPreset:resolveDefaultPreset(presets,existing,defaults),presets,scaffoldVersion:currentVersion,templates},summary:{addedPresets,addedTemplates,deprecatedPresets,newVersion:currentVersion,oldVersion}}},DEPRECATED_PRESET_IDS=new Set,serializeConfig=config=>`import type { StudioConfig } from "@stdout-design/cli";
3609
27
 
3610
- const config: StudioConfig = ${JSON.stringify(config, null, 2)};
28
+ const config: StudioConfig = ${JSON.stringify(config,null,2)};
3611
29
 
3612
30
  export default config;
3613
- `;
3614
- const update = async (projectDir, options) => {
3615
- const cwd = process.cwd();
3616
- const dir = path.resolve(cwd, projectDir ?? ".");
3617
- const configPath = path.resolve(dir, "studio.config.ts");
3618
- if (!existsSync(configPath)) throw new Error("No studio project found. Run `studio init` first.");
3619
- const existingModule = await import(pathToFileURL(configPath).href);
3620
- const existing = existingModule.default ?? existingModule;
3621
- const existingConfig = {
3622
- defaultPreset: existing.defaultPreset,
3623
- outDir: existing.outDir,
3624
- presets: existing.presets ?? [],
3625
- scaffoldVersion: existing.scaffoldVersion,
3626
- templates: existing.templates ?? {}
3627
- };
3628
- const defaults = getDefaults();
3629
- const currentVersion = getScaffoldVersion();
3630
- const { config: merged, summary } = mergeConfig(existingConfig, defaults, currentVersion, DEPRECATED_PRESET_IDS);
3631
- const { intro, outro, confirm } = await import("@clack/prompts");
3632
- intro("studio update");
3633
- if (!(summary.addedPresets.length > 0 || summary.deprecatedPresets.length > 0 || summary.addedTemplates.length > 0 || summary.oldVersion !== summary.newVersion)) {
3634
- console.log("Project is already up to date.");
3635
- outro("Done");
3636
- return;
3637
- }
3638
- console.log("");
3639
- if (summary.oldVersion !== summary.newVersion) console.log(` scaffoldVersion ${summary.oldVersion ?? "(none)"} -> ${summary.newVersion}`);
3640
- for (const id of summary.addedPresets) console.log(` presets +${id}`);
3641
- for (const id of summary.deprecatedPresets) console.log(` presets ! ${id} (deprecated)`);
3642
- for (const id of summary.addedTemplates) console.log(` templates +${id}`);
3643
- console.log(" assets tsconfig.json, .gitignore, types.d.ts (overwrite)");
3644
- console.log(` deps @stdout-design/cli ^x -> ^${currentVersion}`);
3645
- console.log("");
3646
- if (!options?.yes) {
3647
- if (!await confirm({
3648
- initialValue: true,
3649
- message: "Apply these changes?"
3650
- })) {
3651
- console.log("Cancelled.");
3652
- outro("Done");
3653
- return;
3654
- }
3655
- }
3656
- await writeFile(configPath, serializeConfig(merged));
3657
- await copyStaticAssets(dir);
3658
- const pkgPath = path.resolve(dir, "package.json");
3659
- if (existsSync(pkgPath)) {
3660
- const { updated, changed } = updatePackageJsonDeps(readFileSync(pkgPath, "utf-8"), currentVersion);
3661
- if (changed) await writeFile(pkgPath, updated);
3662
- }
3663
- console.log("");
3664
- outro("Done");
3665
- };
3666
- //#endregion
3667
- //#region src/lib/runner.ts
3668
- const handlers = {
3669
- cache: cacheStats,
3670
- cacheClean,
3671
- cacheStats,
3672
- dev,
3673
- init,
3674
- lint,
3675
- render,
3676
- update
3677
- };
3678
- const run = (moduleName, handlerName) => async (...args) => {
3679
- try {
3680
- const handler = handlerName ? handlers[handlerName] : handlers[moduleName];
3681
- if (!handler) throw new Error(`Unknown command: ${handlerName ?? moduleName}`);
3682
- await handler(...args);
3683
- } catch (error) {
3684
- console.error(formatError$1(error));
3685
- process.exit(1);
3686
- }
3687
- };
3688
- //#endregion
3689
- //#region src/index.ts
3690
- const program = new Command().allowExcessArguments(true);
3691
- program.name("studio").description("Social media design tool — render, preview, batch").version("0.0.0");
3692
- program.command("dev").description("Start the studio dev server with live preview").argument("[rootDir]", "Project root directory (default: cwd)").option("-p, --port <number>", "Port to run on", "3000").option("--open", "Open browser on start").action(run("dev"));
3693
- program.command("render").description("Render a template — single or batch with --data").argument("<template>", "Template ID from studio.config.ts").argument("[props...]", "Props as key=value pairs (e.g. title=\"Hello\")").option("--data <path>", "CSV or JSON data file for batch rendering").option("--preset <ids>", "Comma-separated preset IDs").option("--locale <locales>", "Comma-separated locale codes").option("--out-dir <path>", "Output directory").option("--concurrency <n>", "Max concurrent renders in batch mode", "4").option("--fail-fast", "Stop batch on first error").option("--json", "Output results as JSON").action(run("render"));
3694
- const cacheCmd = program.command("cache").description("Manage the render cache");
3695
- cacheCmd.command("stats").description("Show cache statistics").option("--json", "Output as JSON").argument("[rootDir]", "Project root directory (default: cwd)").action(run("cache", "cacheStats"));
3696
- cacheCmd.command("clean").description("Clear the render cache").option("--json", "Output as JSON").argument("[rootDir]", "Project root directory (default: cwd)").action(run("cache", "cacheClean"));
3697
- program.command("lint").description("Check templates for compatibility (coming soon)").argument("[rootDir]", "Project root directory (default: cwd)").action(run("lint"));
3698
- program.command("init").description("Scaffold a new studio project").argument("[projectDir]", "Project directory (default: cwd)").option("-y, --yes", "Skip prompts, use defaults").action(run("init"));
3699
- program.command("update").description("Update an existing studio project to the latest CLI version").argument("[projectDir]", "Project directory (default: cwd)").option("-y, --yes", "Skip confirmation prompts").action(run("update"));
3700
- program.parse();
3701
- //#endregion
3702
- export {};
31
+ `,handlers={cache:cacheStats,cacheClean,cacheStats,dev,init,lint,render,update:async(projectDir,options)=>{let cwd=process.cwd(),dir=path.resolve(cwd,projectDir??`.`),configPath=path.resolve(dir,`studio.config.ts`);if(!existsSync(configPath))throw Error("No studio project found. Run `studio init` first.");let existingModule=await import(pathToFileURL(configPath).href),existing=existingModule.default??existingModule,existingConfig={defaultPreset:existing.defaultPreset,outDir:existing.outDir,presets:existing.presets??[],scaffoldVersion:existing.scaffoldVersion,templates:existing.templates??{}},defaults=getDefaults(),currentVersion=getScaffoldVersion(),{config:merged,summary}=mergeConfig(existingConfig,defaults,currentVersion,DEPRECATED_PRESET_IDS),{intro,outro,confirm}=await import(`@clack/prompts`);if(intro(`studio update`),!(summary.addedPresets.length>0||summary.deprecatedPresets.length>0||summary.addedTemplates.length>0||summary.oldVersion!==summary.newVersion)){console.log(`Project is already up to date.`),outro(`Done`);return}console.log(``),summary.oldVersion!==summary.newVersion&&console.log(` scaffoldVersion ${summary.oldVersion??`(none)`} -> ${summary.newVersion}`);for(let id of summary.addedPresets)console.log(` presets +${id}`);for(let id of summary.deprecatedPresets)console.log(` presets ! ${id} (deprecated)`);for(let id of summary.addedTemplates)console.log(` templates +${id}`);if(console.log(` assets tsconfig.json, .gitignore, types.d.ts (overwrite)`),console.log(` deps @stdout-design/cli ^x -> ^${currentVersion}`),console.log(``),!options?.yes&&!await confirm({initialValue:!0,message:`Apply these changes?`})){console.log(`Cancelled.`),outro(`Done`);return}await writeFile(configPath,serializeConfig(merged)),await copyStaticAssets(dir);let pkgPath=path.resolve(dir,`package.json`);if(existsSync(pkgPath)){let{updated,changed}=updatePackageJsonDeps(readFileSync(pkgPath,`utf-8`),currentVersion);changed&&await writeFile(pkgPath,updated)}console.log(``),outro(`Done`)}},run=(moduleName,handlerName)=>async(...args)=>{try{let handler=handlerName?handlers[handlerName]:handlers[moduleName];if(!handler)throw Error(`Unknown command: ${handlerName??moduleName}`);await handler(...args)}catch(error){console.error(formatError$1(error)),process.exit(1)}},pkg=createRequire(import.meta.url)(`../package.json`),program=new Command().allowExcessArguments(!0);program.name(`studio`).description(`Social media design tool — render, preview, batch`).version(pkg.version,`-v, -V, --version`),program.command(`dev`).description(`Start the studio dev server with live preview`).argument(`[rootDir]`,`Project root directory (default: cwd)`).option(`-p, --port <number>`,`Port to run on`,`3000`).option(`--open`,`Open browser on start`).action(run(`dev`)),program.command(`render`).description(`Render a template — single or batch with --data`).argument(`<template>`,`Template ID from studio.config.ts`).argument(`[props...]`,`Props as key=value pairs (e.g. title="Hello")`).option(`--data <path>`,`CSV or JSON data file for batch rendering`).option(`--preset <ids>`,`Comma-separated preset IDs`).option(`--locale <locales>`,`Comma-separated locale codes`).option(`--out-dir <path>`,`Output directory`).option(`--concurrency <n>`,`Max concurrent renders in batch mode`,`4`).option(`--fail-fast`,`Stop batch on first error`).option(`--json`,`Output results as JSON`).action(run(`render`));const cacheCmd=program.command(`cache`).description(`Manage the render cache`);cacheCmd.command(`stats`).description(`Show cache statistics`).option(`--json`,`Output as JSON`).argument(`[rootDir]`,`Project root directory (default: cwd)`).action(run(`cache`,`cacheStats`)),cacheCmd.command(`clean`).description(`Clear the render cache`).option(`--json`,`Output as JSON`).argument(`[rootDir]`,`Project root directory (default: cwd)`).action(run(`cache`,`cacheClean`)),program.command(`lint`).description(`Check templates for compatibility (coming soon)`).argument(`[rootDir]`,`Project root directory (default: cwd)`).action(run(`lint`)),program.command(`init`).description(`Scaffold a new studio project`).argument(`[projectDir]`,`Project directory (default: cwd)`).option(`-y, --yes`,`Skip prompts, use defaults`).action(run(`init`)),program.command(`update`).description(`Update an existing studio project to the latest CLI version`).argument(`[projectDir]`,`Project directory (default: cwd)`).option(`-y, --yes`,`Skip confirmation prompts`).action(run(`update`)),program.parse();export{};