@scalar/mock-server 0.21.7 → 0.21.9
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 +26 -0
- package/dist/create-mock-server.js +1 -1
- package/dist/create-openapi-mock-server.d.ts +5 -2
- package/dist/create-openapi-mock-server.d.ts.map +1 -1
- package/dist/create-openapi-mock-server.js +67 -20
- package/dist/routes/mock-any-response.d.ts.map +1 -1
- package/dist/routes/mock-any-response.js +22 -20
- package/dist/utils/build-handler-context.d.ts.map +1 -1
- package/dist/utils/build-handler-context.js +9 -9
- package/dist/utils/deserialize-parameter.d.ts +15 -0
- package/dist/utils/deserialize-parameter.d.ts.map +1 -1
- package/dist/utils/deserialize-parameter.js +36 -7
- package/dist/utils/expand-server-variables.d.ts +6 -0
- package/dist/utils/expand-server-variables.d.ts.map +1 -0
- package/dist/utils/expand-server-variables.js +44 -0
- package/dist/utils/get-response-header-example.d.ts +13 -0
- package/dist/utils/get-response-header-example.d.ts.map +1 -0
- package/dist/utils/get-response-header-example.js +94 -0
- package/dist/utils/is-json-content-type.d.ts +4 -0
- package/dist/utils/is-json-content-type.d.ts.map +1 -0
- package/dist/utils/is-json-content-type.js +2 -0
- package/dist/utils/process-document.d.ts +2 -0
- package/dist/utils/process-document.d.ts.map +1 -1
- package/dist/utils/process-document.js +65 -9
- package/dist/utils/resolve-server-base-paths.d.ts +17 -0
- package/dist/utils/resolve-server-base-paths.d.ts.map +1 -0
- package/dist/utils/resolve-server-base-paths.js +85 -0
- package/dist/utils/resolve-server-pathnames.d.ts.map +1 -1
- package/dist/utils/resolve-server-pathnames.js +9 -12
- package/dist/utils/serialize-linkset.d.ts +3 -0
- package/dist/utils/serialize-linkset.d.ts.map +1 -0
- package/dist/utils/serialize-linkset.js +77 -0
- package/dist/utils/validate-request.d.ts.map +1 -1
- package/dist/utils/validate-request.js +165 -96
- package/package.json +10 -10
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# @scalar/mock-server
|
|
2
2
|
|
|
3
|
+
## 0.21.9
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#11215](https://github.com/scalar/scalar/pull/11215): Respect string length bounds when generating plain text and formatted string examples, including API reference examples and mock server responses. Preserve path parameter placeholders in code samples.
|
|
8
|
+
|
|
9
|
+
## 0.21.8
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- [#11195](https://github.com/scalar/scalar/pull/11195): Update compatible dependencies for AI chat, focus management, code and Markdown rendering, HTTP requests, mock servers, and application data fetching.
|
|
14
|
+
- [#11192](https://github.com/scalar/scalar/pull/11192): Validate JSON and plain-text request parameters declared with `content`. Malformed JSON is rejected, and JSON values keep their original types during validation, so `?filter={"price":"5"}` is rejected when `price` is an integer.
|
|
15
|
+
- [#11178](https://github.com/scalar/scalar/pull/11178): Read an empty `matrix` path array (`;ids`) as an empty array during request validation instead of a one-element `['ids']` array.
|
|
16
|
+
- [#11207](https://github.com/scalar/scalar/pull/11207): Validate and parse request bodies sent with structured `+json` media types such as `application/vnd.api+json` and `application/merge-patch+json`, so they are checked against the schema and reach `x-handler` as `req.body`.
|
|
17
|
+
- [#11177](https://github.com/scalar/scalar/pull/11177): Strip the `label` and `matrix` prefixes from primitive path parameters before request validation, so `/users/.5` and `/users/;id=5` are accepted for an integer `id`.
|
|
18
|
+
|
|
19
|
+
Preserve percent-encoded delimiters in matrix parameter names and primitive values so validation checks the complete string.
|
|
20
|
+
- [#11224](https://github.com/scalar/scalar/pull/11224): Send authored response header examples (`example`, `examples`, or a `content` media type) instead of values generated from the header schema.
|
|
21
|
+
|
|
22
|
+
Emit each cookie in its own field and escape Unicode in JSON and XML header examples. Use the referenced schema’s component name as the default XML root element.
|
|
23
|
+
|
|
24
|
+
Share HTTP quoted-string escaping and support character references for line breaks and Unicode in XML header data.
|
|
25
|
+
- [#11204](https://github.com/scalar/scalar/pull/11204): Serve OpenAPI operations under the base path of their servers, so `GET /v1/pets` answers when the document declares `servers: [{ url: 'https://api.example.com/v1' }]`. OpenAPI 2.0 `basePath`, relative server URLs, and every enum value of a server variable in the path are served too, and operation and path item servers take precedence over the servers of the document. Operations keep answering at their bare path keys.
|
|
26
|
+
|
|
27
|
+
Descriptions that exceed the server URL expansion or generated route budget continue serving their bare operation routes.
|
|
28
|
+
|
|
3
29
|
## 0.21.7
|
|
4
30
|
|
|
5
31
|
### Patch Changes
|
|
@@ -9,5 +9,5 @@ export const createMockServer = async (configuration) => {
|
|
|
9
9
|
const processed = await processDocument(configuration?.document ?? configuration?.specification, configuration?.origin);
|
|
10
10
|
return processed.type === 'asyncapi'
|
|
11
11
|
? createAsyncApiMockServer(configuration, processed.document)
|
|
12
|
-
: createOpenApiMockServer(configuration, processed
|
|
12
|
+
: createOpenApiMockServer(configuration, processed);
|
|
13
13
|
};
|
|
@@ -4,7 +4,10 @@ import type { ProcessedDocument } from './utils/process-document.js';
|
|
|
4
4
|
/**
|
|
5
5
|
* Create a mock server instance
|
|
6
6
|
*/
|
|
7
|
-
export declare const createOpenApiMockServer: (configuration: MockServerOptions, schema: Extract<ProcessedDocument, {
|
|
7
|
+
export declare const createOpenApiMockServer: (configuration: MockServerOptions, { document: schema, originalOpenapiVersion, retrievalUri, serverRetrievalUris, }: Extract<ProcessedDocument, {
|
|
8
8
|
type: "openapi";
|
|
9
|
-
}
|
|
9
|
+
}>, aliasLimits?: {
|
|
10
|
+
serverUrls: number;
|
|
11
|
+
generatedRoutes: number;
|
|
12
|
+
}) => Promise<Hono>;
|
|
10
13
|
//# sourceMappingURL=create-openapi-mock-server.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-openapi-mock-server.d.ts","sourceRoot":"","sources":["../src/create-openapi-mock-server.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"create-openapi-mock-server.d.ts","sourceRoot":"","sources":["../src/create-openapi-mock-server.ts"],"names":[],"mappings":"AAIA,OAAO,EAAgB,IAAI,EAA0B,MAAM,MAAM,CAAA;AAIjE,OAAO,KAAK,EAAE,iBAAiB,EAA0B,MAAM,SAAS,CAAA;AAexE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAA;AAoFjE;;GAEG;AACH,eAAO,MAAM,uBAAuB,GAClC,eAAe,iBAAiB,EAChC,kFAKG,OAAO,CAAC,iBAAiB,EAAE;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,CAAC,EAClD;;;CAAgC,KAC/B,OAAO,CAAC,IAAI,CA+Sd,CAAA"}
|
|
@@ -15,6 +15,7 @@ import { getMatchedOperation, getMockedOperation, setMockedOperation, } from './
|
|
|
15
15
|
import { comparePathSpecificity, getPathSpecificity } from './utils/path-specificity.js';
|
|
16
16
|
import { requestMatchesPinnedQuery } from './utils/request-matches-pinned-query.js';
|
|
17
17
|
import { resolveLogger } from './utils/resolve-logger.js';
|
|
18
|
+
import { MAX_SERVER_URL_EXPANSIONS, resolveServerBasePaths } from './utils/resolve-server-base-paths.js';
|
|
18
19
|
import { setUpAuthenticationRoutes } from './utils/set-up-authentication-routes.js';
|
|
19
20
|
import { splitPathKey } from './utils/split-path-key.js';
|
|
20
21
|
import { validateRequest } from './utils/validate-request.js';
|
|
@@ -79,10 +80,12 @@ const runResponseHook = (onResponse) => async (c, next) => {
|
|
|
79
80
|
* `HTTPException` thrown from a second copy of Hono is still recognized.
|
|
80
81
|
*/
|
|
81
82
|
const carriesResponse = (error) => 'getResponse' in error && typeof error.getResponse === 'function';
|
|
83
|
+
/** Limit the extra work a single OpenAPI description can add through server URL aliases. */
|
|
84
|
+
const defaultAliasLimits = { serverUrls: MAX_SERVER_URL_EXPANSIONS, generatedRoutes: 10_000 };
|
|
82
85
|
/**
|
|
83
86
|
* Create a mock server instance
|
|
84
87
|
*/
|
|
85
|
-
export const createOpenApiMockServer = async (configuration, schema, originalOpenapiVersion) => {
|
|
88
|
+
export const createOpenApiMockServer = async (configuration, { document: schema, originalOpenapiVersion, retrievalUri, serverRetrievalUris, }, aliasLimits = defaultAliasLimits) => {
|
|
86
89
|
const app = new Hono();
|
|
87
90
|
const generationContext = {
|
|
88
91
|
openapiVersion: schema.openapi,
|
|
@@ -163,11 +166,12 @@ export const createOpenApiMockServer = async (configuration, schema, originalOpe
|
|
|
163
166
|
if (configuration.onResponse) {
|
|
164
167
|
app.use(runResponseHook(configuration.onResponse));
|
|
165
168
|
}
|
|
166
|
-
|
|
169
|
+
// Built-in authentication routes take precedence over operation routes at the same URL and method.
|
|
167
170
|
setUpAuthenticationRoutes(app, schema);
|
|
168
|
-
//
|
|
171
|
+
// The instructions honor `logger` (on by default). The util still prints warnings and errors
|
|
169
172
|
// about security schemes the mock server cannot handle, which a silenced startup should surface.
|
|
170
|
-
|
|
173
|
+
const logger = resolveLogger(configuration.logger, true);
|
|
174
|
+
logAuthenticationInstructions(schema?.components?.securitySchemes || {}, logger);
|
|
171
175
|
/** Paths specified in the OpenAPI document */
|
|
172
176
|
const paths = schema?.paths ?? {};
|
|
173
177
|
// Hono runs every matching route in registration order and the first one that answers wins, so
|
|
@@ -201,13 +205,19 @@ export const createOpenApiMockServer = async (configuration, schema, originalOpe
|
|
|
201
205
|
const orderedPathKeys = [...pathKeys].sort((a, b) => comparePathSpecificity(a.specificity, b.specificity) ||
|
|
202
206
|
(documentOrder.get(a.pathname) ?? 0) - (documentOrder.get(b.pathname) ?? 0) ||
|
|
203
207
|
b.query.length - a.query.length);
|
|
208
|
+
/** Route handler of each operation, with the base paths its servers serve it under */
|
|
209
|
+
const operationRoutes = [];
|
|
210
|
+
const basePathsByServers = new WeakMap();
|
|
211
|
+
const serverUrlBudget = { remaining: aliasLimits.serverUrls };
|
|
212
|
+
let remainingRoutes = aliasLimits.generatedRoutes;
|
|
213
|
+
let exceededAliasLimit;
|
|
204
214
|
orderedPathKeys.forEach(({ path, query }) => {
|
|
205
215
|
// A path item may itself be a `$ref`, so resolve it before reading its operations.
|
|
206
|
-
const
|
|
216
|
+
const referringPathItem = paths[path];
|
|
217
|
+
const pathItem = getResolvedRef(referringPathItem);
|
|
207
218
|
const operations = getOperations(pathItem);
|
|
208
219
|
/** Keys for all operations of a specified path */
|
|
209
220
|
Object.entries(operations).forEach(([method, operation]) => {
|
|
210
|
-
const route = honoRouteFromPath(path);
|
|
211
221
|
// Remember which operation this route mocks, so the error handler can name it when something
|
|
212
222
|
// fails downstream. Recorded on the context rather than mapped back from the request path,
|
|
213
223
|
// which would not survive the app being mounted under a base path. Registered before the rest
|
|
@@ -263,26 +273,63 @@ export const createOpenApiMockServer = async (configuration, schema, originalOpe
|
|
|
263
273
|
// that does not carry them is handed on to the next matching route — usually the sibling path
|
|
264
274
|
// key without the query string.
|
|
265
275
|
const operationChain = every(...handlers);
|
|
266
|
-
//
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
276
|
+
// An empty server list overrides the enclosing servers without adding a base path.
|
|
277
|
+
const servers = [operation.servers, referringPathItem?.servers, pathItem?.servers, schema.servers].find(Array.isArray);
|
|
278
|
+
if (servers && !exceededAliasLimit) {
|
|
279
|
+
const basePaths = basePathsByServers.get(servers) ??
|
|
280
|
+
resolveServerBasePaths(servers, serverRetrievalUris.get(getRaw(servers)) ?? retrievalUri, serverUrlBudget);
|
|
281
|
+
if (basePaths === undefined) {
|
|
282
|
+
exceededAliasLimit = `${aliasLimits.serverUrls} server URL combinations`;
|
|
271
283
|
}
|
|
272
|
-
else {
|
|
273
|
-
|
|
284
|
+
else if (basePaths.length > remainingRoutes) {
|
|
285
|
+
exceededAliasLimit = `${aliasLimits.generatedRoutes} generated routes`;
|
|
274
286
|
}
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
!requestMatchesPinnedQuery(c, query)) {
|
|
279
|
-
await next();
|
|
280
|
-
return;
|
|
287
|
+
else {
|
|
288
|
+
basePathsByServers.set(servers, basePaths);
|
|
289
|
+
remainingRoutes -= basePaths.length;
|
|
281
290
|
}
|
|
282
|
-
|
|
291
|
+
}
|
|
292
|
+
operationRoutes.push({
|
|
293
|
+
method,
|
|
294
|
+
path,
|
|
295
|
+
basePaths: (servers && basePathsByServers.get(servers)) ?? [],
|
|
296
|
+
handler: async (c, next) => {
|
|
297
|
+
if ((c.req.method !== method && !(method === 'GET' && c.req.method === 'HEAD')) ||
|
|
298
|
+
!requestMatchesPinnedQuery(c, query)) {
|
|
299
|
+
await next();
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
await operationChain(c, next);
|
|
303
|
+
},
|
|
283
304
|
});
|
|
284
305
|
});
|
|
285
306
|
});
|
|
307
|
+
// Hono uppercases methods during registration. Match the original method ourselves so
|
|
308
|
+
// additional operations such as COPY and copy remain distinct.
|
|
309
|
+
const register = (method, route, handler) => {
|
|
310
|
+
if (method === method.toUpperCase()) {
|
|
311
|
+
app.on(method, route, handler);
|
|
312
|
+
}
|
|
313
|
+
else {
|
|
314
|
+
app.all(route, handler);
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
// Each operation answers at its path key and again under the base path of each of its servers. All
|
|
318
|
+
// of these routes are ordered together, so the most concrete one answers a request no matter where
|
|
319
|
+
// it comes from. The path keys go first, so on a tie the path the document declares keeps a request
|
|
320
|
+
// over a copy under a base path, and the stable sort keeps the order set above for the rest.
|
|
321
|
+
if (exceededAliasLimit) {
|
|
322
|
+
logger(`Skipped OpenAPI server base-path aliases. The document exceeded the limit of ${exceededAliasLimit}.`);
|
|
323
|
+
}
|
|
324
|
+
const aliases = exceededAliasLimit
|
|
325
|
+
? []
|
|
326
|
+
: operationRoutes.flatMap((route) => route.basePaths.map((basePath) => ({ ...route, path: `${basePath}${route.path}` })));
|
|
327
|
+
const routes = [...operationRoutes, ...aliases]
|
|
328
|
+
.map((route) => ({ ...route, specificity: getPathSpecificity(route.path) }))
|
|
329
|
+
.sort((a, b) => comparePathSpecificity(a.specificity, b.specificity));
|
|
330
|
+
for (const { method, path, handler } of routes) {
|
|
331
|
+
register(method, honoRouteFromPath(path), handler);
|
|
332
|
+
}
|
|
286
333
|
// OpenAPI JSON file
|
|
287
334
|
app.get('/openapi.json', (c) => respondWithOpenApiDocument(c, exportDocument, 'json'));
|
|
288
335
|
// OpenAPI YAML file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mock-any-response.d.ts","sourceRoot":"","sources":["../../src/routes/mock-any-response.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAKxD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAMnC,OAAO,EAAE,KAAK,wBAAwB,EAA2B,MAAM,mCAAmC,CAAA;
|
|
1
|
+
{"version":3,"file":"mock-any-response.d.ts","sourceRoot":"","sources":["../../src/routes/mock-any-response.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAKxD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAMnC,OAAO,EAAE,KAAK,wBAAwB,EAA2B,MAAM,mCAAmC,CAAA;AAyB1G;;GAEG;AACH,wBAAgB,eAAe,CAC7B,CAAC,EAAE,OAAO,EACV,SAAS,EAAE,WAAW,CAAC,eAAe,EACtC,iBAAiB,GAAE,wBAA6B,YA4KjD"}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { isXmlMediaType } from '@scalar/helpers/http/is-xml-media-type';
|
|
2
2
|
import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
|
|
3
3
|
import { getResolvedRefDeep } from '@scalar/workspace-store/helpers/get-resolved-ref-deep';
|
|
4
|
-
import {
|
|
4
|
+
import { getXmlBodyExample } from '@scalar/workspace-store/request-example';
|
|
5
5
|
import { streamSSE } from 'hono/streaming';
|
|
6
6
|
import { collectSseEvents, isEventStreamContentType } from '../utils/collect-sse-events.js';
|
|
7
7
|
import { findPreferredResponseKey } from '../utils/find-preferred-response-key.js';
|
|
8
8
|
import { generateResponseExample } from '../utils/generate-response-example.js';
|
|
9
|
+
import { getResponseHeaderExample, usesOpenApi32HeaderExamples } from '../utils/get-response-header-example.js';
|
|
9
10
|
import { isSettableResponseHeader } from '../utils/is-settable-response-header.js';
|
|
10
11
|
import { negotiateContentType } from '../utils/negotiate-content-type.js';
|
|
11
12
|
import { normalizeResponseBody } from '../utils/normalize-response-body.js';
|
|
@@ -52,32 +53,33 @@ export function mockAnyResponse(c, operation, generationContext = {}) {
|
|
|
52
53
|
// Headers
|
|
53
54
|
const headers = selectedResponse?.headers ?? {};
|
|
54
55
|
Object.keys(headers).forEach((header) => {
|
|
56
|
+
const name = header.toLowerCase();
|
|
55
57
|
// The body and transport determine these headers. Generated values can truncate a response or
|
|
56
58
|
// make clients decode uncompressed data; OpenAPI also requires ignoring declared Content-Type.
|
|
57
|
-
if (IGNORED_RESPONSE_HEADERS.has(
|
|
59
|
+
if (IGNORED_RESPONSE_HEADERS.has(name)) {
|
|
58
60
|
return;
|
|
59
61
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
// Loose check on purpose: Hono *deletes* a header when handed `undefined`. This loop is the first
|
|
66
|
-
// thing to set the declared headers, so in practice a delete removes a header set earlier by
|
|
67
|
-
// middleware — `cors()` sets `Access-Control-Allow-Origin` before the handler runs.
|
|
68
|
-
if (value != null) {
|
|
69
|
-
try {
|
|
70
|
-
const text = String(value);
|
|
71
|
-
if (isSettableResponseHeader(header, text)) {
|
|
72
|
-
c.header(header, text);
|
|
73
|
-
return;
|
|
74
|
-
}
|
|
62
|
+
try {
|
|
63
|
+
const example = getResponseHeaderExample(headers[header], generationContext, name);
|
|
64
|
+
// Passing undefined to Hono would delete a header already set by middleware such as cors().
|
|
65
|
+
if (example === undefined) {
|
|
66
|
+
return;
|
|
75
67
|
}
|
|
76
|
-
|
|
77
|
-
|
|
68
|
+
// OpenAPI 3.2 models separate Set-Cookie fields as one cookie per line.
|
|
69
|
+
const append = name === 'set-cookie' && usesOpenApi32HeaderExamples(generationContext);
|
|
70
|
+
const values = Array.isArray(example) ? example : [example];
|
|
71
|
+
const fields = append && typeof example === 'string' ? example.split(/\r?\n/).filter(Boolean) : values;
|
|
72
|
+
if (fields.length && fields.every((value) => isSettableResponseHeader(header, value))) {
|
|
73
|
+
for (const value of fields) {
|
|
74
|
+
c.header(header, value, { append });
|
|
75
|
+
}
|
|
76
|
+
return;
|
|
78
77
|
}
|
|
79
|
-
console.warn(`Skipping invalid response header ${JSON.stringify(header)} from the API description.`);
|
|
80
78
|
}
|
|
79
|
+
catch {
|
|
80
|
+
// An authored value may fail serialization, for example if it shadows its own toString.
|
|
81
|
+
}
|
|
82
|
+
console.warn(`Skipping invalid response header ${JSON.stringify(header)} from the API description.`);
|
|
81
83
|
});
|
|
82
84
|
// For 204 No Content responses, we should not set Content-Type and should return null body
|
|
83
85
|
if (statusCode === 204) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-handler-context.d.ts","sourceRoot":"","sources":["../../src/utils/build-handler-context.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"build-handler-context.d.ts","sourceRoot":"","sources":["../../src/utils/build-handler-context.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAGxD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAInC,OAAO,EAAE,KAAK,wBAAwB,EAA2B,MAAM,6BAA6B,CAAA;AAMpG,OAAO,EAAE,KAAK,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAA;AAGjF;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,KAAK,EAAE,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC,cAAc,CAAC,CAAA;IAC5D,GAAG,EAAE;QACH,IAAI,EAAE,GAAG,CAAA;QACT,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QAC9B,oFAAoF;QACpF,KAAK,EAAE,OAAO,CAAA;QACd,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAChC,CAAA;IACD,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;CACzB,CAAA;AAED;;GAEG;AACH,KAAK,oBAAoB,GAAG;IAC1B,OAAO,EAAE,cAAc,CAAA;IACvB,QAAQ,EAAE,sBAAsB,CAAA;CACjC,CAAA;AAmED;;GAEG;AACH,wBAAsB,mBAAmB,CACvC,CAAC,EAAE,OAAO,EACV,SAAS,CAAC,EAAE,WAAW,CAAC,eAAe,EACvC,kBAAkB,CAAC,EAAE,WAAW,CAAC,cAAc,CAAC,YAAY,CAAC,EAC7D,iBAAiB,GAAE,wBAA6B,GAC/C,OAAO,CAAC,oBAAoB,CAAC,CAqD/B"}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { parseMimeType } from '@scalar/helpers/http/mime-type';
|
|
1
2
|
import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
|
|
2
3
|
import { getResolvedRefDeep } from '@scalar/workspace-store/helpers/get-resolved-ref-deep';
|
|
3
4
|
import { accepts } from 'hono/accepts';
|
|
4
5
|
import { store } from '../libs/store.js';
|
|
5
6
|
import { generateResponseExample } from './generate-response-example.js';
|
|
7
|
+
import { isJsonContentType } from './is-json-content-type.js';
|
|
6
8
|
import { normalizeResponseBody } from './normalize-response-body.js';
|
|
7
9
|
import { parsePreferHeader } from './parse-prefer-header.js';
|
|
8
10
|
import { pathParameters } from './path-parameters.js';
|
|
@@ -61,19 +63,17 @@ function getExampleFromResponse(c, statusCode, responses, generationContext = {}
|
|
|
61
63
|
export async function buildHandlerContext(c, operation, pathItemParameters, generationContext = {}) {
|
|
62
64
|
let body = undefined;
|
|
63
65
|
try {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
//
|
|
67
|
-
|
|
68
|
-
// An empty/absent Content-Type is treated as JSON to match request validation, so a headerless
|
|
69
|
-
// JSON body that passes validation is still delivered to the handler as `req.body`.
|
|
70
|
-
if (contentType === '' || contentType.includes('application/json')) {
|
|
66
|
+
const contentType = c.req.header('content-type')?.trim() ?? '';
|
|
67
|
+
const mediaType = contentType ? parseMimeType(contentType) : undefined;
|
|
68
|
+
// Treat an omitted header as JSON to match request validation.
|
|
69
|
+
if (!mediaType || isJsonContentType(mediaType)) {
|
|
71
70
|
body = await c.req.json().catch(() => undefined);
|
|
72
71
|
}
|
|
73
|
-
else if (
|
|
72
|
+
else if (mediaType.essence === 'application/x-www-form-urlencoded') {
|
|
74
73
|
body = await c.req.parseBody().catch(() => undefined);
|
|
75
74
|
}
|
|
76
|
-
else if (
|
|
75
|
+
else if (mediaType.type === 'text' && /^text\//i.test(contentType)) {
|
|
76
|
+
// The MIME parser also returns text/plain for malformed headers.
|
|
77
77
|
body = await c.req.text().catch(() => undefined);
|
|
78
78
|
}
|
|
79
79
|
}
|
|
@@ -43,6 +43,21 @@ export declare const deserializeArrayParameter: ({ style, explode, single, multi
|
|
|
43
43
|
/** Every repeated value (query only, for example `?id=1&id=2` becomes `['1', '2']`) */
|
|
44
44
|
multi?: string[] | undefined;
|
|
45
45
|
}) => string[] | undefined;
|
|
46
|
+
/**
|
|
47
|
+
* Deserialize a string-encoded primitive parameter, removing the `label` or `matrix` prefix.
|
|
48
|
+
*
|
|
49
|
+
* Per the spec Style Examples a `label` primitive is dot-prefixed (`.5`) and a `matrix` primitive is
|
|
50
|
+
* `;name=value` (`;id=5`), with `;id` for an empty value. Other styles send the value as-is.
|
|
51
|
+
*
|
|
52
|
+
* Returns `undefined` when the parameter is absent so the caller can enforce `required` separately.
|
|
53
|
+
*/
|
|
54
|
+
export declare const deserializePrimitiveParameter: ({ style, single, name, }: {
|
|
55
|
+
style: string;
|
|
56
|
+
/** The raw value as read from path, query, header, or cookie */
|
|
57
|
+
single: string | undefined;
|
|
58
|
+
/** Declared parameter name, used to identify the complete matrix prefix */
|
|
59
|
+
name: string;
|
|
60
|
+
}) => string | undefined;
|
|
46
61
|
/**
|
|
47
62
|
* Deserialize a string-encoded object parameter into its properties, following the OpenAPI
|
|
48
63
|
* `style`/`explode` rules. Property values stay as strings so the caller can coerce them against the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deserialize-parameter.d.ts","sourceRoot":"","sources":["../../src/utils/deserialize-parameter.ts"],"names":[],"mappings":"AACA;;;;;GAKG;AAEH,oFAAoF;AACpF,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,OAAO,GAAG,QAAQ,GAAG,QAAQ,CAAA;AAUtE;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,GAC/B,UAAU,iBAAiB,EAC3B,QAAQ,MAAM,EACd,UAAU,OAAO,KAChB;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAGnC,CAAA;AA2BD,8GAA8G;AAC9G,eAAO,MAAM,aAAa,GAAI,QAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,KAAG,OAU3E,CAAA;AAED,gHAAgH;AAChH,eAAO,MAAM,cAAc,GAAI,QAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,KAAG,OAU5E,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,sBAAsB,GAAI,QAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,KAAG,MAAM,EA4B1F,CAAA;
|
|
1
|
+
{"version":3,"file":"deserialize-parameter.d.ts","sourceRoot":"","sources":["../../src/utils/deserialize-parameter.ts"],"names":[],"mappings":"AACA;;;;;GAKG;AAEH,oFAAoF;AACpF,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,OAAO,GAAG,QAAQ,GAAG,QAAQ,CAAA;AAUtE;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,GAC/B,UAAU,iBAAiB,EAC3B,QAAQ,MAAM,EACd,UAAU,OAAO,KAChB;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAGnC,CAAA;AA2BD,8GAA8G;AAC9G,eAAO,MAAM,aAAa,GAAI,QAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,KAAG,OAU3E,CAAA;AAED,gHAAgH;AAChH,eAAO,MAAM,cAAc,GAAI,QAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,KAAG,OAU5E,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,sBAAsB,GAAI,QAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,KAAG,MAAM,EA4B1F,CAAA;AA0GD;;;;;GAKG;AACH,eAAO,MAAM,yBAAyB,GAAI,oCAKvC;IACD,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,OAAO,CAAA;IAChB,iGAAiG;IACjG,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IAC1B,uFAAuF;IACvF,KAAK,CAAC,EAAE,MAAM,EAAE,GAAG,SAAS,CAAA;CAC7B,KAAG,MAAM,EAAE,GAAG,SAoBd,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,6BAA6B,GAAI,0BAI3C;IACD,KAAK,EAAE,MAAM,CAAA;IACb,gEAAgE;IAChE,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IAC1B,2EAA2E;IAC3E,IAAI,EAAE,MAAM,CAAA;CACb,KAAG,MAAM,GAAG,SAkBZ,CAAA;AAgCD;;;;;;;;GAQG;AACH,eAAO,MAAM,0BAA0B,GAAI,qEAQxC;IACD,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,OAAO,CAAA;IAChB,+FAA+F;IAC/F,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IAC1B;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,GAAG,SAAS,CAAA;IACnD,IAAI,EAAE,MAAM,CAAA;IACZ,mGAAmG;IACnG,aAAa,CAAC,EAAE,MAAM,EAAE,GAAG,SAAS,CAAA;IACpC;;;;OAIG;IACH,YAAY,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,SAAS,CAAA;CACvC,KAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,GAAG,SAoEvC,CAAA"}
|
|
@@ -117,10 +117,10 @@ const explodedArray = (single, multi) => {
|
|
|
117
117
|
};
|
|
118
118
|
/** Drop a leading prefix (for example the `.` of `label` or the `;` of `matrix`) when present. */
|
|
119
119
|
const stripPrefix = (value, prefix) => value.startsWith(prefix) ? value.slice(prefix.length) : value;
|
|
120
|
-
/** Return the
|
|
121
|
-
const
|
|
120
|
+
/** Return the value of a `name=value` matrix segment. A bare `name` segment carries an empty value. */
|
|
121
|
+
const matrixValue = (segment) => {
|
|
122
122
|
const equals = segment.indexOf('=');
|
|
123
|
-
return equals === -1 ?
|
|
123
|
+
return equals === -1 ? '' : segment.slice(equals + 1);
|
|
124
124
|
};
|
|
125
125
|
/** Split a `matrix`-encoded value into its `;`-separated segments, dropping the leading `;` and empties. */
|
|
126
126
|
const matrixSegments = (value) => stripPrefix(value, ';')
|
|
@@ -168,12 +168,17 @@ const parseMatrixArray = (value, explode) => {
|
|
|
168
168
|
return undefined;
|
|
169
169
|
}
|
|
170
170
|
const segments = matrixSegments(value);
|
|
171
|
+
// An empty array is serialized as the bare name (`;ids`) or with an empty value (`;ids=`), in both
|
|
172
|
+
// explode modes. It has no elements, matching the other styles, rather than a phantom `'ids'` or `''`.
|
|
173
|
+
const [first] = segments;
|
|
174
|
+
if (first === undefined || (segments.length === 1 && matrixValue(first) === '')) {
|
|
175
|
+
return [];
|
|
176
|
+
}
|
|
171
177
|
if (explode) {
|
|
172
|
-
return segments.map(
|
|
178
|
+
return segments.map(matrixValue);
|
|
173
179
|
}
|
|
174
180
|
// Non-exploded: a single `name=a,b,c` segment whose value is comma-separated.
|
|
175
|
-
|
|
176
|
-
return first === undefined ? [] : valueAfterEquals(first).split(',');
|
|
181
|
+
return matrixValue(first).split(',');
|
|
177
182
|
};
|
|
178
183
|
/**
|
|
179
184
|
* Deserialize a string-encoded array parameter into its elements.
|
|
@@ -202,6 +207,30 @@ export const deserializeArrayParameter = ({ style, explode, single, multi, }) =>
|
|
|
202
207
|
return explode ? explodedArray(single, multi) : split(single, ',');
|
|
203
208
|
}
|
|
204
209
|
};
|
|
210
|
+
/**
|
|
211
|
+
* Deserialize a string-encoded primitive parameter, removing the `label` or `matrix` prefix.
|
|
212
|
+
*
|
|
213
|
+
* Per the spec Style Examples a `label` primitive is dot-prefixed (`.5`) and a `matrix` primitive is
|
|
214
|
+
* `;name=value` (`;id=5`), with `;id` for an empty value. Other styles send the value as-is.
|
|
215
|
+
*
|
|
216
|
+
* Returns `undefined` when the parameter is absent so the caller can enforce `required` separately.
|
|
217
|
+
*/
|
|
218
|
+
export const deserializePrimitiveParameter = ({ style, single, name, }) => {
|
|
219
|
+
if (single === undefined) {
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
if (style === 'label') {
|
|
223
|
+
return stripPrefix(single, '.');
|
|
224
|
+
}
|
|
225
|
+
if (style === 'matrix') {
|
|
226
|
+
// Names and values are already percent-decoded. Match the declared name so an encoded `=` in
|
|
227
|
+
// the name and an encoded `;` in the value are not mistaken for serialization delimiters.
|
|
228
|
+
const prefix = `;${name}=`;
|
|
229
|
+
// A segment without `=` (`;id`) is the parameter name with an empty value.
|
|
230
|
+
return single.startsWith(prefix) ? single.slice(prefix.length) : '';
|
|
231
|
+
}
|
|
232
|
+
return single;
|
|
233
|
+
};
|
|
205
234
|
/** Parse `R,100,G,200` (a flat list alternating key, value) into an object. */
|
|
206
235
|
const parseAlternating = (value, delimiter) => value === undefined ? undefined : alternatingFromList(value.split(delimiter));
|
|
207
236
|
/** Parse `R=100,G=200` (delimiter-separated `key=value` pairs) into an object. */
|
|
@@ -282,7 +311,7 @@ export const deserializeObjectParameter = ({ style, explode, single, map, name,
|
|
|
282
311
|
return pairsFromList(segments);
|
|
283
312
|
}
|
|
284
313
|
const [first] = segments;
|
|
285
|
-
return first === undefined ? {} : alternatingFromList(
|
|
314
|
+
return first === undefined ? {} : alternatingFromList(matrixValue(first).split(','));
|
|
286
315
|
}
|
|
287
316
|
// `spaceDelimited` / `pipeDelimited` (query): a flat alternating key,value list joined by the
|
|
288
317
|
// delimiter, e.g. `R 100 G 200` or `R|100|G|200`. Only defined for the non-exploded form.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Expand server variables within the remaining budget, or return undefined if the combinations would exceed it. */
|
|
2
|
+
export declare const expandServerVariables: (template: string, getValues: (name: string) => Iterable<string> | undefined, remaining?: number) => {
|
|
3
|
+
urls: string[];
|
|
4
|
+
combinationCount: number;
|
|
5
|
+
} | undefined;
|
|
6
|
+
//# sourceMappingURL=expand-server-variables.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"expand-server-variables.d.ts","sourceRoot":"","sources":["../../src/utils/expand-server-variables.ts"],"names":[],"mappings":"AAAA,oHAAoH;AACpH,eAAO,MAAM,qBAAqB,GAChC,UAAU,MAAM,EAChB,WAAW,CAAC,IAAI,EAAE,MAAM,KAAK,QAAQ,CAAC,MAAM,CAAC,GAAG,SAAS,EACzD,kBAAmC,KAClC;IAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IAAC,gBAAgB,EAAE,MAAM,CAAA;CAAE,GAAG,SA+CjD,CAAA"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** Expand server variables within the remaining budget, or return undefined if the combinations would exceed it. */
|
|
2
|
+
export const expandServerVariables = (template, getValues, remaining = Number.MAX_SAFE_INTEGER) => {
|
|
3
|
+
const placeholder = /\{([^{}]+)\}/g;
|
|
4
|
+
const names = new Set([...template.matchAll(placeholder)].map(([, name]) => name));
|
|
5
|
+
const dimensions = [];
|
|
6
|
+
let combinationCount = 1;
|
|
7
|
+
for (const name of names) {
|
|
8
|
+
const values = getValues(name);
|
|
9
|
+
if (values === undefined) {
|
|
10
|
+
continue;
|
|
11
|
+
}
|
|
12
|
+
const unique = new Set();
|
|
13
|
+
const maxValues = Math.floor(remaining / combinationCount);
|
|
14
|
+
for (const value of values) {
|
|
15
|
+
unique.add(value);
|
|
16
|
+
if (unique.size > maxValues) {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
if (unique.size === 0) {
|
|
21
|
+
return { urls: [], combinationCount: 0 };
|
|
22
|
+
}
|
|
23
|
+
dimensions.push([name, [...unique]]);
|
|
24
|
+
combinationCount *= unique.size;
|
|
25
|
+
}
|
|
26
|
+
// A plain URL still consumes one slot. Check before rendering any combination.
|
|
27
|
+
if (combinationCount > remaining) {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
// Change the last variable fastest to preserve enum order without storing every combination.
|
|
31
|
+
dimensions.reverse();
|
|
32
|
+
const substitutions = new Map();
|
|
33
|
+
const urls = new Set();
|
|
34
|
+
for (let index = 0; index < combinationCount; index++) {
|
|
35
|
+
let choice = index;
|
|
36
|
+
for (const [name, values] of dimensions) {
|
|
37
|
+
substitutions.set(name, values[choice % values.length]);
|
|
38
|
+
choice = Math.floor(choice / values.length);
|
|
39
|
+
}
|
|
40
|
+
// Substitute only placeholders present in the original template.
|
|
41
|
+
urls.add(template.replace(placeholder, (match, name) => substitutions.get(name) ?? match));
|
|
42
|
+
}
|
|
43
|
+
return { urls: [...urls], combinationCount };
|
|
44
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { OpenAPIV3_2 } from '@scalar/openapi-types';
|
|
2
|
+
import type { ExampleGenerationContext } from './generate-response-example.js';
|
|
3
|
+
/** Header example rules depend on the authored version, even after document upgrading. */
|
|
4
|
+
export declare const usesOpenApi32HeaderExamples: (context: ExampleGenerationContext) => boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Select and serialize a response header example before HTTP header validation.
|
|
7
|
+
*
|
|
8
|
+
* Header Object examples take precedence over media type examples. Both take precedence over
|
|
9
|
+
* schema generation, and `serializedValue` already contains the text to send.
|
|
10
|
+
* An exploded OpenAPI 3.2 cookie map returns one value per field.
|
|
11
|
+
*/
|
|
12
|
+
export declare const getResponseHeaderExample: (header: OpenAPIV3_2.HeaderObject | OpenAPIV3_2.ReferenceObject | undefined, generationContext?: ExampleGenerationContext, normalizedName?: string) => string | string[] | undefined;
|
|
13
|
+
//# sourceMappingURL=get-response-header-example.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"get-response-header-example.d.ts","sourceRoot":"","sources":["../../src/utils/get-response-header-example.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAQxD,OAAO,KAAK,EAAE,wBAAwB,EAAiB,MAAM,6BAA6B,CAAA;AAU1F,0FAA0F;AAC1F,eAAO,MAAM,2BAA2B,GAAI,SAAS,wBAAwB,KAAG,OACS,CAAA;AAuBzF;;;;;;GAMG;AACH,eAAO,MAAM,wBAAwB,GACnC,QAAQ,WAAW,CAAC,YAAY,GAAG,WAAW,CAAC,eAAe,GAAG,SAAS,EAC1E,oBAAmB,wBAA6B,EAChD,iBAAiB,MAAM,KACtB,MAAM,GAAG,MAAM,EAAE,GAAG,SA8DtB,CAAA"}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { getFirstMediaType } from '@scalar/helpers/http/get-first-media-type';
|
|
2
|
+
import { isJsonMediaType } from '@scalar/helpers/http/is-json-media-type';
|
|
3
|
+
import { isXmlMediaType } from '@scalar/helpers/http/is-xml-media-type';
|
|
4
|
+
import { parseMimeType } from '@scalar/helpers/http/mime-type';
|
|
5
|
+
import { isObject, isObjectLike } from '@scalar/helpers/object/is-object';
|
|
6
|
+
import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
|
|
7
|
+
import { getResolvedRefDeep } from '@scalar/workspace-store/helpers/get-resolved-ref-deep';
|
|
8
|
+
import { serializeQuerystringParameter } from '@scalar/workspace-store/helpers/querystring-parameter';
|
|
9
|
+
import { getExampleFromSchema, getXmlBodyExample, serializeSimpleStyle } from '@scalar/workspace-store/request-example';
|
|
10
|
+
import { coerceValue } from '@scalar/workspace-store/schemas/typebox-coerce';
|
|
11
|
+
import { EncodingObjectSchema } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document';
|
|
12
|
+
import { selectResponseExample } from './select-response-example.js';
|
|
13
|
+
import { serializeLinkset } from './serialize-linkset.js';
|
|
14
|
+
import { serializeResponseBody } from './serialize-response-body.js';
|
|
15
|
+
/** A reference chain can still end at an unresolved Media Type Object reference. */
|
|
16
|
+
const isResolvedMediaType = (value) => isObjectLike(value) && !('$ref' in value);
|
|
17
|
+
/** Header example rules depend on the authored version, even after document upgrading. */
|
|
18
|
+
export const usesOpenApi32HeaderExamples = (context) => (context.originalOpenapiVersion ?? context.openapiVersion)?.startsWith('3.2.') ?? false;
|
|
19
|
+
/** Form-based headers and whole query strings share the same URL encoding. */
|
|
20
|
+
const serializeFormHeader = (value, encoding) => {
|
|
21
|
+
if (!isObject(value)) {
|
|
22
|
+
return typeof value === 'string' ? value : undefined;
|
|
23
|
+
}
|
|
24
|
+
return serializeQuerystringParameter({
|
|
25
|
+
value,
|
|
26
|
+
kind: 'data',
|
|
27
|
+
contentType: 'application/x-www-form-urlencoded',
|
|
28
|
+
encoding: encoding &&
|
|
29
|
+
Object.fromEntries(Object.entries(encoding).map(([key, options]) => [key, coerceValue(EncodingObjectSchema, options)])),
|
|
30
|
+
}, () => null);
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Select and serialize a response header example before HTTP header validation.
|
|
34
|
+
*
|
|
35
|
+
* Header Object examples take precedence over media type examples. Both take precedence over
|
|
36
|
+
* schema generation, and `serializedValue` already contains the text to send.
|
|
37
|
+
* An exploded OpenAPI 3.2 cookie map returns one value per field.
|
|
38
|
+
*/
|
|
39
|
+
export const getResponseHeaderExample = (header, generationContext = {}, normalizedName) => {
|
|
40
|
+
const headerObject = getResolvedRef(header);
|
|
41
|
+
if (!isObjectLike(headerObject)) {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
const [contentType, mediaReference] = getFirstMediaType(headerObject.content) ?? [];
|
|
45
|
+
const resolvedMedia = getResolvedRef(mediaReference);
|
|
46
|
+
const media = isResolvedMediaType(resolvedMedia) ? resolvedMedia : undefined;
|
|
47
|
+
const example = selectResponseExample(headerObject) ?? selectResponseExample(media);
|
|
48
|
+
const mediaType = parseMimeType(contentType).essence;
|
|
49
|
+
if (example?.serializedValue !== undefined) {
|
|
50
|
+
return mediaType === 'application/linkset' ? serializeLinkset(example.serializedValue) : example.serializedValue;
|
|
51
|
+
}
|
|
52
|
+
const authoredSchema = headerObject.schema ?? media?.schema;
|
|
53
|
+
if (isXmlMediaType(contentType)) {
|
|
54
|
+
// The XML serializer uses the referenced component name as the default root element.
|
|
55
|
+
return getXmlBodyExample(authoredSchema, example, {
|
|
56
|
+
...generationContext,
|
|
57
|
+
mode: 'read',
|
|
58
|
+
format: false,
|
|
59
|
+
xmlDeclaration: false,
|
|
60
|
+
escapeForHttpHeader: true,
|
|
61
|
+
}).xml;
|
|
62
|
+
}
|
|
63
|
+
const schema = contentType !== undefined || !example ? getResolvedRefDeep(authoredSchema) : undefined;
|
|
64
|
+
const value = !example && schema ? getExampleFromSchema(schema, generationContext) : example?.value;
|
|
65
|
+
if (value === undefined) {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
if (contentType !== undefined) {
|
|
69
|
+
if (mediaType === 'application/x-www-form-urlencoded') {
|
|
70
|
+
return serializeFormHeader(value, media?.encoding);
|
|
71
|
+
}
|
|
72
|
+
if (mediaType === 'application/linkset') {
|
|
73
|
+
return serializeLinkset(value);
|
|
74
|
+
}
|
|
75
|
+
const json = isJsonMediaType(contentType);
|
|
76
|
+
const provenance = !example || (json && usesOpenApi32HeaderExamples(generationContext)) ? 'data' : example.provenance;
|
|
77
|
+
const text = serializeResponseBody(value, contentType, schema, provenance);
|
|
78
|
+
// JSON escapes keep generated data ASCII on the wire, including surrogate pairs for astral characters.
|
|
79
|
+
return json && text !== value
|
|
80
|
+
? text?.replace(/[\u007f-\uffff]/g, (unit) => `\\u${unit.charCodeAt(0).toString(16).padStart(4, '0')}`)
|
|
81
|
+
: text;
|
|
82
|
+
}
|
|
83
|
+
if (normalizedName === 'set-cookie' &&
|
|
84
|
+
usesOpenApi32HeaderExamples(generationContext) &&
|
|
85
|
+
headerObject.explode === true &&
|
|
86
|
+
isObject(value)) {
|
|
87
|
+
// Commas inside a cookie (for example, in Expires) belong to that cookie's field value.
|
|
88
|
+
return Object.entries(value).map(([cookie, attributes]) => `${cookie}=${String(attributes)}`);
|
|
89
|
+
}
|
|
90
|
+
if (value === null) {
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
return String(example?.provenance === 'data' ? serializeSimpleStyle(value, headerObject.explode ?? false) : value);
|
|
94
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ParsedMimeType } from '@scalar/helpers/http/mime-type';
|
|
2
|
+
/** Match JSON request media types after normalizing the type and subtype. */
|
|
3
|
+
export declare const isJsonContentType: ({ essence, subtype }: ParsedMimeType) => boolean;
|
|
4
|
+
//# sourceMappingURL=is-json-content-type.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"is-json-content-type.d.ts","sourceRoot":"","sources":["../../src/utils/is-json-content-type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAA;AAEpE,6EAA6E;AAC7E,eAAO,MAAM,iBAAiB,GAAI,sBAAsB,cAAc,KAAG,OACZ,CAAA"}
|
|
@@ -5,6 +5,8 @@ export type ProcessedDocument = {
|
|
|
5
5
|
type: 'openapi';
|
|
6
6
|
document: OpenAPIV3_1.Document | OpenAPIV3_2.Document;
|
|
7
7
|
originalOpenapiVersion?: string;
|
|
8
|
+
retrievalUri?: string;
|
|
9
|
+
serverRetrievalUris: WeakMap<object, string>;
|
|
8
10
|
} | {
|
|
9
11
|
type: 'asyncapi';
|
|
10
12
|
document: AsyncApiDocument;
|