@nifrajs/core 2.2.0 → 2.3.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 (133) hide show
  1. package/README.md +2 -2
  2. package/dist/assurance.d.ts +48 -4
  3. package/dist/assurance.d.ts.map +1 -1
  4. package/dist/assurance.js +87 -9
  5. package/dist/assurance.js.map +1 -1
  6. package/dist/binary.d.ts +54 -0
  7. package/dist/binary.d.ts.map +1 -0
  8. package/dist/binary.js +90 -0
  9. package/dist/binary.js.map +1 -0
  10. package/dist/budget.d.ts +1 -1
  11. package/dist/budget.js +1 -1
  12. package/dist/capabilities.d.ts +19 -2
  13. package/dist/capabilities.d.ts.map +1 -1
  14. package/dist/capabilities.js +60 -8
  15. package/dist/capabilities.js.map +1 -1
  16. package/dist/classification.d.ts +1 -1
  17. package/dist/classification.js +1 -1
  18. package/dist/diff.d.ts +6 -6
  19. package/dist/diff.js +6 -6
  20. package/dist/durable-adapters.d.ts.map +1 -1
  21. package/dist/durable-adapters.js +36 -70
  22. package/dist/durable-adapters.js.map +1 -1
  23. package/dist/durable-execution.d.ts +2 -2
  24. package/dist/durable-execution.js +2 -2
  25. package/dist/idempotency.d.ts +3 -3
  26. package/dist/idempotency.js +4 -4
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +3 -3
  29. package/dist/internal/brand.d.ts +1 -1
  30. package/dist/internal/brand.js +1 -1
  31. package/dist/internal/route-catalog.d.ts +58 -0
  32. package/dist/internal/route-catalog.d.ts.map +1 -0
  33. package/dist/internal/route-catalog.js +58 -0
  34. package/dist/internal/route-catalog.js.map +1 -0
  35. package/dist/internal/route-execution.d.ts +75 -0
  36. package/dist/internal/route-execution.d.ts.map +1 -0
  37. package/dist/internal/route-execution.js +2 -0
  38. package/dist/internal/route-execution.js.map +1 -0
  39. package/dist/internal/same-origin.d.ts +29 -0
  40. package/dist/internal/same-origin.d.ts.map +1 -0
  41. package/dist/internal/same-origin.js +47 -0
  42. package/dist/internal/same-origin.js.map +1 -0
  43. package/dist/internal/secret.d.ts +1 -1
  44. package/dist/internal/secret.js +1 -1
  45. package/dist/ledger.d.ts +9 -9
  46. package/dist/ledger.js +5 -5
  47. package/dist/reflection.d.ts +1 -1
  48. package/dist/router/pattern.js +4 -4
  49. package/dist/router/router.js +3 -3
  50. package/dist/schema/standard.d.ts +2 -2
  51. package/dist/schema/standard.js +2 -2
  52. package/dist/seo.d.ts +3 -3
  53. package/dist/seo.js +4 -4
  54. package/dist/server/body.d.ts +2 -2
  55. package/dist/server/body.js +2 -2
  56. package/dist/server/context.d.ts +18 -18
  57. package/dist/server/contract.d.ts +7 -7
  58. package/dist/server/contract.js +3 -3
  59. package/dist/server/cookies.d.ts +4 -4
  60. package/dist/server/cookies.js +8 -8
  61. package/dist/server/edge.d.ts +83 -0
  62. package/dist/server/edge.d.ts.map +1 -0
  63. package/dist/server/edge.js +71 -0
  64. package/dist/server/edge.js.map +1 -0
  65. package/dist/server/install.d.ts +2 -0
  66. package/dist/server/install.d.ts.map +1 -1
  67. package/dist/server/install.js +2 -0
  68. package/dist/server/install.js.map +1 -1
  69. package/dist/server/logger.d.ts +7 -7
  70. package/dist/server/logger.js +4 -4
  71. package/dist/server/registry.d.ts +5 -5
  72. package/dist/server/response-contract-lane.d.ts +91 -0
  73. package/dist/server/response-contract-lane.d.ts.map +1 -0
  74. package/dist/server/response-contract-lane.js +81 -0
  75. package/dist/server/response-contract-lane.js.map +1 -0
  76. package/dist/server/server.d.ts +52 -91
  77. package/dist/server/server.d.ts.map +1 -1
  78. package/dist/server/server.js +130 -186
  79. package/dist/server/server.js.map +1 -1
  80. package/dist/server/sse.d.ts +4 -4
  81. package/dist/server/sse.js +7 -7
  82. package/dist/server/webhook.d.ts +1 -1
  83. package/dist/server/webhook.js +5 -5
  84. package/dist/server/websocket.d.ts +19 -19
  85. package/dist/server/websocket.js +9 -9
  86. package/dist/server/ws-bun.d.ts +4 -4
  87. package/dist/server/ws-bun.js +3 -3
  88. package/dist/server.d.ts +3 -1
  89. package/dist/server.d.ts.map +1 -1
  90. package/dist/server.js +3 -1
  91. package/dist/server.js.map +1 -1
  92. package/dist/transport-codec.d.ts +12 -0
  93. package/dist/transport-codec.d.ts.map +1 -1
  94. package/dist/transport-codec.js +19 -4
  95. package/dist/transport-codec.js.map +1 -1
  96. package/package.json +12 -2
  97. package/src/assurance.ts +154 -8
  98. package/src/binary.ts +128 -0
  99. package/src/budget.ts +1 -1
  100. package/src/capabilities.ts +71 -9
  101. package/src/classification.ts +1 -1
  102. package/src/diff.ts +8 -8
  103. package/src/durable-adapters.ts +40 -70
  104. package/src/durable-execution.ts +2 -2
  105. package/src/idempotency.ts +4 -4
  106. package/src/index.ts +3 -3
  107. package/src/internal/brand.ts +1 -1
  108. package/src/internal/route-catalog.ts +94 -0
  109. package/src/internal/route-execution.ts +106 -0
  110. package/src/internal/same-origin.ts +43 -0
  111. package/src/internal/secret.ts +1 -1
  112. package/src/ledger.ts +11 -11
  113. package/src/reflection.ts +1 -1
  114. package/src/router/pattern.ts +4 -4
  115. package/src/router/router.ts +5 -5
  116. package/src/schema/standard.ts +2 -2
  117. package/src/seo.ts +6 -6
  118. package/src/server/body.ts +2 -2
  119. package/src/server/context.ts +18 -18
  120. package/src/server/contract.ts +13 -13
  121. package/src/server/cookies.ts +8 -8
  122. package/src/server/edge.ts +150 -0
  123. package/src/server/install.ts +5 -0
  124. package/src/server/logger.ts +8 -8
  125. package/src/server/registry.ts +5 -5
  126. package/src/server/response-contract-lane.ts +164 -0
  127. package/src/server/server.ts +159 -366
  128. package/src/server/sse.ts +11 -11
  129. package/src/server/webhook.ts +5 -5
  130. package/src/server/websocket.ts +22 -22
  131. package/src/server/ws-bun.ts +4 -4
  132. package/src/server.ts +8 -5
  133. package/src/transport-codec.ts +24 -5
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Making a route's declared `response` schema mean something at runtime.
3
+ *
4
+ * ## The gap this closes
5
+ *
6
+ * A `response` schema is a LOWER bound, not an upper one. It says "at least these fields, of these
7
+ * types"; it never said "only these". TypeScript does not close the gap either - excess-property
8
+ * checking fires on a fresh object literal in an annotated position, and a handler is neither: it is a
9
+ * contextually-typed argument that usually returns a variable. So this compiles, and ships every field:
10
+ *
11
+ * app.get("/me", { response: PublicUser }, async () => {
12
+ * const user = await db.users.find(id) // { id, name, email, passwordHash, ... }
13
+ * return user // all of it goes on the wire
14
+ * })
15
+ *
16
+ * The client's type says `{ id, name }`, so the leak is invisible from both ends. And it can appear
17
+ * with no code change at all: add a column to `users`, and the next deploy ships it to browsers.
18
+ *
19
+ * ## Why the behaviour follows the schema, not this module
20
+ *
21
+ * Standard Schema exposes exactly one operation - `validate` - and no way to enumerate a schema's
22
+ * declared keys. So a projection of "just the declared fields" cannot be written generically here;
23
+ * the only clean value available is whatever `validate()` returns. That is deliberate on the spec's
24
+ * part, and it means enforcement inherits each validator's own semantics:
25
+ *
26
+ * - a STRIPPING schema (zod, valibot) returns a cleaned value -> the undeclared fields are removed
27
+ * - a STRICT schema (`@nifrajs/schema`'s `t.object`) reports issues -> the response is a violation
28
+ *
29
+ * That is not an inconsistency to paper over: a strict schema has already declared that extra fields
30
+ * are an error, and a stripping one has declared they are ignorable. Enforcement honours what the
31
+ * author wrote rather than overriding it.
32
+ */
33
+ import type { StandardIssue, StandardResult, StandardSchemaV1 } from "../schema/standard.ts"
34
+ import { INSTALL_RESPONSE_CONTRACT } from "./install.ts"
35
+ import type { IdentityPlugin } from "./plugin.ts"
36
+ import type { AnyServer } from "./server.ts"
37
+
38
+ /**
39
+ * How hard a declared `response` schema is held.
40
+ *
41
+ * - `warn` - check and log; the response is sent UNCHANGED, so enabling it cannot break anything.
42
+ * - `enforce` - serialize the validated value, so undeclared data cannot reach the wire.
43
+ *
44
+ * There is no `off`: not installing the plugin IS off, and that is what keeps this module out of an
45
+ * app's bundle entirely rather than shipping a disabled branch to everyone.
46
+ */
47
+ export type ResponseContractMode = "warn" | "enforce"
48
+
49
+ /** The outcome of checking one handler result against its declared response schema. */
50
+ export type ResponseContractOutcome =
51
+ /** Nothing to report. `value` is what should be serialized (the original result, or the cleaned one). */
52
+ | { readonly kind: "ok"; readonly value: unknown }
53
+ /** `warn` only: the payload differed from the contract. The ORIGINAL result is still served. */
54
+ | { readonly kind: "warn"; readonly value: unknown; readonly message: string }
55
+ /** `enforce` only: the payload cannot be reconciled with the contract, so it must not be sent. */
56
+ | { readonly kind: "violation"; readonly message: string }
57
+
58
+ const isPlainObject = (v: unknown): v is Record<string, unknown> =>
59
+ typeof v === "object" && v !== null && !Array.isArray(v)
60
+
61
+ /** Top-level keys present in the handler's result but absent from the validated value. */
62
+ function droppedKeys(result: unknown, value: unknown): string[] {
63
+ if (!isPlainObject(result) || !isPlainObject(value)) return []
64
+ return Object.keys(result).filter((k) => !(k in value))
65
+ }
66
+
67
+ function describeIssues(issues: ReadonlyArray<StandardIssue>): string {
68
+ return issues
69
+ .map((issue) => {
70
+ const path = Array.isArray(issue.path)
71
+ ? issue.path
72
+ .map((seg) =>
73
+ String(typeof seg === "object" && seg !== null ? (seg as { key: unknown }).key : seg),
74
+ )
75
+ .join(".")
76
+ : ""
77
+ return path === "" ? issue.message : `${path}: ${issue.message}`
78
+ })
79
+ .join("; ")
80
+ }
81
+
82
+ /**
83
+ * Check one result against the route's declared response schema.
84
+ *
85
+ * Returns synchronously when the schema does (the common case), so an app that opts in does not pay a
86
+ * microtask per response for a check that had no work to do.
87
+ */
88
+ export function checkResponseContract(
89
+ schema: StandardSchemaV1,
90
+ result: unknown,
91
+ mode: "warn" | "enforce",
92
+ ): ResponseContractOutcome | Promise<ResponseContractOutcome> {
93
+ // A handler may return a raw Response as deliberate control flow (a redirect, a stream). There is no
94
+ // JSON payload to hold to the contract, and re-serializing one would corrupt it.
95
+ if (result instanceof Response || result === undefined) return { kind: "ok", value: result }
96
+ const settled = schema["~standard"].validate(result)
97
+ return settled instanceof Promise
98
+ ? settled.then((r) => interpret(r, result, mode))
99
+ : interpret(settled, result, mode)
100
+ }
101
+
102
+ function interpret(
103
+ settled: StandardResult<unknown>,
104
+ result: unknown,
105
+ mode: "warn" | "enforce",
106
+ ): ResponseContractOutcome {
107
+ if (settled.issues !== undefined) {
108
+ const message = `response does not satisfy its declared contract: ${describeIssues(settled.issues)}`
109
+ // `warn` never changes what is served - it reports and gets out of the way, so switching it on can
110
+ // never be the thing that broke production.
111
+ return mode === "warn"
112
+ ? { kind: "warn", value: result, message }
113
+ : { kind: "violation", message }
114
+ }
115
+ const dropped = droppedKeys(result, settled.value)
116
+ if (mode === "enforce") return { kind: "ok", value: settled.value }
117
+ return dropped.length === 0
118
+ ? { kind: "ok", value: result }
119
+ : {
120
+ kind: "warn",
121
+ value: result,
122
+ message: `response carries fields its contract does not declare: ${dropped.join(", ")}. They are being sent; \`responseContract: "enforce"\` would strip them.`,
123
+ }
124
+ }
125
+
126
+ /**
127
+ * What the server holds when the plugin is installed. The kernel calls `check` through this object and
128
+ * never imports the implementation, so an app that does not install the plugin does not carry it.
129
+ */
130
+ export interface ResponseContractRuntime {
131
+ readonly mode: ResponseContractMode
132
+ check(
133
+ schema: StandardSchemaV1,
134
+ result: unknown,
135
+ ): ResponseContractOutcome | Promise<ResponseContractOutcome>
136
+ }
137
+
138
+ interface ResponseContractInstallable {
139
+ [INSTALL_RESPONSE_CONTRACT](runtime: ResponseContractRuntime): void
140
+ }
141
+
142
+ /**
143
+ * Hold every route's declared `response` schema to what the handler actually returned.
144
+ *
145
+ * app.use(responseContract("enforce"))
146
+ *
147
+ * Install it before the routes it should cover - like `idempotency()`, the decision is made per route
148
+ * at registration, so routes registered earlier are not retroactively covered.
149
+ *
150
+ * A contracted route leaves the fused and native fast paths, because the check needs the handler's
151
+ * value before it becomes bytes. That is the same trade an idempotent route makes, and the reason this
152
+ * is opt-in rather than always on.
153
+ */
154
+ export function responseContract(mode: ResponseContractMode = "warn"): IdentityPlugin {
155
+ const runtime: ResponseContractRuntime = {
156
+ mode,
157
+ check: (schema, result) => checkResponseContract(schema, result, mode),
158
+ }
159
+ const apply = <S extends AnyServer>(app: S): S => {
160
+ ;(app as unknown as ResponseContractInstallable)[INSTALL_RESPONSE_CONTRACT](runtime)
161
+ return app
162
+ }
163
+ return Object.assign(apply, { pluginName: "nifra:response-contract" }) as IdentityPlugin
164
+ }