@scalar/blocks 0.7.1 → 0.7.3

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 (48) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/code-example/components/AsyncApiCodeExample.vue.d.ts.map +1 -1
  3. package/dist/code-example/components/AsyncApiCodeExample.vue.js +1 -1
  4. package/dist/code-example/components/AsyncApiCodeExample.vue.js.map +1 -1
  5. package/dist/code-example/components/AsyncApiCodeExample.vue_vue_type_script_setup_true_lang.js +2 -2
  6. package/dist/code-example/components/AsyncApiCodeExample.vue_vue_type_script_setup_true_lang.js.map +1 -1
  7. package/dist/code-example/components/CodeExample.vue.d.ts.map +1 -1
  8. package/dist/code-example/components/CodeExample.vue.js +1 -1
  9. package/dist/code-example/components/CodeExample.vue.js.map +1 -1
  10. package/dist/code-example/components/CodeExample.vue_vue_type_script_setup_true_lang.js +76 -78
  11. package/dist/code-example/components/CodeExample.vue_vue_type_script_setup_true_lang.js.map +1 -1
  12. package/dist/code-example/components/ExamplePicker.vue.d.ts.map +1 -1
  13. package/dist/code-example/components/ExamplePicker.vue.js.map +1 -1
  14. package/dist/code-example/components/ExamplePicker.vue_vue_type_script_setup_true_lang.js +25 -24
  15. package/dist/code-example/components/ExamplePicker.vue_vue_type_script_setup_true_lang.js.map +1 -1
  16. package/dist/code-example/helpers/generate-code-snippet.d.ts.map +1 -1
  17. package/dist/code-example/helpers/generate-code-snippet.js +6 -3
  18. package/dist/code-example/helpers/generate-code-snippet.js.map +1 -1
  19. package/dist/code-example/helpers/operation-to-har/operation-to-har.d.ts.map +1 -1
  20. package/dist/code-example/helpers/operation-to-har/operation-to-har.js +1 -1
  21. package/dist/code-example/helpers/operation-to-har/operation-to-har.js.map +1 -1
  22. package/dist/code-example/helpers/operation-to-har/process-body.js +5 -5
  23. package/dist/code-example/mount.d.ts.map +1 -1
  24. package/dist/code-example/mount.js +32 -31
  25. package/dist/code-example/mount.js.map +1 -1
  26. package/dist/constants.js +1 -1
  27. package/dist/schema/SchemaObjectExampleCodeBlock.vue.d.ts.map +1 -1
  28. package/dist/schema/SchemaObjectExampleCodeBlock.vue.js.map +1 -1
  29. package/dist/schema/SchemaObjectExampleCodeBlock.vue_vue_type_script_setup_true_lang.js +2 -5
  30. package/dist/schema/SchemaObjectExampleCodeBlock.vue_vue_type_script_setup_true_lang.js.map +1 -1
  31. package/dist/schema/SchemaPropertyExamples.vue.d.ts.map +1 -1
  32. package/dist/schema/SchemaPropertyExamples.vue.js +1 -1
  33. package/dist/schema/SchemaPropertyExamples.vue.js.map +1 -1
  34. package/dist/schema/SchemaPropertyExamples.vue_vue_type_script_setup_true_lang.js +85 -81
  35. package/dist/schema/SchemaPropertyExamples.vue_vue_type_script_setup_true_lang.js.map +1 -1
  36. package/dist/schema/helpers/get-rendered-example.d.ts +19 -0
  37. package/dist/schema/helpers/get-rendered-example.d.ts.map +1 -0
  38. package/dist/schema/helpers/get-rendered-example.js +45 -0
  39. package/dist/schema/helpers/get-rendered-example.js.map +1 -0
  40. package/dist/schema/helpers/get-schema-type.d.ts.map +1 -1
  41. package/dist/schema/helpers/get-schema-type.js +1 -1
  42. package/dist/schema/helpers/get-schema-type.js.map +1 -1
  43. package/dist/schema/helpers/index.d.ts +1 -0
  44. package/dist/schema/helpers/index.d.ts.map +1 -1
  45. package/dist/schema/helpers/index.js +13 -12
  46. package/dist/style.css +83 -9
  47. package/dist/vue-styles.css +1 -1
  48. package/package.json +10 -10
@@ -9,9 +9,12 @@ var a = ({ clientId: a, customCodeSamples: o, includeDefaultHeaders: s = !1, ope
9
9
  if (!a) return "";
10
10
  if (a.startsWith("custom")) {
11
11
  let t = e(o), n = o.filter((e, n) => t[n] === a);
12
- if (!n.some((e) => e.example !== void 0)) return n[0]?.source ?? "Custom example not found";
13
- let r = i(c.requestBody)?.content ?? {}, s = f ?? Object.keys(r)[0], l = d ?? Object.keys(r[s ?? ""]?.examples ?? {})[0];
14
- return (n.find((e) => e.example === l && e.contentType === s) ?? n.find((e) => e.example === l && e.contentType === void 0))?.source ?? null;
12
+ if (!n.some((e) => e.example !== void 0)) {
13
+ let e = n[0]?.source;
14
+ return typeof e == "object" ? null : e ?? "Custom example not found";
15
+ }
16
+ let r = i(c.requestBody)?.content ?? {}, s = f ?? Object.keys(r)[0], l = d ?? Object.keys(r[s ?? ""]?.examples ?? {})[0], u = n.find((e) => e.example === l && e.contentType === s) ?? n.find((e) => e.example === l && e.contentType === void 0);
17
+ return typeof u?.source == "string" ? u.source : null;
15
18
  }
16
19
  let n = r({
17
20
  operation: c,
@@ -1 +1 @@
1
- {"version":3,"file":"generate-code-snippet.js","names":["generateCodeSnippet","clientId","ids","getCustomClientIds","customCodeSamples","samples","index","sample","content","getResolvedRef","operation","mediaType","contentType","exampleKey","example","harRequest","operationToHar","targetKey","clientKey","error","payload","getSnippet","CookieSerializationError"],"sources":["../../../src/code-example/helpers/generate-code-snippet.ts"],"sourcesContent":["import type { AvailableClient, ClientId, TargetId } from '@scalar/snippetz'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport type { SecuritySchemeObjectSecret } from '@scalar/workspace-store/request-example'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type { XCodeSample } from '@scalar/workspace-store/schemas/extensions/operation'\nimport type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\n\nimport { type CustomCodeSampleId, getCustomClientIds } from './generate-client-options'\nimport { getSnippet } from './get-snippet'\nimport { operationToHar } from './operation-to-har/operation-to-har'\nimport { CookieSerializationError } from './operation-to-har/process-parameters'\n\ntype GenerateCodeSnippetProps = {\n /** The selected client/language for code generation (e.g., 'node/fetch') or a custom code sample ID. */\n clientId: AvailableClient | CustomCodeSampleId | undefined\n /** The Content-Type header value for the request body (e.g., 'application/json'). */\n contentType: string | undefined\n /** Array of custom code samples defined in the OpenAPI x-codeSamples extension. */\n customCodeSamples: XCodeSample[]\n /** The specific example value to use when generating the code snippet. */\n example: string | undefined\n /** The HTTP method for the operation (e.g., GET, POST, PUT). */\n method: string\n /** The OpenAPI operation object containing request/response details. */\n operation: OperationObject\n /** The API endpoint path (e.g., '/users/{id}'). */\n path: string\n /** Array of security schemes to apply to the request (e.g., API keys, OAuth). */\n securitySchemes: SecuritySchemeObjectSecret[]\n /** The server object defining the base URL for the API request. */\n server: ServerObject | null\n /** Workspace + document cookies */\n globalCookies?: XScalarCookie[]\n /** Whether to include default headers (e.g., Accept, Content-Type) automatically. */\n includeDefaultHeaders?: boolean\n /** Selected oneOf/anyOf variants for nested request body example generation. */\n /** Originating OpenAPI version, used for XML mapping rules. */\n openapiVersion?: string\n requestBodyCompositionSelection?: Record<string, number>\n /** Whether to disable parameters by default. */\n defaultDisabledParameters?: boolean\n}\n\n/** Generate the code snippet for the selected example OR operation, or null when a linked sample is unavailable. */\nexport const generateCodeSnippet = ({\n clientId,\n customCodeSamples,\n includeDefaultHeaders = false,\n operation,\n method,\n path,\n example,\n contentType,\n server,\n securitySchemes,\n globalCookies,\n openapiVersion,\n requestBodyCompositionSelection,\n defaultDisabledParameters,\n}: GenerateCodeSnippetProps): string | null => {\n try {\n if (!clientId) {\n return ''\n }\n\n // Use the selected custom example, matched by its language-keyed id\n if (clientId.startsWith('custom')) {\n const ids = getCustomClientIds(customCodeSamples)\n const samples = customCodeSamples.filter((_, index) => ids[index] === clientId)\n if (!samples.some((sample) => sample.example !== undefined)) {\n return samples[0]?.source ?? 'Custom example not found'\n }\n\n const content = getResolvedRef(operation.requestBody)?.content ?? {}\n const mediaType = contentType ?? Object.keys(content)[0]\n const exampleKey = example ?? Object.keys(content[mediaType ?? '']?.examples ?? {})[0]\n const sample =\n samples.find((sample) => sample.example === exampleKey && sample.contentType === mediaType) ??\n samples.find((sample) => sample.example === exampleKey && sample.contentType === undefined)\n return sample?.source ?? null\n }\n\n const harRequest = operationToHar({\n operation,\n contentType,\n method,\n path,\n server,\n securitySchemes,\n example,\n globalCookies,\n includeDefaultHeaders,\n openapiVersion,\n requestBodyCompositionSelection,\n defaultDisabledParameters,\n })\n\n const [targetKey, clientKey] = clientId.split('/') as [TargetId, ClientId<TargetId>]\n\n const [error, payload] = getSnippet(targetKey, clientKey, harRequest)\n if (error) {\n console.error('[generateCodeSnippet]', error)\n return error.message ?? 'Error generating code snippet'\n }\n\n return payload\n } catch (error) {\n console.error('[generateCodeSnippet]', error)\n return error instanceof CookieSerializationError ? error.message : 'Error generating code snippet'\n }\n}\n"],"mappings":";;;;;;AA4CA,IAAaA,KAAuB,EAClC,aACA,sBACA,2BAAwB,IACxB,cACA,WACA,SACA,YACA,gBACA,WACA,oBACA,kBACA,mBACA,oCACA,mCAC6C;CAC7C,IAAI;EACF,IAAI,CAACC,GACH,OAAO;EAIT,IAAIA,EAAS,WAAW,QAAQ,GAAG;GACjC,IAAMC,IAAMC,EAAmBC,CAAiB,GAC1CC,IAAUD,EAAkB,QAAQ,GAAG,MAAUF,EAAII,OAAWL,CAAQ;GAC9E,IAAI,CAACI,EAAQ,MAAM,MAAWE,EAAO,YAAY,KAAA,CAAS,GACxD,OAAOF,EAAQ,EAAE,EAAE,UAAU;GAG/B,IAAMG,IAAUC,EAAeC,EAAU,WAAW,CAAC,EAAE,WAAW,CAAC,GAC7DC,IAAYC,KAAe,OAAO,KAAKJ,CAAO,CAAC,CAAC,IAChDK,IAAaC,KAAW,OAAO,KAAKN,EAAQG,KAAa,GAAG,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC;GAIpF,QAFEN,EAAQ,MAAM,MAAWE,EAAO,YAAYM,KAAcN,EAAO,gBAAgBI,CAAS,KAC1FN,EAAQ,MAAM,MAAWE,EAAO,YAAYM,KAAcN,EAAO,gBAAgB,KAAA,CAAS,EAAA,EAC7E,UAAU;EAC3B;EAEA,IAAMQ,IAAaC,EAAe;GAChC;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAAC,GAEK,CAACC,GAAWC,KAAajB,EAAS,MAAM,GAAG,GAE3C,CAACkB,GAAOC,KAAWC,EAAWJ,GAAWC,GAAWH,CAAU;EAMpE,OALII,KACF,QAAQ,MAAM,yBAAyBA,CAAK,GACrCA,EAAM,WAAW,mCAGnBC;CACT,SAASD,GAAO;EAEd,OADA,QAAQ,MAAM,yBAAyBA,CAAK,GACrCA,aAAiBG,IAA2BH,EAAM,UAAU;CACrE;AACF"}
1
+ {"version":3,"file":"generate-code-snippet.js","names":["generateCodeSnippet","clientId","ids","getCustomClientIds","customCodeSamples","samples","index","sample","source","content","getResolvedRef","operation","mediaType","contentType","exampleKey","example","harRequest","operationToHar","targetKey","clientKey","error","payload","getSnippet","CookieSerializationError"],"sources":["../../../src/code-example/helpers/generate-code-snippet.ts"],"sourcesContent":["import type { AvailableClient, ClientId, TargetId } from '@scalar/snippetz'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport type { SecuritySchemeObjectSecret } from '@scalar/workspace-store/request-example'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type { XCodeSample } from '@scalar/workspace-store/schemas/extensions/operation'\nimport type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\n\nimport { type CustomCodeSampleId, getCustomClientIds } from './generate-client-options'\nimport { getSnippet } from './get-snippet'\nimport { operationToHar } from './operation-to-har/operation-to-har'\nimport { CookieSerializationError } from './operation-to-har/process-parameters'\n\ntype GenerateCodeSnippetProps = {\n /** The selected client/language for code generation (e.g., 'node/fetch') or a custom code sample ID. */\n clientId: AvailableClient | CustomCodeSampleId | undefined\n /** The Content-Type header value for the request body (e.g., 'application/json'). */\n contentType: string | undefined\n /** Array of custom code samples defined in the OpenAPI x-codeSamples extension. */\n customCodeSamples: XCodeSample[]\n /** The specific example value to use when generating the code snippet. */\n example: string | undefined\n /** The HTTP method for the operation (e.g., GET, POST, PUT). */\n method: string\n /** The OpenAPI operation object containing request/response details. */\n operation: OperationObject\n /** The API endpoint path (e.g., '/users/{id}'). */\n path: string\n /** Array of security schemes to apply to the request (e.g., API keys, OAuth). */\n securitySchemes: SecuritySchemeObjectSecret[]\n /** The server object defining the base URL for the API request. */\n server: ServerObject | null\n /** Workspace + document cookies */\n globalCookies?: XScalarCookie[]\n /** Whether to include default headers (e.g., Accept, Content-Type) automatically. */\n includeDefaultHeaders?: boolean\n /** Selected oneOf/anyOf variants for nested request body example generation. */\n /** Originating OpenAPI version, used for XML mapping rules. */\n openapiVersion?: string\n requestBodyCompositionSelection?: Record<string, number>\n /** Whether to disable parameters by default. */\n defaultDisabledParameters?: boolean\n}\n\n/** Generate the code snippet for the selected example OR operation, or null when a linked sample is unavailable. */\nexport const generateCodeSnippet = ({\n clientId,\n customCodeSamples,\n includeDefaultHeaders = false,\n operation,\n method,\n path,\n example,\n contentType,\n server,\n securitySchemes,\n globalCookies,\n openapiVersion,\n requestBodyCompositionSelection,\n defaultDisabledParameters,\n}: GenerateCodeSnippetProps): string | null => {\n try {\n if (!clientId) {\n return ''\n }\n\n // Use the selected custom example, matched by its language-keyed id\n if (clientId.startsWith('custom')) {\n const ids = getCustomClientIds(customCodeSamples)\n const samples = customCodeSamples.filter((_, index) => ids[index] === clientId)\n if (!samples.some((sample) => sample.example !== undefined)) {\n const source = samples[0]?.source\n return typeof source === 'object' ? null : (source ?? 'Custom example not found')\n }\n\n const content = getResolvedRef(operation.requestBody)?.content ?? {}\n const mediaType = contentType ?? Object.keys(content)[0]\n const exampleKey = example ?? Object.keys(content[mediaType ?? '']?.examples ?? {})[0]\n const sample =\n samples.find((sample) => sample.example === exampleKey && sample.contentType === mediaType) ??\n samples.find((sample) => sample.example === exampleKey && sample.contentType === undefined)\n return typeof sample?.source === 'string' ? sample.source : null\n }\n\n const harRequest = operationToHar({\n operation,\n contentType,\n method,\n path,\n server,\n securitySchemes,\n example,\n globalCookies,\n includeDefaultHeaders,\n openapiVersion,\n requestBodyCompositionSelection,\n defaultDisabledParameters,\n })\n\n const [targetKey, clientKey] = clientId.split('/') as [TargetId, ClientId<TargetId>]\n\n const [error, payload] = getSnippet(targetKey, clientKey, harRequest)\n if (error) {\n console.error('[generateCodeSnippet]', error)\n return error.message ?? 'Error generating code snippet'\n }\n\n return payload\n } catch (error) {\n console.error('[generateCodeSnippet]', error)\n return error instanceof CookieSerializationError ? error.message : 'Error generating code snippet'\n }\n}\n"],"mappings":";;;;;;AA4CA,IAAaA,KAAuB,EAClC,aACA,sBACA,2BAAwB,IACxB,cACA,WACA,SACA,YACA,gBACA,WACA,oBACA,kBACA,mBACA,oCACA,mCAC6C;CAC7C,IAAI;EACF,IAAI,CAACC,GACH,OAAO;EAIT,IAAIA,EAAS,WAAW,QAAQ,GAAG;GACjC,IAAMC,IAAMC,EAAmBC,CAAiB,GAC1CC,IAAUD,EAAkB,QAAQ,GAAG,MAAUF,EAAII,OAAWL,CAAQ;GAC9E,IAAI,CAACI,EAAQ,MAAM,MAAWE,EAAO,YAAY,KAAA,CAAS,GAAG;IAC3D,IAAMC,IAASH,EAAQ,EAAE,EAAE;IAC3B,OAAO,OAAOG,KAAW,WAAW,OAAQA,KAAU;GACxD;GAEA,IAAMC,IAAUC,EAAeC,EAAU,WAAW,CAAC,EAAE,WAAW,CAAC,GAC7DC,IAAYC,KAAe,OAAO,KAAKJ,CAAO,CAAC,CAAC,IAChDK,IAAaC,KAAW,OAAO,KAAKN,EAAQG,KAAa,GAAG,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC,IAC9EL,IACJF,EAAQ,MAAM,MAAWE,EAAO,YAAYO,KAAcP,EAAO,gBAAgBK,CAAS,KAC1FP,EAAQ,MAAM,MAAWE,EAAO,YAAYO,KAAcP,EAAO,gBAAgB,KAAA,CAAS;GAC5F,OAAO,OAAOA,GAAQ,UAAW,WAAWA,EAAO,SAAS;EAC9D;EAEA,IAAMS,IAAaC,EAAe;GAChC;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAAC,GAEK,CAACC,GAAWC,KAAalB,EAAS,MAAM,GAAG,GAE3C,CAACmB,GAAOC,KAAWC,EAAWJ,GAAWC,GAAWH,CAAU;EAMpE,OALII,KACF,QAAQ,MAAM,yBAAyBA,CAAK,GACrCA,EAAM,WAAW,mCAGnBC;CACT,SAASD,GAAO;EAEd,OADA,QAAQ,MAAM,yBAAyBA,CAAK,GACrCA,aAAiBG,IAA2BH,EAAM,UAAU;CACrE;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"operation-to-har.d.ts","sourceRoot":"","sources":["../../../../src/code-example/helpers/operation-to-har/operation-to-har.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,KAAK,0BAA0B,EAIhC,MAAM,yCAAyC,CAAA;AAChD,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;AASvD,MAAM,MAAM,mBAAmB,GAAG;IAChC,+BAA+B;IAC/B,SAAS,EAAE,eAAe,CAAA;IAC1B,mCAAmC;IACnC,MAAM,EAAE,MAAM,CAAA;IACd,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,4EAA4E;IAC5E,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,+BAA+B,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IACxD;;;OAGG;IACH,yBAAyB,CAAC,EAAE,OAAO,CAAA;CACpC,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,cAAc,GAAI,+LAa5B,mBAAmB,KAAG,UAgKxB,CAAA"}
1
+ {"version":3,"file":"operation-to-har.d.ts","sourceRoot":"","sources":["../../../../src/code-example/helpers/operation-to-har/operation-to-har.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,KAAK,0BAA0B,EAIhC,MAAM,yCAAyC,CAAA;AAChD,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;AASvD,MAAM,MAAM,mBAAmB,GAAG;IAChC,+BAA+B;IAC/B,SAAS,EAAE,eAAe,CAAA;IAC1B,mCAAmC;IACnC,MAAM,EAAE,MAAM,CAAA;IACd,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,4EAA4E;IAC5E,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,+BAA+B,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IACxD;;;OAGG;IACH,yBAAyB,CAAC,EAAE,OAAO,CAAA;CACpC,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,cAAc,GAAI,+LAa5B,mBAAmB,KAAG,UA6JxB,CAAA"}
@@ -80,7 +80,7 @@ var u = ({ includeDefaultHeaders: u = !1, operation: d, contentType: f, method:
80
80
  let e = T.url.indexOf("#"), t = e === -1 ? "" : T.url.slice(e), n = e === -1 ? T.url : T.url.slice(0, e), r = T.queryString.map(({ name: e, value: t }) => `${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&");
81
81
  T.url = `${n}${n.includes("?") ? "&" : "?"}${r}${t}`, T.queryString = [];
82
82
  }
83
- T.postData?.mimeType === "multipart/form-data" && T.postData.params?.some((e) => e.fileName !== void 0) && (T.headers = T.headers.filter((e) => e.name.toLowerCase() !== "content-type"));
83
+ T.postData?.mimeType === "multipart/form-data" && T.postData.params?.length && (T.headers = T.headers.filter((e) => e.name.toLowerCase() !== "content-type"));
84
84
  let j = 0;
85
85
  for (let e of T.headers) j += (e.name?.length ?? 0) + 2 + (e.value?.length ?? 0) + 2;
86
86
  return T.headersSize = j, T;
@@ -1 +1 @@
1
- {"version":3,"file":"operation-to-har.js","names":["operationToHar","defaultHeaders","includeDefaultHeaders","getDefaultHeaders","example","isElectron","APP_VERSION","defaultHeadersWithConventionalNames","restoreConventionalDefaultHeaderNames","disabledGlobalCookies","operation","harRequest","processServerUrl","server","path","name","value","hasCookieStyleEntries","hasSerializedQuery","processedCookieStyleEntries","processedSerializedQuery","processParameters","defaultDisabledParameters","filteredGlobalCookies","globalCookies","filterGlobalCookie","cookie","url","headers","queryString","cookies","body","getResolvedRef","postData","processBody","existingContentTypeHeader","header","hasUriReadyQuery","parameter","securitySchemes","processSecuritySchemes","cookieHeader","extraCookies","hashIndex","hash","query","param","headersSize","h"],"sources":["../../../../src/code-example/helpers/operation-to-har/operation-to-har.ts"],"sourcesContent":["import { isElectron } from '@scalar/helpers/general/is-electron'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport {\n type SecuritySchemeObjectSecret,\n filterGlobalCookie,\n getDefaultHeaders,\n restoreConventionalDefaultHeaderNames,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport type { Request as HarRequest } from 'har-format'\n\nimport { APP_VERSION } from '@/constants'\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: string\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 /** Originating OpenAPI version, used for version-specific serialization. */\n openapiVersion?: string\n requestBodyCompositionSelection?: Record<string, number>\n /**\n * Whether to disable parameters by default.\n * @default false\n */\n defaultDisabledParameters?: 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 openapiVersion,\n requestBodyCompositionSelection,\n defaultDisabledParameters = false,\n}: OperationToHarProps): HarRequest => {\n const defaultHeaders = includeDefaultHeaders\n ? getDefaultHeaders({\n method,\n operation,\n exampleName: example ?? 'default',\n hideDisabledHeaders: true,\n hideOverriddenHeaders: true,\n options: { isElectron: isElectron(), appVersion: APP_VERSION },\n })\n : {}\n const defaultHeadersWithConventionalNames = restoreConventionalDefaultHeaderNames(defaultHeaders)\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: Object.entries(defaultHeadersWithConventionalNames).map(([name, value]) => ({ name, value })),\n queryString: [],\n postData: undefined,\n httpVersion: 'HTTP/1.1',\n cookies: [],\n headersSize: -1,\n bodySize: -1,\n }\n\n let hasCookieStyleEntries = false\n let hasSerializedQuery = false\n\n // Handle parameters\n if (operation.parameters) {\n const {\n url,\n headers,\n queryString,\n cookies,\n hasCookieStyleEntries: processedCookieStyleEntries,\n hasSerializedQuery: processedSerializedQuery,\n } = processParameters({\n harRequest,\n parameters: operation.parameters,\n openapiVersion,\n example,\n defaultDisabled: defaultDisabledParameters,\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 hasCookieStyleEntries = processedCookieStyleEntries\n hasSerializedQuery = processedSerializedQuery ?? false\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 openapiVersion,\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 (\n existingContentTypeHeader &&\n (!existingContentTypeHeader.value ||\n (postData.mimeType.startsWith('multipart/') &&\n postData.mimeType.includes('boundary=') &&\n postData.text !== undefined))\n ) {\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 const hasUriReadyQuery =\n hasSerializedQuery || operation.parameters?.some((parameter) => getResolvedRef(parameter)?.in === 'querystring')\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 // Keep authentication and global cookies in the explicit header as well, so\n // snippet generators cannot replace cookie-style parameters with their own header.\n const cookieHeader = harRequest.headers.find((header) => header.name.toLowerCase() === 'cookie')\n if (hasCookieStyleEntries && cookieHeader && harRequest.cookies.length) {\n const extraCookies = harRequest.cookies\n .map((cookie) => `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`)\n .join('; ')\n cookieHeader.value = cookieHeader.value ? `${cookieHeader.value}; ${extraCookies}` : extraCookies\n harRequest.cookies = []\n }\n\n // Whole-query content and serialized examples must retain their authored URI encoding.\n // Keeping all query data in the URL avoids snippet generators introducing a second question mark.\n if (hasUriReadyQuery && harRequest.queryString.length) {\n const hashIndex = harRequest.url.indexOf('#')\n const hash = hashIndex === -1 ? '' : harRequest.url.slice(hashIndex)\n const url = hashIndex === -1 ? harRequest.url : harRequest.url.slice(0, hashIndex)\n const query = harRequest.queryString\n .map(({ name, value }) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`)\n .join('&')\n harRequest.url = `${url}${url.includes('?') ? '&' : '?'}${query}${hash}`\n harRequest.queryString = []\n }\n\n // Multipart file parts are encoded by the HTTP client, which owns the boundary.\n // Raw multipart text already has its boundary and must retain its Content-Type.\n if (\n harRequest.postData?.mimeType === 'multipart/form-data' &&\n harRequest.postData.params?.some((param) => param.fileName !== undefined)\n ) {\n harRequest.headers = harRequest.headers.filter((header) => header.name.toLowerCase() !== 'content-type')\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":";;;;;;;;;AAuFA,IAAaA,KAAkB,EAC7B,2BAAwB,IACxB,cACA,gBACA,WACA,SACA,YAAS,MACT,YACA,oBACA,kBACA,mBACA,oCACA,+BAA4B,SACS;CACrC,IAAMC,IAAiBC,IACnBC,EAAkB;EAChB;EACA;EACA,aAAaC,KAAW;EACxB,qBAAqB;EACrB,uBAAuB;EACvB,SAAS;GAAE,YAAYC,EAAW;GAAG,YAAYC;EAAY;CAC/D,CAAC,IACD,CAAC,GACCC,IAAsCC,EAAsCP,CAAc,GAE1FQ,IACJC,EAAU,8BAA8B,GAAG,iBAAiB,GAAGN,KAAW,cAAc,CAAC,GAKrFO,IAAyB;EAC7B;EAC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,aAAa,yBAClCA,EAAW,SAAS,QAAQ,MAAM,MAAUmC,EAAM,aAAa,KAAA,CAAS,MAExE,EAAW,UAAUnC,EAAW,QAAQ,QAAQ,MAAWyB,EAAO,KAAK,YAAY,MAAM,cAAc;CAIzG,IAAIW,IAAc;CAClB,KAAK,IAAMC,KAAKrC,EAAW,SAEzB,MAAgBqC,EAAE,MAAM,UAAU,KAAK,KAAKA,EAAE,OAAO,UAAU,KAAK;CAItE,OAFA,EAAW,cAAcD,GAElBpC;AACT"}
1
+ {"version":3,"file":"operation-to-har.js","names":["operationToHar","defaultHeaders","includeDefaultHeaders","getDefaultHeaders","example","isElectron","APP_VERSION","defaultHeadersWithConventionalNames","restoreConventionalDefaultHeaderNames","disabledGlobalCookies","operation","harRequest","processServerUrl","server","path","name","value","hasCookieStyleEntries","hasSerializedQuery","processedCookieStyleEntries","processedSerializedQuery","processParameters","defaultDisabledParameters","filteredGlobalCookies","globalCookies","filterGlobalCookie","cookie","url","headers","queryString","cookies","body","getResolvedRef","postData","processBody","existingContentTypeHeader","header","hasUriReadyQuery","parameter","securitySchemes","processSecuritySchemes","cookieHeader","extraCookies","hashIndex","hash","query","headersSize","h"],"sources":["../../../../src/code-example/helpers/operation-to-har/operation-to-har.ts"],"sourcesContent":["import { isElectron } from '@scalar/helpers/general/is-electron'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport {\n type SecuritySchemeObjectSecret,\n filterGlobalCookie,\n getDefaultHeaders,\n restoreConventionalDefaultHeaderNames,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport type { Request as HarRequest } from 'har-format'\n\nimport { APP_VERSION } from '@/constants'\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: string\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 /** Originating OpenAPI version, used for version-specific serialization. */\n openapiVersion?: string\n requestBodyCompositionSelection?: Record<string, number>\n /**\n * Whether to disable parameters by default.\n * @default false\n */\n defaultDisabledParameters?: 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 openapiVersion,\n requestBodyCompositionSelection,\n defaultDisabledParameters = false,\n}: OperationToHarProps): HarRequest => {\n const defaultHeaders = includeDefaultHeaders\n ? getDefaultHeaders({\n method,\n operation,\n exampleName: example ?? 'default',\n hideDisabledHeaders: true,\n hideOverriddenHeaders: true,\n options: { isElectron: isElectron(), appVersion: APP_VERSION },\n })\n : {}\n const defaultHeadersWithConventionalNames = restoreConventionalDefaultHeaderNames(defaultHeaders)\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: Object.entries(defaultHeadersWithConventionalNames).map(([name, value]) => ({ name, value })),\n queryString: [],\n postData: undefined,\n httpVersion: 'HTTP/1.1',\n cookies: [],\n headersSize: -1,\n bodySize: -1,\n }\n\n let hasCookieStyleEntries = false\n let hasSerializedQuery = false\n\n // Handle parameters\n if (operation.parameters) {\n const {\n url,\n headers,\n queryString,\n cookies,\n hasCookieStyleEntries: processedCookieStyleEntries,\n hasSerializedQuery: processedSerializedQuery,\n } = processParameters({\n harRequest,\n parameters: operation.parameters,\n openapiVersion,\n example,\n defaultDisabled: defaultDisabledParameters,\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 hasCookieStyleEntries = processedCookieStyleEntries\n hasSerializedQuery = processedSerializedQuery ?? false\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 openapiVersion,\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 (\n existingContentTypeHeader &&\n (!existingContentTypeHeader.value ||\n (postData.mimeType.startsWith('multipart/') &&\n postData.mimeType.includes('boundary=') &&\n postData.text !== undefined))\n ) {\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 const hasUriReadyQuery =\n hasSerializedQuery || operation.parameters?.some((parameter) => getResolvedRef(parameter)?.in === 'querystring')\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 // Keep authentication and global cookies in the explicit header as well, so\n // snippet generators cannot replace cookie-style parameters with their own header.\n const cookieHeader = harRequest.headers.find((header) => header.name.toLowerCase() === 'cookie')\n if (hasCookieStyleEntries && cookieHeader && harRequest.cookies.length) {\n const extraCookies = harRequest.cookies\n .map((cookie) => `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`)\n .join('; ')\n cookieHeader.value = cookieHeader.value ? `${cookieHeader.value}; ${extraCookies}` : extraCookies\n harRequest.cookies = []\n }\n\n // Whole-query content and serialized examples must retain their authored URI encoding.\n // Keeping all query data in the URL avoids snippet generators introducing a second question mark.\n if (hasUriReadyQuery && harRequest.queryString.length) {\n const hashIndex = harRequest.url.indexOf('#')\n const hash = hashIndex === -1 ? '' : harRequest.url.slice(hashIndex)\n const url = hashIndex === -1 ? harRequest.url : harRequest.url.slice(0, hashIndex)\n const query = harRequest.queryString\n .map(({ name, value }) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`)\n .join('&')\n harRequest.url = `${url}${url.includes('?') ? '&' : '?'}${query}${hash}`\n harRequest.queryString = []\n }\n\n // Structured multipart parts (with or without files) are encoded by the HTTP client, which owns the boundary.\n // Raw multipart text already has its boundary and must retain its Content-Type.\n if (harRequest.postData?.mimeType === 'multipart/form-data' && harRequest.postData.params?.length) {\n harRequest.headers = harRequest.headers.filter((header) => header.name.toLowerCase() !== 'content-type')\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":";;;;;;;;;AAuFA,IAAaA,KAAkB,EAC7B,2BAAwB,IACxB,cACA,gBACA,WACA,SACA,YAAS,MACT,YACA,oBACA,kBACA,mBACA,oCACA,+BAA4B,SACS;CACrC,IAAMC,IAAiBC,IACnBC,EAAkB;EAChB;EACA;EACA,aAAaC,KAAW;EACxB,qBAAqB;EACrB,uBAAuB;EACvB,SAAS;GAAE,YAAYC,EAAW;GAAG,YAAYC;EAAY;CAC/D,CAAC,IACD,CAAC,GACCC,IAAsCC,EAAsCP,CAAc,GAE1FQ,IACJC,EAAU,8BAA8B,GAAG,iBAAiB,GAAGN,KAAW,cAAc,CAAC,GAKrFO,IAAyB;EAC7B;EACA,KALgBC,EAAiBC,GAAQC,CAKpC;EACL,SAAS,OAAO,QAAQP,CAAmC,CAAC,CAAC,KAAK,CAACQ,GAAMC,QAAY;GAAE;GAAM;EAAM,EAAE;EACrG,aAAa,CAAC;EACd,UAAU,KAAA;EACV,aAAa;EACb,SAAS,CAAC;EACV,aAAa;EACb,UAAU;CACZ,GAEIC,IAAwB,IACxBC,IAAqB;CAGzB,IAAIR,EAAU,YAAY;EACxB,IAAM,EACJ,QACA,YACA,gBACA,YACA,uBAAuBS,GACvB,oBAAoBC,MAClBC,EAAkB;GACpB;GACA,YAAYX,EAAU;GACtB;GACA;GACA,iBAAiBY;EACnB,CAAC,GAGKC,IACJC,GACI,QAAQ,MAAWC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AInB,KAAyBwB,KAAgB9B,EAAW,QAAQ,QAAQ;EACtE,IAAM+B,IAAe/B,EAAW,QAC7B,KAAK,MAAW,GAAG,mBAAmBe,EAAO,IAAI,EAAE,GAAG,mBAAmBA,EAAO,KAAK,GAAG,CAAC,CACzF,KAAK,IAAI;EAEZ,AADA,EAAa,QAAQe,EAAa,QAAQ,GAAGA,EAAa,MAAM,IAAIC,MAAiBA,GACrF,EAAW,UAAU,CAAC;CACxB;CAIA,IAAIL,KAAoB1B,EAAW,YAAY,QAAQ;EACrD,IAAMgC,IAAYhC,EAAW,IAAI,QAAQ,GAAG,GACtCiC,IAAOD,MAAc,KAAK,KAAKhC,EAAW,IAAI,MAAMgC,CAAS,GAC7DhB,IAAMgB,MAAc,KAAKhC,EAAW,MAAMA,EAAW,IAAI,MAAM,GAAGgC,CAAS,GAC3EE,IAAQlC,EAAW,YACtB,KAAK,EAAE,SAAM,eAAY,GAAG,mBAAmBI,CAAI,EAAE,GAAG,mBAAmBC,CAAK,GAAG,CAAC,CACpF,KAAK,GAAG;EAEX,AADA,EAAW,MAAM,GAAGW,IAAMA,EAAI,SAAS,GAAG,IAAI,MAAM,MAAMkB,IAAQD,KAClE,EAAW,cAAc,CAAC;CAC5B;CAIA,AAAIjC,EAAW,UAAU,aAAa,yBAAyBA,EAAW,SAAS,QAAQ,WACzF,EAAW,UAAUA,EAAW,QAAQ,QAAQ,MAAWyB,EAAO,KAAK,YAAY,MAAM,cAAc;CAIzG,IAAIU,IAAc;CAClB,KAAK,IAAMC,KAAKpC,EAAW,SAEzB,MAAgBoC,EAAE,MAAM,UAAU,KAAK,KAAKA,EAAE,OAAO,UAAU,KAAK;CAItE,OAFA,EAAW,cAAcD,GAElBnC;AACT"}
@@ -1,8 +1,8 @@
1
1
  import { snapshotSchema as e } from "@scalar/workspace-store/helpers/snapshot-schema";
2
2
  import { buildRequestBody as t, coerceLeafValueToSchemaType as n, getExample as r, getExampleFromBody as i, getExampleFromSchema as a, needsMultipartEncoding as o, resolveLeafSchema as s, serializeFormPropertyWithEncoding as c, serializeMultipartArray as l, serializeMultipartBody as u } from "@scalar/workspace-store/request-example";
3
3
  import { isXmlMediaType as d } from "@scalar/helpers/http/is-xml-media-type";
4
- import { getResolvedRef as f, mergeSiblingReferences as p } from "@scalar/workspace-store/helpers/get-resolved-ref";
5
- import { getExampleValue as m, getExplicitExampleText as h } from "@scalar/workspace-store/helpers/get-example-value";
4
+ import { getExampleValue as f, getExplicitExampleText as p } from "@scalar/workspace-store/helpers/get-example-value";
5
+ import { getResolvedRef as m, mergeSiblingReferences as h } from "@scalar/workspace-store/helpers/get-resolved-ref";
6
6
  import { serializeStreamExample as g } from "@scalar/workspace-store/helpers/serialize-stream-example";
7
7
  import { unpackProxyObject as _ } from "@scalar/workspace-store/helpers/unpack-proxy";
8
8
  //#region src/code-example/helpers/operation-to-har/process-body.ts
@@ -89,7 +89,7 @@ var v = (e, t, n) => ({
89
89
  text: e.value
90
90
  } : void 0;
91
91
  }
92
- let E = m(r(n, c, s)), D = h(E, y);
92
+ let E = f(r(n, c, s)), D = p(E, y);
93
93
  if (D !== void 0) return {
94
94
  mimeType: b,
95
95
  text: D
@@ -99,7 +99,7 @@ var v = (e, t, n) => ({
99
99
  let e = typeof O == "object" && O ? _(O) : O;
100
100
  return T && typeof e == "object" && e ? {
101
101
  mimeType: b,
102
- params: x(e, C, void 0, y === "multipart/form-data", f(n.content[y]?.schema, p))
102
+ params: x(e, C, void 0, y === "multipart/form-data", m(n.content[y]?.schema, h))
103
103
  } : e instanceof File ? {
104
104
  mimeType: b,
105
105
  text: S(e)
@@ -108,7 +108,7 @@ var v = (e, t, n) => ({
108
108
  text: typeof e == "string" ? e : g(e, y, !1) ?? JSON.stringify(e)
109
109
  };
110
110
  }
111
- let k = n.content[y], A = f(k?.schema ?? k?.itemSchema);
111
+ let k = n.content[y], A = m(k?.schema ?? k?.itemSchema);
112
112
  if (A !== void 0) {
113
113
  let t = a(e(A), {
114
114
  compositionSelection: v,
@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"file":"mount.d.ts","sourceRoot":"","sources":["../../src/code-example/mount.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAA;AACxD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAA;AAOpE,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,yCAAyC,CAAA;AAEzF,OAAO,KAAK,EAAmB,YAAY,EAAE,MAAM,8DAA8D,CAAA;AACjH,OAAO,EAAE,KAAK,GAAG,EAA0B,MAAM,KAAK,CAAA;AAItD,OAAO,EAAE,KAAK,gCAAgC,EAA6B,MAAM,kBAAkB,CAAA;AAEnG,MAAM,MAAM,wBAAwB,GAAG;IACrC,uFAAuF;IACvF,qBAAqB,CAAC,EAAE,MAAM,CAAA;IAC9B,wEAAwE;IACxE,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,yEAAyE;IACzE,KAAK,EAAE,cAAc,CAAA;IACrB,2DAA2D;IAC3D,IAAI,EAAE,MAAM,CAAA;IACZ,8CAA8C;IAC9C,MAAM,EAAE,MAAM,CAAA;IACd,iDAAiD;IACjD,cAAc,CAAC,EAAE,gBAAgB,CAAC,MAAM,CAAC,CAAA;IACzC;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,YAAY,GAAG,IAAI,CAAA;IACpC;;;;;;OAMG;IACH,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,oDAAoD;IACpD,eAAe,CAAC,EAAE,0BAA0B,EAAE,CAAA;IAC9C;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB,CAAA;AAkBD;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB,GAC5B,IAAI,WAAW,GAAG,MAAM,EACxB,SAAS,wBAAwB,GAAG,gCAAgC,KACnE;IAAE,GAAG,EAAE,GAAG,CAAC;IAAC,OAAO,EAAE,MAAM,IAAI,CAAA;CA+IjC,CAAA"}
@@ -3,70 +3,71 @@ import t from "./components/CodeExample.vue.js";
3
3
  import { createAsyncApiCodeExample as n } from "./mount-asyncapi.js";
4
4
  import { createApp as r, h as i, reactive as a } from "vue";
5
5
  import { ScalarWrappingText as o } from "@scalar/components/wrapping-text";
6
- import { createWorkspaceEventBus as s } from "@scalar/workspace-store/events";
7
- import { getResolvedRef as c } from "@scalar/workspace-store/helpers/get-resolved-ref";
6
+ import { getResolvedRef as s } from "@scalar/workspace-store/helpers/get-resolved-ref";
7
+ import { createWorkspaceEventBus as c } from "@scalar/workspace-store/events";
8
8
  import { EXTERNAL_EXAMPLES as l } from "@scalar/workspace-store/helpers/use-external-examples";
9
9
  import { ScalarTeleportRoot as u } from "@scalar/components/teleport";
10
10
  import { getPathItemOperation as d } from "@scalar/workspace-store/helpers/for-each-path-item-operation";
11
11
  import { getFirstServer as f } from "@scalar/workspace-store/helpers/get-first-server";
12
12
  import { generateClientMutators as p } from "@scalar/workspace-store/mutators";
13
+ import { isOpenApiDocument as m } from "@scalar/workspace-store/schemas/type-guards";
13
14
  //#region src/code-example/mount.ts
14
- var m = (e) => e === !0 ? "scalar-app dark-mode" : e === !1 ? "scalar-app light-mode" : "scalar-app", h = (h, g) => {
15
- if ("operationName" in g) return n(h, g);
16
- let _ = typeof h == "string" ? document.querySelector(h) : h;
17
- if (!_) throw Error(`Element not found: ${h}`);
18
- let v = s(), y = e(), b = p(g.store), x = v.on("workspace:update:selected-client", (e) => b.workspace().workspace.updateSelectedClient(e)), S = v.on("workspace:update:selected-example", (e) => b.workspace().workspace.updateSelectedExample(e)), C = () => {
19
- let e = g.store.workspace.activeDocument;
20
- if (!e || !("paths" in e)) return;
21
- let t = c(e.paths?.[g.path]), n = c(d(t, g.method));
15
+ var h = (e) => e === !0 ? "scalar-app dark-mode" : e === !1 ? "scalar-app light-mode" : "scalar-app", g = (g, _) => {
16
+ if ("operationName" in _) return n(g, _);
17
+ let v = typeof g == "string" ? document.querySelector(g) : g;
18
+ if (!v) throw Error(`Element not found: ${g}`);
19
+ let y = c(), b = e(), x = p(_.store), S = y.on("workspace:update:selected-client", (e) => x.workspace().workspace.updateSelectedClient(e)), C = y.on("workspace:update:selected-example", (e) => x.workspace().workspace.updateSelectedExample(e)), w = () => {
20
+ let e = _.store.workspace.activeDocument;
21
+ if (!m(e)) return;
22
+ let t = s(e.paths?.[_.path]), n = s(d(t, _.method));
22
23
  if (n) return {
23
24
  operation: n,
24
25
  server: f(n.servers ?? null, t?.servers ?? null, e.servers ?? null)
25
26
  };
26
27
  };
27
- if (!C()) throw Error(`Operation not found: ${g.method.toUpperCase()} ${g.path}`);
28
- let w, T = () => {
29
- let e = C();
30
- return e && (w = e), e ?? w;
31
- }, E = a({
28
+ if (!w()) throw Error(`Operation not found: ${_.method.toUpperCase()} ${_.path}`);
29
+ let T, E = () => {
30
+ let e = w();
31
+ return e && (T = e), e ?? T;
32
+ }, D = a({
32
33
  get codeSampleUnavailable() {
33
- return g.codeSampleUnavailable;
34
+ return _.codeSampleUnavailable;
34
35
  },
35
36
  get codeSampleLabel() {
36
- return g.codeSampleLabel;
37
+ return _.codeSampleLabel;
37
38
  },
38
39
  get operation() {
39
- return T().operation;
40
+ return E().operation;
40
41
  },
41
42
  get method() {
42
- return g.method;
43
+ return _.method;
43
44
  },
44
45
  get path() {
45
- return g.path;
46
+ return _.path;
46
47
  },
47
- clientOptions: y,
48
- eventBus: v,
48
+ clientOptions: b,
49
+ eventBus: y,
49
50
  get securitySchemes() {
50
- return g.securitySchemes ?? [];
51
+ return _.securitySchemes ?? [];
51
52
  },
52
53
  get selectedClient() {
53
- return g.store.workspace["x-scalar-default-client"] ?? g.selectedClient;
54
+ return _.store.workspace["x-scalar-default-client"] ?? _.selectedClient;
54
55
  },
55
56
  get selectedExample() {
56
- return g.store.workspace["x-scalar-default-example"] ?? g.selectedExample;
57
+ return _.store.workspace["x-scalar-default-example"] ?? _.selectedExample;
57
58
  },
58
59
  get selectedServer() {
59
- return g.selectedServer === void 0 ? T().server : g.selectedServer;
60
+ return _.selectedServer === void 0 ? E().server : _.selectedServer;
60
61
  }
61
- }), D = () => i("span", { class: "font-code text-c-2 min-w-0" }, i(o, { text: g.path })), O = r(() => i("div", { class: m(g.darkMode) }, [i(u, null, { default: () => i(t, E, { header: D }) })]));
62
- return O.provide(l, () => g.store.externalExamples()), O.mount(_), {
63
- app: O,
62
+ }), O = () => i("span", { class: "font-code text-c-2 min-w-0" }, i(o, { text: _.path })), k = r(() => i("div", { class: h(_.darkMode) }, [i(u, null, { default: () => i(t, D, { header: O }) })]));
63
+ return k.provide(l, () => _.store.externalExamples()), k.mount(v), {
64
+ app: k,
64
65
  destroy: () => {
65
- x(), S(), O.unmount();
66
+ S(), C(), k.unmount();
66
67
  }
67
68
  };
68
69
  };
69
70
  //#endregion
70
- export { h as createCodeExample };
71
+ export { g as createCodeExample };
71
72
 
72
73
  //# sourceMappingURL=mount.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mount.js","names":["CodeExample","CodeExample_default","getWrapperClass","darkMode","createCodeExample","options","createAsyncApiCodeExample","el","element","eventBus","createWorkspaceEventBus","clientOptions","generateClientOptions","mutators","generateClientMutators","unsubscribeClient","payload","unsubscribeExample","resolveContext","activeDocument","pathItem","getResolvedRef","operation","getPathItemOperation","getFirstServer","lastContext","currentContext","context","props","reactive","renderHeader","h","ScalarWrappingText","app","createApp","ScalarTeleportRoot","EXTERNAL_EXAMPLES"],"sources":["../../src/code-example/mount.ts"],"sourcesContent":["import { ScalarTeleportRoot } from '@scalar/components/teleport'\nimport { ScalarWrappingText } from '@scalar/components/wrapping-text'\nimport type { AvailableClients } from '@scalar/snippetz'\nimport type { WorkspaceStore } from '@scalar/workspace-store/client'\nimport { createWorkspaceEventBus } from '@scalar/workspace-store/events'\nimport { getPathItemOperation } from '@scalar/workspace-store/helpers/for-each-path-item-operation'\nimport { getFirstServer } from '@scalar/workspace-store/helpers/get-first-server'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { EXTERNAL_EXAMPLES } from '@scalar/workspace-store/helpers/use-external-examples'\nimport { generateClientMutators } from '@scalar/workspace-store/mutators'\nimport type { SecuritySchemeObjectSecret } from '@scalar/workspace-store/request-example'\nimport type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { type App, createApp, h, reactive } from 'vue'\n\nimport CodeExample, { type CodeExampleProps } from './components/CodeExample.vue'\nimport { generateClientOptions } from './helpers/generate-client-options'\nimport { type CreateAsyncApiCodeExampleOptions, createAsyncApiCodeExample } from './mount-asyncapi'\n\nexport type CreateCodeExampleOptions = {\n /** Localized status text shown when the selected example has no linked code sample. */\n codeSampleUnavailable?: string\n /** Localized accessible name for the focusable code sample scroller. */\n codeSampleLabel?: string\n /** Workspace store that holds the OpenAPI document(s) to render from. */\n store: WorkspaceStore\n /** Path of the operation to render, e.g. '/users/{id}'. */\n path: string\n /** HTTP method of the operation to render. */\n method: string\n /** Pre-selected client ID, e.g. 'shell/curl'. */\n selectedClient?: AvailableClients[number]\n /**\n * Server object override used to build the example request.\n *\n * When omitted, the server is derived from the active document (operation,\n * then path item, then document level), mirroring the API reference. Pass\n * `null` to force \"no server\".\n */\n selectedServer?: ServerObject | null\n /**\n * Pre-selected example key for parameters and the request body.\n *\n * The store is the source of truth once an example is picked, so\n * `x-scalar-default-example` wins over this initial seed and the selection\n * round-trips through the store like the client selection does.\n */\n selectedExample?: string\n /** Security schemes applicable to the operation. */\n securitySchemes?: SecuritySchemeObjectSecret[]\n /**\n * Force a color mode on the rendered block.\n *\n * When omitted, the block inherits the ambient theme of the host page.\n * Pass `true` for dark mode or `false` for light mode.\n */\n darkMode?: boolean\n}\n\n/**\n * Builds the wrapper classes for the mounted block.\n *\n * The `.scalar-app` class scopes the Tailwind utilities, and the optional\n * color-mode class lets consumers pin the block to dark or light.\n */\nconst getWrapperClass = (darkMode: boolean | undefined): string => {\n if (darkMode === true) {\n return 'scalar-app dark-mode'\n }\n if (darkMode === false) {\n return 'scalar-app light-mode'\n }\n return 'scalar-app'\n}\n\n/**\n * Mount the CodeExample block to a DOM element without Vue.\n *\n * The consumer creates and controls their own workspace store,\n * then passes it in along with the path and method to render.\n */\nexport const createCodeExample = (\n el: HTMLElement | string,\n options: CreateCodeExampleOptions | CreateAsyncApiCodeExampleOptions,\n): { app: App; destroy: () => void } => {\n if ('operationName' in options) return createAsyncApiCodeExample(el, options)\n\n const element = typeof el === 'string' ? document.querySelector(el) : el\n if (!element) {\n throw new Error(`Element not found: ${el}`)\n }\n\n const eventBus = createWorkspaceEventBus()\n const clientOptions = generateClientOptions()\n\n // Persist client changes back to the store. The block emits\n // `workspace:update:selected-client` on its private bus when the user picks a\n // client; without this subscription the choice would never reach the store\n // and `x-scalar-default-client` (the source of truth read below) would stay\n // stale, so the selection would not survive a re-render or be shared with\n // other blocks reading from the same store.\n const mutators = generateClientMutators(options.store)\n const unsubscribeClient = eventBus.on('workspace:update:selected-client', (payload) =>\n mutators.workspace().workspace.updateSelectedClient(payload),\n )\n\n // Persist example changes back to the store as well, mirroring the client\n // round-trip above. The block emits `workspace:update:selected-example` when\n // the user picks an example; without this the choice would never reach\n // `x-scalar-default-example` (read below) and would neither survive a\n // re-render nor sync to other blocks reading from the same store.\n const unsubscribeExample = eventBus.on('workspace:update:selected-example', (payload) =>\n mutators.workspace().workspace.updateSelectedExample(payload),\n )\n\n type OperationContext = { operation: OperationObject; server: ServerObject | null }\n\n /**\n * Resolve the operation and its effective server from the active document.\n *\n * The server is resolved from the same document the operation came from\n * (operation, then path item, then document level), so a snippet never pairs\n * an operation with a server URL from a different spec.\n */\n const resolveContext = (): OperationContext | undefined => {\n // The active document may be an AsyncAPI document, which has no `paths`.\n const activeDocument = options.store.workspace.activeDocument\n if (!activeDocument || !('paths' in activeDocument)) {\n return undefined\n }\n const pathItem = getResolvedRef(activeDocument.paths?.[options.path])\n const operation = getResolvedRef(getPathItemOperation(pathItem, options.method))\n if (!operation) {\n return undefined\n }\n const server = getFirstServer(operation.servers ?? null, pathItem?.servers ?? null, activeDocument.servers ?? null)\n return { operation, server }\n }\n\n // Fail loudly if the path and method do not point at an operation in the store,\n // mirroring the \"element not found\" guard above.\n if (!resolveContext()) {\n throw new Error(`Operation not found: ${options.method.toUpperCase()} ${options.path}`)\n }\n\n // Remember the last context that resolved so a transient miss (e.g. the active\n // document is swapped to one without this path or method after mount) keeps\n // rendering the previous operation, paired with the server it actually came\n // from, instead of feeding `undefined` to the block.\n let lastContext: OperationContext | undefined\n\n /** Current operation + server, falling back to the last good resolution on a transient miss. */\n const currentContext = (): OperationContext => {\n const context = resolveContext()\n if (context) {\n lastContext = context\n }\n return (context ?? lastContext) as OperationContext\n }\n\n // Props are getters so the block tracks the reactive store (active document,\n // `x-scalar-default-client`, `x-scalar-default-example`) live. Change the\n // client, example, or server through the store to drive re-renders.\n const props = reactive<CodeExampleProps>({\n get codeSampleUnavailable() {\n return options.codeSampleUnavailable\n },\n get codeSampleLabel() {\n return options.codeSampleLabel\n },\n get operation(): OperationObject {\n return currentContext().operation\n },\n get method() {\n return options.method\n },\n get path() {\n return options.path\n },\n clientOptions,\n eventBus,\n get securitySchemes() {\n return options.securitySchemes ?? []\n },\n get selectedClient() {\n // The store is the source of truth once the user picks a client, so it\n // wins over the initial `options.selectedClient` seed and the selection\n // round-trips through the subscription above.\n return options.store.workspace['x-scalar-default-client'] ?? options.selectedClient\n },\n get selectedExample() {\n // Same as the client: the store wins over the initial seed so the example\n // selection survives re-renders and syncs across blocks.\n return options.store.workspace['x-scalar-default-example'] ?? options.selectedExample\n },\n get selectedServer() {\n // An explicit option wins (including an explicit `null` for \"no server\");\n // otherwise derive it from the same document the operation resolved from.\n return options.selectedServer !== undefined ? options.selectedServer : currentContext().server\n },\n })\n\n // Render the operation path in the header by default. The reference renders\n // this via the `#header` slot too, so the standalone block matches its look.\n const renderHeader = () =>\n h('span', { class: 'font-code text-c-2 min-w-0' }, h(ScalarWrappingText, { text: options.path }))\n\n // Wrap the block in its own teleport root so floating UI (the client picker\n // popover) renders inside the themed `.scalar-app` wrapper instead of escaping\n // to `body`, where it would miss the color-mode variables and lose its styling.\n const app = createApp(() =>\n h('div', { class: getWrapperClass(options.darkMode) }, [\n h(ScalarTeleportRoot, null, { default: () => h(CodeExample, props, { header: renderHeader }) }),\n ]),\n )\n\n app.provide(EXTERNAL_EXAMPLES, () => options.store.externalExamples())\n app.mount(element)\n\n return {\n app,\n destroy: () => {\n unsubscribeClient()\n unsubscribeExample()\n app.unmount()\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgEA,IAAME,KAAmB,MACnBC,MAAa,KACR,yBAELA,MAAa,KACR,0BAEF,cASIC,KACX,GACA,MACsC;CACtC,IAAI,mBAAmBC,GAAS,OAAOC,EAA0BC,GAAIF,CAAO;CAE5E,IAAMG,IAAU,OAAOD,KAAO,WAAW,SAAS,cAAcA,CAAE,IAAIA;CACtE,IAAI,CAACC,GACH,MAAU,MAAM,sBAAsBD,GAAI;CAG5C,IAAME,IAAWC,EAAwB,GACnCC,IAAgBC,EAAsB,GAQtCC,IAAWC,EAAuBT,EAAQ,KAAK,GAC/CU,IAAoBN,EAAS,GAAG,qCAAqC,MACzEI,EAAS,UAAU,CAAC,CAAC,UAAU,qBAAqBG,CAAO,CAC7D,GAOMC,IAAqBR,EAAS,GAAG,sCAAsC,MAC3EI,EAAS,UAAU,CAAC,CAAC,UAAU,sBAAsBG,CAAO,CAC9D,GAWME,UAAqD;EAEzD,IAAMC,IAAiBd,EAAQ,MAAM,UAAU;EAC/C,IAAI,CAACc,KAAkB,EAAE,WAAWA,IAClC;EAEF,IAAMC,IAAWC,EAAeF,EAAe,QAAQd,EAAQ,KAAK,GAC9DiB,IAAYD,EAAeE,EAAqBH,GAAUf,EAAQ,MAAM,CAAC;EAC/E,IAAKiB,GAIL,OAAO;GAAE;GAAW,QADLE,EAAeF,EAAU,WAAW,MAAMF,GAAU,WAAW,MAAMD,EAAe,WAAW,IAC1F;EAAO;CAC7B;CAIA,IAAI,CAACD,EAAe,GAClB,MAAU,MAAM,wBA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AAQ;EACd;CACF;AACF"}
1
+ {"version":3,"file":"mount.js","names":["CodeExample","CodeExample_default","getWrapperClass","darkMode","createCodeExample","options","createAsyncApiCodeExample","el","element","eventBus","createWorkspaceEventBus","clientOptions","generateClientOptions","mutators","generateClientMutators","unsubscribeClient","payload","unsubscribeExample","resolveContext","activeDocument","isOpenApiDocument","pathItem","getResolvedRef","operation","getPathItemOperation","getFirstServer","lastContext","currentContext","context","props","reactive","renderHeader","h","ScalarWrappingText","app","createApp","ScalarTeleportRoot","EXTERNAL_EXAMPLES"],"sources":["../../src/code-example/mount.ts"],"sourcesContent":["import { ScalarTeleportRoot } from '@scalar/components/teleport'\nimport { ScalarWrappingText } from '@scalar/components/wrapping-text'\nimport type { AvailableClients } from '@scalar/snippetz'\nimport type { WorkspaceStore } from '@scalar/workspace-store/client'\nimport { createWorkspaceEventBus } from '@scalar/workspace-store/events'\nimport { getPathItemOperation } from '@scalar/workspace-store/helpers/for-each-path-item-operation'\nimport { getFirstServer } from '@scalar/workspace-store/helpers/get-first-server'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { EXTERNAL_EXAMPLES } from '@scalar/workspace-store/helpers/use-external-examples'\nimport { generateClientMutators } from '@scalar/workspace-store/mutators'\nimport type { SecuritySchemeObjectSecret } from '@scalar/workspace-store/request-example'\nimport { isOpenApiDocument } from '@scalar/workspace-store/schemas/type-guards'\nimport type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { type App, createApp, h, reactive } from 'vue'\n\nimport CodeExample, { type CodeExampleProps } from './components/CodeExample.vue'\nimport { generateClientOptions } from './helpers/generate-client-options'\nimport { type CreateAsyncApiCodeExampleOptions, createAsyncApiCodeExample } from './mount-asyncapi'\n\nexport type CreateCodeExampleOptions = {\n /** Localized status text shown when the selected example has no linked code sample. */\n codeSampleUnavailable?: string\n /** Localized accessible name for the focusable code sample scroller. */\n codeSampleLabel?: string\n /** Workspace store that holds the OpenAPI document(s) to render from. */\n store: WorkspaceStore\n /** Path of the operation to render, e.g. '/users/{id}'. */\n path: string\n /** HTTP method of the operation to render. */\n method: string\n /** Pre-selected client ID, e.g. 'shell/curl'. */\n selectedClient?: AvailableClients[number]\n /**\n * Server object override used to build the example request.\n *\n * When omitted, the server is derived from the active document (operation,\n * then path item, then document level), mirroring the API reference. Pass\n * `null` to force \"no server\".\n */\n selectedServer?: ServerObject | null\n /**\n * Pre-selected example key for parameters and the request body.\n *\n * The store is the source of truth once an example is picked, so\n * `x-scalar-default-example` wins over this initial seed and the selection\n * round-trips through the store like the client selection does.\n */\n selectedExample?: string\n /** Security schemes applicable to the operation. */\n securitySchemes?: SecuritySchemeObjectSecret[]\n /**\n * Force a color mode on the rendered block.\n *\n * When omitted, the block inherits the ambient theme of the host page.\n * Pass `true` for dark mode or `false` for light mode.\n */\n darkMode?: boolean\n}\n\n/**\n * Builds the wrapper classes for the mounted block.\n *\n * The `.scalar-app` class scopes the Tailwind utilities, and the optional\n * color-mode class lets consumers pin the block to dark or light.\n */\nconst getWrapperClass = (darkMode: boolean | undefined): string => {\n if (darkMode === true) {\n return 'scalar-app dark-mode'\n }\n if (darkMode === false) {\n return 'scalar-app light-mode'\n }\n return 'scalar-app'\n}\n\n/**\n * Mount the CodeExample block to a DOM element without Vue.\n *\n * The consumer creates and controls their own workspace store,\n * then passes it in along with the path and method to render.\n */\nexport const createCodeExample = (\n el: HTMLElement | string,\n options: CreateCodeExampleOptions | CreateAsyncApiCodeExampleOptions,\n): { app: App; destroy: () => void } => {\n if ('operationName' in options) return createAsyncApiCodeExample(el, options)\n\n const element = typeof el === 'string' ? document.querySelector(el) : el\n if (!element) {\n throw new Error(`Element not found: ${el}`)\n }\n\n const eventBus = createWorkspaceEventBus()\n const clientOptions = generateClientOptions()\n\n // Persist client changes back to the store. The block emits\n // `workspace:update:selected-client` on its private bus when the user picks a\n // client; without this subscription the choice would never reach the store\n // and `x-scalar-default-client` (the source of truth read below) would stay\n // stale, so the selection would not survive a re-render or be shared with\n // other blocks reading from the same store.\n const mutators = generateClientMutators(options.store)\n const unsubscribeClient = eventBus.on('workspace:update:selected-client', (payload) =>\n mutators.workspace().workspace.updateSelectedClient(payload),\n )\n\n // Persist example changes back to the store as well, mirroring the client\n // round-trip above. The block emits `workspace:update:selected-example` when\n // the user picks an example; without this the choice would never reach\n // `x-scalar-default-example` (read below) and would neither survive a\n // re-render nor sync to other blocks reading from the same store.\n const unsubscribeExample = eventBus.on('workspace:update:selected-example', (payload) =>\n mutators.workspace().workspace.updateSelectedExample(payload),\n )\n\n type OperationContext = { operation: OperationObject; server: ServerObject | null }\n\n /**\n * Resolve the operation and its effective server from the active document.\n *\n * The server is resolved from the same document the operation came from\n * (operation, then path item, then document level), so a snippet never pairs\n * an operation with a server URL from a different spec.\n */\n const resolveContext = (): OperationContext | undefined => {\n // The active document may be an AsyncAPI or plugin document, which has no `paths`.\n const activeDocument = options.store.workspace.activeDocument\n if (!isOpenApiDocument(activeDocument)) {\n return undefined\n }\n const pathItem = getResolvedRef(activeDocument.paths?.[options.path])\n const operation = getResolvedRef(getPathItemOperation(pathItem, options.method))\n if (!operation) {\n return undefined\n }\n const server = getFirstServer(operation.servers ?? null, pathItem?.servers ?? null, activeDocument.servers ?? null)\n return { operation, server }\n }\n\n // Fail loudly if the path and method do not point at an operation in the store,\n // mirroring the \"element not found\" guard above.\n if (!resolveContext()) {\n throw new Error(`Operation not found: ${options.method.toUpperCase()} ${options.path}`)\n }\n\n // Remember the last context that resolved so a transient miss (e.g. the active\n // document is swapped to one without this path or method after mount) keeps\n // rendering the previous operation, paired with the server it actually came\n // from, instead of feeding `undefined` to the block.\n let lastContext: OperationContext | undefined\n\n /** Current operation + server, falling back to the last good resolution on a transient miss. */\n const currentContext = (): OperationContext => {\n const context = resolveContext()\n if (context) {\n lastContext = context\n }\n return (context ?? lastContext) as OperationContext\n }\n\n // Props are getters so the block tracks the reactive store (active document,\n // `x-scalar-default-client`, `x-scalar-default-example`) live. Change the\n // client, example, or server through the store to drive re-renders.\n const props = reactive<CodeExampleProps>({\n get codeSampleUnavailable() {\n return options.codeSampleUnavailable\n },\n get codeSampleLabel() {\n return options.codeSampleLabel\n },\n get operation(): OperationObject {\n return currentContext().operation\n },\n get method() {\n return options.method\n },\n get path() {\n return options.path\n },\n clientOptions,\n eventBus,\n get securitySchemes() {\n return options.securitySchemes ?? []\n },\n get selectedClient() {\n // The store is the source of truth once the user picks a client, so it\n // wins over the initial `options.selectedClient` seed and the selection\n // round-trips through the subscription above.\n return options.store.workspace['x-scalar-default-client'] ?? options.selectedClient\n },\n get selectedExample() {\n // Same as the client: the store wins over the initial seed so the example\n // selection survives re-renders and syncs across blocks.\n return options.store.workspace['x-scalar-default-example'] ?? options.selectedExample\n },\n get selectedServer() {\n // An explicit option wins (including an explicit `null` for \"no server\");\n // otherwise derive it from the same document the operation resolved from.\n return options.selectedServer !== undefined ? options.selectedServer : currentContext().server\n },\n })\n\n // Render the operation path in the header by default. The reference renders\n // this via the `#header` slot too, so the standalone block matches its look.\n const renderHeader = () =>\n h('span', { class: 'font-code text-c-2 min-w-0' }, h(ScalarWrappingText, { text: options.path }))\n\n // Wrap the block in its own teleport root so floating UI (the client picker\n // popover) renders inside the themed `.scalar-app` wrapper instead of escaping\n // to `body`, where it would miss the color-mode variables and lose its styling.\n const app = createApp(() =>\n h('div', { class: getWrapperClass(options.darkMode) }, [\n h(ScalarTeleportRoot, null, { default: () => h(CodeExample, props, { header: renderHeader }) }),\n ]),\n )\n\n app.provide(EXTERNAL_EXAMPLES, () => options.store.externalExamples())\n app.mount(element)\n\n return {\n app,\n destroy: () => {\n unsubscribeClient()\n unsubscribeExample()\n app.unmount()\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAiEA,IAAME,KAAmB,MACnBC,MAAa,KACR,yBAELA,MAAa,KACR,0BAEF,cASIC,KACX,GACA,MACsC;CACtC,IAAI,mBAAmBC,GAAS,OAAOC,EAA0BC,GAAIF,CAAO;CAE5E,I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,mBAAmB,CAAC;EACrC;EACA,IAAI,iBAAiB;GAInB,OAAOA,EAAQ,MAAM,UAAU,8BAA8BA,EAAQ;EACvE;EACA,IAAI,kBAAkB;GAGpB,OAAOA,EAAQ,MAAM,UAAU,+BAA+BA,EAAQ;EACxE;EACA,IAAI,iBAAiB;GAGnB,OAAOA,EAAQ,mBAAmB,KAAA,IAAqCsB,EAAe,CAAC,CAAC,SAA1CtB,EAAQ;EACxD;CACF,CAAC,GAIK0B,UACJC,EAAE,QAAQ,EAAE,OAAO,6BAA6B,GAAGA,EAAEC,GAAoB,EAAE,MAAM5B,EAAQ,KAAK,CAAC,CAAC,GAK5F6B,IAAMC,QACVH,EAAE,OAAO,EAAE,OAAO9B,EAAgBG,EAAQ,QAAQ,EAAE,GAAG,CACrD2B,EAAEI,GAAoB,MAAM,EAAE,eAAeJ,EAAEhC,GAAa6B,GAAO,EAAE,QAAQE,EAAa,CAAC,EAAE,CAAC,CAChG,CAAC,CACH;CAKA,OAHAG,EAAI,QAAQG,SAAyBhC,EAAQ,MAAM,iBAAiB,CAAC,GACrE6B,EAAI,MAAM1B,CAAO,GAEV;EACL;EACA,eAAe;GAGb,AAFAO,EAAkB,GAClBE,EAAmB,GACnBiB,EAAI,QAAQ;EACd;CACF;AACF"}
package/dist/constants.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region src/constants.ts
2
- var e = typeof OVERRIDE_PACKAGE_VERSION < "u" ? OVERRIDE_PACKAGE_VERSION : "0.7.1";
2
+ var e = typeof OVERRIDE_PACKAGE_VERSION < "u" ? OVERRIDE_PACKAGE_VERSION : "0.7.3";
3
3
  //#endregion
4
4
  export { e as APP_VERSION };
5
5
 
@@ -1 +1 @@
1
- {"version":3,"file":"SchemaObjectExampleCodeBlock.vue.d.ts","sourceRoot":"","sources":["../../src/schema/SchemaObjectExampleCodeBlock.vue"],"names":[],"mappings":"AAiFA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8DAA8D,CAAA;AAKhG,KAAK,WAAW,GAAG;IAAE,MAAM,EAAE,YAAY,CAAA;CAAE,CAAC;AAmJ5C,QAAA,MAAM,YAAY,kSAEhB,CAAC;wBACkB,OAAO,YAAY;AAAxC,wBAAyC"}
1
+ {"version":3,"file":"SchemaObjectExampleCodeBlock.vue.d.ts","sourceRoot":"","sources":["../../src/schema/SchemaObjectExampleCodeBlock.vue"],"names":[],"mappings":"AA+EA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8DAA8D,CAAA;AAKhG,KAAK,WAAW,GAAG;IAAE,MAAM,EAAE,YAAY,CAAA;CAAE,CAAC;AAgJ5C,QAAA,MAAM,YAAY,kSAEhB,CAAC;wBACkB,OAAO,YAAY;AAAxC,wBAAyC"}
@@ -1 +1 @@
1
- {"version":3,"file":"SchemaObjectExampleCodeBlock.vue.js","names":["_sfc_main","SchemaObjectExampleCodeBlock_vue_vue_type_script_setup_true_lang_default","SchemaObjectExampleCodeBlock_default"],"sources":["../../src/schema/SchemaObjectExampleCodeBlock.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ScalarCard,\n ScalarCardFooter,\n ScalarCardSection,\n} from '@scalar/components/card'\nimport { ScalarCodeBlock } from '@scalar/components/code-block'\nimport type { SchemaObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { computed, ref } from 'vue'\n\nimport { ExamplePicker } from '../code-example'\n\nconst { schema } = defineProps<{ schema: SchemaObject }>()\n\n/** Grab the examples for the schema object */\nconst examples = computed<Record<string, string>>(() => {\n const base: Record<string, string> = {}\n\n // x-examples extension\n if (schema['x-examples']) {\n Object.entries(schema['x-examples']).forEach(([key, value]) => {\n base[key] =\n typeof value === 'object'\n ? JSON.stringify(value, null, 2)\n : String(value)\n })\n }\n\n // Regular schema examples array\n if (schema.examples) {\n schema.examples.forEach((value, index) => {\n base[`Example ${index + 1}`] =\n typeof value === 'object'\n ? JSON.stringify(value, null, 2)\n : String(value)\n })\n }\n\n return base\n})\n\n/** The currently selected example key */\nconst selectedExampleKey = ref<string>(Object.keys(examples.value)[0] ?? '')\n</script>\n<template>\n <ScalarCard\n v-if=\"Object.keys(examples).length > 0\"\n class=\"dark-mode\">\n <!-- Code snippet -->\n <ScalarCardSection>\n <div class=\"code-snippet\">\n <ScalarCodeBlock\n class=\"bg-b-2\"\n lang=\"json\"\n lineNumbers\n :prettyPrintedContent=\"\n examples[selectedExampleKey] ??\n 'There was an error loading the example'\n \" />\n </div>\n </ScalarCardSection>\n\n <!-- Example picker -->\n <ScalarCardFooter\n v-if=\"Object.keys(examples).length > 1\"\n class=\"bg-b-3\">\n <ExamplePicker\n v-model=\"selectedExampleKey\"\n :examples />\n </ScalarCardFooter>\n </ScalarCard>\n</template>\n"],"mappings":""}
1
+ {"version":3,"file":"SchemaObjectExampleCodeBlock.vue.js","names":["_sfc_main","SchemaObjectExampleCodeBlock_vue_vue_type_script_setup_true_lang_default","SchemaObjectExampleCodeBlock_default"],"sources":["../../src/schema/SchemaObjectExampleCodeBlock.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ScalarCard,\n ScalarCardFooter,\n ScalarCardSection,\n} from '@scalar/components/card'\nimport { ScalarCodeBlock } from '@scalar/components/code-block'\nimport type { SchemaObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { computed, ref } from 'vue'\n\nimport { ExamplePicker } from '../code-example'\n\nconst { schema } = defineProps<{ schema: SchemaObject }>()\n\n/** Grab the examples for the schema object */\nconst examples = computed<Record<string, string>>(() => {\n const base: Record<string, string> = {}\n\n // x-examples extension\n if (schema['x-examples']) {\n Object.entries(schema['x-examples']).forEach(([key, value]) => {\n base[key] =\n typeof value === 'object'\n ? JSON.stringify(value, null, 2)\n : String(value)\n })\n }\n\n // Regular schema examples array\n if (schema.examples) {\n schema.examples.forEach((value, index) => {\n base[`Example ${index + 1}`] =\n typeof value === 'object'\n ? JSON.stringify(value, null, 2)\n : String(value)\n })\n }\n\n return base\n})\n\n/** The currently selected example key */\nconst selectedExampleKey = ref<string>(Object.keys(examples.value)[0] ?? '')\n</script>\n<template>\n <ScalarCard\n v-if=\"Object.keys(examples).length > 0\"\n class=\"dark-mode\">\n <!-- Code snippet -->\n <ScalarCardSection>\n <div class=\"code-snippet\">\n <ScalarCodeBlock\n class=\"bg-transparent\"\n lang=\"json\"\n lineNumbers\n :prettyPrintedContent=\"\n examples[selectedExampleKey] ??\n 'There was an error loading the example'\n \" />\n </div>\n </ScalarCardSection>\n\n <!-- Example picker -->\n <ScalarCardFooter v-if=\"Object.keys(examples).length > 1\">\n <ExamplePicker\n v-model=\"selectedExampleKey\"\n :examples />\n </ScalarCardFooter>\n </ScalarCard>\n</template>\n"],"mappings":""}
@@ -21,16 +21,13 @@ var h = { class: "code-snippet" }, g = /*@__PURE__*/ o({
21
21
  }, {
22
22
  default: u(() => [a(l(p), null, {
23
23
  default: u(() => [i("div", h, [a(l(m), {
24
- class: "bg-b-2",
24
+ class: "bg-transparent",
25
25
  lang: "json",
26
26
  lineNumbers: "",
27
27
  prettyPrintedContent: g.value[_.value] ?? "There was an error loading the example"
28
28
  }, null, 8, ["prettyPrintedContent"])])]),
29
29
  _: 1
30
- }), Object.keys(g.value).length > 1 ? (s(), n(l(f), {
31
- key: 0,
32
- class: "bg-b-3"
33
- }, {
30
+ }), Object.keys(g.value).length > 1 ? (s(), n(l(f), { key: 0 }, {
34
31
  default: u(() => [a(l(e), {
35
32
  modelValue: _.value,
36
33
  "onUpdate:modelValue": o[0] ||= (e) => _.value = e,
@@ -1 +1 @@
1
- {"version":3,"file":"SchemaObjectExampleCodeBlock.vue_vue_type_script_setup_true_lang.js","names":["_openBlock","_createBlock","_unref","_withCtx","_createVNode","_createElementVNode","ExamplePicker","_createCommentVNode","ExamplePicker_default","_hoisted_1","SchemaObjectExampleCodeBlock_vue_vue_type_script_setup_true_lang_default","examples","computed","base","__props","key","value","index","selectedExampleKey","ref","openBlock","createBlock","unref","ScalarCard","withCtx","createVNode","ScalarCardSection","createElementVNode","ScalarCodeBlock","ScalarCardFooter","_cache","$event","createCommentVNode"],"sources":["../../src/schema/SchemaObjectExampleCodeBlock.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ScalarCard,\n ScalarCardFooter,\n ScalarCardSection,\n} from '@scalar/components/card'\nimport { ScalarCodeBlock } from '@scalar/components/code-block'\nimport type { SchemaObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { computed, ref } from 'vue'\n\nimport { ExamplePicker } from '../code-example'\n\nconst { schema } = defineProps<{ schema: SchemaObject }>()\n\n/** Grab the examples for the schema object */\nconst examples = computed<Record<string, string>>(() => {\n const base: Record<string, string> = {}\n\n // x-examples extension\n if (schema['x-examples']) {\n Object.entries(schema['x-examples']).forEach(([key, value]) => {\n base[key] =\n typeof value === 'object'\n ? JSON.stringify(value, null, 2)\n : String(value)\n })\n }\n\n // Regular schema examples array\n if (schema.examples) {\n schema.examples.forEach((value, index) => {\n base[`Example ${index + 1}`] =\n typeof value === 'object'\n ? JSON.stringify(value, null, 2)\n : String(value)\n })\n }\n\n return base\n})\n\n/** The currently selected example key */\nconst selectedExampleKey = ref<string>(Object.keys(examples.value)[0] ?? '')\n</script>\n<template>\n <ScalarCard\n v-if=\"Object.keys(examples).length > 0\"\n class=\"dark-mode\">\n <!-- Code snippet -->\n <ScalarCardSection>\n <div class=\"code-snippet\">\n <ScalarCodeBlock\n class=\"bg-b-2\"\n lang=\"json\"\n lineNumbers\n :prettyPrintedContent=\"\n examples[selectedExampleKey] ??\n 'There was an error loading the example'\n \" />\n </div>\n </ScalarCardSection>\n\n <!-- Example picker -->\n <ScalarCardFooter\n v-if=\"Object.keys(examples).length > 1\"\n class=\"bg-b-3\">\n <ExamplePicker\n v-model=\"selectedExampleKey\"\n :examples />\n </ScalarCardFooter>\n </ScalarCard>\n</template>\n"],"mappings":";;;;;;;;;EAeA,IAAMW,IAAWC,QAAuC;GACtD,IAAMC,IAA+B,CAAC;GAsBtC,OAnBIC,EAAA,OAAO,iBACT,OAAO,QAAQA,EAAA,OAAO,aAAa,CAAC,CAAC,SAAS,CAACC,GAAKC,OAAW;IAC7D,EAAKD,KACH,OAAOC,KAAU,WACb,KAAK,UAAUA,GAAO,MAAM,CAAC,IAC7B,OAAOA,CAAK;GACpB,CAAC,GAICF,EAAA,OAAO,YACTA,EAAA,OAAO,SAAS,SAAS,GAAO,MAAU;IACxC,EAAK,WAAWG,IAAQ,OACtB,OAAOD,KAAU,WACb,KAAK,UAAUA,GAAO,MAAM,CAAC,IAC7B,OAAOA,CAAK;GACpB,CAAC,GAGIH;EACT,CAAC,GAGKK,IAAqBC,EAAY,OAAO,KAAKR,EAAS,KAAK,CAAC,CAAC,MAAM,EAAE;E,iBAIjE,OAAO,KAAKA,EAAA,KAAQ,CAAA,CAAE,SAAM,KADpCX,EAAA,GAAAC,EAyBaC,EAAAqB,CAAA,GAAA;;GAvBX,OAAM;;GAEN,SAAApB,QAWoB,CAXpBC,EAWoBF,EAAAwB,CAAA,GAAA,MAAA;IAVlB,SAAAvB,QASM,CATNE,EASM,OATNI,GASM,CARJL,EAOMF,EAAA0B,CAAA,GAAA;KANJ,OAAM;KACN,MAAK;KACL,aAAA;KACC,sBAAmCjB,EAAA,MAASO,EAAA,U;;;G,IAS3C,OAAO,KAAKP,EAAA,KAAQ,CAAA,CAAE,SAAM,KADpCX,EAAA,GAAAC,EAMmBC,EAAA2B,CAAA,GAAA;;IAJjB,OAAM;;IACN,SAAA1B,QAEc,CAFdC,EAEcF,EAAAI,CAAA,GAAA;KADH,YAAAY,EAAA;KAAA,uBAAA,AAAAY,EAAA,QAAA,MAAA,EAAkB,QAAAC;KAC1B,UAAApB,EAAA"}
1
+ {"version":3,"file":"SchemaObjectExampleCodeBlock.vue_vue_type_script_setup_true_lang.js","names":["_openBlock","_createBlock","_unref","_withCtx","_createVNode","_createElementVNode","ExamplePicker","_createCommentVNode","ExamplePicker_default","_hoisted_1","SchemaObjectExampleCodeBlock_vue_vue_type_script_setup_true_lang_default","examples","computed","base","__props","key","value","index","selectedExampleKey","ref","openBlock","createBlock","unref","ScalarCard","withCtx","createVNode","ScalarCardSection","createElementVNode","ScalarCodeBlock","ScalarCardFooter","_cache","$event","createCommentVNode"],"sources":["../../src/schema/SchemaObjectExampleCodeBlock.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ScalarCard,\n ScalarCardFooter,\n ScalarCardSection,\n} from '@scalar/components/card'\nimport { ScalarCodeBlock } from '@scalar/components/code-block'\nimport type { SchemaObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { computed, ref } from 'vue'\n\nimport { ExamplePicker } from '../code-example'\n\nconst { schema } = defineProps<{ schema: SchemaObject }>()\n\n/** Grab the examples for the schema object */\nconst examples = computed<Record<string, string>>(() => {\n const base: Record<string, string> = {}\n\n // x-examples extension\n if (schema['x-examples']) {\n Object.entries(schema['x-examples']).forEach(([key, value]) => {\n base[key] =\n typeof value === 'object'\n ? JSON.stringify(value, null, 2)\n : String(value)\n })\n }\n\n // Regular schema examples array\n if (schema.examples) {\n schema.examples.forEach((value, index) => {\n base[`Example ${index + 1}`] =\n typeof value === 'object'\n ? JSON.stringify(value, null, 2)\n : String(value)\n })\n }\n\n return base\n})\n\n/** The currently selected example key */\nconst selectedExampleKey = ref<string>(Object.keys(examples.value)[0] ?? '')\n</script>\n<template>\n <ScalarCard\n v-if=\"Object.keys(examples).length > 0\"\n class=\"dark-mode\">\n <!-- Code snippet -->\n <ScalarCardSection>\n <div class=\"code-snippet\">\n <ScalarCodeBlock\n class=\"bg-transparent\"\n lang=\"json\"\n lineNumbers\n :prettyPrintedContent=\"\n examples[selectedExampleKey] ??\n 'There was an error loading the example'\n \" />\n </div>\n </ScalarCardSection>\n\n <!-- Example picker -->\n <ScalarCardFooter v-if=\"Object.keys(examples).length > 1\">\n <ExamplePicker\n v-model=\"selectedExampleKey\"\n :examples />\n </ScalarCardFooter>\n </ScalarCard>\n</template>\n"],"mappings":";;;;;;;;;EAeA,IAAMW,IAAWC,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,WAAW,GAAG;IACjB,oFAAoF;IACpF,KAAK,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAA;IAC1B,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,OAAO,CAAC,EAAE,OAAO,CAAA;CAClB,CAAC;AAqaF,QAAA,MAAM,YAAY,kSAEhB,CAAC;wBACkB,OAAO,YAAY;AAAxC,wBAAyC"}
1
+ {"version":3,"file":"SchemaPropertyExamples.vue.d.ts","sourceRoot":"","sources":["../../src/schema/SchemaPropertyExamples.vue"],"names":[],"mappings":"AA0VA,KAAK,WAAW,GAAG;IACjB,oFAAoF;IACpF,KAAK,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAA;IAC1B,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,OAAO,CAAC,EAAE,OAAO,CAAA;CAClB,CAAC;AA+aF,QAAA,MAAM,YAAY,kSAEhB,CAAC;wBACkB,OAAO,YAAY;AAAxC,wBAAyC"}
@@ -2,7 +2,7 @@ import e from "../_virtual/_plugin-vue_export-helper.js";
2
2
  import t from "./SchemaPropertyExamples.vue_vue_type_script_setup_true_lang.js";
3
3
  /* empty css */
4
4
  //#region src/schema/SchemaPropertyExamples.vue
5
- var n = /*#__PURE__*/ e(t, [["__scopeId", "data-v-a431d692"]]);
5
+ var n = /*#__PURE__*/ e(t, [["__scopeId", "data-v-72248a2e"]]);
6
6
  //#endregion
7
7
  export { n as default };
8
8
 
@@ -1 +1 @@
1
- {"version":3,"file":"SchemaPropertyExamples.vue.js","names":["_sfc_main","_plugin_vue_export_helper_default","SchemaPropertyExamples_vue_vue_type_script_setup_true_lang_default","SchemaPropertyExamples_default"],"sources":["../../src/schema/SchemaPropertyExamples.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { ScalarIcon } from '@scalar/components/icon'\nimport { isObject, isObjectLike } from '@scalar/helpers/object/is-object'\nimport { useClipboard } from '@scalar/use-hooks/useClipboard'\nimport { onClickOutside, onKeyStroke } from '@vueuse/core'\nimport { computed, ref, useId } from 'vue'\n\nimport { formatExample } from './helpers/format-example'\nimport LinkButton from './LinkButton.vue'\nimport { useLocalization } from './localization'\n\nconst {\n examples,\n example,\n align = 'center',\n} = defineProps<{\n /** Align the popup with its label when centering would overlap adjacent content. */\n align?: 'center' | 'start'\n examples?: unknown\n example?: unknown\n}>()\n\nconst { copyToClipboard } = useClipboard()\nconst { translate } = useLocalization()\n\n// `null` is a meaningful example value for nullable schemas, so only treat\n// `undefined` as \"not provided\".\nconst hasSingleExample = computed(() => example !== undefined)\n\nconst normalizedExamples = computed<Record<string, unknown>>(() => {\n if (isObjectLike(examples)) {\n return examples\n }\n\n return {}\n})\n\nconst hasMultipleExamples = computed(\n () => Object.keys(normalizedExamples.value).length > 0,\n)\n\nconst multipleExamplesLabel = computed(() =>\n Object.keys(normalizedExamples.value).length === 1\n ? translate('schema.example')\n : translate('schema.examples'),\n)\n\n/**\n * Unwrap an OpenAPI 3 Example Object (`{ value, externalValue, summary, description }`)\n * to the actual sample. Plain values pass through untouched.\n */\nfunction unwrapExampleObject(value: unknown): unknown {\n if (isObject(value)) {\n if ('value' in value) {\n return value.value\n }\n if ('externalValue' in value) {\n return value.externalValue\n }\n }\n return value\n}\n\n/**\n * Hover/`:focus-within` CSS alone left the popup unreachable by Enter, Escape\n * or touch, so it is pinned open on click (as in SchemaPropertyPattern.vue).\n * `example` and `examples` can both render, so each popup has its own state.\n */\nconst singleRootRef = ref<HTMLElement | null>(null)\nconst singleTriggerRef = ref<HTMLElement | { $el: HTMLElement } | null>(null)\nconst isSingleOpen = ref(false)\nconst singlePopupId = useId()\n\nconst multipleRootRef = ref<HTMLElement | null>(null)\nconst multipleTriggerRef = ref<HTMLElement | { $el: HTMLElement } | null>(null)\nconst isMultipleOpen = ref(false)\nconst multiplePopupId = useId()\n\n/**\n * Focus opens the popup through the same state as the click, not a separate\n * `:focus-within` rule; with both, a click's own `focusin` opened it first and\n * the click closed it again. This flag stops a pointer press counting as focus.\n */\nlet openedByPointer = false\n\n/** Long enough to span a touch tap's delayed compatibility mouse events. */\nconst POINTER_GUARD_MS = 500\nlet pointerGuardTimer = 0\n\n/**\n * `closeAndRestore` refocuses the trigger, and `focus()` fires `focusin`\n * synchronously, which would re-open the popup and make the first Escape inert.\n */\nlet restoringFocus = false\n\nconst onPointerDown = (): void => {\n /*\n * A touch tap's compatibility mousedown (which moves focus) lands 50-150ms\n * after touchend, past any one-frame guard, so the tap opened then closed.\n */\n openedByPointer = true\n window.clearTimeout(pointerGuardTimer)\n pointerGuardTimer = window.setTimeout(() => {\n openedByPointer = false\n }, POINTER_GUARD_MS)\n}\n\nconst leftPopup = (event: FocusEvent, root: HTMLElement | null): boolean => {\n const next = event.relatedTarget\n\n return !(next instanceof Node) || !root?.contains(next)\n}\n\nconst onSingleFocusIn = (): void => {\n if (!openedByPointer && !restoringFocus) {\n isSingleOpen.value = true\n }\n}\n\nconst onSingleFocusOut = (event: FocusEvent): void => {\n if (leftPopup(event, singleRootRef.value)) {\n isSingleOpen.value = false\n }\n}\n\nconst onMultipleFocusIn = (): void => {\n if (!openedByPointer && !restoringFocus) {\n isMultipleOpen.value = true\n }\n}\n\nconst onMultipleFocusOut = (event: FocusEvent): void => {\n if (leftPopup(event, multipleRootRef.value)) {\n isMultipleOpen.value = false\n }\n}\n\nonClickOutside(singleRootRef, () => {\n isSingleOpen.value = false\n})\n\nonClickOutside(multipleRootRef, () => {\n isMultipleOpen.value = false\n})\n\n/**\n * Closing hides the popup outright, so focus is handed back deliberately, or\n * Escape from inside it drops focus to <body>.\n */\nconst closeAndRestore = (\n open: typeof isSingleOpen,\n root: typeof singleRootRef,\n trigger: typeof singleTriggerRef,\n): void => {\n if (!open.value) {\n return\n }\n\n const wasInside = root.value?.contains(document.activeElement)\n\n open.value = false\n\n if (wasInside) {\n const element = trigger.value\n const focusable = element instanceof HTMLElement ? element : element?.$el\n\n restoringFocus = true\n focusable?.focus?.()\n restoringFocus = false\n }\n}\n\nonKeyStroke('Escape', () => {\n closeAndRestore(isSingleOpen, singleRootRef, singleTriggerRef)\n closeAndRestore(isMultipleOpen, multipleRootRef, multipleTriggerRef)\n})\n</script>\n<template>\n <!-- single example (deprecated) -->\n <template v-if=\"hasSingleExample\">\n <div\n ref=\"singleRootRef\"\n class=\"property-example\"\n :class=\"{ 'is-open': isSingleOpen }\"\n @focusin=\"onSingleFocusIn\"\n @focusout=\"onSingleFocusOut\">\n <LinkButton\n ref=\"singleTriggerRef\"\n :aria-controls=\"singlePopupId\"\n :aria-expanded=\"isSingleOpen\"\n class=\"decoration-dotted\"\n @click=\"isSingleOpen = !isSingleOpen\"\n @pointerdown=\"onPointerDown\">\n {{ translate('schema.example') }}\n </LinkButton>\n <div\n :id=\"singlePopupId\"\n class=\"property-example-value-list\"\n :class=\"{\n 'flex!': isSingleOpen,\n 'property-example-value-list-start': align === 'start',\n }\">\n <button\n :aria-label=\"`${translate('common.copyExample')}: ${formatExample(example)}`\"\n class=\"property-example-value group\"\n type=\"button\"\n @click=\"copyToClipboard(formatExample(example))\">\n <span>\n {{ formatExample(example) }}\n </span>\n <ScalarIcon\n aria-hidden=\"true\"\n class=\"group-hover:text-c-1 text-c-3 ml-auto min-h-3 min-w-3\"\n icon=\"Clipboard\"\n size=\"xs\" />\n </button>\n </div>\n </div>\n </template>\n\n <!-- multiple examples -->\n <template v-if=\"hasMultipleExamples\">\n <div\n ref=\"multipleRootRef\"\n class=\"property-example\"\n :class=\"{ 'is-open': isMultipleOpen }\"\n @focusin=\"onMultipleFocusIn\"\n @focusout=\"onMultipleFocusOut\">\n <LinkButton\n ref=\"multipleTriggerRef\"\n :aria-controls=\"multiplePopupId\"\n :aria-expanded=\"isMultipleOpen\"\n class=\"decoration-dotted\"\n @click=\"isMultipleOpen = !isMultipleOpen\"\n @pointerdown=\"onPointerDown\">\n {{ multipleExamplesLabel }}\n </LinkButton>\n <div\n :id=\"multiplePopupId\"\n class=\"property-example-value-list\"\n :class=\"{\n 'flex!': isMultipleOpen,\n 'property-example-value-list-start': align === 'start',\n }\">\n <button\n v-for=\"(ex, key) in normalizedExamples\"\n :key=\"key\"\n :aria-label=\"`${translate('common.copyExample')}: ${formatExample(unwrapExampleObject(ex))}`\"\n class=\"property-example-value group\"\n type=\"button\"\n @click=\"copyToClipboard(formatExample(unwrapExampleObject(ex)))\">\n <span>{{ formatExample(unwrapExampleObject(ex)) }} </span>\n <ScalarIcon\n aria-hidden=\"true\"\n class=\"text-c-3 group-hover:text-c-1 ml-auto min-h-3 min-w-3\"\n icon=\"Clipboard\"\n size=\"xs\" />\n </button>\n </div>\n </div>\n </template>\n</template>\n\n<style scoped>\n@reference \"../style.css\";\n\n.property-example {\n display: flex;\n flex-direction: column;\n font-size: var(--scalar-mini);\n position: relative;\n}\n.property-example:hover:before {\n pointer-events: none;\n content: '';\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 20px;\n border-radius: var(--scalar-radius);\n}\n.property-example-value {\n font-family: var(--scalar-font-code);\n display: flex;\n gap: 8px;\n align-items: center;\n width: 100%;\n padding: 6px;\n}\n.property-example-value span {\n display: block;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: pre;\n}\n.property-example-value :deep(svg) {\n color: var(--scalar-color-3);\n}\n\n.property-example-value:hover :deep(svg) {\n color: var(--scalar-color-1);\n}\n\n.property-example-value {\n background: var(--scalar-background-2);\n border: var(--scalar-border-width) solid var(--scalar-border-color);\n border-radius: var(--scalar-radius);\n}\n.property-example-value-list {\n position: absolute;\n top: 18px;\n left: 50%;\n transform: translate3d(-50%, 0, 0);\n overflow: auto;\n background-color: var(--scalar-background-1);\n box-shadow: var(--scalar-shadow-1);\n border-radius: var(--scalar-radius-lg);\n border: var(--scalar-border-width) solid var(--scalar-border-color);\n padding: 9px;\n min-width: 200px;\n max-width: 300px;\n flex-direction: column;\n gap: 3px;\n display: none;\n @apply z-context;\n}\n.property-example-value-list-start {\n left: 0;\n transform: none;\n}\n.property-example:hover .property-example-value-list {\n display: flex;\n}\n</style>\n"],"mappings":""}
1
+ {"version":3,"file":"SchemaPropertyExamples.vue.js","names":["_sfc_main","_plugin_vue_export_helper_default","SchemaPropertyExamples_vue_vue_type_script_setup_true_lang_default","SchemaPropertyExamples_default"],"sources":["../../src/schema/SchemaPropertyExamples.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { ScalarIcon } from '@scalar/components/icon'\nimport { useClipboard } from '@scalar/use-hooks/useClipboard'\nimport { onClickOutside, onKeyStroke } from '@vueuse/core'\nimport { computed, ref, useId } from 'vue'\n\nimport { formatExample } from './helpers/format-example'\nimport { normalizeRenderedExamples } from './helpers/get-rendered-example'\nimport LinkButton from './LinkButton.vue'\nimport { useLocalization } from './localization'\n\nconst {\n examples,\n example,\n align = 'center',\n} = defineProps<{\n /** Align the popup with its label when centering would overlap adjacent content. */\n align?: 'center' | 'start'\n examples?: unknown\n example?: unknown\n}>()\n\nconst { copyToClipboard } = useClipboard()\nconst { translate } = useLocalization()\n\n// `null` is a meaningful example value for nullable schemas, so only treat\n// `undefined` as \"not provided\".\nconst hasSingleExample = computed(() => example !== undefined)\n\nconst normalizedExamples = computed<\n { label: string | undefined; value: string | number; ariaLabel: string }[]\n>(() =>\n normalizeRenderedExamples(examples, { allowRawObjects: true }).map(\n (entry) => {\n const label = entry.summary || entry.name\n const value = formatExample(entry.value)\n return {\n label,\n value,\n ariaLabel: `${translate('common.copyExample')}: ${label ? `${label}: ` : ''}${value}`,\n }\n },\n ),\n)\n\nconst hasMultipleExamples = computed(() => normalizedExamples.value.length > 0)\n\nconst multipleExamplesLabel = computed(() =>\n normalizedExamples.value.length === 1\n ? translate('schema.example')\n : translate('schema.examples'),\n)\n\n/**\n * Hover/`:focus-within` CSS alone left the popup unreachable by Enter, Escape\n * or touch, so it is pinned open on click (as in SchemaPropertyPattern.vue).\n * `example` and `examples` can both render, so each popup has its own state.\n */\nconst singleRootRef = ref<HTMLElement | null>(null)\nconst singleTriggerRef = ref<HTMLElement | { $el: HTMLElement } | null>(null)\nconst isSingleOpen = ref(false)\nconst singlePopupId = useId()\n\nconst multipleRootRef = ref<HTMLElement | null>(null)\nconst multipleTriggerRef = ref<HTMLElement | { $el: HTMLElement } | null>(null)\nconst isMultipleOpen = ref(false)\nconst multiplePopupId = useId()\n\n/**\n * Focus opens the popup through the same state as the click, not a separate\n * `:focus-within` rule; with both, a click's own `focusin` opened it first and\n * the click closed it again. This flag stops a pointer press counting as focus.\n */\nlet openedByPointer = false\n\n/** Long enough to span a touch tap's delayed compatibility mouse events. */\nconst POINTER_GUARD_MS = 500\nlet pointerGuardTimer = 0\n\n/**\n * `closeAndRestore` refocuses the trigger, and `focus()` fires `focusin`\n * synchronously, which would re-open the popup and make the first Escape inert.\n */\nlet restoringFocus = false\n\nconst onPointerDown = (): void => {\n /*\n * A touch tap's compatibility mousedown (which moves focus) lands 50-150ms\n * after touchend, past any one-frame guard, so the tap opened then closed.\n */\n openedByPointer = true\n window.clearTimeout(pointerGuardTimer)\n pointerGuardTimer = window.setTimeout(() => {\n openedByPointer = false\n }, POINTER_GUARD_MS)\n}\n\nconst leftPopup = (event: FocusEvent, root: HTMLElement | null): boolean => {\n const next = event.relatedTarget\n\n return !(next instanceof Node) || !root?.contains(next)\n}\n\nconst onSingleFocusIn = (): void => {\n if (!openedByPointer && !restoringFocus) {\n isSingleOpen.value = true\n }\n}\n\nconst onSingleFocusOut = (event: FocusEvent): void => {\n if (leftPopup(event, singleRootRef.value)) {\n isSingleOpen.value = false\n }\n}\n\nconst onMultipleFocusIn = (): void => {\n if (!openedByPointer && !restoringFocus) {\n isMultipleOpen.value = true\n }\n}\n\nconst onMultipleFocusOut = (event: FocusEvent): void => {\n if (leftPopup(event, multipleRootRef.value)) {\n isMultipleOpen.value = false\n }\n}\n\nonClickOutside(singleRootRef, () => {\n isSingleOpen.value = false\n})\n\nonClickOutside(multipleRootRef, () => {\n isMultipleOpen.value = false\n})\n\n/**\n * Closing hides the popup outright, so focus is handed back deliberately, or\n * Escape from inside it drops focus to <body>.\n */\nconst closeAndRestore = (\n open: typeof isSingleOpen,\n root: typeof singleRootRef,\n trigger: typeof singleTriggerRef,\n): void => {\n if (!open.value) {\n return\n }\n\n const wasInside = root.value?.contains(document.activeElement)\n\n open.value = false\n\n if (wasInside) {\n const element = trigger.value\n const focusable = element instanceof HTMLElement ? element : element?.$el\n\n restoringFocus = true\n focusable?.focus?.()\n restoringFocus = false\n }\n}\n\nonKeyStroke('Escape', () => {\n closeAndRestore(isSingleOpen, singleRootRef, singleTriggerRef)\n closeAndRestore(isMultipleOpen, multipleRootRef, multipleTriggerRef)\n})\n</script>\n<template>\n <!-- single example (deprecated) -->\n <template v-if=\"hasSingleExample\">\n <div\n ref=\"singleRootRef\"\n class=\"property-example\"\n :class=\"{ 'is-open': isSingleOpen }\"\n @focusin=\"onSingleFocusIn\"\n @focusout=\"onSingleFocusOut\">\n <LinkButton\n ref=\"singleTriggerRef\"\n :aria-controls=\"singlePopupId\"\n :aria-expanded=\"isSingleOpen\"\n class=\"decoration-dotted\"\n @click=\"isSingleOpen = !isSingleOpen\"\n @pointerdown=\"onPointerDown\">\n {{ translate('schema.example') }}\n </LinkButton>\n <div\n :id=\"singlePopupId\"\n class=\"property-example-value-list\"\n :class=\"{\n 'flex!': isSingleOpen,\n 'property-example-value-list-start': align === 'start',\n }\">\n <button\n :aria-label=\"`${translate('common.copyExample')}: ${formatExample(example)}`\"\n class=\"property-example-value group\"\n type=\"button\"\n @click=\"copyToClipboard(formatExample(example))\">\n <span>\n {{ formatExample(example) }}\n </span>\n <ScalarIcon\n aria-hidden=\"true\"\n class=\"group-hover:text-c-1 text-c-3 ml-auto min-h-3 min-w-3\"\n icon=\"Clipboard\"\n size=\"xs\" />\n </button>\n </div>\n </div>\n </template>\n\n <!-- multiple examples -->\n <template v-if=\"hasMultipleExamples\">\n <div\n ref=\"multipleRootRef\"\n class=\"property-example\"\n :class=\"{ 'is-open': isMultipleOpen }\"\n @focusin=\"onMultipleFocusIn\"\n @focusout=\"onMultipleFocusOut\">\n <LinkButton\n ref=\"multipleTriggerRef\"\n :aria-controls=\"multiplePopupId\"\n :aria-expanded=\"isMultipleOpen\"\n class=\"decoration-dotted\"\n @click=\"isMultipleOpen = !isMultipleOpen\"\n @pointerdown=\"onPointerDown\">\n {{ multipleExamplesLabel }}\n </LinkButton>\n <div\n :id=\"multiplePopupId\"\n class=\"property-example-value-list gap-3! p-3!\"\n :class=\"{\n 'flex!': isMultipleOpen,\n 'property-example-value-list-start': align === 'start',\n }\">\n <div\n v-for=\"(ex, key) in normalizedExamples\"\n :key=\"key\"\n class=\"flex min-w-0 flex-col gap-1.5\">\n <span\n v-if=\"ex.label\"\n class=\"text-c-2 font-sans text-xs font-normal break-words\">\n {{ ex.label }}\n </span>\n <button\n :aria-label=\"ex.ariaLabel\"\n class=\"property-example-value group text-left\"\n type=\"button\"\n @click=\"copyToClipboard(ex.value)\">\n <span>{{ ex.value }}</span>\n <ScalarIcon\n aria-hidden=\"true\"\n class=\"text-c-3 group-hover:text-c-1 ml-auto min-h-3 min-w-3\"\n icon=\"Clipboard\"\n size=\"xs\" />\n </button>\n </div>\n </div>\n </div>\n </template>\n</template>\n\n<style scoped>\n@reference \"../style.css\";\n\n.property-example {\n display: flex;\n flex-direction: column;\n font-size: var(--scalar-mini);\n position: relative;\n}\n.property-example:hover:before {\n pointer-events: none;\n content: '';\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 20px;\n border-radius: var(--scalar-radius);\n}\n.property-example-value {\n font-family: var(--scalar-font-code);\n display: flex;\n gap: 8px;\n align-items: center;\n width: 100%;\n padding: 6px;\n}\n.property-example-value span {\n display: block;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: pre;\n}\n.property-example-value :deep(svg) {\n color: var(--scalar-color-3);\n}\n\n.property-example-value:hover :deep(svg) {\n color: var(--scalar-color-1);\n}\n\n.property-example-value {\n background: var(--scalar-background-2);\n border: var(--scalar-border-width) solid var(--scalar-border-color);\n border-radius: var(--scalar-radius);\n}\n.property-example-value-list {\n position: absolute;\n top: 18px;\n left: 50%;\n transform: translate3d(-50%, 0, 0);\n overflow: auto;\n background-color: var(--scalar-background-1);\n box-shadow: var(--scalar-shadow-1);\n border-radius: var(--scalar-radius-lg);\n border: var(--scalar-border-width) solid var(--scalar-border-color);\n padding: 9px;\n min-width: 200px;\n max-width: 300px;\n flex-direction: column;\n gap: 3px;\n display: none;\n @apply z-context;\n}\n.property-example-value-list-start {\n left: 0;\n transform: none;\n}\n.property-example:hover .property-example-value-list {\n display: flex;\n}\n</style>\n"],"mappings":""}