@scalar/api-reference 1.51.0 → 1.52.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/dist/browser/standalone.js +211 -209
- package/dist/browser/webpack-stats.json +1 -1
- package/dist/components/ApiReference.vue.js +1 -1
- package/dist/components/ApiReference.vue.js.map +1 -1
- package/dist/components/ApiReference.vue.script.js +1 -1
- package/dist/components/ApiReference.vue.script.js.map +1 -1
- package/dist/components/Content/Schema/SchemaPropertyExamples.vue.d.ts.map +1 -1
- package/dist/components/Content/Schema/SchemaPropertyExamples.vue.js +1 -1
- package/dist/components/Content/Schema/SchemaPropertyExamples.vue.js.map +1 -1
- package/dist/components/Content/Schema/SchemaPropertyExamples.vue.script.js.map +1 -1
- package/dist/features/Operation/components/ParameterListItem.vue.d.ts.map +1 -1
- package/dist/features/Operation/components/ParameterListItem.vue.js +1 -1
- package/dist/features/Operation/components/ParameterListItem.vue.js.map +1 -1
- package/dist/features/Operation/components/ParameterListItem.vue.script.js +22 -13
- package/dist/features/Operation/components/ParameterListItem.vue.script.js.map +1 -1
- package/dist/features/Operation/components/RequestBody.vue.d.ts.map +1 -1
- package/dist/features/Operation/components/RequestBody.vue.js +1 -1
- package/dist/features/Operation/components/RequestBody.vue.js.map +1 -1
- package/dist/features/Operation/components/RequestBody.vue.script.js +31 -21
- package/dist/features/Operation/components/RequestBody.vue.script.js.map +1 -1
- package/dist/features/Search/helpers/create-fuse-instance.d.ts.map +1 -1
- package/dist/features/Search/helpers/create-fuse-instance.js +4 -0
- package/dist/features/Search/helpers/create-fuse-instance.js.map +1 -1
- package/dist/features/Search/helpers/create-search-index.js +4 -3
- package/dist/features/Search/helpers/create-search-index.js.map +1 -1
- package/dist/features/Search/types.d.ts +2 -2
- package/dist/features/Search/types.d.ts.map +1 -1
- package/dist/features/example-responses/ExampleResponses.vue.d.ts.map +1 -1
- package/dist/features/example-responses/ExampleResponses.vue.js +1 -1
- package/dist/features/example-responses/ExampleResponses.vue.js.map +1 -1
- package/dist/features/example-responses/ExampleResponses.vue.script.js +1 -1
- package/dist/features/example-responses/ExampleResponses.vue.script.js.map +1 -1
- package/dist/helpers/map-config-plugins.d.ts +3 -2
- package/dist/helpers/map-config-plugins.d.ts.map +1 -1
- package/dist/helpers/map-config-plugins.js +13 -9
- package/dist/helpers/map-config-plugins.js.map +1 -1
- package/dist/helpers/openapi.d.ts +6 -14
- package/dist/helpers/openapi.d.ts.map +1 -1
- package/dist/helpers/openapi.js +24 -29
- package/dist/helpers/openapi.js.map +1 -1
- package/dist/standalone/lib/html-api.d.ts.map +1 -1
- package/dist/standalone/lib/html-api.js +12 -12
- package/dist/standalone/lib/html-api.js.map +1 -1
- package/dist/style.css +210 -140
- package/package.json +11 -16
- package/dist/ssr.d.ts +0 -22
- package/dist/ssr.d.ts.map +0 -1
- package/dist/ssr.js +0 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-search-index.js","names":[],"sources":["../../../../src/features/Search/helpers/create-search-index.ts"],"sourcesContent":["import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { combineParams } from '@scalar/workspace-store/request-example'\nimport type { TraversedEntry } from '@scalar/workspace-store/schemas/navigation'\nimport type {\n MediaTypeObject,\n OpenApiDocument,\n OperationObject,\n ResponsesObject,\n} from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\n\nimport type { FuseData } from '@/features/Search/types'\nimport {
|
|
1
|
+
{"version":3,"file":"create-search-index.js","names":[],"sources":["../../../../src/features/Search/helpers/create-search-index.ts"],"sourcesContent":["import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { combineParams } from '@scalar/workspace-store/request-example'\nimport type { TraversedEntry } from '@scalar/workspace-store/schemas/navigation'\nimport type {\n MediaTypeObject,\n OpenApiDocument,\n OperationObject,\n ResponsesObject,\n} from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\n\nimport type { FuseData } from '@/features/Search/types'\nimport { extractParameters, extractRequestBody } from '@/helpers/openapi'\n\nfunction responseExampleValueToString(value: unknown): string {\n if (typeof value === 'string') {\n return value\n }\n\n try {\n return JSON.stringify(value)\n } catch (_error) {\n return ''\n }\n}\n\nfunction mediaTypeExamplesToStrings(mediaType: MediaTypeObject): string[] {\n const examplesFromNamedMap = Object.values(mediaType.examples ?? {})\n .flatMap((example) => {\n const resolvedExample = getResolvedRef(example)\n\n if (!resolvedExample || !('value' in resolvedExample)) {\n return []\n }\n\n return responseExampleValueToString(resolvedExample.value)\n })\n .filter((value) => value.length > 0)\n\n const mediaTypeExample =\n 'example' in mediaType && mediaType.example !== undefined ? responseExampleValueToString(mediaType.example) : ''\n\n return mediaTypeExample ? [mediaTypeExample, ...examplesFromNamedMap] : examplesFromNamedMap\n}\n\nfunction extractResponseExamples(responses: ResponsesObject | undefined): string[] {\n if (!responses) {\n return []\n }\n\n return Object.values(responses)\n .flatMap((response) => {\n const resolvedResponse = getResolvedRef(response)\n if (!resolvedResponse?.content) {\n return []\n }\n\n return Object.values(resolvedResponse.content).flatMap((mediaType) => {\n const resolvedMediaType = getResolvedRef(mediaType)\n if (!resolvedMediaType) {\n return []\n }\n\n return mediaTypeExamplesToStrings(resolvedMediaType)\n })\n })\n .filter((value) => value.length > 0)\n}\n\n/**\n * Create a search index from a list of entries.\n */\nexport function createSearchIndex(document: OpenApiDocument | undefined): FuseData[] {\n const index: FuseData[] = []\n\n /**\n * Recursively processes entries and their children to build the search index.\n */\n function processEntries(entriesToProcess: TraversedEntry[]): void {\n entriesToProcess.forEach((entry) => {\n addEntryToIndex(entry, index, document)\n\n // Recursively process children if they exist\n if ('children' in entry && entry.children) {\n processEntries(entry.children)\n }\n })\n }\n\n processEntries(document?.['x-scalar-navigation']?.children ?? [])\n\n return index\n}\n\n/**\n * Adds a single entry to the search index, handling all entry types recursively.\n */\nfunction addEntryToIndex(entry: TraversedEntry, index: FuseData[], document?: OpenApiDocument): void {\n // Operation\n if (entry.type === 'operation') {\n const pathItem = getResolvedRef(document?.paths?.[entry.path])\n const operation = (getResolvedRef(pathItem?.[entry.method]) ?? {}) as OperationObject\n const operationWithPathParams = {\n ...operation,\n parameters: combineParams(pathItem?.parameters, operation.parameters),\n }\n\n const parameters = extractParameters(operationWithPathParams.parameters ?? [])\n const body = extractRequestBody(operationWithPathParams)\n const responseExamples = extractResponseExamples(operationWithPathParams.responses)\n\n index.push({\n type: 'operation',\n title: entry.title,\n id: entry.id,\n description: operationWithPathParams.description || '',\n method: entry.method,\n path: entry.path,\n body: body || '',\n parameters: parameters ?? '',\n responseExamples,\n operationId: operationWithPathParams.operationId,\n entry,\n })\n\n return\n }\n\n // Webhook\n if (entry.type === 'webhook') {\n const webhook = getResolvedRef(document?.webhooks?.[entry.name]?.[entry.method]) ?? {}\n\n index.push({\n id: entry.id,\n type: 'webhook',\n title: entry.title,\n description: 'Webhook',\n method: entry.method,\n body: webhook.description || '',\n operationId: webhook.operationId,\n entry,\n })\n\n return\n }\n\n // Model\n if (entry.type === 'model') {\n const schema = getResolvedRef(document?.components?.schemas?.[entry.name])\n\n const description = schema?.description ?? ''\n\n index.push({\n type: 'model',\n title: entry.title,\n description: 'Model',\n id: entry.id,\n body: description,\n entry,\n })\n\n return\n }\n\n // Models heading\n if (entry.type === 'models') {\n index.push({\n id: entry.id,\n type: 'heading',\n title: 'Models',\n description: 'Heading',\n body: '',\n entry,\n })\n\n return\n }\n\n // Tag\n if (entry.type === 'tag' && entry.isWebhooks === true) {\n index.push({\n id: entry.id,\n type: 'heading',\n title: 'Webhooks',\n description: 'Heading',\n body: '',\n entry,\n })\n\n return\n }\n\n if (entry.type === 'tag' && entry.isGroup === false) {\n index.push({\n id: entry.id,\n title: entry.title,\n description: entry.description || '',\n type: 'tag',\n body: '',\n entry,\n })\n\n return\n }\n\n // Tag group\n if (entry.type === 'tag' && entry.isGroup === true) {\n index.push({\n id: entry.id,\n title: entry.title,\n description: 'Tag Group',\n type: 'tag',\n body: '',\n entry,\n })\n\n return\n }\n\n // Headings from info.description\n if (entry.type === 'text') {\n index.push({\n id: entry.id,\n type: 'heading',\n title: entry.title ?? '',\n description: 'Heading',\n body: '',\n entry,\n })\n\n return\n }\n}\n"],"mappings":";;;;AAaA,SAAS,6BAA6B,OAAwB;AAC5D,KAAI,OAAO,UAAU,SACnB,QAAO;AAGT,KAAI;AACF,SAAO,KAAK,UAAU,MAAM;UACrB,QAAQ;AACf,SAAO;;;AAIX,SAAS,2BAA2B,WAAsC;CACxE,MAAM,uBAAuB,OAAO,OAAO,UAAU,YAAY,EAAE,CAAC,CACjE,SAAS,YAAY;EACpB,MAAM,kBAAkB,eAAe,QAAQ;AAE/C,MAAI,CAAC,mBAAmB,EAAE,WAAW,iBACnC,QAAO,EAAE;AAGX,SAAO,6BAA6B,gBAAgB,MAAM;GAC1D,CACD,QAAQ,UAAU,MAAM,SAAS,EAAE;CAEtC,MAAM,mBACJ,aAAa,aAAa,UAAU,YAAY,KAAA,IAAY,6BAA6B,UAAU,QAAQ,GAAG;AAEhH,QAAO,mBAAmB,CAAC,kBAAkB,GAAG,qBAAqB,GAAG;;AAG1E,SAAS,wBAAwB,WAAkD;AACjF,KAAI,CAAC,UACH,QAAO,EAAE;AAGX,QAAO,OAAO,OAAO,UAAU,CAC5B,SAAS,aAAa;EACrB,MAAM,mBAAmB,eAAe,SAAS;AACjD,MAAI,CAAC,kBAAkB,QACrB,QAAO,EAAE;AAGX,SAAO,OAAO,OAAO,iBAAiB,QAAQ,CAAC,SAAS,cAAc;GACpE,MAAM,oBAAoB,eAAe,UAAU;AACnD,OAAI,CAAC,kBACH,QAAO,EAAE;AAGX,UAAO,2BAA2B,kBAAkB;IACpD;GACF,CACD,QAAQ,UAAU,MAAM,SAAS,EAAE;;;;;AAMxC,SAAgB,kBAAkB,UAAmD;CACnF,MAAM,QAAoB,EAAE;;;;CAK5B,SAAS,eAAe,kBAA0C;AAChE,mBAAiB,SAAS,UAAU;AAClC,mBAAgB,OA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AAI,MAAM,SAAS,UAAU;AAC3B,QAAM,KAAK;GACT,IAAI,MAAM;GACV,MAAM;GACN,OAAO;GACP,aAAa;GACb,MAAM;GACN;GACD,CAAC;AAEF;;AAIF,KAAI,MAAM,SAAS,SAAS,MAAM,eAAe,MAAM;AACrD,QAAM,KAAK;GACT,IAAI,MAAM;GACV,MAAM;GACN,OAAO;GACP,aAAa;GACb,MAAM;GACN;GACD,CAAC;AAEF;;AAGF,KAAI,MAAM,SAAS,SAAS,MAAM,YAAY,OAAO;AACnD,QAAM,KAAK;GACT,IAAI,MAAM;GACV,OAAO,MAAM;GACb,aAAa,MAAM,eAAe;GAClC,MAAM;GACN,MAAM;GACN;GACD,CAAC;AAEF;;AAIF,KAAI,MAAM,SAAS,SAAS,MAAM,YAAY,MAAM;AAClD,QAAM,KAAK;GACT,IAAI,MAAM;GACV,OAAO,MAAM;GACb,aAAa;GACb,MAAM;GACN,MAAM;GACN;GACD,CAAC;AAEF;;AAIF,KAAI,MAAM,SAAS,QAAQ;AACzB,QAAM,KAAK;GACT,IAAI,MAAM;GACV,MAAM;GACN,OAAO,MAAM,SAAS;GACtB,aAAa;GACb,MAAM;GACN;GACD,CAAC;AAEF"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import type { TraversedEntry } from '@scalar/workspace-store/schemas/navigation';
|
|
2
|
-
import type { ParameterMap } from '../../helpers/openapi.js';
|
|
3
2
|
export type EntryType = 'operation' | 'webhook' | 'model' | 'heading' | 'tag';
|
|
4
3
|
export type FuseData = {
|
|
5
4
|
type: EntryType;
|
|
6
5
|
id: string;
|
|
7
6
|
title: string;
|
|
8
7
|
description: string;
|
|
9
|
-
body?: string | string[]
|
|
8
|
+
body?: string | string[];
|
|
9
|
+
parameters?: string | string[];
|
|
10
10
|
responseExamples?: string[];
|
|
11
11
|
method?: string;
|
|
12
12
|
path?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/features/Search/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAA;AAEhF,
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/features/Search/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAA;AAEhF,MAAM,MAAM,SAAS,GAAG,WAAW,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,GAAG,KAAK,CAAA;AAE7E,MAAM,MAAM,QAAQ,GAAG;IACrB,IAAI,EAAE,SAAS,CAAA;IACf,EAAE,EAAE,MAAM,CAAA;IACV,KAAK,EAAE,MAAM,CAAA;IACb,WAAW,EAAE,MAAM,CAAA;IACnB,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;IACxB,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;IAC9B,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAA;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,KAAK,EAAE,cAAc,CAAA;CACtB,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExampleResponses.vue.d.ts","sourceRoot":"","sources":["../../../src/features/example-responses/ExampleResponses.vue"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"ExampleResponses.vue.d.ts","sourceRoot":"","sources":["../../../src/features/example-responses/ExampleResponses.vue"],"names":[],"mappings":"AAwWA,OAAO,KAAK,EAEV,eAAe,EAChB,MAAM,8DAA8D,CAAA;AAWrE;;GAEG;AAEH,KAAK,WAAW,GAAG;IACjB,SAAS,EAAE,eAAe,CAAA;CAC3B,CAAC;AA4WF,QAAA,MAAM,YAAY,kSAEhB,CAAC;wBACkB,OAAO,YAAY;AAAxC,wBAAyC"}
|
|
@@ -2,7 +2,7 @@ import _plugin_vue_export_helper_default from "../../_virtual/_plugin-vue_export
|
|
|
2
2
|
import ExampleResponses_vue_vue_type_script_setup_true_lang_default from "./ExampleResponses.vue.script.js";
|
|
3
3
|
/* empty css */
|
|
4
4
|
//#region src/features/example-responses/ExampleResponses.vue
|
|
5
|
-
var ExampleResponses_default = /* @__PURE__ */ _plugin_vue_export_helper_default(ExampleResponses_vue_vue_type_script_setup_true_lang_default, [["__scopeId", "data-v-
|
|
5
|
+
var ExampleResponses_default = /* @__PURE__ */ _plugin_vue_export_helper_default(ExampleResponses_vue_vue_type_script_setup_true_lang_default, [["__scopeId", "data-v-e0da130d"]]);
|
|
6
6
|
//#endregion
|
|
7
7
|
export { ExampleResponses_default as default };
|
|
8
8
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExampleResponses.vue.js","names":[],"sources":["../../../src/features/example-responses/ExampleResponses.vue"],"sourcesContent":["<script lang=\"ts\" setup>\nimport { ExamplePicker } from '@scalar/api-client/v2/blocks/operation-code-sample'\nimport {\n ScalarCard,\n ScalarCardFooter,\n ScalarCardSection,\n ScalarIcon,\n ScalarMarkdown,\n} from '@scalar/components'\nimport {\n getObjectKeys,\n normalizeMimeTypeObject,\n} from '@scalar/oas-utils/helpers'\nimport { useClipboard } from '@scalar/use-hooks/useClipboard'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { getExample } from '@scalar/workspace-store/request-example'\nimport type {\n MediaTypeObject,\n ResponsesObject,\n} from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport { computed, ref, toValue, useId, watch } from 'vue'\n\nimport ScreenReader from '@/components/ScreenReader.vue'\nimport ExampleSchema from '@/features/example-responses/ExampleSchema.vue'\n\nimport ExampleResponse from './ExampleResponse.vue'\nimport ExampleResponseTab from './ExampleResponseTab.vue'\nimport ExampleResponseTabList from './ExampleResponseTabList.vue'\nimport { hasResponseContent } from './has-response-content'\n\n/**\n * TODO: copyToClipboard isn't using the right content if there are multiple examples\n */\n\nconst { responses } = defineProps<{\n responses: ResponsesObject\n}>()\n\nconst id = useId()\nconst { copyToClipboard } = useClipboard()\n\n// Bring the status codes in the right order.\nconst orderedStatusCodes = computed<string[]>(() =>\n Object.keys(responses ?? {}).sort(),\n)\n\n// Filter to only valid response keys that should render in the example responses panel\nconst statusCodesWithContent = computed<string[]>(() =>\n orderedStatusCodes.value.filter((statusCode) =>\n hasResponseContent(getResolvedRef(responses?.[statusCode]), statusCode),\n ),\n)\n\n// Keep track of the current selected tab\nconst selectedResponseIndex = ref<number>(0)\n\n/**\n * Clamp the selected index when the filtered list shrinks.\n * Without this, the index can become out of bounds and cause a mismatch\n * between the visible tabs and the displayed content.\n *\n * We also reset `selectedExampleKey` to match the behavior of `changeTab`,\n * since the new response may not have the same example keys.\n */\nwatch(statusCodesWithContent, (codes) => {\n if (codes.length === 0) {\n selectedResponseIndex.value = 0\n selectedExampleKey.value = ''\n } else if (selectedResponseIndex.value >= codes.length) {\n selectedResponseIndex.value = codes.length - 1\n selectedExampleKey.value = ''\n }\n})\n\n// Return the whole response object\nconst currentResponse = computed(() => {\n const currentStatusCode =\n toValue(statusCodesWithContent)[toValue(selectedResponseIndex)] ?? ''\n\n return getResolvedRef(responses?.[currentStatusCode])\n})\n\nconst currentResponseContent = computed<MediaTypeObject | undefined>(() => {\n const normalizedContent = normalizeMimeTypeObject(\n currentResponse.value?.content,\n )\n\n /** All the keys of the normalized content */\n const keys = getObjectKeys(normalizedContent ?? {})\n\n return (\n // OpenAPI 3.x\n normalizedContent?.['application/json'] ??\n normalizedContent?.['application/xml'] ??\n normalizedContent?.['text/plain'] ??\n normalizedContent?.['text/html'] ??\n normalizedContent?.['*/*'] ??\n // Take the first key - in the future we may want to use the selected content type\n normalizedContent?.[keys[0] ?? ''] ??\n undefined\n )\n})\n\nconst hasMultipleExamples = computed<boolean>(\n () =>\n !!currentResponseContent.value?.examples &&\n Object.keys(currentResponseContent.value?.examples ?? {}).length > 1,\n)\n\nconst selectedExampleKey = ref<string>(\n Object.keys(currentResponseContent.value?.examples ?? {})[0] ?? '',\n)\n\n/** Get the current example to display */\nconst currentExample = computed(() => {\n if (!currentResponseContent.value) {\n return undefined\n }\n\n // When multiple examples exist and one is selected, we access it directly\n if (hasMultipleExamples.value && selectedExampleKey.value) {\n return currentResponseContent.value.examples?.[selectedExampleKey.value]\n }\n\n // Otherwise, we use getExample with an undefined exampleKey to handle fallbacks\n return getExample(currentResponseContent.value, undefined, undefined)\n})\n\nconst changeTab = (index: number) => {\n selectedResponseIndex.value = index\n selectedExampleKey.value = ''\n}\n\nconst showSchema = ref(false)\n</script>\n<template>\n <ScalarCard\n v-if=\"statusCodesWithContent.length\"\n aria-label=\"Example Responses\"\n class=\"response-card\"\n role=\"region\">\n <ExampleResponseTabList @change=\"changeTab\">\n <ExampleResponseTab\n v-for=\"statusCode in statusCodesWithContent\"\n :key=\"statusCode\"\n :aria-controls=\"id\">\n <ScreenReader>Status:</ScreenReader>\n {{ statusCode }}\n </ExampleResponseTab>\n\n <template #actions>\n <button\n v-if=\"currentResponseContent?.example\"\n class=\"code-copy\"\n type=\"button\"\n @click=\"() => copyToClipboard(currentResponseContent?.example)\">\n <ScalarIcon\n icon=\"Clipboard\"\n width=\"12px\" />\n </button>\n <label\n v-if=\"currentResponseContent?.schema\"\n class=\"scalar-card-checkbox\">\n Show Schema\n <input\n v-model=\"showSchema\"\n :aria-controls=\"id\"\n class=\"scalar-card-checkbox-input\"\n type=\"checkbox\" />\n <span class=\"scalar-card-checkbox-checkmark\" />\n </label>\n </template>\n </ExampleResponseTabList>\n <ScalarCardSection class=\"grid flex-1\">\n <!-- Schema -->\n <ExampleSchema\n v-if=\"currentResponseContent?.schema && showSchema\"\n :id=\"id\"\n :schema=\"currentResponseContent?.schema\" />\n\n <!-- Example -->\n <ExampleResponse\n v-else\n :id=\"id\"\n :example=\"currentExample\"\n :response=\"currentResponseContent\" />\n </ScalarCardSection>\n <ScalarCardFooter\n v-if=\"currentResponse?.description || hasMultipleExamples\"\n class=\"response-card-footer\">\n <ExamplePicker\n v-if=\"hasMultipleExamples\"\n v-model=\"selectedExampleKey\"\n class=\"response-example-selector px-0\"\n :examples=\"currentResponseContent?.examples\" />\n <div class=\"response-description\">\n <ScalarMarkdown\n v-if=\"currentResponse?.description\"\n class=\"response-description-markdown\"\n :value=\"currentResponse.description\" />\n </div>\n </ScalarCardFooter>\n </ScalarCard>\n</template>\n\n<style scoped>\n.response-card {\n font-size: var(--scalar-font-size-3);\n}\n\n.code-copy {\n display: flex;\n align-items: center;\n justify-content: center;\n appearance: none;\n -webkit-appearance: none;\n outline: none;\n background: transparent;\n cursor: pointer;\n color: var(--scalar-color-3);\n border: none;\n padding: 0;\n margin-right: 12px;\n}\n.code-copy:hover {\n color: var(--scalar-color-1);\n}\n.code-copy svg {\n width: 13px;\n height: 13px;\n}\n.response-card-footer {\n display: flex;\n flex-direction: row-reverse;\n flex-wrap: wrap;\n justify-content: start;\n flex-shrink: 0;\n padding: 7px 12px;\n column-gap: 8px;\n}\n.response-example-selector {\n flex-shrink: 0;\n margin: -4px;\n}\n.response-description {\n font-weight: var(--scalar-semibold);\n font-size: var(--scalar-small);\n color: var(--scalar-color--1);\n\n box-sizing: border-box;\n\n flex-grow: 1;\n}\n.response-description-markdown {\n max-height: 3lh;\n}\n\n.response-description-markdown :deep(*) {\n margin: 0;\n}\n.schema-type {\n font-size: var(--scalar-micro);\n color: var(--scalar-color-2);\n font-weight: var(--scalar-semibold);\n background: var(--scalar-background-3);\n padding: 2px 4px;\n border-radius: 4px;\n margin-right: 4px;\n}\n.schema-example {\n font-size: var(--scalar-micro);\n color: var(--scalar-color-2);\n font-weight: var(--scalar-semibold);\n}\n\n.example-response-tab {\n display: block;\n margin: 6px;\n}\n\n.scalar-card-checkbox {\n display: flex;\n align-items: center;\n justify-content: center;\n position: relative;\n min-height: 17px;\n cursor: pointer;\n user-select: none;\n font-size: var(--scalar-small);\n font-weight: var(--scalar-font-normal);\n color: var(--scalar-color-2);\n width: fit-content;\n white-space: nowrap;\n gap: 6px;\n padding: 7px 6px;\n}\n.scalar-card-checkbox:has(.scalar-card-checkbox-input:focus-visible)\n .scalar-card-checkbox-checkmark {\n outline: 1px solid var(--scalar-color-accent);\n}\n.scalar-card-checkbox:hover {\n color: var(--scalar-color--1);\n}\n.scalar-card-checkbox .scalar-card-checkbox-input {\n position: absolute;\n opacity: 0;\n cursor: pointer;\n height: 0;\n width: 0;\n}\n\n.scalar-card-checkbox-checkmark {\n height: 16px;\n width: 16px;\n border-radius: var(--scalar-radius);\n background-color: transparent;\n background-color: var(--scalar-background-3);\n box-shadow: inset 0 0 0 var(--scalar-border-width) var(--scalar-border-color);\n}\n.scalar-card-checkbox:has(.scalar-card-checkbox-input:checked) {\n color: var(--scalar-color-1);\n font-weight: var(--scalar-semibold);\n}\n\n.scalar-card-checkbox\n .scalar-card-checkbox-input:checked\n ~ .scalar-card-checkbox-checkmark {\n background-color: var(--scalar-button-1);\n box-shadow: none;\n}\n\n.scalar-card-checkbox-checkmark:after {\n content: '';\n position: absolute;\n display: none;\n}\n\n.scalar-card-checkbox\n .scalar-card-checkbox-input:checked\n ~ .scalar-card-checkbox-checkmark:after {\n display: block;\n}\n\n.scalar-card-checkbox .scalar-card-checkbox-checkmark:after {\n right: 11.5px;\n top: 12.5px;\n width: 5px;\n height: 9px;\n border: solid 1px var(--scalar-button-1-color);\n border-width: 0 1.5px 1.5px 0;\n transform: rotate(45deg);\n}\n</style>\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"ExampleResponses.vue.js","names":[],"sources":["../../../src/features/example-responses/ExampleResponses.vue"],"sourcesContent":["<script lang=\"ts\" setup>\nimport { ExamplePicker } from '@scalar/api-client/v2/blocks/operation-code-sample'\nimport {\n ScalarCard,\n ScalarCardFooter,\n ScalarCardSection,\n ScalarIcon,\n ScalarMarkdown,\n} from '@scalar/components'\nimport {\n getObjectKeys,\n normalizeMimeTypeObject,\n} from '@scalar/oas-utils/helpers'\nimport { useClipboard } from '@scalar/use-hooks/useClipboard'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { getExample } from '@scalar/workspace-store/request-example'\nimport type {\n MediaTypeObject,\n ResponsesObject,\n} from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport { computed, ref, toValue, useId, watch } from 'vue'\n\nimport ScreenReader from '@/components/ScreenReader.vue'\nimport ExampleSchema from '@/features/example-responses/ExampleSchema.vue'\n\nimport ExampleResponse from './ExampleResponse.vue'\nimport ExampleResponseTab from './ExampleResponseTab.vue'\nimport ExampleResponseTabList from './ExampleResponseTabList.vue'\nimport { hasResponseContent } from './has-response-content'\n\n/**\n * TODO: copyToClipboard isn't using the right content if there are multiple examples\n */\n\nconst { responses } = defineProps<{\n responses: ResponsesObject\n}>()\n\nconst id = useId()\nconst { copyToClipboard } = useClipboard()\n\n// Bring the status codes in the right order.\nconst orderedStatusCodes = computed<string[]>(() =>\n Object.keys(responses ?? {}).sort(),\n)\n\n// Filter to only valid response keys that should render in the example responses panel\nconst statusCodesWithContent = computed<string[]>(() =>\n orderedStatusCodes.value.filter((statusCode) =>\n hasResponseContent(getResolvedRef(responses?.[statusCode]), statusCode),\n ),\n)\n\n// Keep track of the current selected tab\nconst selectedResponseIndex = ref<number>(0)\n\n/**\n * Clamp the selected index when the filtered list shrinks.\n * Without this, the index can become out of bounds and cause a mismatch\n * between the visible tabs and the displayed content.\n *\n * We also reset `selectedExampleKey` to match the behavior of `changeTab`,\n * since the new response may not have the same example keys.\n */\nwatch(statusCodesWithContent, (codes) => {\n if (codes.length === 0) {\n selectedResponseIndex.value = 0\n selectedExampleKey.value = ''\n } else if (selectedResponseIndex.value >= codes.length) {\n selectedResponseIndex.value = codes.length - 1\n selectedExampleKey.value = ''\n }\n})\n\n// Return the whole response object\nconst currentResponse = computed(() => {\n const currentStatusCode =\n toValue(statusCodesWithContent)[toValue(selectedResponseIndex)] ?? ''\n\n return getResolvedRef(responses?.[currentStatusCode])\n})\n\nconst currentResponseContent = computed<MediaTypeObject | undefined>(() => {\n const normalizedContent = normalizeMimeTypeObject(\n currentResponse.value?.content,\n )\n\n /** All the keys of the normalized content */\n const keys = getObjectKeys(normalizedContent ?? {})\n return normalizedContent?.[keys[0] ?? '']\n})\n\nconst hasMultipleExamples = computed<boolean>(\n () =>\n !!currentResponseContent.value?.examples &&\n Object.keys(currentResponseContent.value?.examples ?? {}).length > 1,\n)\n\nconst selectedExampleKey = ref<string>(\n Object.keys(currentResponseContent.value?.examples ?? {})[0] ?? '',\n)\n\n/** Get the current example to display */\nconst currentExample = computed(() => {\n if (!currentResponseContent.value) {\n return undefined\n }\n\n // When multiple examples exist and one is selected, we access it directly\n if (hasMultipleExamples.value && selectedExampleKey.value) {\n return currentResponseContent.value.examples?.[selectedExampleKey.value]\n }\n\n // Otherwise, we use getExample with an undefined exampleKey to handle fallbacks\n return getExample(currentResponseContent.value, undefined, undefined)\n})\n\nconst changeTab = (index: number) => {\n selectedResponseIndex.value = index\n selectedExampleKey.value = ''\n}\n\nconst showSchema = ref(false)\n</script>\n<template>\n <ScalarCard\n v-if=\"statusCodesWithContent.length\"\n aria-label=\"Example Responses\"\n class=\"response-card\"\n role=\"region\">\n <ExampleResponseTabList @change=\"changeTab\">\n <ExampleResponseTab\n v-for=\"statusCode in statusCodesWithContent\"\n :key=\"statusCode\"\n :aria-controls=\"id\">\n <ScreenReader>Status:</ScreenReader>\n {{ statusCode }}\n </ExampleResponseTab>\n\n <template #actions>\n <button\n v-if=\"currentResponseContent?.example\"\n class=\"code-copy\"\n type=\"button\"\n @click=\"() => copyToClipboard(currentResponseContent?.example)\">\n <ScalarIcon\n icon=\"Clipboard\"\n width=\"12px\" />\n </button>\n <label\n v-if=\"currentResponseContent?.schema\"\n class=\"scalar-card-checkbox\">\n Show Schema\n <input\n v-model=\"showSchema\"\n :aria-controls=\"id\"\n class=\"scalar-card-checkbox-input\"\n type=\"checkbox\" />\n <span class=\"scalar-card-checkbox-checkmark\" />\n </label>\n </template>\n </ExampleResponseTabList>\n <ScalarCardSection class=\"grid flex-1\">\n <!-- Schema -->\n <ExampleSchema\n v-if=\"currentResponseContent?.schema && showSchema\"\n :id=\"id\"\n :schema=\"currentResponseContent?.schema\" />\n\n <!-- Example -->\n <ExampleResponse\n v-else\n :id=\"id\"\n :example=\"currentExample\"\n :response=\"currentResponseContent\" />\n </ScalarCardSection>\n <ScalarCardFooter\n v-if=\"currentResponse?.description || hasMultipleExamples\"\n class=\"response-card-footer\">\n <ExamplePicker\n v-if=\"hasMultipleExamples\"\n v-model=\"selectedExampleKey\"\n class=\"response-example-selector px-0\"\n :examples=\"currentResponseContent?.examples\" />\n <div class=\"response-description\">\n <ScalarMarkdown\n v-if=\"currentResponse?.description\"\n class=\"response-description-markdown\"\n :value=\"currentResponse.description\" />\n </div>\n </ScalarCardFooter>\n </ScalarCard>\n</template>\n\n<style scoped>\n.response-card {\n font-size: var(--scalar-font-size-3);\n}\n\n.code-copy {\n display: flex;\n align-items: center;\n justify-content: center;\n appearance: none;\n -webkit-appearance: none;\n outline: none;\n background: transparent;\n cursor: pointer;\n color: var(--scalar-color-3);\n border: none;\n padding: 0;\n margin-right: 12px;\n}\n.code-copy:hover {\n color: var(--scalar-color-1);\n}\n.code-copy svg {\n width: 13px;\n height: 13px;\n}\n.response-card-footer {\n display: flex;\n flex-direction: row-reverse;\n flex-wrap: wrap;\n justify-content: start;\n flex-shrink: 0;\n padding: 7px 12px;\n column-gap: 8px;\n}\n.response-example-selector {\n flex-shrink: 0;\n margin: -4px;\n}\n.response-description {\n font-weight: var(--scalar-semibold);\n font-size: var(--scalar-small);\n color: var(--scalar-color--1);\n\n box-sizing: border-box;\n\n flex-grow: 1;\n}\n.response-description-markdown {\n max-height: 3lh;\n}\n\n.response-description-markdown :deep(*) {\n margin: 0;\n}\n.schema-type {\n font-size: var(--scalar-micro);\n color: var(--scalar-color-2);\n font-weight: var(--scalar-semibold);\n background: var(--scalar-background-3);\n padding: 2px 4px;\n border-radius: 4px;\n margin-right: 4px;\n}\n.schema-example {\n font-size: var(--scalar-micro);\n color: var(--scalar-color-2);\n font-weight: var(--scalar-semibold);\n}\n\n.example-response-tab {\n display: block;\n margin: 6px;\n}\n\n.scalar-card-checkbox {\n display: flex;\n align-items: center;\n justify-content: center;\n position: relative;\n min-height: 17px;\n cursor: pointer;\n user-select: none;\n font-size: var(--scalar-small);\n font-weight: var(--scalar-font-normal);\n color: var(--scalar-color-2);\n width: fit-content;\n white-space: nowrap;\n gap: 6px;\n padding: 7px 6px;\n}\n.scalar-card-checkbox:has(.scalar-card-checkbox-input:focus-visible)\n .scalar-card-checkbox-checkmark {\n outline: 1px solid var(--scalar-color-accent);\n}\n.scalar-card-checkbox:hover {\n color: var(--scalar-color--1);\n}\n.scalar-card-checkbox .scalar-card-checkbox-input {\n position: absolute;\n opacity: 0;\n cursor: pointer;\n height: 0;\n width: 0;\n}\n\n.scalar-card-checkbox-checkmark {\n height: 16px;\n width: 16px;\n border-radius: var(--scalar-radius);\n background-color: transparent;\n background-color: var(--scalar-background-3);\n box-shadow: inset 0 0 0 var(--scalar-border-width) var(--scalar-border-color);\n}\n.scalar-card-checkbox:has(.scalar-card-checkbox-input:checked) {\n color: var(--scalar-color-1);\n font-weight: var(--scalar-semibold);\n}\n\n.scalar-card-checkbox\n .scalar-card-checkbox-input:checked\n ~ .scalar-card-checkbox-checkmark {\n background-color: var(--scalar-button-1);\n box-shadow: none;\n}\n\n.scalar-card-checkbox-checkmark:after {\n content: '';\n position: absolute;\n display: none;\n}\n\n.scalar-card-checkbox\n .scalar-card-checkbox-input:checked\n ~ .scalar-card-checkbox-checkmark:after {\n display: block;\n}\n\n.scalar-card-checkbox .scalar-card-checkbox-checkmark:after {\n right: 11.5px;\n top: 12.5px;\n width: 5px;\n height: 9px;\n border: solid 1px var(--scalar-button-1-color);\n border-width: 0 1.5px 1.5px 0;\n transform: rotate(45deg);\n}\n</style>\n"],"mappings":""}
|
|
@@ -55,7 +55,7 @@ var ExampleResponses_vue_vue_type_script_setup_true_lang_default = /* @__PURE__
|
|
|
55
55
|
const normalizedContent = normalizeMimeTypeObject(currentResponse.value?.content);
|
|
56
56
|
/** All the keys of the normalized content */
|
|
57
57
|
const keys = getObjectKeys(normalizedContent ?? {});
|
|
58
|
-
return normalizedContent?.[
|
|
58
|
+
return normalizedContent?.[keys[0] ?? ""];
|
|
59
59
|
});
|
|
60
60
|
const hasMultipleExamples = computed(() => !!currentResponseContent.value?.examples && Object.keys(currentResponseContent.value?.examples ?? {}).length > 1);
|
|
61
61
|
const selectedExampleKey = ref(Object.keys(currentResponseContent.value?.examples ?? {})[0] ?? "");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExampleResponses.vue.script.js","names":[],"sources":["../../../src/features/example-responses/ExampleResponses.vue"],"sourcesContent":["<script lang=\"ts\" setup>\nimport { ExamplePicker } from '@scalar/api-client/v2/blocks/operation-code-sample'\nimport {\n ScalarCard,\n ScalarCardFooter,\n ScalarCardSection,\n ScalarIcon,\n ScalarMarkdown,\n} from '@scalar/components'\nimport {\n getObjectKeys,\n normalizeMimeTypeObject,\n} from '@scalar/oas-utils/helpers'\nimport { useClipboard } from '@scalar/use-hooks/useClipboard'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { getExample } from '@scalar/workspace-store/request-example'\nimport type {\n MediaTypeObject,\n ResponsesObject,\n} from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport { computed, ref, toValue, useId, watch } from 'vue'\n\nimport ScreenReader from '@/components/ScreenReader.vue'\nimport ExampleSchema from '@/features/example-responses/ExampleSchema.vue'\n\nimport ExampleResponse from './ExampleResponse.vue'\nimport ExampleResponseTab from './ExampleResponseTab.vue'\nimport ExampleResponseTabList from './ExampleResponseTabList.vue'\nimport { hasResponseContent } from './has-response-content'\n\n/**\n * TODO: copyToClipboard isn't using the right content if there are multiple examples\n */\n\nconst { responses } = defineProps<{\n responses: ResponsesObject\n}>()\n\nconst id = useId()\nconst { copyToClipboard } = useClipboard()\n\n// Bring the status codes in the right order.\nconst orderedStatusCodes = computed<string[]>(() =>\n Object.keys(responses ?? {}).sort(),\n)\n\n// Filter to only valid response keys that should render in the example responses panel\nconst statusCodesWithContent = computed<string[]>(() =>\n orderedStatusCodes.value.filter((statusCode) =>\n hasResponseContent(getResolvedRef(responses?.[statusCode]), statusCode),\n ),\n)\n\n// Keep track of the current selected tab\nconst selectedResponseIndex = ref<number>(0)\n\n/**\n * Clamp the selected index when the filtered list shrinks.\n * Without this, the index can become out of bounds and cause a mismatch\n * between the visible tabs and the displayed content.\n *\n * We also reset `selectedExampleKey` to match the behavior of `changeTab`,\n * since the new response may not have the same example keys.\n */\nwatch(statusCodesWithContent, (codes) => {\n if (codes.length === 0) {\n selectedResponseIndex.value = 0\n selectedExampleKey.value = ''\n } else if (selectedResponseIndex.value >= codes.length) {\n selectedResponseIndex.value = codes.length - 1\n selectedExampleKey.value = ''\n }\n})\n\n// Return the whole response object\nconst currentResponse = computed(() => {\n const currentStatusCode =\n toValue(statusCodesWithContent)[toValue(selectedResponseIndex)] ?? ''\n\n return getResolvedRef(responses?.[currentStatusCode])\n})\n\nconst currentResponseContent = computed<MediaTypeObject | undefined>(() => {\n const normalizedContent = normalizeMimeTypeObject(\n currentResponse.value?.content,\n )\n\n /** All the keys of the normalized content */\n const keys = getObjectKeys(normalizedContent ?? {})\n\n return (\n // OpenAPI 3.x\n normalizedContent?.['application/json'] ??\n normalizedContent?.['application/xml'] ??\n normalizedContent?.['text/plain'] ??\n normalizedContent?.['text/html'] ??\n normalizedContent?.['*/*'] ??\n // Take the first key - in the future we may want to use the selected content type\n normalizedContent?.[keys[0] ?? ''] ??\n undefined\n )\n})\n\nconst hasMultipleExamples = computed<boolean>(\n () =>\n !!currentResponseContent.value?.examples &&\n Object.keys(currentResponseContent.value?.examples ?? {}).length > 1,\n)\n\nconst selectedExampleKey = ref<string>(\n Object.keys(currentResponseContent.value?.examples ?? {})[0] ?? '',\n)\n\n/** Get the current example to display */\nconst currentExample = computed(() => {\n if (!currentResponseContent.value) {\n return undefined\n }\n\n // When multiple examples exist and one is selected, we access it directly\n if (hasMultipleExamples.value && selectedExampleKey.value) {\n return currentResponseContent.value.examples?.[selectedExampleKey.value]\n }\n\n // Otherwise, we use getExample with an undefined exampleKey to handle fallbacks\n return getExample(currentResponseContent.value, undefined, undefined)\n})\n\nconst changeTab = (index: number) => {\n selectedResponseIndex.value = index\n selectedExampleKey.value = ''\n}\n\nconst showSchema = ref(false)\n</script>\n<template>\n <ScalarCard\n v-if=\"statusCodesWithContent.length\"\n aria-label=\"Example Responses\"\n class=\"response-card\"\n role=\"region\">\n <ExampleResponseTabList @change=\"changeTab\">\n <ExampleResponseTab\n v-for=\"statusCode in statusCodesWithContent\"\n :key=\"statusCode\"\n :aria-controls=\"id\">\n <ScreenReader>Status:</ScreenReader>\n {{ statusCode }}\n </ExampleResponseTab>\n\n <template #actions>\n <button\n v-if=\"currentResponseContent?.example\"\n class=\"code-copy\"\n type=\"button\"\n @click=\"() => copyToClipboard(currentResponseContent?.example)\">\n <ScalarIcon\n icon=\"Clipboard\"\n width=\"12px\" />\n </button>\n <label\n v-if=\"currentResponseContent?.schema\"\n class=\"scalar-card-checkbox\">\n Show Schema\n <input\n v-model=\"showSchema\"\n :aria-controls=\"id\"\n class=\"scalar-card-checkbox-input\"\n type=\"checkbox\" />\n <span class=\"scalar-card-checkbox-checkmark\" />\n </label>\n </template>\n </ExampleResponseTabList>\n <ScalarCardSection class=\"grid flex-1\">\n <!-- Schema -->\n <ExampleSchema\n v-if=\"currentResponseContent?.schema && showSchema\"\n :id=\"id\"\n :schema=\"currentResponseContent?.schema\" />\n\n <!-- Example -->\n <ExampleResponse\n v-else\n :id=\"id\"\n :example=\"currentExample\"\n :response=\"currentResponseContent\" />\n </ScalarCardSection>\n <ScalarCardFooter\n v-if=\"currentResponse?.description || hasMultipleExamples\"\n class=\"response-card-footer\">\n <ExamplePicker\n v-if=\"hasMultipleExamples\"\n v-model=\"selectedExampleKey\"\n class=\"response-example-selector px-0\"\n :examples=\"currentResponseContent?.examples\" />\n <div class=\"response-description\">\n <ScalarMarkdown\n v-if=\"currentResponse?.description\"\n class=\"response-description-markdown\"\n :value=\"currentResponse.description\" />\n </div>\n </ScalarCardFooter>\n </ScalarCard>\n</template>\n\n<style scoped>\n.response-card {\n font-size: var(--scalar-font-size-3);\n}\n\n.code-copy {\n display: flex;\n align-items: center;\n justify-content: center;\n appearance: none;\n -webkit-appearance: none;\n outline: none;\n background: transparent;\n cursor: pointer;\n color: var(--scalar-color-3);\n border: none;\n padding: 0;\n margin-right: 12px;\n}\n.code-copy:hover {\n color: var(--scalar-color-1);\n}\n.code-copy svg {\n width: 13px;\n height: 13px;\n}\n.response-card-footer {\n display: flex;\n flex-direction: row-reverse;\n flex-wrap: wrap;\n justify-content: start;\n flex-shrink: 0;\n padding: 7px 12px;\n column-gap: 8px;\n}\n.response-example-selector {\n flex-shrink: 0;\n margin: -4px;\n}\n.response-description {\n font-weight: var(--scalar-semibold);\n font-size: var(--scalar-small);\n color: var(--scalar-color--1);\n\n box-sizing: border-box;\n\n flex-grow: 1;\n}\n.response-description-markdown {\n max-height: 3lh;\n}\n\n.response-description-markdown :deep(*) {\n margin: 0;\n}\n.schema-type {\n font-size: var(--scalar-micro);\n color: var(--scalar-color-2);\n font-weight: var(--scalar-semibold);\n background: var(--scalar-background-3);\n padding: 2px 4px;\n border-radius: 4px;\n margin-right: 4px;\n}\n.schema-example {\n font-size: var(--scalar-micro);\n color: var(--scalar-color-2);\n font-weight: var(--scalar-semibold);\n}\n\n.example-response-tab {\n display: block;\n margin: 6px;\n}\n\n.scalar-card-checkbox {\n display: flex;\n align-items: center;\n justify-content: center;\n position: relative;\n min-height: 17px;\n cursor: pointer;\n user-select: none;\n font-size: var(--scalar-small);\n font-weight: var(--scalar-font-normal);\n color: var(--scalar-color-2);\n width: fit-content;\n white-space: nowrap;\n gap: 6px;\n padding: 7px 6px;\n}\n.scalar-card-checkbox:has(.scalar-card-checkbox-input:focus-visible)\n .scalar-card-checkbox-checkmark {\n outline: 1px solid var(--scalar-color-accent);\n}\n.scalar-card-checkbox:hover {\n color: var(--scalar-color--1);\n}\n.scalar-card-checkbox .scalar-card-checkbox-input {\n position: absolute;\n opacity: 0;\n cursor: pointer;\n height: 0;\n width: 0;\n}\n\n.scalar-card-checkbox-checkmark {\n height: 16px;\n width: 16px;\n border-radius: var(--scalar-radius);\n background-color: transparent;\n background-color: var(--scalar-background-3);\n box-shadow: inset 0 0 0 var(--scalar-border-width) var(--scalar-border-color);\n}\n.scalar-card-checkbox:has(.scalar-card-checkbox-input:checked) {\n color: var(--scalar-color-1);\n font-weight: var(--scalar-semibold);\n}\n\n.scalar-card-checkbox\n .scalar-card-checkbox-input:checked\n ~ .scalar-card-checkbox-checkmark {\n background-color: var(--scalar-button-1);\n box-shadow: none;\n}\n\n.scalar-card-checkbox-checkmark:after {\n content: '';\n position: absolute;\n display: none;\n}\n\n.scalar-card-checkbox\n .scalar-card-checkbox-input:checked\n ~ .scalar-card-checkbox-checkmark:after {\n display: block;\n}\n\n.scalar-card-checkbox .scalar-card-checkbox-checkmark:after {\n right: 11.5px;\n top: 12.5px;\n width: 5px;\n height: 9px;\n border: solid 1px var(--scalar-button-1-color);\n border-width: 0 1.5px 1.5px 0;\n transform: rotate(45deg);\n}\n</style>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;EAsCA,MAAM,KAAK,OAAM;EACjB,MAAM,EAAE,oBAAoB,cAAa;EAGzC,MAAM,qBAAqB,eACzB,OAAO,KAAK,QAAA,aAAa,EAAE,CAAC,CAAC,MAAM,CACrC;EAGA,MAAM,yBAAyB,eAC7B,mBAAmB,MAAM,QAAQ,eAC/B,mBAAmB,eAAe,QAAA,YAAY,YAAY,EAAE,WAAW,CACxE,CACH;EAGA,MAAM,wBAAwB,IAAY,EAAC;;;;;;;;;AAU3C,QAAM,yBAAyB,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A,cAAA,EAAA;;mBAFtC,mBAAA;uFAAkB,QAAA;OAC3B,OAAM;OACL,UAAU,uBAAA,OAAwB;+EACrC,mBAKM,OALN,YAKM,CAHI,gBAAA,OAAiB,eAAA,WAAA,EADzB,YAGyC,MAAA,eAAA,EAAA;;OADvC,OAAM;OACL,OAAO,gBAAA,MAAgB"}
|
|
1
|
+
{"version":3,"file":"ExampleResponses.vue.script.js","names":[],"sources":["../../../src/features/example-responses/ExampleResponses.vue"],"sourcesContent":["<script lang=\"ts\" setup>\nimport { ExamplePicker } from '@scalar/api-client/v2/blocks/operation-code-sample'\nimport {\n ScalarCard,\n ScalarCardFooter,\n ScalarCardSection,\n ScalarIcon,\n ScalarMarkdown,\n} from '@scalar/components'\nimport {\n getObjectKeys,\n normalizeMimeTypeObject,\n} from '@scalar/oas-utils/helpers'\nimport { useClipboard } from '@scalar/use-hooks/useClipboard'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { getExample } from '@scalar/workspace-store/request-example'\nimport type {\n MediaTypeObject,\n ResponsesObject,\n} from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport { computed, ref, toValue, useId, watch } from 'vue'\n\nimport ScreenReader from '@/components/ScreenReader.vue'\nimport ExampleSchema from '@/features/example-responses/ExampleSchema.vue'\n\nimport ExampleResponse from './ExampleResponse.vue'\nimport ExampleResponseTab from './ExampleResponseTab.vue'\nimport ExampleResponseTabList from './ExampleResponseTabList.vue'\nimport { hasResponseContent } from './has-response-content'\n\n/**\n * TODO: copyToClipboard isn't using the right content if there are multiple examples\n */\n\nconst { responses } = defineProps<{\n responses: ResponsesObject\n}>()\n\nconst id = useId()\nconst { copyToClipboard } = useClipboard()\n\n// Bring the status codes in the right order.\nconst orderedStatusCodes = computed<string[]>(() =>\n Object.keys(responses ?? {}).sort(),\n)\n\n// Filter to only valid response keys that should render in the example responses panel\nconst statusCodesWithContent = computed<string[]>(() =>\n orderedStatusCodes.value.filter((statusCode) =>\n hasResponseContent(getResolvedRef(responses?.[statusCode]), statusCode),\n ),\n)\n\n// Keep track of the current selected tab\nconst selectedResponseIndex = ref<number>(0)\n\n/**\n * Clamp the selected index when the filtered list shrinks.\n * Without this, the index can become out of bounds and cause a mismatch\n * between the visible tabs and the displayed content.\n *\n * We also reset `selectedExampleKey` to match the behavior of `changeTab`,\n * since the new response may not have the same example keys.\n */\nwatch(statusCodesWithContent, (codes) => {\n if (codes.length === 0) {\n selectedResponseIndex.value = 0\n selectedExampleKey.value = ''\n } else if (selectedResponseIndex.value >= codes.length) {\n selectedResponseIndex.value = codes.length - 1\n selectedExampleKey.value = ''\n }\n})\n\n// Return the whole response object\nconst currentResponse = computed(() => {\n const currentStatusCode =\n toValue(statusCodesWithContent)[toValue(selectedResponseIndex)] ?? ''\n\n return getResolvedRef(responses?.[currentStatusCode])\n})\n\nconst currentResponseContent = computed<MediaTypeObject | undefined>(() => {\n const normalizedContent = normalizeMimeTypeObject(\n currentResponse.value?.content,\n )\n\n /** All the keys of the normalized content */\n const keys = getObjectKeys(normalizedContent ?? {})\n return normalizedContent?.[keys[0] ?? '']\n})\n\nconst hasMultipleExamples = computed<boolean>(\n () =>\n !!currentResponseContent.value?.examples &&\n Object.keys(currentResponseContent.value?.examples ?? {}).length > 1,\n)\n\nconst selectedExampleKey = ref<string>(\n Object.keys(currentResponseContent.value?.examples ?? {})[0] ?? '',\n)\n\n/** Get the current example to display */\nconst currentExample = computed(() => {\n if (!currentResponseContent.value) {\n return undefined\n }\n\n // When multiple examples exist and one is selected, we access it directly\n if (hasMultipleExamples.value && selectedExampleKey.value) {\n return currentResponseContent.value.examples?.[selectedExampleKey.value]\n }\n\n // Otherwise, we use getExample with an undefined exampleKey to handle fallbacks\n return getExample(currentResponseContent.value, undefined, undefined)\n})\n\nconst changeTab = (index: number) => {\n selectedResponseIndex.value = index\n selectedExampleKey.value = ''\n}\n\nconst showSchema = ref(false)\n</script>\n<template>\n <ScalarCard\n v-if=\"statusCodesWithContent.length\"\n aria-label=\"Example Responses\"\n class=\"response-card\"\n role=\"region\">\n <ExampleResponseTabList @change=\"changeTab\">\n <ExampleResponseTab\n v-for=\"statusCode in statusCodesWithContent\"\n :key=\"statusCode\"\n :aria-controls=\"id\">\n <ScreenReader>Status:</ScreenReader>\n {{ statusCode }}\n </ExampleResponseTab>\n\n <template #actions>\n <button\n v-if=\"currentResponseContent?.example\"\n class=\"code-copy\"\n type=\"button\"\n @click=\"() => copyToClipboard(currentResponseContent?.example)\">\n <ScalarIcon\n icon=\"Clipboard\"\n width=\"12px\" />\n </button>\n <label\n v-if=\"currentResponseContent?.schema\"\n class=\"scalar-card-checkbox\">\n Show Schema\n <input\n v-model=\"showSchema\"\n :aria-controls=\"id\"\n class=\"scalar-card-checkbox-input\"\n type=\"checkbox\" />\n <span class=\"scalar-card-checkbox-checkmark\" />\n </label>\n </template>\n </ExampleResponseTabList>\n <ScalarCardSection class=\"grid flex-1\">\n <!-- Schema -->\n <ExampleSchema\n v-if=\"currentResponseContent?.schema && showSchema\"\n :id=\"id\"\n :schema=\"currentResponseContent?.schema\" />\n\n <!-- Example -->\n <ExampleResponse\n v-else\n :id=\"id\"\n :example=\"currentExample\"\n :response=\"currentResponseContent\" />\n </ScalarCardSection>\n <ScalarCardFooter\n v-if=\"currentResponse?.description || hasMultipleExamples\"\n class=\"response-card-footer\">\n <ExamplePicker\n v-if=\"hasMultipleExamples\"\n v-model=\"selectedExampleKey\"\n class=\"response-example-selector px-0\"\n :examples=\"currentResponseContent?.examples\" />\n <div class=\"response-description\">\n <ScalarMarkdown\n v-if=\"currentResponse?.description\"\n class=\"response-description-markdown\"\n :value=\"currentResponse.description\" />\n </div>\n </ScalarCardFooter>\n </ScalarCard>\n</template>\n\n<style scoped>\n.response-card {\n font-size: var(--scalar-font-size-3);\n}\n\n.code-copy {\n display: flex;\n align-items: center;\n justify-content: center;\n appearance: none;\n -webkit-appearance: none;\n outline: none;\n background: transparent;\n cursor: pointer;\n color: var(--scalar-color-3);\n border: none;\n padding: 0;\n margin-right: 12px;\n}\n.code-copy:hover {\n color: var(--scalar-color-1);\n}\n.code-copy svg {\n width: 13px;\n height: 13px;\n}\n.response-card-footer {\n display: flex;\n flex-direction: row-reverse;\n flex-wrap: wrap;\n justify-content: start;\n flex-shrink: 0;\n padding: 7px 12px;\n column-gap: 8px;\n}\n.response-example-selector {\n flex-shrink: 0;\n margin: -4px;\n}\n.response-description {\n font-weight: var(--scalar-semibold);\n font-size: var(--scalar-small);\n color: var(--scalar-color--1);\n\n box-sizing: border-box;\n\n flex-grow: 1;\n}\n.response-description-markdown {\n max-height: 3lh;\n}\n\n.response-description-markdown :deep(*) {\n margin: 0;\n}\n.schema-type {\n font-size: var(--scalar-micro);\n color: var(--scalar-color-2);\n font-weight: var(--scalar-semibold);\n background: var(--scalar-background-3);\n padding: 2px 4px;\n border-radius: 4px;\n margin-right: 4px;\n}\n.schema-example {\n font-size: var(--scalar-micro);\n color: var(--scalar-color-2);\n font-weight: var(--scalar-semibold);\n}\n\n.example-response-tab {\n display: block;\n margin: 6px;\n}\n\n.scalar-card-checkbox {\n display: flex;\n align-items: center;\n justify-content: center;\n position: relative;\n min-height: 17px;\n cursor: pointer;\n user-select: none;\n font-size: var(--scalar-small);\n font-weight: var(--scalar-font-normal);\n color: var(--scalar-color-2);\n width: fit-content;\n white-space: nowrap;\n gap: 6px;\n padding: 7px 6px;\n}\n.scalar-card-checkbox:has(.scalar-card-checkbox-input:focus-visible)\n .scalar-card-checkbox-checkmark {\n outline: 1px solid var(--scalar-color-accent);\n}\n.scalar-card-checkbox:hover {\n color: var(--scalar-color--1);\n}\n.scalar-card-checkbox .scalar-card-checkbox-input {\n position: absolute;\n opacity: 0;\n cursor: pointer;\n height: 0;\n width: 0;\n}\n\n.scalar-card-checkbox-checkmark {\n height: 16px;\n width: 16px;\n border-radius: var(--scalar-radius);\n background-color: transparent;\n background-color: var(--scalar-background-3);\n box-shadow: inset 0 0 0 var(--scalar-border-width) var(--scalar-border-color);\n}\n.scalar-card-checkbox:has(.scalar-card-checkbox-input:checked) {\n color: var(--scalar-color-1);\n font-weight: var(--scalar-semibold);\n}\n\n.scalar-card-checkbox\n .scalar-card-checkbox-input:checked\n ~ .scalar-card-checkbox-checkmark {\n background-color: var(--scalar-button-1);\n box-shadow: none;\n}\n\n.scalar-card-checkbox-checkmark:after {\n content: '';\n position: absolute;\n display: none;\n}\n\n.scalar-card-checkbox\n .scalar-card-checkbox-input:checked\n ~ .scalar-card-checkbox-checkmark:after {\n display: block;\n}\n\n.scalar-card-checkbox .scalar-card-checkbox-checkmark:after {\n right: 11.5px;\n top: 12.5px;\n width: 5px;\n height: 9px;\n border: solid 1px var(--scalar-button-1-color);\n border-width: 0 1.5px 1.5px 0;\n transform: rotate(45deg);\n}\n</style>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;EAsCA,MAAM,KAAK,OAAM;EACjB,MAAM,EAAE,oBAAoB,cAAa;EAGzC,MAAM,qBAAqB,eACzB,OAAO,KAAK,QAAA,aAAa,EAAE,CAAC,CAAC,MAAM,CACrC;EAGA,MAAM,yBAAyB,eAC7B,mBAAmB,MAAM,QAAQ,eAC/B,mBAAmB,eAAe,QAAA,YAAY,YAAY,EAAE,WAAW,CACxE,CACH;EAGA,MAAM,wBAAwB,IAAY,EAAC;;;;;;;;;AAU3C,QAAM,yBAAyB,UAAU;AACvC,OAAI,MAAM,WAAW,GAAG;AACtB,0BAAsB,QAAQ;AAC9B,uBAAmB,QAAQ;cAClB,sBAAsB,SAAS,MAAM,QAAQ;AACtD,0BAAsB,QAAQ,MAAM,SAAS;AAC7C,uBAAmB,QAAQ;;IAE9B;EAGD,MAAM,kBAAkB,eAAe;GACrC,MAAM,oBACJ,QAAQ,uBAAuB,CAAC,QAAQ,sBAAsB,KAAK;AAErE,UAAO,eAAe,QAAA,YAAY,mBAAkB;IACrD;EAED,MAAM,yBAAyB,eAA4C;GACzE,MAAM,oBAAoB,wBACxB,gBAAgB,OAAO,QACzB;;GAG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,GAAA;;6BA1BF,EAAA,UAAA,KAAA,EAD9C,mBAMqB,UAAA,MAAA,WALE,uBAAA,QAAd,eAAU;2BADnB,YAMqB,4BAAA;QAJlB,KAAK;QACL,iBAAe,MAAA,GAAE;;+BACkB,CAApC,YAAoC,sBAAA,MAAA;gCAAf,CAAA,GAAA,OAAA,OAAA,OAAA,KAAA,CAAA,gBAAP,WAAO,GAAA,CAAA,EAAA,CAAA;;4BAAe,MACpC,gBAAG,WAAU,EAAA,EAAA,CAAA,CAAA;;;;;;KA0BjB,YAaoB,MAAA,kBAAA,EAAA,EAbD,OAAM,eAAa,EAAA;6BAKS,CAFrC,uBAAA,OAAwB,UAAU,WAAA,SAAA,WAAA,EAD1C,YAG6C,uBAAA;;OAD1C,IAAI,MAAA,GAAE;OACN,QAAQ,uBAAA,OAAwB;qDAGnC,YAIuC,yBAAA;;OAFpC,IAAI,MAAA,GAAE;OACN,SAAS,eAAA;OACT,UAAU,uBAAA;;;;;;;;KAGP,gBAAA,OAAiB,eAAe,oBAAA,SAAA,WAAA,EADxC,YAcmB,MAAA,iBAAA,EAAA;;MAZjB,OAAM;;6BAK2C,CAHzC,oBAAA,SAAA,WAAA,EADR,YAIiD,MAAA,cAAA,EAAA;;mBAFtC,mBAAA;uFAAkB,QAAA;OAC3B,OAAM;OACL,UAAU,uBAAA,OAAwB;+EACrC,mBAKM,OALN,YAKM,CAHI,gBAAA,OAAiB,eAAA,WAAA,EADzB,YAGyC,MAAA,eAAA,EAAA;;OADvC,OAAM;OACL,OAAO,gBAAA,MAAgB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ClientPlugin } from '@scalar/oas-utils/helpers';
|
|
2
|
-
import type {
|
|
2
|
+
import type { ApiReferenceConfiguration } from '@scalar/types/api-reference';
|
|
3
|
+
import type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments';
|
|
3
4
|
import { type ComputedRef } from 'vue';
|
|
4
5
|
/**
|
|
5
6
|
* Maps API reference configuration callbacks to client plugins.
|
|
@@ -16,5 +17,5 @@ import { type ComputedRef } from 'vue';
|
|
|
16
17
|
* @param config - Reactive configuration object containing optional hook callbacks
|
|
17
18
|
* @returns Array containing a single plugin with the mapped hooks
|
|
18
19
|
*/
|
|
19
|
-
export declare const mapConfigPlugins: (config: ComputedRef<
|
|
20
|
+
export declare const mapConfigPlugins: (config: ComputedRef<ApiReferenceConfiguration>, environment: ComputedRef<XScalarEnvironment>) => ClientPlugin[];
|
|
20
21
|
//# sourceMappingURL=map-config-plugins.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"map-config-plugins.d.ts","sourceRoot":"","sources":["../../src/helpers/map-config-plugins.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAA;AAC7D,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"map-config-plugins.d.ts","sourceRoot":"","sources":["../../src/helpers/map-config-plugins.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAA;AAC7D,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAA;AAE5E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2EAA2E,CAAA;AACnH,OAAO,EAAE,KAAK,WAAW,EAAS,MAAM,KAAK,CAAA;AAE7C;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,gBAAgB,GAC3B,QAAQ,WAAW,CAAC,yBAAyB,CAAC,EAC9C,aAAa,WAAW,CAAC,kBAAkB,CAAC,KAC3C,YAAY,EAwCd,CAAA"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { watch } from "vue";
|
|
2
|
+
import { buildRequest, getEnvironmentVariables } from "@scalar/workspace-store/request-example";
|
|
2
3
|
//#region src/helpers/map-config-plugins.ts
|
|
3
4
|
/**
|
|
4
5
|
* Maps API reference configuration callbacks to client plugins.
|
|
@@ -15,18 +16,21 @@ import { watch } from "vue";
|
|
|
15
16
|
* @param config - Reactive configuration object containing optional hook callbacks
|
|
16
17
|
* @returns Array containing a single plugin with the mapped hooks
|
|
17
18
|
*/
|
|
18
|
-
var mapConfigPlugins = (config) => {
|
|
19
|
+
var mapConfigPlugins = (config, environment) => {
|
|
19
20
|
const plugin = { hooks: {} };
|
|
20
|
-
watch([
|
|
21
|
+
watch([
|
|
22
|
+
() => config.value.onBeforeRequest,
|
|
23
|
+
() => config.value.onRequestSent,
|
|
24
|
+
() => environment.value
|
|
25
|
+
], ([onBeforeRequest, onRequestSent, environment]) => {
|
|
26
|
+
const envVariables = getEnvironmentVariables(environment);
|
|
21
27
|
if (!plugin.hooks) plugin.hooks = {};
|
|
22
28
|
plugin.hooks.beforeRequest = onBeforeRequest ? async (payload) => {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
if (result === void 0) return payload;
|
|
29
|
-
return result;
|
|
29
|
+
await onBeforeRequest({
|
|
30
|
+
request: buildRequest(payload.requestBuilder, { envVariables }).request,
|
|
31
|
+
requestBuilder: payload.requestBuilder,
|
|
32
|
+
envVariables
|
|
33
|
+
});
|
|
30
34
|
} : void 0;
|
|
31
35
|
/**
|
|
32
36
|
* Maps onRequestSent to responseReceived hook.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"map-config-plugins.js","names":[],"sources":["../../src/helpers/map-config-plugins.ts"],"sourcesContent":["import type { ClientPlugin } from '@scalar/oas-utils/helpers'\nimport type {
|
|
1
|
+
{"version":3,"file":"map-config-plugins.js","names":[],"sources":["../../src/helpers/map-config-plugins.ts"],"sourcesContent":["import type { ClientPlugin } from '@scalar/oas-utils/helpers'\nimport type { ApiReferenceConfiguration } from '@scalar/types/api-reference'\nimport { buildRequest, getEnvironmentVariables } from '@scalar/workspace-store/request-example'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport { type ComputedRef, watch } from 'vue'\n\n/**\n * Maps API reference configuration callbacks to client plugins.\n *\n * This function transforms the legacy onBeforeRequest and onRequestSent callbacks\n * into the new plugin hook system. The mapping is reactive, so changes to the\n * configuration will automatically update the plugin hooks.\n *\n * Note: onRequestSent is mapped to responseReceived hook. This is not a perfect\n * one-to-one mapping, but it maintains backward compatibility with the old API.\n * The old callback receives only the URL string, while the new hook receives\n * the full response object.\n *\n * @param config - Reactive configuration object containing optional hook callbacks\n * @returns Array containing a single plugin with the mapped hooks\n */\nexport const mapConfigPlugins = (\n config: ComputedRef<ApiReferenceConfiguration>,\n environment: ComputedRef<XScalarEnvironment>,\n): ClientPlugin[] => {\n // Create a new plugin with the hooks which is going to be updated by the watcher when config changes\n const plugin: ClientPlugin = { hooks: {} }\n\n watch(\n [() => config.value.onBeforeRequest, () => config.value.onRequestSent, () => environment.value],\n ([onBeforeRequest, onRequestSent, environment]) => {\n // Get the environment variables for the current environment\n const envVariables = getEnvironmentVariables(environment)\n\n // Initialize the hooks object if it doesn't exist\n if (!plugin.hooks) {\n plugin.hooks = {}\n }\n\n plugin.hooks.beforeRequest = onBeforeRequest\n ? async (payload) => {\n await onBeforeRequest({\n // We need to build the request to get the fetch `Request`\n request: buildRequest(payload.requestBuilder, { envVariables }).request,\n requestBuilder: payload.requestBuilder,\n envVariables,\n })\n }\n : undefined\n\n /**\n * Maps onRequestSent to responseReceived hook.\n * The old API only passed the URL string, so we extract it from the request.\n */\n plugin.hooks.responseReceived = onRequestSent\n ? (payload) => {\n onRequestSent(payload.request.url)\n }\n : undefined\n },\n { immediate: true },\n )\n\n return [plugin]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqBA,IAAa,oBACX,QACA,gBACmB;CAEnB,MAAM,SAAuB,EAAE,OAAO,EAAE,EAAE;AAE1C,OACE;QAAO,OAAO,MAAM;QAAuB,OAAO,MAAM;QAAqB,YAAY;EAAM,GAC9F,CAAC,iBAAiB,eAAe,iBAAiB;EAEjD,MAAM,eAAe,wBAAwB,YAAY;AAGzD,MAAI,CAAC,OAAO,MACV,QAAO,QAAQ,EAAE;AAGnB,SAAO,MAAM,gBAAgB,kBACzB,OAAO,YAAY;AACjB,SAAM,gBAAgB;IAEpB,SAAS,aAAa,QAAQ,gBAAgB,EAAE,cAAc,CAAC,CAAC;IAChE,gBAAgB,QAAQ;IACxB;IACD,CAAC;MAEJ,KAAA;;;;;AAMJ,SAAO,MAAM,mBAAmB,iBAC3B,YAAY;AACX,iBAAc,QAAQ,QAAQ,IAAI;MAEpC,KAAA;IAEN,EAAE,WAAW,MAAM,CACpB;AAED,QAAO,CAAC,OAAO"}
|
|
@@ -1,8 +1,12 @@
|
|
|
1
|
-
import type { OpenApiDocument, OperationObject, ParameterObject } from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document';
|
|
1
|
+
import type { OpenApiDocument, OperationObject, ParameterObject, ReferenceType } from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document';
|
|
2
2
|
/**
|
|
3
3
|
* Extracts the request body from an operation.
|
|
4
4
|
*/
|
|
5
|
-
export declare function extractRequestBody(operation: OperationObject): string[] |
|
|
5
|
+
export declare function extractRequestBody(operation: OperationObject): string[] | null;
|
|
6
|
+
/**
|
|
7
|
+
* Extracts parameters from an operation into searchable strings.
|
|
8
|
+
*/
|
|
9
|
+
export declare function extractParameters(parameters: ReferenceType<ParameterObject>[]): string[] | null;
|
|
6
10
|
/**
|
|
7
11
|
* Deep merge for objects
|
|
8
12
|
*/
|
|
@@ -12,16 +16,4 @@ export declare function deepMerge(source: Record<any, any>, target: Record<any,
|
|
|
12
16
|
* The returning object has the same structure as a valid OpenAPI specification, but everything is empty.
|
|
13
17
|
*/
|
|
14
18
|
export declare function createEmptySpecification(partialSpecification?: Partial<OpenApiDocument>): OpenApiDocument;
|
|
15
|
-
export type ParameterMap = {
|
|
16
|
-
path: ParameterObject[];
|
|
17
|
-
query: ParameterObject[];
|
|
18
|
-
header: ParameterObject[];
|
|
19
|
-
cookie: ParameterObject[];
|
|
20
|
-
};
|
|
21
|
-
/**
|
|
22
|
-
* This function creates a parameter map from an Operation Object, that's easier to consume.
|
|
23
|
-
*
|
|
24
|
-
* TODO: Isn't it easier to just stick to the OpenAPI structure, without transforming it?
|
|
25
|
-
*/
|
|
26
|
-
export declare function createParameterMap(operation: OperationObject): ParameterMap;
|
|
27
19
|
//# sourceMappingURL=openapi.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openapi.d.ts","sourceRoot":"","sources":["../../src/helpers/openapi.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,eAAe,
|
|
1
|
+
{"version":3,"file":"openapi.d.ts","sourceRoot":"","sources":["../../src/helpers/openapi.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,eAAe,EACf,aAAa,EAGd,MAAM,8DAA8D,CAAA;AAwGrE;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,eAAe,GAAG,MAAM,EAAE,GAAG,IAAI,CAS9E;AAwBD;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,aAAa,CAAC,eAAe,CAAC,EAAE,GAAG,MAAM,EAAE,GAAG,IAAI,CAE/F;AAED;;GAEG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,oBAW3E;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,oBAAoB,CAAC,EAAE,OAAO,CAAC,eAAe,CAAC,mBA4BvF"}
|
package/dist/helpers/openapi.js
CHANGED
|
@@ -66,13 +66,30 @@ function recursiveLogger(obj) {
|
|
|
66
66
|
* Extracts the request body from an operation.
|
|
67
67
|
*/
|
|
68
68
|
function extractRequestBody(operation) {
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
69
|
+
const content = getResolvedRef(operation?.requestBody)?.content;
|
|
70
|
+
const contentValue = Object.values(content ?? {});
|
|
71
|
+
if (contentValue.length === 0) return null;
|
|
72
|
+
return contentValue.flatMap((media) => recursiveLogger(media));
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Formats a parameter into a searchable string.
|
|
76
|
+
*/
|
|
77
|
+
function formatParameter(param) {
|
|
78
|
+
const output = [param.name];
|
|
79
|
+
output.push(param.required ? "REQUIRED" : "optional");
|
|
80
|
+
output.push(param.in);
|
|
81
|
+
if ("schema" in param && param.schema) {
|
|
82
|
+
const schema = getResolvedRef(param.schema);
|
|
83
|
+
if (schema) output.push(schemaTypeToString(schema));
|
|
75
84
|
}
|
|
85
|
+
if (param.description) output.push(param.description);
|
|
86
|
+
return output.join(" ");
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Extracts parameters from an operation into searchable strings.
|
|
90
|
+
*/
|
|
91
|
+
function extractParameters(parameters) {
|
|
92
|
+
return parameters.map((parameter) => formatParameter(getResolvedRef(parameter)));
|
|
76
93
|
}
|
|
77
94
|
/**
|
|
78
95
|
* Deep merge for objects
|
|
@@ -110,29 +127,7 @@ function createEmptySpecification(partialSpecification) {
|
|
|
110
127
|
deepMerge(partialSpecification, emptySpecification);
|
|
111
128
|
return emptySpecification;
|
|
112
129
|
}
|
|
113
|
-
/**
|
|
114
|
-
* This function creates a parameter map from an Operation Object, that's easier to consume.
|
|
115
|
-
*
|
|
116
|
-
* TODO: Isn't it easier to just stick to the OpenAPI structure, without transforming it?
|
|
117
|
-
*/
|
|
118
|
-
function createParameterMap(operation) {
|
|
119
|
-
const map = {
|
|
120
|
-
path: [],
|
|
121
|
-
query: [],
|
|
122
|
-
header: [],
|
|
123
|
-
cookie: []
|
|
124
|
-
};
|
|
125
|
-
(operation.parameters ?? []).forEach((parameterRef) => {
|
|
126
|
-
const parameter = getResolvedRef(parameterRef);
|
|
127
|
-
if (!parameter) return;
|
|
128
|
-
if (parameter.in === "path") map.path.push(parameter);
|
|
129
|
-
else if (parameter.in === "query") map.query.push(parameter);
|
|
130
|
-
else if (parameter.in === "header") map.header.push(parameter);
|
|
131
|
-
else if (parameter.in === "cookie") map.cookie.push(parameter);
|
|
132
|
-
});
|
|
133
|
-
return map;
|
|
134
|
-
}
|
|
135
130
|
//#endregion
|
|
136
|
-
export { createEmptySpecification,
|
|
131
|
+
export { createEmptySpecification, extractParameters, extractRequestBody };
|
|
137
132
|
|
|
138
133
|
//# sourceMappingURL=openapi.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openapi.js","names":[],"sources":["../../src/helpers/openapi.ts"],"sourcesContent":["import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport type { MediaTypeObject } from '@scalar/workspace-store/schemas/v3.1/strict/media-type'\nimport type {\n OpenApiDocument,\n OperationObject,\n ParameterObject,\n SchemaObject,\n SchemaReferenceType,\n} from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport { isObjectSchema } from '@scalar/workspace-store/schemas/v3.1/strict/type-guards'\n\n/** Object schema shape with properties, used when logging request body. */\ntype ObjectSchemaWithProperties = {\n properties: Record<string, SchemaReferenceType<SchemaObject>>\n required?: string[]\n}\n\nconst isSchemaObject = (value: unknown): value is SchemaObject => typeof value === 'object' && value !== null\n\nconst schemaTypeToString = (schema: SchemaObject): string => {\n if (!('type' in schema)) {\n return ''\n }\n\n if (typeof schema.type === 'string') {\n return schema.type\n }\n\n return Array.isArray(schema.type) ? schema.type.join('|') : ''\n}\n\n/**\n * Resolves a schema reference from workspace-store to a SchemaObject.\n * Returns undefined when a reference exists but has not been resolved yet.\n */\nfunction resolveSchemaRef(ref: SchemaReferenceType<SchemaObject>): SchemaObject | undefined {\n if (typeof ref === 'object' && ref !== null && '$ref' in ref) {\n return isSchemaObject(ref['$ref-value']) ? ref['$ref-value'] : undefined\n }\n\n return ref\n}\n\n/**\n * Formats a property object into a string.\n */\nfunction formatProperty(key: string, obj: ObjectSchemaWithProperties): string {\n let output = key\n const isRequired = obj.required?.includes(key)\n output += isRequired ? ' REQUIRED ' : ' optional '\n const propRef = obj.properties[key]\n if (!propRef) return output\n const property = resolveSchemaRef(propRef)\n\n if (property) {\n output += schemaTypeToString(property)\n\n if ('description' in property && typeof property.description === 'string') {\n output += ` ${property.description}`\n }\n }\n\n return output\n}\n\n/**\n * Recursively logs the properties of an object.\n */\nfunction recursiveLogger(obj: MediaTypeObject): string[] {\n const results: string[] = ['Body']\n const schema = getResolvedRef(obj?.schema)\n\n if (!schema || !isObjectSchema(schema) || !schema.properties) {\n return results\n }\n\n const properties = schema.properties\n const schemaWithProps: ObjectSchemaWithProperties = {\n properties,\n required: schema.required,\n }\n Object.keys(properties).forEach((key) => {\n if (!obj.schema) {\n return\n }\n\n results.push(formatProperty(key, schemaWithProps))\n\n const propRef = properties[key]\n if (!propRef) return\n const property = resolveSchemaRef(propRef)\n if (property && isObjectSchema(property) && property.properties) {\n const nestedProperties = property.properties\n Object.keys(nestedProperties).forEach((subKey) => {\n const ref = nestedProperties[subKey]\n if (!ref) return\n const nested = resolveSchemaRef(ref)\n const typeStr = nested ? schemaTypeToString(nested) : ''\n results.push(`${subKey} ${typeStr}`)\n })\n }\n })\n\n return results\n}\n\n/**\n * Extracts the request body from an operation.\n */\nexport function extractRequestBody(operation: OperationObject): string[] |
|
|
1
|
+
{"version":3,"file":"openapi.js","names":[],"sources":["../../src/helpers/openapi.ts"],"sourcesContent":["import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport type { MediaTypeObject } from '@scalar/workspace-store/schemas/v3.1/strict/media-type'\nimport type {\n OpenApiDocument,\n OperationObject,\n ParameterObject,\n ReferenceType,\n SchemaObject,\n SchemaReferenceType,\n} from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport { isObjectSchema } from '@scalar/workspace-store/schemas/v3.1/strict/type-guards'\n\n/** Object schema shape with properties, used when logging request body. */\ntype ObjectSchemaWithProperties = {\n properties: Record<string, SchemaReferenceType<SchemaObject>>\n required?: string[]\n}\n\nconst isSchemaObject = (value: unknown): value is SchemaObject => typeof value === 'object' && value !== null\n\nconst schemaTypeToString = (schema: SchemaObject): string => {\n if (!('type' in schema)) {\n return ''\n }\n\n if (typeof schema.type === 'string') {\n return schema.type\n }\n\n return Array.isArray(schema.type) ? schema.type.join('|') : ''\n}\n\n/**\n * Resolves a schema reference from workspace-store to a SchemaObject.\n * Returns undefined when a reference exists but has not been resolved yet.\n */\nfunction resolveSchemaRef(ref: SchemaReferenceType<SchemaObject>): SchemaObject | undefined {\n if (typeof ref === 'object' && ref !== null && '$ref' in ref) {\n return isSchemaObject(ref['$ref-value']) ? ref['$ref-value'] : undefined\n }\n\n return ref\n}\n\n/**\n * Formats a property object into a string.\n */\nfunction formatProperty(key: string, obj: ObjectSchemaWithProperties): string {\n let output = key\n const isRequired = obj.required?.includes(key)\n output += isRequired ? ' REQUIRED ' : ' optional '\n const propRef = obj.properties[key]\n if (!propRef) {\n return output\n }\n const property = resolveSchemaRef(propRef)\n\n if (property) {\n output += schemaTypeToString(property)\n\n if ('description' in property && typeof property.description === 'string') {\n output += ` ${property.description}`\n }\n }\n\n return output\n}\n\n/**\n * Recursively logs the properties of an object.\n */\nfunction recursiveLogger(obj: MediaTypeObject): string[] {\n const results: string[] = ['Body']\n const schema = getResolvedRef(obj?.schema)\n\n if (!schema || !isObjectSchema(schema) || !schema.properties) {\n return results\n }\n\n const properties = schema.properties\n const schemaWithProps: ObjectSchemaWithProperties = {\n properties,\n required: schema.required,\n }\n Object.keys(properties).forEach((key) => {\n if (!obj.schema) {\n return\n }\n\n results.push(formatProperty(key, schemaWithProps))\n\n const propRef = properties[key]\n if (!propRef) {\n return\n }\n const property = resolveSchemaRef(propRef)\n if (property && isObjectSchema(property) && property.properties) {\n const nestedProperties = property.properties\n Object.keys(nestedProperties).forEach((subKey) => {\n const ref = nestedProperties[subKey]\n if (!ref) {\n return\n }\n const nested = resolveSchemaRef(ref)\n const typeStr = nested ? schemaTypeToString(nested) : ''\n results.push(`${subKey} ${typeStr}`)\n })\n }\n })\n\n return results\n}\n\n/**\n * Extracts the request body from an operation.\n */\nexport function extractRequestBody(operation: OperationObject): string[] | null {\n const content = getResolvedRef(operation?.requestBody)?.content\n const contentValue = Object.values(content ?? {})\n if (contentValue.length === 0) {\n // No content found\n return null\n }\n\n return contentValue.flatMap((media) => recursiveLogger(media))\n}\n\n/**\n * Formats a parameter into a searchable string.\n */\nfunction formatParameter(param: ParameterObject): string {\n const output = [param.name]\n output.push(param.required ? 'REQUIRED' : 'optional')\n output.push(param.in)\n\n if ('schema' in param && param.schema) {\n const schema = getResolvedRef(param.schema)\n if (schema) {\n output.push(schemaTypeToString(schema))\n }\n }\n\n if (param.description) {\n output.push(param.description)\n }\n\n return output.join(' ')\n}\n\n/**\n * Extracts parameters from an operation into searchable strings.\n */\nexport function extractParameters(parameters: ReferenceType<ParameterObject>[]): string[] | null {\n return parameters.map((parameter) => formatParameter(getResolvedRef(parameter)))\n}\n\n/**\n * Deep merge for objects\n */\nexport function deepMerge(source: Record<any, any>, target: Record<any, any>) {\n for (const [key, val] of Object.entries(source)) {\n if (val !== null && typeof val === 'object') {\n target[key] ??= new val.__proto__.constructor()\n deepMerge(val, target[key])\n } else if (typeof val !== 'undefined') {\n target[key] = val\n }\n }\n\n return target\n}\n\n/**\n * Creates an empty specification object.\n * The returning object has the same structure as a valid OpenAPI specification, but everything is empty.\n */\nexport function createEmptySpecification(partialSpecification?: Partial<OpenApiDocument>) {\n const emptySpecification = {\n openapi: '3.1.0',\n info: {\n title: '',\n description: '',\n termsOfService: '',\n version: '',\n license: {\n name: '',\n url: '',\n },\n contact: {\n email: '',\n },\n },\n servers: [],\n tags: [],\n 'x-scalar-original-document-hash': '',\n }\n\n if (!partialSpecification) {\n return emptySpecification as OpenApiDocument\n }\n\n deepMerge(partialSpecification, emptySpecification)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AAO;AAIlB,QAAO;;;;;;AAOT,SAAgB,yBAAyB,sBAAiD;CACxF,MAAM,qBAAqB;EACzB,SAAS;EACT,MAAM;GACJ,OAAO;GACP,aAAa;GACb,gBAAgB;GAChB,SAAS;GACT,SAAS;IACP,MAAM;IACN,KAAK;IACN;GACD,SAAS,EACP,OAAO,IACR;GACF;EACD,SAAS,EAAE;EACX,MAAM,EAAE;EACR,mCAAmC;EACpC;AAED,KAAI,CAAC,qBACH,QAAO;AAGT,WAAU,sBAAsB,mBAAmB;AAEnD,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"html-api.d.ts","sourceRoot":"","sources":["../../../src/standalone/lib/html-api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,mCAAmC,EACnC,kBAAkB,EACnB,MAAM,6BAA6B,CAAA;AASpC;;GAEG;AACH,wBAAgB,kCAAkC,CAAC,GAAG,EAAE,QAAQ,GAAG,mCAAmC,CA+GrG;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,QAAQ,EAAE,aAAa,EAAE,mCAAmC,QAiBnG;AAID,eAAO,MAAM,eAAe,GAAI,KAAK,QAAQ,EAAE,UAAU,OAAO,GAAG,IAAI,mBAatE,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,EAAE,
|
|
1
|
+
{"version":3,"file":"html-api.d.ts","sourceRoot":"","sources":["../../../src/standalone/lib/html-api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,mCAAmC,EACnC,kBAAkB,EACnB,MAAM,6BAA6B,CAAA;AASpC;;GAEG;AACH,wBAAgB,kCAAkC,CAAC,GAAG,EAAE,QAAQ,GAAG,mCAAmC,CA+GrG;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,QAAQ,EAAE,aAAa,EAAE,mCAAmC,QAiBnG;AAID,eAAO,MAAM,eAAe,GAAI,KAAK,QAAQ,EAAE,UAAU,OAAO,GAAG,IAAI,mBAatE,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,EAAE,kBA4HhC,CAAA"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import ApiReference_default from "../../components/ApiReference.vue.js";
|
|
2
|
-
import { createApp, h, reactive } from "vue";
|
|
2
|
+
import { createApp, createSSRApp, h, reactive } from "vue";
|
|
3
3
|
import "@scalar/types/api-reference";
|
|
4
4
|
import { createHead } from "@unhead/vue/client";
|
|
5
5
|
//#region src/standalone/lib/html-api.ts
|
|
@@ -13,14 +13,16 @@ import { createHead } from "@unhead/vue/client";
|
|
|
13
13
|
var createApiReference = (elementOrSelectorOrConfig, optionalConfiguration) => {
|
|
14
14
|
const idPrefix = "scalar-refs";
|
|
15
15
|
const props = reactive({ configuration: optionalConfiguration ?? elementOrSelectorOrConfig ?? {} });
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
16
|
+
const createReferenceApp = (isSsr = false) => {
|
|
17
|
+
const referenceApp = isSsr ? createSSRApp(() => h(ApiReference_default, props)) : createApp(() => h(ApiReference_default, props));
|
|
18
|
+
referenceApp.use(createHead());
|
|
19
|
+
referenceApp.config.idPrefix = idPrefix;
|
|
20
|
+
return referenceApp;
|
|
21
|
+
};
|
|
22
|
+
const mountElement = optionalConfiguration ? typeof elementOrSelectorOrConfig === "string" ? document.querySelector(elementOrSelectorOrConfig) : elementOrSelectorOrConfig : null;
|
|
23
|
+
let app = createReferenceApp(!!optionalConfiguration && !!mountElement && mountElement.children.length > 0);
|
|
24
|
+
if (optionalConfiguration) if (mountElement) app.mount(mountElement);
|
|
25
|
+
else console.error("Could not find a mount point for API References:", elementOrSelectorOrConfig);
|
|
24
26
|
/**
|
|
25
27
|
* Reload the API Reference
|
|
26
28
|
* @deprecated
|
|
@@ -32,9 +34,7 @@ var createApiReference = (elementOrSelectorOrConfig, optionalConfiguration) => {
|
|
|
32
34
|
if (!currentElement) return;
|
|
33
35
|
if (currentElement && !document.body.contains(currentElement)) document.body.appendChild(currentElement);
|
|
34
36
|
app.unmount();
|
|
35
|
-
app =
|
|
36
|
-
app.use(createHead());
|
|
37
|
-
app.config.idPrefix = idPrefix;
|
|
37
|
+
app = createReferenceApp();
|
|
38
38
|
app.mount(currentElement);
|
|
39
39
|
}, false);
|
|
40
40
|
/** Destroy the current API Reference instance */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"html-api.js","names":[],"sources":["../../../src/standalone/lib/html-api.ts"],"sourcesContent":["import type {\n AnyApiReferenceConfiguration,\n ApiReferenceConfigurationWithSource,\n CreateApiReference,\n} from '@scalar/types/api-reference'\nimport { apiReferenceConfigurationWithSourceSchema } from '@scalar/types/api-reference'\nimport { createHead } from '@unhead/vue/client'\nimport { createApp, h, reactive } from 'vue'\n\nimport { default as ApiReference } from '@/components/ApiReference.vue'\n\nconst getSpecScriptTag = (doc: Document) => doc.getElementById('api-reference')\n\n/**\n * Reading the configuration from the data-attributes.\n */\nexport function getConfigurationFromDataAttributes(doc: Document): ApiReferenceConfigurationWithSource {\n const specElement = doc.querySelector('[data-spec]')\n const specUrlElement = doc.querySelector('[data-spec-url]')\n const configurationScriptElement = doc.querySelector('#api-reference[data-configuration]')\n\n const getConfiguration = () => {\n // <script data-configuration=\"{ … }\" />\n if (configurationScriptElement) {\n const configurationFromElement = configurationScriptElement.getAttribute('data-configuration')\n\n if (configurationFromElement) {\n return {\n _integration: 'html',\n ...JSON.parse(configurationFromElement.split('"').join('\"')),\n }\n }\n }\n\n return apiReferenceConfigurationWithSourceSchema.parse({ _integration: 'html' })\n }\n\n const getUrl = () => {\n // Let's first check if the user passed a spec URL in the configuration.\n if (getConfiguration().url) {\n return getConfiguration().url\n }\n\n if (getConfiguration().spec?.url) {\n return getConfiguration().spec?.url\n }\n\n // <script id=\"api-reference\" data-url=\"/scalar.json\" />\n const specScriptTag = getSpecScriptTag(doc)\n if (specScriptTag) {\n const urlFromScriptTag = specScriptTag.getAttribute('data-url')?.trim()\n\n if (urlFromScriptTag) {\n return urlFromScriptTag\n }\n }\n\n // <div data-spec-url=\"/scalar.json\" />\n if (specUrlElement) {\n console.warn(\n '[@scalar/api-reference] The [data-spec-url] HTML API is deprecated. Use the new <script id=\"api-reference\" data-url=\"/scalar.json\" /> API instead.',\n )\n const urlFromSpecUrlElement = specUrlElement.getAttribute('data-spec-url')\n\n if (urlFromSpecUrlElement) {\n return urlFromSpecUrlElement\n }\n }\n\n return undefined\n }\n\n const getContent = (): string | undefined => {\n // <script id=\"api-reference\" type=\"application/json\">{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"Example\"},\"paths\":{}}</script>\n const specScriptTag = getSpecScriptTag(doc)\n if (specScriptTag) {\n const specFromScriptTag = specScriptTag.innerHTML?.trim()\n\n if (specFromScriptTag) {\n return specFromScriptTag\n }\n }\n\n // <div data-spec='{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"Example\"},\"paths\":{}}' />\n if (specElement) {\n console.warn(\n '[@scalar/api-reference] The [data-spec] HTML API is deprecated. Use the new <script id=\"api-reference\" type=\"application/json\">{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"Example\"},\"paths\":{}}</script> API instead.',\n )\n const specFromSpecElement = specElement.getAttribute('data-spec')?.trim()\n\n if (specFromSpecElement) {\n return specFromSpecElement\n }\n }\n\n return undefined\n }\n\n const getProxyUrl = () => {\n // <script id=\"api-reference\" data-proxy-url=\"https://proxy.scalar.com\">…</script>\n const specScriptTag = getSpecScriptTag(doc)\n if (specScriptTag) {\n const proxyUrl = specScriptTag.getAttribute('data-proxy-url')\n\n if (proxyUrl) {\n return proxyUrl.trim()\n }\n }\n\n return undefined\n }\n\n // Ensure Reference Props are reactive\n if (!specUrlElement && !specElement && !getSpecScriptTag(doc)) {\n // Stay quiet.\n } else {\n const urlOrContent = getContent() ? { content: getContent() } : { url: getUrl() }\n\n return apiReferenceConfigurationWithSourceSchema.parse({\n _integration: 'html',\n proxyUrl: getProxyUrl(),\n ...getConfiguration(),\n ...urlOrContent,\n })\n }\n\n return apiReferenceConfigurationWithSourceSchema.parse({ _integration: 'html' })\n}\n\n/**\n * Mount the Scalar API Reference on a given document.\n * Read the HTML data-attributes for configuration.\n */\nexport function findDataAttributes(doc: Document, configuration: ApiReferenceConfigurationWithSource) {\n /** @deprecated Use the new <script id=\"api-reference\" data-url=\"/scalar.json\" /> API instead. */\n const specElement = doc.querySelector('[data-spec]')\n /** @deprecated Use the new <script id=\"api-reference\" data-url=\"/scalar.json\" /> API instead. */\n const specUrlElement = doc.querySelector('[data-spec-url]')\n\n if (configuration?.darkMode) {\n doc.body?.classList.add('dark-mode')\n } else {\n doc.body?.classList.add('light-mode')\n }\n\n const container = createContainer(doc, specElement || specUrlElement)\n\n if (container) {\n createApiReference(container, configuration)\n }\n}\n\n// If it's a script tag, we can't mount the Vue.js app inside that tag.\n// We need to add a new container element before the script tag.\nexport const createContainer = (doc: Document, element?: Element | null) => {\n let _container: Element | null = null\n\n const specScriptTag = getSpecScriptTag(doc)\n\n if (specScriptTag) {\n _container = doc.createElement('div')\n specScriptTag?.parentNode?.insertBefore(_container, specScriptTag)\n } else if (element) {\n _container = element\n }\n\n return _container\n}\n\n/**\n * Create (and mount) a new Scalar API Reference\n *\n * @example createApiReference({ url: '/scalar.json' }).mount('#app')\n * @example createApiReference('#app', { url: '/scalar.json' })\n * @example createApiReference(document.getElementById('app'), { url: '/scalar.json' })\n */\nexport const createApiReference: CreateApiReference = (\n elementOrSelectorOrConfig,\n optionalConfiguration?: AnyApiReferenceConfiguration,\n) => {\n // Create an id prefix for useId so we don't have collisions with other Vue apps\n const idPrefix = 'scalar-refs'\n\n const props = reactive<{ configuration: AnyApiReferenceConfiguration }>({\n // Either the configuration will be the second argument or it MUST be the first (configuration only)\n configuration: optionalConfiguration ?? (elementOrSelectorOrConfig as AnyApiReferenceConfiguration) ?? {},\n })\n\n // Create a new Vue app instance\n let app = createApp(() => h(ApiReference, props))\n\n // Meta tags, etc.\n app.use(createHead())\n\n app.config.idPrefix = idPrefix\n\n // If we have an optional config, then we must mount the element immediately (not sure why type is not narrowing)\n if (optionalConfiguration) {\n // If the element is a string, we need to find the actual DOM element\n const element =\n typeof elementOrSelectorOrConfig === 'string'\n ? document.querySelector(elementOrSelectorOrConfig)\n : (elementOrSelectorOrConfig as Element)\n\n if (element) {\n app.mount(element)\n } else {\n console.error('Could not find a mount point for API References:', elementOrSelectorOrConfig)\n }\n }\n\n /**\n * Reload the API Reference\n * @deprecated\n */\n document.addEventListener(\n 'scalar:reload-references',\n () => {\n console.warn(\n 'scalar:reload-references event has been deprecated, please use the scalarInstance.app.mount method instead.',\n )\n if (!props.configuration) {\n return\n }\n\n // Snag the current element\n const currentElement =\n typeof elementOrSelectorOrConfig === 'string'\n ? document.querySelector(elementOrSelectorOrConfig)\n : (elementOrSelectorOrConfig as Element)\n\n if (!currentElement) {\n return\n }\n\n // Ensure we re-attach the element if it was unmounted\n if (currentElement && !document.body.contains(currentElement)) {\n document.body.appendChild(currentElement)\n }\n\n // Create a new Vue app instance\n app.unmount()\n app = createApp(() => h(ApiReference, props))\n app.use(createHead())\n app.config.idPrefix = idPrefix\n app.mount(currentElement)\n },\n false,\n )\n\n /** Destroy the current API Reference instance */\n const destroy = () => {\n props.configuration = {}\n app.unmount()\n }\n\n /**\n * Allow user to destroy the API Reference\n * @deprecated\n */\n document.addEventListener(\n 'scalar:destroy-references',\n () => {\n console.warn('scalar:destroy-references event has been deprecated, please use scalarInstance.destroy instead.')\n destroy()\n },\n false,\n )\n\n /**\n * Allow user to update configuration\n * @deprecated\n */\n document.addEventListener(\n 'scalar:update-references-config',\n (ev) => {\n console.warn(\n 'scalar:update-references-config event has been deprecated, please use scalarInstance.updateConfiguration instead.',\n )\n if ('detail' in ev) {\n Object.assign(props, ev.detail)\n }\n },\n false,\n )\n\n const instance = {\n app,\n getConfiguration: () => props.configuration ?? {},\n updateConfiguration: (newConfig: AnyApiReferenceConfiguration) => {\n props.configuration = newConfig\n },\n destroy,\n }\n\n return instance\n}\n"],"mappings":";;;;;;;;;;;;AAgLA,IAAa,sBACX,2BACA,0BACG;CAEH,MAAM,WAAW;CAEjB,MAAM,QAAQ,SAA0D,EAEtE,eAAe,yBAA0B,6BAA8D,EAAE,EAC1G,CAAC;CAGF,IAAI,MAAM,gBAAgB,EAAE,sBAAc,MAAM,CAAC;AAGjD,KAAI,IAAI,YAAY,CAAC;AAErB,KAAI,OAAO,WAAW;AAGtB,KAAI,uBAAuB;EAEzB,MAAM,UACJ,OAAO,8BAA8B,WACjC,SAAS,cAAc,0BAA0B,GAChD;AAEP,MAAI,QACF,KAAI,MAAM,QAAQ;MAElB,SAAQ,MAAM,oDAAoD,0BAA0B;;;;;;AAQhG,UAAS,iBACP,kCACM;AACJ,UAAQ,KACN,8GACD;AACD,MAAI,CAAC,MAAM,cACT;EAIF,MAAM,iBACJ,OAAO,8BAA8B,WACjC,SAAS,cAAc,0BAA0B,GAChD;AAEP,MAAI,CAAC,eACH;AAIF,MAAI,kBAAkB,CAAC,SAAS,KAAK,SAAS,eAAe,CAC3D,UAAS,KAAK,YAAY,eAAe;AAI3C,MAAI,SAAS;AACb,QAAM,gBAAgB,EAAE,sBAAc,MAAM,CAAC;AAC7C,MAAI,IAAI,YAAY,CAAC;AACrB,MAAI,OAAO,WAAW;AACtB,MAAI,MAAM,eAAe;IAE3B,MACD;;CAGD,MAAM,gBAAgB;AACpB,QAAM,gBAAgB,EAAE;AACxB,MAAI,SAAS;;;;;;AAOf,UAAS,iBACP,mCACM;AACJ,UAAQ,KAAK,kGAAkG;AAC/G,WAAS;IAEX,MACD;;;;;AAMD,UAAS,iBACP,oCACC,OAAO;AACN,UAAQ,KACN,oHACD;AACD,MAAI,YAAY,GACd,QAAO,OAAO,OAAO,GAAG,OAAO;IAGnC,MACD;AAWD,QATiB;EACf;EACA,wBAAwB,MAAM,iBAAiB,EAAE;EACjD,sBAAsB,cAA4C;AAChE,SAAM,gBAAgB;;EAExB;EACD"}
|
|
1
|
+
{"version":3,"file":"html-api.js","names":[],"sources":["../../../src/standalone/lib/html-api.ts"],"sourcesContent":["import type {\n AnyApiReferenceConfiguration,\n ApiReferenceConfigurationWithSource,\n CreateApiReference,\n} from '@scalar/types/api-reference'\nimport { apiReferenceConfigurationWithSourceSchema } from '@scalar/types/api-reference'\nimport { createHead } from '@unhead/vue/client'\nimport { createApp, createSSRApp, h, reactive } from 'vue'\n\nimport { default as ApiReference } from '@/components/ApiReference.vue'\n\nconst getSpecScriptTag = (doc: Document) => doc.getElementById('api-reference')\n\n/**\n * Reading the configuration from the data-attributes.\n */\nexport function getConfigurationFromDataAttributes(doc: Document): ApiReferenceConfigurationWithSource {\n const specElement = doc.querySelector('[data-spec]')\n const specUrlElement = doc.querySelector('[data-spec-url]')\n const configurationScriptElement = doc.querySelector('#api-reference[data-configuration]')\n\n const getConfiguration = () => {\n // <script data-configuration=\"{ … }\" />\n if (configurationScriptElement) {\n const configurationFromElement = configurationScriptElement.getAttribute('data-configuration')\n\n if (configurationFromElement) {\n return {\n _integration: 'html',\n ...JSON.parse(configurationFromElement.split('"').join('\"')),\n }\n }\n }\n\n return apiReferenceConfigurationWithSourceSchema.parse({ _integration: 'html' })\n }\n\n const getUrl = () => {\n // Let's first check if the user passed a spec URL in the configuration.\n if (getConfiguration().url) {\n return getConfiguration().url\n }\n\n if (getConfiguration().spec?.url) {\n return getConfiguration().spec?.url\n }\n\n // <script id=\"api-reference\" data-url=\"/scalar.json\" />\n const specScriptTag = getSpecScriptTag(doc)\n if (specScriptTag) {\n const urlFromScriptTag = specScriptTag.getAttribute('data-url')?.trim()\n\n if (urlFromScriptTag) {\n return urlFromScriptTag\n }\n }\n\n // <div data-spec-url=\"/scalar.json\" />\n if (specUrlElement) {\n console.warn(\n '[@scalar/api-reference] The [data-spec-url] HTML API is deprecated. Use the new <script id=\"api-reference\" data-url=\"/scalar.json\" /> API instead.',\n )\n const urlFromSpecUrlElement = specUrlElement.getAttribute('data-spec-url')\n\n if (urlFromSpecUrlElement) {\n return urlFromSpecUrlElement\n }\n }\n\n return undefined\n }\n\n const getContent = (): string | undefined => {\n // <script id=\"api-reference\" type=\"application/json\">{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"Example\"},\"paths\":{}}</script>\n const specScriptTag = getSpecScriptTag(doc)\n if (specScriptTag) {\n const specFromScriptTag = specScriptTag.innerHTML?.trim()\n\n if (specFromScriptTag) {\n return specFromScriptTag\n }\n }\n\n // <div data-spec='{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"Example\"},\"paths\":{}}' />\n if (specElement) {\n console.warn(\n '[@scalar/api-reference] The [data-spec] HTML API is deprecated. Use the new <script id=\"api-reference\" type=\"application/json\">{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"Example\"},\"paths\":{}}</script> API instead.',\n )\n const specFromSpecElement = specElement.getAttribute('data-spec')?.trim()\n\n if (specFromSpecElement) {\n return specFromSpecElement\n }\n }\n\n return undefined\n }\n\n const getProxyUrl = () => {\n // <script id=\"api-reference\" data-proxy-url=\"https://proxy.scalar.com\">…</script>\n const specScriptTag = getSpecScriptTag(doc)\n if (specScriptTag) {\n const proxyUrl = specScriptTag.getAttribute('data-proxy-url')\n\n if (proxyUrl) {\n return proxyUrl.trim()\n }\n }\n\n return undefined\n }\n\n // Ensure Reference Props are reactive\n if (!specUrlElement && !specElement && !getSpecScriptTag(doc)) {\n // Stay quiet.\n } else {\n const urlOrContent = getContent() ? { content: getContent() } : { url: getUrl() }\n\n return apiReferenceConfigurationWithSourceSchema.parse({\n _integration: 'html',\n proxyUrl: getProxyUrl(),\n ...getConfiguration(),\n ...urlOrContent,\n })\n }\n\n return apiReferenceConfigurationWithSourceSchema.parse({ _integration: 'html' })\n}\n\n/**\n * Mount the Scalar API Reference on a given document.\n * Read the HTML data-attributes for configuration.\n */\nexport function findDataAttributes(doc: Document, configuration: ApiReferenceConfigurationWithSource) {\n /** @deprecated Use the new <script id=\"api-reference\" data-url=\"/scalar.json\" /> API instead. */\n const specElement = doc.querySelector('[data-spec]')\n /** @deprecated Use the new <script id=\"api-reference\" data-url=\"/scalar.json\" /> API instead. */\n const specUrlElement = doc.querySelector('[data-spec-url]')\n\n if (configuration?.darkMode) {\n doc.body?.classList.add('dark-mode')\n } else {\n doc.body?.classList.add('light-mode')\n }\n\n const container = createContainer(doc, specElement || specUrlElement)\n\n if (container) {\n createApiReference(container, configuration)\n }\n}\n\n// If it's a script tag, we can't mount the Vue.js app inside that tag.\n// We need to add a new container element before the script tag.\nexport const createContainer = (doc: Document, element?: Element | null) => {\n let _container: Element | null = null\n\n const specScriptTag = getSpecScriptTag(doc)\n\n if (specScriptTag) {\n _container = doc.createElement('div')\n specScriptTag?.parentNode?.insertBefore(_container, specScriptTag)\n } else if (element) {\n _container = element\n }\n\n return _container\n}\n\n/**\n * Create (and mount) a new Scalar API Reference\n *\n * @example createApiReference({ url: '/scalar.json' }).mount('#app')\n * @example createApiReference('#app', { url: '/scalar.json' })\n * @example createApiReference(document.getElementById('app'), { url: '/scalar.json' })\n */\nexport const createApiReference: CreateApiReference = (\n elementOrSelectorOrConfig,\n optionalConfiguration?: AnyApiReferenceConfiguration,\n) => {\n // Create an id prefix for useId so we don't have collisions with other Vue apps\n const idPrefix = 'scalar-refs'\n\n const props = reactive<{ configuration: AnyApiReferenceConfiguration }>({\n // Either the configuration will be the second argument or it MUST be the first (configuration only)\n configuration: optionalConfiguration ?? (elementOrSelectorOrConfig as AnyApiReferenceConfiguration) ?? {},\n })\n\n const createReferenceApp = (isSsr = false) => {\n const referenceApp = isSsr ? createSSRApp(() => h(ApiReference, props)) : createApp(() => h(ApiReference, props))\n\n // Meta tags, etc.\n referenceApp.use(createHead())\n referenceApp.config.idPrefix = idPrefix\n\n return referenceApp\n }\n\n // If we have an optional config, then we must mount the element immediately (not sure why type is not narrowing)\n const mountElement = optionalConfiguration\n ? typeof elementOrSelectorOrConfig === 'string'\n ? document.querySelector(elementOrSelectorOrConfig)\n : (elementOrSelectorOrConfig as Element)\n : null\n\n // Detect server-rendered content and use createSSRApp for hydration\n const shouldHydrate = !!optionalConfiguration && !!mountElement && mountElement.children.length > 0\n let app = createReferenceApp(shouldHydrate)\n\n if (optionalConfiguration) {\n if (mountElement) {\n app.mount(mountElement)\n } else {\n console.error('Could not find a mount point for API References:', elementOrSelectorOrConfig)\n }\n }\n\n /**\n * Reload the API Reference\n * @deprecated\n */\n document.addEventListener(\n 'scalar:reload-references',\n () => {\n console.warn(\n 'scalar:reload-references event has been deprecated, please use the scalarInstance.app.mount method instead.',\n )\n if (!props.configuration) {\n return\n }\n\n // Snag the current element\n const currentElement =\n typeof elementOrSelectorOrConfig === 'string'\n ? document.querySelector(elementOrSelectorOrConfig)\n : (elementOrSelectorOrConfig as Element)\n\n if (!currentElement) {\n return\n }\n\n // Ensure we re-attach the element if it was unmounted\n if (currentElement && !document.body.contains(currentElement)) {\n document.body.appendChild(currentElement)\n }\n\n // Create a new Vue app instance\n app.unmount()\n app = createReferenceApp()\n app.mount(currentElement)\n },\n false,\n )\n\n /** Destroy the current API Reference instance */\n const destroy = () => {\n props.configuration = {}\n app.unmount()\n }\n\n /**\n * Allow user to destroy the API Reference\n * @deprecated\n */\n document.addEventListener(\n 'scalar:destroy-references',\n () => {\n console.warn('scalar:destroy-references event has been deprecated, please use scalarInstance.destroy instead.')\n destroy()\n },\n false,\n )\n\n /**\n * Allow user to update configuration\n * @deprecated\n */\n document.addEventListener(\n 'scalar:update-references-config',\n (ev) => {\n console.warn(\n 'scalar:update-references-config event has been deprecated, please use scalarInstance.updateConfiguration instead.',\n )\n if ('detail' in ev) {\n Object.assign(props, ev.detail)\n }\n },\n false,\n )\n\n const instance = {\n app,\n getConfiguration: () => props.configuration ?? {},\n updateConfiguration: (newConfig: AnyApiReferenceConfiguration) => {\n props.configuration = newConfig\n },\n destroy,\n }\n\n return instance\n}\n"],"mappings":";;;;;;;;;;;;AAgLA,IAAa,sBACX,2B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