@scalar/mock-server 0.20.3 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/dist/create-openapi-mock-server.d.ts.map +1 -1
  3. package/dist/create-openapi-mock-server.js +78 -19
  4. package/dist/index.d.ts +1 -1
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/libs/store.d.ts.map +1 -1
  7. package/dist/libs/store.js +13 -11
  8. package/dist/routes/mock-any-response.d.ts.map +1 -1
  9. package/dist/routes/mock-any-response.js +34 -9
  10. package/dist/types.d.ts +39 -0
  11. package/dist/types.d.ts.map +1 -1
  12. package/dist/utils/clone-document.d.ts +13 -0
  13. package/dist/utils/clone-document.d.ts.map +1 -0
  14. package/dist/utils/clone-document.js +56 -0
  15. package/dist/utils/drop-read-only-required.d.ts +8 -0
  16. package/dist/utils/drop-read-only-required.d.ts.map +1 -0
  17. package/dist/utils/drop-read-only-required.js +72 -0
  18. package/dist/utils/generate-response-example.d.ts +2 -18
  19. package/dist/utils/generate-response-example.d.ts.map +1 -1
  20. package/dist/utils/generate-response-example.js +2 -19
  21. package/dist/utils/hono-route-from-path.d.ts +23 -6
  22. package/dist/utils/hono-route-from-path.d.ts.map +1 -1
  23. package/dist/utils/hono-route-from-path.js +82 -20
  24. package/dist/utils/is-settable-response-header.d.ts +3 -0
  25. package/dist/utils/is-settable-response-header.d.ts.map +1 -0
  26. package/dist/utils/is-settable-response-header.js +6 -0
  27. package/dist/utils/mocked-operation.d.ts +21 -0
  28. package/dist/utils/mocked-operation.d.ts.map +1 -0
  29. package/dist/utils/mocked-operation.js +13 -0
  30. package/dist/utils/path-parameters.d.ts +3 -1
  31. package/dist/utils/path-parameters.d.ts.map +1 -1
  32. package/dist/utils/path-parameters.js +24 -3
  33. package/dist/utils/path-specificity.d.ts +32 -0
  34. package/dist/utils/path-specificity.d.ts.map +1 -0
  35. package/dist/utils/path-specificity.js +47 -0
  36. package/dist/utils/process-document.d.ts +5 -1
  37. package/dist/utils/process-document.d.ts.map +1 -1
  38. package/dist/utils/process-document.js +9 -2
  39. package/dist/utils/sandbox.d.ts.map +1 -1
  40. package/dist/utils/sandbox.js +23 -0
  41. package/dist/utils/validate-request.d.ts.map +1 -1
  42. package/dist/utils/validate-request.js +10 -2
  43. package/package.json +8 -7
@@ -1,27 +1,10 @@
1
1
  import { getExampleFromSchema } from '@scalar/workspace-store/request-example';
2
2
  /**
3
- * Generate a mocked response value from a schema the mock has declared.
4
- *
5
- * Every value the mock puts on the wire — an HTTP body, an SSE frame, a channel message — has to
6
- * satisfy the schema it was declared with, which is why this passes `includeDeprecated: true`:
7
- * `deprecated` marks a field as discouraged, not absent, so omitting it answered a declared JSON
8
- * response with zero bytes and dropped required properties. Owning the option set in one place keeps
9
- * a newly added response path from quietly missing that.
10
- *
11
- * Not for response headers. Two of the options here would change what an already-declared header
12
- * emits: `emptyString` yields the literal `string` for a bare `type: 'string'` and switches on
13
- * format-based generation (a `format: 'date-time'` header would emit a fabricated timestamp), and
14
- * `mode: 'read'` drops a `writeOnly` header entirely. Headers set `includeDeprecated` on their own
15
- * call instead.
16
- *
17
- * @param schema - The resolved schema to generate a value for.
18
- * @param variables - Values for `x-variable` substitution, usually a request's path parameters.
19
- * Omitted by callers that have no request in scope, such as channel messages.
20
- * @returns The generated value, or `undefined` when the schema yields nothing.
3
+ * Generate response bodies and message payloads with response-mode defaults.
4
+ * Headers use the generator directly to preserve empty strings and write-only values.
21
5
  */
22
6
  export const generateResponseExample = (schema, variables) => getExampleFromSchema(schema, {
23
7
  emptyString: 'string',
24
8
  variables,
25
9
  mode: 'read',
26
- includeDeprecated: true,
27
10
  });
@@ -1,16 +1,33 @@
1
1
  /** Prefix for the parameters we synthesize to match a literal path segment verbatim. */
2
2
  export declare const LITERAL_PARAMETER_PREFIX = "__scalar_literal_";
3
+ /**
4
+ * Read the path parameters of one segment out of the request segment it matched.
5
+ *
6
+ * The request segment is matched with the same pattern the route was registered with, before it is
7
+ * decoded, so every parameter gets the part of the segment the router assigned to it — an encoded
8
+ * delimiter such as `%2C` in `{a},{b}` stays inside its value. Each part is decoded afterwards.
9
+ * Templates with nothing between them cannot be told apart and stay unbound.
10
+ */
11
+ export declare const parametersFromSegment: (segment: string, requestSegment: string) => Record<string, string>;
12
+ /**
13
+ * Convert an OpenAPI path key into the segments of a Hono route, one entry per `/`-separated segment
14
+ * of the path portion of the key.
15
+ *
16
+ * The segments are returned on their own, rather than as a route string, because an escaped segment
17
+ * carries a regular expression with a `/` in it (`[^/]+`), so the joined route cannot be split back
18
+ * into segments. Everything else about the conversion is described on `honoRouteFromPath`.
19
+ */
20
+ export declare const honoRouteSegmentsFromPath: (path: string) => string[];
3
21
  /**
4
22
  * Convert an OpenAPI path key into a Hono route.
5
23
  *
6
24
  * Example: `/posts/{id}` → `/posts/:id`
7
25
  *
8
- * A segment whose literal text would be read as routing syntax is registered as a single parameter
9
- * with an explicit pattern instead, because Hono allows only one parameter per segment and that is
10
- * the only way to make it match such a segment verbatim. The request then routes to the right
11
- * operation, but the path parameters of that one segment are no longer bound by name: they surface
12
- * as the synthesized parameter, and a required path parameter in it reads as missing to request
13
- * validation. Hono cannot express both at once, and matching the wrong operation is worse.
26
+ * A segment whose literal text would be read as routing syntax, or that mixes a template with
27
+ * literal text (`{id}.json`, `v{version}`), is registered as a single parameter with an explicit
28
+ * pattern instead, because Hono allows only one parameter per segment and that is the only way to
29
+ * make it match such a segment verbatim. Hono then binds the whole segment to the synthesized
30
+ * parameter, so `pathParameters` splits it back into the parameters the path key declares.
14
31
  *
15
32
  * A query string in the key (`/v1/messages?beta=true`) is dropped here — it is matched against the
16
33
  * incoming request separately, see `splitPathKey`.
@@ -1 +1 @@
1
- {"version":3,"file":"hono-route-from-path.d.ts","sourceRoot":"","sources":["../../src/utils/hono-route-from-path.ts"],"names":[],"mappings":"AAaA,wFAAwF;AACxF,eAAO,MAAM,wBAAwB,sBAAsB,CAAA;AA2D3D;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,iBAAiB,GAAI,MAAM,MAAM,KAAG,MAiChD,CAAA"}
1
+ {"version":3,"file":"hono-route-from-path.d.ts","sourceRoot":"","sources":["../../src/utils/hono-route-from-path.ts"],"names":[],"mappings":"AAaA,wFAAwF;AACxF,eAAO,MAAM,wBAAwB,sBAAsB,CAAA;AAuF3D;;;;;;;GAOG;AACH,eAAO,MAAM,qBAAqB,GAAI,SAAS,MAAM,EAAE,gBAAgB,MAAM,KAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAmBpG,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,yBAAyB,GAAI,MAAM,MAAM,KAAG,MAAM,EA4C9D,CAAA;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,iBAAiB,GAAI,MAAM,MAAM,KAAG,MAAmD,CAAA"}
@@ -23,17 +23,23 @@ const escapeRegExpLiteral = (value) => value.replace(/[^A-Za-z0-9]/g, (character
23
23
  const code = character.charCodeAt(0);
24
24
  return code < 128 ? `\\x${code.toString(16).padStart(2, '0')}` : character;
25
25
  });
26
+ /** Whether the template at `index` of a split segment directly follows another template. */
27
+ const isMergedTemplate = (parts, index) => index > 1 && parts[index - 1] === '';
26
28
  /**
27
29
  * Build a regular expression that matches a path segment verbatim.
28
30
  *
29
31
  * Literal text is escaped and a template matches anything but a slash. Every template except the
30
- * last one also excludes the character the literal behind it starts with, so its match has exactly
31
- * one possible end and the engine never has to search: an OpenAPI document is untrusted input, and a
32
+ * last one also stops at the first place the literal behind it appears after a nonempty prefix, so
33
+ * its match has exactly one possible end: an OpenAPI document is untrusted input, and a
32
34
  * segment made of several plain `[^/]+` groups backtracks exponentially on a crafted request, which
33
- * would block the event loop of the whole server. The last template stays greedy, so the common
34
- * `{name}:cancel` shape still accepts a value that contains the delimiter.
35
+ * would block the event loop of the whole server. Stopping at the whole literal rather than at its
36
+ * first character keeps `{id}-v{version}` matching an id with a dash in it. The last template stays
37
+ * greedy, so the common `{name}:cancel` shape still accepts a value that contains the delimiter.
38
+ *
39
+ * With `capture`, every template that can be told apart from its neighbours becomes a capturing
40
+ * group, in the order `parametersFromSegment` reads them back.
35
41
  */
36
- const patternFromSegment = (segment) => {
42
+ const patternFromSegment = (segment, capture = false) => {
37
43
  // Splitting on a regular expression with a capturing group interleaves literals and parameter
38
44
  // names, so every odd entry is a template and the list always begins and ends with a literal.
39
45
  const parts = segment.split(PATH_KEY_TEMPLATE);
@@ -51,31 +57,71 @@ const patternFromSegment = (segment) => {
51
57
  if (followingLiteral === '' && index !== lastTemplate) {
52
58
  continue;
53
59
  }
54
- const delimiter = index === lastTemplate ? '' : escapeRegExpLiteral(followingLiteral.slice(0, 1));
55
- pattern += `[^/${delimiter}]+`;
60
+ // A separator can also start a value, such as the minus sign in `/range/-1-5`. Consume one
61
+ // character before looking for the separator so the parameter stays nonempty without branching.
62
+ const group = index === lastTemplate ? '[^/]+' : `[^/](?:(?!${escapeRegExpLiteral(followingLiteral)})[^/])*`;
63
+ pattern += capture && !isMergedTemplate(parts, index) ? `(${group})` : group;
56
64
  }
57
65
  return pattern;
58
66
  };
59
67
  /**
60
- * Convert an OpenAPI path key into a Hono route.
68
+ * Whether a segment mixes a template with literal text, as in `{id}.json` or `v{version}`.
61
69
  *
62
- * Example: `/posts/{id}` → `/posts/:id`
70
+ * Hono reads `:id.json` as one parameter named `id.json` that matches any value, and `v:version` as
71
+ * the literal text `v:version`. So such a segment has to be a pattern for its literal text to be
72
+ * enforced, and its parameters are bound back by name from the matched value (see `pathParameters`).
73
+ */
74
+ const hasEmbeddedTemplate = (segment) => segment.replace(PATH_KEY_TEMPLATE, '') !== '' && segment.replace(PATH_KEY_TEMPLATE, '') !== segment;
75
+ /** Decode a path parameter value the way Hono does, keeping it verbatim when it is malformed. */
76
+ const decodeParameterValue = (value) => {
77
+ try {
78
+ return decodeURIComponent(value);
79
+ }
80
+ catch {
81
+ return value;
82
+ }
83
+ };
84
+ /**
85
+ * Read the path parameters of one segment out of the request segment it matched.
63
86
  *
64
- * A segment whose literal text would be read as routing syntax is registered as a single parameter
65
- * with an explicit pattern instead, because Hono allows only one parameter per segment and that is
66
- * the only way to make it match such a segment verbatim. The request then routes to the right
67
- * operation, but the path parameters of that one segment are no longer bound by name: they surface
68
- * as the synthesized parameter, and a required path parameter in it reads as missing to request
69
- * validation. Hono cannot express both at once, and matching the wrong operation is worse.
87
+ * The request segment is matched with the same pattern the route was registered with, before it is
88
+ * decoded, so every parameter gets the part of the segment the router assigned to it — an encoded
89
+ * delimiter such as `%2C` in `{a},{b}` stays inside its value. Each part is decoded afterwards.
90
+ * Templates with nothing between them cannot be told apart and stay unbound.
91
+ */
92
+ export const parametersFromSegment = (segment, requestSegment) => {
93
+ const parts = segment.split(PATH_KEY_TEMPLATE);
94
+ const names = parts.filter((_, index) => index % 2 === 1 && (parts[index + 1] !== '' || index === parts.length - 2) && !isMergedTemplate(parts, index));
95
+ const match = new RegExp(`^${patternFromSegment(segment, true)}$`).exec(requestSegment);
96
+ if (!match) {
97
+ return {};
98
+ }
99
+ return Object.fromEntries(names.flatMap((name, index) => {
100
+ const parameterValue = match[index + 1];
101
+ return parameterValue === undefined ? [] : [[name, decodeParameterValue(parameterValue)]];
102
+ }));
103
+ };
104
+ /**
105
+ * Convert an OpenAPI path key into the segments of a Hono route, one entry per `/`-separated segment
106
+ * of the path portion of the key.
70
107
  *
71
- * A query string in the key (`/v1/messages?beta=true`) is dropped here — it is matched against the
72
- * incoming request separately, see `splitPathKey`.
108
+ * The segments are returned on their own, rather than as a route string, because an escaped segment
109
+ * carries a regular expression with a `/` in it (`[^/]+`), so the joined route cannot be split back
110
+ * into segments. Everything else about the conversion is described on `honoRouteFromPath`.
73
111
  */
74
- export const honoRouteFromPath = (path) => {
112
+ export const honoRouteSegmentsFromPath = (path) => {
75
113
  const { path: pathname } = splitPathKey(path);
76
114
  const route = [];
77
115
  let literalIndex = 0;
78
116
  let previousIsPattern = false;
117
+ // A synthesized name must not be one the document declares, or Hono binds both to one value.
118
+ const declaredNames = new Set([...pathname.matchAll(new RegExp(PATH_KEY_TEMPLATE))].map(([, name]) => name));
119
+ const nextSyntheticName = () => {
120
+ while (declaredNames.has(`${LITERAL_PARAMETER_PREFIX}${literalIndex}`)) {
121
+ literalIndex++;
122
+ }
123
+ return `${LITERAL_PARAMETER_PREFIX}${literalIndex++}`;
124
+ };
79
125
  for (const segment of pathname.split('/')) {
80
126
  // Check the literal text and the parameter names, but not the braces around them — the `:` we
81
127
  // generate for a template is meant to be routing syntax, a `?` in a parameter name is not.
@@ -87,14 +133,30 @@ export const honoRouteFromPath = (path) => {
87
133
  // the router throw on every request. An empty segment (a trailing slash, or `//`) is exempt:
88
134
  // Hono skips the lookahead for it, and it has no literal text to turn into a pattern.
89
135
  const needsPattern = HONO_ROUTING_CHARACTERS.test(routeText) ||
136
+ hasEmbeddedTemplate(segment) ||
90
137
  (previousIsPattern && plainSegment !== '' && !plainSegment.startsWith(':'));
91
138
  if (needsPattern) {
92
- route.push(`:${LITERAL_PARAMETER_PREFIX}${literalIndex++}{${patternFromSegment(segment)}}`);
139
+ route.push(`:${nextSyntheticName()}{${patternFromSegment(segment)}}`);
93
140
  }
94
141
  else {
95
142
  route.push(plainSegment);
96
143
  }
97
144
  previousIsPattern = needsPattern;
98
145
  }
99
- return route.join('/');
146
+ return route;
100
147
  };
148
+ /**
149
+ * Convert an OpenAPI path key into a Hono route.
150
+ *
151
+ * Example: `/posts/{id}` → `/posts/:id`
152
+ *
153
+ * A segment whose literal text would be read as routing syntax, or that mixes a template with
154
+ * literal text (`{id}.json`, `v{version}`), is registered as a single parameter with an explicit
155
+ * pattern instead, because Hono allows only one parameter per segment and that is the only way to
156
+ * make it match such a segment verbatim. Hono then binds the whole segment to the synthesized
157
+ * parameter, so `pathParameters` splits it back into the parameters the path key declares.
158
+ *
159
+ * A query string in the key (`/v1/messages?beta=true`) is dropped here — it is matched against the
160
+ * incoming request separately, see `splitPathKey`.
161
+ */
162
+ export const honoRouteFromPath = (path) => honoRouteSegmentsFromPath(path).join('/');
@@ -0,0 +1,3 @@
1
+ /** Reject fields that Fetch or the HTTP transport cannot represent, before writing the response. */
2
+ export declare const isSettableResponseHeader: (name: string, value: string) => boolean;
3
+ //# sourceMappingURL=is-settable-response-header.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"is-settable-response-header.d.ts","sourceRoot":"","sources":["../../src/utils/is-settable-response-header.ts"],"names":[],"mappings":"AAEA,oGAAoG;AACpG,eAAO,MAAM,wBAAwB,GAAI,MAAM,MAAM,EAAE,OAAO,MAAM,KAAG,OAGtE,CAAA"}
@@ -0,0 +1,6 @@
1
+ import { HTTP_TOKEN } from '@scalar/helpers/http/http-token';
2
+ /** Reject fields that Fetch or the HTTP transport cannot represent, before writing the response. */
3
+ export const isSettableResponseHeader = (name, value) => {
4
+ // Compare the full match because a regexp's end anchor can precede a final newline.
5
+ return HTTP_TOKEN.exec(name)?.[0] === name && !/[^\t\x20-\x7e\x80-\xff]/.test(value);
6
+ };
@@ -0,0 +1,21 @@
1
+ import type { OpenAPIV3_1 } from '@scalar/openapi-types';
2
+ import type { Context } from 'hono';
3
+ /** The operation a route mocks, used to name what failed in an error response */
4
+ export type MockedOperation = {
5
+ /** HTTP method with the capitalization sent in the request, for example `GET` or `copy` */
6
+ method: string;
7
+ /** The OpenAPI path key, for example `/pets/{petId}` (not the Hono route it is registered as) */
8
+ path: string;
9
+ /** The `operationId` of the operation, when the document declares one */
10
+ operationId?: string;
11
+ };
12
+ /**
13
+ * Record which operation a request matched, so an error escaping it can be named and `onResponse`
14
+ * receives the operation object itself.
15
+ */
16
+ export declare const setMockedOperation: (c: Context, mockedOperation: MockedOperation, operation: OpenAPIV3_1.OperationObject) => void;
17
+ /** Read back the operation a request matched, or `undefined` when it reached no mocked route */
18
+ export declare const getMockedOperation: (c: Context) => MockedOperation | undefined;
19
+ /** Read back the operation object a request matched, or `undefined` when it reached no mocked route */
20
+ export declare const getMatchedOperation: (c: Context) => OpenAPIV3_1.OperationObject | undefined;
21
+ //# sourceMappingURL=mocked-operation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mocked-operation.d.ts","sourceRoot":"","sources":["../../src/utils/mocked-operation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAEnC,iFAAiF;AACjF,MAAM,MAAM,eAAe,GAAG;IAC5B,2FAA2F;IAC3F,MAAM,EAAE,MAAM,CAAA;IACd,iGAAiG;IACjG,IAAI,EAAE,MAAM,CAAA;IACZ,yEAAyE;IACzE,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB,CAAA;AAaD;;;GAGG;AACH,eAAO,MAAM,kBAAkB,GAC7B,GAAG,OAAO,EACV,iBAAiB,eAAe,EAChC,WAAW,WAAW,CAAC,eAAe,KACrC,IAGF,CAAA;AAED,gGAAgG;AAChG,eAAO,MAAM,kBAAkB,GAAI,GAAG,OAAO,KAAG,eAAe,GAAG,SACjB,CAAA;AAEjD,uGAAuG;AACvG,eAAO,MAAM,mBAAmB,GAAI,GAAG,OAAO,KAAG,WAAW,CAAC,eAAe,GAAG,SAC7B,CAAA"}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Record which operation a request matched, so an error escaping it can be named and `onResponse`
3
+ * receives the operation object itself.
4
+ */
5
+ export const setMockedOperation = (c, mockedOperation, operation) => {
6
+ ;
7
+ c.set('mockedOperation', mockedOperation);
8
+ c.set('matchedOperation', operation);
9
+ };
10
+ /** Read back the operation a request matched, or `undefined` when it reached no mocked route */
11
+ export const getMockedOperation = (c) => c.get('mockedOperation');
12
+ /** Read back the operation object a request matched, or `undefined` when it reached no mocked route */
13
+ export const getMatchedOperation = (c) => c.get('matchedOperation');
@@ -7,7 +7,9 @@ import type { Context } from 'hono';
7
7
  * in an `x-handler` context or among the variables a mocked response body is generated from.
8
8
  *
9
9
  * The names are read back off the matched route rather than recognized by their prefix, so a
10
- * document that happens to declare a parameter of the same name keeps it.
10
+ * document that happens to declare a parameter of the same name keeps it. The value of a synthesized
11
+ * parameter is split into the parameters its segment declares, as in `{id}.json` or `{from}-{to}`,
12
+ * which needs the OpenAPI path key the request matched.
11
13
  */
12
14
  export declare const pathParameters: (context: Context) => Record<string, string>;
13
15
  //# sourceMappingURL=path-parameters.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"path-parameters.d.ts","sourceRoot":"","sources":["../../src/utils/path-parameters.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAOnC;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,GAAI,SAAS,OAAO,KAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAItE,CAAA"}
1
+ {"version":3,"file":"path-parameters.d.ts","sourceRoot":"","sources":["../../src/utils/path-parameters.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAgBnC;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,cAAc,GAAI,SAAS,OAAO,KAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAsBtE,CAAA"}
@@ -1,6 +1,10 @@
1
- import { LITERAL_PARAMETER_PREFIX } from './hono-route-from-path.js';
1
+ import { LITERAL_PARAMETER_PREFIX, honoRouteSegmentsFromPath, parametersFromSegment, } from './hono-route-from-path.js';
2
+ import { getMockedOperation } from './mocked-operation.js';
3
+ import { splitPathKey } from './split-path-key.js';
2
4
  /** Matches the parameters `honoRouteFromPath` synthesizes, which always carry an explicit pattern. */
3
5
  const synthesizedParameter = new RegExp(`:(${LITERAL_PARAMETER_PREFIX}\\d+)\\{`, 'g');
6
+ /** Matches a route segment that is a synthesized parameter. */
7
+ const synthesizedSegment = new RegExp(`^:(${LITERAL_PARAMETER_PREFIX}\\d+)\\{`);
4
8
  /**
5
9
  * Read the path parameters of a request, without the ones synthesized for routing.
6
10
  *
@@ -9,9 +13,26 @@ const synthesizedParameter = new RegExp(`:(${LITERAL_PARAMETER_PREFIX}\\d+)\\{`,
9
13
  * in an `x-handler` context or among the variables a mocked response body is generated from.
10
14
  *
11
15
  * The names are read back off the matched route rather than recognized by their prefix, so a
12
- * document that happens to declare a parameter of the same name keeps it.
16
+ * document that happens to declare a parameter of the same name keeps it. The value of a synthesized
17
+ * parameter is split into the parameters its segment declares, as in `{id}.json` or `{from}-{to}`,
18
+ * which needs the OpenAPI path key the request matched.
13
19
  */
14
20
  export const pathParameters = (context) => {
15
21
  const synthesized = new Set([...context.req.routePath.matchAll(synthesizedParameter)].map(([, name]) => name));
16
- return Object.fromEntries(Object.entries(context.req.param()).filter(([name]) => !synthesized.has(name)));
22
+ const values = context.req.param();
23
+ const declared = Object.fromEntries(Object.entries(values).filter(([name]) => !synthesized.has(name)));
24
+ const pathKey = getMockedOperation(context)?.path;
25
+ if (pathKey === undefined) {
26
+ return declared;
27
+ }
28
+ // The path key lines up with the end of the request path, which carries any base path in front.
29
+ const segments = splitPathKey(pathKey).path.split('/');
30
+ const requestSegments = context.req.path.split('/').slice(-segments.length);
31
+ const embedded = honoRouteSegmentsFromPath(pathKey).flatMap((route, index) => {
32
+ const requestSegment = requestSegments[index];
33
+ return synthesizedSegment.test(route) && requestSegment !== undefined
34
+ ? [parametersFromSegment(segments[index] ?? '', requestSegment)]
35
+ : [];
36
+ });
37
+ return Object.assign({}, ...embedded, declared);
17
38
  };
@@ -0,0 +1,32 @@
1
+ /**
2
+ * How specific one path segment is, lower being more specific:
3
+ *
4
+ * - `0` — literal text only (`messages`, `users:batchGet`), which matches one value
5
+ * - `1` — a template mixed with literal text (`{jobId}:cancel`), which matches a subset of values
6
+ * - `2` — nothing but templates (`{id}`, `{a}{b}`), which matches any value
7
+ */
8
+ type SegmentSpecificity = 0 | 1 | 2;
9
+ /**
10
+ * Describe how specific a path key is, one rank per `/`-separated segment of its path portion.
11
+ *
12
+ * The query string of the key is ignored: it does not take part in routing, and variants of one path
13
+ * are ordered among themselves by how many query parameters they pin.
14
+ */
15
+ export declare const getPathSpecificity: (pathKey: string) => readonly SegmentSpecificity[];
16
+ /**
17
+ * Order two paths so the more concrete one is matched first, as the OpenAPI Paths Object asks:
18
+ * "When matching URLs, concrete (non-templated) paths would be matched before their templated
19
+ * counterparts."
20
+ *
21
+ * Segments are compared position by position and the first one that differs decides, so
22
+ * `/pets/mine` comes before `/pets/{petId}`, and `/a/literal/{y}` before `/a/{x}/b`. The specification
23
+ * leaves pairs like `/{entity}/me` and `/books/{id}` ambiguous and up to the tooling; reading from
24
+ * the left, the way a path is resolved one segment at a time, settles them toward `/books/{id}`.
25
+ *
26
+ * Paths with a different number of segments can never match the same request, because a path
27
+ * parameter never matches a `/`, so the shorter one simply goes first to keep the order total. Paths
28
+ * that rank the same return `0` and keep their relative order in a stable sort.
29
+ */
30
+ export declare const comparePathSpecificity: (left: readonly SegmentSpecificity[], right: readonly SegmentSpecificity[]) => number;
31
+ export {};
32
+ //# sourceMappingURL=path-specificity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path-specificity.d.ts","sourceRoot":"","sources":["../../src/utils/path-specificity.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,KAAK,kBAAkB,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;AAkBnC;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB,GAAI,SAAS,MAAM,KAAG,SAAS,kBAAkB,EAI/E,CAAA;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,sBAAsB,GACjC,MAAM,SAAS,kBAAkB,EAAE,EACnC,OAAO,SAAS,kBAAkB,EAAE,KACnC,MAUF,CAAA"}
@@ -0,0 +1,47 @@
1
+ import { PATH_KEY_TEMPLATE, splitPathKey } from './split-path-key.js';
2
+ /**
3
+ * Rank one segment of a path key.
4
+ *
5
+ * A segment that mixes a template with literal text ranks between the two, because the router
6
+ * enforces its literal text (see `honoRouteFromPath`).
7
+ */
8
+ const segmentSpecificity = (segment) => {
9
+ const literalText = segment.replace(PATH_KEY_TEMPLATE, '');
10
+ if (literalText === segment) {
11
+ return 0;
12
+ }
13
+ return literalText === '' ? 2 : 1;
14
+ };
15
+ /**
16
+ * Describe how specific a path key is, one rank per `/`-separated segment of its path portion.
17
+ *
18
+ * The query string of the key is ignored: it does not take part in routing, and variants of one path
19
+ * are ordered among themselves by how many query parameters they pin.
20
+ */
21
+ export const getPathSpecificity = (pathKey) => {
22
+ const { path: pathname } = splitPathKey(pathKey);
23
+ return pathname.split('/').map((segment) => segmentSpecificity(segment));
24
+ };
25
+ /**
26
+ * Order two paths so the more concrete one is matched first, as the OpenAPI Paths Object asks:
27
+ * "When matching URLs, concrete (non-templated) paths would be matched before their templated
28
+ * counterparts."
29
+ *
30
+ * Segments are compared position by position and the first one that differs decides, so
31
+ * `/pets/mine` comes before `/pets/{petId}`, and `/a/literal/{y}` before `/a/{x}/b`. The specification
32
+ * leaves pairs like `/{entity}/me` and `/books/{id}` ambiguous and up to the tooling; reading from
33
+ * the left, the way a path is resolved one segment at a time, settles them toward `/books/{id}`.
34
+ *
35
+ * Paths with a different number of segments can never match the same request, because a path
36
+ * parameter never matches a `/`, so the shorter one simply goes first to keep the order total. Paths
37
+ * that rank the same return `0` and keep their relative order in a stable sort.
38
+ */
39
+ export const comparePathSpecificity = (left, right) => {
40
+ for (let index = 0; index < Math.min(left.length, right.length); index++) {
41
+ const difference = (left[index] ?? 0) - (right[index] ?? 0);
42
+ if (difference !== 0) {
43
+ return difference;
44
+ }
45
+ }
46
+ return left.length - right.length;
47
+ };
@@ -8,6 +8,10 @@ export type ProcessedDocument = {
8
8
  type: 'asyncapi';
9
9
  document: AsyncApiDocument;
10
10
  };
11
- /** Bundle API descriptions once, retaining AsyncAPI and upgrading compatible OpenAPI input. */
11
+ /**
12
+ * Bundle API descriptions once, retaining AsyncAPI and upgrading compatible OpenAPI input.
13
+ *
14
+ * An object input is never modified; the returned document is built from a copy of it.
15
+ */
12
16
  export declare const processDocument: (document: string | Record<string, unknown> | undefined, origin?: string) => Promise<ProcessedDocument>;
13
17
  //# sourceMappingURL=process-document.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"process-document.d.ts","sourceRoot":"","sources":["../../src/utils/process-document.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAErE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AAGlE,8FAA8F;AAC9F,MAAM,MAAM,iBAAiB,GACzB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,QAAQ,EAAE,WAAW,CAAC,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAA;CAAE,GAC1E;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,EAAE,gBAAgB,CAAA;CAAE,CAAA;AAEpD,+FAA+F;AAC/F,eAAO,MAAM,eAAe,GAC1B,UAAU,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EACtD,SAAS,MAAM,KACd,OAAO,CAAC,iBAAiB,CAyE3B,CAAA"}
1
+ {"version":3,"file":"process-document.d.ts","sourceRoot":"","sources":["../../src/utils/process-document.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAErE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AAKlE,8FAA8F;AAC9F,MAAM,MAAM,iBAAiB,GACzB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,QAAQ,EAAE,WAAW,CAAC,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAA;CAAE,GAC1E;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,EAAE,gBAAgB,CAAA;CAAE,CAAA;AAEpD;;;;GAIG;AACH,eAAO,MAAM,eAAe,GAC1B,UAAU,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EACtD,SAAS,MAAM,KACd,OAAO,CAAC,iBAAiB,CA2E3B,CAAA"}
@@ -8,7 +8,12 @@ import { isHttpUrl } from '@scalar/json-magic/helpers/is-http-url';
8
8
  import { createMagicProxy } from '@scalar/json-magic/magic-proxy';
9
9
  import { upgrade } from '@scalar/openapi-upgrader';
10
10
  import { openApiDocument, resolveOpenApiDocument } from '@scalar/workspace-store/plugins/bundler';
11
- /** Bundle API descriptions once, retaining AsyncAPI and upgrading compatible OpenAPI input. */
11
+ import { cloneDocument } from './clone-document.js';
12
+ /**
13
+ * Bundle API descriptions once, retaining AsyncAPI and upgrading compatible OpenAPI input.
14
+ *
15
+ * An object input is never modified; the returned document is built from a copy of it.
16
+ */
12
17
  export const processDocument = async (document, origin) => {
13
18
  // Handle empty/undefined input gracefully
14
19
  if (!document || (typeof document === 'object' && Object.keys(document).length === 0)) {
@@ -34,7 +39,9 @@ export const processDocument = async (document, origin) => {
34
39
  try {
35
40
  // Bundle external references with Node.js plugins
36
41
  // Include parseJson and parseYaml to handle string inputs
37
- bundled = await bundle(document, {
42
+ // `bundle` edits the object it is handed — it records external documents under `x-ext` and drops
43
+ // `x-ext-urls` — so an object input is copied first and the caller's document is left as passed.
44
+ bundled = await bundle(typeof document === 'string' ? document : cloneDocument(document), {
38
45
  origin,
39
46
  plugins: [
40
47
  openApiDocument(),
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../../src/utils/sandbox.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAiCrD;;GAEG;AACH,KAAK,mBAAmB,GAAG;IACzB,mHAAmH;IACnH,IAAI,EAAE,MAAM,CAAA;IACZ,mEAAmE;IACnE,KAAK,EAAE,cAAc,CAAA;IACrB,8FAA8F;IAC9F,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACrC,yGAAyG;IACzG,WAAW,CAAC,EAAE,OAAO,CAAA;CACtB,CAAA;AA8LD;;;;;;;GAOG;AACH,wBAAsB,YAAY,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,OAAO,CAAC,CAqEjF"}
1
+ {"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../../src/utils/sandbox.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAiCrD;;GAEG;AACH,KAAK,mBAAmB,GAAG;IACzB,mHAAmH;IACnH,IAAI,EAAE,MAAM,CAAA;IACZ,mEAAmE;IACnE,KAAK,EAAE,cAAc,CAAA;IACrB,8FAA8F;IAC9F,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACrC,yGAAyG;IACzG,WAAW,CAAC,EAAE,OAAO,CAAA;CACtB,CAAA;AAyND;;;;;;;GAOG;AACH,wBAAsB,YAAY,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,OAAO,CAAC,CAqEjF"}
@@ -54,6 +54,17 @@ function callFaker(path, args) {
54
54
  // Bind to the resolved module so faker methods keep their expected `this`.
55
55
  return fn.apply(receiver, args);
56
56
  }
57
+ /** Select only the argument used as an item key by the requested store method. */
58
+ const idArgument = (method, args) => {
59
+ const value = args[1];
60
+ if (method === 'create') {
61
+ return value !== null && typeof value === 'object' && 'id' in value ? value.id : undefined;
62
+ }
63
+ if (method === 'get' || method === 'update' || method === 'delete') {
64
+ return value;
65
+ }
66
+ return undefined;
67
+ };
57
68
  /**
58
69
  * Run a store method requested by the guest and return a JSON envelope.
59
70
  */
@@ -63,6 +74,18 @@ function runStoreBridge(store, method, argsJson) {
63
74
  throw new Error(`store: "${method}" is not a method`);
64
75
  }
65
76
  const args = JSON.parse(argsJson);
77
+ if (!Array.isArray(args)) {
78
+ throw new Error('store: arguments must be an array');
79
+ }
80
+ const [collection] = args;
81
+ if (typeof collection !== 'string' && !(method === 'clear' && collection == null)) {
82
+ throw new Error('store: collection must be a string');
83
+ }
84
+ // Do not coerce guest objects or arrays into property names on the host.
85
+ const id = idArgument(method, args);
86
+ if (id != null && typeof id !== 'string' && typeof id !== 'number') {
87
+ throw new Error('store: item ID must be a string or number');
88
+ }
66
89
  const result = store[method](...args);
67
90
  return serializeEnvelope({ ok: true, value: result ?? null });
68
91
  }
@@ -1 +1 @@
1
- {"version":3,"file":"validate-request.d.ts","sourceRoot":"","sources":["../../src/utils/validate-request.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAe,MAAM,uBAAuB,CAAA;AAMrE,OAAO,KAAK,EAAW,iBAAiB,EAAE,MAAM,MAAM,CAAA;AAuTtD;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe,GAC1B,WAAW,WAAW,CAAC,eAAe,EACtC,qBAAqB,WAAW,CAAC,cAAc,CAAC,YAAY,CAAC,KAC5D,iBAmLF,CAAA"}
1
+ {"version":3,"file":"validate-request.d.ts","sourceRoot":"","sources":["../../src/utils/validate-request.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAe,MAAM,uBAAuB,CAAA;AAMrE,OAAO,KAAK,EAAW,iBAAiB,EAAE,MAAM,MAAM,CAAA;AA8TtD;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe,GAC1B,WAAW,WAAW,CAAC,eAAe,EACtC,qBAAqB,WAAW,CAAC,cAAc,CAAC,YAAY,CAAC,KAC5D,iBAoLF,CAAA"}
@@ -1,11 +1,14 @@
1
1
  import { getFirstMediaType } from '@scalar/helpers/http/get-first-media-type';
2
2
  import { parseMimeType } from '@scalar/helpers/http/mime-type';
3
+ import { useDecimalMultipleOf } from '@scalar/json-schema-validator/decimal-multiple-of';
3
4
  import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
4
5
  import { getResolvedRefDeep } from '@scalar/workspace-store/helpers/get-resolved-ref-deep';
5
6
  import Ajv2020 from 'ajv/dist/2020.js';
6
7
  import addFormats from 'ajv-formats';
7
8
  import { getCookie } from 'hono/cookie';
9
+ import { pathParameters } from './path-parameters.js';
8
10
  import { deserializeArrayParameter, deserializeObjectParameter, getObjectPropertyNames, isArraySchema, isObjectSchema, resolveSerialization, } from './deserialize-parameter.js';
11
+ import { dropReadOnlyRequired } from './drop-read-only-required.js';
9
12
  import { findQuerystringParameter, getQuerystringJsonSchema, parseQuerystringParameter } from './querystring-parameter.js';
10
13
  import { replaceCircularMarkers } from './replace-circular-markers.js';
11
14
  /**
@@ -133,9 +136,11 @@ const compileSchema = (ajv, schema, label) => {
133
136
  const compileValidators = (operation, pathItemParameters) => {
134
137
  // Coerce string parameters to their declared types (integer, boolean, …).
135
138
  const parameterAjv = new Ajv2020({ strict: false, allErrors: true, coerceTypes: true });
139
+ useDecimalMultipleOf(parameterAjv);
136
140
  addFormats(parameterAjv);
137
141
  // Do not coerce the JSON body; a JSON value already carries its type and coercion would mask errors.
138
142
  const bodyAjv = new Ajv2020({ strict: false, allErrors: true });
143
+ useDecimalMultipleOf(bodyAjv);
139
144
  addFormats(bodyAjv);
140
145
  // Path-item parameters apply to every operation, so fold them in before building the schemas.
141
146
  const parameters = mergeParameters(pathItemParameters, operation.parameters);
@@ -151,7 +156,9 @@ const compileValidators = (operation, pathItemParameters) => {
151
156
  let bodySchema = null;
152
157
  try {
153
158
  const jsonSchema = getResolvedRef(requestBody?.content?.['application/json'])?.schema;
154
- bodySchema = jsonSchema ? asCompilableSchema(getResolvedRefDeep(jsonSchema)) : null;
159
+ bodySchema = jsonSchema
160
+ ? dropReadOnlyRequired(asCompilableSchema(getResolvedRefDeep(jsonSchema)))
161
+ : null;
155
162
  }
156
163
  catch (error) {
157
164
  console.error('Error resolving request body schema, skipping body validation:', error);
@@ -283,12 +290,13 @@ export const validateRequest = (operation, pathItemParameters) => {
283
290
  // survives deserialization;
284
291
  // - cookie supplies a `getMap` (each exploded `form` object property is its own cookie);
285
292
  // - header names are matched case-insensitively by Hono's `c.req.header`.
293
+ const requestPathParameters = pathParameters(c);
286
294
  const parameterLocations = [
287
295
  {
288
296
  validator: validators.path,
289
297
  descriptors: validators.pathParameters,
290
298
  location: 'path',
291
- getValue: (name) => c.req.param(name),
299
+ getValue: (name) => requestPathParameters[name],
292
300
  },
293
301
  {
294
302
  validator: validators.query,
package/package.json CHANGED
@@ -16,7 +16,7 @@
16
16
  "swagger",
17
17
  "cli"
18
18
  ],
19
- "version": "0.20.3",
19
+ "version": "0.21.1",
20
20
  "engines": {
21
21
  "node": ">=22.19.0"
22
22
  },
@@ -52,12 +52,13 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@faker-js/faker": "10.6.0",
55
- "@scalar/helpers": "0.16.4",
56
- "@scalar/json-magic": "0.17.0",
57
- "@scalar/openapi-types": "0.9.8",
58
- "@scalar/openapi-upgrader": "0.4.6",
59
- "@scalar/types": "0.26.0",
60
- "@scalar/workspace-store": "0.69.3",
55
+ "@scalar/helpers": "0.17.1",
56
+ "@scalar/json-magic": "0.19.0",
57
+ "@scalar/json-schema-validator": "0.1.19",
58
+ "@scalar/openapi-types": "0.9.9",
59
+ "@scalar/openapi-upgrader": "0.4.8",
60
+ "@scalar/types": "0.28.0",
61
+ "@scalar/workspace-store": "0.71.0",
61
62
  "ajv": "^8.20.0",
62
63
  "ajv-formats": "^3.0.1",
63
64
  "hono": "^4.13.13",