@scalar/workspace-store 0.70.0 → 0.71.1

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 +41 -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 +552 -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';
@@ -9,11 +14,20 @@ import { EXAMPLE_EVALUATION } from './example-evaluation.js';
9
14
  const MAX_LEVELS_DEEP = 10;
10
15
  /** Default name used for additional properties when no custom name is provided */
11
16
  const DEFAULT_ADDITIONAL_PROPERTIES_NAME = 'additionalProperty';
17
+ /**
18
+ * Base64 of the bytes "scalar". Six bytes encode without `=` padding and the output avoids `+`, `/`,
19
+ * `-` and `_`, so strict decoders accept it under both the standard and URL-safe alphabets (RFC 4648).
20
+ */
21
+ const BASE64_EXAMPLE = 'c2NhbGFy';
22
+ /** Content encodings whose example is the base64 placeholder (compared case-insensitively, as in RFC 2045). */
23
+ const BASE64_CONTENT_ENCODINGS = new Set(['base64', 'base64url']);
12
24
  /**
13
25
  * Mapping of OpenAPI string formats to example values.
14
26
  * Used to generate realistic examples for different string formats.
15
27
  */
16
28
  const genericExampleValues = {
29
+ // OpenAPI 3.0 base64 encoded characters. A plain placeholder like "string" is not valid base64.
30
+ 'byte': BASE64_EXAMPLE,
17
31
  'duration': 'P1D',
18
32
  'email': 'hello@example.com',
19
33
  'hostname': 'example.com',
@@ -67,9 +81,14 @@ const getPropertyNamesEnumValues = (schema) => {
67
81
  */
68
82
  const guessFromFormat = (schema, makeUpRandomData = false, fallback = '') => {
69
83
  // 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') {
84
+ if (isFileSchema(schema, false)) {
71
85
  return '@filename';
72
86
  }
87
+ // Encoded strings need a valid encoding even when a format also supplies a placeholder, such as password.
88
+ if (typeof schema.contentEncoding === 'string' &&
89
+ BASE64_CONTENT_ENCODINGS.has(schema.contentEncoding.toLowerCase())) {
90
+ return BASE64_EXAMPLE;
91
+ }
73
92
  if ('format' in schema && ['date', 'date-time', 'time'].includes(schema.format ?? '')) {
74
93
  // Do not persist enclosing objects or arrays with generated clock-dependent values.
75
94
  generatedCurrentTime = true;
@@ -166,12 +185,12 @@ const isComposed = (schema) => !!(schema.allOf || schema.oneOf || schema.anyOf);
166
185
  * Determine if a property should be omitted based on the options.
167
186
  * Properties are omitted if they are not required and the option is enabled.
168
187
  */
169
- const shouldOmitProperty = (schema, parentSchema, propertyName, options) => {
188
+ const shouldOmitProperty = (schema, parentSchema, propertyName, options, isRequiredProperty = false) => {
170
189
  // Early exits for schemas that should not be included (readOnly, writeOnly)
171
190
  if ((options?.mode === 'write' && schema.readOnly) || (options?.mode === 'read' && schema.writeOnly)) {
172
191
  return true;
173
192
  }
174
- if (options?.omitEmptyAndOptionalProperties !== true) {
193
+ if (isRequiredProperty || options?.omitEmptyAndOptionalProperties !== true) {
175
194
  return false;
176
195
  }
177
196
  // Never omit container types (objects/arrays) or composed schemas
@@ -392,6 +411,87 @@ const getDiscriminatorSelectionIndex = (schema, variants, options, value) => {
392
411
  const fallbackIndex = findTarget(discriminator.defaultMapping);
393
412
  return fallbackIndex >= 0 ? fallbackIndex : undefined;
394
413
  };
414
+ const COMPONENT_SCHEMA_PREFIX = '#/components/schemas/';
415
+ /**
416
+ * Find the discriminator value that selects `variant`: the explicit mapping key that targets it,
417
+ * or the component name, which is the implicit mapping.
418
+ */
419
+ const getDiscriminatorTag = (discriminator, variant) => {
420
+ if (!('$ref' in variant) || typeof variant.$ref !== 'string') {
421
+ return undefined;
422
+ }
423
+ const reference = variant.$ref;
424
+ const componentName = reference.startsWith(COMPONENT_SCHEMA_PREFIX)
425
+ ? unescapeJsonPointer(reference.slice(COMPONENT_SCHEMA_PREFIX.length))
426
+ : undefined;
427
+ const mapped = Object.entries(discriminator.mapping ?? {}).find(([, target]) => target === reference || target === componentName);
428
+ return mapped?.[0] ?? componentName;
429
+ };
430
+ /** Preserve authored or intentionally omitted values while following the same composition choices as generation. */
431
+ const hasPreservedDiscriminatorValue = (schema, propertyName, options, schemaPath, seen = new Set(), level = 0) => {
432
+ const resolved = schema && resolve.schema(schema);
433
+ if (!resolved || level > MAX_LEVELS_DEEP) {
434
+ return false;
435
+ }
436
+ if (propertyName === undefined && shouldOmitProperty(resolved, undefined, undefined, { mode: options?.mode })) {
437
+ return true;
438
+ }
439
+ const target = getSchemaCacheTarget(resolved);
440
+ if (seen.has(target)) {
441
+ return false;
442
+ }
443
+ const nextSeen = new Set(seen).add(target);
444
+ const variable = resolved['x-variable'];
445
+ const value = variable && options?.variables?.[variable] !== undefined ? options.variables[variable] : getDeclaredValue(resolved);
446
+ if (value !== undefined) {
447
+ return (propertyName === undefined || (value !== null && typeof value === 'object' && Object.hasOwn(value, propertyName)));
448
+ }
449
+ if (propertyName !== undefined && 'properties' in resolved) {
450
+ const property = resolved.properties?.[propertyName];
451
+ const resolvedProperty = property && resolve.schema(property);
452
+ if (resolvedProperty && shouldOmitProperty(resolvedProperty, resolved, propertyName, options)) {
453
+ return true;
454
+ }
455
+ if (hasPreservedDiscriminatorValue(property, undefined, options, [...schemaPath, propertyName], nextSeen, level + 1)) {
456
+ return true;
457
+ }
458
+ }
459
+ const anyOfKeyword = resolved.anyOf ? 'anyOf' : undefined;
460
+ const keyword = resolved.oneOf ? 'oneOf' : anyOfKeyword;
461
+ if (keyword) {
462
+ const selected = selectExampleComposition(resolved, schemaPath, options);
463
+ return hasPreservedDiscriminatorValue(selected, propertyName, consumeCompositionSelection(options, schemaPath, keyword), schemaPath, nextSeen, level + 1);
464
+ }
465
+ let choiceIndex = 0;
466
+ return (resolved.allOf?.some((member) => {
467
+ const resolvedMember = resolve.schema(member);
468
+ const isChoice = !!resolvedMember && !!(resolvedMember.oneOf || resolvedMember.anyOf);
469
+ const memberPath = isChoice ? [...schemaPath, String(choiceIndex++)] : schemaPath;
470
+ return hasPreservedDiscriminatorValue(member, propertyName, options, memberPath, nextSeen, level + 1);
471
+ }) ?? false);
472
+ };
473
+ /**
474
+ * Write the selected variant's discriminator value into the example. Without it the example
475
+ * carries an empty tag and a server cannot tell which variant it is. Declared values win, and a
476
+ * `defaultMapping` means the property may be omitted, so selection alone decides the variant there.
477
+ */
478
+ const withDiscriminatorTag = (schema, variant, example, options, schemaPath) => {
479
+ const discriminator = schema.discriminator;
480
+ if (!discriminator ||
481
+ discriminator.defaultMapping !== undefined ||
482
+ !variant ||
483
+ options?.xml ||
484
+ !example ||
485
+ typeof example !== 'object' ||
486
+ Array.isArray(example)) {
487
+ return example;
488
+ }
489
+ if (hasPreservedDiscriminatorValue(schema, discriminator.propertyName, options, schemaPath)) {
490
+ return example;
491
+ }
492
+ const tag = getDiscriminatorTag(discriminator, variant);
493
+ return tag === undefined ? example : { ...example, [discriminator.propertyName]: tag };
494
+ };
395
495
  /**
396
496
  * Read the numeric `x-order` extension value from a raw property entry, if present.
397
497
  * The entry may be a schema or a `$ref` object, so we check membership before reading.
@@ -426,11 +526,22 @@ const sortPropertyNamesByXOrder = (properties) => Object.keys(properties).sort((
426
526
  * Build an example for an object schema, including properties, patternProperties,
427
527
  * additionalProperties, and composition (allOf/oneOf/anyOf) merging.
428
528
  */
429
- const handleObjectSchema = (schema, options, level, seen, cacheKey, schemaPath, dynamicScope) => {
529
+ const handleObjectSchema = (schema, options, level, seen, cacheKey, schemaPath, dynamicScope, requiredScope) => {
430
530
  const response = {};
431
531
  // Children are evaluated with this schema added to the dynamic scope so nested `$dynamicRef`s bind here.
432
532
  const childScope = pushDynamicScope(dynamicScope, schema);
433
533
  const skipCache = dynamicScope.length > 0 || !!options?.[EXAMPLE_EVALUATION];
534
+ // Carry requirements through composition wrappers before they cross the cap. Property children
535
+ // start their own scope, since their required names belong to a different object.
536
+ const memberRequiredScope = requiredScope ??
537
+ (isComposed(schema)
538
+ ? getCompositionRequiredNames(schema, options, schemaPath, level, seen, dynamicScope)
539
+ : undefined);
540
+ // Past the cap only the properties the object requires are rendered: optional ones are what the cap
541
+ // exists to stop descending into. Composition members share the names of the object they belong to.
542
+ const required = level > MAX_LEVELS_DEEP
543
+ ? (memberRequiredScope ?? getCompositionRequiredNames(schema, options, schemaPath, level, seen, dynamicScope))
544
+ : undefined;
434
545
  if ('properties' in schema && schema.properties) {
435
546
  const properties = schema.properties;
436
547
  const propertyNames = sortPropertyNamesByXOrder(properties);
@@ -438,24 +549,39 @@ const handleObjectSchema = (schema, options, level, seen, cacheKey, schemaPath,
438
549
  for (let i = 0; i < limit; i++) {
439
550
  const propertyName = propertyNames[i];
440
551
  const propertySchema = resolve.schema(properties[propertyName]);
441
- if (!propertySchema) {
552
+ if (!propertySchema || (required && !required.has(propertyName))) {
442
553
  continue;
443
554
  }
444
555
  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
- });
556
+ const discriminatorExample = schema.discriminator?.defaultMapping !== undefined && schema.discriminator.propertyName === propertyName
557
+ ? evaluateDiscriminator(schema, options, {
558
+ level,
559
+ schemaPath,
560
+ seen,
561
+ dynamicScope,
562
+ isRequiredProperty: !!required,
563
+ })
564
+ : undefined;
565
+ if (discriminatorExample?.evaluation) {
566
+ options?.[EXAMPLE_EVALUATION]?.stack.at(-1)?.children.push(discriminatorExample.evaluation);
567
+ }
568
+ const value = discriminatorExample
569
+ ? discriminatorExample.value
570
+ : getExampleFromSchema(propertySchema, options, {
571
+ level: level + 1,
572
+ parentSchema: schema,
573
+ name: propertyName,
574
+ isRequiredProperty: !!required,
575
+ schemaPath: [...schemaPath, propertyName],
576
+ seen,
577
+ dynamicScope: childScope,
578
+ });
453
579
  if (typeof value !== 'undefined') {
454
580
  response[propertyXmlName ?? propertyName] = value;
455
581
  }
456
582
  }
457
583
  }
458
- if ('patternProperties' in schema && schema.patternProperties) {
584
+ if (!required && 'patternProperties' in schema && schema.patternProperties) {
459
585
  for (const pattern of Object.keys(schema.patternProperties)) {
460
586
  const propertySchema = resolve.schema(schema.patternProperties[pattern]);
461
587
  if (!propertySchema) {
@@ -471,7 +597,7 @@ const handleObjectSchema = (schema, options, level, seen, cacheKey, schemaPath,
471
597
  });
472
598
  }
473
599
  }
474
- if ('additionalProperties' in schema && schema.additionalProperties) {
600
+ if (!required && 'additionalProperties' in schema && schema.additionalProperties) {
475
601
  const additional = typeof schema.additionalProperties === 'boolean'
476
602
  ? schema.additionalProperties
477
603
  : resolve.schema(schema.additionalProperties);
@@ -512,7 +638,9 @@ const handleObjectSchema = (schema, options, level, seen, cacheKey, schemaPath,
512
638
  schemaPath,
513
639
  seen,
514
640
  dynamicScope: childScope,
641
+ requiredScope: memberRequiredScope,
515
642
  }));
643
+ Object.assign(response, withDiscriminatorTag(schema, chosen, response, options, schemaPath));
516
644
  }
517
645
  }
518
646
  // allOf — thread a choice-ordinal into schemaPath for each direct oneOf/anyOf
@@ -532,6 +660,7 @@ const handleObjectSchema = (schema, options, level, seen, cacheKey, schemaPath,
532
660
  seen,
533
661
  dynamicScope: childScope,
534
662
  schemaPath: memberSchemaPath,
663
+ requiredScope: memberRequiredScope,
535
664
  });
536
665
  merged = mergeExamples(merged, ex);
537
666
  }
@@ -546,20 +675,98 @@ const handleObjectSchema = (schema, options, level, seen, cacheKey, schemaPath,
546
675
  }
547
676
  return cache(schema, response, cacheKey, skipCache);
548
677
  };
678
+ /** Bound padding per array, counting repeated values by their serialized size; not a global output limit. */
679
+ const MAX_ARRAY_PADDING_NODES = 1_000;
680
+ const countExampleNodes = (value, limit) => {
681
+ if (limit <= 1 || value === null || typeof value !== 'object') {
682
+ return 1;
683
+ }
684
+ let count = 1;
685
+ for (const child of Array.isArray(value) ? value : Object.values(value)) {
686
+ count += countExampleNodes(child, limit - count);
687
+ if (count >= limit) {
688
+ break;
689
+ }
690
+ }
691
+ return count;
692
+ };
693
+ /** Ignore malformed bounds from unvalidated descriptions. */
694
+ const readArrayLengthBound = (value, fallback) => typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : fallback;
695
+ /** Recognize an array described by its item keywords when no type was declared. */
696
+ const inferArrayType = (schema) => !('properties' in schema) && ('items' in schema || 'prefixItems' in schema) ? 'array' : undefined;
697
+ /** Apply the same explicit-type and inference precedence at either union selection site. */
698
+ const getSelectedType = (variant, holder) => (variant && 'type' in variant ? variant.type : undefined) ??
699
+ ('type' in holder ? holder.type : undefined) ??
700
+ (hasUnencodedJsonContent(holder) ? 'string' : ((variant && inferArrayType(variant)) ?? inferArrayType(holder)));
701
+ /** These keywords describe values without restricting which values the schema accepts. */
702
+ const ITEM_ANNOTATIONS = new Set([
703
+ '$ref',
704
+ '$id',
705
+ '$schema',
706
+ '$anchor',
707
+ '$comment',
708
+ '$defs',
709
+ 'definitions',
710
+ 'title',
711
+ 'description',
712
+ 'deprecated',
713
+ 'readOnly',
714
+ 'writeOnly',
715
+ 'examples',
716
+ 'default',
717
+ 'example',
718
+ 'xml',
719
+ 'externalDocs',
720
+ ]);
721
+ /** Keep constraints from the surrounding array when selecting a composition branch. */
722
+ const mergeSelectedSchema = (schema, variant, isArray) => {
723
+ const { oneOf: _oneOf, anyOf: _anyOf, ...base } = schema;
724
+ const merged = { ...base, ...variant };
725
+ // Object properties would otherwise take precedence in non-object schema dispatch.
726
+ if ('properties' in merged) {
727
+ delete merged.properties;
728
+ }
729
+ if (isArray) {
730
+ if ('minItems' in schema) {
731
+ Object.assign(merged, {
732
+ minItems: Math.max(readArrayLengthBound(schema.minItems, 0), readArrayLengthBound('minItems' in variant ? variant.minItems : undefined, 0)),
733
+ });
734
+ }
735
+ if ('maxItems' in schema) {
736
+ Object.assign(merged, {
737
+ maxItems: Math.min(readArrayLengthBound(schema.maxItems, Number.POSITIVE_INFINITY), readArrayLengthBound('maxItems' in variant ? variant.maxItems : undefined, Number.POSITIVE_INFINITY)),
738
+ });
739
+ }
740
+ if ('uniqueItems' in schema && schema.uniqueItems) {
741
+ Object.assign(merged, { uniqueItems: true });
742
+ }
743
+ }
744
+ return merged;
745
+ };
549
746
  /** Build an example for an array schema, including items, allOf, oneOf/anyOf, and XML wrapping */
550
747
  const handleArraySchema = (schema, options, level, seen, cacheKey, schemaPath, dynamicScope) => {
551
748
  const childScope = pushDynamicScope(dynamicScope, schema);
552
749
  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
- }));
750
+ const maxItems = readArrayLengthBound('maxItems' in schema ? schema.maxItems : undefined, Number.POSITIVE_INFINITY);
751
+ const minItems = Math.min(readArrayLengthBound('minItems' in schema ? schema.minItems : undefined, 0), maxItems, MAX_ARRAY_PADDING_NODES);
752
+ if (maxItems === 0) {
753
+ return cache(schema, [], cacheKey, skipCache);
754
+ }
755
+ const prefixes = 'prefixItems' in schema && Array.isArray(schema.prefixItems) ? schema.prefixItems : undefined;
756
+ const values = prefixes?.slice(0, maxItems).map((item, index) => getExampleFromSchema(item, options, {
757
+ level: level + 1,
758
+ schemaPath: [...schemaPath, 'prefixItems', String(index)],
759
+ seen,
760
+ dynamicScope: childScope,
761
+ })) ?? [];
762
+ if (prefixes && values.length >= minItems) {
763
+ return cache(schema, values, cacheKey, skipCache);
764
+ }
765
+ const itemSchema = 'items' in schema ? schema.items : undefined;
766
+ if (itemSchema === false) {
560
767
  return cache(schema, values, cacheKey, skipCache);
561
768
  }
562
- let items = 'items' in schema ? resolve.schema(schema.items) : undefined;
769
+ let items = resolve.schema(itemSchema);
563
770
  // Bind a dynamic item type (e.g. the generic `PaginatedResponse<T>` pattern) before inspecting it.
564
771
  // Crossing a `$dynamicRef` leaves the static schema graph, so the cycle guard built up by the outer
565
772
  // walk no longer applies to the bound type. Restart `seen` for the item recursion so recursive trees
@@ -579,6 +786,26 @@ const handleArraySchema = (schema, options, level, seen, cacheKey, schemaPath, d
579
786
  if (schema.example !== undefined) {
580
787
  return cache(schema, wrapItems ? { [itemsXmlTagName]: schema.example } : schema.example, cacheKey, skipCache);
581
788
  }
789
+ const completeArrayExample = (examples, sample = examples[0]) => {
790
+ for (const example of examples) {
791
+ if (values.length >= maxItems || (prefixes && values.length >= minItems)) {
792
+ break;
793
+ }
794
+ values.push(wrapItems ? { [itemsXmlTagName]: example } : example);
795
+ }
796
+ // Intentionally leave minItems unsatisfied for uniqueItems: repeating a sample violates
797
+ // uniqueness, and inventing distinct values can violate enum, bounds, or other constraints.
798
+ if (sample !== undefined && values.length < minItems && !('uniqueItems' in schema && schema.uniqueItems)) {
799
+ const value = wrapItems ? { [itemsXmlTagName]: sample } : sample;
800
+ const remaining = MAX_ARRAY_PADDING_NODES - countExampleNodes(values, MAX_ARRAY_PADDING_NODES);
801
+ const size = countExampleNodes(value, MAX_ARRAY_PADDING_NODES);
802
+ const copies = Math.min(minItems - values.length, Math.floor(remaining / size));
803
+ for (let index = 0; index < copies; index++) {
804
+ values.push(value);
805
+ }
806
+ }
807
+ return cache(schema, values, cacheKey, skipCache);
808
+ };
582
809
  if (items && typeof items === 'object') {
583
810
  if (Array.isArray(items.allOf) && items.allOf.length > 0) {
584
811
  const allOf = items.allOf.filter(isDefined);
@@ -592,7 +819,7 @@ const handleArraySchema = (schema, options, level, seen, cacheKey, schemaPath, d
592
819
  seen: itemsSeen,
593
820
  dynamicScope: childScope,
594
821
  });
595
- return cache(schema, wrapItems ? [{ [itemsXmlTagName]: merged }] : [merged], cacheKey, skipCache);
822
+ return completeArrayExample(isDefined(merged) ? [merged] : []);
596
823
  }
597
824
  const examples = allOf
598
825
  .map((s) => getExampleFromSchema(resolve.schema(s), options, {
@@ -603,7 +830,10 @@ const handleArraySchema = (schema, options, level, seen, cacheKey, schemaPath, d
603
830
  dynamicScope: childScope,
604
831
  }))
605
832
  .filter(isDefined);
606
- return cache(schema, wrapItems ? examples.map((e) => ({ [itemsXmlTagName]: e })) : examples, cacheKey, skipCache);
833
+ // Let generation resolve references, declarations and union selections before deciding whether
834
+ // the members describe one object. A primitive contribution keeps the existing per-member result.
835
+ const result = examples.length > 0 && examples.every(isObject) ? [examples.reduce(mergeExamples, {})] : examples;
836
+ return completeArrayExample(result);
607
837
  }
608
838
  const anyOfKeyword = items.anyOf ? 'anyOf' : undefined;
609
839
  const compositionKeyword = items.oneOf ? 'oneOf' : anyOfKeyword;
@@ -613,7 +843,15 @@ const handleArraySchema = (schema, options, level, seen, cacheKey, schemaPath, d
613
843
  getDiscriminatorSelectionIndex(items, union, options) ??
614
844
  0;
615
845
  const selected = union[selectedIndex];
616
- const ex = getExampleFromSchema(resolve.schema(selected), consumeCompositionSelection(options, itemsSchemaPath, compositionKeyword), {
846
+ const selectedTarget = getResolvedRef(selected);
847
+ const variant = resolve.schema(selected);
848
+ // Merging creates a new identity, so check the original branch before losing its cycle marker.
849
+ if ((selectedTarget && typeof selectedTarget === 'object' && itemsSeen.has(getSchemaCacheTarget(selectedTarget))) ||
850
+ (variant && itemsSeen.has(getSchemaCacheTarget(variant)))) {
851
+ return values.length > 0 || level === 0 ? cache(schema, values, cacheKey, skipCache) : undefined;
852
+ }
853
+ const selectedType = getSelectedType(variant, items);
854
+ const ex = getExampleFromSchema(variant && selectedType === 'array' ? mergeSelectedSchema(items, variant, true) : variant, consumeCompositionSelection(options, itemsSchemaPath, compositionKeyword), {
617
855
  level: level + 1,
618
856
  parentSchema: schema,
619
857
  schemaPath: itemsSchemaPath,
@@ -621,14 +859,18 @@ const handleArraySchema = (schema, options, level, seen, cacheKey, schemaPath, d
621
859
  dynamicScope: childScope,
622
860
  });
623
861
  if (ex === undefined) {
624
- return undefined;
862
+ return values.length > 0 ? cache(schema, values, cacheKey, skipCache) : undefined;
625
863
  }
626
- return cache(schema, wrapItems ? [{ [itemsXmlTagName]: ex }] : [ex], cacheKey, skipCache);
864
+ const tagged = withDiscriminatorTag(items, selected, ex, options, itemsSchemaPath);
865
+ return completeArrayExample([tagged]);
627
866
  }
628
867
  }
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)) {
868
+ const isObjectItems = items && typeof items === 'object' && (('type' in items && items.type === 'object') || 'properties' in items);
869
+ const isArray = items &&
870
+ typeof items === 'object' &&
871
+ (('type' in items && items.type === 'array') || 'items' in items || 'prefixItems' in items);
872
+ const hasDeclaredItem = values.length < minItems && items && getDeclaredValue(items) !== undefined;
873
+ if (items && (('type' in items && items.type) || isObjectItems || isArray || hasDeclaredItem)) {
632
874
  const ex = getExampleFromSchema(items, options, {
633
875
  level: level + 1,
634
876
  schemaPath: itemsSchemaPath,
@@ -637,11 +879,28 @@ const handleArraySchema = (schema, options, level, seen, cacheKey, schemaPath, d
637
879
  });
638
880
  // Propagate an omitted recursive item so optional arrays do not serialize it as null.
639
881
  if (ex === undefined) {
640
- return undefined;
882
+ return values.length > 0 ? cache(schema, values, cacheKey, skipCache) : undefined;
641
883
  }
642
- return cache(schema, wrapItems ? [{ [itemsXmlTagName]: ex }] : [ex], cacheKey, skipCache);
884
+ return completeArrayExample([ex]);
885
+ }
886
+ const target = getResolvedRef(itemSchema);
887
+ const unrestricted = itemSchema === undefined ||
888
+ target === true ||
889
+ (target !== undefined && items && Object.keys(items).every((key) => ITEM_ANNOTATIONS.has(key)));
890
+ // The strict model does not yet expose contains, but runtime 3.1+ descriptions can provide it.
891
+ const contains = 'contains' in schema && schema.contains && typeof schema.contains === 'object' && !Array.isArray(schema.contains)
892
+ ? resolve.schema(schema.contains)
893
+ : undefined;
894
+ if (unrestricted && contains) {
895
+ const sample = getExampleFromSchema(contains, options, {
896
+ level: level + 1,
897
+ schemaPath: [...schemaPath, 'contains'],
898
+ seen: itemsSeen,
899
+ dynamicScope: childScope,
900
+ });
901
+ return completeArrayExample(sample === undefined ? [] : [sample]);
643
902
  }
644
- return cache(schema, [], cacheKey, skipCache);
903
+ return completeArrayExample([], unrestricted ? null : undefined);
645
904
  };
646
905
  /** Return primitive example value for single-type schemas, or undefined if not primitive */
647
906
  const getPrimitiveValue = (schema, makeUpRandomData, emptyString) => {
@@ -725,6 +984,201 @@ const getOptionsCacheKey = (options, level) => {
725
984
  const MAX_DEPTH_EXCEEDED = '[Max Depth Exceeded]';
726
985
  /** How long a chain of composition wrappers may be unwrapped before the stack becomes the concern. */
727
986
  const MAX_COMPOSITION_DEPTH = MAX_LEVELS_DEEP * 5;
987
+ /**
988
+ * How deep the walk keeps going past `MAX_LEVELS_DEEP` to fill the properties a truncated object requires.
989
+ *
990
+ * Past the cap the walk still renders objects, but only their required properties, so a strict decoder
991
+ * reading the example finds every key it insists on. This level bounds that, well below the XML
992
+ * serializer's depth limit of 50 (which discards the whole body when crossed), and past it objects
993
+ * stand in empty again.
994
+ */
995
+ const MAX_REQUIRED_LEVELS_DEEP = MAX_LEVELS_DEEP * 2;
996
+ /**
997
+ * How many schemas the walk may enter past `MAX_LEVELS_DEEP` in one top-level call.
998
+ *
999
+ * Cycle guards stop a schema that requires itself, but not a chain of distinct schemas that each point
1000
+ * at the next one twice, through two required properties or an `allOf` that lists the same member
1001
+ * twice: the work doubles with every link. Once the budget is spent, objects stand in empty.
1002
+ */
1003
+ const MAX_REQUIRED_STEPS = 10_000;
1004
+ /** Schemas the walk may still enter past `MAX_LEVELS_DEEP` in the current top-level call. */
1005
+ let requiredSteps = MAX_REQUIRED_STEPS;
1006
+ /** Cache requirements within one walk; generated discriminator values may select a new branch next time. */
1007
+ let compositionRequiredNamesCache = new WeakMap();
1008
+ /** Values are reused only within one call; generated dates and traversal contexts must not leak across calls. */
1009
+ let discriminatorExamples = new WeakMap();
1010
+ /** Evaluate the discriminator through the same path as any other property, before choosing its branch. */
1011
+ const evaluateDiscriminator = (schema, options, context) => {
1012
+ const { level, schemaPath, seen, dynamicScope, isRequiredProperty } = context;
1013
+ const name = schema.discriminator?.propertyName;
1014
+ const property = name !== undefined && 'properties' in schema ? resolve.schema(schema.properties?.[name]) : undefined;
1015
+ if (name === undefined || !property) {
1016
+ return { value: undefined };
1017
+ }
1018
+ const target = getSchemaCacheTarget(schema);
1019
+ const key = JSON.stringify([schemaPath, createOptionsCacheKey(options), level, isRequiredProperty]);
1020
+ const cached = discriminatorExamples.get(target)?.get(key);
1021
+ if (cached && dynamicScope.length === 0) {
1022
+ return cached;
1023
+ }
1024
+ const capture = options?.[EXAMPLE_EVALUATION] ? { stack: [] } : undefined;
1025
+ // A composition member may not yet be on the main walk's path when collecting its requirements.
1026
+ const alreadySeen = seen.has(target);
1027
+ seen.add(target);
1028
+ try {
1029
+ const value = getExampleFromSchema(property, { ...options, [EXAMPLE_EVALUATION]: capture }, {
1030
+ level: level + 1,
1031
+ parentSchema: schema,
1032
+ name,
1033
+ schemaPath: [...schemaPath, name],
1034
+ seen,
1035
+ dynamicScope: pushDynamicScope(dynamicScope, schema),
1036
+ isRequiredProperty,
1037
+ });
1038
+ const example = { value, evaluation: capture?.root };
1039
+ if (dynamicScope.length === 0) {
1040
+ const entries = discriminatorExamples.get(target) ?? new Map();
1041
+ entries.set(key, example);
1042
+ discriminatorExamples.set(target, entries);
1043
+ }
1044
+ return example;
1045
+ }
1046
+ finally {
1047
+ if (!alreadySeen) {
1048
+ seen.delete(target);
1049
+ }
1050
+ }
1051
+ };
1052
+ /**
1053
+ * Gather requirements across allOf members and the selected alternatives only. A name required by an
1054
+ * unselected alternative may be optional in the chosen one, and emitting it can match both oneOf branches.
1055
+ */
1056
+ const getCompositionRequiredNames = (schema, options, schemaPath, level, seen, dynamicScope) => {
1057
+ const root = getSchemaCacheTarget(schema);
1058
+ const cacheKey = JSON.stringify([schemaPath, createOptionsCacheKey(options), level]);
1059
+ const cached = compositionRequiredNamesCache.get(root)?.get(cacheKey);
1060
+ if (cached && dynamicScope.length === 0) {
1061
+ return cached;
1062
+ }
1063
+ const names = new Set();
1064
+ const visited = new Map();
1065
+ const scopeResourceIds = new Map();
1066
+ const pending = [{ schema, options, schemaPath, dynamicScope, depth: 0 }];
1067
+ // A cycle can change its selection path, so identity and path caching alone cannot bound this walk.
1068
+ let steps = MAX_REQUIRED_STEPS;
1069
+ while (pending.length > 0 && steps-- > 0) {
1070
+ const current = pending.pop();
1071
+ const target = getSchemaCacheTarget(current.schema);
1072
+ // A shared template can require different fields under each binding. Include the ordered scope
1073
+ // identities so visiting it in one branch does not suppress another branch's requirements.
1074
+ const scopeKey = current.dynamicScope.map((resource) => {
1075
+ const identity = getSchemaCacheTarget(resource);
1076
+ const existing = scopeResourceIds.get(identity);
1077
+ if (existing !== undefined) {
1078
+ return existing;
1079
+ }
1080
+ const id = scopeResourceIds.size;
1081
+ scopeResourceIds.set(identity, id);
1082
+ return id;
1083
+ });
1084
+ const key = JSON.stringify([current.schemaPath, createOptionsCacheKey(current.options), current.depth, scopeKey]);
1085
+ const contexts = visited.get(target) ?? new Set();
1086
+ if (contexts.has(key) || current.depth > MAX_COMPOSITION_DEPTH) {
1087
+ continue;
1088
+ }
1089
+ contexts.add(key);
1090
+ visited.set(target, contexts);
1091
+ // Requirements behind a dynamic reference constrain the same instance as its composition siblings.
1092
+ // Follow the same binding as the example walk, within this collector's existing depth and step bounds.
1093
+ if (isDynamicRef(current.schema)) {
1094
+ const resolved = resolveDynamicRef(current.schema.$dynamicRef, current.dynamicScope);
1095
+ if (resolved) {
1096
+ pending.push({ ...current, schema: resolved, depth: current.depth + 1 });
1097
+ continue;
1098
+ }
1099
+ }
1100
+ // An omitted member cannot make a sibling's otherwise optional fields required for this example.
1101
+ if (shouldOmitProperty(current.schema, undefined, undefined, { mode: current.options?.mode })) {
1102
+ continue;
1103
+ }
1104
+ if ('required' in current.schema && Array.isArray(current.schema.required)) {
1105
+ for (const name of current.schema.required) {
1106
+ names.add(name);
1107
+ }
1108
+ }
1109
+ const keyword = current.schema.oneOf ? 'oneOf' : current.schema.anyOf ? 'anyOf' : undefined;
1110
+ if (keyword) {
1111
+ const discriminator = current.schema.discriminator;
1112
+ const requiredOnly = level + current.depth > MAX_LEVELS_DEEP;
1113
+ const omittedDiscriminator = requiredOnly &&
1114
+ discriminator?.defaultMapping !== undefined &&
1115
+ // The negative level gathers shared requirements without evaluating discriminator values.
1116
+ !getCompositionRequiredNames(schema, options, schemaPath, -MAX_COMPOSITION_DEPTH, seen, dynamicScope).has(discriminator.propertyName);
1117
+ // Evaluate once using the ordinary property walk. Rendering reuses both the value and its XML
1118
+ // provenance, so mode omissions, generated strings and composed tags cannot change branches.
1119
+ const evaluated = level >= 0 && discriminator?.defaultMapping !== undefined && !omittedDiscriminator
1120
+ ? evaluateDiscriminator(current.schema, current.options, {
1121
+ level: level + current.depth,
1122
+ schemaPath: current.schemaPath,
1123
+ seen,
1124
+ dynamicScope: current.dynamicScope,
1125
+ isRequiredProperty: requiredOnly,
1126
+ })
1127
+ : undefined;
1128
+ const property = discriminator && 'properties' in current.schema
1129
+ ? resolve.schema(current.schema.properties?.[discriminator.propertyName])
1130
+ : undefined;
1131
+ const propertyName = current.options?.xml && property && 'xml' in property
1132
+ ? (property.xml?.name ?? discriminator?.propertyName)
1133
+ : discriminator?.propertyName;
1134
+ const discriminatorValue = evaluated && propertyName !== undefined ? { [propertyName]: evaluated.value } : undefined;
1135
+ const selected = selectExampleComposition(current.schema, current.schemaPath, current.options, false, omittedDiscriminator ? {} : discriminatorValue);
1136
+ const resolved = selected ? resolve.schema(selected) : undefined;
1137
+ if (resolved) {
1138
+ pending.push({
1139
+ schema: resolved,
1140
+ options: consumeCompositionSelection(current.options, current.schemaPath, keyword),
1141
+ schemaPath: current.schemaPath,
1142
+ dynamicScope: pushDynamicScope(current.dynamicScope, current.schema),
1143
+ depth: current.depth + 1,
1144
+ });
1145
+ }
1146
+ continue;
1147
+ }
1148
+ let choiceIndex = 0;
1149
+ for (const member of current.schema.allOf ?? []) {
1150
+ const resolved = resolve.schema(member);
1151
+ if (resolved) {
1152
+ const isChoiceMember = Array.isArray(resolved.oneOf) || Array.isArray(resolved.anyOf);
1153
+ pending.push({
1154
+ schema: resolved,
1155
+ options: current.options,
1156
+ schemaPath: isChoiceMember ? [...current.schemaPath, String(choiceIndex++)] : current.schemaPath,
1157
+ dynamicScope: pushDynamicScope(current.dynamicScope, current.schema),
1158
+ depth: current.depth + 1,
1159
+ });
1160
+ }
1161
+ }
1162
+ }
1163
+ if (dynamicScope.length === 0) {
1164
+ const contexts = compositionRequiredNamesCache.get(root) ?? new Map();
1165
+ contexts.set(cacheKey, names);
1166
+ compositionRequiredNamesCache.set(root, contexts);
1167
+ }
1168
+ return names;
1169
+ };
1170
+ /**
1171
+ * Whether the walk keeps rendering a schema past `MAX_LEVELS_DEEP` to fill its required properties.
1172
+ *
1173
+ * Only an object or composition with a property marked `required` qualifies, either somewhere in its
1174
+ * own compositions or, for a composition member, in the object it belongs to (`requiredScope`):
1175
+ * anything else has nothing a decoder insists on, and keeps its usual stand-in. Arrays always stand in
1176
+ * empty, because their items are what the cap exists to stop descending into.
1177
+ */
1178
+ const fillsRequiredProperties = (schema, requiredScope, options, schemaPath, level, seen, dynamicScope) => !getDeclaredTypes(schema).includes('array') &&
1179
+ !Array.isArray(getEmptyContainer(schema)) &&
1180
+ ('properties' in schema || ('type' in schema && schema.type === 'object') || isComposed(schema)) &&
1181
+ (requiredScope ?? getCompositionRequiredNames(schema, options, schemaPath, level, seen, dynamicScope)).size > 0;
728
1182
  /** Read a schema's declared types as a list, so `type: 'object'` and `type: ['object']` behave alike. */
729
1183
  const getDeclaredTypes = (schema) => {
730
1184
  if (!('type' in schema) || !schema.type) {
@@ -738,7 +1192,7 @@ const getEmptyContainer = (schema) => {
738
1192
  if ('properties' in schema || types.includes('object')) {
739
1193
  return {};
740
1194
  }
741
- if ('items' in schema || types.includes('array')) {
1195
+ if ('items' in schema || 'prefixItems' in schema || types.includes('array')) {
742
1196
  return [];
743
1197
  }
744
1198
  return undefined;
@@ -793,10 +1247,10 @@ const getDeclaredValue = (schema) => {
793
1247
  * Describe a composed schema by the member the walk itself would have rendered.
794
1248
  * Returns `undefined` when no member describes a shape.
795
1249
  */
796
- const describeComposition = (schema, options, schemaPath, seen) => {
1250
+ const describeComposition = (schema, options, schemaPath, seen, emptySchemaValue) => {
797
1251
  const variant = getSelectedVariant(schema, options, schemaPath);
798
1252
  if (variant) {
799
- return getMaxDepthValue(variant, options, schemaPath, seen);
1253
+ return getMaxDepthValue(variant, options, schemaPath, seen, emptySchemaValue);
800
1254
  }
801
1255
  if (!Array.isArray(schema.allOf) || schema.allOf.length === 0) {
802
1256
  return undefined;
@@ -835,7 +1289,7 @@ const describeComposition = (schema, options, schemaPath, seen) => {
835
1289
  * The value is empty rather than complete: satisfying `required` or `minItems` means descending
836
1290
  * again, which is exactly what the cap exists to prevent.
837
1291
  */
838
- const getMaxDepthValue = (schema, options, schemaPath, seen = new Set()) => {
1292
+ const getMaxDepthValue = (schema, options, schemaPath, seen = new Set(), emptySchemaValue = MAX_DEPTH_EXCEEDED) => {
839
1293
  // A stated value beats any stand-in, and matches what a full render would have produced.
840
1294
  const declared = getDeclaredValue(schema);
841
1295
  if (declared !== undefined) {
@@ -860,9 +1314,11 @@ const getMaxDepthValue = (schema, options, schemaPath, seen = new Set()) => {
860
1314
  // inheritance chain may be. `seen` holds exactly the path, so its size bounds the stack against a
861
1315
  // pathological chain, the way `schemaAllowsValue` bounds its own recursion.
862
1316
  const target = getSchemaCacheTarget(schema);
863
- if (!seen.has(target) && seen.size < MAX_COMPOSITION_DEPTH) {
1317
+ // The step budget bounds a wrapper whose members repeat one another (`allOf: [next, next]`), which
1318
+ // the path guard alone lets double with every link.
1319
+ if (!seen.has(target) && seen.size < MAX_COMPOSITION_DEPTH && requiredSteps-- > 0) {
864
1320
  seen.add(target);
865
- const composed = describeComposition(schema, options, schemaPath, seen);
1321
+ const composed = describeComposition(schema, options, schemaPath, seen, emptySchemaValue);
866
1322
  seen.delete(target);
867
1323
  if (composed !== undefined) {
868
1324
  return composed;
@@ -886,7 +1342,7 @@ const getMaxDepthValue = (schema, options, schemaPath, seen = new Set()) => {
886
1342
  return null;
887
1343
  }
888
1344
  truncated = true;
889
- return MAX_DEPTH_EXCEEDED;
1345
+ return emptySchemaValue;
890
1346
  };
891
1347
  const hasUnencodedJsonContent = (schema) => {
892
1348
  if (!('contentSchema' in schema) || !isJsonMediaType(schema.contentMediaType))
@@ -910,11 +1366,14 @@ const hasUnencodedJsonContent = (schema) => {
910
1366
  * @param name - The name of the property being processed.
911
1367
  * @returns An example value for the given schema.
912
1368
  */
913
- const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, name, seen = new WeakSet(), schemaPath = [], dynamicScope = [], } = {}) => {
1369
+ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, name, seen = new WeakSet(), schemaPath = [], dynamicScope = [], requiredScope, isRequiredProperty = false, } = {}) => {
914
1370
  // Cache restrictions only apply to the current traversal, so every top-level call starts clean.
915
1371
  if (level === 0) {
916
1372
  truncated = false;
917
1373
  generatedCurrentTime = false;
1374
+ requiredSteps = MAX_REQUIRED_STEPS;
1375
+ compositionRequiredNamesCache = new WeakMap();
1376
+ discriminatorExamples = new WeakMap();
918
1377
  }
919
1378
  // Resolve any $ref references to get the actual schema
920
1379
  const _schema = resolve.schema(schema);
@@ -937,6 +1396,8 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
937
1396
  seen: new WeakSet(),
938
1397
  schemaPath,
939
1398
  dynamicScope,
1399
+ requiredScope,
1400
+ isRequiredProperty,
940
1401
  });
941
1402
  }
942
1403
  }
@@ -963,7 +1424,7 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
963
1424
  // Determine if we should generate realistic example data
964
1425
  const makeUpRandomData = !!options?.emptyString;
965
1426
  // Early exits for schemas that should not be included (readOnly, writeOnly, omitEmptyAndOptionalProperties)
966
- if (shouldOmitProperty(_schema, parentSchema, name, options)) {
1427
+ if (shouldOmitProperty(_schema, parentSchema, name, options, isRequiredProperty)) {
967
1428
  seen.delete(targetValue);
968
1429
  return undefined;
969
1430
  }
@@ -1007,33 +1468,46 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
1007
1468
  // Stop descending once the walk is too deep to keep going, which also breaks circular references.
1008
1469
  // Everything above still applied, so an explicit example, `const` or `enum` wins here as it would at
1009
1470
  // any other level; only the children are given up on.
1471
+ //
1472
+ // An object still renders its required properties for a while past the cap, through this same walk, so
1473
+ // every rule that applies at a shallower level (read/write omission, composition selection, variables,
1474
+ // binary files) applies to them too. Required primitive compositions use the same walk so their
1475
+ // members retain those rules as well; arrays and anything past the bounds still stand in.
1010
1476
  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);
1477
+ if ((!(isRequiredProperty && getEmptyContainer(_schema) === undefined) &&
1478
+ !fillsRequiredProperties(_schema, requiredScope, options, schemaPath, level, seen, dynamicScope)) ||
1479
+ level > MAX_REQUIRED_LEVELS_DEEP ||
1480
+ requiredSteps <= 0) {
1481
+ seen.delete(targetValue);
1482
+ // Deliberately not cached: the value holds only at this level, and the cache key carries none.
1483
+ // Constraint-only composition members must not replace a sibling's required fields with the depth marker.
1484
+ const fallback = isRequiredProperty || requiredScope?.size ? null : MAX_DEPTH_EXCEEDED;
1485
+ return getMaxDepthValue(_schema, options, schemaPath, undefined, fallback);
1486
+ }
1487
+ requiredSteps--;
1488
+ // The rendered value omits optional properties, so it holds only at this level and must not be cached.
1489
+ truncated = true;
1014
1490
  }
1491
+ // A composition can start above the cap and cross it in a nested member. Keep the shared
1492
+ // requirements available throughout that descent, without filtering properties above the cap.
1493
+ const memberRequiredScope = requiredScope ??
1494
+ (isComposed(_schema)
1495
+ ? getCompositionRequiredNames(_schema, options, schemaPath, level, seen, dynamicScope)
1496
+ : undefined);
1015
1497
  // Resolve non-object unions before type dispatch so shared root keywords do not
1016
1498
  // hide the selected member. Use the same selection and discriminator rules as other unions.
1017
1499
  const selectedAnyOf = _schema.anyOf ? 'anyOf' : undefined;
1018
1500
  const selectedComposition = _schema.oneOf ? 'oneOf' : selectedAnyOf;
1019
1501
  const selectedVariant = getSelectedVariant(_schema, options, schemaPath);
1020
1502
  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);
1503
+ const selectedType = getSelectedType(selectedVariant, _schema);
1030
1504
  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;
1505
+ if (seen.has(getSchemaCacheTarget(selectedVariant))) {
1506
+ seen.delete(targetValue);
1507
+ return undefined;
1036
1508
  }
1509
+ const selectedSchema = mergeSelectedSchema(_schema, selectedVariant, selectedType === 'array');
1510
+ // These keywords only constrain their own types, but also drive our type inference.
1037
1511
  if (selectedType !== 'array' && 'items' in selectedSchema) {
1038
1512
  delete selectedSchema.items;
1039
1513
  }
@@ -1044,6 +1518,7 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
1044
1518
  schemaPath,
1045
1519
  seen,
1046
1520
  dynamicScope: childScope,
1521
+ isRequiredProperty,
1047
1522
  });
1048
1523
  seen.delete(targetValue);
1049
1524
  return cache(_schema, result, cacheKey, skipCache);
@@ -1061,6 +1536,7 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
1061
1536
  schemaPath: [...schemaPath, 'contentSchema'],
1062
1537
  seen,
1063
1538
  dynamicScope: childScope,
1539
+ isRequiredProperty,
1064
1540
  });
1065
1541
  if (content !== undefined) {
1066
1542
  seen.delete(targetValue);
@@ -1070,7 +1546,7 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
1070
1546
  }
1071
1547
  // Handle object types - check for properties to identify objects
1072
1548
  if ('properties' in _schema || ('type' in _schema && _schema.type === 'object')) {
1073
- const result = handleObjectSchema(_schema, options, level, seen, cacheKey, schemaPath, dynamicScope);
1549
+ const result = handleObjectSchema(_schema, options, level, seen, cacheKey, schemaPath, dynamicScope, requiredScope);
1074
1550
  seen.delete(targetValue);
1075
1551
  return result;
1076
1552
  }
@@ -1096,12 +1572,14 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
1096
1572
  const resolved = resolve.schema(candidate);
1097
1573
  if (resolved) {
1098
1574
  seen.delete(targetValue);
1099
- return cache(_schema, getExampleFromSchema(resolved, consumeCompositionSelection(options, schemaPath, compositionKeyword), {
1575
+ return cache(_schema, withDiscriminatorTag(_schema, candidate, getExampleFromSchema(resolved, consumeCompositionSelection(options, schemaPath, compositionKeyword), {
1100
1576
  level: level + 1,
1101
1577
  schemaPath,
1102
1578
  seen,
1103
1579
  dynamicScope: childScope,
1104
- }), cacheKey, skipCache);
1580
+ requiredScope: memberRequiredScope,
1581
+ isRequiredProperty,
1582
+ }), options, schemaPath), cacheKey, skipCache);
1105
1583
  }
1106
1584
  }
1107
1585
  seen.delete(targetValue);
@@ -1122,6 +1600,8 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
1122
1600
  schemaPath: memberSchemaPath,
1123
1601
  seen,
1124
1602
  dynamicScope: childScope,
1603
+ requiredScope: memberRequiredScope,
1604
+ isRequiredProperty,
1125
1605
  });
1126
1606
  if (merged === undefined) {
1127
1607
  merged = ex;
@@ -1149,26 +1629,24 @@ const generateExampleFromSchema = (schema, options, { level = 0, parentSchema, n
1149
1629
  return cache(_schema, null, cacheKey, skipCache);
1150
1630
  };
1151
1631
  /** 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('@')) {
1632
+ const asBinaryFile = (schema, value, options, schemaPath = []) => {
1633
+ if (!options?.binaryAsFile || typeof value !== 'string' || !value.startsWith('@')) {
1154
1634
  return value;
1155
1635
  }
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') {
1636
+ if (isFileSchema(resolveFormSchema(schema, options.compositionSelection, schemaPath) ?? schema)) {
1162
1637
  return new File([], value.slice(1), { lastModified: 0 });
1163
1638
  }
1164
1639
  return value;
1165
1640
  };
1166
- /** Generate data, optionally retaining the exact schema decisions for another output format. */
1641
+ /**
1642
+ * Generate data, optionally retaining the exact schema decisions for another output format.
1643
+ * Treat returned values as read-only: cached results and padded items can share object references.
1644
+ */
1167
1645
  export const getExampleFromSchema = (schema, options, context = {}) => {
1168
1646
  const capture = options?.[EXAMPLE_EVALUATION];
1169
1647
  if (!capture) {
1170
1648
  const value = generateExampleFromSchema(schema, options, context);
1171
- return asBinaryFile(schema, value, options?.binaryAsFile);
1649
+ return asBinaryFile(schema, value, options, context.schemaPath);
1172
1650
  }
1173
1651
  const node = {
1174
1652
  schema,
@@ -1187,7 +1665,7 @@ export const getExampleFromSchema = (schema, options, context = {}) => {
1187
1665
  }
1188
1666
  capture.stack.push(node);
1189
1667
  try {
1190
- node.value = asBinaryFile(schema, generateExampleFromSchema(schema, options, context), options?.binaryAsFile);
1668
+ node.value = asBinaryFile(schema, generateExampleFromSchema(schema, options, context), options, context.schemaPath);
1191
1669
  return node.value;
1192
1670
  }
1193
1671
  finally {