@politty/valibot 0.0.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.
@@ -0,0 +1,477 @@
1
+ import { n as resolveFieldMeta, o as registerValidatorAdapter } from "./field-meta-DMy5BcRr.js";
2
+ import { safeParse } from "valibot";
3
+
4
+ //#region ../core/src/core/arg-registry.ts
5
+ /**
6
+ * Custom registry for politty argument metadata, keyed by schema identity.
7
+ * This avoids polluting Zod's GlobalMeta, and — unlike `z.registry()` — is
8
+ * validator-neutral: any schema object (zod, valibot, internal descriptors)
9
+ * can carry arg metadata without politty importing the schema library.
10
+ */
11
+ const argRegistry = /* @__PURE__ */ new WeakMap();
12
+ function arg(schema, meta) {
13
+ if (meta) argRegistry.set(schema, meta);
14
+ return schema;
15
+ }
16
+ /**
17
+ * Get metadata for a schema from the registry
18
+ *
19
+ * @param schema - The schema object used as the registry key
20
+ * @returns The metadata if registered, undefined otherwise
21
+ */
22
+ function getArgMeta$1(schema) {
23
+ return argRegistry.get(schema);
24
+ }
25
+
26
+ //#endregion
27
+ //#region src/adapter.ts
28
+ /**
29
+ * Valibot validator adapter: implements politty's neutral `ValidatorAdapter`
30
+ * contract against valibot v1's schema representation.
31
+ *
32
+ * Valibot schemas are plain objects (`kind` / `type` / `entries` / `pipe`
33
+ * properties are public API), so all introspection here is structural.
34
+ * Validation goes through `safeParse` so error output keeps valibot's
35
+ * issue detail (`type` / `expected` / `received`).
36
+ */
37
+ function asNode(schema) {
38
+ return schema;
39
+ }
40
+ /** Wrapper types that make a field accept a missing / undefined value. */
41
+ const OPTIONAL_WRAPPERS = /* @__PURE__ */ new Set([
42
+ "optional",
43
+ "exact_optional",
44
+ "nullish",
45
+ "undefinedable"
46
+ ]);
47
+ /** Wrapper types that carry a `wrapped` inner schema. */
48
+ const UNWRAPPABLE = /* @__PURE__ */ new Set([
49
+ "optional",
50
+ "exact_optional",
51
+ "nullish",
52
+ "undefinedable",
53
+ "nullable",
54
+ "non_optional",
55
+ "non_nullable",
56
+ "non_nullish"
57
+ ]);
58
+ /**
59
+ * Get the inner schema, unwrapping optional/nullable/etc. wrappers. Piped
60
+ * schemas need no explicit handling: `v.pipe` spreads its base schema, so
61
+ * the wrapper's own properties are already visible on the pipe result.
62
+ */
63
+ function unwrapSchema(schema) {
64
+ let current = schema;
65
+ while (current.type && UNWRAPPABLE.has(current.type) && current.wrapped) current = current.wrapped;
66
+ return current;
67
+ }
68
+ /**
69
+ * Detect the base type of a schema.
70
+ *
71
+ * Input-side detection (matching the zod adapter, which unwraps pipes to
72
+ * their input schema): the CLI parser cares about what the user types, not
73
+ * what a transform produces. The one refinement is `unknown`/`any` inputs —
74
+ * the idiomatic valibot coercion pattern is
75
+ * `v.pipe(v.unknown(), v.transform(Number), v.number())`, where the input
76
+ * schema says nothing; in that case the later pipe schemas are scanned so
77
+ * the field still presents as a number in help / prompts / completion.
78
+ */
79
+ function detectType(schema) {
80
+ const inner = unwrapSchema(schema);
81
+ const detected = bucketOf(inner.type);
82
+ if (detected !== "unknown") return detected;
83
+ if ((inner.type === "unknown" || inner.type === "any") && Array.isArray(inner.pipe)) for (const item of inner.pipe) {
84
+ if (item.kind === "schema") {
85
+ const bucket = bucketOf(item.type);
86
+ if (bucket !== "unknown") return bucket;
87
+ }
88
+ if (item.kind === "validation" && impliesNumber(item)) return "number";
89
+ }
90
+ return "unknown";
91
+ }
92
+ /** Validation actions whose input type is exclusively `number`. */
93
+ const NUMBER_ONLY_VALIDATIONS = /* @__PURE__ */ new Set([
94
+ "integer",
95
+ "safe_integer",
96
+ "finite"
97
+ ]);
98
+ /**
99
+ * Whether a validation action constrains its input to a number.
100
+ *
101
+ * `v.multipleOf` is overloaded for both `number` and `bigint` inputs under
102
+ * the same `multiple_of` action type, so it only implies a number field when
103
+ * its requirement is a number — `v.multipleOf(2n)` describes a bigint, which
104
+ * politty has no field type for and leaves as `unknown`.
105
+ */
106
+ function impliesNumber(action) {
107
+ if (!action.type) return false;
108
+ if (NUMBER_ONLY_VALIDATIONS.has(action.type)) return true;
109
+ return action.type === "multiple_of" && typeof action.requirement === "number";
110
+ }
111
+ function bucketOf(type) {
112
+ switch (type) {
113
+ case "string":
114
+ case "picklist":
115
+ case "enum": return "string";
116
+ case "number": return "number";
117
+ case "boolean": return "boolean";
118
+ case "array": return "array";
119
+ default: return "unknown";
120
+ }
121
+ }
122
+ /**
123
+ * Extract enum values from a schema if it's enum-like
124
+ * (picklist, enum, array of enums, or a union of string literals).
125
+ */
126
+ function extractEnumValues(schema) {
127
+ const inner = unwrapSchema(asNode(schema));
128
+ const allStrings = (values) => values.length > 0 && values.every((value) => typeof value === "string");
129
+ if (inner.type === "picklist" && Array.isArray(inner.options)) return allStrings(inner.options) ? inner.options : void 0;
130
+ if (inner.type === "enum") {
131
+ const values = Array.isArray(inner.options) ? inner.options : inner.enum && typeof inner.enum === "object" ? Object.values(inner.enum) : [];
132
+ return allStrings(values) ? values : void 0;
133
+ }
134
+ if (inner.type === "array" && inner.item) return extractEnumValues(inner.item);
135
+ if (inner.type === "union" && Array.isArray(inner.options)) {
136
+ const literalValues = [];
137
+ for (const option of inner.options) {
138
+ const node = asNode(option);
139
+ if (node.type === "literal" && typeof node.literal === "string") literalValues.push(node.literal);
140
+ }
141
+ if (literalValues.length === inner.options.length && literalValues.length > 0) return literalValues;
142
+ }
143
+ }
144
+ /**
145
+ * Check if a schema is required: no optional-ish wrapper anywhere in the
146
+ * wrapper chain. Mirrors the zod adapter's `isOptional()` semantics —
147
+ * `nullable` alone does NOT make a CLI arg optional (CLI values are present
148
+ * or absent, never null).
149
+ */
150
+ function isRequired(schema) {
151
+ let current = schema;
152
+ while (current.type && UNWRAPPABLE.has(current.type)) {
153
+ if (OPTIONAL_WRAPPERS.has(current.type)) return false;
154
+ if (!current.wrapped) break;
155
+ current = current.wrapped;
156
+ }
157
+ return true;
158
+ }
159
+ /**
160
+ * Extract the declared default value, walking the wrapper chain.
161
+ * Factory defaults (`v.optional(schema, () => value)`) are invoked, matching
162
+ * `v.getDefault` and the zod adapter's behavior for `.default(() => ...)`.
163
+ */
164
+ function extractDefaultValue(schema) {
165
+ let current = schema;
166
+ while (current?.type && UNWRAPPABLE.has(current.type)) {
167
+ if (current.default !== void 0) return typeof current.default === "function" ? current.default() : current.default;
168
+ current = current.wrapped;
169
+ }
170
+ }
171
+ /**
172
+ * Extract a description from `v.description(...)` metadata actions in the
173
+ * schema's pipe, recursing into wrappers. The last action wins, matching
174
+ * valibot's `v.getDescription` behavior for a single pipe.
175
+ *
176
+ * Hand-rolled rather than `v.getDescription` / `v.getDefault` because the
177
+ * official utilities do not look through wrapper schemas — e.g.
178
+ * `v.getDescription(v.optional(v.pipe(v.string(), v.description("x"))))`
179
+ * returns `undefined` — while zod-adapter parity requires descriptions and
180
+ * defaults declared on the wrapped inner schema to be found.
181
+ */
182
+ function extractDescription(schema) {
183
+ if (Array.isArray(schema.pipe)) {
184
+ let description;
185
+ for (const item of schema.pipe) if (item.kind === "metadata" && item.type === "description") {
186
+ if (typeof item.description === "string") description = item.description;
187
+ }
188
+ if (description !== void 0) return description;
189
+ }
190
+ if (schema.type && UNWRAPPABLE.has(schema.type) && schema.wrapped) return extractDescription(schema.wrapped);
191
+ }
192
+ /**
193
+ * Extract `v.metadata({...})` action content from the schema's pipe,
194
+ * recursing into wrappers. Later actions win key-by-key.
195
+ */
196
+ function extractMetadataAction(schema) {
197
+ let merged;
198
+ if (schema.type && UNWRAPPABLE.has(schema.type) && schema.wrapped) merged = extractMetadataAction(schema.wrapped);
199
+ if (Array.isArray(schema.pipe)) {
200
+ for (const item of schema.pipe) if (item.kind === "metadata" && item.type === "metadata" && item.metadata) merged = {
201
+ ...merged,
202
+ ...item.metadata
203
+ };
204
+ }
205
+ return merged;
206
+ }
207
+ /**
208
+ * Find arg() registry metadata for a schema. `v.pipe(...)` spreads its base
209
+ * schema into a NEW object, so metadata registered before composing —
210
+ * `v.pipe(arg(v.string(), {...}), v.transform(...))` — is keyed by the
211
+ * original base object, which survives only as an item of the `pipe` array.
212
+ * Walk pipe items and wrapper chains so composition never drops metadata.
213
+ */
214
+ function lookupRegistryMeta(node, seen) {
215
+ if (seen.has(node)) return void 0;
216
+ seen.add(node);
217
+ const direct = getArgMeta$1(node);
218
+ if (direct) return direct;
219
+ if (Array.isArray(node.pipe)) {
220
+ for (const item of node.pipe) if (item && item.kind === "schema") {
221
+ const hit = lookupRegistryMeta(item, seen);
222
+ if (hit) return hit;
223
+ }
224
+ }
225
+ if (node.wrapped) return lookupRegistryMeta(node.wrapped, seen);
226
+ }
227
+ /**
228
+ * Get ArgMeta for a field schema.
229
+ * Priority: politty's arg() registry > `v.metadata({...})` pipe actions.
230
+ */
231
+ function getArgMeta(schema) {
232
+ const fromRegistry = lookupRegistryMeta(schema, /* @__PURE__ */ new Set());
233
+ if (fromRegistry) return fromRegistry;
234
+ const fromMetadataAction = extractMetadataAction(schema);
235
+ if (fromMetadataAction) return fromMetadataAction;
236
+ }
237
+ /**
238
+ * Resolve field metadata from a valibot field schema. The valibot-specific
239
+ * introspection happens here; the shared alias/negation policy lives in
240
+ * `resolveFieldMeta` (adapter/field-meta.ts).
241
+ */
242
+ function resolveValibotFieldMeta(name, schema) {
243
+ const node = asNode(schema);
244
+ return resolveFieldMeta(name, {
245
+ argMeta: getArgMeta(node),
246
+ description: extractDescription(node),
247
+ required: isRequired(node),
248
+ defaultValue: extractDefaultValue(node),
249
+ type: detectType(node),
250
+ enumValues: extractEnumValues(node),
251
+ schema
252
+ });
253
+ }
254
+ /**
255
+ * Detect unknown keys handling mode from a valibot object schema.
256
+ *
257
+ * - `v.object()`: strips unknown keys (politty warns) → "strip"
258
+ * - `v.strictObject()`: rejects unknown keys → "strict"
259
+ * - `v.looseObject()` / `v.objectWithRest()`: keeps unknown keys → "passthrough"
260
+ */
261
+ function getUnknownKeysMode(schema) {
262
+ switch (unwrapSchema(asNode(schema)).type) {
263
+ case "strict_object": return "strict";
264
+ case "loose_object":
265
+ case "object_with_rest": return "passthrough";
266
+ default: return "strip";
267
+ }
268
+ }
269
+ /**
270
+ * Extract fields from an object-like schema's entries
271
+ */
272
+ function extractFromObject(schema) {
273
+ const entries = schema.entries ?? {};
274
+ return Object.entries(entries).map(([name, fieldSchema]) => resolveValibotFieldMeta(name, fieldSchema));
275
+ }
276
+ /**
277
+ * Get the discriminator value of one variant option for `v.variant(key, ...)`.
278
+ * Supports `v.literal()` and single-value `v.picklist()` / `v.enum()`.
279
+ */
280
+ function getDiscriminatorValue(option, key) {
281
+ const discriminatorSchema = option.entries?.[key];
282
+ if (!discriminatorSchema) return "";
283
+ const inner = unwrapSchema(discriminatorSchema);
284
+ if (inner.type === "literal" && inner.literal !== void 0) return String(inner.literal);
285
+ const enumValues = extractEnumValues(inner);
286
+ if (enumValues && enumValues.length === 1) return enumValues[0];
287
+ return "";
288
+ }
289
+ /**
290
+ * Extract fields from `v.variant(key, [...])` (valibot's discriminated union)
291
+ */
292
+ function extractFromVariant(schema) {
293
+ const discriminator = schema.key ?? "";
294
+ const options = schema.options ?? [];
295
+ const allFieldsMap = /* @__PURE__ */ new Map();
296
+ const variants = [];
297
+ for (const option of options) {
298
+ const optionNode = asNode(option);
299
+ const variantFields = [];
300
+ for (const [name, fieldSchema] of Object.entries(optionNode.entries ?? {})) {
301
+ const fieldMeta = resolveValibotFieldMeta(name, fieldSchema);
302
+ variantFields.push(fieldMeta);
303
+ if (!allFieldsMap.has(name)) allFieldsMap.set(name, fieldMeta);
304
+ }
305
+ const variantDescription = extractDescription(optionNode);
306
+ variants.push({
307
+ discriminatorValue: getDiscriminatorValue(optionNode, discriminator),
308
+ fields: variantFields,
309
+ ...variantDescription ? { description: variantDescription } : {}
310
+ });
311
+ }
312
+ const description = extractDescription(schema);
313
+ return {
314
+ fields: Array.from(allFieldsMap.values()),
315
+ schema,
316
+ schemaType: "discriminatedUnion",
317
+ unknownKeysMode: getUnknownKeysMode(schema),
318
+ discriminator,
319
+ variants,
320
+ ...description ? { description } : {}
321
+ };
322
+ }
323
+ /**
324
+ * Extract fields from a union schema
325
+ */
326
+ function extractFromUnion(schema) {
327
+ const options = schema.options ?? [];
328
+ const allFieldsMap = /* @__PURE__ */ new Map();
329
+ const unionOptions = [];
330
+ for (const option of options) {
331
+ const extracted = extractValibotFields(option);
332
+ unionOptions.push(extracted);
333
+ for (const field of extracted.fields) if (!allFieldsMap.has(field.name)) allFieldsMap.set(field.name, field);
334
+ }
335
+ const description = extractDescription(schema);
336
+ return {
337
+ fields: Array.from(allFieldsMap.values()),
338
+ schema,
339
+ schemaType: "union",
340
+ unknownKeysMode: getUnknownKeysMode(schema),
341
+ unionOptions,
342
+ ...description ? { description } : {}
343
+ };
344
+ }
345
+ /**
346
+ * Extract fields from `v.intersect([...])`
347
+ */
348
+ function extractFromIntersect(schema) {
349
+ const allFieldsMap = /* @__PURE__ */ new Map();
350
+ for (const option of schema.options ?? []) {
351
+ const extracted = extractValibotFields(option);
352
+ for (const field of extracted.fields) if (!allFieldsMap.has(field.name)) allFieldsMap.set(field.name, field);
353
+ }
354
+ const description = extractDescription(schema);
355
+ return {
356
+ fields: Array.from(allFieldsMap.values()),
357
+ schema,
358
+ schemaType: "intersection",
359
+ unknownKeysMode: getUnknownKeysMode(schema),
360
+ ...description ? { description } : {}
361
+ };
362
+ }
363
+ /**
364
+ * Cache for extractValibotFields results to avoid redundant schema extraction
365
+ */
366
+ const extractFieldsCache = /* @__PURE__ */ new WeakMap();
367
+ /**
368
+ * Extract all fields from a valibot args schema
369
+ * (object, strictObject, looseObject, variant, union, intersect)
370
+ */
371
+ function extractValibotFields(schema) {
372
+ const cached = extractFieldsCache.get(schema);
373
+ if (cached) return cached;
374
+ const node = unwrapSchema(asNode(schema));
375
+ let result;
376
+ switch (node.type) {
377
+ case "object":
378
+ case "strict_object":
379
+ case "loose_object":
380
+ case "object_with_rest": {
381
+ const description = extractDescription(asNode(schema));
382
+ result = {
383
+ fields: extractFromObject(node),
384
+ schema,
385
+ schemaType: "object",
386
+ unknownKeysMode: getUnknownKeysMode(node),
387
+ ...description ? { description } : {}
388
+ };
389
+ break;
390
+ }
391
+ case "variant":
392
+ result = {
393
+ ...extractFromVariant(node),
394
+ schema
395
+ };
396
+ break;
397
+ case "union":
398
+ result = {
399
+ ...extractFromUnion(node),
400
+ schema
401
+ };
402
+ break;
403
+ case "intersect":
404
+ result = {
405
+ ...extractFromIntersect(node),
406
+ schema
407
+ };
408
+ break;
409
+ default: {
410
+ const description = extractDescription(asNode(schema));
411
+ result = {
412
+ fields: [],
413
+ schema,
414
+ schemaType: "object",
415
+ unknownKeysMode: getUnknownKeysMode(node),
416
+ ...description ? { description } : {}
417
+ };
418
+ break;
419
+ }
420
+ }
421
+ extractFieldsCache.set(schema, result);
422
+ return result;
423
+ }
424
+ /**
425
+ * Convert valibot issues to ValidationError array
426
+ */
427
+ function formatValibotIssues(issues) {
428
+ return issues.map((raw) => {
429
+ const issue = raw;
430
+ return {
431
+ path: issue.path?.map((item) => String(item.key)) ?? [],
432
+ message: issue.message,
433
+ code: issue.type,
434
+ received: issue.input,
435
+ expected: issue.expected ?? void 0
436
+ };
437
+ });
438
+ }
439
+ /**
440
+ * Validate raw arguments against a valibot schema
441
+ */
442
+ function validateValibotArgs(rawArgs, schema) {
443
+ const result = safeParse(schema, rawArgs);
444
+ if (result.success) return {
445
+ success: true,
446
+ data: result.output
447
+ };
448
+ return {
449
+ success: false,
450
+ errors: formatValibotIssues(result.issues)
451
+ };
452
+ }
453
+ /**
454
+ * The valibot validator adapter.
455
+ */
456
+ const valibotAdapter = {
457
+ vendor: "valibot",
458
+ extractFields: extractValibotFields,
459
+ resolveFieldMeta: resolveValibotFieldMeta,
460
+ getUnknownKeysMode,
461
+ validate: validateValibotArgs
462
+ };
463
+
464
+ //#endregion
465
+ //#region src/register.ts
466
+ /**
467
+ * Import-time side effect: register the valibot adapter with `@politty/core`.
468
+ *
469
+ * Every entry module of this package imports this file first (except
470
+ * `compile-cache`, which never touches schemas), so any code path a user
471
+ * can reach has the adapter installed before core touches a schema.
472
+ * Registration is idempotent.
473
+ */
474
+ registerValidatorAdapter(valibotAdapter);
475
+
476
+ //#endregion
477
+ export { arg as t };