@scalar/api-client 2.39.0 → 2.39.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/hooks/useClientConfig.d.ts +18 -0
  3. package/dist/hooks/useClientConfig.d.ts.map +1 -1
  4. package/dist/style.css +23 -28
  5. package/dist/v2/blocks/operation-block/OperationBlock.vue.d.ts +2 -0
  6. package/dist/v2/blocks/operation-block/OperationBlock.vue.d.ts.map +1 -1
  7. package/dist/v2/blocks/operation-block/OperationBlock.vue.js.map +1 -1
  8. package/dist/v2/blocks/operation-block/OperationBlock.vue.script.js +6 -2
  9. package/dist/v2/blocks/operation-block/OperationBlock.vue.script.js.map +1 -1
  10. package/dist/v2/blocks/operation-block/helpers/build-request-body.d.ts +3 -1
  11. package/dist/v2/blocks/operation-block/helpers/build-request-body.d.ts.map +1 -1
  12. package/dist/v2/blocks/operation-block/helpers/build-request-body.js +2 -2
  13. package/dist/v2/blocks/operation-block/helpers/build-request-body.js.map +1 -1
  14. package/dist/v2/blocks/operation-block/helpers/build-request.d.ts +3 -1
  15. package/dist/v2/blocks/operation-block/helpers/build-request.d.ts.map +1 -1
  16. package/dist/v2/blocks/operation-block/helpers/build-request.js +2 -2
  17. package/dist/v2/blocks/operation-block/helpers/build-request.js.map +1 -1
  18. package/dist/v2/blocks/operation-code-sample/components/OperationCodeSample.vue.d.ts +5 -0
  19. package/dist/v2/blocks/operation-code-sample/components/OperationCodeSample.vue.d.ts.map +1 -1
  20. package/dist/v2/blocks/operation-code-sample/components/OperationCodeSample.vue.js +1 -1
  21. package/dist/v2/blocks/operation-code-sample/components/OperationCodeSample.vue.js.map +1 -1
  22. package/dist/v2/blocks/operation-code-sample/components/OperationCodeSample.vue.script.js +6 -3
  23. package/dist/v2/blocks/operation-code-sample/components/OperationCodeSample.vue.script.js.map +1 -1
  24. package/dist/v2/blocks/operation-code-sample/helpers/generate-code-snippet.d.ts +3 -1
  25. package/dist/v2/blocks/operation-code-sample/helpers/generate-code-snippet.d.ts.map +1 -1
  26. package/dist/v2/blocks/operation-code-sample/helpers/generate-code-snippet.js +3 -2
  27. package/dist/v2/blocks/operation-code-sample/helpers/generate-code-snippet.js.map +1 -1
  28. package/dist/v2/blocks/operation-code-sample/helpers/get-example-from-schema.d.ts +5 -1
  29. package/dist/v2/blocks/operation-code-sample/helpers/get-example-from-schema.d.ts.map +1 -1
  30. package/dist/v2/blocks/operation-code-sample/helpers/get-example-from-schema.js +51 -25
  31. package/dist/v2/blocks/operation-code-sample/helpers/get-example-from-schema.js.map +1 -1
  32. package/dist/v2/blocks/operation-code-sample/helpers/operation-to-har/operation-to-har.d.ts +6 -1
  33. package/dist/v2/blocks/operation-code-sample/helpers/operation-to-har/operation-to-har.d.ts.map +1 -1
  34. package/dist/v2/blocks/operation-code-sample/helpers/operation-to-har/operation-to-har.js +3 -2
  35. package/dist/v2/blocks/operation-code-sample/helpers/operation-to-har/operation-to-har.js.map +1 -1
  36. package/dist/v2/blocks/operation-code-sample/helpers/operation-to-har/process-body.d.ts +2 -2
  37. package/dist/v2/blocks/operation-code-sample/helpers/operation-to-har/process-body.d.ts.map +1 -1
  38. package/dist/v2/blocks/operation-code-sample/helpers/operation-to-har/process-body.js +5 -3
  39. package/dist/v2/blocks/operation-code-sample/helpers/operation-to-har/process-body.js.map +1 -1
  40. package/dist/v2/blocks/request-block/RequestBlock.vue.d.ts +1 -0
  41. package/dist/v2/blocks/request-block/RequestBlock.vue.d.ts.map +1 -1
  42. package/dist/v2/blocks/request-block/RequestBlock.vue.js +1 -1
  43. package/dist/v2/blocks/request-block/RequestBlock.vue.js.map +1 -1
  44. package/dist/v2/blocks/request-block/RequestBlock.vue.script.js +4 -1
  45. package/dist/v2/blocks/request-block/RequestBlock.vue.script.js.map +1 -1
  46. package/dist/v2/blocks/request-block/components/RequestBody.vue.d.ts +2 -0
  47. package/dist/v2/blocks/request-block/components/RequestBody.vue.d.ts.map +1 -1
  48. package/dist/v2/blocks/request-block/components/RequestBody.vue.js +1 -1
  49. package/dist/v2/blocks/request-block/components/RequestBody.vue.js.map +1 -1
  50. package/dist/v2/blocks/request-block/components/RequestBody.vue.script.js +3 -2
  51. package/dist/v2/blocks/request-block/components/RequestBody.vue.script.js.map +1 -1
  52. package/dist/v2/blocks/request-block/components/RequestCodeSnippet.vue.script.js +2 -1
  53. package/dist/v2/blocks/request-block/components/RequestCodeSnippet.vue.script.js.map +1 -1
  54. package/dist/v2/blocks/request-block/components/RequestTableTooltip.vue.d.ts.map +1 -1
  55. package/dist/v2/blocks/request-block/components/RequestTableTooltip.vue.js +1 -3
  56. package/dist/v2/blocks/request-block/components/RequestTableTooltip.vue.js.map +1 -1
  57. package/dist/v2/blocks/request-block/components/RequestTableTooltip.vue.script.js +2 -3
  58. package/dist/v2/blocks/request-block/components/RequestTableTooltip.vue.script.js.map +1 -1
  59. package/dist/v2/blocks/request-block/helpers/get-form-body-rows.d.ts.map +1 -1
  60. package/dist/v2/blocks/request-block/helpers/get-form-body-rows.js +6 -1
  61. package/dist/v2/blocks/request-block/helpers/get-form-body-rows.js.map +1 -1
  62. package/dist/v2/blocks/request-block/helpers/get-request-body-example.d.ts +1 -1
  63. package/dist/v2/blocks/request-block/helpers/get-request-body-example.d.ts.map +1 -1
  64. package/dist/v2/blocks/request-block/helpers/get-request-body-example.js +6 -2
  65. package/dist/v2/blocks/request-block/helpers/get-request-body-example.js.map +1 -1
  66. package/dist/v2/constants.js +1 -1
  67. package/dist/v2/features/app/helpers/routes.d.ts +2 -0
  68. package/dist/v2/features/app/helpers/routes.d.ts.map +1 -1
  69. package/dist/v2/features/collection/DocumentCollection.vue.d.ts.map +1 -1
  70. package/dist/v2/features/collection/DocumentCollection.vue.js.map +1 -1
  71. package/dist/v2/features/collection/DocumentCollection.vue.script.js +71 -48
  72. package/dist/v2/features/collection/DocumentCollection.vue.script.js.map +1 -1
  73. package/dist/v2/features/modal/Modal.vue.d.ts +3 -1
  74. package/dist/v2/features/modal/Modal.vue.d.ts.map +1 -1
  75. package/dist/v2/features/modal/Modal.vue.js.map +1 -1
  76. package/dist/v2/features/modal/Modal.vue.script.js +4 -0
  77. package/dist/v2/features/modal/Modal.vue.script.js.map +1 -1
  78. package/dist/v2/features/modal/helpers/create-api-client-modal.d.ts.map +1 -1
  79. package/dist/v2/features/modal/helpers/create-api-client-modal.js +3 -0
  80. package/dist/v2/features/modal/helpers/create-api-client-modal.js.map +1 -1
  81. package/dist/v2/features/modal/modal-events.d.ts +2 -1
  82. package/dist/v2/features/modal/modal-events.d.ts.map +1 -1
  83. package/dist/v2/features/modal/modal-events.js +3 -1
  84. package/dist/v2/features/modal/modal-events.js.map +1 -1
  85. package/dist/v2/features/operation/Operation.vue.d.ts +4 -0
  86. package/dist/v2/features/operation/Operation.vue.d.ts.map +1 -1
  87. package/dist/v2/features/operation/Operation.vue.js.map +1 -1
  88. package/dist/v2/features/operation/Operation.vue.script.js +4 -1
  89. package/dist/v2/features/operation/Operation.vue.script.js.map +1 -1
  90. package/dist/v2/helpers/download-document.d.ts +2 -0
  91. package/dist/v2/helpers/download-document.d.ts.map +1 -0
  92. package/dist/v2/helpers/download-document.js +42 -0
  93. package/dist/v2/helpers/download-document.js.map +1 -0
  94. package/dist/v2/posthog.d.ts.map +1 -1
  95. package/dist/v2/posthog.js +1 -0
  96. package/dist/v2/posthog.js.map +1 -1
  97. package/dist/views/Request/ResponseSection/ResponseEmpty.vue.script.js +1 -1
  98. package/package.json +13 -13
@@ -1 +1 @@
1
- {"version":3,"file":"get-example-from-schema.js","names":[],"sources":["../../../../../src/v2/blocks/operation-code-sample/helpers/get-example-from-schema.ts"],"sourcesContent":["import { isDefined } from '@scalar/helpers/array/is-defined'\nimport { unpackProxyObject } from '@scalar/workspace-store/helpers/unpack-proxy'\nimport { resolve } from '@scalar/workspace-store/resolve'\nimport type { SchemaObject } from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\n\n/** Maximum recursion depth to prevent infinite loops in circular references */\nconst MAX_LEVELS_DEEP = 10\n\n/** Default name used for additional properties when no custom name is provided */\nconst DEFAULT_ADDITIONAL_PROPERTIES_NAME = 'additionalProperty'\n\n/**\n * Pre-computed date/time values to avoid expensive Date operations on every call.\n * These are calculated once at module load time for better performance.\n */\nconst currentISOString = new Date().toISOString()\nconst currentDateString = currentISOString.split('T')[0]!\nconst currentTimeString = currentISOString.split('T')[1]!.split('.')[0]!\n\n/**\n * Mapping of OpenAPI string formats to example values.\n * Used to generate realistic examples for different string formats.\n */\nconst genericExampleValues: Record<string, string> = {\n 'date-time': currentISOString,\n 'date': currentDateString,\n 'email': 'hello@example.com',\n 'hostname': 'example.com',\n // https://tools.ietf.org/html/rfc6531#section-3.3\n 'idn-email': 'jane.doe@example.com',\n // https://tools.ietf.org/html/rfc5890#section-2.3.2.3\n 'idn-hostname': 'example.com',\n 'ipv4': '127.0.0.1',\n 'ipv6': '51d4:7fab:bfbf:b7d7:b2cb:d4b4:3dad:d998',\n 'iri-reference': '/entitiy/1',\n // https://tools.ietf.org/html/rfc3987\n 'iri': 'https://example.com/entity/123',\n 'json-pointer': '/nested/objects',\n 'password': 'super-secret',\n 'regex': '/[a-z]/',\n // https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01\n 'relative-json-pointer': '1/nested/objects',\n // full-time in https://tools.ietf.org/html/rfc3339#section-5.6\n 'time': currentTimeString,\n // either a URI or relative-reference https://tools.ietf.org/html/rfc3986#section-4.1\n 'uri-reference': '../folder',\n 'uri-template': 'https://example.com/{id}',\n 'uri': 'https://example.com',\n 'uuid': '123e4567-e89b-12d3-a456-426614174000',\n 'object-id': '6592008029c8c3e4dc76256c',\n}\n\n/**\n * Extract enum values from the propertyNames keyword of an object schema.\n * JSON Schema's propertyNames constrains which keys are valid in a map/dict.\n */\nconst getPropertyNamesEnumValues = (schema: SchemaObject): unknown[] | undefined => {\n if (!('propertyNames' in schema) || !schema.propertyNames) {\n return undefined\n }\n\n const resolved = resolve.schema(schema.propertyNames as SchemaObject)\n if (resolved && 'enum' in resolved && Array.isArray(resolved.enum) && resolved.enum.length > 0) {\n return resolved.enum\n }\n\n return undefined\n}\n\n/**\n * Generate example values for string types based on their format.\n * Special handling for binary format which returns a File object.\n */\nconst guessFromFormat = (\n schema: SchemaObject,\n makeUpRandomData: boolean = false,\n fallback: string = '',\n): string | File => {\n // Handle binary format specially - return a File object\n if ('type' in schema && schema.type === 'string' && 'format' in schema && schema.format === 'binary') {\n return '@filename'\n }\n\n // Return format-specific example if we have one and are making up data\n if (makeUpRandomData && 'format' in schema && schema.format) {\n return genericExampleValues[schema.format] ?? fallback\n }\n\n return fallback\n}\n\n/**\n * WeakMap cache for memoizing resolved example results.\n * Uses the resolved schema object as the key for efficient lookups.\n */\nconst resultCache = new WeakMap<object, Map<string, unknown>>()\n\n/** Cache required property names per parent schema for O(1) membership checks */\nconst requiredNamesCache = new WeakMap<object, ReadonlySet<string>>()\n\n/** Normalize schema identity for cache and cycle tracking */\nconst getSchemaCacheTarget = (schema: SchemaObject): object => unpackProxyObject(schema, { depth: 1 }) as object\n\n/**\n * Retrieves the set of required property names from a schema.\n * Caches the result in a WeakMap for efficient lookups.\n */\nconst getRequiredNames = (parentSchema: SchemaObject | undefined): ReadonlySet<string> | undefined => {\n if (!parentSchema) {\n return undefined\n }\n\n const cached = requiredNamesCache.get(parentSchema)\n if (cached) {\n return cached\n }\n\n if ('required' in parentSchema) {\n const required = parentSchema.required\n if (Array.isArray(required) && required.length > 0) {\n const set = new Set<string>(required)\n requiredNamesCache.set(parentSchema, set)\n return set\n }\n }\n\n return undefined\n}\n\n/**\n * Cache the result for a schema if it is an object type.\n * Primitive values are not cached to avoid unnecessary WeakMap operations.\n * Stores a map of cacheKey strings which is made up of the options object.\n */\nconst cache = (schema: SchemaObject, result: unknown, cacheKey: string) => {\n if (typeof result !== 'object' || result === null) {\n return result\n }\n const rawSchema = getSchemaCacheTarget(schema)\n\n const cacheMap = resultCache.get(rawSchema) ?? new Map()\n if (cacheMap) {\n cacheMap.set(cacheKey, result)\n }\n resultCache.set(rawSchema, cacheMap)\n return result\n}\n\n/**\n * Check if a schema uses composition keywords (allOf, oneOf, anyOf).\n * These require special handling for merging or selecting schemas.\n */\nconst isComposed = (schema: SchemaObject): boolean => !!(schema.allOf || schema.oneOf || schema.anyOf)\n\n/**\n * Determine if a property should be omitted based on the options.\n * Properties are omitted if they are not required and the option is enabled.\n */\nconst shouldOmitProperty = (\n schema: SchemaObject,\n parentSchema: SchemaObject | undefined,\n propertyName: string | undefined,\n options: Pick<GetExampleFromSchemaOptions, 'omitEmptyAndOptionalProperties' | 'mode'> | undefined,\n): boolean => {\n // Early exits for schemas that should not be included (deprecated, readOnly, writeOnly)\n if (\n schema.deprecated ||\n (options?.mode === 'write' && schema.readOnly) ||\n (options?.mode === 'read' && schema.writeOnly)\n ) {\n return true\n }\n\n if (options?.omitEmptyAndOptionalProperties !== true) {\n return false\n }\n\n // Never omit container types (objects/arrays) or composed schemas\n const isContainer = ('type' in schema && (schema.type === 'object' || schema.type === 'array')) || isComposed(schema)\n if (isContainer) {\n return false\n }\n\n // Do not omit if explicit example-like values are present\n if (\n ('examples' in schema && Array.isArray(schema.examples) && schema.examples.length > 0) ||\n ('example' in schema && schema.example !== undefined) ||\n ('default' in schema && schema.default !== undefined) ||\n ('const' in schema && schema.const !== undefined) ||\n ('enum' in schema && Array.isArray(schema.enum) && schema.enum.length > 0)\n ) {\n return false\n }\n\n // Check if the property is required\n const name = propertyName ?? schema.title ?? ''\n const requiredNames = getRequiredNames(parentSchema)\n const isRequired = requiredNames ? requiredNames.has(name) : false\n\n return !isRequired\n}\n\n/**\n * Merge two example values with predictable semantics.\n * Arrays are concatenated, objects are merged, otherwise the new value wins.\n */\nconst mergeExamples = (baseValue: unknown, newValue: unknown): unknown => {\n if (Array.isArray(baseValue) && Array.isArray(newValue)) {\n return [...baseValue, ...newValue]\n }\n if (baseValue && typeof baseValue === 'object' && newValue && typeof newValue === 'object') {\n return { ...(baseValue as Record<string, unknown>), ...(newValue as Record<string, unknown>) }\n }\n return newValue\n}\n\n/**\n * Build an example for an object schema, including properties, patternProperties,\n * additionalProperties, and composition (allOf/oneOf/anyOf) merging.\n */\nconst handleObjectSchema = (\n schema: SchemaObject,\n options: Parameters<typeof getExampleFromSchema>[1],\n level: number,\n seen: WeakSet<object>,\n cacheKey: string,\n): unknown => {\n const response: Record<string, unknown> = {}\n\n if ('properties' in schema && schema.properties) {\n const propertyNames = Object.keys(schema.properties)\n const limit = propertyNames.length\n\n for (let i = 0; i < limit; i++) {\n const propertyName = propertyNames[i]!\n const propertySchema = resolve.schema(schema.properties[propertyName])\n if (!propertySchema) {\n continue\n }\n\n const propertyXmlName = options?.xml && 'xml' in propertySchema ? propertySchema.xml?.name : undefined\n const value = getExampleFromSchema(propertySchema, options, {\n level: level + 1,\n parentSchema: schema,\n name: propertyName,\n seen,\n })\n\n if (typeof value !== 'undefined') {\n response[propertyXmlName ?? propertyName] = value\n }\n }\n }\n\n if ('patternProperties' in schema && schema.patternProperties) {\n for (const pattern of Object.keys(schema.patternProperties)) {\n const propertySchema = resolve.schema(schema.patternProperties[pattern])\n if (!propertySchema) {\n continue\n }\n response[pattern] = getExampleFromSchema(propertySchema, options, {\n level: level + 1,\n parentSchema: schema,\n name: pattern,\n seen,\n })\n }\n }\n\n if ('additionalProperties' in schema && schema.additionalProperties) {\n const additional =\n typeof schema.additionalProperties === 'boolean'\n ? schema.additionalProperties\n : resolve.schema(schema.additionalProperties)\n const isAnyType =\n schema.additionalProperties === true ||\n (typeof schema.additionalProperties === 'object' && Object.keys(schema.additionalProperties).length === 0)\n\n // Check for explicit x-additionalPropertiesName first\n const hasCustomName =\n typeof additional === 'object' &&\n 'x-additionalPropertiesName' in additional &&\n typeof additional['x-additionalPropertiesName'] === 'string' &&\n additional['x-additionalPropertiesName'].trim().length > 0\n\n // Use propertyNames enum values as example keys when no custom name is set\n const propertyNamesEnum = hasCustomName ? undefined : getPropertyNamesEnumValues(schema)\n\n const additionalName = hasCustomName\n ? (additional as unknown as Record<string, string>)['x-additionalPropertiesName']!.trim()\n : DEFAULT_ADDITIONAL_PROPERTIES_NAME\n\n const additionalValue = isAnyType\n ? 'anything'\n : typeof additional === 'object'\n ? getExampleFromSchema(additional, options, {\n level: level + 1,\n seen,\n })\n : 'anything'\n\n if (propertyNamesEnum && propertyNamesEnum.length > 0) {\n // Use the first enum value as a realistic example key\n response[String(propertyNamesEnum[0])] = additionalValue\n } else {\n response[additionalName] = additionalValue\n }\n }\n\n // onOf\n if (schema.oneOf?.[0]) {\n Object.assign(\n response,\n getExampleFromSchema(resolve.schema(schema.oneOf[0]), options, {\n level: level + 1,\n seen,\n }),\n )\n }\n // anyOf\n else if (schema.anyOf?.[0]) {\n Object.assign(\n response,\n getExampleFromSchema(resolve.schema(schema.anyOf[0]), options, {\n level: level + 1,\n seen,\n }),\n )\n }\n // allOf\n else if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {\n let merged: unknown = response\n for (const item of schema.allOf) {\n const ex = getExampleFromSchema(resolve.schema(item), options, {\n level: level + 1,\n parentSchema: schema,\n seen,\n })\n merged = mergeExamples(merged, ex)\n }\n if (merged && typeof merged === 'object') {\n Object.assign(response, merged as Record<string, unknown>)\n }\n }\n\n if (options?.xml && 'xml' in schema && schema.xml?.name && level === 0) {\n const wrapped: Record<string, unknown> = {}\n wrapped[schema.xml.name] = response\n return cache(schema, wrapped, cacheKey)\n }\n\n return cache(schema, response, cacheKey)\n}\n\n/** Build an example for an array schema, including items, allOf, oneOf/anyOf, and XML wrapping */\nconst handleArraySchema = (\n schema: SchemaObject,\n options: Parameters<typeof getExampleFromSchema>[1],\n level: number,\n seen: WeakSet<object>,\n cacheKey: string,\n) => {\n const items = 'items' in schema ? resolve.schema(schema.items) : undefined\n const itemsXmlTagName = items && typeof items === 'object' && 'xml' in items ? items.xml?.name : undefined\n const wrapItems = !!(options?.xml && 'xml' in schema && schema.xml?.wrapped && itemsXmlTagName)\n\n if (schema.example !== undefined) {\n return cache(schema, wrapItems ? { [itemsXmlTagName as string]: schema.example } : schema.example, cacheKey)\n }\n\n if (items && typeof items === 'object') {\n if (Array.isArray(items.allOf) && items.allOf.length > 0) {\n const allOf = items.allOf.filter(isDefined)\n const first = resolve.schema(allOf[0])\n\n if (first && typeof first === 'object' && 'type' in first && first.type === 'object') {\n const combined: SchemaObject = { type: 'object', allOf }\n const merged = getExampleFromSchema(combined, options, {\n level: level + 1,\n parentSchema: schema,\n seen,\n })\n return cache(schema, wrapItems ? [{ [itemsXmlTagName as string]: merged }] : [merged], cacheKey)\n }\n\n const examples = allOf\n .map((s) =>\n getExampleFromSchema(resolve.schema(s), options, {\n level: level + 1,\n parentSchema: schema,\n seen,\n }),\n )\n .filter(isDefined)\n return cache(\n schema,\n wrapItems ? (examples as unknown[]).map((e) => ({ [itemsXmlTagName as string]: e })) : examples,\n cacheKey,\n )\n }\n\n const union = items.anyOf || items.oneOf\n if (union && union.length > 0) {\n const first = union[0]!\n const ex = getExampleFromSchema(resolve.schema(first), options, {\n level: level + 1,\n parentSchema: schema,\n seen,\n })\n return cache(schema, wrapItems ? [{ [itemsXmlTagName as string]: ex }] : [ex], cacheKey)\n }\n }\n\n const isObject =\n items && typeof items === 'object' && (('type' in items && items.type === 'object') || 'properties' in items)\n const isArray =\n items && typeof items === 'object' && (('type' in items && items.type === 'array') || 'items' in items)\n\n if (items && typeof items === 'object' && (('type' in items && items.type) || isObject || isArray)) {\n const ex = getExampleFromSchema(items as SchemaObject, options, {\n level: level + 1,\n seen,\n })\n return cache(schema, wrapItems ? [{ [itemsXmlTagName as string]: ex }] : [ex], cacheKey)\n }\n\n return cache(schema, [], cacheKey)\n}\n\n/** Return primitive example value for single-type schemas, or undefined if not primitive */\nconst getPrimitiveValue = (schema: SchemaObject, makeUpRandomData: boolean, emptyString: string | undefined) => {\n if ('type' in schema && schema.type && !Array.isArray(schema.type)) {\n switch (schema.type) {\n case 'string':\n return guessFromFormat(schema, makeUpRandomData, emptyString ?? '')\n case 'boolean':\n return true\n case 'integer':\n return 'minimum' in schema && typeof schema.minimum === 'number' ? schema.minimum : 1\n case 'number':\n return 'minimum' in schema && typeof schema.minimum === 'number' ? schema.minimum : 1\n case 'array':\n return []\n default:\n return undefined\n }\n }\n return undefined\n}\n\n/** Return primitive example value for union-type schemas (type: string[]) */\nconst getUnionPrimitiveValue = (schema: SchemaObject, makeUpRandomData: boolean, emptyString: string | undefined) => {\n if ('type' in schema && Array.isArray(schema.type)) {\n if (schema.type.includes('null')) {\n return null\n }\n\n const first = schema.type[0]\n if (first) {\n switch (first) {\n case 'string':\n return guessFromFormat(schema, makeUpRandomData, emptyString ?? '')\n case 'boolean':\n return true\n case 'integer':\n return 'minimum' in schema && typeof schema.minimum === 'number' ? schema.minimum : 1\n case 'number':\n return 'minimum' in schema && typeof schema.minimum === 'number' ? schema.minimum : 1\n case 'null':\n return null\n default:\n return undefined\n }\n }\n }\n return undefined\n}\n\ntype GetExampleFromSchemaOptions = {\n /** Fallback string for empty string values. */\n emptyString?: string\n /** Whether to use XML tag names as keys. */\n xml?: boolean\n /** Whether to show read-only/write-only properties. */\n mode?: 'read' | 'write'\n /** Dynamic variables which can replace values via x-variable. */\n variables?: Record<string, unknown>\n /** Whether to omit empty and optional properties. */\n omitEmptyAndOptionalProperties?: boolean\n}\n\n/** Create stable cache key from the options object */\nconst createOptionsCacheKey = (options: GetExampleFromSchemaOptions | undefined) =>\n JSON.stringify({\n emptyString: options?.emptyString,\n xml: options?.xml,\n mode: options?.mode,\n variables: options?.variables,\n omitEmptyAndOptionalProperties: options?.omitEmptyAndOptionalProperties,\n })\n\n/**\n * Generate an example value from a given OpenAPI SchemaObject.\n *\n * This function recursively processes OpenAPI schemas to create realistic example data.\n * It handles all OpenAPI schema types including primitives, objects, arrays, and\n * composition schemas (allOf, oneOf, anyOf).\n * Uses a tonne of caching for maximum performance.\n *\n * @param schema - The OpenAPI SchemaObject to generate an example from.\n * @param options - Options to customize example generation.\n * @param level - The current recursion depth.\n * @param parentSchema - The parent schema, if any.\n * @param name - The name of the property being processed.\n * @returns An example value for the given schema.\n */\nexport const getExampleFromSchema = (\n schema: SchemaObject,\n options?: GetExampleFromSchemaOptions,\n {\n level = 0,\n parentSchema,\n name,\n seen = new WeakSet(),\n }: Partial<{\n level: number\n parentSchema: SchemaObject\n name: string\n seen: WeakSet<object>\n }> = {},\n): unknown => {\n // Resolve any $ref references to get the actual schema\n const _schema = resolve.schema(schema)\n if (!isDefined(_schema)) {\n return undefined\n }\n\n // Unpack from all proxies to get the raw schema object for cycle detection\n const targetValue = getSchemaCacheTarget(_schema)\n if (seen.has(targetValue)) {\n return undefined\n }\n seen.add(targetValue)\n\n /** Make the cache key unique per options */\n const cacheKey = createOptionsCacheKey(options)\n\n // Check cache first for performance - avoid recomputing the same schema\n const cached = resultCache.get(targetValue)?.get(cacheKey)\n if (typeof cached !== 'undefined') {\n seen.delete(targetValue)\n return cached\n }\n\n // Prevent infinite recursion in circular references\n if (level > MAX_LEVELS_DEEP) {\n seen.delete(targetValue)\n return '[Max Depth Exceeded]'\n }\n\n // Determine if we should generate realistic example data\n const makeUpRandomData = !!options?.emptyString\n\n // Early exits for schemas that should not be included (deprecated, readOnly, writeOnly, omitEmptyAndOptionalProperties)\n if (shouldOmitProperty(_schema, parentSchema, name, options)) {\n seen.delete(targetValue)\n return undefined\n }\n\n // Handle custom variables (x-variable extension)\n if ('x-variable' in _schema && _schema['x-variable']) {\n const value = options?.variables?.[_schema['x-variable']]\n if (value !== undefined) {\n // Type coercion for numeric types\n if ('type' in _schema && (_schema.type === 'number' || _schema.type === 'integer')) {\n seen.delete(targetValue)\n return cache(_schema, Number(value), cacheKey)\n }\n seen.delete(targetValue)\n return cache(_schema, value, cacheKey)\n }\n }\n\n // Priority order: examples > example > default > const > enum\n if (Array.isArray(_schema.examples) && _schema.examples.length > 0) {\n seen.delete(targetValue)\n return cache(_schema, _schema.examples[0], cacheKey)\n }\n if (_schema.example !== undefined) {\n seen.delete(targetValue)\n return cache(_schema, _schema.example, cacheKey)\n }\n if (_schema.default !== undefined) {\n seen.delete(targetValue)\n return cache(_schema, _schema.default, cacheKey)\n }\n if (_schema.const !== undefined) {\n seen.delete(targetValue)\n return cache(_schema, _schema.const, cacheKey)\n }\n if (Array.isArray(_schema.enum) && _schema.enum.length > 0) {\n seen.delete(targetValue)\n return cache(_schema, _schema.enum[0], cacheKey)\n }\n\n // Handle object types - check for properties to identify objects\n if ('properties' in _schema || ('type' in _schema && _schema.type === 'object')) {\n const result = handleObjectSchema(_schema, options, level, seen, cacheKey)\n seen.delete(targetValue)\n return result\n }\n\n // Handle array types\n if (('type' in _schema && _schema.type === 'array') || 'items' in _schema) {\n const result = handleArraySchema(_schema, options, level, seen, cacheKey)\n seen.delete(targetValue)\n return result\n }\n\n // Handle primitive types without allocating temporary objects\n const primitive = getPrimitiveValue(_schema, makeUpRandomData, options?.emptyString)\n if (primitive !== undefined) {\n seen.delete(targetValue)\n return cache(_schema, primitive, cacheKey)\n }\n\n // Handle composition schemas (oneOf, anyOf) at root level\n const discriminate = _schema.oneOf || _schema.anyOf\n if (Array.isArray(discriminate) && discriminate.length > 0) {\n // Find the first non-null type without allocating intermediate arrays\n for (const item of discriminate) {\n const resolved = resolve.schema(item)\n if (resolved && (!('type' in resolved) || resolved.type !== 'null')) {\n seen.delete(targetValue)\n return cache(\n _schema,\n getExampleFromSchema(resolved, options, {\n level: level + 1,\n seen,\n }),\n cacheKey,\n )\n }\n }\n seen.delete(targetValue)\n return cache(_schema, null, cacheKey)\n }\n\n // Handle allOf at root level (non-object/array schemas)\n if (Array.isArray(_schema.allOf) && _schema.allOf.length > 0) {\n let merged: unknown = undefined\n const items = _schema.allOf\n for (const item of items) {\n const ex = getExampleFromSchema(item as SchemaObject, options, {\n level: level + 1,\n parentSchema: _schema,\n seen,\n })\n if (merged === undefined) {\n merged = ex\n } else if (merged && typeof merged === 'object' && ex && typeof ex === 'object') {\n merged = mergeExamples(merged, ex)\n } else if (ex !== undefined) {\n // Prefer the latest defined primitive value\n merged = ex\n }\n }\n seen.delete(targetValue)\n return cache(_schema, merged ?? null, cacheKey)\n }\n\n // Handle union types (array of types)\n const unionPrimitive = getUnionPrimitiveValue(_schema, makeUpRandomData, options?.emptyString)\n if (unionPrimitive !== undefined) {\n seen.delete(targetValue)\n return cache(_schema, unionPrimitive, cacheKey)\n }\n\n // Default fallback\n seen.delete(targetValue)\n return cache(_schema, null, cacheKey)\n}\n"],"mappings":";;;;;AAMA,IAAM,kBAAkB;;AAGxB,IAAM,qCAAqC;;;;;AAM3C,IAAM,oCAAmB,IAAI,MAAM,EAAC,aAAa;AACjD,IAAM,oBAAoB,iBAAiB,MAAM,IAAI,CAAC;AACtD,IAAM,oBAAoB,iBAAiB,MAAM,IAAI,CAAC,GAAI,MAAM,IAAI,CAAC;;;;;AAMrE,IAAM,uBAA+C;CACnD,aAAa;CACb,QAAQ;CACR,SAAS;CACT,YAAY;CAEZ,aAAa;CAEb,gBAAgB;CAChB,QAAQ;CACR,QAAQ;CACR,iBAAiB;CAEjB,OAAO;CACP,gBAAgB;CAChB,YAAY;CACZ,SAAS;CAET,yBAAyB;CAEzB,QAAQ;CAER,iBAAiB;CACjB,gBAAgB;CAChB,OAAO;CACP,QAAQ;CACR,aAAa;CACd;;;;;AAMD,IAAM,8BAA8B,WAAgD;AAClF,KAAI,EAAE,mBAAmB,WAAW,CAAC,OAAO,cAC1C;CAGF,MAAM,WAAW,QAAQ,OAAO,OAAO,cAA8B;AACrE,KAAI,YAAY,UAAU,YAAY,MAAM,QAAQ,SAAS,KAAK,IAAI,SAAS,KAAK,SAAS,EAC3F,QAAO,SAAS;;;;;;AAUpB,IAAM,mBACJ,QACA,mBAA4B,OAC5B,WAAmB,OACD;AAElB,KAAI,UAAU,UAAU,OAAO,SAAS,YAAY,YAAY,UAAU,OAAO,WAAW,SAC1F,QAAO;AAIT,KAAI,oBAAoB,YAAY,UAAU,OAAO,OACnD,QAAO,qBAAqB,OAA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gB,SAAS;;AAIjD,MAAK,OAAO,YAAY;AACxB,QAAO,MAAM,SAAS,MAAM,SAAS"}
1
+ {"version":3,"file":"get-example-from-schema.js","names":[],"sources":["../../../../../src/v2/blocks/operation-code-sample/helpers/get-example-from-schema.ts"],"sourcesContent":["import { isDefined } from '@scalar/helpers/array/is-defined'\nimport { unpackProxyObject } from '@scalar/workspace-store/helpers/unpack-proxy'\nimport { resolve } from '@scalar/workspace-store/resolve'\nimport type { SchemaObject } from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\n\n/** Maximum recursion depth to prevent infinite loops in circular references */\nconst MAX_LEVELS_DEEP = 10\n\n/** Default name used for additional properties when no custom name is provided */\nconst DEFAULT_ADDITIONAL_PROPERTIES_NAME = 'additionalProperty'\n\n/**\n * Pre-computed date/time values to avoid expensive Date operations on every call.\n * These are calculated once at module load time for better performance.\n */\nconst currentISOString = new Date().toISOString()\nconst currentDateString = currentISOString.split('T')[0]!\nconst currentTimeString = currentISOString.split('T')[1]!.split('.')[0]!\n\n/**\n * Mapping of OpenAPI string formats to example values.\n * Used to generate realistic examples for different string formats.\n */\nconst genericExampleValues: Record<string, string> = {\n 'date-time': currentISOString,\n 'date': currentDateString,\n 'email': 'hello@example.com',\n 'hostname': 'example.com',\n // https://tools.ietf.org/html/rfc6531#section-3.3\n 'idn-email': 'jane.doe@example.com',\n // https://tools.ietf.org/html/rfc5890#section-2.3.2.3\n 'idn-hostname': 'example.com',\n 'ipv4': '127.0.0.1',\n 'ipv6': '51d4:7fab:bfbf:b7d7:b2cb:d4b4:3dad:d998',\n 'iri-reference': '/entitiy/1',\n // https://tools.ietf.org/html/rfc3987\n 'iri': 'https://example.com/entity/123',\n 'json-pointer': '/nested/objects',\n 'password': 'super-secret',\n 'regex': '/[a-z]/',\n // https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01\n 'relative-json-pointer': '1/nested/objects',\n // full-time in https://tools.ietf.org/html/rfc3339#section-5.6\n 'time': currentTimeString,\n // either a URI or relative-reference https://tools.ietf.org/html/rfc3986#section-4.1\n 'uri-reference': '../folder',\n 'uri-template': 'https://example.com/{id}',\n 'uri': 'https://example.com',\n 'uuid': '123e4567-e89b-12d3-a456-426614174000',\n 'object-id': '6592008029c8c3e4dc76256c',\n}\n\n/**\n * Extract enum values from the propertyNames keyword of an object schema.\n * JSON Schema's propertyNames constrains which keys are valid in a map/dict.\n */\nconst getPropertyNamesEnumValues = (schema: SchemaObject): unknown[] | undefined => {\n if (!('propertyNames' in schema) || !schema.propertyNames) {\n return undefined\n }\n\n const resolved = resolve.schema(schema.propertyNames as SchemaObject)\n if (resolved && 'enum' in resolved && Array.isArray(resolved.enum) && resolved.enum.length > 0) {\n return resolved.enum\n }\n\n return undefined\n}\n\n/**\n * Generate example values for string types based on their format.\n * Special handling for binary format which returns a File object.\n */\nconst guessFromFormat = (\n schema: SchemaObject,\n makeUpRandomData: boolean = false,\n fallback: string = '',\n): string | File => {\n // Handle binary format specially - return a File object\n if ('type' in schema && schema.type === 'string' && 'format' in schema && schema.format === 'binary') {\n return '@filename'\n }\n\n // Return format-specific example if we have one and are making up data\n if (makeUpRandomData && 'format' in schema && schema.format) {\n return genericExampleValues[schema.format] ?? fallback\n }\n\n return fallback\n}\n\n/**\n * WeakMap cache for memoizing resolved example results.\n * Uses the resolved schema object as the key for efficient lookups.\n */\nconst resultCache = new WeakMap<object, Map<string, unknown>>()\n\n/** Cache required property names per parent schema for O(1) membership checks */\nconst requiredNamesCache = new WeakMap<object, ReadonlySet<string>>()\n\n/** Normalize schema identity for cache and cycle tracking */\nconst getSchemaCacheTarget = (schema: SchemaObject): object => unpackProxyObject(schema, { depth: 1 }) as object\n\n/**\n * Retrieves the set of required property names from a schema.\n * Caches the result in a WeakMap for efficient lookups.\n */\nconst getRequiredNames = (parentSchema: SchemaObject | undefined): ReadonlySet<string> | undefined => {\n if (!parentSchema) {\n return undefined\n }\n\n const cached = requiredNamesCache.get(parentSchema)\n if (cached) {\n return cached\n }\n\n if ('required' in parentSchema) {\n const required = parentSchema.required\n if (Array.isArray(required) && required.length > 0) {\n const set = new Set<string>(required)\n requiredNamesCache.set(parentSchema, set)\n return set\n }\n }\n\n return undefined\n}\n\n/**\n * Cache the result for a schema if it is an object type.\n * Primitive values are not cached to avoid unnecessary WeakMap operations.\n * Stores a map of cacheKey strings which is made up of the options object.\n */\nconst cache = (schema: SchemaObject, result: unknown, cacheKey: string) => {\n if (typeof result !== 'object' || result === null) {\n return result\n }\n const rawSchema = getSchemaCacheTarget(schema)\n\n const cacheMap = resultCache.get(rawSchema) ?? new Map()\n if (cacheMap) {\n cacheMap.set(cacheKey, result)\n }\n resultCache.set(rawSchema, cacheMap)\n return result\n}\n\n/**\n * Check if a schema uses composition keywords (allOf, oneOf, anyOf).\n * These require special handling for merging or selecting schemas.\n */\nconst isComposed = (schema: SchemaObject): boolean => !!(schema.allOf || schema.oneOf || schema.anyOf)\n\n/**\n * Determine if a property should be omitted based on the options.\n * Properties are omitted if they are not required and the option is enabled.\n */\nconst shouldOmitProperty = (\n schema: SchemaObject,\n parentSchema: SchemaObject | undefined,\n propertyName: string | undefined,\n options: Pick<GetExampleFromSchemaOptions, 'omitEmptyAndOptionalProperties' | 'mode'> | undefined,\n): boolean => {\n // Early exits for schemas that should not be included (deprecated, readOnly, writeOnly)\n if (\n schema.deprecated ||\n (options?.mode === 'write' && schema.readOnly) ||\n (options?.mode === 'read' && schema.writeOnly)\n ) {\n return true\n }\n\n if (options?.omitEmptyAndOptionalProperties !== true) {\n return false\n }\n\n // Never omit container types (objects/arrays) or composed schemas\n const isContainer = ('type' in schema && (schema.type === 'object' || schema.type === 'array')) || isComposed(schema)\n if (isContainer) {\n return false\n }\n\n // Do not omit if explicit example-like values are present\n if (\n ('examples' in schema && Array.isArray(schema.examples) && schema.examples.length > 0) ||\n ('example' in schema && schema.example !== undefined) ||\n ('default' in schema && schema.default !== undefined) ||\n ('const' in schema && schema.const !== undefined) ||\n ('enum' in schema && Array.isArray(schema.enum) && schema.enum.length > 0)\n ) {\n return false\n }\n\n // Check if the property is required\n const name = propertyName ?? schema.title ?? ''\n const requiredNames = getRequiredNames(parentSchema)\n const isRequired = requiredNames ? requiredNames.has(name) : false\n\n return !isRequired\n}\n\n/**\n * Merge two example values with predictable semantics.\n * Arrays are concatenated, objects are merged, otherwise the new value wins.\n */\nconst mergeExamples = (baseValue: unknown, newValue: unknown): unknown => {\n if (Array.isArray(baseValue) && Array.isArray(newValue)) {\n return [...baseValue, ...newValue]\n }\n if (baseValue && typeof baseValue === 'object' && newValue && typeof newValue === 'object') {\n return { ...(baseValue as Record<string, unknown>), ...(newValue as Record<string, unknown>) }\n }\n return newValue\n}\n\ntype CompositionKeyword = 'anyOf' | 'oneOf'\n\nconst getCompositionSelectionKey = (schemaPath: string[], composition: CompositionKeyword): string =>\n [...schemaPath, composition].join('.')\n\nconst getCompositionSelectionIndex = (\n schemaPath: string[],\n composition: CompositionKeyword,\n options: GetExampleFromSchemaOptions | undefined,\n length: number,\n): number | undefined => {\n const rawIndex = options?.compositionSelection?.[getCompositionSelectionKey(schemaPath, composition)]\n\n if (typeof rawIndex !== 'number' || Number.isNaN(rawIndex)) {\n return undefined\n }\n\n return Math.max(0, Math.min(rawIndex, length - 1))\n}\n\n/**\n * Build an example for an object schema, including properties, patternProperties,\n * additionalProperties, and composition (allOf/oneOf/anyOf) merging.\n */\nconst handleObjectSchema = (\n schema: SchemaObject,\n options: Parameters<typeof getExampleFromSchema>[1],\n level: number,\n seen: WeakSet<object>,\n cacheKey: string,\n schemaPath: string[],\n): unknown => {\n const response: Record<string, unknown> = {}\n\n if ('properties' in schema && schema.properties) {\n const propertyNames = Object.keys(schema.properties)\n const limit = propertyNames.length\n\n for (let i = 0; i < limit; i++) {\n const propertyName = propertyNames[i]!\n const propertySchema = resolve.schema(schema.properties[propertyName])\n if (!propertySchema) {\n continue\n }\n\n const propertyXmlName = options?.xml && 'xml' in propertySchema ? propertySchema.xml?.name : undefined\n const value = getExampleFromSchema(propertySchema, options, {\n level: level + 1,\n parentSchema: schema,\n name: propertyName,\n schemaPath: [...schemaPath, propertyName],\n seen,\n })\n\n if (typeof value !== 'undefined') {\n response[propertyXmlName ?? propertyName] = value\n }\n }\n }\n\n if ('patternProperties' in schema && schema.patternProperties) {\n for (const pattern of Object.keys(schema.patternProperties)) {\n const propertySchema = resolve.schema(schema.patternProperties[pattern])\n if (!propertySchema) {\n continue\n }\n response[pattern] = getExampleFromSchema(propertySchema, options, {\n level: level + 1,\n parentSchema: schema,\n name: pattern,\n schemaPath: [...schemaPath, pattern],\n seen,\n })\n }\n }\n\n if ('additionalProperties' in schema && schema.additionalProperties) {\n const additional =\n typeof schema.additionalProperties === 'boolean'\n ? schema.additionalProperties\n : resolve.schema(schema.additionalProperties)\n const isAnyType =\n schema.additionalProperties === true ||\n (typeof schema.additionalProperties === 'object' && Object.keys(schema.additionalProperties).length === 0)\n\n // Check for explicit x-additionalPropertiesName first\n const hasCustomName =\n typeof additional === 'object' &&\n 'x-additionalPropertiesName' in additional &&\n typeof additional['x-additionalPropertiesName'] === 'string' &&\n additional['x-additionalPropertiesName'].trim().length > 0\n\n // Use propertyNames enum values as example keys when no custom name is set\n const propertyNamesEnum = hasCustomName ? undefined : getPropertyNamesEnumValues(schema)\n\n const additionalName = hasCustomName\n ? (additional as unknown as Record<string, string>)['x-additionalPropertiesName']!.trim()\n : DEFAULT_ADDITIONAL_PROPERTIES_NAME\n\n const additionalValue = isAnyType\n ? 'anything'\n : typeof additional === 'object'\n ? getExampleFromSchema(additional, options, {\n level: level + 1,\n schemaPath: [...schemaPath, additionalName],\n seen,\n })\n : 'anything'\n\n if (propertyNamesEnum && propertyNamesEnum.length > 0) {\n // Use the first enum value as a realistic example key\n response[String(propertyNamesEnum[0])] = additionalValue\n } else {\n response[additionalName] = additionalValue\n }\n }\n\n const compositionKeyword = schema.oneOf ? 'oneOf' : schema.anyOf ? 'anyOf' : undefined\n const oneOfAnyOf = compositionKeyword ? schema[compositionKeyword] : undefined\n if (compositionKeyword && oneOfAnyOf?.length) {\n const index = getCompositionSelectionIndex(schemaPath, compositionKeyword, options, oneOfAnyOf.length) ?? 0\n const chosen = resolve.schema(oneOfAnyOf[index])\n if (chosen) {\n Object.assign(\n response,\n getExampleFromSchema(chosen, options, {\n level: level + 1,\n schemaPath,\n seen,\n }),\n )\n }\n }\n // allOf\n else if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {\n let merged: unknown = response\n for (const item of schema.allOf) {\n const ex = getExampleFromSchema(resolve.schema(item), options, {\n level: level + 1,\n parentSchema: schema,\n seen,\n })\n merged = mergeExamples(merged, ex)\n }\n if (merged && typeof merged === 'object') {\n Object.assign(response, merged as Record<string, unknown>)\n }\n }\n\n if (options?.xml && 'xml' in schema && schema.xml?.name && level === 0) {\n const wrapped: Record<string, unknown> = {}\n wrapped[schema.xml.name] = response\n return cache(schema, wrapped, cacheKey)\n }\n\n return cache(schema, response, cacheKey)\n}\n\n/** Build an example for an array schema, including items, allOf, oneOf/anyOf, and XML wrapping */\nconst handleArraySchema = (\n schema: SchemaObject,\n options: Parameters<typeof getExampleFromSchema>[1],\n level: number,\n seen: WeakSet<object>,\n cacheKey: string,\n schemaPath: string[],\n) => {\n const items = 'items' in schema ? resolve.schema(schema.items) : undefined\n const itemsSchemaPath = [...schemaPath, 'items']\n const itemsXmlTagName = items && typeof items === 'object' && 'xml' in items ? items.xml?.name : undefined\n const wrapItems = !!(options?.xml && 'xml' in schema && schema.xml?.wrapped && itemsXmlTagName)\n\n if (schema.example !== undefined) {\n return cache(schema, wrapItems ? { [itemsXmlTagName as string]: schema.example } : schema.example, cacheKey)\n }\n\n if (items && typeof items === 'object') {\n if (Array.isArray(items.allOf) && items.allOf.length > 0) {\n const allOf = items.allOf.filter(isDefined)\n const first = resolve.schema(allOf[0])\n\n if (first && typeof first === 'object' && 'type' in first && first.type === 'object') {\n const combined: SchemaObject = { type: 'object', allOf }\n const merged = getExampleFromSchema(combined, options, {\n level: level + 1,\n parentSchema: schema,\n schemaPath: itemsSchemaPath,\n seen,\n })\n return cache(schema, wrapItems ? [{ [itemsXmlTagName as string]: merged }] : [merged], cacheKey)\n }\n\n const examples = allOf\n .map((s) =>\n getExampleFromSchema(resolve.schema(s), options, {\n level: level + 1,\n parentSchema: schema,\n schemaPath: itemsSchemaPath,\n seen,\n }),\n )\n .filter(isDefined)\n return cache(\n schema,\n wrapItems ? (examples as unknown[]).map((e) => ({ [itemsXmlTagName as string]: e })) : examples,\n cacheKey,\n )\n }\n\n const compositionKeyword = items.oneOf ? 'oneOf' : items.anyOf ? 'anyOf' : undefined\n const union = compositionKeyword ? items[compositionKeyword] : undefined\n if (compositionKeyword && union && union.length > 0) {\n const selectedIndex =\n getCompositionSelectionIndex(itemsSchemaPath, compositionKeyword, options, union.length) ?? 0\n const selected = union[selectedIndex]!\n const ex = getExampleFromSchema(resolve.schema(selected), options, {\n level: level + 1,\n parentSchema: schema,\n schemaPath: itemsSchemaPath,\n seen,\n })\n return cache(schema, wrapItems ? [{ [itemsXmlTagName as string]: ex }] : [ex], cacheKey)\n }\n }\n\n const isObject =\n items && typeof items === 'object' && (('type' in items && items.type === 'object') || 'properties' in items)\n const isArray =\n items && typeof items === 'object' && (('type' in items && items.type === 'array') || 'items' in items)\n\n if (items && typeof items === 'object' && (('type' in items && items.type) || isObject || isArray)) {\n const ex = getExampleFromSchema(items as SchemaObject, options, {\n level: level + 1,\n schemaPath: itemsSchemaPath,\n seen,\n })\n return cache(schema, wrapItems ? [{ [itemsXmlTagName as string]: ex }] : [ex], cacheKey)\n }\n\n return cache(schema, [], cacheKey)\n}\n\n/** Return primitive example value for single-type schemas, or undefined if not primitive */\nconst getPrimitiveValue = (schema: SchemaObject, makeUpRandomData: boolean, emptyString: string | undefined) => {\n if ('type' in schema && schema.type && !Array.isArray(schema.type)) {\n switch (schema.type) {\n case 'string':\n return guessFromFormat(schema, makeUpRandomData, emptyString ?? '')\n case 'boolean':\n return true\n case 'integer':\n return 'minimum' in schema && typeof schema.minimum === 'number' ? schema.minimum : 1\n case 'number':\n return 'minimum' in schema && typeof schema.minimum === 'number' ? schema.minimum : 1\n case 'array':\n return []\n default:\n return undefined\n }\n }\n return undefined\n}\n\n/** Return primitive example value for union-type schemas (type: string[]) */\nconst getUnionPrimitiveValue = (schema: SchemaObject, makeUpRandomData: boolean, emptyString: string | undefined) => {\n if ('type' in schema && Array.isArray(schema.type)) {\n if (schema.type.includes('null')) {\n return null\n }\n\n const first = schema.type[0]\n if (first) {\n switch (first) {\n case 'string':\n return guessFromFormat(schema, makeUpRandomData, emptyString ?? '')\n case 'boolean':\n return true\n case 'integer':\n return 'minimum' in schema && typeof schema.minimum === 'number' ? schema.minimum : 1\n case 'number':\n return 'minimum' in schema && typeof schema.minimum === 'number' ? schema.minimum : 1\n case 'null':\n return null\n default:\n return undefined\n }\n }\n }\n return undefined\n}\n\ntype GetExampleFromSchemaOptions = {\n /** Fallback string for empty string values. */\n emptyString?: string\n /** Whether to use XML tag names as keys. */\n xml?: boolean\n /** Whether to show read-only/write-only properties. */\n mode?: 'read' | 'write'\n /** Dynamic variables which can replace values via x-variable. */\n variables?: Record<string, unknown>\n /** Whether to omit empty and optional properties. */\n omitEmptyAndOptionalProperties?: boolean\n /** Selected oneOf/anyOf variants keyed by schema path. */\n compositionSelection?: Record<string, number>\n}\n\n/** Create stable cache key from the options object */\nconst createOptionsCacheKey = (options: GetExampleFromSchemaOptions | undefined) =>\n JSON.stringify({\n emptyString: options?.emptyString,\n xml: options?.xml,\n mode: options?.mode,\n variables: options?.variables,\n omitEmptyAndOptionalProperties: options?.omitEmptyAndOptionalProperties,\n compositionSelection: options?.compositionSelection\n ? Object.entries(options.compositionSelection).sort(([a], [b]) => a.localeCompare(b))\n : undefined,\n })\n\n/**\n * Generate an example value from a given OpenAPI SchemaObject.\n *\n * This function recursively processes OpenAPI schemas to create realistic example data.\n * It handles all OpenAPI schema types including primitives, objects, arrays, and\n * composition schemas (allOf, oneOf, anyOf).\n * Uses a tonne of caching for maximum performance.\n *\n * @param schema - The OpenAPI SchemaObject to generate an example from.\n * @param options - Options to customize example generation.\n * @param level - The current recursion depth.\n * @param parentSchema - The parent schema, if any.\n * @param name - The name of the property being processed.\n * @returns An example value for the given schema.\n */\nexport const getExampleFromSchema = (\n schema: SchemaObject,\n options?: GetExampleFromSchemaOptions,\n {\n level = 0,\n parentSchema,\n name,\n seen = new WeakSet(),\n schemaPath = [],\n }: Partial<{\n level: number\n parentSchema: SchemaObject\n name: string\n seen: WeakSet<object>\n /** Internal traversal path used to resolve nested composition selections. */\n schemaPath: string[]\n }> = {},\n): unknown => {\n // Resolve any $ref references to get the actual schema\n const _schema = resolve.schema(schema)\n if (!isDefined(_schema)) {\n return undefined\n }\n\n // Unpack from all proxies to get the raw schema object for cycle detection\n const targetValue = getSchemaCacheTarget(_schema)\n if (seen.has(targetValue)) {\n return undefined\n }\n seen.add(targetValue)\n\n /** Make the cache key unique per options and schema path */\n const cacheKey = createOptionsCacheKey(options) + (schemaPath.length > 0 ? `:path:${schemaPath.join('.')}` : '')\n\n // Check cache first for performance - avoid recomputing the same schema\n const cached = resultCache.get(targetValue)?.get(cacheKey)\n if (typeof cached !== 'undefined') {\n seen.delete(targetValue)\n return cached\n }\n\n // Prevent infinite recursion in circular references\n if (level > MAX_LEVELS_DEEP) {\n seen.delete(targetValue)\n return '[Max Depth Exceeded]'\n }\n\n // Determine if we should generate realistic example data\n const makeUpRandomData = !!options?.emptyString\n\n // Early exits for schemas that should not be included (deprecated, readOnly, writeOnly, omitEmptyAndOptionalProperties)\n if (shouldOmitProperty(_schema, parentSchema, name, options)) {\n seen.delete(targetValue)\n return undefined\n }\n\n // Handle custom variables (x-variable extension)\n if ('x-variable' in _schema && _schema['x-variable']) {\n const value = options?.variables?.[_schema['x-variable']]\n if (value !== undefined) {\n // Type coercion for numeric types\n if ('type' in _schema && (_schema.type === 'number' || _schema.type === 'integer')) {\n seen.delete(targetValue)\n return cache(_schema, Number(value), cacheKey)\n }\n seen.delete(targetValue)\n return cache(_schema, value, cacheKey)\n }\n }\n\n // Priority order: examples > example > default > const > enum\n if (Array.isArray(_schema.examples) && _schema.examples.length > 0) {\n seen.delete(targetValue)\n return cache(_schema, _schema.examples[0], cacheKey)\n }\n if (_schema.example !== undefined) {\n seen.delete(targetValue)\n return cache(_schema, _schema.example, cacheKey)\n }\n if (_schema.default !== undefined) {\n seen.delete(targetValue)\n return cache(_schema, _schema.default, cacheKey)\n }\n if (_schema.const !== undefined) {\n seen.delete(targetValue)\n return cache(_schema, _schema.const, cacheKey)\n }\n if (Array.isArray(_schema.enum) && _schema.enum.length > 0) {\n seen.delete(targetValue)\n return cache(_schema, _schema.enum[0], cacheKey)\n }\n\n // Handle object types - check for properties to identify objects\n if ('properties' in _schema || ('type' in _schema && _schema.type === 'object')) {\n const result = handleObjectSchema(_schema, options, level, seen, cacheKey, schemaPath)\n seen.delete(targetValue)\n return result\n }\n\n // Handle array types\n if (('type' in _schema && _schema.type === 'array') || 'items' in _schema) {\n const result = handleArraySchema(_schema, options, level, seen, cacheKey, schemaPath)\n seen.delete(targetValue)\n return result\n }\n\n // Handle primitive types without allocating temporary objects\n const primitive = getPrimitiveValue(_schema, makeUpRandomData, options?.emptyString)\n if (primitive !== undefined) {\n seen.delete(targetValue)\n return cache(_schema, primitive, cacheKey)\n }\n\n // Handle composition schemas (oneOf, anyOf)\n const compositionKeyword = _schema.oneOf ? 'oneOf' : _schema.anyOf ? 'anyOf' : undefined\n const discriminate = compositionKeyword ? _schema[compositionKeyword] : undefined\n if (compositionKeyword && Array.isArray(discriminate) && discriminate.length > 0) {\n const index = getCompositionSelectionIndex(schemaPath, compositionKeyword, options, discriminate.length)\n const candidate =\n index !== undefined\n ? discriminate[index]\n : discriminate.find((item) => {\n const resolved = resolve.schema(item)\n return resolved && (!('type' in resolved) || resolved.type !== 'null')\n })\n if (candidate) {\n const resolved = resolve.schema(candidate)\n if (resolved) {\n seen.delete(targetValue)\n return cache(\n _schema,\n getExampleFromSchema(resolved, options, {\n level: level + 1,\n schemaPath,\n seen,\n }),\n cacheKey,\n )\n }\n }\n seen.delete(targetValue)\n return cache(_schema, null, cacheKey)\n }\n\n // Handle allOf at root level (non-object/array schemas)\n if (Array.isArray(_schema.allOf) && _schema.allOf.length > 0) {\n let merged: unknown = undefined\n const items = _schema.allOf\n for (const item of items) {\n const ex = getExampleFromSchema(item as SchemaObject, options, {\n level: level + 1,\n parentSchema: _schema,\n schemaPath,\n seen,\n })\n if (merged === undefined) {\n merged = ex\n } else if (merged && typeof merged === 'object' && ex && typeof ex === 'object') {\n merged = mergeExamples(merged, ex)\n } else if (ex !== undefined) {\n // Prefer the latest defined primitive value\n merged = ex\n }\n }\n seen.delete(targetValue)\n return cache(_schema, merged ?? null, cacheKey)\n }\n\n // Handle union types (array of types)\n const unionPrimitive = getUnionPrimitiveValue(_schema, makeUpRandomData, options?.emptyString)\n if (unionPrimitive !== undefined) {\n seen.delete(targetValue)\n return cache(_schema, unionPrimitive, cacheKey)\n }\n\n // Default fallback\n seen.delete(targetValue)\n return cache(_schema, null, cacheKey)\n}\n"],"mappings":";;;;;AAMA,IAAM,kBAAkB;;AAGxB,IAAM,qCAAqC;;;;;AAM3C,IAAM,oCAAmB,IAAI,MAAM,EAAC,aAAa;AACjD,IAAM,oBAAoB,iBAAiB,MAAM,IAAI,CAAC;AACtD,IAAM,oBAAoB,iBAAiB,MAAM,IAAI,CAAC,GAAI,MAAM,IAAI,CAAC;;;;;AAMrE,IAAM,uBAA+C;CACnD,aAAa;CACb,QAAQ;CACR,SAAS;CACT,YAAY;CAEZ,aAAa;CAEb,gBAAgB;CAChB,QAAQ;CACR,QAAQ;CACR,iBAAiB;CAEjB,OAAO;CACP,gBAAgB;CAChB,YAAY;CACZ,SAAS;CAET,yBAAyB;CAEzB,QAAQ;CAER,iBAAiB;CACjB,gBAAgB;CAChB,OAAO;CACP,QAAQ;CACR,aAAa;CACd;;;;;AAMD,IAAM,8BAA8B,WAAgD;AAClF,KAAI,EAAE,mBAAmB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,EACb,UAAS;YACA,UAAU,OAAO,WAAW,YAAY,MAAM,OAAO,OAAO,SACrE,UAAS,cAAc,QAAQ,GAAG;YACzB,OAAO,KAAA,EAEhB,UAAS;;AAGb,OAAK,OAAO,YAAY;AACxB,SAAO,MAAM,SAAS,UAAU,MAAM,SAAS;;CAIjD,MAAM,iBAAiB,uBAAuB,SAAS,kBAAkB,SAAS,YAAY;AAC9F,KAAI,mBAAmB,KAAA,GAAW;AAChC,OAAK,OAAO,YAAY;AACxB,SAAO,MAAM,SAAS,gBAAgB,SAAS;;AAIjD,MAAK,OAAO,YAAY;AACxB,QAAO,MAAM,SAAS,MAAM,SAAS"}
@@ -35,6 +35,11 @@ export type OperationToHarProps = {
35
35
  * @default true
36
36
  */
37
37
  includeDefaultHeaders?: boolean;
38
+ /**
39
+ * Selected oneOf/anyOf variants for nested request body example generation
40
+ * (e.g. from the schema dropdowns in the API reference).
41
+ */
42
+ requestBodyCompositionSelection?: Record<string, number>;
38
43
  };
39
44
  /**
40
45
  * Converts an OpenAPI Operation to a HarRequest format for generating HTTP request snippets.
@@ -58,5 +63,5 @@ export type OperationToHarProps = {
58
63
  * @see https://w3c.github.io/web-performance/specs/HAR/Overview.html
59
64
  * @see https://spec.openapis.org/oas/v3.1.0#operation-object
60
65
  */
61
- export declare const operationToHar: ({ includeDefaultHeaders, operation, contentType, method, path, server, example, securitySchemes, globalCookies, }: OperationToHarProps) => HarRequest;
66
+ export declare const operationToHar: ({ includeDefaultHeaders, operation, contentType, method, path, server, example, securitySchemes, globalCookies, requestBodyCompositionSelection, }: OperationToHarProps) => HarRequest;
62
67
  //# sourceMappingURL=operation-to-har.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"operation-to-har.d.ts","sourceRoot":"","sources":["../../../../../../src/v2/blocks/operation-code-sample/helpers/operation-to-har/operation-to-har.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAA;AAEnE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qEAAqE,CAAA;AACxG,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,8DAA8D,CAAA;AACjH,OAAO,KAAK,EAAE,OAAO,IAAI,UAAU,EAAE,MAAM,YAAY,CAAA;AAIvD,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,6DAA6D,CAAA;AAO7G,MAAM,MAAM,mBAAmB,GAAG;IAChC,+BAA+B;IAC/B,SAAS,EAAE,eAAe,CAAA;IAC1B,mCAAmC;IACnC,MAAM,EAAE,UAAU,CAAA;IAClB,4BAA4B;IAC5B,IAAI,EAAE,MAAM,CAAA;IACZ;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,4BAA4B;IAC5B,MAAM,CAAC,EAAE,YAAY,GAAG,IAAI,CAAA;IAC5B,2EAA2E;IAC3E,eAAe,CAAC,EAAE,0BAA0B,EAAE,CAAA;IAC9C,mCAAmC;IACnC,aAAa,CAAC,EAAE,aAAa,EAAE,CAAA;IAC/B;;;;OAIG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAA;CAChC,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,cAAc,GAAI,mHAU5B,mBAAmB,KAAG,UA+FxB,CAAA"}
1
+ {"version":3,"file":"operation-to-har.d.ts","sourceRoot":"","sources":["../../../../../../src/v2/blocks/operation-code-sample/helpers/operation-to-har/operation-to-har.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAA;AAEnE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qEAAqE,CAAA;AACxG,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,8DAA8D,CAAA;AACjH,OAAO,KAAK,EAAE,OAAO,IAAI,UAAU,EAAE,MAAM,YAAY,CAAA;AAIvD,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,6DAA6D,CAAA;AAO7G,MAAM,MAAM,mBAAmB,GAAG;IAChC,+BAA+B;IAC/B,SAAS,EAAE,eAAe,CAAA;IAC1B,mCAAmC;IACnC,MAAM,EAAE,UAAU,CAAA;IAClB,4BAA4B;IAC5B,IAAI,EAAE,MAAM,CAAA;IACZ;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,4BAA4B;IAC5B,MAAM,CAAC,EAAE,YAAY,GAAG,IAAI,CAAA;IAC5B,2EAA2E;IAC3E,eAAe,CAAC,EAAE,0BAA0B,EAAE,CAAA;IAC9C,mCAAmC;IACnC,aAAa,CAAC,EAAE,aAAa,EAAE,CAAA;IAC/B;;;;OAIG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAA;IAC/B;;;OAGG;IACH,+BAA+B,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACzD,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,cAAc,GAAI,oJAW5B,mBAAmB,KAAG,UAoGxB,CAAA"}
@@ -28,7 +28,7 @@ import { getResolvedRef } from "@scalar/workspace-store/helpers/get-resolved-ref
28
28
  * @see https://w3c.github.io/web-performance/specs/HAR/Overview.html
29
29
  * @see https://spec.openapis.org/oas/v3.1.0#operation-object
30
30
  */
31
- var operationToHar = ({ includeDefaultHeaders = false, operation, contentType, method, path, server = null, example, securitySchemes, globalCookies }) => {
31
+ var operationToHar = ({ includeDefaultHeaders = false, operation, contentType, method, path, server = null, example, securitySchemes, globalCookies, requestBodyCompositionSelection }) => {
32
32
  const defaultHeaders = includeDefaultHeaders ? getDefaultHeaders({
33
33
  method,
34
34
  operation,
@@ -74,7 +74,8 @@ var operationToHar = ({ includeDefaultHeaders = false, operation, contentType, m
74
74
  const postData = processBody({
75
75
  requestBody: body,
76
76
  contentType,
77
- example
77
+ example,
78
+ requestBodyCompositionSelection
78
79
  });
79
80
  if (postData) {
80
81
  harRequest.postData = postData;
@@ -1 +1 @@
1
- {"version":3,"file":"operation-to-har.js","names":[],"sources":["../../../../../../src/v2/blocks/operation-code-sample/helpers/operation-to-har/operation-to-har.ts"],"sourcesContent":["import type { HttpMethod } from '@scalar/helpers/http/http-methods'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport type { Request as HarRequest } from 'har-format'\n\nimport { filterGlobalCookie } from '@/v2/blocks/operation-block/helpers/filter-global-cookies'\nimport { getDefaultHeaders } from '@/v2/blocks/request-block/helpers/get-default-headers'\nimport type { SecuritySchemeObjectSecret } from '@/v2/blocks/scalar-auth-selector-block/helpers/secret-types'\n\nimport { processBody } from './process-body'\nimport { processParameters } from './process-parameters'\nimport { processSecuritySchemes } from './process-security-schemes'\nimport { processServerUrl } from './process-server-url'\n\nexport type OperationToHarProps = {\n /** OpenAPI Operation object */\n operation: OperationObject\n /** HTTP method of the operation */\n method: HttpMethod\n /** Path of the operation */\n path: string\n /**\n * Name of the currently selected operation example\n *\n * Applies to both the body and the parameters\n */\n example?: string\n /**\n * Content type of the operation\n *\n * Applies to both the body and the parameters (if applicable)\n * @defaults to the first content type in the MediaTypeObject\n */\n contentType?: string\n /** OpenAPI Server object */\n server?: ServerObject | null\n /** OpenAPI SecurityScheme objects which are applicable to the operation */\n securitySchemes?: SecuritySchemeObjectSecret[]\n /** Workspace + document cookies */\n globalCookies?: XScalarCookie[]\n /**\n * Whether to include default headers (e.g., Accept, Content-Type) automatically.\n * If false, default headers will be omitted from the HAR request.\n * @default true\n */\n includeDefaultHeaders?: boolean\n}\n\n/**\n * Converts an OpenAPI Operation to a HarRequest format for generating HTTP request snippets.\n *\n * This function transforms OpenAPI 3.1 operation objects into HAR (HTTP Archive) format requests,\n * which can be used to generate code snippets for various programming languages and HTTP clients.\n *\n * The conversion handles:\n * - Server URL processing and path parameter substitution\n * - Query parameter formatting based on OpenAPI parameter styles\n * - Request body processing with content type handling\n * - Security scheme integration (API keys, etc.)\n *\n * The resulting HarRequest object follows the HAR specification and includes:\n * - HTTP method and URL\n * - Headers and query parameters\n * - Request body (if present)\n * - Cookie information\n * - Size calculations for headers and body\n *\n * @see https://w3c.github.io/web-performance/specs/HAR/Overview.html\n * @see https://spec.openapis.org/oas/v3.1.0#operation-object\n */\nexport const operationToHar = ({\n includeDefaultHeaders = false,\n operation,\n contentType,\n method,\n path,\n server = null,\n example,\n securitySchemes,\n globalCookies,\n}: OperationToHarProps): HarRequest => {\n const defaultHeaders = includeDefaultHeaders\n ? getDefaultHeaders({\n method,\n operation,\n exampleKey: example ?? 'default',\n hideDisabledHeaders: true,\n }).filter((header) => !header.isOverridden)\n : []\n\n const disabledGlobalCookies =\n operation['x-scalar-disable-parameters']?.['global-cookies']?.[example ?? 'default'] ?? {}\n\n const serverUrl = processServerUrl(server, path)\n\n // Initialize the HAR request with basic properties\n const harRequest: HarRequest = {\n method,\n url: serverUrl,\n headers: defaultHeaders.map((header) => ({ name: header.name, value: header.defaultValue })),\n queryString: [],\n postData: undefined,\n httpVersion: 'HTTP/1.1',\n cookies: [],\n headersSize: -1,\n bodySize: -1,\n }\n\n // Handle parameters\n if (operation.parameters) {\n const { url, headers, queryString, cookies } = processParameters({\n harRequest,\n parameters: operation.parameters,\n example,\n })\n\n // Correctly filter the global cookies by the processed url\n const filteredGlobalCookies =\n globalCookies\n ?.filter((cookie) => filterGlobalCookie({ cookie, url, disabledGlobalCookies }))\n ?.map((cookie) => ({ name: cookie.name, value: cookie.value })) ?? []\n\n harRequest.url = url\n harRequest.headers = headers\n harRequest.queryString = queryString\n harRequest.cookies = [...filteredGlobalCookies, ...cookies]\n }\n\n const body = getResolvedRef(operation.requestBody)\n\n // Handle request body\n if (body?.content) {\n const postData = processBody({ requestBody: body, contentType, example })\n\n if (postData) {\n harRequest.postData = postData\n harRequest.bodySize = postData.text?.length ?? -1\n\n // Add or update Content-Type header\n if (postData.mimeType) {\n const existingContentTypeHeader = harRequest.headers.find(\n (header) => header.name.toLowerCase() === 'content-type',\n )\n // Update existing header if it has an empty value\n if (existingContentTypeHeader && !existingContentTypeHeader.value) {\n existingContentTypeHeader.value = postData.mimeType\n }\n // Add new header if none exists\n else if (!existingContentTypeHeader) {\n harRequest.headers.push({\n name: 'Content-Type',\n value: postData.mimeType,\n })\n }\n }\n }\n }\n\n // Handle security schemes\n if (securitySchemes) {\n const { headers, queryString, cookies } = processSecuritySchemes(securitySchemes)\n harRequest.headers.push(...headers)\n harRequest.queryString.push(...queryString)\n harRequest.cookies.push(...cookies)\n }\n\n // Calculate headers size without allocating a large joined string\n let headersSize = 0\n for (const h of harRequest.headers) {\n // name + \": \" + value + \"\\r\\n\"\n headersSize += (h.name?.length ?? 0) + 2 + (h.value?.length ?? 0) + 2\n }\n harRequest.headersSize = headersSize\n\n return harRequest\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,IAAa,kBAAkB,EAC7B,wBAAwB,OACxB,WACA,aACA,QACA,MACA,SAAS,MACT,SACA,iBACA,oBACqC;CACrC,MAAM,iBAAiB,wBACnB,kBAAkB;EAChB;EACA;EACA,YAAY,WAAW;EACvB,qBAAqB;EACtB,CAAC,CAAC,QAAQ,WAAW,CAAC,OAAO,aAAa,GAC3C,EAAE;CAEN,MAAM,wBACJ,UAAU,iCAAiC,oBAAoB,WAAW,cAAc,EAAE;CAK5F,MAAM,aAAyB;EAC7B;EACA,KALgB,iBAAiB,QAAQ,KAAK;EAM9C,SAAS,eAAe,KAAK,YAAY;GAAE,MAAM,OAAO;GAAM,OAAO,OAAO;GAAc,EAAE;EAC5F,aAAa,EAAE;EACf,UAAU,KAAA;EACV,aAAa;EACb,SAAS,EAAE;EACX,aA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../../../../../../src/v2/blocks/operation-code-sample/helpers/operation-to-har/operation-to-har.ts"],"sourcesContent":["import type { HttpMethod } from '@scalar/helpers/http/http-methods'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport type { Request as HarRequest } from 'har-format'\n\nimport { filterGlobalCookie } from '@/v2/blocks/operation-block/helpers/filter-global-cookies'\nimport { getDefaultHeaders } from '@/v2/blocks/request-block/helpers/get-default-headers'\nimport type { SecuritySchemeObjectSecret } from '@/v2/blocks/scalar-auth-selector-block/helpers/secret-types'\n\nimport { processBody } from './process-body'\nimport { processParameters } from './process-parameters'\nimport { processSecuritySchemes } from './process-security-schemes'\nimport { processServerUrl } from './process-server-url'\n\nexport type OperationToHarProps = {\n /** OpenAPI Operation object */\n operation: OperationObject\n /** HTTP method of the operation */\n method: HttpMethod\n /** Path of the operation */\n path: string\n /**\n * Name of the currently selected operation example\n *\n * Applies to both the body and the parameters\n */\n example?: string\n /**\n * Content type of the operation\n *\n * Applies to both the body and the parameters (if applicable)\n * @defaults to the first content type in the MediaTypeObject\n */\n contentType?: string\n /** OpenAPI Server object */\n server?: ServerObject | null\n /** OpenAPI SecurityScheme objects which are applicable to the operation */\n securitySchemes?: SecuritySchemeObjectSecret[]\n /** Workspace + document cookies */\n globalCookies?: XScalarCookie[]\n /**\n * Whether to include default headers (e.g., Accept, Content-Type) automatically.\n * If false, default headers will be omitted from the HAR request.\n * @default true\n */\n includeDefaultHeaders?: boolean\n /**\n * Selected oneOf/anyOf variants for nested request body example generation\n * (e.g. from the schema dropdowns in the API reference).\n */\n requestBodyCompositionSelection?: Record<string, number>\n}\n\n/**\n * Converts an OpenAPI Operation to a HarRequest format for generating HTTP request snippets.\n *\n * This function transforms OpenAPI 3.1 operation objects into HAR (HTTP Archive) format requests,\n * which can be used to generate code snippets for various programming languages and HTTP clients.\n *\n * The conversion handles:\n * - Server URL processing and path parameter substitution\n * - Query parameter formatting based on OpenAPI parameter styles\n * - Request body processing with content type handling\n * - Security scheme integration (API keys, etc.)\n *\n * The resulting HarRequest object follows the HAR specification and includes:\n * - HTTP method and URL\n * - Headers and query parameters\n * - Request body (if present)\n * - Cookie information\n * - Size calculations for headers and body\n *\n * @see https://w3c.github.io/web-performance/specs/HAR/Overview.html\n * @see https://spec.openapis.org/oas/v3.1.0#operation-object\n */\nexport const operationToHar = ({\n includeDefaultHeaders = false,\n operation,\n contentType,\n method,\n path,\n server = null,\n example,\n securitySchemes,\n globalCookies,\n requestBodyCompositionSelection,\n}: OperationToHarProps): HarRequest => {\n const defaultHeaders = includeDefaultHeaders\n ? getDefaultHeaders({\n method,\n operation,\n exampleKey: example ?? 'default',\n hideDisabledHeaders: true,\n }).filter((header) => !header.isOverridden)\n : []\n\n const disabledGlobalCookies =\n operation['x-scalar-disable-parameters']?.['global-cookies']?.[example ?? 'default'] ?? {}\n\n const serverUrl = processServerUrl(server, path)\n\n // Initialize the HAR request with basic properties\n const harRequest: HarRequest = {\n method,\n url: serverUrl,\n headers: defaultHeaders.map((header) => ({ name: header.name, value: header.defaultValue })),\n queryString: [],\n postData: undefined,\n httpVersion: 'HTTP/1.1',\n cookies: [],\n headersSize: -1,\n bodySize: -1,\n }\n\n // Handle parameters\n if (operation.parameters) {\n const { url, headers, queryString, cookies } = processParameters({\n harRequest,\n parameters: operation.parameters,\n example,\n })\n\n // Correctly filter the global cookies by the processed url\n const filteredGlobalCookies =\n globalCookies\n ?.filter((cookie) => filterGlobalCookie({ cookie, url, disabledGlobalCookies }))\n ?.map((cookie) => ({ name: cookie.name, value: cookie.value })) ?? []\n\n harRequest.url = url\n harRequest.headers = headers\n harRequest.queryString = queryString\n harRequest.cookies = [...filteredGlobalCookies, ...cookies]\n }\n\n const body = getResolvedRef(operation.requestBody)\n\n // Handle request body\n if (body?.content) {\n const postData = processBody({\n requestBody: body,\n contentType,\n example,\n requestBodyCompositionSelection,\n })\n\n if (postData) {\n harRequest.postData = postData\n harRequest.bodySize = postData.text?.length ?? -1\n\n // Add or update Content-Type header\n if (postData.mimeType) {\n const existingContentTypeHeader = harRequest.headers.find(\n (header) => header.name.toLowerCase() === 'content-type',\n )\n // Update existing header if it has an empty value\n if (existingContentTypeHeader && !existingContentTypeHeader.value) {\n existingContentTypeHeader.value = postData.mimeType\n }\n // Add new header if none exists\n else if (!existingContentTypeHeader) {\n harRequest.headers.push({\n name: 'Content-Type',\n value: postData.mimeType,\n })\n }\n }\n }\n }\n\n // Handle security schemes\n if (securitySchemes) {\n const { headers, queryString, cookies } = processSecuritySchemes(securitySchemes)\n harRequest.headers.push(...headers)\n harRequest.queryString.push(...queryString)\n harRequest.cookies.push(...cookies)\n }\n\n // Calculate headers size without allocating a large joined string\n let headersSize = 0\n for (const h of harRequest.headers) {\n // name + \": \" + value + \"\\r\\n\"\n headersSize += (h.name?.length ?? 0) + 2 + (h.value?.length ?? 0) + 2\n }\n harRequest.headersSize = headersSize\n\n return harRequest\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,IAAa,kBAAkB,EAC7B,wBAAwB,OACxB,WACA,aACA,QACA,MACA,SAAS,MACT,SACA,iBACA,eACA,sCACqC;CACrC,MAAM,iBAAiB,wBACnB,kBAAkB;EAChB;EACA;EACA,YAAY,WAAW;EACvB,qBAAqB;EACtB,CAAC,CAAC,QAAQ,WAAW,CAAC,OAAO,aAAa,GAC3C,EAAE;CAEN,MAAM,wBACJ,UAAU,iCAAiC,oBAAoB,WAAW,cAAc,EAAE;CAK5F,MAAM,aAAyB;EAC7B;EACA,KALgB,iBAAiB,QAAQ,KAAK;EAM9C,SAAS,eAAe,KAAK,YAAY;GAAE,MAAM,OAAO;GAAM,OAAO,OAAO;GAAc,EAAE;EAC5F,aAAa,EAAE;EACf,UAAU,KAAA;EACV,aAAa;EACb,SAAS,EAAE;EACX,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yObject } from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document';
2
2
  import type { PostData } from 'har-format';
3
3
  import type { OperationToHarProps } from './operation-to-har.js';
4
- type ProcessBodyProps = Pick<OperationToHarProps, 'contentType' | 'example'> & {
4
+ type ProcessBodyProps = Pick<OperationToHarProps, 'contentType' | 'example' | 'requestBodyCompositionSelection'> & {
5
5
  requestBody: RequestBodyObject;
6
6
  };
7
7
  /**
8
8
  * Processes the request body and returns the processed data
9
9
  * Returns undefined if no example is found
10
10
  */
11
- export declare const processBody: ({ requestBody, contentType, example }: ProcessBodyProps) => PostData | undefined;
11
+ export declare const processBody: ({ requestBody, contentType, example, requestBodyCompositionSelection, }: ProcessBodyProps) => PostData | undefined;
12
12
  export {};
13
13
  //# sourceMappingURL=process-body.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"process-body.d.ts","sourceRoot":"","sources":["../../../../../../src/v2/blocks/operation-code-sample/helpers/operation-to-har/process-body.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAmB,iBAAiB,EAAE,MAAM,8DAA8D,CAAA;AAEtH,OAAO,KAAK,EAAS,QAAQ,EAAE,MAAM,YAAY,CAAA;AAIjD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAA;AAE7D,KAAK,gBAAgB,GAAG,IAAI,CAAC,mBAAmB,EAAE,aAAa,GAAG,SAAS,CAAC,GAAG;IAC7E,WAAW,EAAE,iBAAiB,CAAA;CAC/B,CAAA;AAoED;;;GAGG;AACH,eAAO,MAAM,WAAW,GAAI,uCAAuC,gBAAgB,KAAG,QAAQ,GAAG,SA+EhG,CAAA"}
1
+ {"version":3,"file":"process-body.d.ts","sourceRoot":"","sources":["../../../../../../src/v2/blocks/operation-code-sample/helpers/operation-to-har/process-body.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAEV,iBAAiB,EAElB,MAAM,8DAA8D,CAAA;AAGrE,OAAO,KAAK,EAAS,QAAQ,EAAE,MAAM,YAAY,CAAA;AAIjD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAA;AAE7D,KAAK,gBAAgB,GAAG,IAAI,CAAC,mBAAmB,EAAE,aAAa,GAAG,SAAS,GAAG,iCAAiC,CAAC,GAAG;IACjH,WAAW,EAAE,iBAAiB,CAAA;CAC/B,CAAA;AAoED;;;GAGG;AACH,eAAO,MAAM,WAAW,GAAI,yEAKzB,gBAAgB,KAAG,QAAQ,GAAG,SAuFhC,CAAA"}
@@ -1,3 +1,4 @@
1
+ import { getResolvedRefDeep } from "../get-resolved-ref-deep.js";
1
2
  import { getExample } from "../../../operation-block/helpers/get-example.js";
2
3
  import { getExampleFromSchema } from "../get-example-from-schema.js";
3
4
  import { getResolvedRef } from "@scalar/workspace-store/helpers/get-resolved-ref";
@@ -56,7 +57,7 @@ var objectToFormParams = (obj, encoding, parentKey) => {
56
57
  * Processes the request body and returns the processed data
57
58
  * Returns undefined if no example is found
58
59
  */
59
- var processBody = ({ requestBody, contentType, example }) => {
60
+ var processBody = ({ requestBody, contentType, example, requestBodyCompositionSelection }) => {
60
61
  const _contentType = contentType || Object.keys(requestBody.content)[0] || "";
61
62
  const formatBinaryFile = (file) => {
62
63
  return `@${unpackProxyObject(file).name || "filename"}`;
@@ -86,10 +87,11 @@ var processBody = ({ requestBody, contentType, example }) => {
86
87
  }
87
88
  const contentSchema = getResolvedRef(requestBody.content[_contentType]?.schema);
88
89
  if (typeof contentSchema !== "undefined") {
89
- const extractedExample = getExampleFromSchema(contentSchema, {
90
+ const extractedExample = getExampleFromSchema(getResolvedRefDeep(contentSchema), {
91
+ compositionSelection: requestBodyCompositionSelection,
90
92
  mode: "write",
91
93
  xml: isXml
92
- });
94
+ }, { schemaPath: ["requestBody"] });
93
95
  if (extractedExample !== void 0) {
94
96
  if (isFormData && typeof extractedExample === "object" && extractedExample !== null) return {
95
97
  mimeType: _contentType,
@@ -1 +1 @@
1
- {"version":3,"file":"process-body.js","names":[],"sources":["../../../../../../src/v2/blocks/operation-code-sample/helpers/operation-to-har/process-body.ts"],"sourcesContent":["import { json2xml } from '@scalar/helpers/file/json2xml'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { unpackProxyObject } from '@scalar/workspace-store/helpers/unpack-proxy'\nimport type { MediaTypeObject, RequestBodyObject } from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport { getExampleFromSchema } from '@v2/blocks/operation-code-sample/helpers/get-example-from-schema'\nimport type { Param, PostData } from 'har-format'\n\nimport { getExample } from '@/v2/blocks/operation-block/helpers/get-example'\n\nimport type { OperationToHarProps } from './operation-to-har'\n\ntype ProcessBodyProps = Pick<OperationToHarProps, 'contentType' | 'example'> & {\n requestBody: RequestBodyObject\n}\n\ntype MultipartEncodingMap = MediaTypeObject['encoding']\n\n/**\n * Converts an object to an array of form parameters\n * @param obj - The object to convert\n * @returns Array of form parameters with name and value properties\n */\nconst objectToFormParams = (\n obj: object | { name: string; value: unknown; isDisabled: boolean }[],\n encoding?: MultipartEncodingMap,\n parentKey?: string,\n): Param[] => {\n const params: Param[] = []\n\n /** Ensure we do not include disabled items */\n const entries = Array.isArray(obj)\n ? obj.filter((item) => !item.isDisabled).map((item) => [item.name, item.value])\n : Object.entries(obj)\n\n for (const [key, value] of entries) {\n if (value === undefined || value === null) {\n continue\n }\n\n const partContentType = parentKey ? undefined : encoding?.[key]?.contentType\n\n // Handle File objects by converting them to 'BINARY'\n if (value instanceof File) {\n const file = unpackProxyObject(value)\n params.push({ name: key, value: `@${file.name}`, ...(partContentType ? { contentType: partContentType } : {}) })\n }\n // Multipart encodings can override the entire top-level part payload\n else if (partContentType && typeof value === 'object') {\n params.push({\n name: key,\n value: JSON.stringify(unpackProxyObject(value)),\n contentType: partContentType,\n })\n }\n // Handle arrays by adding each item with the same key\n else if (Array.isArray(value)) {\n for (const item of value) {\n // Check if array item is a File\n if (item instanceof File) {\n const file = unpackProxyObject(item)\n params.push({ name: key, value: `@${file.name}` })\n } else {\n params.push({ name: key, value: String(item) })\n }\n }\n }\n // Handle nested objects by flattening them\n else if (typeof value === 'object') {\n const nestedParams = objectToFormParams(value, undefined, key)\n\n for (const param of nestedParams) {\n params.push({ name: `${key}.${param.name}`, value: param.value })\n }\n } else {\n params.push({ name: key, value: String(value), ...(partContentType ? { contentType: partContentType } : {}) })\n }\n }\n\n return params\n}\n\n/**\n * Processes the request body and returns the processed data\n * Returns undefined if no example is found\n */\nexport const processBody = ({ requestBody, contentType, example }: ProcessBodyProps): PostData | undefined => {\n const _contentType = contentType || Object.keys(requestBody.content)[0] || ''\n const formatBinaryFile = (file: File) => {\n const unwrappedFile = unpackProxyObject(file)\n return `@${unwrappedFile.name || 'filename'}`\n }\n const encoding = requestBody.content[_contentType]?.encoding\n\n // Check if this is a form data content type\n const isFormData = _contentType === 'multipart/form-data' || _contentType === 'application/x-www-form-urlencoded'\n\n // Check if this is an XML content type\n const isXml = _contentType === 'application/xml'\n\n // Get the example value\n const _example = getExample(requestBody, example, contentType)?.value\n\n // Return the provided top level example\n if (typeof _example !== 'undefined') {\n const exampleValue = _example !== null && typeof _example === 'object' ? unpackProxyObject(_example) : _example\n\n if (isFormData && typeof exampleValue === 'object' && exampleValue !== null) {\n return {\n mimeType: _contentType,\n params: objectToFormParams(exampleValue, _contentType === 'multipart/form-data' ? encoding : undefined),\n }\n }\n\n if (isXml && typeof exampleValue === 'object' && exampleValue !== null) {\n return {\n mimeType: _contentType,\n text: json2xml(exampleValue),\n }\n }\n\n if (exampleValue instanceof File) {\n return {\n mimeType: _contentType,\n text: formatBinaryFile(exampleValue),\n }\n }\n\n return {\n mimeType: _contentType,\n text: typeof exampleValue === 'string' ? exampleValue : JSON.stringify(exampleValue),\n }\n }\n\n // Try to extract examples from the schema\n const contentSchema = getResolvedRef(requestBody.content[_contentType]?.schema)\n if (typeof contentSchema !== 'undefined') {\n const extractedExample = getExampleFromSchema(contentSchema, {\n mode: 'write',\n xml: isXml,\n })\n\n if (extractedExample !== undefined) {\n if (isFormData && typeof extractedExample === 'object' && extractedExample !== null) {\n return {\n mimeType: _contentType,\n params: objectToFormParams(extractedExample, _contentType === 'multipart/form-data' ? encoding : undefined),\n }\n }\n\n if (isXml && typeof extractedExample === 'object' && extractedExample !== null) {\n return {\n mimeType: _contentType,\n text: json2xml(extractedExample),\n }\n }\n\n return {\n mimeType: _contentType,\n text: typeof extractedExample === 'string' ? extractedExample : JSON.stringify(extractedExample),\n }\n }\n }\n\n return undefined\n}\n"],"mappings":";;;;;;;;;;;AAsBA,IAAM,sBACJ,KACA,UACA,cACY;CACZ,MAAM,SAAkB,EAAE;;CAG1B,MAAM,UAAU,MAAM,QAAQ,IAAI,GAC9B,IAAI,QAAQ,SAAS,CAAC,KAAK,WAAW,CAAC,KAAK,SAAS,CAAC,KAAK,MAAM,KAAK,MAAM,CAAC,GAC7E,OAAO,QAAQ,IAAI;AAEvB,MAAK,MAAM,CAAC,KAAK,UAAU,SAAS;AAClC,MAAI,UAAU,KAAA,KAAa,UAAU,KACnC;EAGF,MAAM,kBAAkB,YAAY,KAAA,IAAY,WAAW,MAAM;AAGjE,MAAI,iBAAiB,MAAM;GACzB,MAAM,OAAO,kBAAkB,MAAM;AACrC,UAAO,KAAK;IAAE,MAAM;IAAK,OAAO,IAAI,KAAK;IAAQ,GAAI,kBAAkB,EAAE,aAAa,iBAAiB,GAAG,EAAE;IAAG,CAAC;aAGzG,mBAAmB,OAAO,UAAU,SAC3C,QAAO,KAAK;GACV,MAAM;GACN,OAAO,KAAK,UAAU,kBAAkB,MAAM,CAAC;GAC/C,aAAa;GACd,CAAC;WAGK,MAAM,QAAQ,MAAM,CAC3B,MAAK,MAAM,QAAQ,MAEjB,KAAI,gBAAgB,MAAM;GACxB,MAAM,OAAO,kBAAkB,KAAK;AACpC,UAAO,KAAK;IAAE,MAAM;IAAK,OAAO,IAAI,KAAK;IAAQ,CAAC;QAElD,QAAO,KAAK;GAAE,MAAM;GAAK,OAAO,OAAO,KAAK;GAAE,CAA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AAI,OAAO,kBAAkB,aAAa;EACxC,MAAM,mBAAmB,qBAAqB,eAAe;GAC3D,MAAM;GACN,KAAK;GACN,CAAC;AAEF,MAAI,qBAAqB,KAAA,GAAW;AAClC,OAAI,cAAc,OAAO,qBAAqB,YAAY,qBAAqB,KAC7E,QAAO;IACL,UAAU;IACV,QAAQ,mBAAmB,kBAAkB,iBAAiB,wBAAwB,WAAW,KAAA,EAAU;IAC5G;AAGH,OAAI,SAAS,OAAO,qBAAqB,YAAY,qBAAqB,KACxE,QAAO;IACL,UAAU;IACV,MAAM,SAAS,iBAAiB;IACjC;AAGH,UAAO;IACL,UAAU;IACV,MAAM,OAAO,qBAAqB,WAAW,mBAAmB,KAAK,UAAU,iBAAiB;IACjG"}
1
+ {"version":3,"file":"process-body.js","names":[],"sources":["../../../../../../src/v2/blocks/operation-code-sample/helpers/operation-to-har/process-body.ts"],"sourcesContent":["import { json2xml } from '@scalar/helpers/file/json2xml'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { unpackProxyObject } from '@scalar/workspace-store/helpers/unpack-proxy'\nimport type {\n MediaTypeObject,\n RequestBodyObject,\n SchemaObject,\n} from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport { getExampleFromSchema } from '@v2/blocks/operation-code-sample/helpers/get-example-from-schema'\nimport { getResolvedRefDeep } from '@v2/blocks/operation-code-sample/helpers/get-resolved-ref-deep'\nimport type { Param, PostData } from 'har-format'\n\nimport { getExample } from '@/v2/blocks/operation-block/helpers/get-example'\n\nimport type { OperationToHarProps } from './operation-to-har'\n\ntype ProcessBodyProps = Pick<OperationToHarProps, 'contentType' | 'example' | 'requestBodyCompositionSelection'> & {\n requestBody: RequestBodyObject\n}\n\ntype MultipartEncodingMap = MediaTypeObject['encoding']\n\n/**\n * Converts an object to an array of form parameters\n * @param obj - The object to convert\n * @returns Array of form parameters with name and value properties\n */\nconst objectToFormParams = (\n obj: object | { name: string; value: unknown; isDisabled: boolean }[],\n encoding?: MultipartEncodingMap,\n parentKey?: string,\n): Param[] => {\n const params: Param[] = []\n\n /** Ensure we do not include disabled items */\n const entries = Array.isArray(obj)\n ? obj.filter((item) => !item.isDisabled).map((item) => [item.name, item.value])\n : Object.entries(obj)\n\n for (const [key, value] of entries) {\n if (value === undefined || value === null) {\n continue\n }\n\n const partContentType = parentKey ? undefined : encoding?.[key]?.contentType\n\n // Handle File objects by converting them to 'BINARY'\n if (value instanceof File) {\n const file = unpackProxyObject(value)\n params.push({ name: key, value: `@${file.name}`, ...(partContentType ? { contentType: partContentType } : {}) })\n }\n // Multipart encodings can override the entire top-level part payload\n else if (partContentType && typeof value === 'object') {\n params.push({\n name: key,\n value: JSON.stringify(unpackProxyObject(value)),\n contentType: partContentType,\n })\n }\n // Handle arrays by adding each item with the same key\n else if (Array.isArray(value)) {\n for (const item of value) {\n // Check if array item is a File\n if (item instanceof File) {\n const file = unpackProxyObject(item)\n params.push({ name: key, value: `@${file.name}` })\n } else {\n params.push({ name: key, value: String(item) })\n }\n }\n }\n // Handle nested objects by flattening them\n else if (typeof value === 'object') {\n const nestedParams = objectToFormParams(value, undefined, key)\n\n for (const param of nestedParams) {\n params.push({ name: `${key}.${param.name}`, value: param.value })\n }\n } else {\n params.push({ name: key, value: String(value), ...(partContentType ? { contentType: partContentType } : {}) })\n }\n }\n\n return params\n}\n\n/**\n * Processes the request body and returns the processed data\n * Returns undefined if no example is found\n */\nexport const processBody = ({\n requestBody,\n contentType,\n example,\n requestBodyCompositionSelection,\n}: ProcessBodyProps): PostData | undefined => {\n const _contentType = contentType || Object.keys(requestBody.content)[0] || ''\n const formatBinaryFile = (file: File) => {\n const unwrappedFile = unpackProxyObject(file)\n return `@${unwrappedFile.name || 'filename'}`\n }\n const encoding = requestBody.content[_contentType]?.encoding\n\n // Check if this is a form data content type\n const isFormData = _contentType === 'multipart/form-data' || _contentType === 'application/x-www-form-urlencoded'\n\n // Check if this is an XML content type\n const isXml = _contentType === 'application/xml'\n\n // Get the example value\n const _example = getExample(requestBody, example, contentType)?.value\n\n // Return the provided top level example\n if (typeof _example !== 'undefined') {\n const exampleValue = _example !== null && typeof _example === 'object' ? unpackProxyObject(_example) : _example\n\n if (isFormData && typeof exampleValue === 'object' && exampleValue !== null) {\n return {\n mimeType: _contentType,\n params: objectToFormParams(exampleValue, _contentType === 'multipart/form-data' ? encoding : undefined),\n }\n }\n\n if (isXml && typeof exampleValue === 'object' && exampleValue !== null) {\n return {\n mimeType: _contentType,\n text: json2xml(exampleValue),\n }\n }\n\n if (exampleValue instanceof File) {\n return {\n mimeType: _contentType,\n text: formatBinaryFile(exampleValue),\n }\n }\n\n return {\n mimeType: _contentType,\n text: typeof exampleValue === 'string' ? exampleValue : JSON.stringify(exampleValue),\n }\n }\n\n // Try to extract examples from the schema\n const contentSchema = getResolvedRef(requestBody.content[_contentType]?.schema)\n if (typeof contentSchema !== 'undefined') {\n const resolvedContentSchema = getResolvedRefDeep(contentSchema) as SchemaObject\n const extractedExample = getExampleFromSchema(\n resolvedContentSchema,\n {\n compositionSelection: requestBodyCompositionSelection,\n mode: 'write',\n xml: isXml,\n },\n {\n schemaPath: ['requestBody'],\n },\n )\n\n if (extractedExample !== undefined) {\n if (isFormData && typeof extractedExample === 'object' && extractedExample !== null) {\n return {\n mimeType: _contentType,\n params: objectToFormParams(extractedExample, _contentType === 'multipart/form-data' ? encoding : undefined),\n }\n }\n\n if (isXml && typeof extractedExample === 'object' && extractedExample !== null) {\n return {\n mimeType: _contentType,\n text: json2xml(extractedExample),\n }\n }\n\n return {\n mimeType: _contentType,\n text: typeof extractedExample === 'string' ? extractedExample : JSON.stringify(extractedExample),\n }\n }\n }\n\n return undefined\n}\n"],"mappings":";;;;;;;;;;;;AA2BA,IAAM,sBACJ,KACA,UACA,cACY;CACZ,MAAM,SAAkB,EAAE;;CAG1B,MAAM,UAAU,MAAM,QAAQ,IAAI,GAC9B,IAAI,QAAQ,SAAS,CAAC,KAAK,WAAW,CAAC,KAAK,SAAS,CAA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BAAmB,KAAK,UAAU,iBAAiB;IACjG"}
@@ -26,6 +26,7 @@ type __VLS_Props = {
26
26
  path: string;
27
27
  plugins: ClientPlugin[];
28
28
  proxyUrl: string;
29
+ requestBodyCompositionSelection?: Record<string, number>;
29
30
  securityRequirements: OpenApiDocument['security'];
30
31
  securitySchemes: MergedSecuritySchemes;
31
32
  selectedClient: WorkspaceStore['workspace']['x-scalar-default-client'];
@@ -1 +1 @@
1
- {"version":3,"file":"RequestBlock.vue.d.ts","sourceRoot":"","sources":["../../../../src/v2/blocks/request-block/RequestBlock.vue"],"names":[],"mappings":"AAikBA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAA;AAEnE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAA;AAC7D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAA;AACpE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAA;AAC7E,OAAO,KAAK,EAEV,QAAQ,EACR,iBAAiB,EAClB,MAAM,gCAAgC,CAAA;AAGvC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2EAA2E,CAAA;AACnH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qEAAqE,CAAA;AACxG,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,YAAY,EACb,MAAM,8DAA8D,CAAA;AAKrE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AAI3C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAA;AAU1E,OAAO,EAEL,KAAK,qBAAqB,EAC3B,MAAM,wCAAwC,CAAA;AAC/C,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,6DAA6D,CAAA;AAW7G,MAAM,MAAM,oBAAoB,GAAG,aAAa,GAAG;IACjD,QAAQ,EAAE,UAAU,GAAG,WAAW,CAAA;CACnC,CAAA;AAED,KAAK,WAAW,GAAG;IACjB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QAAA,MAAM,YAAY,kSAEhB,CAAC;wBACkB,OAAO,YAAY;AAAxC,wBAAyC"}
@@ -2,7 +2,7 @@ import _plugin_vue_export_helper_default from "../../../_virtual/_plugin-vue_exp
2
2
  import RequestBlock_vue_vue_type_script_setup_true_lang_default from "./RequestBlock.vue.script.js";
3
3
  /* empty css */
4
4
  //#region src/v2/blocks/request-block/RequestBlock.vue
5
- var RequestBlock_default = /* @__PURE__ */ _plugin_vue_export_helper_default(RequestBlock_vue_vue_type_script_setup_true_lang_default, [["__scopeId", "data-v-98af86fe"]]);
5
+ var RequestBlock_default = /* @__PURE__ */ _plugin_vue_export_helper_default(RequestBlock_vue_vue_type_script_setup_true_lang_default, [["__scopeId", "data-v-e0c182d2"]]);
6
6
  //#endregion
7
7
  export { RequestBlock_default as default };
8
8
 
@@ -1 +1 @@
1
- {"version":3,"file":"RequestBlock.vue.js","names":[],"sources":["../../../../src/v2/blocks/request-block/RequestBlock.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { ScalarErrorBoundary } from '@scalar/components'\nimport { canMethodHaveBody } from '@scalar/helpers/http/can-method-have-body'\nimport type { HttpMethod } from '@scalar/helpers/http/http-methods'\nimport { REGEX } from '@scalar/helpers/regex/regex-helpers'\nimport type { ClientPlugin } from '@scalar/oas-utils/helpers'\nimport type { WorkspaceStore } from '@scalar/workspace-store/client'\nimport type { SelectedSecurity } from '@scalar/workspace-store/entities/auth'\nimport type {\n ApiReferenceEvents,\n AuthMeta,\n WorkspaceEventBus,\n} from '@scalar/workspace-store/events'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { unpackProxyObject } from '@scalar/workspace-store/helpers/unpack-proxy'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type {\n OpenApiDocument,\n OperationObject,\n ServerObject,\n} from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport { computed, ref, useId, watch } from 'vue'\n\nimport SectionFilter from '@/components/SectionFilter.vue'\nimport ViewLayoutSection from '@/components/ViewLayout/ViewLayoutSection.vue'\nimport type { ClientLayout } from '@/hooks'\nimport { filterGlobalCookie } from '@/v2/blocks/operation-block/helpers/filter-global-cookies'\nimport { getExample } from '@/v2/blocks/operation-block/helpers/get-example'\nimport { getResolvedUrl } from '@/v2/blocks/operation-block/helpers/get-resolved-url'\nimport type { ClientOptionGroup } from '@/v2/blocks/operation-code-sample'\nimport RequestBody from '@/v2/blocks/request-block/components/RequestBody.vue'\nimport RequestCodeSnippet from '@/v2/blocks/request-block/components/RequestCodeSnippet.vue'\nimport RequestParams from '@/v2/blocks/request-block/components/RequestParams.vue'\nimport type { TableRow } from '@/v2/blocks/request-block/components/RequestTableRow.vue'\nimport { createParameterHandlers } from '@/v2/blocks/request-block/helpers/create-parameter-handlers'\nimport { getDefaultHeaders } from '@/v2/blocks/request-block/helpers/get-default-headers'\nimport { getParameterSchema } from '@/v2/blocks/request-block/helpers/get-parameter-schema'\nimport { groupBy } from '@/v2/blocks/request-block/helpers/group-by'\nimport { isParamDisabled } from '@/v2/blocks/request-block/helpers/is-param-disabled'\nimport {\n AuthSelector,\n type MergedSecuritySchemes,\n} from '@/v2/blocks/scalar-auth-selector-block'\nimport type { SecuritySchemeObjectSecret } from '@/v2/blocks/scalar-auth-selector-block/helpers/secret-types'\n\ntype Filter =\n | 'All'\n | 'Auth'\n | 'Variables'\n | 'Cookies'\n | 'Headers'\n | 'Query'\n | 'Body'\n\nexport type ExtendedScalarCookie = XScalarCookie & {\n location: 'document' | 'workspace'\n}\n\nconst {\n authMeta = { type: 'document' },\n clientOptions,\n environment,\n eventBus,\n exampleKey,\n globalCookies,\n layout,\n method,\n operation,\n path,\n plugins,\n proxyUrl,\n securityRequirements,\n securitySchemes,\n selectedClient,\n selectedSecurity,\n selectedSecuritySchemes,\n server,\n} = defineProps<{\n authMeta: AuthMeta\n clientOptions: ClientOptionGroup[]\n environment: XScalarEnvironment\n eventBus: WorkspaceEventBus\n exampleKey: string\n globalCookies: ExtendedScalarCookie[]\n layout: ClientLayout\n method: HttpMethod\n operation: OperationObject\n path: string\n plugins: ClientPlugin[]\n proxyUrl: string\n securityRequirements: OpenApiDocument['security']\n securitySchemes: MergedSecuritySchemes\n selectedClient: WorkspaceStore['workspace']['x-scalar-default-client']\n selectedSecurity: SelectedSecurity\n selectedSecuritySchemes: SecuritySchemeObjectSecret[]\n server: ServerObject | null\n}>()\n\n/** Operation metadata used across event emissions */\nconst meta = computed(() => ({\n method,\n path,\n exampleKey,\n}))\n\n/** Parameters grouped by type (path, query, header, cookie) */\nconst sections = computed(() =>\n groupBy(\n operation.parameters?.map((param) => getResolvedRef(param)) ?? [],\n 'in',\n (param) => {\n const example = getExample(param, exampleKey, undefined)\n\n return {\n name: param.name,\n value: example?.value ?? '',\n description: param.description,\n schema: getParameterSchema(param),\n isRequired: param.required,\n isDisabled: isParamDisabled(param, example),\n originalParameter: param,\n } as TableRow\n },\n ),\n)\n\n// Generate a reverse map for fast lookup of headers by the name\nconst headersMap = computed(() =>\n groupBy(\n sections.value.header?.map((it) => ({\n ...it,\n name: it.name.toLowerCase(),\n })) ?? [],\n 'name',\n ),\n)\n\nconst autoGeneratedHeaders = computed(() =>\n getDefaultHeaders({ method, operation, exampleKey }),\n)\n\nconst defaultHeaders = computed(() => {\n const disableParameters =\n operation['x-scalar-disable-parameters']?.['default-headers']?.[\n exampleKey\n ] ?? {}\n\n return autoGeneratedHeaders.value.map((it) => {\n const realHeader = headersMap.value[it.name.toLowerCase()]?.[0]\n\n return {\n name: it.name,\n value: it.defaultValue,\n schema: undefined,\n isOverridden: realHeader && !realHeader?.isDisabled,\n isReadonly: true,\n isDisabled: disableParameters[it.name.toLowerCase()] ?? false,\n } satisfies TableRow\n })\n})\n\nconst headers = computed(() => [\n ...defaultHeaders.value,\n ...(sections.value.header ?? []),\n])\n\nconst defaultCookies = computed(() => {\n const resolvedUrl = getResolvedUrl({\n environment,\n server,\n path,\n pathVariables: {},\n })\n\n const disabledGlobalCookies =\n operation['x-scalar-disable-parameters']?.['global-cookies']?.[\n exampleKey\n ] ?? {}\n\n return (\n globalCookies\n ?.filter((cookie) =>\n filterGlobalCookie({\n cookie,\n url: resolvedUrl,\n // Do not filter global cookies for the default cookies section (it's already filtered in the buildRequestCookieHeader function)\n // This is because we still want to show them on the UI\n disabledGlobalCookies: {},\n }),\n )\n .map((it) => ({\n name: it.name,\n value: it.value,\n globalRoute:\n it.location === 'document'\n ? ({ page: 'document', path: 'cookies' } as const)\n : ({ page: 'workspace', path: 'cookies' } as const),\n isReadonly: true,\n isDisabled: disabledGlobalCookies[it.name.toLowerCase()] ?? false,\n })) ?? ([] satisfies TableRow[])\n )\n})\n\nconst cookies = computed(() => [\n ...(defaultCookies.value ?? []),\n ...(sections.value.cookie ?? []),\n])\n\n/** Currently selected filter for the request sections */\nconst selectedFilter = ref<Filter>('All')\n\n/** Available operation sections */\nconst OPERATION_SECTIONS: readonly Filter[] = [\n 'Auth',\n 'Variables',\n 'Cookies',\n 'Headers',\n 'Query',\n 'Body',\n] as const\n\n/**\n * Pre-generated stable IDs for all possible filter sections.\n * These are created once at setup time to avoid regenerating IDs on re-render.\n */\nconst sectionIds: Record<Filter, string> = {\n All: useId(),\n Auth: useId(),\n Variables: useId(),\n Cookies: useId(),\n Headers: useId(),\n Query: useId(),\n Body: useId(),\n}\n\n/** Filters available based on operation state */\nconst filters = computed<Filter[]>(() => {\n const availableFilters = new Set<Filter>(['All', ...OPERATION_SECTIONS])\n\n if (!sections.value.path?.length) {\n availableFilters.delete('Variables')\n }\n if (!canMethodHaveBody(method)) {\n availableFilters.delete('Body')\n }\n if (isAuthHidden.value) {\n availableFilters.delete('Auth')\n }\n\n return [...availableFilters]\n})\n\n/**\n * Map available filters to their pre-generated stable IDs.\n * Only includes IDs for filters that are currently available.\n */\nconst filterIds = computed(\n () =>\n Object.fromEntries(\n filters.value.map((section) => [section, sectionIds[section]]),\n ) as Record<Filter, string>,\n)\n\n/**\n * Hide auth selector in readonly mode when no security schemes are defined.\n * This keeps the UI clean when there are no authentication options available.\n */\nconst isAuthHidden = computed(\n () => layout === 'modal' && !Object.keys(securitySchemes ?? {}).length,\n)\n\n/**\n * Keep auth available for unauthenticated operations, but collapse it by default\n * in readonly modal layouts unless a requirement or manual selection exists.\n */\nconst isAuthDefaultOpen = computed(\n () =>\n layout !== 'modal' ||\n Boolean(\n securityRequirements?.length || selectedSecurity.selectedSchemes.length,\n ),\n)\n\n/** Get a sensible placeholder for the request name input */\nconst requestNamePlaceholder = computed(() => {\n if (operation.summary) {\n return operation.summary\n }\n const cleanPath = path.replace(REGEX.PROTOCOL, '')\n return cleanPath || 'Request Name'\n})\n\n/** Check if the section should be shown based on the selected filter */\nconst isSectionVisible = (section: Filter): boolean => {\n return selectedFilter.value === 'All' || selectedFilter.value === section\n}\n\n/**\n * Reset filter to 'All' if Body filter is selected but method changes to one that cannot have a body.\n * This prevents showing an empty Body section when switching methods.\n */\nwatch(\n () => method,\n (newMethod) => {\n if (selectedFilter.value === 'Body' && !canMethodHaveBody(newMethod)) {\n selectedFilter.value = 'All'\n }\n },\n)\n\n/** Handle operation summary updates */\nconst handleSummaryUpdate = (event: Event): void => {\n const summary = (event.target as HTMLInputElement).value\n eventBus.emit('operation:update:meta', {\n meta: meta.value,\n payload: { summary: summary.trim() },\n })\n}\n\n/** Parameter handlers */\nconst parameterHandlers = computed(() => ({\n path: createParameterHandlers('path', eventBus, meta.value, {\n context: sections.value.path ?? [],\n }),\n cookie: createParameterHandlers('cookie', eventBus, meta.value, {\n context: cookies.value ?? [],\n globalParameters: defaultCookies.value.length,\n }),\n header: createParameterHandlers('header', eventBus, meta.value, {\n context: headers.value,\n defaultParameters: defaultHeaders.value.length,\n }),\n query: createParameterHandlers('query', eventBus, meta.value, {\n context: sections.value.query ?? [],\n }),\n}))\n\n/** Handle request body content type update */\nconst handleUpdateContentType = (payload: { value: string }): void =>\n eventBus.emit('operation:update:requestBody:contentType', {\n payload: { contentType: payload.value },\n meta: meta.value,\n })\n\n/** Handle request body value update */\nconst handleUpdateBodyValue = ({\n payload,\n contentType,\n}: Pick<\n ApiReferenceEvents['operation:update:requestBody:value'],\n 'payload' | 'contentType'\n>): void => {\n const debounceKey =\n typeof payload === 'string'\n ? `update:requestBody:value-${contentType}`\n : undefined\n\n eventBus.emit(\n 'operation:update:requestBody:value',\n {\n payload,\n contentType,\n meta: meta.value,\n },\n {\n debounceKey,\n },\n )\n}\n\n/** Handle request body value update */\nconst handleUpdateBodyFormValue = ({\n payload,\n contentType,\n}: Pick<\n ApiReferenceEvents['operation:update:requestBody:formValue'],\n 'payload' | 'contentType'\n>): void => {\n const debounceKey = `update:requestBody:${contentType}-form-value`\n\n eventBus.emit(\n 'operation:update:requestBody:formValue',\n {\n payload: payload.map((row) => unpackProxyObject(row, { depth: 1 })),\n contentType,\n meta: meta.value,\n },\n {\n debounceKey,\n },\n )\n}\n\nconst labelRequestNameId = useId()\n\n/** Allow updating the operation extensions for the plugins */\nconst updateOperationExtension = (\n payload: ApiReferenceEvents['operation:update:extension']['payload'],\n): void =>\n eventBus.emit('operation:update:extension', { payload, meta: meta.value })\n</script>\n<template>\n <ViewLayoutSection :aria-label=\"`Request: ${operation.summary}`\">\n <template #title>\n <div\n class=\"group pointer-events-none flex flex-1 items-center gap-1 lg:pr-24\">\n <label\n v-if=\"layout !== 'modal'\"\n class=\"pointer-events-auto absolute top-0 left-0 h-full w-full cursor-text opacity-0\"\n :for=\"labelRequestNameId\" />\n <input\n v-if=\"layout !== 'modal'\"\n :id=\"labelRequestNameId\"\n class=\"text-c-1 group-hover-input pointer-events-auto relative z-10 -ml-0.5 h-8 w-full rounded pl-1.25 has-[:focus-visible]:outline md:-ml-1.25\"\n :placeholder=\"requestNamePlaceholder\"\n :value=\"operation.summary\"\n @blur=\"handleSummaryUpdate\" />\n <span\n v-else\n class=\"text-c-1 flex h-8 items-center\">\n {{ operation.summary }}\n </span>\n </div>\n <SectionFilter\n v-model=\"selectedFilter\"\n :filterIds=\"filterIds\"\n :filters=\"filters\" />\n </template>\n\n <div\n :id=\"filterIds.All\"\n class=\"request-section-content custom-scroll relative flex flex-1 flex-col\"\n :role=\"selectedFilter === 'All' ? 'tabpanel' : 'none'\">\n <!-- Auth Selector -->\n <AuthSelector\n v-show=\"isSectionVisible('Auth') && !isAuthHidden\"\n :id=\"filterIds.Auth\"\n :createAnySecurityScheme=\"layout !== 'modal'\"\n :defaultOpen=\"isAuthDefaultOpen\"\n :environment\n :eventBus\n :meta=\"authMeta\"\n :proxyUrl\n :securityRequirements\n :securitySchemes\n :selectedSecurity\n :selectedSecuritySchemes\n :server\n title=\"Authentication\" />\n\n <!-- Variables (Path Parameters) -->\n <RequestParams\n v-show=\"isSectionVisible('Variables') && sections.path?.length\"\n :id=\"filterIds.Variables\"\n :environment\n :eventBus\n :exampleKey\n :rows=\"sections.path ?? []\"\n :showAddRowPlaceholder=\"false\"\n title=\"Variables\"\n v-on=\"parameterHandlers.path\" />\n\n <!-- Cookies -->\n <RequestParams\n v-show=\"isSectionVisible('Cookies')\"\n :id=\"filterIds.Cookies\"\n :environment\n :eventBus\n :exampleKey\n :rows=\"cookies ?? []\"\n :showAddRowPlaceholder=\"true\"\n title=\"Cookies\"\n v-on=\"parameterHandlers.cookie\" />\n\n <!-- Headers -->\n <RequestParams\n v-show=\"isSectionVisible('Headers')\"\n :id=\"filterIds.Headers\"\n :environment\n :eventBus\n :exampleKey\n :rows=\"headers ?? []\"\n title=\"Headers\"\n v-on=\"parameterHandlers.header\" />\n\n <!-- Query Parameters -->\n <RequestParams\n v-show=\"isSectionVisible('Query')\"\n :id=\"filterIds.Query\"\n :environment\n :eventBus\n :exampleKey\n :rows=\"sections.query ?? []\"\n title=\"Query Parameters\"\n v-on=\"parameterHandlers.query\" />\n\n <!-- Request Body -->\n <RequestBody\n v-show=\"isSectionVisible('Body') && canMethodHaveBody(method)\"\n :id=\"filterIds.Body\"\n :environment\n :exampleKey\n :requestBody=\"getResolvedRef(operation.requestBody)\"\n title=\"Request Body\"\n @update:contentType=\"handleUpdateContentType\"\n @update:formValue=\"handleUpdateBodyFormValue\"\n @update:value=\"handleUpdateBodyValue\" />\n\n <!-- Inject request section plugin components -->\n <ScalarErrorBoundary\n v-for=\"(plugin, index) in plugins\"\n :key=\"index\">\n <component\n :is=\"plugin.components.request.component\"\n v-if=\"plugin?.components?.request\"\n v-show=\"selectedFilter === 'All'\"\n :operation\n v-bind=\"plugin.components.request.additionalProps\"\n @operation:update:extension=\"updateOperationExtension\" />\n </ScalarErrorBoundary>\n\n <!-- Spacer -->\n <div class=\"flex grow\" />\n <!-- Code Snippet -->\n <RequestCodeSnippet\n v-show=\"selectedFilter === 'All'\"\n :clientOptions\n :eventBus\n :globalCookies=\"globalCookies\"\n integration=\"client\"\n :method\n :operation\n :path\n :securitySchemes=\"selectedSecuritySchemes\"\n :selectedClient\n :selectedContentType=\"\n getResolvedRef(operation.requestBody)?.[\n 'x-scalar-selected-content-type'\n ]?.[exampleKey]\n \"\n :selectedServer=\"server ?? undefined\" />\n </div>\n </ViewLayoutSection>\n</template>\n<style scoped>\n.request-section-content {\n --scalar-border-width: 0.5px;\n}\n.request-section-content-filter {\n box-shadow: 0 -10px 0 10px var(--scalar-background-1);\n}\n.request-item:focus-within .request-meta-buttons {\n opacity: 1;\n}\n.group-hover-input {\n border-width: var(--scalar-border-width);\n border-color: transparent;\n}\n.group:hover .group-hover-input {\n background: color-mix(\n in srgb,\n var(--scalar-background-1),\n var(--scalar-background-2)\n );\n border-color: var(--scalar-border-color);\n}\n.group-hover-input:focus {\n background: transparent !important;\n border-color: var(--scalar-border-color) !important;\n}\n</style>\n"],"mappings":""}
1
+ {"version":3,"file":"RequestBlock.vue.js","names":[],"sources":["../../../../src/v2/blocks/request-block/RequestBlock.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { ScalarErrorBoundary } from '@scalar/components'\nimport { canMethodHaveBody } from '@scalar/helpers/http/can-method-have-body'\nimport type { HttpMethod } from '@scalar/helpers/http/http-methods'\nimport { REGEX } from '@scalar/helpers/regex/regex-helpers'\nimport type { ClientPlugin } from '@scalar/oas-utils/helpers'\nimport type { WorkspaceStore } from '@scalar/workspace-store/client'\nimport type { SelectedSecurity } from '@scalar/workspace-store/entities/auth'\nimport type {\n ApiReferenceEvents,\n AuthMeta,\n WorkspaceEventBus,\n} from '@scalar/workspace-store/events'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { unpackProxyObject } from '@scalar/workspace-store/helpers/unpack-proxy'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type {\n OpenApiDocument,\n OperationObject,\n ServerObject,\n} from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport { computed, ref, useId, watch } from 'vue'\n\nimport SectionFilter from '@/components/SectionFilter.vue'\nimport ViewLayoutSection from '@/components/ViewLayout/ViewLayoutSection.vue'\nimport type { ClientLayout } from '@/hooks'\nimport { filterGlobalCookie } from '@/v2/blocks/operation-block/helpers/filter-global-cookies'\nimport { getExample } from '@/v2/blocks/operation-block/helpers/get-example'\nimport { getResolvedUrl } from '@/v2/blocks/operation-block/helpers/get-resolved-url'\nimport type { ClientOptionGroup } from '@/v2/blocks/operation-code-sample'\nimport RequestBody from '@/v2/blocks/request-block/components/RequestBody.vue'\nimport RequestCodeSnippet from '@/v2/blocks/request-block/components/RequestCodeSnippet.vue'\nimport RequestParams from '@/v2/blocks/request-block/components/RequestParams.vue'\nimport type { TableRow } from '@/v2/blocks/request-block/components/RequestTableRow.vue'\nimport { createParameterHandlers } from '@/v2/blocks/request-block/helpers/create-parameter-handlers'\nimport { getDefaultHeaders } from '@/v2/blocks/request-block/helpers/get-default-headers'\nimport { getParameterSchema } from '@/v2/blocks/request-block/helpers/get-parameter-schema'\nimport { groupBy } from '@/v2/blocks/request-block/helpers/group-by'\nimport { isParamDisabled } from '@/v2/blocks/request-block/helpers/is-param-disabled'\nimport {\n AuthSelector,\n type MergedSecuritySchemes,\n} from '@/v2/blocks/scalar-auth-selector-block'\nimport type { SecuritySchemeObjectSecret } from '@/v2/blocks/scalar-auth-selector-block/helpers/secret-types'\n\ntype Filter =\n | 'All'\n | 'Auth'\n | 'Variables'\n | 'Cookies'\n | 'Headers'\n | 'Query'\n | 'Body'\n\nexport type ExtendedScalarCookie = XScalarCookie & {\n location: 'document' | 'workspace'\n}\n\nconst {\n authMeta = { type: 'document' },\n clientOptions,\n environment,\n eventBus,\n exampleKey,\n globalCookies,\n layout,\n method,\n operation,\n path,\n plugins,\n proxyUrl,\n requestBodyCompositionSelection,\n securityRequirements,\n securitySchemes,\n selectedClient,\n selectedSecurity,\n selectedSecuritySchemes,\n server,\n} = defineProps<{\n authMeta: AuthMeta\n clientOptions: ClientOptionGroup[]\n environment: XScalarEnvironment\n eventBus: WorkspaceEventBus\n exampleKey: string\n globalCookies: ExtendedScalarCookie[]\n layout: ClientLayout\n method: HttpMethod\n operation: OperationObject\n path: string\n plugins: ClientPlugin[]\n proxyUrl: string\n requestBodyCompositionSelection?: Record<string, number>\n securityRequirements: OpenApiDocument['security']\n securitySchemes: MergedSecuritySchemes\n selectedClient: WorkspaceStore['workspace']['x-scalar-default-client']\n selectedSecurity: SelectedSecurity\n selectedSecuritySchemes: SecuritySchemeObjectSecret[]\n server: ServerObject | null\n}>()\n\n/** Operation metadata used across event emissions */\nconst meta = computed(() => ({\n method,\n path,\n exampleKey,\n}))\n\n/** Parameters grouped by type (path, query, header, cookie) */\nconst sections = computed(() =>\n groupBy(\n operation.parameters?.map((param) => getResolvedRef(param)) ?? [],\n 'in',\n (param) => {\n const example = getExample(param, exampleKey, undefined)\n\n return {\n name: param.name,\n value: example?.value ?? '',\n description: param.description,\n schema: getParameterSchema(param),\n isRequired: param.required,\n isDisabled: isParamDisabled(param, example),\n originalParameter: param,\n } as TableRow\n },\n ),\n)\n\n// Generate a reverse map for fast lookup of headers by the name\nconst headersMap = computed(() =>\n groupBy(\n sections.value.header?.map((it) => ({\n ...it,\n name: it.name.toLowerCase(),\n })) ?? [],\n 'name',\n ),\n)\n\nconst autoGeneratedHeaders = computed(() =>\n getDefaultHeaders({ method, operation, exampleKey }),\n)\n\nconst defaultHeaders = computed(() => {\n const disableParameters =\n operation['x-scalar-disable-parameters']?.['default-headers']?.[\n exampleKey\n ] ?? {}\n\n return autoGeneratedHeaders.value.map((it) => {\n const realHeader = headersMap.value[it.name.toLowerCase()]?.[0]\n\n return {\n name: it.name,\n value: it.defaultValue,\n schema: undefined,\n isOverridden: realHeader && !realHeader?.isDisabled,\n isReadonly: true,\n isDisabled: disableParameters[it.name.toLowerCase()] ?? false,\n } satisfies TableRow\n })\n})\n\nconst headers = computed(() => [\n ...defaultHeaders.value,\n ...(sections.value.header ?? []),\n])\n\nconst defaultCookies = computed(() => {\n const resolvedUrl = getResolvedUrl({\n environment,\n server,\n path,\n pathVariables: {},\n })\n\n const disabledGlobalCookies =\n operation['x-scalar-disable-parameters']?.['global-cookies']?.[\n exampleKey\n ] ?? {}\n\n return (\n globalCookies\n ?.filter((cookie) =>\n filterGlobalCookie({\n cookie,\n url: resolvedUrl,\n // Do not filter global cookies for the default cookies section (it's already filtered in the buildRequestCookieHeader function)\n // This is because we still want to show them on the UI\n disabledGlobalCookies: {},\n }),\n )\n .map((it) => ({\n name: it.name,\n value: it.value,\n globalRoute:\n it.location === 'document'\n ? ({ page: 'document', path: 'cookies' } as const)\n : ({ page: 'workspace', path: 'cookies' } as const),\n isReadonly: true,\n isDisabled: disabledGlobalCookies[it.name.toLowerCase()] ?? false,\n })) ?? ([] satisfies TableRow[])\n )\n})\n\nconst cookies = computed(() => [\n ...(defaultCookies.value ?? []),\n ...(sections.value.cookie ?? []),\n])\n\n/** Currently selected filter for the request sections */\nconst selectedFilter = ref<Filter>('All')\n\n/** Available operation sections */\nconst OPERATION_SECTIONS: readonly Filter[] = [\n 'Auth',\n 'Variables',\n 'Cookies',\n 'Headers',\n 'Query',\n 'Body',\n] as const\n\n/**\n * Pre-generated stable IDs for all possible filter sections.\n * These are created once at setup time to avoid regenerating IDs on re-render.\n */\nconst sectionIds: Record<Filter, string> = {\n All: useId(),\n Auth: useId(),\n Variables: useId(),\n Cookies: useId(),\n Headers: useId(),\n Query: useId(),\n Body: useId(),\n}\n\n/** Filters available based on operation state */\nconst filters = computed<Filter[]>(() => {\n const availableFilters = new Set<Filter>(['All', ...OPERATION_SECTIONS])\n\n if (!sections.value.path?.length) {\n availableFilters.delete('Variables')\n }\n if (!canMethodHaveBody(method)) {\n availableFilters.delete('Body')\n }\n if (isAuthHidden.value) {\n availableFilters.delete('Auth')\n }\n\n return [...availableFilters]\n})\n\n/**\n * Map available filters to their pre-generated stable IDs.\n * Only includes IDs for filters that are currently available.\n */\nconst filterIds = computed(\n () =>\n Object.fromEntries(\n filters.value.map((section) => [section, sectionIds[section]]),\n ) as Record<Filter, string>,\n)\n\n/**\n * Hide auth selector in readonly mode when no security schemes are defined.\n * This keeps the UI clean when there are no authentication options available.\n */\nconst isAuthHidden = computed(\n () => layout === 'modal' && !Object.keys(securitySchemes ?? {}).length,\n)\n\n/**\n * Keep auth available for unauthenticated operations, but collapse it by default\n * in readonly modal layouts unless a requirement or manual selection exists.\n */\nconst isAuthDefaultOpen = computed(\n () =>\n layout !== 'modal' ||\n Boolean(\n securityRequirements?.length || selectedSecurity.selectedSchemes.length,\n ),\n)\n\n/** Get a sensible placeholder for the request name input */\nconst requestNamePlaceholder = computed(() => {\n if (operation.summary) {\n return operation.summary\n }\n const cleanPath = path.replace(REGEX.PROTOCOL, '')\n return cleanPath || 'Request Name'\n})\n\n/** Check if the section should be shown based on the selected filter */\nconst isSectionVisible = (section: Filter): boolean => {\n return selectedFilter.value === 'All' || selectedFilter.value === section\n}\n\n/**\n * Reset filter to 'All' if Body filter is selected but method changes to one that cannot have a body.\n * This prevents showing an empty Body section when switching methods.\n */\nwatch(\n () => method,\n (newMethod) => {\n if (selectedFilter.value === 'Body' && !canMethodHaveBody(newMethod)) {\n selectedFilter.value = 'All'\n }\n },\n)\n\n/** Handle operation summary updates */\nconst handleSummaryUpdate = (event: Event): void => {\n const summary = (event.target as HTMLInputElement).value\n eventBus.emit('operation:update:meta', {\n meta: meta.value,\n payload: { summary: summary.trim() },\n })\n}\n\n/** Parameter handlers */\nconst parameterHandlers = computed(() => ({\n path: createParameterHandlers('path', eventBus, meta.value, {\n context: sections.value.path ?? [],\n }),\n cookie: createParameterHandlers('cookie', eventBus, meta.value, {\n context: cookies.value ?? [],\n globalParameters: defaultCookies.value.length,\n }),\n header: createParameterHandlers('header', eventBus, meta.value, {\n context: headers.value,\n defaultParameters: defaultHeaders.value.length,\n }),\n query: createParameterHandlers('query', eventBus, meta.value, {\n context: sections.value.query ?? [],\n }),\n}))\n\n/** Handle request body content type update */\nconst handleUpdateContentType = (payload: { value: string }): void =>\n eventBus.emit('operation:update:requestBody:contentType', {\n payload: { contentType: payload.value },\n meta: meta.value,\n })\n\n/** Handle request body value update */\nconst handleUpdateBodyValue = ({\n payload,\n contentType,\n}: Pick<\n ApiReferenceEvents['operation:update:requestBody:value'],\n 'payload' | 'contentType'\n>): void => {\n const debounceKey =\n typeof payload === 'string'\n ? `update:requestBody:value-${contentType}`\n : undefined\n\n eventBus.emit(\n 'operation:update:requestBody:value',\n {\n payload,\n contentType,\n meta: meta.value,\n },\n {\n debounceKey,\n },\n )\n}\n\n/** Handle request body value update */\nconst handleUpdateBodyFormValue = ({\n payload,\n contentType,\n}: Pick<\n ApiReferenceEvents['operation:update:requestBody:formValue'],\n 'payload' | 'contentType'\n>): void => {\n const debounceKey = `update:requestBody:${contentType}-form-value`\n\n eventBus.emit(\n 'operation:update:requestBody:formValue',\n {\n payload: payload.map((row) => unpackProxyObject(row, { depth: 1 })),\n contentType,\n meta: meta.value,\n },\n {\n debounceKey,\n },\n )\n}\n\nconst labelRequestNameId = useId()\n\n/** Allow updating the operation extensions for the plugins */\nconst updateOperationExtension = (\n payload: ApiReferenceEvents['operation:update:extension']['payload'],\n): void =>\n eventBus.emit('operation:update:extension', { payload, meta: meta.value })\n</script>\n<template>\n <ViewLayoutSection :aria-label=\"`Request: ${operation.summary}`\">\n <template #title>\n <div\n class=\"group pointer-events-none flex flex-1 items-center gap-1 lg:pr-24\">\n <label\n v-if=\"layout !== 'modal'\"\n class=\"pointer-events-auto absolute top-0 left-0 h-full w-full cursor-text opacity-0\"\n :for=\"labelRequestNameId\" />\n <input\n v-if=\"layout !== 'modal'\"\n :id=\"labelRequestNameId\"\n class=\"text-c-1 group-hover-input pointer-events-auto relative z-10 -ml-0.5 h-8 w-full rounded pl-1.25 has-[:focus-visible]:outline md:-ml-1.25\"\n :placeholder=\"requestNamePlaceholder\"\n :value=\"operation.summary\"\n @blur=\"handleSummaryUpdate\" />\n <span\n v-else\n class=\"text-c-1 flex h-8 items-center\">\n {{ operation.summary }}\n </span>\n </div>\n <SectionFilter\n v-model=\"selectedFilter\"\n :filterIds=\"filterIds\"\n :filters=\"filters\" />\n </template>\n\n <div\n :id=\"filterIds.All\"\n class=\"request-section-content custom-scroll relative flex flex-1 flex-col\"\n :role=\"selectedFilter === 'All' ? 'tabpanel' : 'none'\">\n <!-- Auth Selector -->\n <AuthSelector\n v-show=\"isSectionVisible('Auth') && !isAuthHidden\"\n :id=\"filterIds.Auth\"\n :createAnySecurityScheme=\"layout !== 'modal'\"\n :defaultOpen=\"isAuthDefaultOpen\"\n :environment\n :eventBus\n :meta=\"authMeta\"\n :proxyUrl\n :securityRequirements\n :securitySchemes\n :selectedSecurity\n :selectedSecuritySchemes\n :server\n title=\"Authentication\" />\n\n <!-- Variables (Path Parameters) -->\n <RequestParams\n v-show=\"isSectionVisible('Variables') && sections.path?.length\"\n :id=\"filterIds.Variables\"\n :environment\n :eventBus\n :exampleKey\n :rows=\"sections.path ?? []\"\n :showAddRowPlaceholder=\"false\"\n title=\"Variables\"\n v-on=\"parameterHandlers.path\" />\n\n <!-- Cookies -->\n <RequestParams\n v-show=\"isSectionVisible('Cookies')\"\n :id=\"filterIds.Cookies\"\n :environment\n :eventBus\n :exampleKey\n :rows=\"cookies ?? []\"\n :showAddRowPlaceholder=\"true\"\n title=\"Cookies\"\n v-on=\"parameterHandlers.cookie\" />\n\n <!-- Headers -->\n <RequestParams\n v-show=\"isSectionVisible('Headers')\"\n :id=\"filterIds.Headers\"\n :environment\n :eventBus\n :exampleKey\n :rows=\"headers ?? []\"\n title=\"Headers\"\n v-on=\"parameterHandlers.header\" />\n\n <!-- Query Parameters -->\n <RequestParams\n v-show=\"isSectionVisible('Query')\"\n :id=\"filterIds.Query\"\n :environment\n :eventBus\n :exampleKey\n :rows=\"sections.query ?? []\"\n title=\"Query Parameters\"\n v-on=\"parameterHandlers.query\" />\n\n <!-- Request Body -->\n <RequestBody\n v-show=\"isSectionVisible('Body') && canMethodHaveBody(method)\"\n :id=\"filterIds.Body\"\n :environment\n :exampleKey\n :requestBody=\"getResolvedRef(operation.requestBody)\"\n :requestBodyCompositionSelection\n title=\"Request Body\"\n @update:contentType=\"handleUpdateContentType\"\n @update:formValue=\"handleUpdateBodyFormValue\"\n @update:value=\"handleUpdateBodyValue\" />\n\n <!-- Inject request section plugin components -->\n <ScalarErrorBoundary\n v-for=\"(plugin, index) in plugins\"\n :key=\"index\">\n <component\n :is=\"plugin.components.request.component\"\n v-if=\"plugin?.components?.request\"\n v-show=\"selectedFilter === 'All'\"\n :operation\n v-bind=\"plugin.components.request.additionalProps\"\n @operation:update:extension=\"updateOperationExtension\" />\n </ScalarErrorBoundary>\n\n <!-- Spacer -->\n <div class=\"flex grow\" />\n <!-- Code Snippet -->\n <RequestCodeSnippet\n v-show=\"selectedFilter === 'All'\"\n :clientOptions\n :eventBus\n :globalCookies=\"globalCookies\"\n integration=\"client\"\n :method\n :operation\n :path\n :securitySchemes=\"selectedSecuritySchemes\"\n :selectedClient\n :selectedContentType=\"\n getResolvedRef(operation.requestBody)?.[\n 'x-scalar-selected-content-type'\n ]?.[exampleKey]\n \"\n :selectedServer=\"server ?? undefined\" />\n </div>\n </ViewLayoutSection>\n</template>\n<style scoped>\n.request-section-content {\n --scalar-border-width: 0.5px;\n}\n.request-section-content-filter {\n box-shadow: 0 -10px 0 10px var(--scalar-background-1);\n}\n.request-item:focus-within .request-meta-buttons {\n opacity: 1;\n}\n.group-hover-input {\n border-width: var(--scalar-border-width);\n border-color: transparent;\n}\n.group:hover .group-hover-input {\n background: color-mix(\n in srgb,\n var(--scalar-background-1),\n var(--scalar-background-2)\n );\n border-color: var(--scalar-border-color);\n}\n.group-hover-input:focus {\n background: transparent !important;\n border-color: var(--scalar-border-color) !important;\n}\n</style>\n"],"mappings":""}
@@ -46,6 +46,7 @@ var RequestBlock_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ d
46
46
  path: {},
47
47
  plugins: {},
48
48
  proxyUrl: {},
49
+ requestBodyCompositionSelection: {},
49
50
  securityRequirements: {},
50
51
  securitySchemes: {},
51
52
  selectedClient: {},
@@ -356,6 +357,7 @@ var RequestBlock_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ d
356
357
  environment: __props.environment,
357
358
  exampleKey: __props.exampleKey,
358
359
  requestBody: unref(getResolvedRef)(__props.operation.requestBody),
360
+ requestBodyCompositionSelection: __props.requestBodyCompositionSelection,
359
361
  title: "Request Body",
360
362
  "onUpdate:contentType": handleUpdateContentType,
361
363
  "onUpdate:formValue": handleUpdateBodyFormValue,
@@ -364,7 +366,8 @@ var RequestBlock_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ d
364
366
  "id",
365
367
  "environment",
366
368
  "exampleKey",
367
- "requestBody"
369
+ "requestBody",
370
+ "requestBodyCompositionSelection"
368
371
  ]), [[vShow, isSectionVisible("Body") && unref(canMethodHaveBody)(__props.method)]]),
369
372
  (openBlock(true), createElementBlock(Fragment, null, renderList(__props.plugins, (plugin, index) => {
370
373
  return openBlock(), createBlock(unref(ScalarErrorBoundary), { key: index }, {