@scalar/mock-server 0.21.0 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # @scalar/mock-server
2
2
 
3
+ ## 0.21.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#10951](https://github.com/scalar/scalar/pull/10951): Use shortest round-trip decimal values consistently for multipleOf checks, including large JSON integers and positive exponents. Fast-path safe integers and share keyword registration across validators.
8
+ - [#10951](https://github.com/scalar/scalar/pull/10951): Validate decimal `multipleOf` constraints with exact decimal arithmetic, accepting values such as `19.99` and `1000000.19` for `multipleOf: 0.01` while rejecting nonmultiples without a floating-point tolerance.
9
+ - [#10813](https://github.com/scalar/scalar/pull/10813): fix: keep the required properties of an object that the example depth cap truncates, so a deeply nested mock response no longer serves `{}` where its schema requires keys, including keys required through `allOf` members or the selected `oneOf`/`anyOf` variant
10
+
11
+ Preserve explicit values equal to the depth marker and exclude requirements from unselected union branches.
12
+
13
+ Keep required primitive compositions on the normal traversal and collect discriminator requirements from the branch rendered after depth truncation.
14
+
15
+ Reuse evaluated discriminator values for required-property collection and keep inferred tuple arrays empty past the depth cap.
16
+
17
+ Preserve shared requirements and required primitive values through dynamic references, including requirements declared in dynamically referenced composition members.
18
+
19
+ Collect requirements separately when composition branches reuse a shared template under different dynamic bindings.
20
+
21
+ Exclude requirements from composition members omitted by the request or response mode.
22
+
23
+ - [#10950](https://github.com/scalar/scalar/pull/10950): Ignore declared Content-Length, Content-Encoding, and Content-Type response headers so generated bodies remain readable and empty responses do not inherit a declared content type.
24
+
25
+ Ignore other transport-managed headers, including Transfer-Encoding and Trailer. Skip and warn about malformed declared header names and values instead of failing the response.
26
+
27
+ - [#10938](https://github.com/scalar/scalar/pull/10938): fix: merge array items whose `allOf` describes an object without `type: object` on the first member into one example instead of one partial object per member
28
+ - [#10940](https://github.com/scalar/scalar/pull/10940): Route path segments that mix parameters with literal text, such as `{id}.json`, `{id}:cancel` and `v{version}`, only to requests that carry the literal text, and pass their parameters to request validation, `x-handler` and `x-variable`.
29
+ - [#10930](https://github.com/scalar/scalar/pull/10930): Accept request bodies that leave out required `readOnly` properties during request validation.
30
+ - [#10875](https://github.com/scalar/scalar/pull/10875): Keep mock store collections and item IDs isolated from inherited host properties, and validate keys passed through the script sandbox.
31
+
3
32
  ## 0.21.0
4
33
 
5
34
  ### Minor Changes
@@ -1 +1 @@
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;AASxE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAA;AAyHjE;;GAEG;AACH,eAAO,MAAM,uBAAuB,GAClC,eAAe,iBAAiB,EAChC,QAAQ,OAAO,CAAC,iBAAiB,EAAE;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,CAAC,CAAC,UAAU,CAAC,KAClE,OAAO,CAAC,IAAI,CAsPd,CAAA"}
1
+ {"version":3,"file":"create-openapi-mock-server.d.ts","sourceRoot":"","sources":["../src/create-openapi-mock-server.ts"],"names":[],"mappings":"AAGA,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;AAgFjE;;GAEG;AACH,eAAO,MAAM,uBAAuB,GAClC,eAAe,iBAAiB,EAChC,QAAQ,OAAO,CAAC,iBAAiB,EAAE;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,CAAC,CAAC,UAAU,CAAC,KAClE,OAAO,CAAC,IAAI,CAsPd,CAAA"}
@@ -11,6 +11,7 @@ import { handleAuthentication } from './utils/handle-authentication.js';
11
11
  import { honoRouteFromPath } from './utils/hono-route-from-path.js';
12
12
  import { isAuthenticationRequired } from './utils/is-authentication-required.js';
13
13
  import { logAuthenticationInstructions } from './utils/log-authentication-instructions.js';
14
+ import { getMatchedOperation, getMockedOperation, setMockedOperation, } from './utils/mocked-operation.js';
14
15
  import { comparePathSpecificity, getPathSpecificity } from './utils/path-specificity.js';
15
16
  import { requestMatchesPinnedQuery } from './utils/request-matches-pinned-query.js';
16
17
  import { resolveLogger } from './utils/resolve-logger.js';
@@ -21,19 +22,6 @@ import { store } from './libs/store.js';
21
22
  import { mockAnyResponse } from './routes/mock-any-response.js';
22
23
  import { mockHandlerResponse } from './routes/mock-handler-response.js';
23
24
  import { respondWithOpenApiDocument } from './routes/respond-with-openapi-document.js';
24
- /**
25
- * Record which operation a request matched, so an error escaping it can be named and `onResponse`
26
- * receives the operation object itself.
27
- */
28
- const setMockedOperation = (c, mockedOperation, operation) => {
29
- ;
30
- c.set('mockedOperation', mockedOperation);
31
- c.set('matchedOperation', operation);
32
- };
33
- /** Read back the operation a request matched, or `undefined` when it reached no mocked route */
34
- const getMockedOperation = (c) => c.get('mockedOperation');
35
- /** Read back the operation object a request matched, or `undefined` when it reached no mocked route */
36
- const getMatchedOperation = (c) => c.get('matchedOperation');
37
25
  /**
38
26
  * Make `response` the response of the request, keeping only the headers that were staged before the
39
27
  * request was handled — the CORS headers — where `response` does not set them itself.
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/libs/store.ts"],"names":[],"mappings":"AAMA,qBAAa,KAAK;IAChB,OAAO,CAAC,IAAI,CAAgB;IAE5B;;OAEG;IACH,IAAI,CAAC,UAAU,EAAE,MAAM,GAAG,GAAG,EAAE;IAK/B;;OAEG;IACH,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,GAAG,GAAG,SAAS;IAIpD;;;OAGG;IACH,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,GAAG,GAAG;IAe1C;;;OAGG;IACH,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,GAAG,GAAG,GAAG,IAAI;IAa7D;;;OAGG;IACH,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI;IAUtD;;OAEG;IACH,KAAK,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI;CAOjC;AAED;;GAEG;AACH,eAAO,MAAM,KAAK,OAAc,CAAA"}
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/libs/store.ts"],"names":[],"mappings":"AAMA,qBAAa,KAAK;IAEhB,OAAO,CAAC,IAAI,CAAiC;IAE7C;;OAEG;IACH,IAAI,CAAC,UAAU,EAAE,MAAM,GAAG,GAAG,EAAE;IAK/B;;OAEG;IACH,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,GAAG,GAAG,SAAS;IAIpD;;;OAGG;IACH,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,GAAG,GAAG;IAc1C;;;OAGG;IACH,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,GAAG,GAAG,GAAG,IAAI;IAc7D;;;OAGG;IACH,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI;IAWtD;;OAEG;IACH,KAAK,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI;CAOjC;AAED;;GAEG;AACH,eAAO,MAAM,KAAK,OAAc,CAAA"}
@@ -1,5 +1,6 @@
1
1
  export class Store {
2
- data = {};
2
+ // Collection names and item IDs come from guest code, so neither lookup may inherit host properties.
3
+ data = Object.create(null);
3
4
  /**
4
5
  * Get all items in a collection.
5
6
  */
@@ -18,14 +19,13 @@ export class Store {
18
19
  * Auto-generates an ID if not provided.
19
20
  */
20
21
  create(collection, data) {
21
- if (!this.data[collection]) {
22
- this.data[collection] = {};
23
- }
22
+ const items = this.data[collection] ?? Object.create(null);
23
+ this.data[collection] = items;
24
24
  // Handle null/undefined data by defaulting to empty object
25
25
  const safeData = data ?? {};
26
26
  const id = safeData.id ?? crypto.randomUUID();
27
27
  const item = { ...safeData, id };
28
- this.data[collection][id] = item;
28
+ items[id] = item;
29
29
  return item;
30
30
  }
31
31
  /**
@@ -33,13 +33,14 @@ export class Store {
33
33
  * Returns null if the item is not found.
34
34
  */
35
35
  update(collection, id, data) {
36
- if (!this.data[collection]?.[id]) {
36
+ const items = this.data[collection];
37
+ if (!items || !(id in items)) {
37
38
  return null;
38
39
  }
39
40
  // Handle null/undefined data by defaulting to empty object
40
41
  const safeData = data ?? {};
41
- const updated = { ...this.data[collection][id], ...safeData, id };
42
- this.data[collection][id] = updated;
42
+ const updated = { ...items[id], ...safeData, id };
43
+ items[id] = updated;
43
44
  return updated;
44
45
  }
45
46
  /**
@@ -47,10 +48,11 @@ export class Store {
47
48
  * Returns null if the item is not found.
48
49
  */
49
50
  delete(collection, id) {
50
- if (!this.data[collection]?.[id]) {
51
+ const items = this.data[collection];
52
+ if (!items || !(id in items)) {
51
53
  return null;
52
54
  }
53
- delete this.data[collection][id];
55
+ delete items[id];
54
56
  return true;
55
57
  }
56
58
  /**
@@ -61,7 +63,7 @@ export class Store {
61
63
  delete this.data[collection];
62
64
  }
63
65
  else {
64
- this.data = {};
66
+ this.data = Object.create(null);
65
67
  }
66
68
  }
67
69
  }
@@ -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;AAenC;;GAEG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,WAAW,CAAC,eAAe,EAAE,cAAc,CAAC,EAAE,MAAM,YA2J1G"}
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;AA8BnC;;GAEG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,WAAW,CAAC,eAAe,EAAE,cAAc,CAAC,EAAE,MAAM,YAuK1G"}
@@ -6,6 +6,7 @@ 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 { isSettableResponseHeader } from '../utils/is-settable-response-header.js';
9
10
  import { negotiateContentType } from '../utils/negotiate-content-type.js';
10
11
  import { normalizeResponseBody } from '../utils/normalize-response-body.js';
11
12
  import { parsePreferHeader } from '../utils/parse-prefer-header.js';
@@ -13,6 +14,19 @@ import { pathParameters } from '../utils/path-parameters.js';
13
14
  import { selectResponseExample } from '../utils/select-response-example.js';
14
15
  import { serializeResponseBody } from '../utils/serialize-response-body.js';
15
16
  import { getStreamingResponse, sendStreamingResponse } from '../utils/streaming-response.js';
17
+ /** These fields are owned by the response serializer and transport, never the API description. */
18
+ const IGNORED_RESPONSE_HEADERS = new Set([
19
+ 'content-length',
20
+ 'content-encoding',
21
+ 'content-type',
22
+ 'transfer-encoding',
23
+ 'trailer',
24
+ 'connection',
25
+ 'keep-alive',
26
+ 'upgrade',
27
+ 'te',
28
+ 'proxy-connection',
29
+ ]);
16
30
  /**
17
31
  * Mock any response
18
32
  */
@@ -38,16 +52,29 @@ export function mockAnyResponse(c, operation, openapiVersion) {
38
52
  // Headers
39
53
  const headers = selectedResponse?.headers ?? {};
40
54
  Object.keys(headers).forEach((header) => {
55
+ // The body and transport determine these headers. Generated values can truncate a response or
56
+ // make clients decode uncompressed data; OpenAPI also requires ignoring declared Content-Type.
57
+ if (IGNORED_RESPONSE_HEADERS.has(header.toLowerCase())) {
58
+ return;
59
+ }
41
60
  const headerObject = getResolvedRef(headers[header]);
42
61
  // Headers use the generator defaults to preserve their declared values.
43
- const value = headerObject?.schema
44
- ? getExampleFromSchema(getResolvedRefDeep(headerObject.schema))
45
- : null;
62
+ const value = headerObject?.schema ? getExampleFromSchema(getResolvedRefDeep(headerObject.schema)) : null;
46
63
  // Loose check on purpose: Hono *deletes* a header when handed `undefined`. This loop is the first
47
64
  // thing to set the declared headers, so in practice a delete removes a header set earlier by
48
65
  // middleware — `cors()` sets `Access-Control-Allow-Origin` before the handler runs.
49
66
  if (value != null) {
50
- c.header(header, value);
67
+ try {
68
+ const text = String(value);
69
+ if (isSettableResponseHeader(header, text)) {
70
+ c.header(header, text);
71
+ return;
72
+ }
73
+ }
74
+ catch {
75
+ // An authored object can also shadow toString and prevent string conversion.
76
+ }
77
+ console.warn(`Skipping invalid response header ${JSON.stringify(header)} from the API description.`);
51
78
  }
52
79
  });
53
80
  // For 204 No Content responses, we should not set Content-Type and should return null body
@@ -85,9 +112,8 @@ export function mockAnyResponse(c, operation, openapiVersion) {
85
112
  generate: generateFromSchema,
86
113
  });
87
114
  c.status(statusCode);
88
- // `streamSSE` sets the transport headers itself (`Content-Type`, `Cache-Control`, `Connection`,
89
- // `Transfer-Encoding`), so those win over a value the document declared for the same header —
90
- // they are what makes the stream readable. Every other declared header set above survives.
115
+ // Transport headers are never copied from the API description. `streamSSE` adds the framing
116
+ // and cache policy needed for an event stream; ordinary custom headers survive.
91
117
  return streamSSE(c, async (stream) => {
92
118
  for (const event of events) {
93
119
  if (event.framed) {
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Remove `readOnly` properties from `required` throughout a request body schema.
3
+ *
4
+ * OpenAPI only enforces `required` for a `readOnly` property on responses, so a client creating a
5
+ * resource must be able to leave out server-assigned fields such as `id` or `createdAt`.
6
+ */
7
+ export declare const dropReadOnlyRequired: (schema: unknown, readOnlyNames?: ReadonlySet<string>) => unknown;
8
+ //# sourceMappingURL=drop-read-only-required.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drop-read-only-required.d.ts","sourceRoot":"","sources":["../../src/utils/drop-read-only-required.ts"],"names":[],"mappings":"AAqCA;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,GAAI,QAAQ,OAAO,EAAE,gBAAe,WAAW,CAAC,MAAM,CAAa,KAAG,OAyCtG,CAAA"}
@@ -0,0 +1,72 @@
1
+ import { isObject } from '@scalar/helpers/object/is-object';
2
+ /** Keywords whose subschemas describe the same instance, so a read-only property declared beside them still applies */
3
+ const SAME_INSTANCE_KEYWORDS = new Set(['allOf', 'anyOf', 'oneOf', 'then', 'else']);
4
+ /** Keywords whose subschemas describe a different instance (an item, a property value, …) */
5
+ const NESTED_INSTANCE_KEYWORDS = new Set([
6
+ 'additionalItems',
7
+ 'additionalProperties',
8
+ 'contains',
9
+ 'items',
10
+ 'prefixItems',
11
+ 'unevaluatedItems',
12
+ 'unevaluatedProperties',
13
+ ]);
14
+ /** Keywords whose value maps author-chosen names to schemas */
15
+ const SCHEMA_MAP_KEYWORDS = new Set(['$defs', 'definitions', 'dependentSchemas', 'patternProperties', 'properties']);
16
+ /** Only unconditional annotations apply when a property is omitted, so union and conditional branches are excluded. */
17
+ const isReadOnlyProperty = (schema) => isObject(schema) &&
18
+ (schema.readOnly === true || (Array.isArray(schema.allOf) && schema.allOf.some(isReadOnlyProperty)));
19
+ /** Names of the properties a schema, or any `allOf` member of it, marks as `readOnly` */
20
+ const getReadOnlyPropertyNames = (schema) => {
21
+ const own = isObject(schema.properties)
22
+ ? Object.entries(schema.properties)
23
+ .filter(([, property]) => isReadOnlyProperty(property))
24
+ .map(([name]) => name)
25
+ : [];
26
+ const inherited = Array.isArray(schema.allOf)
27
+ ? schema.allOf.filter(isObject).flatMap((member) => getReadOnlyPropertyNames(member))
28
+ : [];
29
+ return [...own, ...inherited];
30
+ };
31
+ /**
32
+ * Remove `readOnly` properties from `required` throughout a request body schema.
33
+ *
34
+ * OpenAPI only enforces `required` for a `readOnly` property on responses, so a client creating a
35
+ * resource must be able to leave out server-assigned fields such as `id` or `createdAt`.
36
+ */
37
+ export const dropReadOnlyRequired = (schema, readOnlyNames = new Set()) => {
38
+ if (Array.isArray(schema)) {
39
+ return schema.map((item) => dropReadOnlyRequired(item));
40
+ }
41
+ if (!isObject(schema)) {
42
+ return schema;
43
+ }
44
+ const names = new Set([...readOnlyNames, ...getReadOnlyPropertyNames(schema)]);
45
+ return Object.fromEntries(Object.entries(schema).map(([keyword, value]) => {
46
+ // These schemas test predicates rather than require fields in the request.
47
+ // Relaxing them could select a different branch or make a negation reject a valid body.
48
+ if (keyword === 'if' || keyword === 'not') {
49
+ return [keyword, value];
50
+ }
51
+ if (keyword === 'required' && Array.isArray(value)) {
52
+ return [keyword, value.filter((name) => !names.has(name))];
53
+ }
54
+ if (SAME_INSTANCE_KEYWORDS.has(keyword)) {
55
+ const relax = (member) => dropReadOnlyRequired(member, names);
56
+ return [keyword, Array.isArray(value) ? value.map(relax) : relax(value)];
57
+ }
58
+ if (NESTED_INSTANCE_KEYWORDS.has(keyword)) {
59
+ return [keyword, dropReadOnlyRequired(value)];
60
+ }
61
+ if (SCHEMA_MAP_KEYWORDS.has(keyword) && isObject(value)) {
62
+ return [
63
+ keyword,
64
+ Object.fromEntries(Object.entries(value).map(([name, member]) => [
65
+ name,
66
+ dropReadOnlyRequired(member, keyword === 'dependentSchemas' ? names : undefined),
67
+ ])),
68
+ ];
69
+ }
70
+ return [keyword, value];
71
+ }));
72
+ };
@@ -1,5 +1,14 @@
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>;
3
12
  /**
4
13
  * Convert an OpenAPI path key into the segments of a Hono route, one entry per `/`-separated segment
5
14
  * of the path portion of the key.
@@ -14,12 +23,11 @@ export declare const honoRouteSegmentsFromPath: (path: string) => string[];
14
23
  *
15
24
  * Example: `/posts/{id}` → `/posts/:id`
16
25
  *
17
- * A segment whose literal text would be read as routing syntax is registered as a single parameter
18
- * with an explicit pattern instead, because Hono allows only one parameter per segment and that is
19
- * the only way to make it match such a segment verbatim. The request then routes to the right
20
- * operation, but the path parameters of that one segment are no longer bound by name: they surface
21
- * as the synthesized parameter, and a required path parameter in it reads as missing to request
22
- * 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.
23
31
  *
24
32
  * A query string in the key (`/v1/messages?beta=true`) is dropped here — it is matched against the
25
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;;;;;;;GAOG;AACH,eAAO,MAAM,yBAAyB,GAAI,MAAM,MAAM,KAAG,MAAM,EAiC9D,CAAA;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,iBAAiB,GAAI,MAAM,MAAM,KAAG,MAAmD,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,11 +57,50 @@ 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
  };
67
+ /**
68
+ * Whether a segment mixes a template with literal text, as in `{id}.json` or `v{version}`.
69
+ *
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.
86
+ *
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
+ };
59
104
  /**
60
105
  * Convert an OpenAPI path key into the segments of a Hono route, one entry per `/`-separated segment
61
106
  * of the path portion of the key.
@@ -69,6 +114,14 @@ export const honoRouteSegmentsFromPath = (path) => {
69
114
  const route = [];
70
115
  let literalIndex = 0;
71
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
+ };
72
125
  for (const segment of pathname.split('/')) {
73
126
  // Check the literal text and the parameter names, but not the braces around them — the `:` we
74
127
  // generate for a template is meant to be routing syntax, a `?` in a parameter name is not.
@@ -80,9 +133,10 @@ export const honoRouteSegmentsFromPath = (path) => {
80
133
  // the router throw on every request. An empty segment (a trailing slash, or `//`) is exempt:
81
134
  // Hono skips the lookahead for it, and it has no literal text to turn into a pattern.
82
135
  const needsPattern = HONO_ROUTING_CHARACTERS.test(routeText) ||
136
+ hasEmbeddedTemplate(segment) ||
83
137
  (previousIsPattern && plainSegment !== '' && !plainSegment.startsWith(':'));
84
138
  if (needsPattern) {
85
- route.push(`:${LITERAL_PARAMETER_PREFIX}${literalIndex++}{${patternFromSegment(segment)}}`);
139
+ route.push(`:${nextSyntheticName()}{${patternFromSegment(segment)}}`);
86
140
  }
87
141
  else {
88
142
  route.push(plainSegment);
@@ -96,12 +150,11 @@ export const honoRouteSegmentsFromPath = (path) => {
96
150
  *
97
151
  * Example: `/posts/{id}` → `/posts/:id`
98
152
  *
99
- * A segment whose literal text would be read as routing syntax is registered as a single parameter
100
- * with an explicit pattern instead, because Hono allows only one parameter per segment and that is
101
- * the only way to make it match such a segment verbatim. The request then routes to the right
102
- * operation, but the path parameters of that one segment are no longer bound by name: they surface
103
- * as the synthesized parameter, and a required path parameter in it reads as missing to request
104
- * validation. Hono cannot express both at once, and matching the wrong operation is worse.
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.
105
158
  *
106
159
  * A query string in the key (`/v1/messages?beta=true`) is dropped here — it is matched against the
107
160
  * incoming request separately, see `splitPathKey`.
@@ -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
  };
@@ -1 +1 @@
1
- {"version":3,"file":"path-specificity.d.ts","sourceRoot":"","sources":["../../src/utils/path-specificity.ts"],"names":[],"mappings":"AAGA;;;;;;GAMG;AACH,KAAK,kBAAkB,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;AA8BnC;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB,GAAI,SAAS,MAAM,KAAG,SAAS,kBAAkB,EAK/E,CAAA;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,sBAAsB,GACjC,MAAM,SAAS,kBAAkB,EAAE,EACnC,OAAO,SAAS,kBAAkB,EAAE,KACnC,MAUF,CAAA"}
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"}
@@ -1,26 +1,16 @@
1
- import { LITERAL_PARAMETER_PREFIX, honoRouteSegmentsFromPath } from './hono-route-from-path.js';
2
1
  import { PATH_KEY_TEMPLATE, splitPathKey } from './split-path-key.js';
3
- /** Matches a segment the route compiler turned into a parameter with an explicit pattern. */
4
- const PATTERN_SEGMENT = new RegExp(`^:${LITERAL_PARAMETER_PREFIX}\\d+\\{`);
5
2
  /**
6
- * Rank one segment of a path key, given the Hono route segment it compiles to.
3
+ * Rank one segment of a path key.
7
4
  *
8
- * A segment that mixes a template with literal text ranks between the two, as long as the router
9
- * actually enforces that literal text. Not every mixed segment compiles that way: `{name}.json`
10
- * becomes the whole-segment parameter `:name.json`, which Hono matches against any value. Such a
11
- * segment ranks like a bare template, because ranking it higher would let it answer requests meant
12
- * for a plain `{id}` sibling that the document may well have declared first.
5
+ * A segment that mixes a template with literal text ranks between the two, because the router
6
+ * enforces its literal text (see `honoRouteFromPath`).
13
7
  */
14
- const segmentSpecificity = (segment, routeSegment) => {
8
+ const segmentSpecificity = (segment) => {
15
9
  const literalText = segment.replace(PATH_KEY_TEMPLATE, '');
16
10
  if (literalText === segment) {
17
11
  return 0;
18
12
  }
19
- if (literalText === '') {
20
- return 2;
21
- }
22
- const matchesAnyValue = routeSegment.startsWith(':') && !PATTERN_SEGMENT.test(routeSegment);
23
- return matchesAnyValue ? 2 : 1;
13
+ return literalText === '' ? 2 : 1;
24
14
  };
25
15
  /**
26
16
  * Describe how specific a path key is, one rank per `/`-separated segment of its path portion.
@@ -30,8 +20,7 @@ const segmentSpecificity = (segment, routeSegment) => {
30
20
  */
31
21
  export const getPathSpecificity = (pathKey) => {
32
22
  const { path: pathname } = splitPathKey(pathKey);
33
- const routeSegments = honoRouteSegmentsFromPath(pathname);
34
- return pathname.split('/').map((segment, index) => segmentSpecificity(segment, routeSegments[index] ?? ''));
23
+ return pathname.split('/').map((segment) => segmentSpecificity(segment));
35
24
  };
36
25
  /**
37
26
  * Order two paths so the more concrete one is matched first, as the OpenAPI Paths Object asks:
@@ -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.21.0",
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.17.0",
56
- "@scalar/json-magic": "0.18.0",
57
- "@scalar/openapi-types": "0.9.8",
58
- "@scalar/openapi-upgrader": "0.4.7",
59
- "@scalar/types": "0.27.0",
60
- "@scalar/workspace-store": "0.70.0",
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",