schema-truth 0.8.1 → 0.8.2

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.
@@ -1,5 +1,5 @@
1
1
  import { $ as DEFINITION_REF_PREFIXES, At as UNSAFE_GENERATED_MARKER, B as isSchemaObject, D as isComposite, E as isArktypeDefinition, H as isStringWireLocation, I as isQuoted, M as isNullable, N as isObjectPrototypeProperty, O as isDeepLocalPointer, R as isRootRef, S as hasFixedLength, St as QUOTE_OR_BACKSLASH_PATTERN, V as isShapelessMember, X as DEFAULT_ROOT_NAME, at as INTEGER_TEXT_PATTERN, c as normalizeTypes, j as isNullTypeMember, l as resolveOpenAPIRef, o as issueMessageExpression, pt as NUMBER_RANGES, s as makeSafeKey, x as hasFixedItemCount, y as hasCombinator } from "./utils-Bky98UmP.js";
2
- import { A as wireNullText, B as emitOptionsOf, C as isPrimitiveUnion, D as stringboolTruthyPattern, E as stringboolPattern, G as schemaNamer, H as planDocument, M as formatPattern, N as regexSource, O as unionPrimitiveTypes, Q as findCodeExtensionKeysInSchema, S as isNullTextRead, T as ownProperties, V as missingDefinitionComment, W as rootNameOf, X as arktypePreprocess, Y as itemsSchemaOf, Z as arktypeWrap, at as regexLiteral, b as integerWirePattern, c as withPolymorphicBases, d as propertyEmitOptions, et as constraintMessage, f as withoutParameterSerialization, g as hoistNestedRefs, h as valueListLiteral, j as wireNumericKind, k as wireArrayOnce, l as hasParameterSerialization, m as notPredicate, nt as foldAllOfMembers, p as isBigintFormat, rt as isKeywordOnlyMember, tt as constraintPredicate, u as parameterReaders, w as numberWirePattern, x as isNullMatchedFirst, y as impliedWireType } from "./helper-CbeedY35.js";
2
+ import { $ as callbackReturn, A as wireNullText, B as emitOptionsOf, C as isPrimitiveUnion, D as stringboolTruthyPattern, E as stringboolPattern, G as schemaNamer, H as planDocument, K as discriminatedMembers, M as formatPattern, N as regexSource, O as unionPrimitiveTypes, Q as arktypeWrap, S as isNullTextRead, T as ownProperties, V as missingDefinitionComment, W as rootNameOf, X as itemsSchemaOf, Z as arktypePreprocess, at as foldAllOfMembers, b as integerWirePattern, c as withPolymorphicBases, ct as regexLiteral, d as propertyEmitOptions, et as callbackType, f as withoutParameterSerialization, g as hoistNestedRefs, h as valueListLiteral, i as isEvaluatedKeyExpression, it as constraintPredicate, j as wireNumericKind, k as wireArrayOnce, l as hasParameterSerialization, m as notPredicate, ot as isKeywordOnlyMember, p as isBigintFormat, r as evaluatedProperties, rt as constraintMessage, tt as findCodeExtensionKeysInSchema, u as parameterReaders, w as numberWirePattern, x as isNullMatchedFirst, y as impliedWireType, z as definitionsOf } from "./helper-S7SSsYwh.js";
3
3
  //#region src/generator/arktype/number.ts
4
4
  /** The comparators of a numeric node: `>= 1`, `< 5`, `% 2`. */
5
5
  function numericConstraints(schema) {
@@ -236,12 +236,13 @@ function _enum(schema) {
236
236
  }
237
237
  //#endregion
238
238
  //#region src/generator/arktype/object.ts
239
- function composeNarrows(base, narrows) {
240
- return narrows.length === 0 ? base : narrows.reduce((acc, n) => `${acc}.narrow(${n})`, base);
241
- }
242
- /** Wrap a raw arktype expression with `type(...)` if it's a bare quoted string. */
243
- function ensureRuntime(s) {
244
- return isQuoted(s) ? `type(${s})` : s;
239
+ /**
240
+ * An object definition with its narrows. Inside a scope they stay in definition syntax
241
+ * (`[def, ":", fn]`), which the scope resolves; outside, they chain on `type(def)`.
242
+ */
243
+ function composeNarrows(definition, narrows, scopeMode) {
244
+ if (scopeMode) return narrows.reduce((acc, n) => `[${acc},":",${n}]`, definition);
245
+ return narrows.reduce((acc, n) => `${acc}.narrow(${n})`, `type(${definition})`);
245
246
  }
246
247
  /**
247
248
  * Compose a `.narrow(...)` argument with an optional error message.
@@ -249,7 +250,7 @@ function ensureRuntime(s) {
249
250
  * - Without message: `(data) => predicate`
250
251
  */
251
252
  function narrowPredicate(predicate, message) {
252
- return message ? `(data, ctx) => ${predicate} || ctx.mustBe(${JSON.stringify(message)})` : `(data) => ${predicate}`;
253
+ return message ? callbackReturn("(data, ctx)", `${predicate} || ctx.mustBe(${JSON.stringify(message)})`) : callbackReturn("(data)", predicate);
253
254
  }
254
255
  /**
255
256
  * Generate an Arktype object schema for a JSON Schema object node.
@@ -277,28 +278,34 @@ function object(schema, rootName, isArktype, options) {
277
278
  return "";
278
279
  };
279
280
  const patternPropertiesNarrows = () => schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, propSchema]) => {
280
- const s = ensureRuntime(arktype(propSchema, rootName, isArktype, options));
281
+ const s = callbackType(arktype(propSchema, rootName, isArktype, options), isArktype);
281
282
  return narrowPredicate(`Object.entries(data).every(([key, value]) => !new RegExp(${JSON.stringify(pattern)}).test(key) || ${s}.allows(value))`, patternPropsMessage);
282
283
  }) : [];
283
- if (typeof schema.additionalProperties === "object") {
284
+ if (typeof schema.additionalProperties === "object" && schema.properties === void 0 && schema.patternProperties === void 0) {
284
285
  const innerLiteral = `{"[string]":${arktype(schema.additionalProperties, rootName, isArktype, options)}}`;
285
- const narrows = [propertyNamesNarrow(), ...patternPropertiesNarrows()].filter((a) => a !== "");
286
- if (narrows.length > 0) return composeNarrows(`type(${innerLiteral})`, narrows);
286
+ const narrows = [propertyNamesNarrow()].filter((a) => a !== "");
287
+ if (narrows.length > 0) return composeNarrows(innerLiteral, narrows, isArktype);
287
288
  return isArktype ? innerLiteral : `type(${innerLiteral})`;
288
289
  }
290
+ const properties = schema.properties ?? {};
291
+ const undeclaredRequired = (schema.required ?? []).filter((key) => !Object.hasOwn(properties, key));
289
292
  if (!schema.properties) {
290
293
  if (schema.additionalProperties === true) return "\"unknown\"";
291
- return isArktype ? "{}" : "type({})";
294
+ if (!(undeclaredRequired.length > 0 || schema.patternProperties !== void 0 || schema.additionalProperties === false || schema.unevaluatedProperties !== void 0)) return isArktype ? "{}" : "type({})";
292
295
  }
293
- const additionalMode = schema.additionalProperties === true ? "delete" : schema.additionalProperties === false ? "reject" : void 0;
296
+ const isEvaluated = isEvaluatedKeyExpression({
297
+ names: Object.keys(properties),
298
+ patterns: Object.keys(schema.patternProperties ?? {})
299
+ }, "key");
300
+ const additionalMode = schema.additionalProperties === true ? "delete" : schema.additionalProperties === false && schema.patternProperties === void 0 ? "reject" : void 0;
294
301
  const required = new Set(schema.required);
295
- const props = Object.entries(schema.properties).map(([key, propSchema]) => {
302
+ const props = [...Object.entries(properties).map(([key, propSchema]) => {
296
303
  const parsed = arktype(propSchema, rootName, isArktype, propertyEmitOptions(key, propSchema, options) ?? options);
297
304
  if (!parsed) return null;
298
305
  const isRequired = required.has(key);
299
306
  const baseSafeKey = makeSafeKey(key);
300
307
  return `${isRequired ? baseSafeKey : baseSafeKey.startsWith("\"") ? JSON.stringify(`${key}?`) : `"${key}?"`}:${parsed}`;
301
- }).filter((p) => p !== null);
308
+ }).filter((p) => p !== null), ...undeclaredRequired.map((key) => `${makeSafeKey(key)}:"unknown"`)];
302
309
  const additionalProp = additionalMode ? `"+":"${additionalMode}"` : void 0;
303
310
  const innerLiteral = `{${[...props, additionalProp].filter((p) => p !== void 0).join(",")}}`;
304
311
  const minPropertiesNarrow = typeof schema.minProperties === "number" ? narrowPredicate(`Object.keys(data).length >= ${schema.minProperties}`, minimumMessage) : "";
@@ -307,22 +314,25 @@ function object(schema, rootName, isArktype, options) {
307
314
  return narrowPredicate(`!('${key}' in data) || (${deps.map((d) => `'${d}' in data`).join(" && ")})`, depReqMessage);
308
315
  }) : [];
309
316
  const dependentSchemasNarrows = schema.dependentSchemas ? Object.entries(schema.dependentSchemas).map(([key, subSchema]) => {
310
- return narrowPredicate(`!('${key}' in data) || ${ensureRuntime(arktype(subSchema, rootName, isArktype, options))}.allows(data)`, depSchMessage);
317
+ return narrowPredicate(`!('${key}' in data) || ${callbackType(arktype(subSchema, rootName, isArktype, options), isArktype)}.allows(data)`, depSchMessage);
311
318
  }) : [];
312
- const additionalPropertiesNarrow = schema.additionalProperties === false && addlPropsMessage ? narrowPredicate(`Object.keys(data).every((key) => ${JSON.stringify(Object.keys(schema.properties))}.includes(key))`, addlPropsMessage) : "";
319
+ const additionalPropertiesNarrow = schema.additionalProperties === false && (addlPropsMessage !== void 0 || schema.patternProperties !== void 0) ? narrowPredicate(`Object.keys(data).every((key) => ${isEvaluated})`, addlPropsMessage) : "";
313
320
  const unevaluatedPropertiesNarrow = (() => {
314
- const u = schema.unevaluatedProperties;
321
+ const u = typeof schema.additionalProperties === "object" ? schema.additionalProperties : schema.unevaluatedProperties;
315
322
  if (u === void 0 || u === true) return "";
316
- const declaredKeys = JSON.stringify(Object.keys(schema.properties ?? {}));
317
- if (u === false) return narrowPredicate(`Object.keys(data).every((key) => ${declaredKeys}.includes(key))`, unevalPropsRawMessage);
318
- if (typeof u === "object") return narrowPredicate(`Object.entries(data).filter(([key]) => !${declaredKeys}.includes(key)).every(([, value]) => ${ensureRuntime(arktype(u, rootName, isArktype, options))}.allows(value))`, unevalPropsRawMessage);
323
+ const message = typeof schema.additionalProperties === "object" ? addlPropsMessage : unevalPropsRawMessage;
324
+ if (u === false) return narrowPredicate(`Object.keys(data).every((key) => ${isEvaluated})`, message);
325
+ if (typeof u === "object") {
326
+ const s = callbackType(arktype(u, rootName, isArktype, options), isArktype);
327
+ return narrowPredicate(`Object.entries(data).every(([key, value]) => ${isEvaluated} || ${s}.allows(value))`, message);
328
+ }
319
329
  return "";
320
330
  })();
321
331
  const ifThenElseNarrows = (() => {
322
332
  if (!schema.if) return [];
323
- const ifS = ensureRuntime(arktype(schema.if, rootName, isArktype, options));
324
- const thenS = schema.then ? ensureRuntime(arktype(schema.then, rootName, isArktype, options)) : void 0;
325
- const elseS = schema.else ? ensureRuntime(arktype(schema.else, rootName, isArktype, options)) : void 0;
333
+ const ifS = callbackType(arktype(schema.if, rootName, isArktype, options), isArktype);
334
+ const thenS = schema.then ? callbackType(arktype(schema.then, rootName, isArktype, options), isArktype) : void 0;
335
+ const elseS = schema.else ? callbackType(arktype(schema.else, rootName, isArktype, options), isArktype) : void 0;
326
336
  if (!thenS && !elseS) return [];
327
337
  const ifMessage = schema["x-if-message"];
328
338
  const thenMessage = schema["x-then-message"] ?? ifMessage;
@@ -343,13 +353,14 @@ function object(schema, rootName, isArktype, options) {
343
353
  unevaluatedPropertiesNarrow,
344
354
  ...ifThenElseNarrows
345
355
  ].filter((a) => a !== "");
346
- const baseExpr = narrows.length > 0 ? composeNarrows(`type(${innerLiteral})`, narrows) : isArktype ? innerLiteral : `type(${innerLiteral})`;
356
+ const baseExpr = narrows.length > 0 ? composeNarrows(innerLiteral, narrows, isArktype) : isArktype ? innerLiteral : `type(${innerLiteral})`;
347
357
  const propsMessage = schema["x-properties-message"];
348
358
  const described = (() => {
349
359
  if (typeof propsMessage !== "string") return baseExpr;
350
- return `${baseExpr.startsWith("{") ? `type(${baseExpr})` : baseExpr}.describe(${JSON.stringify(propsMessage)})`;
360
+ if (isArktype && isArktypeDefinition(baseExpr)) return `[${baseExpr},"@",${JSON.stringify(propsMessage)}]`;
361
+ return `${isArktypeDefinition(baseExpr) ? `type(${baseExpr})` : baseExpr}.describe(${JSON.stringify(propsMessage)})`;
351
362
  })();
352
- const hasInheritedName = Object.keys(schema.properties).some(isObjectPrototypeProperty);
363
+ const hasInheritedName = Object.keys(properties).some(isObjectPrototypeProperty);
353
364
  return isStringWireLocation(options?.paramIn) && hasInheritedName ? `${arktypePreprocess([ownProperties("data")], described, "object")}.pipe((data) => ({ ...data }))` : described;
354
365
  }
355
366
  //#endregion
@@ -517,6 +528,28 @@ function formatConst(value, isBigint) {
517
528
  function isNumericMember(schema) {
518
529
  return (schema.type === "number" || schema.type === "integer") && schema.$ref === void 0 && !hasCombinator(schema) && schema.enum === void 0 && schema.const === void 0 && !isInt64(schema) && schema.format !== "bigint";
519
530
  }
531
+ /** An ArkType regex index-signature key for `source`, its slashes escaped. */
532
+ function indexKey(source) {
533
+ return JSON.stringify(`[/${source.replaceAll("/", "\\/")}/]`);
534
+ }
535
+ /**
536
+ * The members an `allOf` gains from `patternProperties` and `unevaluatedProperties` beside
537
+ * it: a regex index signature per pattern, holding the keys it matches to its schema, and
538
+ * one matching every key no member evaluates (no listed name, no pattern matching anywhere
539
+ * in it), holding it to `unevaluatedProperties`. An index signature can name a scope alias,
540
+ * which a `.narrow()` callback cannot.
541
+ */
542
+ function objectKeysMembers(schema, rootName, isArktype, options) {
543
+ const patternMembers = Object.entries(schema.patternProperties ?? {}).map(([pattern, propSchema]) => `{${indexKey(pattern)}:${arktype(propSchema, rootName, isArktype, options)}}`);
544
+ const unevaluated = schema.unevaluatedProperties;
545
+ if (unevaluated !== false && (typeof unevaluated !== "object" || unevaluated === null)) return patternMembers;
546
+ const evaluated = evaluatedProperties(schema, options?.definitions);
547
+ if (evaluated === void 0) return patternMembers;
548
+ const value = unevaluated === false ? "\"never\"" : arktype(unevaluated, rootName, isArktype, options);
549
+ const names = evaluated.names.map((name) => name.replaceAll(/[\\^$.*+?()[\]{}|]/gu, "\\$&"));
550
+ const exclusions = [...names.length === 0 ? [] : [`(?!(?:${names.join("|")})$)`], ...evaluated.patterns.map((pattern) => `(?![\\s\\S]*?(?:${pattern}))`)];
551
+ return [...patternMembers, `{${indexKey(`^${exclusions.join("")}`)}:${value}}`];
552
+ }
520
553
  /**
521
554
  * Generate ArkType schema code from JSON Schema.
522
555
  *
@@ -587,7 +620,14 @@ function node(schema, rootName, isArktype, options) {
587
620
  }, rootName, isArktype, options);
588
621
  if (schema.oneOf) {
589
622
  if (schema.oneOf.length === 0) return arktypeWrap$1("\"unknown\"", schema);
590
- return arktypeWrap$1(unionOf(schema.oneOf.map((s) => arktype(s, rootName, isArktype, options)), schema["x-oneOf-message"]), schema);
623
+ const discriminated = discriminatedMembers(schema, schema.oneOf);
624
+ return arktypeWrap$1(unionOf(schema.oneOf.map((s, i) => {
625
+ const member = arktype(s, rootName, isArktype, options);
626
+ const values = discriminated?.members[i]?.values;
627
+ if (discriminated === void 0 || values === void 0) return member;
628
+ const literal = values.map((value) => `'${value.replaceAll(/['\\]/gu, "\\$&")}'`).join(" | ");
629
+ return intersectionStr([member, `{${JSON.stringify(discriminated.propertyName)}:${JSON.stringify(literal)}}`], isArktype);
630
+ }), schema["x-oneOf-message"]), schema);
591
631
  }
592
632
  if (schema.anyOf) {
593
633
  if (schema.anyOf.length === 0) return arktypeWrap$1("\"unknown\"", schema);
@@ -614,7 +654,8 @@ function node(schema, rootName, isArktype, options) {
614
654
  ...schema,
615
655
  nullable
616
656
  });
617
- return arktypeWrap$1(schemas.length === 1 ? schemas[0] : intersectionStr(schemas, isArktype), {
657
+ const intersected = [...schemas, ...objectKeysMembers(schema, rootName, isArktype, options)];
658
+ return arktypeWrap$1(intersected.length === 1 ? intersected[0] : intersectionStr(intersected, isArktype), {
618
659
  ...schema,
619
660
  nullable
620
661
  });
@@ -729,13 +770,13 @@ function node(schema, rootName, isArktype, options) {
729
770
  const uniqueExpr = schema.uniqueItems === true ? narrowWith(lengthExpr, `(data: unknown[], ctx) => new Set(data).size === data.length${uniqueItemsMessage ? ` || ctx.mustBe(${JSON.stringify(uniqueItemsMessage)})` : ""}`) : lengthExpr;
730
771
  return arktypeWrap$1(wireArray(describeWithMessage((() => {
731
772
  if (!schema.contains) return [];
732
- const containsRt = asRuntime(arktype(schema.contains, rootName, isArktype, options));
773
+ const containsRt = callbackType(arktype(schema.contains, rootName, isArktype, options), isArktype);
733
774
  const minC = schema.minContains;
734
775
  const maxC = schema.maxContains;
735
- if (minC === void 0 && maxC === void 0) return [`.narrow((data: unknown[], ctx) => data.some((item) => ${containsRt}.allows(item)) || ctx.mustBe(${JSON.stringify(containsMessage ?? "must contain at least one matching item")}))`];
776
+ if (minC === void 0 && maxC === void 0) return [callbackReturn("(data: unknown[], ctx)", `data.some((item) => ${containsRt}.allows(item)) || ctx.mustBe(${JSON.stringify(containsMessage ?? "must contain at least one matching item")})`)];
736
777
  const effectiveMin = minC ?? 1;
737
- return [effectiveMin > 0 ? `.narrow((data: unknown[], ctx) => data.filter((item) => ${containsRt}.allows(item)).length >= ${effectiveMin} || ctx.mustBe(${JSON.stringify(minContainsMessage ?? `must contain at least ${effectiveMin} matching items`)}))` : void 0, maxC !== void 0 ? `.narrow((data: unknown[], ctx) => data.filter((item) => ${containsRt}.allows(item)).length <= ${maxC} || ctx.mustBe(${JSON.stringify(maxContainsMessage ?? `must contain at most ${maxC} matching items`)}))` : void 0].filter((v) => v !== void 0);
738
- })().reduce((acc, narrow) => `${asRuntime(acc)}${narrow}`, uniqueExpr), schema["x-items-message"])), schema);
778
+ return [effectiveMin > 0 ? callbackReturn("(data: unknown[], ctx)", `data.filter((item) => ${containsRt}.allows(item)).length >= ${effectiveMin} || ctx.mustBe(${JSON.stringify(minContainsMessage ?? `must contain at least ${effectiveMin} matching items`)})`) : void 0, maxC !== void 0 ? callbackReturn("(data: unknown[], ctx)", `data.filter((item) => ${containsRt}.allows(item)).length <= ${maxC} || ctx.mustBe(${JSON.stringify(maxContainsMessage ?? `must contain at most ${maxC} matching items`)})`) : void 0].filter((v) => v !== void 0);
779
+ })().reduce((acc, narrow) => isArktype && isArktypeDefinition(acc) ? `[${acc},":",${narrow}]` : `${asRuntime(acc)}.narrow(${narrow})`, uniqueExpr), schema["x-items-message"])), schema);
739
780
  }
740
781
  if (types.includes("object")) return readonly(arktypeWrap$1(object(schema, rootName, isArktype, options), schema));
741
782
  if (types.includes("date")) {
@@ -756,10 +797,15 @@ function node(schema, rootName, isArktype, options) {
756
797
  function schemaToArktype(input, options) {
757
798
  const schema = withPolymorphicBases(hoistNestedRefs(input));
758
799
  const exportType = options?.exportType ?? true;
759
- const emitOptions = emitOptionsOf(options);
760
- const prefix = emitOptions.unsafeCodeExtensions === true && findCodeExtensionKeysInSchema(schema).length > 0 ? [UNSAFE_GENERATED_MARKER] : [];
761
- const toName = schemaNamer(emitOptions.openapi);
800
+ const baseOptions = emitOptionsOf(options);
801
+ const prefix = baseOptions.unsafeCodeExtensions === true && findCodeExtensionKeysInSchema(schema).length > 0 ? [UNSAFE_GENERATED_MARKER] : [];
802
+ const toName = schemaNamer(baseOptions.openapi);
762
803
  const plan = planDocument(schema, rootNameOf(schema, toName));
804
+ const definitions = definitionsOf(baseOptions, plan.definitions);
805
+ const emitOptions = definitions === void 0 ? baseOptions : {
806
+ ...baseOptions,
807
+ definitions
808
+ };
763
809
  const { rootName } = plan;
764
810
  if (plan.hasDefinitions) {
765
811
  const defEntries = plan.orderedNames.map((name) => {
@@ -768,8 +814,9 @@ function schemaToArktype(input, options) {
768
814
  const pc = toName(name);
769
815
  return `${pc}:${arktype(def, pc, true, emitOptions)}`;
770
816
  });
771
- const scopeBody = `const types = scope({${(plan.rootDefinition === void 0 ? [...defEntries, `${rootName}:${arktype(schema, rootName, true, emitOptions)}`] : defEntries).join(",")}}).export()`;
772
- const usesType = /\btype[(.]/u.test(scopeBody);
817
+ const entries = (plan.rootDefinition === void 0 ? [...defEntries, `${rootName}:${arktype(schema, rootName, true, emitOptions)}`] : defEntries).join(",");
818
+ const scopeBody = entries.includes("$.type(") ? `const $ = scope({${entries}})\n\nconst types = $.export()` : `const types = scope({${entries}}).export()`;
819
+ const usesType = /(?<![\w$.])type[(.]/u.test(scopeBody);
773
820
  return [
774
821
  ...prefix,
775
822
  `import { scope${usesType ? ", type" : ""} } from "arktype"`,
package/dist/arktype.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { r as JSONSchema } from "./index-G7UqNQ4w.js";
2
- import { n as GenerateOptions } from "./index-DYzAccyT.js";
2
+ import { n as GenerateOptions } from "./index-EK43HM_z.js";
3
3
  //#region src/generator/arktype/index.d.ts
4
4
  /**
5
5
  * A whole JSON Schema document as an ArkType module. A document with definitions becomes
package/dist/arktype.js CHANGED
@@ -1 +1 @@
1
- export { t as schemaToArktype } from "./arktype-CRZ8vXZ5.js";
1
+ export { t as schemaToArktype } from "./arktype-CBV4bg-0.js";
package/dist/cli/ajv.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { t as schemaToAjv } from "../ajv-DS9gtNZC.js";
3
- import { n as version, t as cli } from "../cli-eAY8LqwP.js";
3
+ import { n as version, t as cli } from "../cli-CB9GJ7qa.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToArktype } from "../arktype-CRZ8vXZ5.js";
3
- import { n as version, t as cli } from "../cli-eAY8LqwP.js";
2
+ import { t as schemaToArktype } from "../arktype-CBV4bg-0.js";
3
+ import { n as version, t as cli } from "../cli-CB9GJ7qa.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToEffect } from "../effect-BkWovUi3.js";
3
- import { n as version, t as cli } from "../cli-eAY8LqwP.js";
2
+ import { t as schemaToEffect } from "../effect-D9pvwi_6.js";
3
+ import { n as version, t as cli } from "../cli-CB9GJ7qa.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToTypebox } from "../typebox-wYeJqy7T.js";
3
- import { n as version, t as cli } from "../cli-eAY8LqwP.js";
2
+ import { t as schemaToTypebox } from "../typebox-DGGKJLdP.js";
3
+ import { n as version, t as cli } from "../cli-CB9GJ7qa.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToValibot } from "../valibot-DQUEDYKt.js";
3
- import { n as version, t as cli } from "../cli-eAY8LqwP.js";
2
+ import { t as schemaToValibot } from "../valibot-B6y4VQFF.js";
3
+ import { n as version, t as cli } from "../cli-CB9GJ7qa.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
package/dist/cli/yup.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToYup } from "../yup-BMpa9Co1.js";
3
- import { n as version, t as cli } from "../cli-eAY8LqwP.js";
2
+ import { t as schemaToYup } from "../yup-DuqQwHUv.js";
3
+ import { n as version, t as cli } from "../cli-CB9GJ7qa.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
package/dist/cli/zod.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToZod } from "../zod-Dq9LtqPL.js";
3
- import { n as version, t as cli } from "../cli-eAY8LqwP.js";
2
+ import { t as schemaToZod } from "../zod-CXo9NFuF.js";
3
+ import { n as version, t as cli } from "../cli-CB9GJ7qa.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -9,7 +9,7 @@ import * as Stdio from "effect/Stdio";
9
9
  import "@effect/platform-node/NodeFileSystem";
10
10
  import * as FileSystem from "effect/FileSystem";
11
11
  //#region package.json
12
- var version = "0.8.1";
12
+ var version = "0.8.2";
13
13
  //#endregion
14
14
  //#region src/file/index.ts
15
15
  /** Creates the directory and its parents. An existing directory is not an error. */
@@ -1,5 +1,5 @@
1
1
  import { At as UNSAFE_GENERATED_MARKER, B as isSchemaObject, H as isStringWireLocation, M as isNullable, N as isObjectPrototypeProperty, S as hasFixedLength, T as hasType, V as isShapelessMember, X as DEFAULT_ROOT_NAME, at as INTEGER_TEXT_PATTERN, b as hasConditional, c as normalizeTypes, i as effectMessage, j as isNullTypeMember, k as isDefaultOnlyMember, n as effectError, pt as NUMBER_RANGES, r as effectErrorPart, s as makeSafeKey, x as hasFixedItemCount, y as hasCombinator } from "./utils-Bky98UmP.js";
2
- import { B as emitOptionsOf, C as isPrimitiveUnion, D as stringboolTruthyPattern, E as stringboolPattern, F as jsLiteral, G as schemaNamer, H as planDocument, M as formatPattern, N as regexSource, O as unionPrimitiveTypes, Q as findCodeExtensionKeysInSchema, S as isNullTextRead, T as ownProperties, U as renderDefinitions, W as rootNameOf, Y as itemsSchemaOf, _ as effectPreprocess, at as regexLiteral, b as integerWirePattern, c as withPolymorphicBases, d as propertyEmitOptions, et as constraintMessage, f as withoutParameterSerialization, g as hoistNestedRefs, h as valueListLiteral, i as isEvaluatedKeyExpression, j as wireNumericKind, k as wireArrayOnce, l as hasParameterSerialization, m as notPredicate, nt as foldAllOfMembers, o as typeDeclaration, p as isBigintFormat, q as hasRootSelfReference, r as evaluatedProperties, rt as isKeywordOnlyMember, s as refTarget, tt as constraintPredicate, u as parameterReaders, v as effectWrap, w as numberWirePattern, y as impliedWireType, z as definitionsOf } from "./helper-CbeedY35.js";
2
+ import { B as emitOptionsOf, C as isPrimitiveUnion, D as stringboolTruthyPattern, E as stringboolPattern, F as jsLiteral, G as schemaNamer, H as planDocument, J as hasRootSelfReference, K as discriminatedMembers, M as formatPattern, N as regexSource, O as unionPrimitiveTypes, S as isNullTextRead, T as ownProperties, U as renderDefinitions, W as rootNameOf, X as itemsSchemaOf, _ as effectPreprocess, at as foldAllOfMembers, b as integerWirePattern, c as withPolymorphicBases, ct as regexLiteral, d as propertyEmitOptions, f as withoutParameterSerialization, g as hoistNestedRefs, h as valueListLiteral, i as isEvaluatedKeyExpression, it as constraintPredicate, j as wireNumericKind, k as wireArrayOnce, l as hasParameterSerialization, m as notPredicate, o as typeDeclaration, ot as isKeywordOnlyMember, p as isBigintFormat, r as evaluatedProperties, rt as constraintMessage, s as refTarget, tt as findCodeExtensionKeysInSchema, u as parameterReaders, v as effectWrap, w as numberWirePattern, y as impliedWireType, z as definitionsOf } from "./helper-S7SSsYwh.js";
3
3
  //#region src/generator/effect/number.ts
4
4
  /** The bound and `multipleOf` checks of a numeric node. */
5
5
  function numberChecks(schema, lit = (n) => `${n}`, suffix = "") {
@@ -168,14 +168,21 @@ function object(schema, rootName, isEffect, options) {
168
168
  };
169
169
  const patternPropertiesFilters = () => schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, propSchema]) => {
170
170
  const s = effect(propSchema, rootName, isEffect, options);
171
- return `Schema.makeFilter((input)=>Object.entries(input).every(([key,value])=>!new RegExp(${JSON.stringify(pattern)}).test(key)||Schema.is(${s})(value))${patternErrorArg})`;
171
+ return `Schema.makeFilter((input)=>Object.entries(input).every(([key,value])=>!new RegExp(${JSON.stringify(pattern)}).test(key)||Schema.is(Schema.toEncoded(${s}))(value))${patternErrorArg})`;
172
172
  }) : [];
173
- if (typeof schema.additionalProperties === "object") {
173
+ if (typeof schema.additionalProperties === "object" && schema.properties === void 0 && schema.patternProperties === void 0) {
174
174
  const record = `Schema.Record(Schema.String,${effect(schema.additionalProperties, rootName, isEffect, options)})`;
175
- const checks = [propertyNamesFilter(), ...patternPropertiesFilters()].filter((a) => a !== "");
175
+ const checks = [propertyNamesFilter()].filter((a) => a !== "");
176
176
  return checks.length > 0 ? `${record}.check(${checks.join(",")})` : record;
177
177
  }
178
- if (!schema.properties) {
178
+ const properties = schema.properties ?? {};
179
+ const undeclaredRequired = (schema.required ?? []).filter((key) => !Object.hasOwn(properties, key));
180
+ const unevaluated = schema.unevaluatedProperties;
181
+ const closed = schema.additionalProperties === false || unevaluated === false;
182
+ const extraSchema = typeof schema.additionalProperties === "object" ? schema.additionalProperties : typeof unevaluated === "object" ? unevaluated : void 0;
183
+ const extraMessage = typeof schema.additionalProperties === "object" ? schema["x-additionalProperties-message"] : schema["x-unevaluatedProperties-message"];
184
+ const checksKeys = undeclaredRequired.length > 0 || extraSchema !== void 0 || closed;
185
+ if (!schema.properties && !checksKeys) {
179
186
  if (schema.patternProperties) {
180
187
  const record = "Schema.Record(Schema.String,Schema.Unknown)";
181
188
  const checks = [propertyNamesFilter(), ...patternPropertiesFilters()].filter((a) => a !== "");
@@ -185,7 +192,7 @@ function object(schema, rootName, isEffect, options) {
185
192
  return "Schema.Struct({})";
186
193
  }
187
194
  const required = new Set(schema.required);
188
- const props = Object.entries(schema.properties).map(([key, propSchema]) => {
195
+ const props = Object.entries(properties).map(([key, propSchema]) => {
189
196
  const parsed = effect(propSchema, rootName, isEffect, propertyEmitOptions(key, propSchema, options) ?? options);
190
197
  if (!parsed) return null;
191
198
  const safeKey = makeSafeKey(key);
@@ -193,9 +200,9 @@ function object(schema, rootName, isEffect, options) {
193
200
  const hasDecodingDefault = parsed.includes("Schema.withDecodingDefault");
194
201
  return isRequired || hasDecodingDefault ? `${safeKey}:${parsed}` : `${safeKey}:Schema.optional(${parsed})`;
195
202
  }).filter((p) => p !== null);
196
- const conditionalKeysReferenced = hasConditional(schema);
203
+ const readsUndeclaredKeys = hasConditional(schema) || schema.patternProperties !== void 0 || schema.propertyNames !== void 0 || schema.minProperties !== void 0 || schema.maxProperties !== void 0 || schema.dependentRequired !== void 0 || checksKeys;
197
204
  const struct = `Schema.Struct({${props.join(",")}})`;
198
- const rawBase = conditionalKeysReferenced ? `Schema.StructWithRest(${struct},[Schema.Record(Schema.String,Schema.Unknown)])` : struct;
205
+ const rawBase = readsUndeclaredKeys ? `Schema.StructWithRest(${struct},[Schema.Record(Schema.String,Schema.Unknown)])` : struct;
199
206
  const propsMessage = schema["x-properties-message"];
200
207
  const partialBase = propsMessage ? wholeValueMessage(rawBase, propsMessage) : rawBase;
201
208
  const minPropertiesFilter = typeof schema.minProperties === "number" ? `Schema.makeFilter((input)=>Object.keys(input).length>=${schema.minProperties}${minErrorArg})` : "";
@@ -206,7 +213,12 @@ function object(schema, rootName, isEffect, options) {
206
213
  const dependentSchemasFilters = schema.dependentSchemas ? Object.entries(schema.dependentSchemas).map(([key, subSchema]) => {
207
214
  return `Schema.makeFilter((input)=>!('${key}' in input)||Schema.is(${effect(subSchema, rootName, isEffect, options)})(input)${depSchErrorArg})`;
208
215
  }) : [];
209
- const strictExtrasAnnotation = schema.additionalProperties === false || schema.unevaluatedProperties === false ? strictExtrasMessage ? `.annotate({parseOptions:{onExcessProperty:"error"},messageUnexpectedKey:${JSON.stringify(strictExtrasMessage)}})` : `.annotate({parseOptions:{onExcessProperty:"error"}})` : "";
216
+ const requiredPresentFilter = undeclaredRequired.length > 0 ? `Schema.makeFilter((input)=>${JSON.stringify(undeclaredRequired)}.every((key)=>key in input)${errorArg})` : "";
217
+ const isEvaluated = isEvaluatedKeyExpression({
218
+ names: Object.keys(properties),
219
+ patterns: Object.keys(schema.patternProperties ?? {})
220
+ }, "key");
221
+ const unevaluatedKeysFilter = closed ? `Schema.makeFilter((input)=>Object.keys(input).every((key)=>${isEvaluated})${effectErrorPart(strictExtrasMessage ?? errorMessage)})` : extraSchema !== void 0 ? `Schema.makeFilter((input)=>Object.entries(input).every(([key,value])=>${isEvaluated}||Schema.is(Schema.toEncoded(${effect(extraSchema, rootName, isEffect, options)}))(value))${effectErrorPart(extraMessage ?? errorMessage)})` : "";
210
222
  const ifThenElseFilters = (() => {
211
223
  if (!schema.if) return [];
212
224
  const ifSchema = effect(schema.if, rootName, isEffect, options);
@@ -232,12 +244,14 @@ function object(schema, rootName, isEffect, options) {
232
244
  maxPropertiesFilter,
233
245
  propertyNamesFilter(),
234
246
  ...patternPropertiesFilters(),
247
+ requiredPresentFilter,
248
+ unevaluatedKeysFilter,
235
249
  ...dependentRequiredFilters,
236
250
  ...dependentSchemasFilters,
237
251
  ...ifThenElseFilters
238
252
  ].filter((a) => a !== "");
239
- const objectExpr = `${checks.length > 0 ? `${partialBase}.check(${checks.join(",")})` : partialBase}${strictExtrasAnnotation}`;
240
- const hasInheritedName = Object.keys(schema.properties).some(isObjectPrototypeProperty);
253
+ const objectExpr = checks.length > 0 ? `${partialBase}.check(${checks.join(",")})` : partialBase;
254
+ const hasInheritedName = Object.keys(properties).some(isObjectPrototypeProperty);
241
255
  return isStringWireLocation(options?.paramIn) && hasInheritedName ? effectPreprocess([ownProperties("input")], objectExpr) : objectExpr;
242
256
  }
243
257
  //#endregion
@@ -370,7 +384,7 @@ function intersect(schemas) {
370
384
  const [first, ...rest] = schemas;
371
385
  if (first === void 0) return "Schema.Unknown";
372
386
  if (schemas.every(isStructExpr)) return `Schema.Struct({${schemas.map((s) => `...${s}.fields`).join(",")}})`;
373
- if (schemas.some((s) => s.startsWith("Schema.suspend("))) return `(()=>{${schemas.map((s, i) => `const M${i}=${s}`).join(";")};return Schema.Unknown.pipe(Schema.refine((input):input is ${schemas.map((_, i) => `typeof M${i}.Type`).join("&")}=>${schemas.map((_, i) => `Schema.is(Schema.toEncoded(M${i}))(input)`).join("&&")}))})()`;
387
+ if (schemas.some((s) => s.startsWith("Schema.suspend("))) return `(()=>{${schemas.map((s, i) => `const M${i}=${s}`).join(";")};const isAll=(input:unknown):input is ${schemas.map((_, i) => `typeof M${i}.Type`).join("&")}=>${schemas.map((_, i) => `Schema.is(M${i})(input)`).join("&&")};return Schema.Unknown.pipe(Schema.decodeTo(Schema.declare(isAll),{decode:${`SchemaGetter.transformEffect((input)=>Effect.all([${schemas.map((_, i) => `Schema.decodeUnknownEffect(M${i})(input)`).join(",")}]).pipe(Effect.mapError((error)=>error.issue),Effect.flatMap((values)=>{const merged=values.every((value)=>typeof value==='object'&&value!==null&&!Array.isArray(value))?Object.assign({},...values):values[0];return isAll(merged)?Effect.succeed(merged):Effect.fail(new SchemaIssue.InvalidValue(undefined,merged))})))`},encode:SchemaGetter.passthrough({strict:false})}))})()`;
374
388
  return `${first}.check(${rest.map((s) => `Schema.makeFilter((input)=>Schema.is(${s})(input))`).join(",")})`;
375
389
  }
376
390
  /**
@@ -387,16 +401,20 @@ function wholeValueMessage(inner, message) {
387
401
  return `Schema.Unknown.check(Schema.makeFilter((input)=>Schema.is(${inner})(input),${effectError(message)})).pipe(Schema.decodeTo(${inner}))`;
388
402
  }
389
403
  /**
390
- * An `allOf` with `unevaluatedProperties` beside it: the members' structs strip what they
391
- * do not declare, so the keys no member evaluates are checked on the input before it is
392
- * decoded. `inner` as given when the keyword is absent or every key is evaluated.
404
+ * An `allOf` with `patternProperties` or `unevaluatedProperties` beside it: the members'
405
+ * structs strip what they do not declare, so the keys are checked on the input before it is
406
+ * decoded — a key a pattern matches against that pattern's schema, a key no member
407
+ * evaluates against `unevaluatedProperties`. `inner` as given when there is nothing to check.
393
408
  */
394
- function unevaluatedPropertiesCheck(inner, schema, rootName, isEffect, options) {
409
+ function objectKeysCheck(inner, schema, rootName, isEffect, options) {
410
+ const patterns = Object.entries(schema.patternProperties ?? {});
395
411
  const unevaluated = schema.unevaluatedProperties;
396
- if (unevaluated !== false && (typeof unevaluated !== "object" || unevaluated === null)) return inner;
397
- const evaluated = evaluatedProperties(schema, options?.definitions);
398
- if (evaluated === void 0) return inner;
399
- return `Schema.Unknown.check(Schema.makeFilter(${`(input)=>typeof input!=='object'||input===null||Array.isArray(input)||Object.entries(input).every(([k,v])=>${isEvaluatedKeyExpression(evaluated, "k")}||${unevaluated === false ? "false" : `Schema.is(${effect(unevaluated, rootName, isEffect, options)})(v)`})`}${effectErrorPart(schema["x-unevaluatedProperties-message"])})).pipe(Schema.decodeTo(${inner}))`;
412
+ const unevaluatedSchema = typeof unevaluated === "object" ? unevaluated : void 0;
413
+ const evaluated = unevaluated === false || unevaluatedSchema !== void 0 ? evaluatedProperties(schema, options?.definitions) : void 0;
414
+ const accepts = (s) => `Schema.is(Schema.toEncoded(${effect(s, rootName, isEffect, options)}))(v)`;
415
+ const filters = [...patterns.map(([pattern, propSchema]) => `Schema.makeFilter((input)=>typeof input!=='object'||input===null||Array.isArray(input)||Object.entries(input).every(([k,v])=>!new RegExp(${JSON.stringify(pattern)}).test(k)||${accepts(propSchema)})${effectErrorPart(schema["x-patternProperties-message"])})`), ...evaluated === void 0 ? [] : [`Schema.makeFilter((input)=>typeof input!=='object'||input===null||Array.isArray(input)||Object.entries(input).every(([k,v])=>${isEvaluatedKeyExpression(evaluated, "k")}||${unevaluatedSchema === void 0 ? "false" : accepts(unevaluatedSchema)})${effectErrorPart(schema["x-unevaluatedProperties-message"])})`]];
416
+ if (filters.length === 0) return inner;
417
+ return `Schema.Unknown.check(${filters.join(",")}).pipe(Schema.decodeTo(${inner}))`;
400
418
  }
401
419
  /**
402
420
  * Generate Effect Schema code from a JSON Schema.
@@ -460,7 +478,14 @@ function node(schema, rootName, isEffect, options) {
460
478
  }, rootName, isEffect, options);
461
479
  if (schema.oneOf) {
462
480
  if (schema.oneOf.length === 0) return effectWrap$1("Schema.Unknown", schema);
463
- const schemas = schema.oneOf.map((s) => effect(s, rootName, isEffect, options));
481
+ const discriminated = discriminatedMembers(schema, schema.oneOf);
482
+ const schemas = schema.oneOf.map((s, i) => {
483
+ const member = effect(s, rootName, isEffect, options);
484
+ const values = discriminated?.members[i]?.values;
485
+ if (discriminated === void 0 || values === void 0) return member;
486
+ const literal = values.length === 1 ? `Schema.Literal(${JSON.stringify(values[0])})` : `Schema.Literals(${JSON.stringify(values)})`;
487
+ return intersect([member, `Schema.Struct({${makeSafeKey(discriminated.propertyName)}:${literal}})`]);
488
+ });
464
489
  const oneOfMessage = schema["x-oneOf-message"];
465
490
  const expr = `Schema.Union([${schemas.join(",")}])`;
466
491
  return effectWrap$1(oneOfMessage ? `${expr}.annotate(${effectError(oneOfMessage)})` : expr, schema);
@@ -483,7 +508,7 @@ function node(schema, rootName, isEffect, options) {
483
508
  });
484
509
  const intersected = schemas.length === 1 ? schemas[0] : intersect(schemas);
485
510
  const allOfMessage = schema["x-allOf-message"];
486
- const baseResult = unevaluatedPropertiesCheck(allOfMessage ? wholeValueMessage(intersected, allOfMessage) : intersected, schema, rootName, isEffect, options);
511
+ const baseResult = objectKeysCheck(allOfMessage ? wholeValueMessage(intersected, allOfMessage) : intersected, schema, rootName, isEffect, options);
487
512
  if (defaultValue !== void 0) return `${nullable ? `Schema.NullOr(${baseResult})` : baseResult}.pipe(${isWireCoerced ? "Schema.withDecodingDefaultType" : "Schema.withDecodingDefault"}(Effect.succeed(${jsLiteral(defaultValue)})))`;
488
513
  return effectWrap$1(baseResult, {
489
514
  ...schema,
@@ -661,8 +686,10 @@ function schemaToEffect(input, options) {
661
686
  const rootExport = needsTypeDef ? `export const ${rootName}: Schema.Schema<_${rootName}> = ${rootSchema}` : `export const ${rootName} = ${rootSchema}`;
662
687
  const emitted = `${schemaDefsCode}\n${rootExport}`;
663
688
  const importLine = `import { ${[
664
- ...emitted.includes("Effect.succeed(") ? ["Effect"] : [],
689
+ .../(?<![\w.])Effect\./u.test(emitted) ? ["Effect"] : [],
665
690
  "Schema",
691
+ ...emitted.includes("SchemaGetter.") ? ["SchemaGetter"] : [],
692
+ ...emitted.includes("SchemaIssue.") ? ["SchemaIssue"] : [],
666
693
  ...emitted.includes("SchemaTransformation.") ? ["SchemaTransformation"] : []
667
694
  ].join(", ")} } from "effect"`;
668
695
  return [
package/dist/effect.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { r as JSONSchema } from "./index-G7UqNQ4w.js";
2
- import { n as GenerateOptions } from "./index-DYzAccyT.js";
2
+ import { n as GenerateOptions } from "./index-EK43HM_z.js";
3
3
  //#region src/generator/effect/index.d.ts
4
4
  /**
5
5
  * A whole JSON Schema document as an Effect Schema module: imports, `$defs` in
package/dist/effect.js CHANGED
@@ -1 +1 @@
1
- export { t as schemaToEffect } from "./effect-BkWovUi3.js";
1
+ export { t as schemaToEffect } from "./effect-D9pvwi_6.js";
@@ -484,6 +484,24 @@ function readCodeExtension(schema, key, options) {
484
484
  //#endregion
485
485
  //#region src/helper/arktype-wrap.ts
486
486
  /**
487
+ * A definition a callback checks values against at validation time. Inside
488
+ * `scope({...})` it goes through the scope (bound to `$`), which resolves the aliases
489
+ * it may name; the global `type(...)` cannot. An expression that already evaluates to a
490
+ * `Type` is used as it is.
491
+ */
492
+ function callbackType(source, scopeMode) {
493
+ if (scopeMode) return isArktypeDefinition(source) ? `$.type(${source})` : source;
494
+ return isQuoted(source) ? `type(${source})` : source;
495
+ }
496
+ /**
497
+ * A callback that reaches the scope through `$`: its return type is spelled out, since
498
+ * `$` is still being declared where the callback is written and TypeScript would
499
+ * otherwise infer the scope's type from itself.
500
+ */
501
+ function callbackReturn(params, body) {
502
+ return `${params}${body.includes("$.type(") ? ": boolean" : ""} => ${body}`;
503
+ }
504
+ /**
487
505
  * `inner` read after `readers`, each a `(data) => ...` arrow over the raw value: a morph
488
506
  * from `input` that pipes into `inner`, with `.to()` for a bare definition.
489
507
  */
@@ -659,6 +677,42 @@ function cyclicDefinitionNames(schema) {
659
677
  return cyclic;
660
678
  }
661
679
  //#endregion
680
+ //#region src/helper/discriminator.ts
681
+ function definitionName(ref) {
682
+ for (const prefix of DEFINITION_REF_PREFIXES) {
683
+ if (!ref.startsWith(prefix)) continue;
684
+ const rest = ref.slice(prefix.length);
685
+ if (rest === "" || rest.includes("/")) return void 0;
686
+ return decodeURIComponent(rest);
687
+ }
688
+ }
689
+ /**
690
+ * The discriminator values that select each `oneOf` / `anyOf` member (OpenAPI 3.x
691
+ * Discriminator Object): the `mapping` keys whose target names the member's `$ref`, or,
692
+ * when the mapping names it nowhere, the definition name itself (the implicit mapping).
693
+ * `undefined` when the node has no discriminator property.
694
+ */
695
+ function discriminatedMembers(schema, members) {
696
+ const propertyName = schema.discriminator?.propertyName;
697
+ if (propertyName === void 0) return void 0;
698
+ const mapping = Object.entries(schema.discriminator?.mapping ?? {});
699
+ return {
700
+ propertyName,
701
+ members: members.map((member) => {
702
+ const name = member.$ref === void 0 ? void 0 : definitionName(member.$ref);
703
+ if (name === void 0) return {
704
+ member,
705
+ values: void 0
706
+ };
707
+ const mapped = mapping.filter(([, target]) => target === member.$ref || definitionName(target) === name).map(([value]) => value);
708
+ return {
709
+ member,
710
+ values: mapped.length > 0 ? mapped : [name]
711
+ };
712
+ })
713
+ };
714
+ }
715
+ //#endregion
662
716
  //#region src/helper/resolve-schema-dependencies-from-schema.ts
663
717
  /** The definition name the fragment of an external `$ref` points at, if it names one. */
664
718
  function fragmentDefinitionName(fragment) {
@@ -1618,10 +1672,10 @@ function nonNullType(schema, flavour, rootName) {
1618
1672
  * time, because TypeBox stores metadata on the schema object during
1619
1673
  * construction and exposes no post-construction `.meta()` method.
1620
1674
  */
1621
- function typeboxWrap(typeboxStr, schema) {
1675
+ function typeboxWrap(typeboxStr, schema, definitions) {
1622
1676
  const withNullable = isNullable(schema) ? `Type.Union([${typeboxStr},Type.Null()])` : typeboxStr;
1623
1677
  const withReadonly = schema["x-readonly"] === true ? `Type.Readonly(${withNullable})` : withNullable;
1624
- return hasKeptDefault(schema) ? `Type.Optional(${withReadonly})` : withReadonly;
1678
+ return hasKeptDefault(schema, definitions) ? `Type.Optional(${withReadonly})` : withReadonly;
1625
1679
  }
1626
1680
  //#endregion
1627
1681
  //#region src/helper/unevaluated.ts
@@ -1795,4 +1849,4 @@ function zodWrap(zodStr, schema, options) {
1795
1849
  return withMeta;
1796
1850
  }
1797
1851
  //#endregion
1798
- export { hasNotKeyword as $, wireNullText as A, emitOptionsOf as B, isPrimitiveUnion as C, stringboolTruthyPattern as D, stringboolPattern as E, jsLiteral as F, schemaNamer as G, planDocument as H, typeboxDefaultOpt as I, isOptionalByDefault as J, cyclicDefinitionNames as K, typeboxMetaOpts as L, formatPattern as M, regexSource as N, unionPrimitiveTypes as O, timePattern as P, findCodeExtensionKeysInSchema as Q, typeboxRefOpt as R, isNullTextRead as S, ownProperties as T, renderDefinitions as U, missingDefinitionComment as V, rootNameOf as W, arktypePreprocess as X, itemsSchemaOf as Y, arktypeWrap as Z, effectPreprocess as _, typeboxWrap as a, regexLiteral as at, integerWirePattern as b, withPolymorphicBases as c, propertyEmitOptions as d, constraintMessage as et, withoutParameterSerialization as f, hoistNestedRefs as g, valueListLiteral as h, isEvaluatedKeyExpression as i, patternSource as it, wireNumericKind as j, wireArrayOnce as k, hasParameterSerialization as l, notPredicate as m, valibotWrap as n, foldAllOfMembers as nt, typeDeclaration as o, isBigintFormat as p, hasRootSelfReference as q, evaluatedProperties as r, isKeywordOnlyMember as rt, refTarget as s, zodWrap as t, constraintPredicate as tt, parameterReaders as u, effectWrap as v, numberWirePattern as w, isNullMatchedFirst as x, impliedWireType as y, definitionsOf as z };
1852
+ export { callbackReturn as $, wireNullText as A, emitOptionsOf as B, isPrimitiveUnion as C, stringboolTruthyPattern as D, stringboolPattern as E, jsLiteral as F, schemaNamer as G, planDocument as H, typeboxDefaultOpt as I, hasRootSelfReference as J, discriminatedMembers as K, typeboxMetaOpts as L, formatPattern as M, regexSource as N, unionPrimitiveTypes as O, timePattern as P, arktypeWrap as Q, typeboxRefOpt as R, isNullTextRead as S, ownProperties as T, renderDefinitions as U, missingDefinitionComment as V, rootNameOf as W, itemsSchemaOf as X, isOptionalByDefault as Y, arktypePreprocess as Z, effectPreprocess as _, typeboxWrap as a, foldAllOfMembers as at, integerWirePattern as b, withPolymorphicBases as c, regexLiteral as ct, propertyEmitOptions as d, callbackType as et, withoutParameterSerialization as f, hoistNestedRefs as g, valueListLiteral as h, isEvaluatedKeyExpression as i, constraintPredicate as it, wireNumericKind as j, wireArrayOnce as k, hasParameterSerialization as l, notPredicate as m, valibotWrap as n, hasNotKeyword as nt, typeDeclaration as o, isKeywordOnlyMember as ot, isBigintFormat as p, cyclicDefinitionNames as q, evaluatedProperties as r, constraintMessage as rt, refTarget as s, patternSource as st, zodWrap as t, findCodeExtensionKeysInSchema as tt, parameterReaders as u, effectWrap as v, numberWirePattern as w, isNullMatchedFirst as x, impliedWireType as y, definitionsOf as z };
@@ -66,4 +66,4 @@ type GenerateOptions = {
66
66
  /** The options threaded through every node emitter: `GenerateOptions` without `exportType`. */
67
67
  type EmitOptions = Omit<GenerateOptions, 'exportType'>;
68
68
  //#endregion
69
- export { GenerateOptions as n, EmitOptions as t };
69
+ export { GenerateOptions as n, SchemaDefinitions as r, EmitOptions as t };