@fuzdev/fuz_app 0.163.0 → 0.164.0

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 (181) hide show
  1. package/README.md +2 -1
  2. package/dist/actions/action_event_data.d.ts +1 -1
  3. package/dist/actions/action_rpc.d.ts.map +1 -1
  4. package/dist/actions/action_rpc.js +4 -0
  5. package/dist/actions/action_spec.d.ts +3 -3
  6. package/dist/actions/action_spec.d.ts.map +1 -1
  7. package/dist/auth/CLAUDE.md +1 -1
  8. package/dist/auth/account_route_schema.d.ts +3 -27
  9. package/dist/auth/account_route_schema.d.ts.map +1 -1
  10. package/dist/auth/account_route_schema.js +6 -20
  11. package/dist/auth/admin_action_specs.d.ts +56 -56
  12. package/dist/auth/audit_log_route_schema.d.ts +1 -1
  13. package/dist/auth/audit_log_route_schema.d.ts.map +1 -1
  14. package/dist/auth/audit_log_route_schema.js +4 -5
  15. package/dist/auth/audit_log_schema.d.ts +18 -18
  16. package/dist/auth/bootstrap_route_schema.d.ts +1 -30
  17. package/dist/auth/bootstrap_route_schema.d.ts.map +1 -1
  18. package/dist/auth/bootstrap_route_schema.js +3 -8
  19. package/dist/auth/daemon_token.d.ts +4 -4
  20. package/dist/auth/daemon_token.d.ts.map +1 -1
  21. package/dist/auth/daemon_token.js +3 -3
  22. package/dist/auth/daemon_token_middleware.d.ts +1 -1
  23. package/dist/auth/daemon_token_middleware.d.ts.map +1 -1
  24. package/dist/auth/daemon_token_middleware.js +5 -5
  25. package/dist/auth/middleware.js +4 -4
  26. package/dist/auth/role_grant_offer_action_specs.d.ts +2 -2
  27. package/dist/auth/signup_route_schema.d.ts.map +1 -1
  28. package/dist/auth/signup_route_schema.js +3 -7
  29. package/dist/db/CLAUDE.md +2 -1
  30. package/dist/db/file_fact_url.d.ts +11 -6
  31. package/dist/db/file_fact_url.d.ts.map +1 -1
  32. package/dist/db/file_fact_url.js +5 -5
  33. package/dist/db/schema_ready.d.ts +0 -5
  34. package/dist/db/schema_ready.d.ts.map +1 -1
  35. package/dist/db/schema_ready.js +0 -5
  36. package/dist/http/CLAUDE.md +104 -71
  37. package/dist/http/auth_shape.d.ts +48 -29
  38. package/dist/http/auth_shape.d.ts.map +1 -1
  39. package/dist/http/auth_shape.js +12 -85
  40. package/dist/http/body_limit.d.ts +12 -0
  41. package/dist/http/body_limit.d.ts.map +1 -1
  42. package/dist/http/body_limit.js +15 -0
  43. package/dist/http/body_limit_schema.d.ts +20 -0
  44. package/dist/http/body_limit_schema.d.ts.map +1 -0
  45. package/dist/http/body_limit_schema.js +20 -0
  46. package/dist/http/common_routes.d.ts +1 -1
  47. package/dist/http/common_routes.d.ts.map +1 -1
  48. package/dist/http/common_routes.js +11 -14
  49. package/dist/http/db_routes.d.ts.map +1 -1
  50. package/dist/http/db_routes.js +59 -69
  51. package/dist/http/dev_route_error_check.d.ts +70 -0
  52. package/dist/http/dev_route_error_check.d.ts.map +1 -0
  53. package/dist/http/dev_route_error_check.js +119 -0
  54. package/dist/http/error_schemas.d.ts +365 -189
  55. package/dist/http/error_schemas.d.ts.map +1 -1
  56. package/dist/http/error_schemas.js +256 -149
  57. package/dist/http/health_schema.d.ts +10 -6
  58. package/dist/http/health_schema.d.ts.map +1 -1
  59. package/dist/http/health_schema.js +3 -3
  60. package/dist/http/middleware_spec.d.ts +8 -3
  61. package/dist/http/middleware_spec.d.ts.map +1 -1
  62. package/dist/http/origin.d.ts +12 -43
  63. package/dist/http/origin.d.ts.map +1 -1
  64. package/dist/http/origin.js +10 -6
  65. package/dist/http/route_error_check.d.ts +158 -0
  66. package/dist/http/route_error_check.d.ts.map +1 -0
  67. package/dist/http/route_error_check.js +247 -0
  68. package/dist/http/route_errors.d.ts +80 -0
  69. package/dist/http/route_errors.d.ts.map +1 -0
  70. package/dist/http/route_errors.js +83 -0
  71. package/dist/http/route_spec.d.ts +33 -17
  72. package/dist/http/route_spec.d.ts.map +1 -1
  73. package/dist/http/route_spec.js +48 -62
  74. package/dist/http/schema_helpers.d.ts +0 -33
  75. package/dist/http/schema_helpers.d.ts.map +1 -1
  76. package/dist/http/schema_helpers.js +0 -45
  77. package/dist/http/surface.d.ts +19 -12
  78. package/dist/http/surface.d.ts.map +1 -1
  79. package/dist/http/surface.js +25 -38
  80. package/dist/http/surface_query.d.ts +11 -2
  81. package/dist/http/surface_query.d.ts.map +1 -1
  82. package/dist/http/surface_query.js +7 -1
  83. package/dist/primitive_schemas_fuz.d.ts +17 -3
  84. package/dist/primitive_schemas_fuz.d.ts.map +1 -1
  85. package/dist/primitive_schemas_fuz.js +13 -3
  86. package/dist/rate_limiter.d.ts +13 -0
  87. package/dist/rate_limiter.d.ts.map +1 -1
  88. package/dist/rate_limiter.js +20 -2
  89. package/dist/schema_issues.d.ts +29 -11
  90. package/dist/schema_issues.d.ts.map +1 -1
  91. package/dist/schema_issues.js +11 -10
  92. package/dist/schema_meta.d.ts +8 -1
  93. package/dist/schema_meta.d.ts.map +1 -1
  94. package/dist/schema_meta.js +2 -1
  95. package/dist/server/app_server.d.ts +3 -1
  96. package/dist/server/app_server.d.ts.map +1 -1
  97. package/dist/server/app_server.js +24 -10
  98. package/dist/server/serve_fact_route.d.ts.map +1 -1
  99. package/dist/server/serve_fact_route.js +8 -31
  100. package/dist/server/surface_route.d.ts.map +1 -1
  101. package/dist/server/surface_route.js +5 -6
  102. package/dist/server/x_accel.d.ts +12 -7
  103. package/dist/server/x_accel.d.ts.map +1 -1
  104. package/dist/server/x_accel.js +7 -9
  105. package/dist/testing/CLAUDE.md +33 -39
  106. package/dist/testing/admin_integration.js +1 -1
  107. package/dist/testing/adversarial_404.d.ts +4 -18
  108. package/dist/testing/adversarial_404.d.ts.map +1 -1
  109. package/dist/testing/adversarial_404.js +19 -51
  110. package/dist/testing/adversarial_headers.d.ts +3 -4
  111. package/dist/testing/adversarial_headers.d.ts.map +1 -1
  112. package/dist/testing/adversarial_headers.js +8 -6
  113. package/dist/testing/adversarial_input.d.ts.map +1 -1
  114. package/dist/testing/adversarial_input.js +18 -17
  115. package/dist/testing/assertions.d.ts +33 -11
  116. package/dist/testing/assertions.d.ts.map +1 -1
  117. package/dist/testing/assertions.js +52 -12
  118. package/dist/testing/attack_surface.d.ts +5 -35
  119. package/dist/testing/attack_surface.d.ts.map +1 -1
  120. package/dist/testing/attack_surface.js +29 -91
  121. package/dist/testing/auth_apps.d.ts.map +1 -1
  122. package/dist/testing/auth_apps.js +2 -1
  123. package/dist/testing/cross_backend/action_manifest.d.ts +126 -56
  124. package/dist/testing/cross_backend/action_manifest.d.ts.map +1 -1
  125. package/dist/testing/cross_backend/action_manifest.js +11 -11
  126. package/dist/testing/cross_backend/action_manifest_parity.d.ts +1 -1
  127. package/dist/testing/cross_backend/action_manifest_parity.d.ts.map +1 -1
  128. package/dist/testing/cross_backend/cell_crud.d.ts.map +1 -1
  129. package/dist/testing/cross_backend/cell_crud.js +2 -1
  130. package/dist/testing/cross_backend/conformance_table.js +1 -1
  131. package/dist/testing/cross_backend/fact_serving.js +3 -3
  132. package/dist/testing/cross_backend/origin_conformance.d.ts +278 -102
  133. package/dist/testing/cross_backend/origin_conformance.d.ts.map +1 -1
  134. package/dist/testing/cross_backend/origin_conformance.js +21 -21
  135. package/dist/testing/cross_backend/rust_spine_consumer_surface.d.ts.map +1 -1
  136. package/dist/testing/cross_backend/rust_spine_consumer_surface.js +7 -1
  137. package/dist/testing/cross_backend/setup.d.ts +13 -0
  138. package/dist/testing/cross_backend/setup.d.ts.map +1 -1
  139. package/dist/testing/cross_backend/setup.js +24 -7
  140. package/dist/testing/cross_backend/testing_origin_check.d.ts +147 -71
  141. package/dist/testing/cross_backend/testing_origin_check.d.ts.map +1 -1
  142. package/dist/testing/cross_backend/testing_origin_check.js +16 -13
  143. package/dist/testing/cross_backend/testing_reset_actions.d.ts +70 -27
  144. package/dist/testing/cross_backend/testing_reset_actions.d.ts.map +1 -1
  145. package/dist/testing/data_exposure.d.ts.map +1 -1
  146. package/dist/testing/data_exposure.js +5 -4
  147. package/dist/testing/error_coverage.d.ts +24 -34
  148. package/dist/testing/error_coverage.d.ts.map +1 -1
  149. package/dist/testing/error_coverage.js +46 -89
  150. package/dist/testing/integration.d.ts.map +1 -1
  151. package/dist/testing/integration.js +5 -13
  152. package/dist/testing/integration_helpers.d.ts +37 -9
  153. package/dist/testing/integration_helpers.d.ts.map +1 -1
  154. package/dist/testing/integration_helpers.js +86 -40
  155. package/dist/testing/middleware.d.ts +3 -5
  156. package/dist/testing/middleware.d.ts.map +1 -1
  157. package/dist/testing/middleware.js +5 -4
  158. package/dist/testing/rate_limiting.d.ts +1 -1
  159. package/dist/testing/rate_limiting.d.ts.map +1 -1
  160. package/dist/testing/rate_limiting.js +5 -4
  161. package/dist/testing/round_trip.d.ts.map +1 -1
  162. package/dist/testing/round_trip.js +5 -3
  163. package/dist/testing/schema_generators.d.ts +10 -3
  164. package/dist/testing/schema_generators.d.ts.map +1 -1
  165. package/dist/testing/schema_generators.js +23 -11
  166. package/dist/testing/stubs.d.ts +10 -1
  167. package/dist/testing/stubs.d.ts.map +1 -1
  168. package/dist/testing/stubs.js +15 -5
  169. package/dist/testing/surface_invariants.d.ts +36 -115
  170. package/dist/testing/surface_invariants.d.ts.map +1 -1
  171. package/dist/testing/surface_invariants.js +106 -269
  172. package/dist/ui/CLAUDE.md +4 -2
  173. package/dist/ui/auth_state.svelte.d.ts.map +1 -1
  174. package/dist/ui/auth_state.svelte.js +2 -8
  175. package/dist/ui/backend_probe.svelte.js +3 -3
  176. package/dist/ui/table_state.svelte.d.ts.map +1 -1
  177. package/dist/ui/table_state.svelte.js +1 -8
  178. package/dist/ui/ui_fetch.d.ts +12 -2
  179. package/dist/ui/ui_fetch.d.ts.map +1 -1
  180. package/dist/ui/ui_fetch.js +22 -4
  181. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"body_limit.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/http/body_limit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgEG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAQ9C;;;;;;;GAOG;AACH,eAAO,MAAM,4BAA4B,GAAI,UAAU,MAAM,KAAG,iBA6B/D,CAAC"}
1
+ {"version":3,"file":"body_limit.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/http/body_limit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgEG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAI9C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAM3D;;;;;;;GAOG;AACH,eAAO,MAAM,4BAA4B,GAAI,UAAU,MAAM,KAAG,iBA6B/D,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,iCAAiC,GAAI,UAAU,MAAM,KAAG,cAGnE,CAAC"}
@@ -65,6 +65,7 @@
65
65
  */
66
66
  import { bodyLimit } from 'hono/body-limit';
67
67
  import { ERROR_INVALID_CONTENT_LENGTH, ERROR_PAYLOAD_TOO_LARGE } from './error_schemas.js';
68
+ import { body_limit_middleware_shape } from './body_limit_schema.js';
68
69
  /** A well-formed `Content-Length` value: one or more ASCII digits and nothing else. */
69
70
  const CONTENT_LENGTH_DIGITS = /^[0-9]+$/;
70
71
  /**
@@ -103,3 +104,17 @@ export const create_body_limit_middleware = (max_size) => {
103
104
  return streaming_limit(c, next);
104
105
  };
105
106
  };
107
+ /**
108
+ * Create the body size limit as a middleware spec — `body_limit_middleware_shape`
109
+ * at `'*'` with its handler — which `create_app_server` mounts ahead of the
110
+ * other middleware, so every route's error map carries the limit's `413` and
111
+ * `400`.
112
+ *
113
+ * @param max_size - the largest accepted body, in bytes; a safe integer, `0` or more
114
+ * @returns the spec, its handler `create_body_limit_middleware(max_size)`
115
+ * @throws Error when `max_size` is not a safe integer `0` or more
116
+ */
117
+ export const create_body_limit_middleware_spec = (max_size) => ({
118
+ ...body_limit_middleware_shape,
119
+ handler: create_body_limit_middleware(max_size)
120
+ });
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The body size limit's middleware shape minus its handler — hono-free data,
3
+ * so the surface builders that never mount the limit (`testing/stubs.ts`)
4
+ * declare it without importing `hono/body-limit`.
5
+ *
6
+ * @module
7
+ */
8
+ /**
9
+ * The body limit's middleware spec minus its handler: at `'*'`, ahead of the
10
+ * other middleware, answering `413` `payload_too_large` past the cap and
11
+ * `400` `invalid_content_length` to a `Content-Length` it cannot read.
12
+ * `create_body_limit_middleware_spec` (`http/body_limit.ts`) spreads it and
13
+ * attaches the live handler.
14
+ */
15
+ export declare const body_limit_middleware_shape: {
16
+ readonly name: "body_limit";
17
+ readonly path: "*";
18
+ readonly errors: readonly [import("./error_schemas.js").RestErrorDef<413, "payload_too_large", Record<never, never>>, import("./error_schemas.js").RestErrorDef<400, "invalid_content_length", Record<never, never>>];
19
+ };
20
+ //# sourceMappingURL=body_limit_schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"body_limit_schema.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/http/body_limit_schema.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH;;;;;;GAMG;AACH,eAAO,MAAM,2BAA2B;;;;CAIY,CAAC"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The body size limit's middleware shape minus its handler — hono-free data,
3
+ * so the surface builders that never mount the limit (`testing/stubs.ts`)
4
+ * declare it without importing `hono/body-limit`.
5
+ *
6
+ * @module
7
+ */
8
+ import { REST_INVALID_CONTENT_LENGTH, REST_PAYLOAD_TOO_LARGE } from './error_schemas.js';
9
+ /**
10
+ * The body limit's middleware spec minus its handler: at `'*'`, ahead of the
11
+ * other middleware, answering `413` `payload_too_large` past the cap and
12
+ * `400` `invalid_content_length` to a `Content-Length` it cannot read.
13
+ * `create_body_limit_middleware_spec` (`http/body_limit.ts`) spreads it and
14
+ * attaches the live handler.
15
+ */
16
+ export const body_limit_middleware_shape = {
17
+ name: 'body_limit',
18
+ path: '*',
19
+ errors: [REST_PAYLOAD_TOO_LARGE, REST_INVALID_CONTENT_LENGTH]
20
+ };
@@ -67,7 +67,7 @@ export declare const create_ready_route_spec: (options: ReadyRouteOptions) => Ro
67
67
  export interface ServerStatusOptions {
68
68
  /** Application version string. */
69
69
  version: string;
70
- /** Returns milliseconds since server start. */
70
+ /** Returns whole milliseconds since server start, which the route's output requires. */
71
71
  get_uptime_ms: () => number;
72
72
  }
73
73
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"common_routes.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/http/common_routes.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAKH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AAEtD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEjD,OAAO,EAIN,KAAK,cAAc,EACnB,MAAM,uBAAuB,CAAC;AAE/B;;;;;GAKG;AACH,eAAO,MAAM,wBAAwB,QAAO,SAQ1C,CAAC;AAKH;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,oBAAoB,GAAI,KAAK,GAAG,GAAG,MAAM,KAAG,cAkBxD,CAAC;AAEF,6CAA6C;AAC7C,MAAM,WAAW,iBAAiB;IACjC;;;;OAIG;IACH,QAAQ,EAAE,cAAc,CAAC;IACzB,gFAAgF;IAChF,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,uBAAuB,GAAI,SAAS,iBAAiB,KAAG,SAoCpE,CAAC;AAEF,yDAAyD;AACzD,MAAM,WAAW,mBAAmB;IACnC,kCAAkC;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,+CAA+C;IAC/C,aAAa,EAAE,MAAM,MAAM,CAAC;CAC5B;AAED;;;;;GAKG;AACH,eAAO,MAAM,+BAA+B,GAAI,SAAS,mBAAmB,KAAG,SAQ7E,CAAC"}
1
+ {"version":3,"file":"common_routes.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/http/common_routes.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAcH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AAEtD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAQjD,OAAO,EAGN,KAAK,cAAc,EACnB,MAAM,uBAAuB,CAAC;AAE/B;;;;;GAKG;AACH,eAAO,MAAM,wBAAwB,QAAO,SAQ1C,CAAC;AAKH;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,oBAAoB,GAAI,KAAK,GAAG,GAAG,MAAM,KAAG,cAkBxD,CAAC;AAEF,6CAA6C;AAC7C,MAAM,WAAW,iBAAiB;IACjC;;;;OAIG;IACH,QAAQ,EAAE,cAAc,CAAC;IACzB,gFAAgF;IAChF,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,uBAAuB,GAAI,SAAS,iBAAiB,KAAG,SAgCpE,CAAC;AAEF,yDAAyD;AACzD,MAAM,WAAW,mBAAmB;IACnC,kCAAkC;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,wFAAwF;IACxF,aAAa,EAAE,MAAM,MAAM,CAAC;CAC5B;AAED;;;;;GAKG;AACH,eAAO,MAAM,+BAA+B,GAAI,SAAS,mBAAmB,KAAG,SAQ7E,CAAC"}
@@ -7,9 +7,10 @@
7
7
  * @module
8
8
  */
9
9
  import { readFileSync } from 'node:fs';
10
- import { z } from 'zod';
10
+ import { integer, literal, loose_object, min_value, number, object, pipe, string } from '@fuzdev/fuz_schema/schema.ts';
11
11
  import { HEALTH_PATH, HealthResponse } from './health_schema.js';
12
- import { check_schema_drift, format_schema_drift, READY_ERROR } from '../db/schema_ready.js';
12
+ import { ERROR_DB_UNREACHABLE, ERROR_SCHEMA_DRIFT, REST_DB_UNREACHABLE, REST_SCHEMA_DRIFT } from './error_schemas.js';
13
+ import { check_schema_drift, format_schema_drift } from '../db/schema_ready.js';
13
14
  /**
14
15
  * Create a public health check route spec.
15
16
  *
@@ -22,7 +23,7 @@ export const create_health_route_spec = () => ({
22
23
  auth: { account: 'none', actor: 'none' },
23
24
  handler: (c) => c.json({ status: 'ok' }),
24
25
  description: 'Health check',
25
- input: z.null(),
26
+ input: literal(null),
26
27
  output: HealthResponse
27
28
  });
28
29
  /** Module-level cache of loaded expected-schema fixtures, keyed by URL. */
@@ -91,13 +92,9 @@ export const create_ready_route_spec = (options) => {
91
92
  path: '/ready',
92
93
  auth: { account: 'none', actor: 'none' },
93
94
  description: 'Readiness probe — verifies the live DB schema matches the expected column map',
94
- input: z.null(),
95
- output: z.strictObject({ ready: z.literal(true) }),
96
- errors: {
97
- 503: z.strictObject({
98
- error: z.enum([READY_ERROR.schema_drift, READY_ERROR.db_unreachable])
99
- })
100
- },
95
+ input: literal(null),
96
+ output: object({ ready: literal(true) }),
97
+ errors: [REST_SCHEMA_DRIFT, REST_DB_UNREACHABLE],
101
98
  handler: async (c, route) => {
102
99
  try {
103
100
  const drift = await check_schema_drift(route.db, options.expected);
@@ -106,11 +103,11 @@ export const create_ready_route_spec = (options) => {
106
103
  // Detailed drift goes to the server log only — the public body stays a
107
104
  // minimal error code so the endpoint doesn't leak schema structure.
108
105
  options.log?.error(`[ready] schema drift detected:\n${format_schema_drift(drift)}`);
109
- return c.json({ error: READY_ERROR.schema_drift }, 503);
106
+ return c.json({ error: ERROR_SCHEMA_DRIFT }, 503);
110
107
  }
111
108
  catch (err) {
112
109
  options.log?.error('[ready] readiness check failed (db unreachable?):', err);
113
- return c.json({ error: READY_ERROR.db_unreachable }, 503);
110
+ return c.json({ error: ERROR_DB_UNREACHABLE }, 503);
114
111
  }
115
112
  }
116
113
  };
@@ -127,6 +124,6 @@ export const create_server_status_route_spec = (options) => ({
127
124
  auth: { account: 'required', actor: 'none' },
128
125
  handler: (c) => c.json({ version: options.version, uptime_ms: options.get_uptime_ms() }),
129
126
  description: 'Server version and uptime',
130
- input: z.null(),
131
- output: z.looseObject({ version: z.string(), uptime_ms: z.number() })
127
+ input: literal(null),
128
+ output: loose_object({ version: string, uptime_ms: pipe(number, integer, min_value(0)) })
132
129
  });
@@ -1 +1 @@
1
- {"version":3,"file":"db_routes.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/http/db_routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AAEtD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAGpD,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAqC,KAAK,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAiBpF;;GAEG;AACH,MAAM,WAAW,SAAS;IACzB,UAAU,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC9B,WAAW,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,UAAU;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,sDAAsD;AACtD,eAAO,MAAM,2BAA2B,MAAM,CAAC;AAC/C,sDAAsD;AACtD,eAAO,MAAM,uBAAuB,OAAO,CAAC;AAE5C;;;;;;GAMG;AACH,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,oBAAoB,EAAE,aAAa,CAAC,MAAM,CAKrD,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,oBAAoB,EAAE,aAAa,CAAC,MAAM,CAKrD,CAAC;AAEH;;;;;GAKG;AACH,MAAM,WAAW,WAAW;IAC3B;;;;;;OAMG;IACH,KAAK,EAAE;QACN,SAAS,EAAE,CAAC,KAAK,EAAE;YAClB,UAAU,EAAE,qBAAqB,CAAC;YAClC,UAAU,EAAE,IAAI,GAAG,IAAI,CAAC;YACxB,EAAE,EAAE,MAAM,CAAC;YACX,QAAQ,EAAE;gBAAE,KAAK,EAAE,MAAM,CAAC;gBAAC,SAAS,EAAE,MAAM,CAAC;gBAAC,EAAE,EAAE,MAAM,CAAA;aAAE,CAAC;SAC3D,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;KACpB,CAAC;CACF;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB;;;;;;;OAOG;IACH,gBAAgB,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IACxC,8EAA8E;IAC9E,WAAW,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,KAAK,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAC3D,+EAA+E;IAC/E,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;OAGG;IACH,oBAAoB,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;CAC7C;AA2CD;;GAEG;AACH,eAAO,MAAM,qBAAqB,GACjC,MAAM,WAAW,EACjB,SAAS,cAAc,KACrB,KAAK,CAAC,SAAS,CA+YjB,CAAC"}
1
+ {"version":3,"file":"db_routes.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/http/db_routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AAsBtD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAGpD,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAqC,KAAK,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAoBpF;;GAEG;AACH,MAAM,WAAW,SAAS;IACzB,UAAU,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC9B,WAAW,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,UAAU;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACpB;AAwCD,sDAAsD;AACtD,eAAO,MAAM,2BAA2B,MAAM,CAAC;AAC/C,sDAAsD;AACtD,eAAO,MAAM,uBAAuB,OAAO,CAAC;AAE5C;;;;;;GAMG;AACH,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,oBAAoB,EAAE,aAAa,CAAC,MAAM,CAKrD,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,oBAAoB,EAAE,aAAa,CAAC,MAAM,CAKrD,CAAC;AAEH;;;;;GAKG;AACH,MAAM,WAAW,WAAW;IAC3B;;;;;;OAMG;IACH,KAAK,EAAE;QACN,SAAS,EAAE,CAAC,KAAK,EAAE;YAClB,UAAU,EAAE,qBAAqB,CAAC;YAClC,UAAU,EAAE,IAAI,GAAG,IAAI,CAAC;YACxB,EAAE,EAAE,MAAM,CAAC;YACX,QAAQ,EAAE;gBAAE,KAAK,EAAE,MAAM,CAAC;gBAAC,SAAS,EAAE,MAAM,CAAC;gBAAC,EAAE,EAAE,MAAM,CAAA;aAAE,CAAC;SAC3D,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;KACpB,CAAC;CACF;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB;;;;;;;OAOG;IACH,gBAAgB,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IACxC,8EAA8E;IAC9E,WAAW,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,KAAK,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAC3D,+EAA+E;IAC/E,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;OAGG;IACH,oBAAoB,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;CAC7C;AA2CD;;GAEG;AACH,eAAO,MAAM,qBAAqB,GACjC,MAAM,WAAW,EACjB,SAAS,cAAc,KACrB,KAAK,CAAC,SAAS,CAqWjB,CAAC"}
@@ -9,16 +9,37 @@
9
9
  *
10
10
  * @module
11
11
  */
12
- import { z } from 'zod';
13
- import { object } from '@fuzdev/fuz_schema/schema.ts';
14
- import { ActingActor as ActingActorFuz } from '../primitive_schemas_fuz.js';
12
+ import { meta } from '@fuzdev/fuz_schema/meta.ts';
13
+ import { array, boolean, integer, literal, loose_object, max_value, min_value, nullable, number, object, pipe, record, regex, safe_integer, string, transform, unknown, with_default } from '@fuzdev/fuz_schema/schema.ts';
14
+ import { ActingActor } from '../primitive_schemas_fuz.js';
15
15
  import { get_route_params, get_route_query } from './route_spec.js';
16
- import { ActingActor } from './auth_shape.js';
17
- import { ForeignKeyError, ERROR_TABLE_NOT_FOUND, ERROR_TABLE_NO_PRIMARY_KEY, ERROR_TABLE_NOT_DELETABLE, ERROR_ROW_NOT_FOUND, ERROR_FOREIGN_KEY_VIOLATION, ERROR_INVALID_ROUTE_PARAMS, ERROR_DATABASE_CONNECTION_FAILED } from './error_schemas.js';
16
+ import { ERROR_TABLE_NOT_FOUND, ERROR_TABLE_NO_PRIMARY_KEY, ERROR_TABLE_NOT_DELETABLE, ERROR_ROW_NOT_FOUND, ERROR_FOREIGN_KEY_VIOLATION, ERROR_DATABASE_CONNECTION_FAILED, REST_DATABASE_CONNECTION_FAILED, REST_FOREIGN_KEY_VIOLATION, REST_ROW_NOT_FOUND, REST_TABLE_NO_PRIMARY_KEY, REST_TABLE_NOT_DELETABLE, REST_TABLE_NOT_FOUND } from './error_schemas.js';
18
17
  import { assert_valid_sql_identifier, VALID_SQL_IDENTIFIER } from '../db/sql_identifier.js';
19
18
  import { pg_error_code } from '../db/pg_error.js';
20
19
  import { get_client_ip } from './client_ip.js';
21
20
  import { emit_after_commit } from './pending_effects.js';
21
+ // the spellings `query_int` reads as an integer: decimal digits with an optional sign
22
+ const QUERY_INT_PATTERN = /^[+-]?\d+$/;
23
+ /**
24
+ * A strict integer query param with bounds and a default — accepts exactly
25
+ * the spellings the Rust twin's `str::parse::<i64>` does (`[+-]?digits`), so
26
+ * the twins refuse the same ones (`""`, `" 5"`, `"1e2"`, `"5.0"`, `"0x10"`),
27
+ * then a safe integer within `[min, max]`. An absent param is `fallback`.
28
+ *
29
+ * The surface writes it as a string with `QUERY_INT_PATTERN`, its bounds in
30
+ * the description: the steps after the `transform` read a number JSON Schema
31
+ * can't say the string becomes.
32
+ *
33
+ * @param min - the least integer accepted
34
+ * @param max - the greatest integer accepted
35
+ * @param fallback - the value of an absent param
36
+ * @returns the query param schema, whose output is a number
37
+ */
38
+ const query_int = (min, max, fallback) => meta(with_default(pipe(pipe(string, regex(QUERY_INT_PATTERN), transform(Number)), safe_integer, min_value(min), max_value(max)), fallback), { description: `an integer from ${min} to ${max}, as decimal digits with an optional sign` });
39
+ /** A count or position the db routes answer with: a non-negative integer. */
40
+ const Count = pipe(number, integer, min_value(0));
41
+ /** A table name in a path: a valid SQL identifier. */
42
+ const TableName = pipe(string, regex(VALID_SQL_IDENTIFIER));
22
43
  /** Default page size for `GET /tables/:name` rows. */
23
44
  export const DB_TABLE_ROWS_DEFAULT_LIMIT = 100;
24
45
  /** Maximum page size for `GET /tables/:name` rows. */
@@ -142,16 +163,6 @@ export const create_db_route_specs = (deps, options) => {
142
163
  await set_statement_timeout(db);
143
164
  return query_table_exists(db, name);
144
165
  };
145
- /**
146
- * Strict integer query param — accepts exactly what the Rust twin's
147
- * `str::parse::<i64>` does (`[+-]?digits`), so the twins refuse the same
148
- * spellings (`z.coerce` alone admits `""`, `" 5"`, `"1e2"`, `"5.0"`).
149
- */
150
- const query_int = (bounds, fallback) => z.preprocess((v) => v === undefined
151
- ? undefined
152
- : typeof v === 'string' && /^[+-]?\d+$/.test(v)
153
- ? Number(v)
154
- : Number.NaN, bounds.default(fallback));
155
166
  return [
156
167
  {
157
168
  method: 'GET',
@@ -163,12 +174,10 @@ export const create_db_route_specs = (deps, options) => {
163
174
  credential_types: ['daemon_token']
164
175
  },
165
176
  description: 'Database health and stats',
166
- query: object({ acting: ActingActorFuz }),
167
- input: z.null(),
168
- output: z.looseObject({ connected: z.boolean() }),
169
- errors: {
170
- 503: z.looseObject({ error: z.literal(ERROR_DATABASE_CONNECTION_FAILED) })
171
- },
177
+ query: object({ acting: ActingActor }),
178
+ input: literal(null),
179
+ output: loose_object({ connected: boolean }),
180
+ errors: [REST_DATABASE_CONNECTION_FAILED],
172
181
  handler: async (c, route) => {
173
182
  try {
174
183
  await route.db.query('SELECT 1');
@@ -206,10 +215,10 @@ export const create_db_route_specs = (deps, options) => {
206
215
  credential_types: ['daemon_token']
207
216
  },
208
217
  description: 'List browsable tables with row counts',
209
- query: object({ acting: ActingActorFuz }),
210
- input: z.null(),
211
- output: z.looseObject({
212
- tables: z.array(z.strictObject({ name: z.string(), row_count: z.number() }))
218
+ query: object({ acting: ActingActor }),
219
+ input: literal(null),
220
+ output: loose_object({
221
+ tables: array(object({ name: string, row_count: Count }))
213
222
  }),
214
223
  transaction: true,
215
224
  handler: async (c, route) => {
@@ -242,32 +251,22 @@ export const create_db_route_specs = (deps, options) => {
242
251
  credential_types: ['daemon_token']
243
252
  },
244
253
  description: 'Get table columns and rows (paginated)',
245
- params: z.strictObject({ name: z.string().regex(VALID_SQL_IDENTIFIER) }),
246
- // Zod, unlike the `{acting}`-only queries here: its paging params are
247
- // `query_int`'s Zod preprocess, which stays with the rest of these
248
- // routes' Zod schemas
249
- query: z.strictObject({
254
+ params: object({ name: TableName }),
255
+ query: object({
250
256
  acting: ActingActor,
251
- offset: query_int(z.number().int().min(0), 0),
252
- limit: query_int(z.number().int().min(1).max(DB_TABLE_ROWS_LIMIT_MAX), DB_TABLE_ROWS_DEFAULT_LIMIT)
257
+ offset: query_int(0, Number.MAX_SAFE_INTEGER, 0),
258
+ limit: query_int(1, DB_TABLE_ROWS_LIMIT_MAX, DB_TABLE_ROWS_DEFAULT_LIMIT)
253
259
  }),
254
- input: z.null(),
255
- errors: {
256
- 400: z.looseObject({ error: z.literal(ERROR_INVALID_ROUTE_PARAMS) }),
257
- 404: z.looseObject({ error: z.literal(ERROR_TABLE_NOT_FOUND) })
258
- },
259
- output: z.looseObject({
260
- columns: z.array(z.strictObject({
261
- column_name: z.string(),
262
- data_type: z.string(),
263
- is_nullable: z.string()
264
- })),
265
- rows: z.array(z.record(z.string(), z.unknown())),
266
- total: z.number(),
267
- offset: z.number(),
268
- limit: z.number(),
269
- primary_key: z.string().nullable(),
270
- deletable: z.boolean()
260
+ input: literal(null),
261
+ errors: [REST_TABLE_NOT_FOUND],
262
+ output: loose_object({
263
+ columns: array(object({ column_name: string, data_type: string, is_nullable: string })),
264
+ rows: array(record(unknown)),
265
+ total: Count,
266
+ offset: Count,
267
+ limit: Count,
268
+ primary_key: nullable(string),
269
+ deletable: boolean
271
270
  }),
272
271
  transaction: true,
273
272
  handler: async (c, route) => {
@@ -331,26 +330,17 @@ export const create_db_route_specs = (deps, options) => {
331
330
  credential_types: ['daemon_token']
332
331
  },
333
332
  description: 'Delete a row by primary key',
334
- params: z.strictObject({
335
- name: z.string().regex(VALID_SQL_IDENTIFIER),
336
- id: z.string()
337
- }),
338
- query: object({ acting: ActingActorFuz }),
339
- input: z.null(),
340
- output: z.looseObject({ success: z.boolean() }),
341
- errors: {
342
- 400: z.looseObject({
343
- error: z.enum([
344
- ERROR_INVALID_ROUTE_PARAMS,
345
- ERROR_TABLE_NO_PRIMARY_KEY,
346
- ERROR_TABLE_NOT_DELETABLE
347
- ])
348
- }),
349
- 404: z.looseObject({
350
- error: z.enum([ERROR_TABLE_NOT_FOUND, ERROR_ROW_NOT_FOUND])
351
- }),
352
- 409: ForeignKeyError
353
- },
333
+ params: object({ name: TableName, id: string }),
334
+ query: object({ acting: ActingActor }),
335
+ input: literal(null),
336
+ output: loose_object({ success: boolean }),
337
+ errors: [
338
+ REST_TABLE_NOT_DELETABLE,
339
+ REST_TABLE_NO_PRIMARY_KEY,
340
+ REST_TABLE_NOT_FOUND,
341
+ REST_ROW_NOT_FOUND,
342
+ REST_FOREIGN_KEY_VIOLATION
343
+ ],
354
344
  handler: async (c, route) => {
355
345
  const { name, id } = get_route_params(c);
356
346
  // Same allowlist gate and masking as the detail route — an
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The DEV-only error check: an outer middleware that logs every JSON error
3
+ * response its route doesn't declare.
4
+ *
5
+ * Mounted outermost by `create_app_server`, so it sees what every layer
6
+ * answers — a middleware's refusal (the body limit, the origin check, the
7
+ * auth guards) as much as a handler's or the error catch's. After the request
8
+ * it finds the route the request reached (`create_route_lookup`: Hono's own
9
+ * router over the route specs in mount order, `HEAD` read as `GET`) and checks the
10
+ * response against that route's error map (`check_route_error`): an error
11
+ * status the map lacks, or a body off the status's schema, is logged. A 500
12
+ * `internal_error` and a 503 `service_unavailable` are always accepted, a
13
+ * JSON-RPC error envelope on a `jsonrpc` route is not a REST error body, a
14
+ * non-JSON response is skipped, and so is a request no route spec matches
15
+ * (an unmatched path's 404 is Hono's plain text, no JSON convention to hold
16
+ * it to).
17
+ *
18
+ * Logs, never throws — a throw inside it, its logger's included, is swallowed
19
+ * — and leaves the response unchanged. Outside DEV
20
+ * `create_dev_route_error_check` returns `null` and nothing is mounted.
21
+ *
22
+ * @module
23
+ */
24
+ import type { MiddlewareHandler } from 'hono';
25
+ import type { Logger } from '@fuzdev/fuz_util/log.ts';
26
+ import { type RouteErrorMap, type RouteErrorMapSpec } from './route_errors.js';
27
+ /**
28
+ * A lookup of the route a request reaches, by Hono's own router — the
29
+ * `SmartRouter` over a `RegExpRouter` and a `TrieRouter` that `new Hono()`
30
+ * builds: the routes are added in mount order, and a request's first match is
31
+ * the route Hono dispatches it to — `HEAD` read as `GET`, which Hono answers
32
+ * it with.
33
+ *
34
+ * Its router holds only the route specs, while the app's also holds every
35
+ * middleware and non-spec route (WS upgrades, static serving), which can put
36
+ * the app on a different router than the lookup's — a `TrieRouter` where the
37
+ * lookup has a `RegExpRouter`. Where the two differ the cost is a missed DEV
38
+ * log, and rarely a wrong route.
39
+ *
40
+ * @param routes - the routes, in the order they were mounted
41
+ * @param to_value - what to keep beside each route
42
+ * @returns a function from a request's method and path to the matched route's
43
+ * value, or `undefined` when none matches
44
+ */
45
+ export declare const create_route_lookup: <TRoute extends {
46
+ readonly method: string;
47
+ readonly path: string;
48
+ }, T>(routes: ReadonlyArray<TRoute>, to_value: (route: TRoute) => T) => ((method: string, path: string) => T | undefined);
49
+ /** What `create_dev_route_error_check` reads of a route spec. */
50
+ export interface DevRouteErrorCheckSpec extends RouteErrorMapSpec {
51
+ readonly jsonrpc?: boolean;
52
+ }
53
+ /** Options for `create_dev_route_error_check`. */
54
+ export interface DevRouteErrorCheckOptions {
55
+ /** The app's route specs, in mount order. */
56
+ route_specs: ReadonlyArray<DevRouteErrorCheckSpec>;
57
+ /** Each route's error map, keyed `METHOD path` (`resolve_app_route_error_maps`). */
58
+ route_error_maps: ReadonlyMap<string, RouteErrorMap>;
59
+ /** Receives each response its route doesn't declare. */
60
+ log: Logger;
61
+ }
62
+ /**
63
+ * Build the DEV error check (module doc), or `null` outside DEV.
64
+ *
65
+ * @param options - the routes, their error maps, and the logger
66
+ * @returns the middleware to mount outermost, or `null` in production
67
+ * @throws Error when `route_error_maps` lacks a route of `route_specs` (`get_route_error_map`)
68
+ */
69
+ export declare const create_dev_route_error_check: (options: DevRouteErrorCheckOptions) => MiddlewareHandler | null;
70
+ //# sourceMappingURL=dev_route_error_check.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev_route_error_check.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/http/dev_route_error_check.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAK9C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AAQtD,OAAO,EAAuB,KAAK,aAAa,EAAE,KAAK,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAEpG;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,mBAAmB,GAC/B,MAAM,SAAS;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EACjE,CAAC,EAED,QAAQ,aAAa,CAAC,MAAM,CAAC,EAC7B,UAAU,CAAC,KAAK,EAAE,MAAM,KAAK,CAAC,KAC5B,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,KAAK,CAAC,GAAG,SAAS,CAclD,CAAC;AAEF,iEAAiE;AACjE,MAAM,WAAW,sBAAuB,SAAQ,iBAAiB;IAChE,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED,kDAAkD;AAClD,MAAM,WAAW,yBAAyB;IACzC,6CAA6C;IAC7C,WAAW,EAAE,aAAa,CAAC,sBAAsB,CAAC,CAAC;IACnD,oFAAoF;IACpF,gBAAgB,EAAE,WAAW,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACrD,wDAAwD;IACxD,GAAG,EAAE,MAAM,CAAC;CACZ;AAED;;;;;;GAMG;AACH,eAAO,MAAM,4BAA4B,GACxC,SAAS,yBAAyB,KAChC,iBAAiB,GAAG,IA2CtB,CAAC"}
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The DEV-only error check: an outer middleware that logs every JSON error
3
+ * response its route doesn't declare.
4
+ *
5
+ * Mounted outermost by `create_app_server`, so it sees what every layer
6
+ * answers — a middleware's refusal (the body limit, the origin check, the
7
+ * auth guards) as much as a handler's or the error catch's. After the request
8
+ * it finds the route the request reached (`create_route_lookup`: Hono's own
9
+ * router over the route specs in mount order, `HEAD` read as `GET`) and checks the
10
+ * response against that route's error map (`check_route_error`): an error
11
+ * status the map lacks, or a body off the status's schema, is logged. A 500
12
+ * `internal_error` and a 503 `service_unavailable` are always accepted, a
13
+ * JSON-RPC error envelope on a `jsonrpc` route is not a REST error body, a
14
+ * non-JSON response is skipped, and so is a request no route spec matches
15
+ * (an unmatched path's 404 is Hono's plain text, no JSON convention to hold
16
+ * it to).
17
+ *
18
+ * Logs, never throws — a throw inside it, its logger's included, is swallowed
19
+ * — and leaves the response unchanged. Outside DEV
20
+ * `create_dev_route_error_check` returns `null` and nothing is mounted.
21
+ *
22
+ * @module
23
+ */
24
+ import { RegExpRouter } from 'hono/router/reg-exp-router';
25
+ import { SmartRouter } from 'hono/router/smart-router';
26
+ import { TrieRouter } from 'hono/router/trie-router';
27
+ import { DEV } from 'esm-env';
28
+ import { check_route_error, format_route_error_check, is_error_status, is_json_response } from './route_error_check.js';
29
+ import { get_route_error_map } from './route_errors.js';
30
+ /**
31
+ * A lookup of the route a request reaches, by Hono's own router — the
32
+ * `SmartRouter` over a `RegExpRouter` and a `TrieRouter` that `new Hono()`
33
+ * builds: the routes are added in mount order, and a request's first match is
34
+ * the route Hono dispatches it to — `HEAD` read as `GET`, which Hono answers
35
+ * it with.
36
+ *
37
+ * Its router holds only the route specs, while the app's also holds every
38
+ * middleware and non-spec route (WS upgrades, static serving), which can put
39
+ * the app on a different router than the lookup's — a `TrieRouter` where the
40
+ * lookup has a `RegExpRouter`. Where the two differ the cost is a missed DEV
41
+ * log, and rarely a wrong route.
42
+ *
43
+ * @param routes - the routes, in the order they were mounted
44
+ * @param to_value - what to keep beside each route
45
+ * @returns a function from a request's method and path to the matched route's
46
+ * value, or `undefined` when none matches
47
+ */
48
+ export const create_route_lookup = (routes, to_value) => {
49
+ const values = routes.map(to_value);
50
+ // `new Hono()`'s own router: a `RegExpRouter`, or a `TrieRouter` where the
51
+ // route set has a template the first can't compile — the two differ on an
52
+ // edge or two (`/w/*/c` on `/w//c`), so the lookup takes the one Hono would
53
+ const router = new SmartRouter({
54
+ routers: [new RegExpRouter(), new TrieRouter()]
55
+ });
56
+ routes.forEach((route, i) => router.add(route.method, route.path, i));
57
+ return (method, path) => {
58
+ const [matches] = router.match(method === 'HEAD' ? 'GET' : method, path);
59
+ const first = matches[0];
60
+ return first === undefined ? undefined : values[first[0]];
61
+ };
62
+ };
63
+ /**
64
+ * Build the DEV error check (module doc), or `null` outside DEV.
65
+ *
66
+ * @param options - the routes, their error maps, and the logger
67
+ * @returns the middleware to mount outermost, or `null` in production
68
+ * @throws Error when `route_error_maps` lacks a route of `route_specs` (`get_route_error_map`)
69
+ */
70
+ export const create_dev_route_error_check = (options) => {
71
+ if (!DEV)
72
+ return null;
73
+ const { route_error_maps, log } = options;
74
+ const find_route = create_route_lookup(options.route_specs, (spec) => ({
75
+ errors: get_route_error_map(route_error_maps, spec),
76
+ jsonrpc: spec.jsonrpc ?? false
77
+ }));
78
+ // named, so an assembled app's route table shows it
79
+ const dev_route_error_check = async (c, next) => {
80
+ await next();
81
+ // the check never changes the response: a throw in it, a logger's
82
+ // included, is logged if it can be and swallowed, so it never reaches `onError`
83
+ try {
84
+ const response = c.res;
85
+ if (!is_error_status(response.status))
86
+ return;
87
+ if (!is_json_response(response))
88
+ return;
89
+ const route = find_route(c.req.method, c.req.path);
90
+ if (!route)
91
+ return;
92
+ let body;
93
+ try {
94
+ body = await response.clone().json();
95
+ }
96
+ catch {
97
+ // a body claiming JSON that isn't
98
+ return;
99
+ }
100
+ const check = check_route_error(route.errors, response.status, body, route.jsonrpc);
101
+ if (check.ok)
102
+ return;
103
+ const message = format_route_error_check(check, response.status, `${c.req.method} ${c.req.path}`);
104
+ if (check.kind === 'schema_mismatch')
105
+ log.error(message, check.issues);
106
+ else
107
+ log.error(message, body);
108
+ }
109
+ catch (err) {
110
+ try {
111
+ log.error('dev_route_error_check failed:', err);
112
+ }
113
+ catch {
114
+ // the logger itself threw; nothing left to tell
115
+ }
116
+ }
117
+ };
118
+ return dev_route_error_check;
119
+ };