@vite-hub/rate-limit 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +18 -14
  2. package/dist/cli-szm60zN5.d.ts +163 -0
  3. package/dist/cli.d.ts +1 -1
  4. package/dist/cli.js +12 -26
  5. package/dist/{cloudflare-DUDRACVB.js → cloudflare-otBvOPv4.js} +5 -4
  6. package/dist/{counters-pKORpgGd.d.ts → counters-DXpF67J_.d.ts} +3 -3
  7. package/dist/{counters-wdEMxDEY.js → counters-DgVdHwdL.js} +13 -6
  8. package/dist/dev-peer-CHafxbtj.js +238 -0
  9. package/dist/drivers/cloudflare.d.ts +1 -1
  10. package/dist/drivers/cloudflare.js +1 -1
  11. package/dist/drivers/kv.d.ts +2 -0
  12. package/dist/drivers/kv.js +92 -0
  13. package/dist/drivers/memory.d.ts +1 -1
  14. package/dist/drivers/memory.js +5 -5
  15. package/dist/durability.d.ts +12 -0
  16. package/dist/durability.js +35 -0
  17. package/dist/error-diagnostics-MgAnhRTP.js +234 -0
  18. package/dist/index.d.ts +16 -7
  19. package/dist/index.js +108 -38
  20. package/dist/{inspect-D-FzyM_x.js → inspect-B6gTdgy9.js} +7 -1
  21. package/dist/kv-C1wpLulE.d.ts +29 -0
  22. package/dist/{limiter-DBrMI4vi.js → kv-provider-C1S6dRTR.js} +16 -9
  23. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  24. package/dist/operations-BYRa7wpx.js +1355 -0
  25. package/dist/{operations-Bu-xulNd.js → operations-CLI9w3rO.js} +9 -14
  26. package/dist/operations.d.ts +9 -4
  27. package/dist/operations.js +51 -23
  28. package/dist/runtime.d.ts +21 -3
  29. package/dist/runtime.js +2 -2
  30. package/dist/state-BU-zcLNY.js +89 -0
  31. package/dist/{types-CQEJpgtz.d.ts → types-CMyR1JeW.d.ts} +43 -23
  32. package/dist/vite.d.ts +131 -21
  33. package/dist/vite.js +349 -2479
  34. package/package.json +21 -17
  35. package/dist/cli-Cniq99iX.d.ts +0 -85
  36. package/dist/error-diagnostics-CTAC_bbr.js +0 -56
  37. package/dist/h3-v1-request-qoGwJr5-.js +0 -235
  38. package/dist/operations-B09NnEjT.js +0 -1438
  39. package/dist/state-Ct7zR8fD.js +0 -43
@@ -1,1438 +0,0 @@
1
- import { defineDiagnostics } from "nostics";
2
- import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
3
- import { basename, dirname, join, parse, resolve } from "node:path";
4
- import { tmpdir } from "node:os";
5
- //#region ../internal/src/object.ts
6
- function isPlainObject(value) {
7
- if (value === null || Object(value) !== value || Array.isArray(value)) return false;
8
- return typeof value === "object";
9
- }
10
- function parseViteHubDevTimeout(value, error) {
11
- if (!/^\d+$/.test(value)) throw error("--timeout must be an integer from 1 to 2147483647 milliseconds.");
12
- const timeout = Number(value);
13
- if (timeout > 2147483647) throw error("--timeout must be at most 2147483647 milliseconds.");
14
- if (!Number.isInteger(timeout) || timeout < 1) throw error("--timeout must be an integer from 1 to 2147483647 milliseconds.");
15
- return timeout;
16
- }
17
- /**
18
- * Reads one dev target option at `args[index]`: `--url <url>`, `--server <url>`,
19
- * `--url=<url>`, `--timeout <ms>` or `--timeout=<ms>`.
20
- *
21
- * Returns the number of extra arguments that the option used (`0` or `1`), or
22
- * `undefined` when `args[index]` is not a dev target option.
23
- */
24
- function readViteHubDevTargetOption(args, index, target, errors) {
25
- const arg = args[index];
26
- if (arg === void 0) return;
27
- const readValue = () => {
28
- const value = args[index + 1];
29
- if (!value || value.startsWith("-")) throw errors.missingValue(`Missing value for ${arg}.`);
30
- return value;
31
- };
32
- if (arg === "--url" || arg === "--server") {
33
- target.url = readValue();
34
- return 1;
35
- }
36
- if (arg.startsWith("--url=")) {
37
- const value = arg.slice(6);
38
- if (!value) throw errors.missingValue(`Missing value for ${arg}.`);
39
- target.url = value;
40
- return 0;
41
- }
42
- if (arg === "--timeout") {
43
- target.timeout = parseViteHubDevTimeout(readValue(), errors.invalidTimeout);
44
- return 1;
45
- }
46
- if (arg.startsWith("--timeout=")) {
47
- target.timeout = parseViteHubDevTimeout(arg.slice(10), errors.invalidInlineTimeout);
48
- return 0;
49
- }
50
- }
51
- /** File in the project root where the running dev server tells commands where it listens. */
52
- const viteHubDevServerFile = ".vitehub/dev-server.json";
53
- function writeViteHubDevServerFile(root, info) {
54
- const file = join(root, viteHubDevServerFile);
55
- mkdirSync(dirname(file), { recursive: true });
56
- writeFileSync(file, `${JSON.stringify(info)}\n`);
57
- }
58
- function removeViteHubDevServerFile(root) {
59
- rmSync(join(root, viteHubDevServerFile), { force: true });
60
- }
61
- /** The dev server that runs in `root`, or undefined when there is no file or it is not valid. */
62
- function readViteHubDevServerFile(root) {
63
- try {
64
- const value = JSON.parse(readFileSync(join(root, viteHubDevServerFile), "utf8"));
65
- const url = isPlainObject(value) ? value.url : void 0;
66
- const served = isPlainObject(value) ? value.root : void 0;
67
- return typeof url === "string" && url && typeof served === "string" && served ? {
68
- root: served,
69
- url
70
- } : void 0;
71
- } catch {
72
- return;
73
- }
74
- }
75
- /**
76
- * Where a command finds the dev server of its project: the file that the server wrote in a project root, else
77
- * `VITEHUB_DEV_SERVER_URL`. It never guesses a port, since another project may use it.
78
- */
79
- function findViteHubDevServerUrl(roots, env) {
80
- for (const root of roots) {
81
- const file = readViteHubDevServerFile(root);
82
- if (file && roots.some((candidate) => candidate.replace(/\/+$/, "") === file.root.replace(/\/+$/, ""))) return file.url;
83
- }
84
- return env["VITEHUB_DEV_SERVER_URL"] || void 0;
85
- }
86
- //#endregion
87
- //#region ../internal/src/build/vite.ts
88
- const projectRootDirectoryMarkers = [
89
- ["server", "agents"],
90
- ["server", "channels"],
91
- ["server", "connections"],
92
- ["server", "browsers"],
93
- ["server", "emails"],
94
- ["server", "schedules"],
95
- ["server", "workspaces"]
96
- ];
97
- const projectRootFileMarkers = [
98
- ["package.json"],
99
- ["nuxt.config.ts"],
100
- ["nuxt.config.mts"],
101
- ["nuxt.config.js"],
102
- ["nuxt.config.mjs"]
103
- ];
104
- function createNoExternalAddition(...packageNames) {
105
- return (current) => {
106
- if (current === true) return;
107
- const values = Array.isArray(current) ? current : [current];
108
- const missing = packageNames.filter((packageName) => !values.includes(packageName));
109
- return missing.length ? missing : void 0;
110
- };
111
- }
112
- function isServerEnvironment(name, config) {
113
- return name === "ssr" || config.consumer === "server";
114
- }
115
- function shouldSkipViteProviderBuild(command, mode) {
116
- return command === "serve" || mode === "e2e";
117
- }
118
- function resolveViteHubProjectRoot(root, options = {}) {
119
- const resolvedRoot = resolve(root);
120
- const temporaryRoot = resolve(tmpdir());
121
- const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
122
- if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
123
- if (basename(resolvedRoot) === "app") {
124
- const parent = dirname(resolvedRoot);
125
- if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
126
- "nuxt.config.ts",
127
- "nuxt.config.mts",
128
- "nuxt.config.js",
129
- "nuxt.config.mjs"
130
- ]))) return parent;
131
- }
132
- let current = resolvedRoot;
133
- while (true) {
134
- if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
135
- if (hasProjectRootMarker(current)) return current;
136
- const parent = dirname(current);
137
- if (parent === current) return resolvedRoot;
138
- current = parent;
139
- }
140
- }
141
- function hasProjectRootDirectoryMarker(root) {
142
- for (const marker of projectRootDirectoryMarkers) try {
143
- if (statSync(resolve(root, ...marker)).isDirectory()) return true;
144
- } catch (error) {
145
- if (error.code !== "ENOENT") throw error;
146
- }
147
- return false;
148
- }
149
- function hasProjectRootMarker(root) {
150
- if (hasProjectRootDirectoryMarker(root)) return true;
151
- return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
152
- }
153
- function hasProjectRootFileMarker(root, markers) {
154
- for (const marker of markers) {
155
- const path = Array.isArray(marker) ? marker : [marker];
156
- try {
157
- if (statSync(resolve(root, ...path)).isFile()) return true;
158
- } catch (error) {
159
- if (error.code !== "ENOENT") throw error;
160
- }
161
- }
162
- return false;
163
- }
164
- //#endregion
165
- //#region ../internal/src/error-diagnostics.ts
166
- const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
167
- const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
168
- docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
169
- codes: {
170
- INTERNAL_R0012: dynamicError,
171
- INTERNAL_R0013: dynamicError,
172
- INTERNAL_R0014: {
173
- why: ({ path }) => `Cannot read Provision State from "${path}".`,
174
- fix: "Check file access and restore valid JSON while preserving existing resource IDs."
175
- },
176
- INTERNAL_R0020: {
177
- fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
178
- why: ({ message }) => message === void 0 ? "" : String(message)
179
- },
180
- INTERNAL_R0021: {
181
- fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
182
- why: ({ message }) => message === void 0 ? "" : String(message)
183
- },
184
- INTERNAL_R0022: {
185
- fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
186
- why: ({ message }) => message === void 0 ? "" : String(message)
187
- },
188
- INTERNAL_R0024: {
189
- fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app with credentials in VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET.",
190
- why: ({ message }) => message === void 0 ? "" : String(message)
191
- },
192
- INTERNAL_R0023: {
193
- fix: "Ask for access to the section of this operation.",
194
- why: ({ message }) => message === void 0 ? "" : String(message)
195
- },
196
- INTERNAL_B0001: dynamicError,
197
- INTERNAL_B0002: dynamicError,
198
- INTERNAL_B0003: dynamicError,
199
- INTERNAL_B0004: dynamicError,
200
- INTERNAL_B0005: dynamicError,
201
- INTERNAL_B0006: dynamicError,
202
- INTERNAL_B0007: dynamicError,
203
- INTERNAL_B0008: dynamicError,
204
- INTERNAL_B0009: dynamicError,
205
- INTERNAL_B0010: dynamicError,
206
- INTERNAL_B0011: dynamicError,
207
- INTERNAL_B0012: dynamicError,
208
- INTERNAL_B0013: dynamicError,
209
- INTERNAL_B0014: dynamicError,
210
- INTERNAL_B0015: dynamicError,
211
- INTERNAL_B0016: dynamicError,
212
- INTERNAL_B0017: dynamicError,
213
- INTERNAL_B0018: dynamicError,
214
- INTERNAL_B0019: dynamicError,
215
- INTERNAL_B0020: dynamicError,
216
- INTERNAL_B0021: dynamicError,
217
- INTERNAL_B0022: dynamicError,
218
- INTERNAL_B0023: dynamicError,
219
- INTERNAL_B0024: dynamicError,
220
- INTERNAL_B0025: dynamicError,
221
- INTERNAL_B0026: dynamicError,
222
- INTERNAL_B0027: dynamicError,
223
- INTERNAL_B0028: dynamicError,
224
- INTERNAL_B0029: dynamicError,
225
- INTERNAL_B0030: dynamicError,
226
- INTERNAL_B0031: dynamicError,
227
- INTERNAL_B0032: dynamicError,
228
- INTERNAL_B0033: dynamicError,
229
- INTERNAL_B0034: dynamicError,
230
- INTERNAL_B0035: dynamicError,
231
- INTERNAL_B0036: dynamicError,
232
- INTERNAL_B0037: dynamicError,
233
- INTERNAL_B0038: dynamicError,
234
- INTERNAL_B0039: dynamicError,
235
- INTERNAL_B0040: dynamicError,
236
- INTERNAL_B0041: dynamicError,
237
- INTERNAL_B0042: dynamicError,
238
- INTERNAL_B0043: dynamicError,
239
- INTERNAL_B0044: dynamicError,
240
- INTERNAL_B0045: dynamicError,
241
- INTERNAL_B0046: dynamicError,
242
- INTERNAL_B0047: dynamicError,
243
- INTERNAL_B0048: {
244
- fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
245
- why: ({ message }) => message === void 0 ? "" : String(message)
246
- },
247
- INTERNAL_B0049: {
248
- fix: "Set `cli: { namespace, command }` on one of the two operations.",
249
- why: ({ message }) => message === void 0 ? "" : String(message)
250
- },
251
- INTERNAL_B0050: {
252
- fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
253
- why: ({ message }) => message === void 0 ? "" : String(message)
254
- },
255
- INTERNAL_R0025: {
256
- fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
257
- why: ({ message }) => message === void 0 ? "" : String(message)
258
- },
259
- INTERNAL_R0026: {
260
- why: "The server parsed a destructive operation that the CLI did not confirm.",
261
- fix: "Review the operation, then run it again with --yes to confirm the change."
262
- },
263
- INTERNAL_C0001: dynamicError,
264
- INTERNAL_C0002: dynamicError,
265
- INTERNAL_R0001: dynamicError,
266
- INTERNAL_R0002: dynamicError,
267
- INTERNAL_R0003: dynamicError,
268
- INTERNAL_R0004: dynamicError,
269
- INTERNAL_R0005: dynamicError,
270
- INTERNAL_R0006: dynamicError,
271
- INTERNAL_R0007: dynamicError,
272
- INTERNAL_R0008: dynamicError,
273
- INTERNAL_R0009: dynamicError,
274
- INTERNAL_R0010: dynamicError,
275
- INTERNAL_R0011: dynamicError
276
- }
277
- });
278
- //#endregion
279
- //#region ../internal/src/standard-schema.ts
280
- function readOwn(value, key) {
281
- if (value === null || Object(value) !== value) return;
282
- try {
283
- return Reflect.get(Object(value), key);
284
- } catch {
285
- return;
286
- }
287
- }
288
- function isRecord(value) {
289
- return value !== null && Object(value) === value && !Array.isArray(value);
290
- }
291
- /**
292
- * Read a Standard JSON Schema projection without throwing.
293
- *
294
- * Returns `undefined` when the schema has no `~standard.jsonSchema`, when the library cannot represent the type
295
- * (Zod throws for `Date`), or when the projection is not an object. Callers decide how to fall back.
296
- */
297
- function standardJsonSchema(schema, direction, target = "draft-2020-12", libraryOptions) {
298
- const jsonSchema = readOwn(readOwn(schema, "~standard"), "jsonSchema");
299
- const project = readOwn(jsonSchema, direction);
300
- if (typeof project !== "function") return;
301
- try {
302
- const result = project.call(jsonSchema, libraryOptions ? {
303
- target,
304
- libraryOptions
305
- } : { target });
306
- return isRecord(result) ? result : void 0;
307
- } catch {
308
- return;
309
- }
310
- }
311
- //#endregion
312
- //#region ../../node_modules/.pnpm/@valibot+to-json-schema@1.8.0_valibot@1.5.0_typescript@6.0.3_/node_modules/@valibot/to-json-schema/dist/index.mjs
313
- /**
314
- * Adds an error message to the errors array.
315
- *
316
- * @param errors The array of error messages.
317
- * @param message The error message to add.
318
- *
319
- * @returns The new errors.
320
- */
321
- function addError(errors, message) {
322
- if (errors) {
323
- errors.push(message);
324
- return errors;
325
- }
326
- return [message];
327
- }
328
- const ESCAPE_REGEX = /[.*+?^${}()|[\]\\]/g;
329
- /**
330
- * Escapes special regex characters in a string.
331
- *
332
- * @param string The string to escape.
333
- *
334
- * @returns The escaped string.
335
- */
336
- function escapeRegExp(string) {
337
- return string.replace(ESCAPE_REGEX, "\\$&");
338
- }
339
- /**
340
- * Throws an error or logs a warning based on the configuration.
341
- *
342
- * @param message The message to throw or log.
343
- * @param config The conversion configuration.
344
- */
345
- function handleError(message, config) {
346
- switch (config?.errorMode) {
347
- case "ignore": break;
348
- case "warn":
349
- console.warn(message);
350
- break;
351
- default: throw new Error(message);
352
- }
353
- }
354
- /**
355
- * Whether a value is JSON compatible for a const keyword.
356
- *
357
- * @param value The value to check.
358
- *
359
- * @returns Whether the value is JSON compatible.
360
- */
361
- function isJsonConstValue(value) {
362
- return typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || typeof value === "string";
363
- }
364
- /**
365
- * Whether values are JSON compatible for an enum keyword.
366
- *
367
- * @param values The values to check.
368
- *
369
- * @returns Whether the values are JSON compatible.
370
- */
371
- function isJsonEnumValues(values) {
372
- return values.every(isJsonConstValue);
373
- }
374
- /**
375
- * Schema reference map with collision-free reference ID allocation.
376
- */
377
- var ReferenceMap = class extends Map {
378
- /**
379
- * Creates an empty schema reference map.
380
- */
381
- constructor() {
382
- super();
383
- this.count = 0;
384
- this.usedIds = /* @__PURE__ */ new Set();
385
- }
386
- /**
387
- * Adds a schema reference and reserves its ID.
388
- *
389
- * @param schema The Valibot schema.
390
- * @param referenceId The reference ID.
391
- *
392
- * @returns The reference map.
393
- */
394
- set(schema, referenceId) {
395
- this.usedIds.add(referenceId);
396
- return super.set(schema, referenceId);
397
- }
398
- /**
399
- * Creates a reference ID that is not yet used.
400
- *
401
- * @param definitions The JSON Schema definitions.
402
- *
403
- * @returns The unused reference ID.
404
- */
405
- createId(definitions) {
406
- while (this.usedIds.has(`${this.count}`) || `${this.count}` in definitions) this.count++;
407
- return `${this.count++}`;
408
- }
409
- };
410
- /**
411
- * Returns the stricter lower bound.
412
- *
413
- * @param current The current lower bound.
414
- * @param value The new lower bound.
415
- *
416
- * @returns The stricter lower bound.
417
- */
418
- function getLowerBound(current, value) {
419
- if (typeof current !== "number" || !Number.isFinite(current) || value > current) return value;
420
- return current;
421
- }
422
- /**
423
- * Returns the stricter upper bound.
424
- *
425
- * @param current The current upper bound.
426
- * @param value The new upper bound.
427
- *
428
- * @returns The stricter upper bound.
429
- */
430
- function getUpperBound(current, value) {
431
- if (typeof current !== "number" || !Number.isFinite(current) || value < current) return value;
432
- return current;
433
- }
434
- /**
435
- * Returns the combined not restriction.
436
- *
437
- * @param current The current not restriction.
438
- * @param value The new not restriction.
439
- *
440
- * @returns The combined not restriction.
441
- */
442
- /* @__NO_SIDE_EFFECTS__ */
443
- function getNotRestriction(current, value) {
444
- return current !== void 0 ? { anyOf: [current, value] } : value;
445
- }
446
- /**
447
- * Intersects allowed values with an existing enum restriction.
448
- *
449
- * @param jsonSchema The JSON Schema object.
450
- * @param values The allowed values.
451
- */
452
- function intersectEnum(jsonSchema, values) {
453
- let enumValues = jsonSchema.enum ?? values;
454
- if (jsonSchema.enum) {
455
- const valueSet = new Set(values);
456
- enumValues = enumValues.filter((value) => valueSet.has(value));
457
- }
458
- if (enumValues.length) jsonSchema.enum = [...new Set(enumValues)];
459
- else {
460
- delete jsonSchema.enum;
461
- jsonSchema.not = /* @__PURE__ */ getNotRestriction(jsonSchema.not, {});
462
- }
463
- }
464
- /**
465
- * Converts any supported Valibot action to the JSON Schema format.
466
- *
467
- * @param jsonSchema The JSON Schema object.
468
- * @param valibotAction The Valibot action object.
469
- * @param config The conversion configuration.
470
- *
471
- * @returns The converted JSON Schema.
472
- */
473
- function convertAction(jsonSchema, valibotAction, config) {
474
- if (config?.ignoreActions?.includes(valibotAction.type)) return jsonSchema;
475
- let errors;
476
- switch (valibotAction.type) {
477
- case "base64":
478
- jsonSchema.contentEncoding = "base64";
479
- break;
480
- case "bic":
481
- case "cuid2":
482
- case "decimal":
483
- case "digits":
484
- case "domain":
485
- case "emoji":
486
- case "hash":
487
- case "hexadecimal":
488
- case "hex_color":
489
- case "isrc":
490
- case "iso_time_second":
491
- case "iso_week":
492
- case "ksuid":
493
- case "mac":
494
- case "mac48":
495
- case "mac64":
496
- case "nanoid":
497
- case "octal":
498
- case "slug":
499
- case "ulid":
500
- if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
501
- else jsonSchema.pattern = valibotAction.requirement.source;
502
- break;
503
- case "description":
504
- jsonSchema.description = valibotAction.description;
505
- break;
506
- case "email":
507
- case "rfc_email":
508
- jsonSchema.format = "email";
509
- break;
510
- case "ends_with":
511
- if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
512
- else jsonSchema.pattern = `${escapeRegExp(valibotAction.requirement)}$`;
513
- break;
514
- case "empty":
515
- if (jsonSchema.type === "array") jsonSchema.maxItems = 0;
516
- else {
517
- if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
518
- jsonSchema.maxLength = 0;
519
- }
520
- break;
521
- case "entries":
522
- if (!Number.isInteger(valibotAction.requirement) || valibotAction.requirement < 0) {
523
- errors = addError(errors, "The requirement of the \"entries\" action must be a non-negative integer.");
524
- break;
525
- }
526
- jsonSchema.minProperties = getLowerBound(jsonSchema.minProperties, valibotAction.requirement);
527
- jsonSchema.maxProperties = getUpperBound(jsonSchema.maxProperties, valibotAction.requirement);
528
- break;
529
- case "examples":
530
- if (Array.isArray(jsonSchema.examples)) jsonSchema.examples = [...jsonSchema.examples, ...valibotAction.examples];
531
- else jsonSchema.examples = valibotAction.examples;
532
- break;
533
- case "gt_value":
534
- if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") {
535
- errors = addError(errors, `The "gt_value" action is not supported on type "${jsonSchema.type}".`);
536
- break;
537
- }
538
- if (!Number.isFinite(valibotAction.requirement)) {
539
- errors = addError(errors, "The requirement of the \"gt_value\" action is not JSON compatible.");
540
- break;
541
- }
542
- if (config?.target === "openapi-3.0") {
543
- errors = addError(errors, "The \"gt_value\" action is not supported for OpenAPI 3.0.");
544
- break;
545
- }
546
- jsonSchema.exclusiveMinimum = getLowerBound(jsonSchema.exclusiveMinimum, valibotAction.requirement);
547
- break;
548
- case "includes":
549
- if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
550
- else jsonSchema.pattern = escapeRegExp(valibotAction.requirement);
551
- break;
552
- case "integer":
553
- jsonSchema.type = "integer";
554
- break;
555
- case "ipv4":
556
- jsonSchema.format = "ipv4";
557
- break;
558
- case "ipv6":
559
- jsonSchema.format = "ipv6";
560
- break;
561
- case "iso_date":
562
- jsonSchema.format = "date";
563
- break;
564
- case "iso_date_time":
565
- case "iso_timestamp":
566
- jsonSchema.format = "date-time";
567
- break;
568
- case "iso_time":
569
- jsonSchema.format = "time";
570
- break;
571
- case "jws_compact":
572
- if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
573
- else jsonSchema.pattern = valibotAction.requirement.source;
574
- break;
575
- case "length":
576
- if (!Number.isInteger(valibotAction.requirement) || valibotAction.requirement < 0) {
577
- errors = addError(errors, "The requirement of the \"length\" action must be a non-negative integer.");
578
- break;
579
- }
580
- if (jsonSchema.type === "array") {
581
- jsonSchema.minItems = getLowerBound(jsonSchema.minItems, valibotAction.requirement);
582
- jsonSchema.maxItems = getUpperBound(jsonSchema.maxItems, valibotAction.requirement);
583
- } else {
584
- if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
585
- jsonSchema.minLength = getLowerBound(jsonSchema.minLength, valibotAction.requirement);
586
- jsonSchema.maxLength = getUpperBound(jsonSchema.maxLength, valibotAction.requirement);
587
- }
588
- break;
589
- case "lt_value":
590
- if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") {
591
- errors = addError(errors, `The "lt_value" action is not supported on type "${jsonSchema.type}".`);
592
- break;
593
- }
594
- if (!Number.isFinite(valibotAction.requirement)) {
595
- errors = addError(errors, "The requirement of the \"lt_value\" action is not JSON compatible.");
596
- break;
597
- }
598
- if (config?.target === "openapi-3.0") {
599
- errors = addError(errors, "The \"lt_value\" action is not supported for OpenAPI 3.0.");
600
- break;
601
- }
602
- jsonSchema.exclusiveMaximum = getUpperBound(jsonSchema.exclusiveMaximum, valibotAction.requirement);
603
- break;
604
- case "max_entries":
605
- if (!Number.isInteger(valibotAction.requirement) || valibotAction.requirement < 0) {
606
- errors = addError(errors, "The requirement of the \"max_entries\" action must be a non-negative integer.");
607
- break;
608
- }
609
- jsonSchema.maxProperties = getUpperBound(jsonSchema.maxProperties, valibotAction.requirement);
610
- break;
611
- case "max_length":
612
- if (!Number.isInteger(valibotAction.requirement) || valibotAction.requirement < 0) {
613
- errors = addError(errors, "The requirement of the \"max_length\" action must be a non-negative integer.");
614
- break;
615
- }
616
- if (jsonSchema.type === "array") jsonSchema.maxItems = getUpperBound(jsonSchema.maxItems, valibotAction.requirement);
617
- else {
618
- if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
619
- jsonSchema.maxLength = getUpperBound(jsonSchema.maxLength, valibotAction.requirement);
620
- }
621
- break;
622
- case "max_value":
623
- if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") {
624
- errors = addError(errors, `The "max_value" action is not supported on type "${jsonSchema.type}".`);
625
- break;
626
- }
627
- if (!Number.isFinite(valibotAction.requirement)) {
628
- errors = addError(errors, "The requirement of the \"max_value\" action is not JSON compatible.");
629
- break;
630
- }
631
- jsonSchema.maximum = getUpperBound(jsonSchema.maximum, valibotAction.requirement);
632
- break;
633
- case "metadata":
634
- if (typeof valibotAction.metadata.title === "string") jsonSchema.title = valibotAction.metadata.title;
635
- if (typeof valibotAction.metadata.description === "string") jsonSchema.description = valibotAction.metadata.description;
636
- if (Array.isArray(valibotAction.metadata.examples)) if (Array.isArray(jsonSchema.examples)) jsonSchema.examples = [...jsonSchema.examples, ...valibotAction.metadata.examples];
637
- else jsonSchema.examples = valibotAction.metadata.examples;
638
- for (const key of Object.keys(valibotAction.metadata)) if (key !== "title" && key !== "description" && key !== "examples" && key !== "__proto__") jsonSchema[key] = valibotAction.metadata[key];
639
- break;
640
- case "min_entries":
641
- if (!Number.isInteger(valibotAction.requirement) || valibotAction.requirement < 0) {
642
- errors = addError(errors, "The requirement of the \"min_entries\" action must be a non-negative integer.");
643
- break;
644
- }
645
- jsonSchema.minProperties = getLowerBound(jsonSchema.minProperties, valibotAction.requirement);
646
- break;
647
- case "min_length":
648
- if (!Number.isInteger(valibotAction.requirement) || valibotAction.requirement < 0) {
649
- errors = addError(errors, "The requirement of the \"min_length\" action must be a non-negative integer.");
650
- break;
651
- }
652
- if (jsonSchema.type === "array") jsonSchema.minItems = getLowerBound(jsonSchema.minItems, valibotAction.requirement);
653
- else {
654
- if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
655
- jsonSchema.minLength = getLowerBound(jsonSchema.minLength, valibotAction.requirement);
656
- }
657
- break;
658
- case "min_value":
659
- if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") {
660
- errors = addError(errors, `The "min_value" action is not supported on type "${jsonSchema.type}".`);
661
- break;
662
- }
663
- if (!Number.isFinite(valibotAction.requirement)) {
664
- errors = addError(errors, "The requirement of the \"min_value\" action is not JSON compatible.");
665
- break;
666
- }
667
- jsonSchema.minimum = getLowerBound(jsonSchema.minimum, valibotAction.requirement);
668
- break;
669
- case "multiple_of":
670
- jsonSchema.multipleOf = valibotAction.requirement;
671
- break;
672
- case "non_empty":
673
- if (jsonSchema.type === "array") jsonSchema.minItems = getLowerBound(jsonSchema.minItems, 1);
674
- else {
675
- if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
676
- jsonSchema.minLength = getLowerBound(jsonSchema.minLength, 1);
677
- }
678
- break;
679
- case "not_value":
680
- if (!isJsonConstValue(valibotAction.requirement)) {
681
- errors = addError(errors, "The requirement of the \"not_value\" action is not JSON compatible.");
682
- break;
683
- }
684
- jsonSchema.not = /* @__PURE__ */ getNotRestriction(jsonSchema.not, config?.target === "openapi-3.0" ? { enum: [valibotAction.requirement] } : { const: valibotAction.requirement });
685
- break;
686
- case "not_values":
687
- if (!isJsonEnumValues(valibotAction.requirement)) {
688
- errors = addError(errors, "A requirement of the \"not_values\" action is not JSON compatible.");
689
- break;
690
- }
691
- if (valibotAction.requirement.length) jsonSchema.not = /* @__PURE__ */ getNotRestriction(jsonSchema.not, { enum: [...new Set(valibotAction.requirement)] });
692
- break;
693
- case "regex":
694
- if (valibotAction.requirement.flags) errors = addError(errors, "RegExp flags are not supported by JSON Schema.");
695
- if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
696
- else jsonSchema.pattern = valibotAction.requirement.source;
697
- break;
698
- case "safe_integer":
699
- jsonSchema.type = "integer";
700
- jsonSchema.minimum = getLowerBound(jsonSchema.minimum, Number.MIN_SAFE_INTEGER);
701
- jsonSchema.maximum = getUpperBound(jsonSchema.maximum, Number.MAX_SAFE_INTEGER);
702
- break;
703
- case "starts_with":
704
- if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
705
- else jsonSchema.pattern = `^${escapeRegExp(valibotAction.requirement)}`;
706
- break;
707
- case "title":
708
- jsonSchema.title = valibotAction.title;
709
- break;
710
- case "url":
711
- jsonSchema.format = "uri";
712
- break;
713
- case "uuid":
714
- jsonSchema.format = "uuid";
715
- break;
716
- case "value":
717
- if (!isJsonConstValue(valibotAction.requirement)) {
718
- errors = addError(errors, "The requirement of the \"value\" action is not JSON compatible.");
719
- break;
720
- }
721
- if (config?.target === "openapi-3.0") intersectEnum(jsonSchema, [valibotAction.requirement]);
722
- else if ("const" in jsonSchema && jsonSchema.const !== valibotAction.requirement) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with a different "const" restriction.`);
723
- else jsonSchema.const = valibotAction.requirement;
724
- break;
725
- case "values":
726
- if (!isJsonEnumValues(valibotAction.requirement)) {
727
- errors = addError(errors, "A requirement of the \"values\" action is not JSON compatible.");
728
- break;
729
- }
730
- intersectEnum(jsonSchema, valibotAction.requirement);
731
- break;
732
- default: errors = addError(errors, `The "${valibotAction.type}" action cannot be converted to JSON Schema.`);
733
- }
734
- if (config?.overrideAction) {
735
- const actionOverride = config.overrideAction({
736
- valibotAction,
737
- jsonSchema,
738
- errors
739
- });
740
- if (actionOverride) return { ...actionOverride };
741
- }
742
- if (errors) for (const message of errors) handleError(message, config);
743
- return jsonSchema;
744
- }
745
- /**
746
- * Flattens a Valibot pipe by recursively expanding nested pipes.
747
- *
748
- * @param pipe The pipeline to flatten.
749
- *
750
- * @returns A flat pipeline.
751
- */
752
- function flattenPipe(pipe) {
753
- return pipe.flatMap((item) => "pipe" in item ? flattenPipe(item.pipe) : item);
754
- }
755
- /**
756
- * Returns the JSON Pointer reference for a definition key.
757
- *
758
- * @param referenceId The unescaped definition key.
759
- *
760
- * @returns The encoded JSON Pointer fragment.
761
- */
762
- function getDefinitionRef(referenceId) {
763
- return `#/$defs/${referenceId.replaceAll("~", "~0").replaceAll("/", "~1")}`;
764
- }
765
- /**
766
- * Converts any supported Valibot schema to the JSON Schema format.
767
- *
768
- * @param jsonSchema The JSON Schema object.
769
- * @param valibotSchema The Valibot schema object.
770
- * @param config The conversion configuration.
771
- * @param context The conversion context.
772
- * @param skipRef Whether to skip using a reference.
773
- *
774
- * @returns The converted JSON Schema.
775
- */
776
- function convertSchema(jsonSchema, valibotSchema, config, context, skipRef = false) {
777
- if (!skipRef) {
778
- const referenceId = context.referenceMap.get(valibotSchema);
779
- if (referenceId) {
780
- jsonSchema.$ref = getDefinitionRef(referenceId);
781
- if (config?.overrideRef) {
782
- const refOverride = config.overrideRef({
783
- ...context,
784
- referenceId,
785
- valibotSchema,
786
- jsonSchema
787
- });
788
- if (refOverride) jsonSchema.$ref = refOverride;
789
- }
790
- return jsonSchema;
791
- }
792
- }
793
- if ("pipe" in valibotSchema) {
794
- const flatPipe = flattenPipe(valibotSchema.pipe);
795
- let startIndex = 0;
796
- let stopIndex = flatPipe.length - 1;
797
- if (config?.typeMode === "input") {
798
- const inputStopIndex = flatPipe.slice(1).findIndex((item) => item.kind === "schema" || item.kind === "transformation" && (item.type === "find_item" || item.type === "parse_json" || item.type === "raw_transform" || item.type === "reduce_items" || item.type === "stringify_json" || item.type === "to_bigint" || item.type === "to_boolean" || item.type === "to_date" || item.type === "to_number" || item.type === "to_string" || item.type === "transform"));
799
- if (inputStopIndex !== -1) stopIndex = inputStopIndex;
800
- } else if (config?.typeMode === "output") {
801
- const outputStartIndex = flatPipe.findLastIndex((item) => item.kind === "schema");
802
- if (outputStartIndex !== -1) startIndex = outputStartIndex;
803
- }
804
- for (let index = startIndex; index <= stopIndex; index++) {
805
- const valibotPipeItem = flatPipe[index];
806
- if (valibotPipeItem.kind === "schema") {
807
- if (index > startIndex) handleError("Set the \"typeMode\" config to \"input\" or \"output\" to convert pipelines with multiple schemas.", config);
808
- jsonSchema = convertSchema(jsonSchema, valibotPipeItem, config, context, true);
809
- } else jsonSchema = convertAction(jsonSchema, valibotPipeItem, config);
810
- }
811
- return jsonSchema;
812
- }
813
- let errors;
814
- switch (valibotSchema.type) {
815
- case "boolean":
816
- jsonSchema.type = "boolean";
817
- break;
818
- case "null":
819
- if (config?.target === "openapi-3.0") jsonSchema.enum = [null];
820
- else jsonSchema.type = "null";
821
- break;
822
- case "number":
823
- jsonSchema.type = "number";
824
- break;
825
- case "string":
826
- jsonSchema.type = "string";
827
- break;
828
- case "array":
829
- jsonSchema.type = "array";
830
- jsonSchema.items = convertSchema({}, valibotSchema.item, config, context);
831
- break;
832
- case "tuple":
833
- case "tuple_with_rest":
834
- case "loose_tuple":
835
- case "strict_tuple":
836
- jsonSchema.type = "array";
837
- if (config?.target === "openapi-3.0") {
838
- jsonSchema.items = { anyOf: [] };
839
- jsonSchema.minItems = valibotSchema.items.length;
840
- for (const item of valibotSchema.items) jsonSchema.items.anyOf.push(convertSchema({}, item, config, context));
841
- if (valibotSchema.type === "tuple_with_rest") jsonSchema.items.anyOf.push(convertSchema({}, valibotSchema.rest, config, context));
842
- else if (valibotSchema.type === "strict_tuple" || valibotSchema.type === "tuple") jsonSchema.maxItems = valibotSchema.items.length;
843
- } else if (config?.target === "draft-2020-12") {
844
- jsonSchema.prefixItems = [];
845
- jsonSchema.minItems = valibotSchema.items.length;
846
- for (const item of valibotSchema.items) jsonSchema.prefixItems.push(convertSchema({}, item, config, context));
847
- if (valibotSchema.type === "tuple_with_rest") jsonSchema.items = convertSchema({}, valibotSchema.rest, config, context);
848
- else if (valibotSchema.type === "strict_tuple") jsonSchema.items = false;
849
- } else {
850
- jsonSchema.items = [];
851
- jsonSchema.minItems = valibotSchema.items.length;
852
- for (const item of valibotSchema.items) jsonSchema.items.push(convertSchema({}, item, config, context));
853
- if (valibotSchema.type === "tuple_with_rest") jsonSchema.additionalItems = convertSchema({}, valibotSchema.rest, config, context);
854
- else if (valibotSchema.type === "strict_tuple") jsonSchema.additionalItems = false;
855
- }
856
- break;
857
- case "object":
858
- case "object_with_rest":
859
- case "loose_object":
860
- case "strict_object":
861
- jsonSchema.type = "object";
862
- jsonSchema.properties = {};
863
- jsonSchema.required = [];
864
- for (const key in valibotSchema.entries) {
865
- const entry = valibotSchema.entries[key];
866
- jsonSchema.properties[key] = convertSchema({}, entry, config, context);
867
- if (entry.type !== "exact_optional" && entry.type !== "nullish" && entry.type !== "optional") jsonSchema.required.push(key);
868
- }
869
- if (valibotSchema.type === "object_with_rest") jsonSchema.additionalProperties = convertSchema({}, valibotSchema.rest, config, context);
870
- else if (valibotSchema.type === "strict_object") jsonSchema.additionalProperties = false;
871
- break;
872
- case "record":
873
- if (config?.target === "openapi-3.0" && "pipe" in valibotSchema.key) errors = addError(errors, "The \"record\" schema with a schema for the key that contains a \"pipe\" cannot be converted to JSON Schema.");
874
- if (valibotSchema.key.type !== "string") errors = addError(errors, `The "record" schema with the "${valibotSchema.key.type}" schema for the key cannot be converted to JSON Schema.`);
875
- jsonSchema.type = "object";
876
- if (config?.target !== "openapi-3.0") jsonSchema.propertyNames = convertSchema({}, valibotSchema.key, config, context);
877
- jsonSchema.additionalProperties = convertSchema({}, valibotSchema.value, config, context);
878
- break;
879
- case "any":
880
- case "unknown": break;
881
- case "never":
882
- jsonSchema.not = {};
883
- break;
884
- case "nullable":
885
- case "nullish":
886
- if (config?.target === "openapi-3.0") {
887
- const innerSchema = convertSchema({}, valibotSchema.wrapped, config, context);
888
- Object.assign(jsonSchema, innerSchema);
889
- jsonSchema.nullable = true;
890
- } else jsonSchema.anyOf = [convertSchema({}, valibotSchema.wrapped, config, context), { type: "null" }];
891
- if (valibotSchema.default !== void 0) jsonSchema.default = typeof valibotSchema.default === "function" ? valibotSchema.default() : valibotSchema.default;
892
- break;
893
- case "exact_optional":
894
- case "optional":
895
- case "undefinedable":
896
- jsonSchema = convertSchema(jsonSchema, valibotSchema.wrapped, config, context);
897
- if (valibotSchema.default !== void 0) jsonSchema.default = typeof valibotSchema.default === "function" ? valibotSchema.default() : valibotSchema.default;
898
- break;
899
- case "literal":
900
- if (!isJsonConstValue(valibotSchema.literal)) {
901
- errors = addError(errors, "The value of the \"literal\" schema is not JSON compatible.");
902
- break;
903
- }
904
- if (config?.target === "openapi-3.0") jsonSchema.enum = [valibotSchema.literal];
905
- else jsonSchema.const = valibotSchema.literal;
906
- break;
907
- case "enum":
908
- case "picklist": {
909
- const options = valibotSchema.options;
910
- if (!options.every((option) => typeof option === "string" || typeof option === "number" && Number.isFinite(option))) {
911
- errors = addError(errors, `An option of the "${valibotSchema.type}" schema is not JSON compatible.`);
912
- break;
913
- }
914
- jsonSchema.enum = options;
915
- if (options.every((option) => typeof option === "string")) jsonSchema.type = "string";
916
- else if (options.every((option) => typeof option === "number")) jsonSchema.type = "number";
917
- else if (config?.target !== "openapi-3.0") jsonSchema.type = ["string", "number"];
918
- break;
919
- }
920
- case "union":
921
- jsonSchema.anyOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context));
922
- break;
923
- case "variant":
924
- jsonSchema.oneOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context));
925
- break;
926
- case "intersect":
927
- jsonSchema.allOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context));
928
- break;
929
- case "lazy": {
930
- let wrappedValibotSchema = context.getterMap.get(valibotSchema.getter);
931
- if (!wrappedValibotSchema) {
932
- wrappedValibotSchema = valibotSchema.getter(void 0);
933
- context.getterMap.set(valibotSchema.getter, wrappedValibotSchema);
934
- }
935
- let referenceId = context.referenceMap.get(wrappedValibotSchema);
936
- if (!referenceId) {
937
- referenceId = context.referenceMap.createId(context.definitions);
938
- context.referenceMap.set(wrappedValibotSchema, referenceId);
939
- context.definitions[referenceId] = convertSchema({}, wrappedValibotSchema, config, context, true);
940
- }
941
- jsonSchema.$ref = getDefinitionRef(referenceId);
942
- if (config?.overrideRef) {
943
- const refOverride = config.overrideRef({
944
- ...context,
945
- referenceId,
946
- valibotSchema: wrappedValibotSchema,
947
- jsonSchema
948
- });
949
- if (refOverride) jsonSchema.$ref = refOverride;
950
- }
951
- break;
952
- }
953
- default: errors = addError(errors, `The "${valibotSchema.type}" schema cannot be converted to JSON Schema.`);
954
- }
955
- if (config?.overrideSchema) {
956
- const schemaOverride = config.overrideSchema({
957
- ...context,
958
- referenceId: context.referenceMap.get(valibotSchema),
959
- valibotSchema,
960
- jsonSchema,
961
- errors
962
- });
963
- if (schemaOverride) return { ...schemaOverride };
964
- }
965
- if (errors) for (const message of errors) handleError(message, config);
966
- return jsonSchema;
967
- }
968
- /**
969
- * Converts a Valibot schema to the JSON Schema format.
970
- *
971
- * @param schema The Valibot schema object.
972
- * @param config The JSON Schema configuration.
973
- *
974
- * @returns The converted JSON Schema.
975
- */
976
- function toJsonSchema(schema, config) {
977
- const context = {
978
- definitions: {},
979
- referenceMap: new ReferenceMap(),
980
- getterMap: /* @__PURE__ */ new Map()
981
- };
982
- const definitions = config?.definitions ?? void 0;
983
- if (definitions) {
984
- for (const key in definitions) context.referenceMap.set(definitions[key], key);
985
- for (const key in definitions) context.definitions[key] = convertSchema({}, definitions[key], config, context, true);
986
- }
987
- const jsonSchema = convertSchema({}, schema, config, context);
988
- const target = config?.target ?? "draft-07";
989
- if (target === "draft-2020-12") jsonSchema.$schema = "https://json-schema.org/draft/2020-12/schema";
990
- else if (target === "draft-07") jsonSchema.$schema = "http://json-schema.org/draft-07/schema#";
991
- if (context.referenceMap.size) jsonSchema.$defs = context.definitions;
992
- return jsonSchema;
993
- }
994
- //#endregion
995
- //#region ../internal/src/valibot.ts
996
- const valibotTargets = /* @__PURE__ */ new Set([
997
- "draft-07",
998
- "draft-2020-12",
999
- "openapi-3.0"
1000
- ]);
1001
- function isValibotTarget(value) {
1002
- return valibotTargets.has(String(value));
1003
- }
1004
- /**
1005
- * Add Standard JSON Schema conversion to a plain Valibot schema. Valibot schemas validate as Standard Schema but carry
1006
- * no JSON Schema, so forms, tools, and model providers would get no shape for them. Other schemas, Valibot schemas that
1007
- * already convert, and async Valibot schemas return unchanged. The copy keeps every Valibot property, so validation
1008
- * does not change.
1009
- *
1010
- * `target` fixes the JSON Schema dialect. Without it, each conversion uses the dialect that the caller asks for.
1011
- */
1012
- function withValibotJsonSchema(schema, options = {}) {
1013
- const standard = schema["~standard"];
1014
- if (standard.vendor !== "valibot" || Reflect.get(schema, "async") === true) return schema;
1015
- if (Object.hasOwn(standard, "jsonSchema") && standard.jsonSchema) return schema;
1016
- const convert = (typeMode) => (request) => {
1017
- const target = options.target ?? request.target;
1018
- if (!isValibotTarget(target)) throw new Error(`[vitehub] Valibot cannot convert a schema to the ${String(target)} JSON Schema target.`);
1019
- return toJsonSchema(schema, {
1020
- target,
1021
- typeMode,
1022
- errorMode: "ignore"
1023
- });
1024
- };
1025
- return {
1026
- ...schema,
1027
- "~standard": {
1028
- ...standard,
1029
- jsonSchema: {
1030
- input: convert("input"),
1031
- output: convert("output")
1032
- }
1033
- }
1034
- };
1035
- }
1036
- //#endregion
1037
- //#region ../internal/src/operations.ts
1038
- /** Path of the operation RPC under the app. Dev servers and deployed apps serve it the same way. */
1039
- const operationRpcPath = "/_vitehub/rpc/__call";
1040
- /** Header that proves the caller is not a browser page. A foreign page cannot send it without a CORS preflight. */
1041
- const operationRpcHeader = "x-vitehub-console";
1042
- /** Response header of the local dev RPC. Its value is {@link projectRootHash} of the project that the server runs. */
1043
- const operationRootHeader = "x-vitehub-root";
1044
- const operationExpectedRootsHeader = "x-vitehub-expected-roots";
1045
- /** A short stable hash of a project root. The CLI uses it to see that the dev server runs its own project. */
1046
- function projectRootHash(root) {
1047
- const normalized = root.replace(/\\/g, "/").replace(/\/+$/, "");
1048
- let first = 3735928559;
1049
- let second = 1103547991;
1050
- for (let index = 0; index < normalized.length; index++) {
1051
- const code = normalized.charCodeAt(index);
1052
- first = Math.imul(first ^ code, 2654435761);
1053
- second = Math.imul(second ^ code, 1597334677);
1054
- }
1055
- first = Math.imul(first ^ first >>> 16, 2246822507) ^ Math.imul(second ^ second >>> 13, 3266489909);
1056
- second = Math.imul(second ^ second >>> 16, 2246822507) ^ Math.imul(first ^ first >>> 13, 3266489909);
1057
- return `${(second >>> 0).toString(16).padStart(8, "0")}${(first >>> 0).toString(16).padStart(8, "0")}`;
1058
- }
1059
- /** Header that names the tool behind a call. `cli` marks `vitehub` commands. */
1060
- const operationSurfaceHeader = "x-vitehub-surface";
1061
- /** Generated CLI commands ask the server to check confirmation after it parses the input. */
1062
- const operationConfirmationHeader = "x-vitehub-confirmation";
1063
- const nameFormat = /^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/;
1064
- const kinds = /* @__PURE__ */ new Set([
1065
- "read",
1066
- "write",
1067
- "destructive"
1068
- ]);
1069
- function isObject(value) {
1070
- return value !== null && Object(value) === value && !Array.isArray(value);
1071
- }
1072
- function invalidDefinition(name, reason) {
1073
- return internalErrorDiagnostics.INTERNAL_R0020({ message: `[vitehub] Operation ${JSON.stringify(name)} is invalid: ${reason}` });
1074
- }
1075
- function checkDefinition(definition) {
1076
- if (!isObject(definition)) throw invalidDefinition(void 0, "defineOperation() takes an object.");
1077
- const { name } = definition;
1078
- if (String(name) !== name || !nameFormat.test(name)) throw invalidDefinition(name, "the name must look like `section.verb`, in lower case.");
1079
- if (String(definition.description) !== definition.description || !definition.description) throw invalidDefinition(name, "add a one sentence description.");
1080
- const { section } = definition;
1081
- if (section !== false && !(section instanceof Function) && (String(section) !== section || !section)) throw invalidDefinition(name, "section must be a Console section id, a function, or false.");
1082
- if (!kinds.has(String(definition.kind))) throw invalidDefinition(name, "kind must be \"read\", \"write\", or \"destructive\".");
1083
- const input = definition.input;
1084
- if (!isObject(input) || !isObject(input["~standard"]) || !(input["~standard"].validate instanceof Function)) throw invalidDefinition(name, "input must be a Standard Schema, such as a valibot object.");
1085
- if (!(definition.run instanceof Function)) throw invalidDefinition(name, "run must be a function.");
1086
- const { maxRequestBytes } = definition;
1087
- if (maxRequestBytes !== void 0 && (!Number.isInteger(maxRequestBytes) || Number(maxRequestBytes) < 65536)) throw invalidDefinition(name, `maxRequestBytes can only raise the limit above ${defaultRequestBytes} bytes (64 KiB).`);
1088
- if (definition.readOnlyWhen !== void 0 && !(definition.readOnlyWhen instanceof Function)) throw invalidDefinition(name, "readOnlyWhen must be a function.");
1089
- }
1090
- /** The default limit of a call, in bytes. */
1091
- const defaultRequestBytes = 65536;
1092
- /** CLI namespaces owned by built-in commands. */
1093
- const reservedOperationNamespaces = ["inspect", "provision"];
1094
- /** Input keys that the generated CLI commands read themselves. */
1095
- const reservedOperationFlags = [
1096
- "input",
1097
- "json",
1098
- "timeout",
1099
- "url",
1100
- "yes"
1101
- ];
1102
- /**
1103
- * Define one operation. The Console, the CLI, MCP, and agent tools call the same definition. Contribute it with
1104
- * `vitehub: { operations: [{ module, export }] }` on a Vite plugin.
1105
- */
1106
- function defineOperation(definition) {
1107
- checkDefinition(definition);
1108
- const defined = {
1109
- ...definition,
1110
- input: withValibotJsonSchema(definition.input)
1111
- };
1112
- const properties = operationInputJsonSchema(defined).properties;
1113
- const clashes = isObject(properties) ? Object.keys(properties).filter((key) => reservedOperationFlags.includes(key)) : [];
1114
- if (clashes.length) throw invalidDefinition(definition.name, `the input key ${clashes.map((key) => JSON.stringify(key)).join(", ")} is a CLI flag of every command (${reservedOperationFlags.join(", ")}). Rename it.`);
1115
- return defined;
1116
- }
1117
- function isOperation(value) {
1118
- try {
1119
- checkDefinition(value);
1120
- return true;
1121
- } catch {
1122
- return false;
1123
- }
1124
- }
1125
- function pluginName(plugin) {
1126
- const name = Reflect.get(plugin, "name");
1127
- return String(name) === name && name ? name : "unnamed plugin";
1128
- }
1129
- /** Reads `plugin.vitehub.operations` from resolved Vite plugins. The same module and export from two plugins counts once. */
1130
- async function collectOperationContributions(plugins) {
1131
- const collected = /* @__PURE__ */ new Map();
1132
- for (const plugin of plugins) {
1133
- if (!isObject(plugin) || !Object.hasOwn(plugin, "vitehub")) continue;
1134
- const declared = Reflect.get(Object(Reflect.get(plugin, "vitehub")), "operations");
1135
- if (declared === void 0) continue;
1136
- const entries = declared instanceof Function ? await declared() : declared;
1137
- const owner = pluginName(plugin);
1138
- if (!Array.isArray(entries)) throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] ${owner} sets vitehub.operations, which must be a list of { module, export }.` });
1139
- for (const entry of entries) {
1140
- if (!isObject(entry) || String(entry.module) !== entry.module || !entry.module) throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] ${owner} contributes an operation entry without a module.` });
1141
- const exportName = String(entry.export) === entry.export && entry.export ? entry.export : "default";
1142
- const key = `${entry.module}#${exportName}`;
1143
- if (collected.has(key)) continue;
1144
- collected.set(key, {
1145
- module: entry.module,
1146
- export: exportName,
1147
- plugin: owner,
1148
- ...entry.load instanceof Function ? { load: entry.load } : {},
1149
- ...entry.runtime === false ? { runtime: false } : {}
1150
- });
1151
- }
1152
- }
1153
- return [...collected.values()];
1154
- }
1155
- /** Operations of one module export, flat. A single operation or an array both work. */
1156
- function operationsOf(value) {
1157
- const list = Array.isArray(value) ? value : [value];
1158
- const operations = [];
1159
- for (const item of list) {
1160
- if (!isOperation(item)) throw invalidDefinition(isObject(item) ? item.name : void 0, "a contributed export must hold defineOperation() results.");
1161
- operations.push(item);
1162
- }
1163
- return operations;
1164
- }
1165
- /** The CLI namespace and command of an operation. Defaults: the section (or the name prefix) and the verb. */
1166
- function operationCliPath(operation) {
1167
- const dot = operation.name.indexOf(".");
1168
- return {
1169
- command: operation.cli?.command ?? operation.name.slice(dot + 1),
1170
- namespace: operation.cli?.namespace ?? (typeof operation.section === "string" ? operation.section : operation.name.slice(0, dot))
1171
- };
1172
- }
1173
- /**
1174
- * The MCP tool name of an operation: every character outside `[a-zA-Z0-9_-]` becomes `_`, since clients such as
1175
- * Claude reject a dot in a tool name. `content.publish` is `content_publish`.
1176
- */
1177
- function operationToolName(name) {
1178
- return name.replace(/[^\w-]/g, "_");
1179
- }
1180
- /** Build the registry by name. A duplicate name or CLI command fails with `INTERNAL_B0048` or `INTERNAL_B0049`, two MCP tool names that match with `INTERNAL_B0050`. */
1181
- function createOperationRegistry(sources) {
1182
- const byName = /* @__PURE__ */ new Map();
1183
- for (const source of sources) for (const operation of source.operations) {
1184
- const existing = byName.get(operation.name);
1185
- if (existing && existing.operation !== operation) {
1186
- const owners = [existing.plugin, source.plugin].filter(Boolean).join(" and ");
1187
- throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] Two operations are named ${JSON.stringify(operation.name)}${owners ? ` (${owners})` : ""}.` });
1188
- }
1189
- byName.set(operation.name, {
1190
- operation,
1191
- ...source.plugin ? { plugin: source.plugin } : {}
1192
- });
1193
- }
1194
- const operations = [...byName.values()].map((entry) => entry.operation).sort((left, right) => left.name.localeCompare(right.name));
1195
- const commands = /* @__PURE__ */ new Map();
1196
- for (const operation of operations) {
1197
- const { command, namespace } = operationCliPath(operation);
1198
- if (reservedOperationNamespaces.includes(namespace)) throw invalidDefinition(operation.name, `the CLI namespace ${JSON.stringify(namespace)} is reserved for built-in commands. Set cli.namespace to another name.`);
1199
- const key = `${namespace} ${command}`;
1200
- const other = commands.get(key);
1201
- if (other) throw internalErrorDiagnostics.INTERNAL_B0049({ message: `[vitehub] The operations ${JSON.stringify(other.name)} and ${JSON.stringify(operation.name)} are both the CLI command \`vitehub ${key}\`.` });
1202
- commands.set(key, operation);
1203
- }
1204
- const tools = /* @__PURE__ */ new Map();
1205
- for (const operation of operations) {
1206
- if (operation.mcp === false) continue;
1207
- const tool = operationToolName(operation.name);
1208
- const other = tools.get(tool);
1209
- if (other) throw internalErrorDiagnostics.INTERNAL_B0050({ message: `[vitehub] The operations ${JSON.stringify(other.name)} and ${JSON.stringify(operation.name)} are both the MCP tool ${JSON.stringify(tool)}.` });
1210
- tools.set(tool, operation);
1211
- }
1212
- return {
1213
- get: (name) => byName.get(name)?.operation,
1214
- list: () => [...operations]
1215
- };
1216
- }
1217
- /** JSON Schema of the input, for CLI flags and MCP tool schemas. Falls back to an open object. */
1218
- function operationInputJsonSchema(operation) {
1219
- return standardJsonSchema(operation.input, "input") ?? { type: "object" };
1220
- }
1221
- /** Issues of a failed Standard Schema check as one short line per issue. */
1222
- function describeInputIssues(issues) {
1223
- return issues.slice(0, 5).map((issue) => {
1224
- const path = (issue.path ?? []).map((segment) => String(isObject(segment) && "key" in segment ? segment.key : segment)).join(".");
1225
- return path ? `${path}: ${issue.message}` : issue.message;
1226
- }).join(" ");
1227
- }
1228
- /** Validate `input` with the schema of the operation. Throws `INTERNAL_R0022` with `status: 400`. */
1229
- async function parseOperationInput(operation, input) {
1230
- const result = await operation.input["~standard"].validate(input ?? {});
1231
- if (!result.issues) return result.value;
1232
- const error = internalErrorDiagnostics.INTERNAL_R0022({ message: `Invalid input for ${operation.name}. ${describeInputIssues(result.issues)}` });
1233
- throw Object.assign(error, { status: 400 });
1234
- }
1235
- /** The section that grants a call, or `false` for any Console user. `undefined` means the input names no valid section. */
1236
- function operationSection(operation, input) {
1237
- const section = operation.section;
1238
- return section instanceof Function ? section(input) : section;
1239
- }
1240
- /**
1241
- * Whether the checked access covers the section. Without `call`, a read-only grant (`"kv:read"`) counts, so the answer
1242
- * is whether the section is visible. With `call`, a read-only grant allows only a `read` operation or a call that only
1243
- * reads. Every surface (RPC, CLI, agents, MCP) checks access here.
1244
- */
1245
- function operationAccessAllows(access, section, call) {
1246
- if (section === void 0) return false;
1247
- if (section === false || access.sections === "all") return true;
1248
- if (access.sections.includes(section)) return true;
1249
- if (!access.sections.includes(`${section}:read`)) return false;
1250
- return call === void 0 || call.kind === "read" || call.readOnly === true;
1251
- }
1252
- /** The kind of one call of an operation: a `readOnlyWhen` match makes a write operation a read. */
1253
- function operationCall(operation, input) {
1254
- return {
1255
- kind: operation.kind,
1256
- readOnly: operation.readOnlyWhen?.(input) === true
1257
- };
1258
- }
1259
- function text(value) {
1260
- return String(value) === value && value ? value : void 0;
1261
- }
1262
- /** Read the shared failure fields from anything an operation throws. */
1263
- function toOperationFailure(error) {
1264
- const value = Object(error);
1265
- const rawStatus = Reflect.get(value, "status") ?? Reflect.get(value, "statusCode");
1266
- const status = Number.isInteger(rawStatus) && Number(rawStatus) >= 400 && Number(rawStatus) <= 599 ? Number(rawStatus) : 500;
1267
- const message = text(Reflect.get(value, "statusMessage")) ?? (error instanceof Error ? error.message : void 0) ?? "The operation failed.";
1268
- const failure = {
1269
- code: text(Reflect.get(value, "code")) ?? (status >= 500 ? "OPERATION_FAILED" : "OPERATION_REJECTED"),
1270
- message,
1271
- status
1272
- };
1273
- const fix = text(Reflect.get(value, "fix"));
1274
- const docs = text(Reflect.get(value, "docs"));
1275
- const details = Reflect.get(value, "details");
1276
- if (fix) failure.fix = fix;
1277
- if (docs) failure.docs = docs;
1278
- if (isObject(details)) failure.details = details;
1279
- return failure;
1280
- }
1281
- /**
1282
- * Run one operation by name: validate the input, check the section against `context.access`, and run. Never throws.
1283
- * The Console RPC and agent tools call it.
1284
- */
1285
- async function runOperation(registry, name, input, context, options = {}) {
1286
- const failure = options.failure ?? toOperationFailure;
1287
- try {
1288
- const operation = registry.get(name);
1289
- if (!operation) throw Object.assign(internalErrorDiagnostics.INTERNAL_R0021({ message: `No operation is named ${JSON.stringify(name)}.` }), { status: 404 });
1290
- return await runParsedOperation(operation, await parseOperationInput(operation, input), context, options);
1291
- } catch (error) {
1292
- return {
1293
- ok: false,
1294
- ...failure(error)
1295
- };
1296
- }
1297
- }
1298
- /** Run input already validated by parseOperationInput, so approval and execution can share one normalization. */
1299
- async function runParsedOperation(operation, parsed, context, options = {}) {
1300
- const failure = options.failure ?? toOperationFailure;
1301
- try {
1302
- const section = operationSection(operation, parsed);
1303
- if (!operationAccessAllows(context.access, section)) throw Object.assign(internalErrorDiagnostics.INTERNAL_R0023({ message: `This access does not include the ${JSON.stringify(section)} section, which ${operation.name} needs.` }), { status: 403 });
1304
- if (!operationAccessAllows(context.access, section, operationCall(operation, parsed))) throw Object.assign(internalErrorDiagnostics.INTERNAL_R0023({ message: `This access to the ${JSON.stringify(section)} section is read-only, and ${operation.name} is a ${operation.kind} operation. Grant the section without ":read" to allow it.` }), { status: 403 });
1305
- return {
1306
- ok: true,
1307
- value: await operation.run(parsed, context)
1308
- };
1309
- } catch (error) {
1310
- return {
1311
- ok: false,
1312
- ...failure(error)
1313
- };
1314
- }
1315
- }
1316
- const operationCredentialHint = "Set VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET.";
1317
- /** Headers of an operation call. The credentials are the ones the Agent Invocations CLI reads. */
1318
- function operationHeaders(env) {
1319
- const headers = new Headers({
1320
- "accept": "application/json",
1321
- "content-type": "application/json",
1322
- [operationRpcHeader]: "1",
1323
- [operationSurfaceHeader]: "cli"
1324
- });
1325
- if (env.VITEHUB_CONSOLE_AUTHORIZATION) headers.set("authorization", env.VITEHUB_CONSOLE_AUTHORIZATION);
1326
- if (env.VITEHUB_CONSOLE_COOKIE) headers.set("cookie", env.VITEHUB_CONSOLE_COOKIE);
1327
- if (env.CF_ACCESS_CLIENT_ID) headers.set("cf-access-client-id", env.CF_ACCESS_CLIENT_ID);
1328
- if (env.CF_ACCESS_CLIENT_SECRET) headers.set("cf-access-client-secret", env.CF_ACCESS_CLIENT_SECRET);
1329
- return headers;
1330
- }
1331
- function unreachable(message, status = 503) {
1332
- const error = internalErrorDiagnostics.INTERNAL_R0024({ message });
1333
- return {
1334
- ok: false,
1335
- code: "INTERNAL_R0024",
1336
- fix: Reflect.get(error, "fix"),
1337
- message,
1338
- status
1339
- };
1340
- }
1341
- function hasCredentials(env) {
1342
- return Boolean(env.VITEHUB_CONSOLE_AUTHORIZATION || env.VITEHUB_CONSOLE_COOKIE || env.CF_ACCESS_CLIENT_ID || env.CF_ACCESS_CLIENT_SECRET);
1343
- }
1344
- /** Refuse a stale local discovery target before dispatching any operation. */
1345
- function assertOperationProject(request, root) {
1346
- const expected = request.headers.get(operationExpectedRootsHeader);
1347
- if (expected === null) return;
1348
- if (root && expected.split(",").includes(projectRootHash(root))) return;
1349
- throw Object.assign(internalErrorDiagnostics.INTERNAL_R0025({ message: "The server runs another project than the command expects." }), { status: 409 });
1350
- }
1351
- /** Call one operation over the RPC of a dev server or a deployed app. Never throws. */
1352
- async function callOperation(target, name, input) {
1353
- let origin = "the ViteHub app";
1354
- try {
1355
- const base = new URL(target.url);
1356
- if (!base.pathname.endsWith("/")) base.pathname = `${base.pathname}/`;
1357
- const url = new URL(operationRpcPath.slice(1), base);
1358
- origin = url.origin;
1359
- const env = target.roots?.length ? {} : target.env;
1360
- const headers = operationHeaders(env);
1361
- if (target.confirmed !== void 0) headers.set(operationConfirmationHeader, target.confirmed ? "confirmed" : "required");
1362
- if (target.roots?.length) headers.set(operationExpectedRootsHeader, target.roots.map(projectRootHash).join(","));
1363
- const response = await (target.fetch ?? fetch)(url.href, {
1364
- body: JSON.stringify({
1365
- operation: name,
1366
- input: input ?? {}
1367
- }),
1368
- headers,
1369
- method: "POST",
1370
- redirect: "manual",
1371
- signal: AbortSignal.timeout(target.timeout ?? 3e4)
1372
- });
1373
- const served = response.headers.get(operationRootHeader);
1374
- if (served && target.roots?.length && !target.roots.some((root) => projectRootHash(root) === served)) {
1375
- const message = `The server at ${url.origin} runs another project than ${target.roots[0]}.`;
1376
- const error = internalErrorDiagnostics.INTERNAL_R0025({ message });
1377
- return {
1378
- ok: false,
1379
- code: "INTERNAL_R0025",
1380
- fix: Reflect.get(error, "fix"),
1381
- message,
1382
- status: 409
1383
- };
1384
- }
1385
- const body = await response.text();
1386
- let json;
1387
- try {
1388
- json = body ? JSON.parse(body) : void 0;
1389
- } catch {
1390
- json = void 0;
1391
- }
1392
- if (isObject(json) && json.ok === true) return {
1393
- ok: true,
1394
- value: json.value
1395
- };
1396
- if (isObject(json) && String(json.code) === json.code && String(json.message) === json.message) {
1397
- const failure = {
1398
- ok: false,
1399
- code: json.code,
1400
- message: json.message,
1401
- status: Number.isInteger(json.status) ? Number(json.status) : response.status
1402
- };
1403
- if (text(json.fix)) failure.fix = text(json.fix);
1404
- if (text(json.docs)) failure.docs = text(json.docs);
1405
- if (isObject(json.details)) failure.details = json.details;
1406
- if ((failure.status === 401 || failure.status === 403) && !hasCredentials(env) && !failure.fix) failure.fix = target.roots?.length ? `Pass --url <origin> to send deployment credentials. ${operationCredentialHint}` : operationCredentialHint;
1407
- return failure;
1408
- }
1409
- if (response.status === 401 || response.status >= 300 && response.status < 400) return unreachable(`${url.origin} asked for authentication (HTTP ${response.status}).`, 401);
1410
- return unreachable(`${url.origin} did not answer as a ViteHub app (HTTP ${response.status}). Pass the origin of an app that runs ViteHub.`, response.status);
1411
- } catch (error) {
1412
- return unreachable(`The request to ${origin} failed: ${error instanceof Error ? error.message : String(error)}`);
1413
- }
1414
- }
1415
- /**
1416
- * Call one operation from a `vitehub` command: on `--url` when it is set, else on the dev server that the project
1417
- * started. Never throws. Without a dev server the result is an `INTERNAL_R0024` failure that says to start one.
1418
- */
1419
- async function callOperationFromCli(call, name, input) {
1420
- let roots;
1421
- try {
1422
- roots = [.../* @__PURE__ */ new Set([call.rootDir, resolveViteHubProjectRoot(call.rootDir)])];
1423
- } catch {
1424
- roots = [call.rootDir];
1425
- }
1426
- const url = call.url ?? findViteHubDevServerUrl(roots, call.env);
1427
- if (!url) return unreachable(`No dev server is running for ${call.rootDir}.`);
1428
- return await callOperation({
1429
- ...call.confirmed !== void 0 ? { confirmed: call.confirmed } : {},
1430
- env: call.env,
1431
- ...call.fetch ? { fetch: call.fetch } : {},
1432
- ...call.url ? {} : { roots },
1433
- ...call.timeout ? { timeout: call.timeout } : {},
1434
- url
1435
- }, name, input);
1436
- }
1437
- //#endregion
1438
- export { isPlainObject as S, shouldSkipViteProviderBuild as _, defineOperation as a, removeViteHubDevServerFile as b, operationRpcPath as c, runOperation as d, toOperationFailure as f, resolveViteHubProjectRoot as g, isServerEnvironment as h, createOperationRegistry as i, operationsOf as l, createNoExternalAddition as m, callOperationFromCli as n, operationRootHeader as o, internalErrorDiagnostics as p, collectOperationContributions as r, operationRpcHeader as s, assertOperationProject as t, projectRootHash as u, readViteHubDevServerFile as v, writeViteHubDevServerFile as x, readViteHubDevTargetOption as y };