@scalar/workspace-store 0.70.0 → 0.71.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 (61) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/entities/auth/schema.d.ts +150 -0
  3. package/dist/entities/auth/schema.d.ts.map +1 -1
  4. package/dist/events/definitions/operation.d.ts +1 -1
  5. package/dist/events/definitions/operation.d.ts.map +1 -1
  6. package/dist/helpers/is-file-schema.d.ts +4 -0
  7. package/dist/helpers/is-file-schema.d.ts.map +1 -0
  8. package/dist/helpers/is-file-schema.js +53 -0
  9. package/dist/helpers/resolve-form-schema.d.ts +1 -1
  10. package/dist/helpers/resolve-form-schema.d.ts.map +1 -1
  11. package/dist/helpers/resolve-form-schema.js +13 -3
  12. package/dist/request-example/builder/helpers/get-example-from-schema.d.ts +9 -2
  13. package/dist/request-example/builder/helpers/get-example-from-schema.d.ts.map +1 -1
  14. package/dist/request-example/builder/helpers/get-example-from-schema.js +538 -74
  15. package/dist/request-example/builder/security/secret-types.d.ts +4 -0
  16. package/dist/request-example/builder/security/secret-types.d.ts.map +1 -1
  17. package/dist/request-example/context/security/extract-security-scheme-secrets.d.ts +5 -1
  18. package/dist/request-example/context/security/extract-security-scheme-secrets.d.ts.map +1 -1
  19. package/dist/request-example/context/security/extract-security-scheme-secrets.js +26 -6
  20. package/dist/request-example/context/security/get-selected-security.js +3 -3
  21. package/dist/request-example/context/security/resolve-credential-placeholders.d.ts +13 -0
  22. package/dist/request-example/context/security/resolve-credential-placeholders.d.ts.map +1 -0
  23. package/dist/request-example/context/security/resolve-credential-placeholders.js +73 -0
  24. package/dist/request-example/index.d.ts +3 -1
  25. package/dist/request-example/index.d.ts.map +1 -1
  26. package/dist/request-example/index.js +3 -1
  27. package/dist/schemas/extensions/document/x-scalar-sdk-installation.d.ts +4 -0
  28. package/dist/schemas/extensions/document/x-scalar-sdk-installation.d.ts.map +1 -1
  29. package/dist/schemas/extensions/document/x-scalar-sdk-installation.js +2 -0
  30. package/dist/schemas/extensions/operation/x-code-samples.d.ts +11 -0
  31. package/dist/schemas/extensions/operation/x-code-samples.d.ts.map +1 -1
  32. package/dist/schemas/extensions/operation/x-code-samples.js +2 -0
  33. package/dist/schemas/extensions/security/x-scalar-credential-placeholders.d.ts +24 -0
  34. package/dist/schemas/extensions/security/x-scalar-credential-placeholders.d.ts.map +1 -0
  35. package/dist/schemas/extensions/security/x-scalar-credential-placeholders.js +17 -0
  36. package/dist/schemas/reference-config/index.d.ts +30 -0
  37. package/dist/schemas/reference-config/index.d.ts.map +1 -1
  38. package/dist/schemas/reference-config/settings.d.ts +30 -0
  39. package/dist/schemas/reference-config/settings.d.ts.map +1 -1
  40. package/dist/schemas/v3.1/strict/info.d.ts +1 -0
  41. package/dist/schemas/v3.1/strict/info.d.ts.map +1 -1
  42. package/dist/schemas/v3.1/strict/openapi-document.d.ts +1050 -0
  43. package/dist/schemas/v3.1/strict/openapi-document.d.ts.map +1 -1
  44. package/dist/schemas/v3.1/strict/operation.d.ts +4 -0
  45. package/dist/schemas/v3.1/strict/operation.d.ts.map +1 -1
  46. package/dist/schemas/v3.1/strict/security-scheme.d.ts +27 -1
  47. package/dist/schemas/v3.1/strict/security-scheme.d.ts.map +1 -1
  48. package/dist/schemas/v3.1/strict/security-scheme.js +2 -1
  49. package/dist/schemas/v3.2/openapi/index.d.ts +1 -0
  50. package/dist/schemas/v3.2/openapi/index.d.ts.map +1 -1
  51. package/dist/schemas/v3.2/openapi/index.js +2 -0
  52. package/dist/schemas/v3.2/strict/info.d.ts +1 -0
  53. package/dist/schemas/v3.2/strict/info.d.ts.map +1 -1
  54. package/dist/schemas/v3.2/strict/openapi-document.d.ts +1050 -0
  55. package/dist/schemas/v3.2/strict/openapi-document.d.ts.map +1 -1
  56. package/dist/schemas/v3.2/strict/operation.d.ts +4 -0
  57. package/dist/schemas/v3.2/strict/operation.d.ts.map +1 -1
  58. package/dist/schemas/v3.2/strict/security-scheme.d.ts +27 -1
  59. package/dist/schemas/v3.2/strict/security-scheme.d.ts.map +1 -1
  60. package/dist/schemas/v3.2/strict/security-scheme.js +2 -1
  61. package/package.json +9 -9
@@ -1,7 +1,12 @@
1
1
  import { isDefined } from '@scalar/helpers/array/is-defined';
2
2
  import { isJsonMediaType } from '@scalar/helpers/http/is-json-media-type';
3
3
  import { escapeJsonPointer } from '@scalar/helpers/json/escape-json-pointer';
4
+ import { unescapeJsonPointer } from '@scalar/helpers/json/unescape-json-pointer';
5
+ import { isObject } from '@scalar/helpers/object/is-object';
4
6
  import { isDynamicRef, pushDynamicScope, resolveDynamicRef } from '../../../helpers/dynamic-ref.js';
7
+ import { getResolvedRef } from '../../../helpers/get-resolved-ref.js';
8
+ import { isFileSchema } from '../../../helpers/is-file-schema.js';
9
+ import { resolveFormSchema } from '../../../helpers/resolve-form-schema.js';
5
10
  import { unpackProxyObject } from '../../../helpers/unpack-proxy.js';
6
11
  import { resolve } from '../../../resolve.js';
7
12
  import { EXAMPLE_EVALUATION } from './example-evaluation.js';
@@ -67,7 +72,7 @@ const getPropertyNamesEnumValues = (schema) => {
67
72
  */
68
73
  const guessFromFormat = (schema, makeUpRandomData = false, fallback = '') => {
69
74
  // Binary filename placeholders are converted to File objects only for multipart callers.
70
- if ('type' in schema && schema.type === 'string' && 'format' in schema && schema.format === 'binary') {
75
+ if (isFileSchema(schema, false)) {
71
76
  return '@filename';
72
77
  }
73
78
  if ('format' in schema && ['date', 'date-time', 'time'].includes(schema.format ?? '')) {
@@ -166,12 +171,12 @@ const isComposed = (schema) => !!(schema.allOf || schema.oneOf || schema.anyOf);
166
171
  * Determine if a property should be omitted based on the options.
167
172
  * Properties are omitted if they are not required and the option is enabled.
168
173
  */
169
- const shouldOmitProperty = (schema, parentSchema, propertyName, options) => {
174
+ const shouldOmitProperty = (schema, parentSchema, propertyName, options, isRequiredProperty = false) => {
170
175
  // Early exits for schemas that should not be included (readOnly, writeOnly)
171
176
  if ((options?.mode === 'write' && schema.readOnly) || (options?.mode === 'read' && schema.writeOnly)) {
172
177
  return true;
173
178
  }
174
- if (options?.omitEmptyAndOptionalProperties !== true) {
179
+ if (isRequiredProperty || options?.omitEmptyAndOptionalProperties !== true) {
175
180
  return false;
176
181
  }
177
182
  // Never omit container types (objects/arrays) or composed schemas
@@ -392,6 +397,87 @@ const getDiscriminatorSelectionIndex = (schema, variants, options, value) => {
392
397
  const fallbackIndex = findTarget(discriminator.defaultMapping);
393
398
  return fallbackIndex >= 0 ? fallbackIndex : undefined;
394
399
  };
400
+ const COMPONENT_SCHEMA_PREFIX = '#/components/schemas/';
401
+ /**
402
+ * Find the discriminator value that selects `variant`: the explicit mapping key that targets it,
403
+ * or the component name, which is the implicit mapping.
404
+ */
405
+ const getDiscriminatorTag = (discriminator, variant) => {
406
+ if (!('$ref' in variant) || typeof variant.$ref !== 'string') {
407
+ return undefined;
408
+ }
409
+ const reference = variant.$ref;
410
+ const componentName = reference.startsWith(COMPONENT_SCHEMA_PREFIX)
411
+ ? unescapeJsonPointer(reference.slice(COMPONENT_SCHEMA_PREFIX.length))
412
+ : undefined;
413
+ const mapped = Object.entries(discriminator.mapping ?? {}).find(([, target]) => target === reference || target === componentName);
414
+ return mapped?.[0] ?? componentName;
415
+ };
416
+ /** Preserve authored or intentionally omitted values while following the same composition choices as generation. */
417
+ const hasPreservedDiscriminatorValue = (schema, propertyName, options, schemaPath, seen = new Set(), level = 0) => {
418
+ const resolved = schema && resolve.schema(schema);
419
+ if (!resolved || level > MAX_LEVELS_DEEP) {
420
+ return false;
421
+ }
422
+ if (propertyName === undefined && shouldOmitProperty(resolved, undefined, undefined, { mode: options?.mode })) {
423
+ return true;
424
+ }
425
+ const target = getSchemaCacheTarget(resolved);
426
+ if (seen.has(target)) {
427
+ return false;
428
+ }
429
+ const nextSeen = new Set(seen).add(target);
430
+ const variable = resolved['x-variable'];
431
+ const value = variable && options?.variables?.[variable] !== undefined ? options.variables[variable] : getDeclaredValue(resolved);
432
+ if (value !== undefined) {
433
+ return (propertyName === undefined || (value !== null && typeof value === 'object' && Object.hasOwn(value, propertyName)));
434
+ }
435
+ if (propertyName !== undefined && 'properties' in resolved) {
436
+ const property = resolved.properties?.[propertyName];
437
+ const resolvedProperty = property && resolve.schema(property);
438
+ if (resolvedProperty && shouldOmitProperty(resolvedProperty, resolved, propertyName, options)) {
439
+ return true;
440
+ }
441
+ if (hasPreservedDiscriminatorValue(property, undefined, options, [...schemaPath, propertyName], nextSeen, level + 1)) {
442
+ return true;
443
+ }
444
+ }
445
+ const anyOfKeyword = resolved.anyOf ? 'anyOf' : undefined;
446
+ const keyword = resolved.oneOf ? 'oneOf' : anyOfKeyword;
447
+ if (keyword) {
448
+ const selected = selectExampleComposition(resolved, schemaPath, options);
449
+ return hasPreservedDiscriminatorValue(selected, propertyName, consumeCompositionSelection(options, schemaPath, keyword), schemaPath, nextSeen, level + 1);
450
+ }
451
+ let choiceIndex = 0;
452
+ return (resolved.allOf?.some((member) => {
453
+ const resolvedMember = resolve.schema(member);
454
+ const isChoice = !!resolvedMember && !!(resolvedMember.oneOf || resolvedMember.anyOf);
455
+ const memberPath = isChoice ? [...schemaPath, String(choiceIndex++)] : schemaPath;
456
+ return hasPreservedDiscriminatorValue(member, propertyName, options, memberPath, nextSeen, level + 1);
457
+ }) ?? false);
458
+ };
459
+ /**
460
+ * Write the selected variant's discriminator value into the example. Without it the example
461
+ * carries an empty tag and a server cannot tell which variant it is. Declared values win, and a
462
+ * `defaultMapping` means the property may be omitted, so selection alone decides the variant there.
463
+ */
464
+ const withDiscriminatorTag = (schema, variant, example, options, schemaPath) => {
465
+ const discriminator = schema.discriminator;
466
+ if (!discriminator ||
467
+ discriminator.defaultMapping !== undefined ||
468
+ !variant ||
469
+ options?.xml ||
470
+ !example ||
471
+ typeof example !== 'object' ||
472
+ Array.isArray(example)) {
473
+ return example;
474
+ }
475
+ if (hasPreservedDiscriminatorValue(schema, discriminator.propertyName, options, schemaPath)) {
476
+ return example;
477
+ }
478
+ const tag = getDiscriminatorTag(discriminator, variant);
479
+ return tag === undefined ? example : { ...example, [discriminator.propertyName]: tag };
480
+ };
395
481
  /**
396
482
  * Read the numeric `x-order` extension value from a raw property entry, if present.
397
483
  * The entry may be a schema or a `$ref` object, so we check membership before reading.
@@ -426,11 +512,22 @@ const sortPropertyNamesByXOrder = (properties) => Object.keys(properties).sort((
426
512
  * Build an example for an object schema, including properties, patternProperties,
427
513
  * additionalProperties, and composition (allOf/oneOf/anyOf) merging.
428
514
  */
429
- const handleObjectSchema = (schema, options, level, seen, cacheKey, schemaPath, dynamicScope) => {
515
+ const handleObjectSchema = (schema, options, level, seen, cacheKey, schemaPath, dynamicScope, requiredScope) => {
430
516
  const response = {};
431
517
  // Children are evaluated with this schema added to the dynamic scope so nested `$dynamicRef`s bind here.
432
518
  const childScope = pushDynamicScope(dynamicScope, schema);
433
519
  const skipCache = dynamicScope.length > 0 || !!options?.[EXAMPLE_EVALUATION];
520
+ // Carry requirements through composition wrappers before they cross the cap. Property children
521
+ // start their own scope, since their required names belong to a different object.
522
+ const memberRequiredScope = requiredScope ??
523
+ (isComposed(schema)
524
+ ? getCompositionRequiredNames(schema, options, schemaPath, level, seen, dynamicScope)
525
+ : undefined);
526
+ // Past the cap only the properties the object requires are rendered: optional ones are what the cap
527
+ // exists to stop descending into. Composition members share the names of the object they belong to.
528
+ const required = level > MAX_LEVELS_DEEP
529
+ ? (memberRequiredScope ?? getCompositionRequiredNames(schema, options, schemaPath, level, seen, dynamicScope))
530
+ : undefined;
434
531
  if ('properties' in schema && schema.properties) {
435
532
  const properties = schema.properties;
436
533
  const propertyNames = sortPropertyNamesByXOrder(properties);
@@ -438,24 +535,39 @@ const handleObjectSchema = (schema, options, level, seen, cacheKey, schemaPath,
438
535
  for (let i = 0; i < limit; i++) {
439
536
  const propertyName = propertyNames[i];
440
537
  const propertySchema = resolve.schema(properties[propertyName]);
441
- if (!propertySchema) {
538
+ if (!propertySchema || (required && !required.has(propertyName))) {
442
539
  continue;
443
540
  }
444
541
  const propertyXmlName = options?.xml && 'xml' in propertySchema ? propertySchema.xml?.name : undefined;
445
- const value = getExampleFromSchema(propertySchema, options, {
446
- level: level + 1,
447
- parentSchema: schema,
448
- name: propertyName,
449
- schemaPath: [...schemaPath, propertyName],
450
- seen,
451
- dynamicScope: childScope,
452
- });
542
+ const discriminatorExample = schema.discriminator?.defaultMapping !== undefined && schema.discriminator.propertyName === propertyName
543
+ ? evaluateDiscriminator(schema, options, {
544
+ level,
545
+ schemaPath,
546
+ seen,
547
+ dynamicScope,
548
+ isRequiredProperty: !!required,
549
+ })
550
+ : undefined;
551
+ if (discriminatorExample?.evaluation) {
552
+ options?.[EXAMPLE_EVALUATION]?.stack.at(-1)?.children.push(discriminatorExample.evaluation);
553
+ }
554
+ const value = discriminatorExample
555
+ ? discriminatorExample.value
556
+ : getExampleFromSchema(propertySchema, options, {
557
+ level: level + 1,
558
+ parentSchema: schema,
559
+ name: propertyName,
560
+ isRequiredProperty: !!required,
561
+ schemaPath: [...schemaPath, propertyName],
562
+ seen,
563
+ dynamicScope: childScope,
564
+ });
453
565
  if (typeof value !== 'undefined') {
454
566
  response[propertyXmlName ?? propertyName] = value;
455
567
  }
456
568
  }
457
569
  }
458
- if ('patternProperties' in schema && schema.patternProperties) {
570
+ if (!required && 'patternProperties' in schema && schema.patternProperties) {
459
571
  for (const pattern of Object.keys(schema.patternProperties)) {
460
572
  const propertySchema = resolve.schema(schema.patternProperties[pattern]);
461
573
  if (!propertySchema) {
@@ -471,7 +583,7 @@ const handleObjectSchema = (schema, options, level, seen, cacheKey, schemaPath,
471
583
  });
472
584
  }
473
585
  }
474
- if ('additionalProperties' in schema && schema.additionalProperties) {
586
+ if (!required && 'additionalProperties' in schema && schema.additionalProperties) {
475
587
  const additional = typeof schema.additionalProperties === 'boolean'
476
588
  ? schema.additionalProperties
477
589
  : resolve.schema(schema.additionalProperties);
@@ -512,7 +624,9 @@ const handleObjectSchema = (schema, options, level, seen, cacheKey, schemaPath,
512
624
  schemaPath,
513
625
  seen,
514
626
  dynamicScope: childScope,
627
+ requiredScope: memberRequiredScope,
515
628
  }));
629
+ Object.assign(response, withDiscriminatorTag(schema, chosen, response, options, schemaPath));
516
630
  }
517
631
  }
518
632
  // allOf — thread a choice-ordinal into schemaPath for each direct oneOf/anyOf
@@ -532,6 +646,7 @@ const handleObjectSchema = (schema, options, level, seen, cacheKey, schemaPath,
532
646
  seen,
533
647
  dynamicScope: childScope,
534
648
  schemaPath: memberSchemaPath,
649
+ requiredScope: memberRequiredScope,
535
650
  });
536
651
  merged = mergeExamples(merged, ex);
537
652
  }
@@ -546,20 +661,98 @@ const handleObjectSchema = (schema, options, level, seen, cacheKey, schemaPath,
546
661
  }
547
662
  return cache(schema, response, cacheKey, skipCache);
548
663
  };
664
+ /** Bound padding per array, counting repeated values by their serialized size; not a global output limit. */
665
+ const MAX_ARRAY_PADDING_NODES = 1_000;
666
+ const countExampleNodes = (value, limit) => {
667
+ if (limit <= 1 || value === null || typeof value !== 'object') {
668
+ return 1;
669
+ }
670
+ let count = 1;
671
+ for (const child of Array.isArray(value) ? value : Object.values(value)) {
672
+ count += countExampleNodes(child, limit - count);
673
+ if (count >= limit) {
674
+ break;
675
+ }
676
+ }
677
+ return count;
678
+ };
679
+ /** Ignore malformed bounds from unvalidated descriptions. */
680
+ const readArrayLengthBound = (value, fallback) => typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : fallback;
681
+ /** Recognize an array described by its item keywords when no type was declared. */
682
+ const inferArrayType = (schema) => !('properties' in schema) && ('items' in schema || 'prefixItems' in schema) ? 'array' : undefined;
683
+ /** Apply the same explicit-type and inference precedence at either union selection site. */
684
+ const getSelectedType = (variant, holder) => (variant && 'type' in variant ? variant.type : undefined) ??
685
+ ('type' in holder ? holder.type : undefined) ??
686
+ (hasUnencodedJsonContent(holder) ? 'string' : ((variant && inferArrayType(variant)) ?? inferArrayType(holder)));
687
+ /** These keywords describe values without restricting which values the schema accepts. */
688
+ const ITEM_ANNOTATIONS = new Set([
689
+ '$ref',
690
+ '$id',
691
+ '$schema',
692
+ '$anchor',
693
+ '$comment',
694
+ '$defs',
695
+ 'definitions',
696
+ 'title',
697
+ 'description',
698
+ 'deprecated',
699
+ 'readOnly',
700
+ 'writeOnly',
701
+ 'examples',
702
+ 'default',
703
+ 'example',
704
+ 'xml',
705
+ 'externalDocs',
706
+ ]);
707
+ /** Keep constraints from the surrounding array when selecting a composition branch. */
708
+ const mergeSelectedSchema = (schema, variant, isArray) => {
709
+ const { oneOf: _oneOf, anyOf: _anyOf, ...base } = schema;
710
+ const merged = { ...base, ...variant };
711
+ // Object properties would otherwise take precedence in non-object schema dispatch.
712
+ if ('properties' in merged) {
713
+ delete merged.properties;
714
+ }
715
+ if (isArray) {
716
+ if ('minItems' in schema) {
717
+ Object.assign(merged, {
718
+ minItems: Math.max(readArrayLengthBound(schema.minItems, 0), readArrayLengthBound('minItems' in variant ? variant.minItems : undefined, 0)),
719
+ });
720
+ }
721
+ if ('maxItems' in schema) {
722
+ Object.assign(merged, {
723
+ maxItems: Math.min(readArrayLengthBound(schema.maxItems, Number.POSITIVE_INFINITY), readArrayLengthBound('maxItems' in variant ? variant.maxItems : undefined, Number.POSITIVE_INFINITY)),
724
+ });
725
+ }
726
+ if ('uniqueItems' in schema && schema.uniqueItems) {
727
+ Object.assign(merged, { uniqueItems: true });
728
+ }
729
+ }
730
+ return merged;
731
+ };
549
732
  /** Build an example for an array schema, including items, allOf, oneOf/anyOf, and XML wrapping */
550
733
  const handleArraySchema = (schema, options, level, seen, cacheKey, schemaPath, dynamicScope) => {
551
734
  const childScope = pushDynamicScope(dynamicScope, schema);
552
735
  const skipCache = dynamicScope.length > 0 || !!options?.[EXAMPLE_EVALUATION];
553
- if ('prefixItems' in schema && Array.isArray(schema.prefixItems)) {
554
- const values = schema.prefixItems.map((item, index) => getExampleFromSchema(item, options, {
555
- level: level + 1,
556
- schemaPath: [...schemaPath, 'prefixItems', String(index)],
557
- seen,
558
- dynamicScope: childScope,
559
- }));
736
+ const maxItems = readArrayLengthBound('maxItems' in schema ? schema.maxItems : undefined, Number.POSITIVE_INFINITY);
737
+ const minItems = Math.min(readArrayLengthBound('minItems' in schema ? schema.minItems : undefined, 0), maxItems, MAX_ARRAY_PADDING_NODES);
738
+ if (maxItems === 0) {
739
+ return cache(schema, [], cacheKey, skipCache);
740
+ }
741
+ const prefixes = 'prefixItems' in schema && Array.isArray(schema.prefixItems) ? schema.prefixItems : undefined;
742
+ const values = prefixes?.slice(0, maxItems).map((item, index) => getExampleFromSchema(item, options, {
743
+ level: level + 1,
744
+ schemaPath: [...schemaPath, 'prefixItems', String(index)],
745
+ seen,
746
+ dynamicScope: childScope,
747
+ })) ?? [];
748
+ if (prefixes && values.length >= minItems) {
749
+ return cache(schema, values, cacheKey, skipCache);
750
+ }
751
+ const itemSchema = 'items' in schema ? schema.items : undefined;
752
+ if (itemSchema === false) {
560
753
  return cache(schema, values, cacheKey, skipCache);
561
754
  }
562
- let items = 'items' in schema ? resolve.schema(schema.items) : undefined;
755
+ let items = resolve.schema(itemSchema);
563
756
  // Bind a dynamic item type (e.g. the generic `PaginatedResponse<T>` pattern) before inspecting it.
564
757
  // Crossing a `$dynamicRef` leaves the static schema graph, so the cycle guard built up by the outer
565
758
  // walk no longer applies to the bound type. Restart `seen` for the item recursion so recursive trees
@@ -579,6 +772,26 @@ const handleArraySchema = (schema, options, level, seen, cacheKey, schemaPath, d
579
772
  if (schema.example !== undefined) {
580
773
  return cache(schema, wrapItems ? { [itemsXmlTagName]: schema.example } : schema.example, cacheKey, skipCache);
581
774
  }
775
+ const completeArrayExample = (examples, sample = examples[0]) => {
776
+ for (const example of examples) {
777
+ if (values.length >= maxItems || (prefixes && values.length >= minItems)) {
778
+ break;
779
+ }
780
+ values.push(wrapItems ? { [itemsXmlTagName]: example } : example);
781
+ }
782
+ // Intentionally leave minItems unsatisfied for uniqueItems: repeating a sample violates
783
+ // uniqueness, and inventing distinct values can violate enum, bounds, or other constraints.
784
+ if (sample !== undefined && values.length < minItems && !('uniqueItems' in schema && schema.uniqueItems)) {
785
+ const value = wrapItems ? { [itemsXmlTagName]: sample } : sample;
786
+ const remaining = MAX_ARRAY_PADDING_NODES - countExampleNodes(values, MAX_ARRAY_PADDING_NODES);
787
+ const size = countExampleNodes(value, MAX_ARRAY_PADDING_NODES);
788
+ const copies = Math.min(minItems - values.length, Math.floor(remaining / size));
789
+ for (let index = 0; index < copies; index++) {
790
+ values.push(value);
791
+ }
792
+ }
793
+ return cache(schema, values, cacheKey, skipCache);
794
+ };
582
795
  if (items && typeof items === 'object') {
583
796
  if (Array.isArray(items.allOf) && items.allOf.length > 0) {
584
797
  const allOf = items.allOf.filter(isDefined);
@@ -592,7 +805,7 @@ const handleArraySchema = (schema, options, level, seen, cacheKey, schemaPath, d
592
805
  seen: itemsSeen,
593
806
  dynamicScope: childScope,
594
807
  });
595
- return cache(schema, wrapItems ? [{ [itemsXmlTagName]: merged }] : [merged], cacheKey, skipCache);
808
+ return completeArrayExample(isDefined(merged) ? [merged] : []);
596
809
  }
597
810
  const examples = allOf
598
811
  .map((s) => getExampleFromSchema(resolve.schema(s), options, {
@@ -603,7 +816,10 @@ const handleArraySchema = (schema, options, level, seen, cacheKey, schemaPath, d
603
816
  dynamicScope: childScope,
604
817
  }))
605
818
  .filter(isDefined);
606
- return cache(schema, wrapItems ? examples.map((e) => ({ [itemsXmlTagName]: e })) : examples, cacheKey, skipCache);
819
+ // Let generation resolve references, declarations and union selections before deciding whether
820
+ // the members describe one object. A primitive contribution keeps the existing per-member result.
821
+ const result = examples.length > 0 && examples.every(isObject) ? [examples.reduce(mergeExamples, {})] : examples;
822
+ return completeArrayExample(result);
607
823
  }
608
824
  const anyOfKeyword = items.anyOf ? 'anyOf' : undefined;
609
825
  const compositionKeyword = items.oneOf ? 'oneOf' : anyOfKeyword;
@@ -613,7 +829,15 @@ const handleArraySchema = (schema, options, level, seen, cacheKey, schemaPath, d
613
829
  getDiscriminatorSelectionIndex(items, union, options) ??
614
830
  0;
615
831
  const selected = union[selectedIndex];
616
- const ex = getExampleFromSchema(resolve.schema(selected), consumeCompositionSelection(options, itemsSchemaPath, compositionKeyword), {
832
+ const selectedTarget = getResolvedRef(selected);
833
+ const variant = resolve.schema(selected);
834
+ // Merging creates a new identity, so check the original branch before losing its cycle marker.
835
+ if ((selectedTarget && typeof selectedTarget === 'object' && itemsSeen.has(getSchemaCacheTarget(selectedTarget))) ||
836
+ (variant && itemsSeen.has(getSchemaCacheTarget(variant)))) {
837
+ return values.length > 0 || level === 0 ? cache(schema, values, cacheKey, skipCache) : undefined;
838
+ }
839
+ const selectedType = getSelectedType(variant, items);
840
+ const ex = getExampleFromSchema(variant && selectedType === 'array' ? mergeSelectedSchema(items, variant, true) : variant, consumeCompositionSelection(options, itemsSchemaPath, compositionKeyword), {
617
841
  level: level + 1,
618
842
  parentSchema: schema,
619
843
  schemaPath: itemsSchemaPath,
@@ -621,14 +845,18 @@ const handleArraySchema = (schema, options, level, seen, cacheKey, schemaPath, d
621
845
  dynamicScope: childScope,
622
846
  });
623
847
  if (ex === undefined) {
624
- return undefined;
848
+ return values.length > 0 ? cache(schema, values, cacheKey, skipCache) : undefined;
625
849
  }
626
- return cache(schema, wrapItems ? [{ [itemsXmlTagName]: ex }] : [ex], cacheKey, skipCache);
850
+ const tagged = withDiscriminatorTag(items, selected, ex, options, itemsSchemaPath);
851
+ return completeArrayExample([tagged]);
627
852
  }
628
853
  }
629
- const isObject = items && typeof items === 'object' && (('type' in items && items.type === 'object') || 'properties' in items);
630
- const isArray = items && typeof items === 'object' && (('type' in items && items.type === 'array') || 'items' in items);
631
- if (items && typeof items === 'object' && (('type' in items && items.type) || isObject || isArray)) {
854
+ const isObjectItems = items && typeof items === 'object' && (('type' in items && items.type === 'object') || 'properties' in items);
855
+ const isArray = items &&
856
+ typeof items === 'object' &&
857
+ (('type' in items && items.type === 'array') || 'items' in items || 'prefixItems' in items);
858
+ const hasDeclaredItem = values.length < minItems && items && getDeclaredValue(items) !== undefined;
859
+ if (items && (('type' in items && items.type) || isObjectItems || isArray || hasDeclaredItem)) {
632
860
  const ex = getExampleFromSchema(items, options, {
633
861
  level: level + 1,
634
862
  schemaPath: itemsSchemaPath,
@@ -637,11 +865,28 @@ const handleArraySchema = (schema, options, level, seen, cacheKey, schemaPath, d
637
865
  });
638
866
  // Propagate an omitted recursive item so optional arrays do not serialize it as null.
639
867
  if (ex === undefined) {
640
- return undefined;
868
+ return values.length > 0 ? cache(schema, values, cacheKey, skipCache) : undefined;
641
869
  }
642
- return cache(schema, wrapItems ? [{ [itemsXmlTagName]: ex }] : [ex], cacheKey, skipCache);
870
+ return completeArrayExample([ex]);
871
+ }
872
+ const target = getResolvedRef(itemSchema);
873
+ const unrestricted = itemSchema === undefined ||
874
+ target === true ||
875
+ (target !== undefined && items && Object.keys(items).every((key) => ITEM_ANNOTATIONS.has(key)));
876
+ // The strict model does not yet expose contains, but runtime 3.1+ descriptions can provide it.
877
+ const contains = 'contains' in schema && schema.contains && typeof schema.contains === 'object' && !Array.isArray(schema.contains)
878
+ ? resolve.schema(schema.contains)
879
+ : undefined;
880
+ if (unrestricted && contains) {
881
+ const sample = getExampleFromSchema(contains, options, {
882
+ level: level + 1,
883
+ schemaPath: [...schemaPath, 'contains'],
884
+ seen: itemsSeen,
885
+ dynamicScope: childScope,
886
+ });
887
+ return completeArrayExample(sample === undefined ? [] : [sample]);
643
888
  }
644
- return cache(schema, [], cacheKey, skipCache);
889
+ return completeArrayExample([], unrestricted ? null : undefined);
645
890
  };
646
891
  /** Return primitive example value for single-type schemas, or undefined if not primitive */
647
892
  const getPrimitiveValue = (schema, makeUpRandomData, emptyString) => {
@@ -725,6 +970,201 @@ const getOptionsCacheKey = (options, level) => {
725
970
  const MAX_DEPTH_EXCEEDED = '[Max Depth Exceeded]';
726
971
  /** How long a chain of composition wrappers may be unwrapped before the stack becomes the concern. */
727
972
  const MAX_COMPOSITION_DEPTH = MAX_LEVELS_DEEP * 5;
973
+ /**
974
+ * How deep the walk keeps going past `MAX_LEVELS_DEEP` to fill the properties a truncated object requires.
975
+ *
976
+ * Past the cap the walk still renders objects, but only their required properties, so a strict decoder
977
+ * reading the example finds every key it insists on. This level bounds that, well below the XML
978
+ * serializer's depth limit of 50 (which discards the whole body when crossed), and past it objects
979
+ * stand in empty again.
980
+ */
981
+ const MAX_REQUIRED_LEVELS_DEEP = MAX_LEVELS_DEEP * 2;
982
+ /**
983
+ * How many schemas the walk may enter past `MAX_LEVELS_DEEP` in one top-level call.
984
+ *
985
+ * Cycle guards stop a schema that requires itself, but not a chain of distinct schemas that each point
986
+ * at the next one twice, through two required properties or an `allOf` that lists the same member
987
+ * twice: the work doubles with every link. Once the budget is spent, objects stand in empty.
988
+ */
989
+ const MAX_REQUIRED_STEPS = 10_000;
990
+ /** Schemas the walk may still enter past `MAX_LEVELS_DEEP` in the current top-level call. */
991
+ let requiredSteps = MAX_REQUIRED_STEPS;
992
+ /** Cache requirements within one walk; generated discriminator values may select a new branch next time. */
993
+ let compositionRequiredNamesCache = new WeakMap();
994
+ /** Values are reused only within one call; generated dates and traversal contexts must not leak across calls. */
995
+ let discriminatorExamples = new WeakMap();
996
+ /** Evaluate the discriminator through the same path as any other property, before choosing its branch. */
997
+ const evaluateDiscriminator = (schema, options, context) => {
998
+ const { level, schemaPath, seen, dynamicScope, isRequiredProperty } = context;
999
+ const name = schema.discriminator?.propertyName;
1000
+ const property = name !== undefined && 'properties' in schema ? resolve.schema(schema.properties?.[name]) : undefined;
1001
+ if (name === undefined || !property) {
1002
+ return { value: undefined };
1003
+ }
1004
+ const target = getSchemaCacheTarget(schema);
1005
+ const key = JSON.stringify([schemaPath, createOptionsCacheKey(options), level, isRequiredProperty]);
1006
+ const cached = discriminatorExamples.get(target)?.get(key);
1007
+ if (cached && dynamicScope.length === 0) {
1008
+ return cached;
1009
+ }
1010
+ const capture = options?.[EXAMPLE_EVALUATION] ? { stack: [] } : undefined;
1011
+ // A composition member may not yet be on the main walk's path when collecting its requirements.
1012
+ const alreadySeen = seen.has(target);
1013
+ seen.add(target);
1014
+ try {
1015
+ const value = getExampleFromSchema(property, { ...options, [EXAMPLE_EVALUATION]: capture }, {
1016
+ level: level + 1,
1017
+ parentSchema: schema,
1018
+ name,
1019
+ schemaPath: [...schemaPath, name],
1020
+ seen,
1021
+ dynamicScope: pushDynamicScope(dynamicScope, schema),
1022
+ isRequiredProperty,
1023
+ });
1024
+ const example = { value, evaluation: capture?.root };
1025
+ if (dynamicScope.length === 0) {
1026
+ const entries = discriminatorExamples.get(target) ?? new Map();
1027
+ entries.set(key, example);
1028
+ discriminatorExamples.set(target, entries);
1029
+ }
1030
+ return example;
1031
+ }
1032
+ finally {
1033
+ if (!alreadySeen) {
1034
+ seen.delete(target);
1035
+ }
1036
+ }
1037
+ };
1038
+ /**
1039
+ * Gather requirements across allOf members and the selected alternatives only. A name required by an
1040
+ * unselected alternative may be optional in the chosen one, and emitting it can match both oneOf branches.
1041
+ */
1042
+ const getCompositionRequiredNames = (schema, options, schemaPath, level, seen, dynamicScope) => {
1043
+ const root = getSchemaCacheTarget(schema);
1044
+ const cacheKey = JSON.stringify([schemaPath, createOptionsCacheKey(options), level]);
1045
+ const cached = compositionRequiredNamesCache.get(root)?.get(cacheKey);
1046
+ if (cached && dynamicScope.length === 0) {
1047
+ return cached;
1048
+ }
1049
+ const names = new Set();
1050
+ const visited = new Map();
1051
+ const scopeResourceIds = new Map();
1052
+ const pending = [{ schema, options, schemaPath, dynamicScope, depth: 0 }];
1053
+ // A cycle can change its selection path, so identity and path caching alone cannot bound this walk.
1054
+ let steps = MAX_REQUIRED_STEPS;
1055
+ while (pending.length > 0 && steps-- > 0) {
1056
+ const current = pending.pop();
1057
+ const target = getSchemaCacheTarget(current.schema);
1058
+ // A shared template can require different fields under each binding. Include the ordered scope
1059
+ // identities so visiting it in one branch does not suppress another branch's requirements.
1060
+ const scopeKey = current.dynamicScope.map((resource) => {
1061
+ const identity = getSchemaCacheTarget(resource);
1062
+ const existing = scopeResourceIds.get(identity);
1063
+ if (existing !== undefined) {
1064
+ return existing;
1065
+ }
1066
+ const id = scopeResourceIds.size;
1067
+ scopeResourceIds.set(identity, id);
1068
+ return id;
1069
+ });
1070
+ const key = JSON.stringify([current.schemaPath, createOptionsCacheKey(current.options), current.depth, scopeKey]);
1071
+ const contexts = visited.get(target) ?? new Set();
1072
+ if (contexts.has(key) || current.depth > MAX_COMPOSITION_DEPTH) {
1073
+ continue;
1074
+ }
1075
+ contexts.add(key);
1076
+ visited.set(target, contexts);
1077
+ // Requirements behind a dynamic reference constrain the same instance as its composition siblings.
1078
+ // Follow the same binding as the example walk, within this collector's existing depth and step bounds.
1079
+ if (isDynamicRef(current.schema)) {
1080
+ const resolved = resolveDynamicRef(current.schema.$dynamicRef, current.dynamicScope);
1081
+ if (resolved) {
1082
+ pending.push({ ...current, schema: resolved, depth: current.depth + 1 });
1083
+ continue;
1084
+ }
1085
+ }
1086
+ // An omitted member cannot make a sibling's otherwise optional fields required for this example.
1087
+ if (shouldOmitProperty(current.schema, undefined, undefined, { mode: current.options?.mode })) {
1088
+ continue;
1089
+ }
1090
+ if ('required' in current.schema && Array.isArray(current.schema.required)) {
1091
+ for (const name of current.schema.required) {
1092
+ names.add(name);
1093
+ }
1094
+ }
1095
+ const keyword = current.schema.oneOf ? 'oneOf' : current.schema.anyOf ? 'anyOf' : undefined;
1096
+ if (keyword) {
1097
+ const discriminator = current.schema.discriminator;
1098
+ const requiredOnly = level + current.depth > MAX_LEVELS_DEEP;
1099
+ const omittedDiscriminator = requiredOnly &&
1100
+ discriminator?.defaultMapping !== undefined &&
1101
+ // The negative level gathers shared requirements without evaluating discriminator values.
1102
+ !getCompositionRequiredNames(schema, options, schemaPath, -MAX_COMPOSITION_DEPTH, seen, dynamicScope).has(discriminator.propertyName);
1103
+ // Evaluate once using the ordinary property walk. Rendering reuses both the value and its XML
1104
+ // provenance, so mode omissions, generated strings and composed tags cannot change branches.
1105
+ const evaluated = level >= 0 && discriminator?.defaultMapping !== undefined && !omittedDiscriminator
1106
+ ? evaluateDiscriminator(current.schema, current.options, {
1107
+ level: level + current.depth,
1108
+ schemaPath: current.schemaPath,
1109
+ seen,
1110
+ dynamicScope: current.dynamicScope,
1111
+ isRequiredProperty: requiredOnly,
1112
+ })
1113
+ : undefined;
1114
+ const property = discriminator && 'properties' in current.schema
1115
+ ? resolve.schema(current.schema.properties?.[discriminator.propertyName])
1116
+ : undefined;
1117
+ const propertyName = current.options?.xml && property && 'xml' in property
1118
+ ? (property.xml?.name ?? discriminator?.propertyName)
1119
+ : discriminator?.propertyName;
1120
+ const discriminatorValue = evaluated && propertyName !== undefined ? { [propertyName]: evaluated.value } : undefined;
1121
+ const selected = selectExampleComposition(current.schema, current.schemaPath, current.options, false, omittedDiscriminator ? {} : discriminatorValue);
1122
+ const resolved = selected ? resolve.schema(selected) : undefined;
1123
+ if (resolved) {
1124
+ pending.push({
1125
+ schema: resolved,
1126
+ options: consumeCompositionSelection(current.options, current.schemaPath, keyword),
1127
+ schemaPath: current.schemaPath,
1128
+ dynamicScope: pushDynamicScope(current.dynamicScope, current.schema),
1129
+ depth: current.depth + 1,
1130
+ });
1131
+ }
1132
+ continue;
1133
+ }
1134
+ let choiceIndex = 0;
1135
+ for (const member of current.schema.allOf ?? []) {
1136
+ const resolved = resolve.schema(member);
1137
+ if (resolved) {
1138
+ const isChoiceMember = Array.isArray(resolved.oneOf) || Array.isArray(resolved.anyOf);
1139
+ pending.push({
1140
+ schema: resolved,
1141
+ options: current.options,
1142
+ schemaPath: isChoiceMember ? [...current.schemaPath, String(choiceIndex++)] : current.schemaPath,
1143
+ dynamicScope: pushDynamicScope(current.dynamicScope, current.schema),
1144
+ depth: current.depth + 1,
1145
+ });
1146
+ }
1147
+ }
1148
+ }
1149
+ if (dynamicScope.length === 0) {
1150
+ const contexts = compositionRequiredNamesCache.get(root) ?? new Map();
1151
+ contexts.set(cacheKey, names);
1152
+ compositionRequiredNamesCache.set(root, contexts);
1153
+ }
1154
+ return names;
1155
+ };
1156
+ /**
1157
+ * Whether the walk keeps rendering a schema past `MAX_LEVELS_DEEP` to fill its required properties.
1158
+ *
1159
+ * Only an object or composition with a property marked `required` qualifies, either somewhere in its
1160
+ * own compositions or, for a composition member, in the object it belongs to (`requiredScope`):
1161
+ * anything else has nothing a decoder insists on, and keeps its usual stand-in. Arrays always stand in
1162
+ * empty, because their items are what the cap exists to stop descending into.
1163
+ */
1164
+ const fillsRequiredProperties = (schema, requiredScope, options, schemaPath, level, seen, dynamicScope) => !getDeclaredTypes(schema).includes('array') &&
1165
+ !Array.isArray(getEmptyContainer(schema)) &&
1166
+ ('properties' in schema || ('type' in schema && schema.type === 'object') || isComposed(schema)) &&
1167
+ (requiredScope ?? getCompositionRequiredNames(schema, options, schemaPath, level, seen, dynamicScope)).size > 0;
728
1168
  /** Read a schema's declared types as a list, so `type: 'object'` and `type: ['object']` behave alike. */
729
1169
  const getDeclaredTypes = (schema) => {
730
1170
  if (!('type' in schema) || !schema.type) {
@@ -738,7 +1178,7 @@ const getEmptyContainer = (schema) => {
738
1178
  if ('properties' in schema || types.includes('object')) {
739
1179
  return {};
740
1180
  }
741
- if ('items' in schema || types.includes('array')) {
1181
+ if ('items' in schema || 'prefixItems' in schema || types.includes('array')) {
742
1182
  return [];
743
1183
  }
744
1184
  return undefined;
@@ -793,10 +1233,10 @@ const getDeclaredValue = (schema) => {
793
1233
  * Describe a composed schema by the member the walk itself would have rendered.
794
1234
  * Returns `undefined` when no member describes a shape.
795
1235
  */
796
- const describeComposition = (schema, options, schemaPath, seen) => {
1236
+ const describeComposition = (schema, options, schemaPath, seen, emptySchemaValue) => {
797
1237
  const variant = getSelectedVariant(schema, options, schemaPath);
798
1238
  if (variant) {
799
- return getMaxDepthValue(variant, options, schemaPath, seen);
1239
+ return getMaxDepthValue(variant, options, schemaPath, seen, emptySchemaValue);
800
1240
  }
801
1241
  if (!Array.isArray(schema.allOf) || schema.allOf.length === 0) {
802
1242
  return undefined;
@@ -835,7 +1275,7 @@ const describeComposition = (schema, options, schemaPath, seen) => {
835
1275
  * The value is empty rather than complete: satisfying `required` or `minItems` means descending
836
1276
  * again, which is exactly what the cap exists to prevent.
837
1277
  */
838
- const getMaxDepthValue = (schema, options, schemaPath, seen = new Set()) => {
1278
+ const getMaxDepthValue = (schema, options, schemaPath, seen = new Set(), emptySchemaValue = MAX_DEPTH_EXCEEDED) => {
839
1279
  // A stated value beats any stand-in, and matches what a full render would have produced.
840
1280
  const declared = getDeclaredValue(schema);
841
1281
  if (declared !== undefined) {
@@ -860,9 +1300,11 @@ const getMaxDepthValue = (schema, options, schemaPath, seen = new Set()) => {
860
1300
  // inheritance chain may be. `seen` holds exactly the path, so its size bounds the stack against a
861
1301
  // pathological chain, the way `schemaAllowsValue` bounds its own recursion.
862
1302
  const target = getSchemaCacheTarget(schema);
863
- if (!seen.has(target) && seen.size < MAX_COMPOSITION_DEPTH) {
1303
+ // The step budget bounds a wrapper whose members repeat one another (`allOf: [next, next]`), which
1304
+ // the path guard alone lets double with every link.
1305
+ if (!seen.has(target) && seen.size < MAX_COMPOSITION_DEPTH && requiredSteps-- > 0) {
864
1306
  seen.add(target);
865
- const composed = describeComposition(schema, options, schemaPath, seen);
1307
+ const composed = describeComposition(schema, options, schemaPath, seen, emptySchemaValue);
866
1308
  seen.delete(target);
867
1309
  if (composed !== undefined) {
868
1310
  return composed;
@@ -886,7 +1328,7 @@ const getMaxDepthValue = (schema, options, schemaPath, seen = new Set()) => {
886
1328
  return null;
887
1329
  }
888
1330
  truncated = true;
889
- return MAX_DEPTH_EXCEEDED;
1331
+ return emptySchemaValue;
890
1332
  };
891
1333
  const hasUnencodedJsonContent = (schema) => {
892
1334
  if (!('contentSchema' in schema) || !isJsonMediaType(schema.contentMediaType))
@@ -910,11 +1352,14 @@ const hasUnencodedJsonContent = (schema) => {
910
1352
  * @param name - The name of the property being processed.
911
1353
  * @returns An example value for the given schema.
912
1354
  */
913
- const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, name, seen = new WeakSet(), schemaPath = [], dynamicScope = [], } = {}) => {
1355
+ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, name, seen = new WeakSet(), schemaPath = [], dynamicScope = [], requiredScope, isRequiredProperty = false, } = {}) => {
914
1356
  // Cache restrictions only apply to the current traversal, so every top-level call starts clean.
915
1357
  if (level === 0) {
916
1358
  truncated = false;
917
1359
  generatedCurrentTime = false;
1360
+ requiredSteps = MAX_REQUIRED_STEPS;
1361
+ compositionRequiredNamesCache = new WeakMap();
1362
+ discriminatorExamples = new WeakMap();
918
1363
  }
919
1364
  // Resolve any $ref references to get the actual schema
920
1365
  const _schema = resolve.schema(schema);
@@ -937,6 +1382,8 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
937
1382
  seen: new WeakSet(),
938
1383
  schemaPath,
939
1384
  dynamicScope,
1385
+ requiredScope,
1386
+ isRequiredProperty,
940
1387
  });
941
1388
  }
942
1389
  }
@@ -963,7 +1410,7 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
963
1410
  // Determine if we should generate realistic example data
964
1411
  const makeUpRandomData = !!options?.emptyString;
965
1412
  // Early exits for schemas that should not be included (readOnly, writeOnly, omitEmptyAndOptionalProperties)
966
- if (shouldOmitProperty(_schema, parentSchema, name, options)) {
1413
+ if (shouldOmitProperty(_schema, parentSchema, name, options, isRequiredProperty)) {
967
1414
  seen.delete(targetValue);
968
1415
  return undefined;
969
1416
  }
@@ -1007,33 +1454,46 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
1007
1454
  // Stop descending once the walk is too deep to keep going, which also breaks circular references.
1008
1455
  // Everything above still applied, so an explicit example, `const` or `enum` wins here as it would at
1009
1456
  // any other level; only the children are given up on.
1457
+ //
1458
+ // An object still renders its required properties for a while past the cap, through this same walk, so
1459
+ // every rule that applies at a shallower level (read/write omission, composition selection, variables,
1460
+ // binary files) applies to them too. Required primitive compositions use the same walk so their
1461
+ // members retain those rules as well; arrays and anything past the bounds still stand in.
1010
1462
  if (level > MAX_LEVELS_DEEP) {
1011
- seen.delete(targetValue);
1012
- // Deliberately not cached: the value holds only at this level, and the cache key carries none.
1013
- return getMaxDepthValue(_schema, options, schemaPath);
1463
+ if ((!(isRequiredProperty && getEmptyContainer(_schema) === undefined) &&
1464
+ !fillsRequiredProperties(_schema, requiredScope, options, schemaPath, level, seen, dynamicScope)) ||
1465
+ level > MAX_REQUIRED_LEVELS_DEEP ||
1466
+ requiredSteps <= 0) {
1467
+ seen.delete(targetValue);
1468
+ // Deliberately not cached: the value holds only at this level, and the cache key carries none.
1469
+ // Constraint-only composition members must not replace a sibling's required fields with the depth marker.
1470
+ const fallback = isRequiredProperty || requiredScope?.size ? null : MAX_DEPTH_EXCEEDED;
1471
+ return getMaxDepthValue(_schema, options, schemaPath, undefined, fallback);
1472
+ }
1473
+ requiredSteps--;
1474
+ // The rendered value omits optional properties, so it holds only at this level and must not be cached.
1475
+ truncated = true;
1014
1476
  }
1477
+ // A composition can start above the cap and cross it in a nested member. Keep the shared
1478
+ // requirements available throughout that descent, without filtering properties above the cap.
1479
+ const memberRequiredScope = requiredScope ??
1480
+ (isComposed(_schema)
1481
+ ? getCompositionRequiredNames(_schema, options, schemaPath, level, seen, dynamicScope)
1482
+ : undefined);
1015
1483
  // Resolve non-object unions before type dispatch so shared root keywords do not
1016
1484
  // hide the selected member. Use the same selection and discriminator rules as other unions.
1017
1485
  const selectedAnyOf = _schema.anyOf ? 'anyOf' : undefined;
1018
1486
  const selectedComposition = _schema.oneOf ? 'oneOf' : selectedAnyOf;
1019
1487
  const selectedVariant = getSelectedVariant(_schema, options, schemaPath);
1020
1488
  if (selectedComposition && selectedVariant) {
1021
- const rootType = 'type' in _schema ? _schema.type : undefined;
1022
- const variantType = 'type' in selectedVariant ? selectedVariant.type : undefined;
1023
- const selectedType = variantType ??
1024
- rootType ??
1025
- (hasUnencodedJsonContent(_schema)
1026
- ? 'string'
1027
- : 'items' in _schema && !('properties' in _schema)
1028
- ? 'array'
1029
- : undefined);
1489
+ const selectedType = getSelectedType(selectedVariant, _schema);
1030
1490
  if (selectedType !== undefined && selectedType !== 'object') {
1031
- const { oneOf: _oneOf, anyOf: _anyOf, ...base } = _schema;
1032
- const selectedSchema = { ...base, ...selectedVariant };
1033
- // These keywords only constrain their own types, but also drive our type inference.
1034
- if ('properties' in selectedSchema) {
1035
- delete selectedSchema.properties;
1491
+ if (seen.has(getSchemaCacheTarget(selectedVariant))) {
1492
+ seen.delete(targetValue);
1493
+ return undefined;
1036
1494
  }
1495
+ const selectedSchema = mergeSelectedSchema(_schema, selectedVariant, selectedType === 'array');
1496
+ // These keywords only constrain their own types, but also drive our type inference.
1037
1497
  if (selectedType !== 'array' && 'items' in selectedSchema) {
1038
1498
  delete selectedSchema.items;
1039
1499
  }
@@ -1044,6 +1504,7 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
1044
1504
  schemaPath,
1045
1505
  seen,
1046
1506
  dynamicScope: childScope,
1507
+ isRequiredProperty,
1047
1508
  });
1048
1509
  seen.delete(targetValue);
1049
1510
  return cache(_schema, result, cacheKey, skipCache);
@@ -1061,6 +1522,7 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
1061
1522
  schemaPath: [...schemaPath, 'contentSchema'],
1062
1523
  seen,
1063
1524
  dynamicScope: childScope,
1525
+ isRequiredProperty,
1064
1526
  });
1065
1527
  if (content !== undefined) {
1066
1528
  seen.delete(targetValue);
@@ -1070,7 +1532,7 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
1070
1532
  }
1071
1533
  // Handle object types - check for properties to identify objects
1072
1534
  if ('properties' in _schema || ('type' in _schema && _schema.type === 'object')) {
1073
- const result = handleObjectSchema(_schema, options, level, seen, cacheKey, schemaPath, dynamicScope);
1535
+ const result = handleObjectSchema(_schema, options, level, seen, cacheKey, schemaPath, dynamicScope, requiredScope);
1074
1536
  seen.delete(targetValue);
1075
1537
  return result;
1076
1538
  }
@@ -1096,12 +1558,14 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
1096
1558
  const resolved = resolve.schema(candidate);
1097
1559
  if (resolved) {
1098
1560
  seen.delete(targetValue);
1099
- return cache(_schema, getExampleFromSchema(resolved, consumeCompositionSelection(options, schemaPath, compositionKeyword), {
1561
+ return cache(_schema, withDiscriminatorTag(_schema, candidate, getExampleFromSchema(resolved, consumeCompositionSelection(options, schemaPath, compositionKeyword), {
1100
1562
  level: level + 1,
1101
1563
  schemaPath,
1102
1564
  seen,
1103
1565
  dynamicScope: childScope,
1104
- }), cacheKey, skipCache);
1566
+ requiredScope: memberRequiredScope,
1567
+ isRequiredProperty,
1568
+ }), options, schemaPath), cacheKey, skipCache);
1105
1569
  }
1106
1570
  }
1107
1571
  seen.delete(targetValue);
@@ -1122,6 +1586,8 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
1122
1586
  schemaPath: memberSchemaPath,
1123
1587
  seen,
1124
1588
  dynamicScope: childScope,
1589
+ requiredScope: memberRequiredScope,
1590
+ isRequiredProperty,
1125
1591
  });
1126
1592
  if (merged === undefined) {
1127
1593
  merged = ex;
@@ -1149,26 +1615,24 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
1149
1615
  return cache(_schema, null, cacheKey, skipCache);
1150
1616
  };
1151
1617
  /** Keep binary provenance for multipart callers without resolving schemas on the default data path. */
1152
- const asBinaryFile = (schema, value, enabled = false) => {
1153
- if (!enabled || typeof value !== 'string' || !value.startsWith('@')) {
1618
+ const asBinaryFile = (schema, value, options, schemaPath = []) => {
1619
+ if (!options?.binaryAsFile || typeof value !== 'string' || !value.startsWith('@')) {
1154
1620
  return value;
1155
1621
  }
1156
- const resolved = resolve.schema(schema);
1157
- if (resolved &&
1158
- 'type' in resolved &&
1159
- resolved.type === 'string' &&
1160
- 'format' in resolved &&
1161
- resolved.format === 'binary') {
1622
+ if (isFileSchema(resolveFormSchema(schema, options.compositionSelection, schemaPath) ?? schema)) {
1162
1623
  return new File([], value.slice(1), { lastModified: 0 });
1163
1624
  }
1164
1625
  return value;
1165
1626
  };
1166
- /** Generate data, optionally retaining the exact schema decisions for another output format. */
1627
+ /**
1628
+ * Generate data, optionally retaining the exact schema decisions for another output format.
1629
+ * Treat returned values as read-only: cached results and padded items can share object references.
1630
+ */
1167
1631
  export const getExampleFromSchema = (schema, options, context = {}) => {
1168
1632
  const capture = options?.[EXAMPLE_EVALUATION];
1169
1633
  if (!capture) {
1170
1634
  const value = generateExampleFromSchema(schema, options, context);
1171
- return asBinaryFile(schema, value, options?.binaryAsFile);
1635
+ return asBinaryFile(schema, value, options, context.schemaPath);
1172
1636
  }
1173
1637
  const node = {
1174
1638
  schema,
@@ -1187,7 +1651,7 @@ export const getExampleFromSchema = (schema, options, context = {}) => {
1187
1651
  }
1188
1652
  capture.stack.push(node);
1189
1653
  try {
1190
- node.value = asBinaryFile(schema, generateExampleFromSchema(schema, options, context), options?.binaryAsFile);
1654
+ node.value = asBinaryFile(schema, generateExampleFromSchema(schema, options, context), options, context.schemaPath);
1191
1655
  return node.value;
1192
1656
  }
1193
1657
  finally {