@bleedingdev/modern-js-server-runtime-extensions 3.9.0-ultramodern.2 → 3.9.0-ultramodern.20

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 (211) hide show
  1. package/README.md +8 -6
  2. package/dist/cjs/backend-federation-security/index.js +73 -152
  3. package/dist/cjs/bff-policy/crossProjectPolicy.js +299 -0
  4. package/dist/cjs/bff-policy/index.js +69 -0
  5. package/dist/cjs/bff-policy/node.js +85 -0
  6. package/dist/cjs/bff-policy/operationContracts.js +197 -0
  7. package/dist/cjs/bff-policy/operationIdentity.js +81 -0
  8. package/dist/cjs/bff-policy/producer.js +79 -0
  9. package/dist/cjs/bff-policy/resolveCrossProjectPolicy.js +65 -0
  10. package/dist/cjs/contract-gate-snapshot-store/http-store.js +1 -8
  11. package/dist/cjs/errorResponsePlugin.js +57 -0
  12. package/dist/cjs/localisedLoader.js +65 -0
  13. package/dist/cjs/localisedLoaderPlugin.js +62 -0
  14. package/dist/cjs/mfCache.js +6 -0
  15. package/dist/cjs/module-federation-css/plugin.js +6 -0
  16. package/dist/cjs/module-federation-css/remote.js +2 -1
  17. package/dist/cjs/serverConfig.js +18 -0
  18. package/dist/cjs/serverPlugin.js +74 -0
  19. package/dist/cjs/static-serving/plugin.js +57 -0
  20. package/dist/cjs/static-serving/responders.js +158 -0
  21. package/dist/cjs/static-serving/staticModuleFederation.js +173 -0
  22. package/dist/cjs/static-serving/staticPrecompressed.js +152 -0
  23. package/dist/cjs/telemetry/exporters.js +4 -4
  24. package/dist/cjs/telemetry/healthSetup.js +14 -14
  25. package/dist/cjs/telemetry/lifecycle.js +20 -21
  26. package/dist/cjs/telemetry/plugin.js +10 -4
  27. package/dist/cjs/telemetry/runtimeEndpoints.js +3 -2
  28. package/dist/cjs/telemetryCore.js +5 -5
  29. package/dist/esm/backend-federation-security/index.mjs +73 -152
  30. package/dist/esm/bff-policy/crossProjectPolicy.mjs +249 -0
  31. package/dist/esm/bff-policy/index.mjs +2 -0
  32. package/dist/esm/bff-policy/operationIdentity.mjs +30 -0
  33. package/dist/esm/bff-policy/producer.mjs +31 -0
  34. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +1 -8
  35. package/dist/esm/errorResponsePlugin.mjs +19 -0
  36. package/dist/esm/localisedLoader.mjs +24 -0
  37. package/dist/esm/localisedLoaderPlugin.mjs +24 -0
  38. package/dist/esm/mfCache.mjs +6 -0
  39. package/dist/esm/module-federation-css/plugin.mjs +6 -0
  40. package/dist/esm/module-federation-css/remote.mjs +2 -1
  41. package/dist/esm/serverConfig.mjs +0 -0
  42. package/dist/esm/serverPlugin.mjs +34 -0
  43. package/dist/esm/telemetry/exporters.mjs +2 -2
  44. package/dist/esm/telemetry/healthSetup.mjs +14 -14
  45. package/dist/esm/telemetry/lifecycle.mjs +21 -22
  46. package/dist/esm/telemetry/plugin.mjs +9 -3
  47. package/dist/esm/telemetry/runtimeEndpoints.mjs +3 -2
  48. package/dist/esm/telemetryCore.mjs +1 -1
  49. package/dist/esm-node/backend-federation-security/index.mjs +73 -152
  50. package/dist/esm-node/bff-policy/crossProjectPolicy.mjs +250 -0
  51. package/dist/esm-node/bff-policy/index.mjs +3 -0
  52. package/dist/esm-node/bff-policy/node.mjs +4 -0
  53. package/dist/esm-node/bff-policy/operationContracts.mjs +107 -0
  54. package/dist/esm-node/bff-policy/operationIdentity.mjs +31 -0
  55. package/dist/esm-node/bff-policy/producer.mjs +32 -0
  56. package/dist/esm-node/bff-policy/resolveCrossProjectPolicy.mjs +28 -0
  57. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +1 -8
  58. package/dist/esm-node/errorResponsePlugin.mjs +20 -0
  59. package/dist/esm-node/localisedLoader.mjs +25 -0
  60. package/dist/esm-node/localisedLoaderPlugin.mjs +25 -0
  61. package/dist/esm-node/mfCache.mjs +6 -0
  62. package/dist/esm-node/module-federation-css/plugin.mjs +6 -0
  63. package/dist/esm-node/module-federation-css/remote.mjs +2 -1
  64. package/dist/esm-node/serverConfig.mjs +1 -0
  65. package/dist/esm-node/serverPlugin.mjs +35 -0
  66. package/dist/esm-node/static-serving/plugin.mjs +18 -0
  67. package/dist/esm-node/static-serving/responders.mjs +111 -0
  68. package/dist/esm-node/static-serving/staticModuleFederation.mjs +105 -0
  69. package/dist/esm-node/static-serving/staticPrecompressed.mjs +112 -0
  70. package/dist/esm-node/telemetry/exporters.mjs +2 -2
  71. package/dist/esm-node/telemetry/healthSetup.mjs +14 -14
  72. package/dist/esm-node/telemetry/lifecycle.mjs +21 -22
  73. package/dist/esm-node/telemetry/plugin.mjs +9 -3
  74. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +3 -2
  75. package/dist/esm-node/telemetryCore.mjs +1 -1
  76. package/dist/types/backend-federation-security/node.d.ts +1 -1
  77. package/dist/types/bff-policy/crossProjectPolicy.d.ts +101 -0
  78. package/dist/types/bff-policy/index.d.ts +2 -0
  79. package/dist/types/bff-policy/node.d.ts +3 -0
  80. package/dist/types/bff-policy/operationContracts.d.ts +46 -0
  81. package/dist/types/bff-policy/operationIdentity.d.ts +34 -0
  82. package/dist/types/bff-policy/producer.d.ts +10 -0
  83. package/dist/types/bff-policy/resolveCrossProjectPolicy.d.ts +39 -0
  84. package/dist/types/errorResponsePlugin.d.ts +3 -0
  85. package/dist/types/index.d.ts +1 -0
  86. package/dist/types/localisedLoader.d.ts +15 -0
  87. package/dist/types/localisedLoaderPlugin.d.ts +2 -0
  88. package/dist/types/mfCache.d.ts +2 -3
  89. package/dist/types/module-federation-css/plugin.d.ts +2 -3
  90. package/dist/types/module-federation-css/remote.d.ts +2 -0
  91. package/dist/types/serverConfig.d.ts +17 -0
  92. package/dist/types/serverPlugin.d.ts +5 -0
  93. package/dist/types/static-serving/plugin.d.ts +3 -0
  94. package/dist/types/static-serving/responders.d.ts +2 -0
  95. package/dist/types/static-serving/staticModuleFederation.d.ts +13 -0
  96. package/dist/types/static-serving/staticPrecompressed.d.ts +13 -0
  97. package/dist/types/telemetry/exporters.d.ts +1 -1
  98. package/dist/types/telemetry/healthSetup.d.ts +3 -3
  99. package/dist/types/telemetry/lifecycle.d.ts +4 -4
  100. package/dist/types/telemetry/plugin.d.ts +2 -1
  101. package/dist/types/telemetryCore.d.ts +1 -1
  102. package/dist/types-esm/backend-federation-security/index.d.mts +68 -0
  103. package/dist/types-esm/backend-federation-security/node.d.mts +3 -0
  104. package/dist/types-esm/bff-policy/crossProjectPolicy.d.mts +101 -0
  105. package/dist/types-esm/bff-policy/index.d.mts +2 -0
  106. package/dist/types-esm/bff-policy/node.d.mts +3 -0
  107. package/dist/types-esm/bff-policy/operationContracts.d.mts +46 -0
  108. package/dist/types-esm/bff-policy/operationIdentity.d.mts +34 -0
  109. package/dist/types-esm/bff-policy/producer.d.mts +10 -0
  110. package/dist/types-esm/bff-policy/resolveCrossProjectPolicy.d.mts +39 -0
  111. package/dist/types-esm/contract-gate-snapshot-normalization.d.mts +15 -0
  112. package/dist/types-esm/contract-gate-snapshot-store/file-store.d.mts +3 -0
  113. package/dist/types-esm/contract-gate-snapshot-store/http-store.d.mts +5 -0
  114. package/dist/types-esm/contract-gate-snapshot-store/index.d.mts +5 -0
  115. package/dist/types-esm/contract-gate-snapshot-store/resolve.d.mts +9 -0
  116. package/dist/types-esm/contract-gate-snapshot-store/types.d.mts +47 -0
  117. package/dist/types-esm/contractGateSnapshotObserver.d.mts +33 -0
  118. package/dist/types-esm/env.d.mts +40 -0
  119. package/dist/types-esm/errorResponsePlugin.d.mts +3 -0
  120. package/dist/types-esm/index.d.mts +8 -0
  121. package/dist/types-esm/localisedLoader.d.mts +15 -0
  122. package/dist/types-esm/localisedLoaderPlugin.d.mts +2 -0
  123. package/dist/types-esm/mfCache.d.mts +26 -0
  124. package/dist/types-esm/module-federation-css/collector.d.mts +25 -0
  125. package/dist/types-esm/module-federation-css/index.d.mts +8 -0
  126. package/dist/types-esm/module-federation-css/manifest.d.mts +28 -0
  127. package/dist/types-esm/module-federation-css/plugin.d.mts +22 -0
  128. package/dist/types-esm/module-federation-css/remote.d.mts +22 -0
  129. package/dist/types-esm/runtime-fallback-signal/index.d.mts +4 -0
  130. package/dist/types-esm/runtime-fallback-signal/model.d.mts +70 -0
  131. package/dist/types-esm/runtime-fallback-signal/resolver.d.mts +29 -0
  132. package/dist/types-esm/runtime-fallback-signal/store.d.mts +4 -0
  133. package/dist/types-esm/runtimeFallbackSignal.d.mts +1 -0
  134. package/dist/types-esm/runtimeLifecycle.d.mts +10 -0
  135. package/dist/types-esm/serverConfig.d.mts +17 -0
  136. package/dist/types-esm/serverPlugin.d.mts +5 -0
  137. package/dist/types-esm/static-serving/plugin.d.mts +3 -0
  138. package/dist/types-esm/static-serving/responders.d.mts +2 -0
  139. package/dist/types-esm/static-serving/staticModuleFederation.d.mts +13 -0
  140. package/dist/types-esm/static-serving/staticPrecompressed.d.mts +13 -0
  141. package/dist/types-esm/telemetry/envelope.d.mts +55 -0
  142. package/dist/types-esm/telemetry/exporters.d.mts +12 -0
  143. package/dist/types-esm/telemetry/healthEvaluation.d.mts +20 -0
  144. package/dist/types-esm/telemetry/healthMonitor.d.mts +88 -0
  145. package/dist/types-esm/telemetry/healthSetup.d.mts +17 -0
  146. package/dist/types-esm/telemetry/lifecycle.d.mts +18 -0
  147. package/dist/types-esm/telemetry/metrics.d.mts +3 -0
  148. package/dist/types-esm/telemetry/plugin.d.mts +13 -0
  149. package/dist/types-esm/telemetry/registry.d.mts +69 -0
  150. package/dist/types-esm/telemetry/registryTypes.d.mts +50 -0
  151. package/dist/types-esm/telemetry/runtimeEndpoints.d.mts +35 -0
  152. package/dist/types-esm/telemetry.d.mts +1 -0
  153. package/dist/types-esm/telemetryCore.d.mts +6 -0
  154. package/package.json +183 -29
  155. package/rslib.config.mts +36 -2
  156. package/rstest.config.mts +11 -0
  157. package/src/backend-federation-security/index.ts +151 -318
  158. package/src/backend-federation-security/node.ts +24 -22
  159. package/src/bff-policy/crossProjectPolicy.ts +754 -0
  160. package/src/bff-policy/index.ts +2 -0
  161. package/src/bff-policy/node.ts +3 -0
  162. package/src/bff-policy/operationContracts.ts +225 -0
  163. package/src/bff-policy/operationIdentity.ts +90 -0
  164. package/src/bff-policy/producer.ts +40 -0
  165. package/src/bff-policy/resolveCrossProjectPolicy.ts +88 -0
  166. package/src/contract-gate-snapshot-store/http-store.ts +1 -11
  167. package/src/contract-gate-snapshot-store/resolve.ts +0 -1
  168. package/src/errorResponsePlugin.ts +21 -0
  169. package/src/index.ts +4 -0
  170. package/src/localisedLoader.ts +50 -0
  171. package/src/localisedLoaderPlugin.ts +33 -0
  172. package/src/mfCache.ts +4 -3
  173. package/src/module-federation-css/plugin.ts +4 -3
  174. package/src/module-federation-css/remote.ts +3 -1
  175. package/src/serverConfig.ts +32 -0
  176. package/src/serverPlugin.ts +38 -0
  177. package/src/static-serving/plugin.ts +16 -0
  178. package/src/static-serving/responders.ts +208 -0
  179. package/src/static-serving/staticModuleFederation.ts +255 -0
  180. package/src/static-serving/staticPrecompressed.ts +193 -0
  181. package/src/telemetry/exporters.ts +1 -1
  182. package/src/telemetry/healthSetup.ts +17 -20
  183. package/src/telemetry/lifecycle.ts +27 -39
  184. package/src/telemetry/plugin.ts +6 -4
  185. package/src/telemetry/runtimeEndpoints.ts +3 -2
  186. package/src/telemetryCore.ts +1 -1
  187. package/tests/backendFederationSecurity.test.ts +63 -0
  188. package/tests/bff-policy/crossProjectPolicy.matrix.test.ts +450 -0
  189. package/tests/bff-policy/crossProjectPolicy.test.ts +197 -0
  190. package/tests/bff-policy/operationContracts.test.ts +278 -0
  191. package/tests/bff-policy/optionalZodPeer.test.ts +30 -0
  192. package/tests/bff-policy/resolveCrossProjectPolicy.test.ts +76 -0
  193. package/tests/bff-policy/zodEvaluatorProbe.test.ts +49 -0
  194. package/tests/contractGateSnapshotObserver.test.ts +0 -58
  195. package/tests/contractGateSnapshotStore.test.ts +0 -51
  196. package/tests/env.test.ts +45 -64
  197. package/tests/localisedLoader.test.ts +155 -0
  198. package/tests/mfCache.test.ts +1 -88
  199. package/tests/moduleFederationCss.test.ts +98 -41
  200. package/tests/nativeErrorResponse.test.ts +118 -0
  201. package/tests/nativeServerAssembly.test.ts +385 -0
  202. package/tests/runtimeLifecycle.test.ts +69 -17
  203. package/tests/static-serving/ordering.test.ts +214 -0
  204. package/tests/static-serving/static.test.ts +411 -0
  205. package/tests/telemetry.test.ts +35 -198
  206. package/tests/telemetryHealthMonitor.test.ts +0 -4
  207. package/tests/telemetryHealthObservation.test.ts +302 -0
  208. package/tests/telemetryLifecycle.test.ts +7 -303
  209. package/tests/telemetryRegistryQueueMatrix.test.ts +14 -111
  210. package/tests/registration.test.ts +0 -112
  211. package/tests/telemetryAutopilot.test.ts +0 -1134
@@ -0,0 +1,2 @@
1
+ export * from './crossProjectPolicy';
2
+ export * from './operationIdentity';
@@ -0,0 +1,3 @@
1
+ export * from './operationContracts';
2
+ export { resolveOperationProducer } from './producer';
3
+ export * from './resolveCrossProjectPolicy';
@@ -0,0 +1,225 @@
1
+ import { createRequire } from 'node:module';
2
+ import { createHash } from 'crypto';
3
+ import 'reflect-metadata';
4
+
5
+ // Structural handler protocol; native operators retain ownership of metadata.
6
+ type ApiHandler = (...args: any) => any | Promise<any>;
7
+
8
+ import {
9
+ DEFAULT_OPERATION_VERSION,
10
+ type OperationContractDefinition,
11
+ type OperationContractEntry,
12
+ type OperationContractHashInput,
13
+ type OperationContractMap,
14
+ serializeOperationContract,
15
+ stableOperationStringify,
16
+ } from './operationIdentity';
17
+
18
+ export * from './operationIdentity';
19
+
20
+ const sha256 = (text: string) =>
21
+ createHash('sha256').update(text).digest('hex');
22
+
23
+ type ZodToJSONSchema = (schema: unknown, options?: unknown) => unknown;
24
+
25
+ let cachedZodToJSONSchema: ZodToJSONSchema | null | undefined;
26
+
27
+ // FORK: the specifier is assembled at runtime so the bundler cannot see it.
28
+ // A literal require of the zod specifier here is externalized by rslib/rspack
29
+ // into a TOP-LEVEL static import of it in the esm-node output, which makes
30
+ // this OPTIONAL peer a hard runtime requirement: every consumer of
31
+ // this Node policy entry (and its BFF consumers) crashed with
32
+ // ERR_MODULE_NOT_FOUND: zod unless they happened to install zod.
33
+ // Guard: tests/bff-policy/optionalZodPeer.test.ts. Keep the lazy lookup.
34
+ const ZOD_SPECIFIER = ['z', 'o', 'd'].join('');
35
+
36
+ const resolveZodToJSONSchema = (): ZodToJSONSchema | null => {
37
+ if (typeof cachedZodToJSONSchema !== 'undefined') {
38
+ return cachedZodToJSONSchema;
39
+ }
40
+ try {
41
+ // zod is an optional peer dependency: schema serialization degrades to a
42
+ // route-identity hash when it is absent.
43
+ const load = createRequire(
44
+ typeof __filename === 'string' ? __filename : import.meta.url,
45
+ );
46
+ const zod = load(ZOD_SPECIFIER) as Record<string, unknown> & {
47
+ z?: Record<string, unknown>;
48
+ };
49
+ const candidate = zod?.toJSONSchema ?? zod?.z?.toJSONSchema;
50
+ cachedZodToJSONSchema =
51
+ typeof candidate === 'function' ? (candidate as ZodToJSONSchema) : null;
52
+ } catch {
53
+ cachedZodToJSONSchema = null;
54
+ }
55
+ return cachedZodToJSONSchema;
56
+ };
57
+
58
+ const INPUT_SCHEMA_METADATA_KEYS = [
59
+ 'DATA',
60
+ 'QUERY',
61
+ 'PARAMS',
62
+ 'HEADERS',
63
+ 'Files',
64
+ ] as const;
65
+
66
+ const serializeSchema = (schema: unknown): unknown => {
67
+ const toJSONSchema = resolveZodToJSONSchema();
68
+ if (toJSONSchema) {
69
+ try {
70
+ return toJSONSchema(schema, { io: 'input', unrepresentable: 'any' });
71
+ } catch {
72
+ // fall through to the opaque marker below
73
+ }
74
+ }
75
+ // The schema cannot be serialized (non-zod schema, exotic zod type or zod
76
+ // not installed). Contribute a stable marker so the hash still reflects
77
+ // that *a* schema constraint exists on this slot.
78
+ return { __unserializableSchema: true };
79
+ };
80
+
81
+ /**
82
+ * Serializes the zod input schemas attached to an operator-decorated handler
83
+ * (`Data`/`Query`/`Params`/`Headers`/`Upload` metadata) into JSON-schema
84
+ * documents. Returns `undefined` for handlers without schema metadata
85
+ * (plain handlers, farrow schema-mode handlers).
86
+ */
87
+ export const serializeOperationSchemas = (
88
+ handler: ApiHandler | undefined,
89
+ ): Record<string, unknown> | undefined => {
90
+ if (typeof handler !== 'function') {
91
+ return undefined;
92
+ }
93
+ const serialized: Record<string, unknown> = {};
94
+ for (const metadataKey of INPUT_SCHEMA_METADATA_KEYS) {
95
+ let schema: unknown;
96
+ try {
97
+ schema = Reflect.getMetadata(metadataKey, handler);
98
+ } catch {
99
+ schema = undefined;
100
+ }
101
+ if (typeof schema === 'undefined' || schema === null) {
102
+ continue;
103
+ }
104
+ serialized[metadataKey] = serializeSchema(schema);
105
+ }
106
+ return Object.keys(serialized).length > 0 ? serialized : undefined;
107
+ };
108
+
109
+ export const createOperationContractHash = (
110
+ operation: OperationContractHashInput,
111
+ requestId: string,
112
+ ): string => sha256(serializeOperationContract(operation, requestId));
113
+
114
+ export const createOperationEntries = (
115
+ handlers: Array<{
116
+ name: string;
117
+ httpMethod: string;
118
+ routePath: string;
119
+ }>,
120
+ ): OperationContractEntry[] =>
121
+ handlers
122
+ .map(item => ({
123
+ name: item.name,
124
+ httpMethod: String(item.httpMethod || '').toUpperCase(),
125
+ routePath: item.routePath,
126
+ }))
127
+ .sort((a, b) => {
128
+ const keyA = `${a.routePath}:${a.httpMethod}:${a.name}`;
129
+ const keyB = `${b.routePath}:${b.httpMethod}:${b.name}`;
130
+ return keyA.localeCompare(keyB);
131
+ });
132
+
133
+ /**
134
+ * Aggregate hash over a set of per-operation contract hashes. Used for the
135
+ * module-level `operationSchemaHash` manifest export; stable across route
136
+ * reordering because the per-operation hashes are sorted before hashing.
137
+ */
138
+ export const createOperationSchemaHash = (
139
+ operationEntries: Array<OperationContractEntry & { schemaHash?: string }>,
140
+ requestId: string,
141
+ ): string =>
142
+ sha256(
143
+ stableOperationStringify({
144
+ operations: [...operationEntries]
145
+ .map(item => ({
146
+ hash:
147
+ item.schemaHash ??
148
+ createOperationContractHash(
149
+ {
150
+ name: item.name,
151
+ httpMethod: item.httpMethod,
152
+ routePath: item.routePath,
153
+ },
154
+ requestId,
155
+ ),
156
+ }))
157
+ .sort((a, b) => a.hash.localeCompare(b.hash)),
158
+ requestId,
159
+ }),
160
+ );
161
+
162
+ export type OperationContractSource = {
163
+ name: string;
164
+ httpMethod: string;
165
+ routePath: string;
166
+ filename?: string;
167
+ /**
168
+ * Optional handler function used to serialize schema metadata. Sources
169
+ * without a handler (e.g. reflected Effect HttpApi endpoints) hash the
170
+ * route identity only.
171
+ */
172
+ handler?: ApiHandler;
173
+ };
174
+
175
+ export const buildOperationContractMap = ({
176
+ handlers,
177
+ requestId,
178
+ operationVersion,
179
+ }: {
180
+ handlers: OperationContractSource[];
181
+ requestId?: string;
182
+ /**
183
+ * Producer contract version, usually `deriveOperationVersion(pkg.version)`.
184
+ * Defaults to {@link DEFAULT_OPERATION_VERSION}.
185
+ */
186
+ operationVersion?: number;
187
+ }): OperationContractMap => {
188
+ const normalizedRequestId =
189
+ typeof requestId === 'string' && requestId.trim().length > 0
190
+ ? requestId.trim()
191
+ : 'default';
192
+ const normalizedOperationVersion =
193
+ typeof operationVersion === 'number' && Number.isInteger(operationVersion)
194
+ ? operationVersion
195
+ : DEFAULT_OPERATION_VERSION;
196
+
197
+ const contracts: OperationContractMap = {};
198
+ handlers.forEach(item => {
199
+ const httpMethod = String(item.httpMethod || '').toUpperCase();
200
+ const schemaHash = createOperationContractHash(
201
+ {
202
+ name: item.name,
203
+ httpMethod,
204
+ routePath: item.routePath,
205
+ schemas: serializeOperationSchemas(item.handler),
206
+ },
207
+ normalizedRequestId,
208
+ );
209
+ const operationId = `${normalizedRequestId}:${item.name}`;
210
+ const contract: OperationContractDefinition = {
211
+ requestId: normalizedRequestId,
212
+ operationVersion: normalizedOperationVersion,
213
+ schemaHash,
214
+ method: httpMethod,
215
+ routePath: item.routePath,
216
+ operationId,
217
+ handlerName: item.name,
218
+ filename: item.filename,
219
+ };
220
+ contracts[`${httpMethod}:${item.routePath}`] = contract;
221
+ contracts[`operation:${operationId}`] = contract;
222
+ });
223
+
224
+ return contracts;
225
+ };
@@ -0,0 +1,90 @@
1
+ export type OperationContractEntry = {
2
+ name: string;
3
+ httpMethod: string;
4
+ routePath: string;
5
+ };
6
+
7
+ export type OperationContractDefinition = {
8
+ requestId: string;
9
+ operationVersion: number;
10
+ schemaHash: string;
11
+ method: string;
12
+ routePath: string;
13
+ operationId: string;
14
+ handlerName: string;
15
+ filename?: string;
16
+ };
17
+
18
+ export type OperationContractMap = Record<string, OperationContractDefinition>;
19
+
20
+ export const DEFAULT_OPERATION_VERSION = 1;
21
+
22
+ /**
23
+ * Derives the operation version from a producer package version: the semver
24
+ * major is the contract version, so consumers regenerated against an older
25
+ * producer major fail the `operation_version_mismatch` gate instead of
26
+ * silently calling an incompatible API.
27
+ *
28
+ * Falls back to {@link DEFAULT_OPERATION_VERSION} when no parseable version
29
+ * is available.
30
+ */
31
+ export const deriveOperationVersion = (packageVersion?: unknown): number => {
32
+ if (typeof packageVersion !== 'string') {
33
+ return DEFAULT_OPERATION_VERSION;
34
+ }
35
+ const match = packageVersion.trim().match(/^v?(\d+)\./);
36
+ if (!match) {
37
+ return DEFAULT_OPERATION_VERSION;
38
+ }
39
+ const major = Number.parseInt(match[1]!, 10);
40
+ return Number.isInteger(major) && major >= 0
41
+ ? major
42
+ : DEFAULT_OPERATION_VERSION;
43
+ };
44
+
45
+ /** JSON.stringify with recursively sorted object keys for stable hashing. */
46
+ export const stableOperationStringify = (value: unknown): string => {
47
+ if (Array.isArray(value)) {
48
+ return `[${value.map(item => stableOperationStringify(item)).join(',')}]`;
49
+ }
50
+ if (value && typeof value === 'object') {
51
+ const entries = Object.entries(value as Record<string, unknown>)
52
+ .filter(([, entryValue]) => typeof entryValue !== 'undefined')
53
+ .sort(([a], [b]) => a.localeCompare(b))
54
+ .map(
55
+ ([key, entryValue]) =>
56
+ `${JSON.stringify(key)}:${stableOperationStringify(entryValue)}`,
57
+ );
58
+ return `{${entries.join(',')}}`;
59
+ }
60
+ return JSON.stringify(value) ?? 'null';
61
+ };
62
+
63
+ export type OperationContractHashInput = OperationContractEntry & {
64
+ schemas?: Record<string, unknown>;
65
+ };
66
+
67
+ export const serializeOperationContract = (
68
+ operation: OperationContractHashInput,
69
+ requestId: string,
70
+ ): string =>
71
+ stableOperationStringify({
72
+ httpMethod: String(operation.httpMethod || '').toUpperCase(),
73
+ name: operation.name,
74
+ requestId,
75
+ routePath: operation.routePath,
76
+ ...(operation.schemas ? { schemas: operation.schemas } : {}),
77
+ });
78
+
79
+ export async function digestOperationContract(
80
+ operation: OperationContractHashInput,
81
+ requestId: string,
82
+ ): Promise<string> {
83
+ const digest = await globalThis.crypto.subtle.digest(
84
+ 'SHA-256',
85
+ new TextEncoder().encode(serializeOperationContract(operation, requestId)),
86
+ );
87
+ return Array.from(new Uint8Array(digest), value =>
88
+ value.toString(16).padStart(2, '0'),
89
+ ).join('');
90
+ }
@@ -0,0 +1,40 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { deriveOperationVersion } from './operationIdentity';
4
+
5
+ /** Resolve the owning package once. Never borrow an ancestor's version when
6
+ * the producer has an absent or invalid version of its own. */
7
+ export function resolveOperationProducer(options: {
8
+ directories: Array<string | undefined>;
9
+ requestId?: string;
10
+ onDependency?: (filename: string) => void;
11
+ }) {
12
+ for (const directory of options.directories) {
13
+ if (!directory) continue;
14
+ let current = path.resolve(directory);
15
+ while (true) {
16
+ const filename = path.join(current, 'package.json');
17
+ if (existsSync(filename)) {
18
+ options.onDependency?.(filename);
19
+ let metadata: { name?: unknown; version?: unknown } = {};
20
+ try {
21
+ metadata = JSON.parse(readFileSync(filename, 'utf8')) ?? {};
22
+ } catch {}
23
+ return {
24
+ requestId:
25
+ options.requestId?.trim() ||
26
+ (typeof metadata.name === 'string' && metadata.name.trim()) ||
27
+ 'default',
28
+ operationVersion: deriveOperationVersion(metadata.version),
29
+ };
30
+ }
31
+ const parent = path.dirname(current);
32
+ if (parent === current) break;
33
+ current = parent;
34
+ }
35
+ }
36
+ return {
37
+ requestId: options.requestId?.trim() || 'default',
38
+ operationVersion: deriveOperationVersion(),
39
+ };
40
+ }
@@ -0,0 +1,88 @@
1
+ import type {
2
+ CrossProjectPolicyConfig,
3
+ NormalizedCrossProjectPolicy,
4
+ } from './crossProjectPolicy';
5
+ import {
6
+ buildOperationContractMap,
7
+ type OperationContractSource,
8
+ } from './operationContracts';
9
+
10
+ /**
11
+ * Runtime input collected by BFF server adapters (hono/effect/...) before
12
+ * the cross-project policy can be enforced.
13
+ *
14
+ * `crossProjectPolicy` accepts the raw `bff.crossProjectPolicy` user config —
15
+ * `BffCrossProjectPolicyUserConfig` is a structural subset of
16
+ * `CrossProjectPolicyConfig`, so no casts are required at the call site.
17
+ */
18
+ export interface ResolveCrossProjectPolicyInput {
19
+ crossProjectPolicy?: CrossProjectPolicyConfig;
20
+ /** Registered API handlers used to derive the operation-contract map. */
21
+ handlers: OperationContractSource[];
22
+ /** Logical producer ID (`bff.requestId`). */
23
+ requestId?: string;
24
+ /** Marker injected by generated cross-project SDK plugins. */
25
+ isCrossProjectServer?: boolean;
26
+ /**
27
+ * Producer contract version (usually derived from the producer
28
+ * package.json major via `deriveOperationVersion`).
29
+ */
30
+ operationVersion?: number;
31
+ }
32
+
33
+ /**
34
+ * Fully-defaulted policy returned by {@link resolveCrossProjectPolicy}.
35
+ */
36
+ export type ResolvedCrossProjectPolicy = NormalizedCrossProjectPolicy;
37
+
38
+ /**
39
+ * Normalizes the user-facing cross-project policy config into the evaluator
40
+ * input shared by every BFF server adapter:
41
+ *
42
+ * - returns `undefined` when neither a policy nor the cross-project server
43
+ * marker is present (policy middleware must not be installed);
44
+ * - applies the documented defaults for all `require*` switches;
45
+ * - merges generated operation contracts (derived from the registered
46
+ * handlers) over any user-provided `expectedOperationContracts`.
47
+ */
48
+ export const resolveCrossProjectPolicy = (
49
+ input: ResolveCrossProjectPolicyInput,
50
+ ): ResolvedCrossProjectPolicy | undefined => {
51
+ const {
52
+ crossProjectPolicy,
53
+ handlers,
54
+ requestId,
55
+ isCrossProjectServer,
56
+ operationVersion,
57
+ } = input;
58
+ if (!crossProjectPolicy && !isCrossProjectServer) {
59
+ return undefined;
60
+ }
61
+
62
+ const policy: CrossProjectPolicyConfig = crossProjectPolicy ?? {};
63
+ const effectiveRequestId =
64
+ typeof requestId === 'string' && requestId.trim().length > 0
65
+ ? requestId
66
+ : 'default';
67
+ const generatedContracts = buildOperationContractMap({
68
+ handlers,
69
+ requestId: effectiveRequestId,
70
+ operationVersion,
71
+ });
72
+
73
+ return {
74
+ ...policy,
75
+ enabled: policy.enabled ?? Boolean(isCrossProjectServer),
76
+ requireEnvelope: policy.requireEnvelope ?? true,
77
+ requireOperationContext: policy.requireOperationContext ?? true,
78
+ requireOperationContextDetails:
79
+ policy.requireOperationContextDetails ?? true,
80
+ requireOperationSchemaHash: policy.requireOperationSchemaHash ?? true,
81
+ requireOperationVersion: policy.requireOperationVersion ?? true,
82
+ allowUnknownOperations: policy.allowUnknownOperations ?? false,
83
+ expectedOperationContracts: {
84
+ ...(policy.expectedOperationContracts ?? {}),
85
+ ...generatedContracts,
86
+ },
87
+ };
88
+ };
@@ -8,16 +8,6 @@ import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from './types';
8
8
 
9
9
  const DEFAULT_HTTP_STORE_TIMEOUT_MS = 5_000;
10
10
 
11
- const BUILTIN_HTTP_STATE_STORE_MODULES = new Set([
12
- 'http',
13
- // historical aliases kept for config compatibility with the era when these
14
- // modules lived inside @modern-js/server-core.
15
- '@modern-js/server-core/http',
16
- '@modern-js/server-core/contract-gate-http-store',
17
- '@modern-js/server-runtime-extensions/http',
18
- '@modern-js/server-runtime-extensions/contract-gate-http-store',
19
- ]);
20
-
21
11
  const normalizeHttpStoreOptions = (
22
12
  options: Record<string, unknown> | undefined,
23
13
  ): ContractGateSnapshotHttpStoreOptions => {
@@ -149,7 +139,7 @@ export const tryResolveBuiltinSnapshotStore = (input: {
149
139
  stateStore: ContractGateSnapshotStoreUserConfig;
150
140
  }): ContractGateSnapshotStore | undefined => {
151
141
  const moduleName = input.stateStore.module.trim();
152
- if (!BUILTIN_HTTP_STATE_STORE_MODULES.has(moduleName)) {
142
+ if (moduleName !== 'http') {
153
143
  return undefined;
154
144
  }
155
145
 
@@ -9,7 +9,6 @@ import { tryResolveBuiltinSnapshotStore } from './http-store';
9
9
  import type {
10
10
  ContractGateSnapshotStore,
11
11
  ContractGateSnapshotStoreFactory,
12
- ContractGateSnapshotStoreFactoryContext,
13
12
  ContractGateSnapshotStoreModule,
14
13
  ContractGateSnapshotStoreUserConfig,
15
14
  GateSnapshot,
@@ -0,0 +1,21 @@
1
+ import { createSafeJsonFailureResponse } from '@modern-js/runtime-extensions/safe-failure';
2
+ import type { ServerPlugin } from '@modern-js/server-core';
3
+
4
+ /** Serialize unhandled BFF failures using the fork's public error contract. */
5
+ export const injectErrorResponsePlugin = (): ServerPlugin => ({
6
+ name: '@modern-js/safe-error-response',
7
+ setup(api) {
8
+ api.handleError(async (input, next) => {
9
+ const prefix = api.getServerConfig().bff?.prefix || '/api';
10
+ const prefixes = Array.isArray(prefix) ? prefix : [prefix];
11
+ if (prefixes.some(value => input.context.req.path.startsWith(value))) {
12
+ return {
13
+ ...input,
14
+ response: createSafeJsonFailureResponse(input.error),
15
+ };
16
+ }
17
+ next?.(input);
18
+ return input;
19
+ });
20
+ },
21
+ });
package/src/index.ts CHANGED
@@ -56,6 +56,10 @@ export {
56
56
  registerServerRuntimeDisposer,
57
57
  type ServerRuntimeHandle,
58
58
  } from './runtimeLifecycle';
59
+ export type {
60
+ UltramodernBffUserConfig,
61
+ UltramodernServerUserConfig,
62
+ } from './serverConfig';
59
63
  export {
60
64
  createOtlpTelemetryExporter,
61
65
  createRuntimeFallbackSignalRuntimeState,
@@ -0,0 +1,50 @@
1
+ import type { LoaderRouteIdResolver } from '@modern-js/plugin-data-loader/runtime';
2
+ import { resolveLocalisedLoaderRouteId } from '@modern-js/runtime-extensions/localised-loader-identity';
3
+ import { applyLocalisedUrlsToRoutes } from '@modern-js/runtime-extensions/localised-urls';
4
+ import type { ServerLoaderBundle } from '@modern-js/server-core';
5
+
6
+ type LoaderRoutes = ServerLoaderBundle['routes'];
7
+
8
+ /**
9
+ * Project canonical-only localized routes so loader matching sees every
10
+ * localized URL. Routes already emitted as physical localized aliases are
11
+ * returned unchanged.
12
+ *
13
+ * Runtime-neutral: shared by the Node server plugin and the Cloudflare worker
14
+ * route data handler.
15
+ */
16
+ export function expandLocalisedLoaderRoutes(
17
+ routes: LoaderRoutes,
18
+ ): LoaderRoutes {
19
+ const languages = new Set<string>();
20
+ const localisedUrls: Record<string, Record<string, string>> = {};
21
+ let physical = false;
22
+ const visit = (nodes: LoaderRoutes) => {
23
+ for (const route of nodes) {
24
+ physical ||= 'modernCanonicalPath' in route;
25
+ const identity = Reflect.get(route, 'modernLocalisedRoute') as
26
+ | { canonicalPath: string; paths?: Record<string, string> }
27
+ | undefined;
28
+ if (identity?.paths) {
29
+ localisedUrls[identity.canonicalPath] = identity.paths;
30
+ for (const language of Object.keys(identity.paths))
31
+ languages.add(language);
32
+ }
33
+ if ('children' in route && route.children) visit(route.children);
34
+ }
35
+ };
36
+ visit(routes);
37
+ return physical || languages.size === 0
38
+ ? routes
39
+ : (applyLocalisedUrlsToRoutes(
40
+ routes,
41
+ [...languages],
42
+ localisedUrls,
43
+ ) as LoaderRoutes);
44
+ }
45
+
46
+ /** Resolve a canonical loader route ID to the localized alias matched by the URL. */
47
+ export const resolveLocalisedLoaderRoute: LoaderRouteIdResolver = (
48
+ requestedRouteId,
49
+ { routes, matchedRouteIds },
50
+ ) => resolveLocalisedLoaderRouteId(routes, requestedRouteId, matchedRouteIds);
@@ -0,0 +1,33 @@
1
+ import { setLoaderRouteIdResolver } from '@modern-js/plugin-data-loader/runtime';
2
+ import {
3
+ getLoaderCtx,
4
+ type MiddlewareHandler,
5
+ type ServerPlugin,
6
+ } from '@modern-js/server-core';
7
+ import {
8
+ expandLocalisedLoaderRoutes,
9
+ resolveLocalisedLoaderRoute,
10
+ } from './localisedLoader';
11
+
12
+ export function injectLocalisedLoaderPlugin(): ServerPlugin {
13
+ return {
14
+ name: '@modern-js/localised-loader',
15
+ setup(api) {
16
+ const handler: MiddlewareHandler = async (context, next) => {
17
+ setLoaderRouteIdResolver(
18
+ getLoaderCtx(context),
19
+ resolveLocalisedLoaderRoute,
20
+ expandLocalisedLoaderRoutes,
21
+ );
22
+ await next();
23
+ };
24
+ api.onPrepare(() => {
25
+ api.getServerContext().middlewares.push({
26
+ name: 'localised-loader-route-id',
27
+ before: ['render'],
28
+ handler,
29
+ });
30
+ });
31
+ },
32
+ };
33
+ }
package/src/mfCache.ts CHANGED
@@ -81,12 +81,13 @@ export function resolveMfAssetCacheHeaders(
81
81
  * - `remoteEntry*.js` revalidates unless explicitly version-pinned via a
82
82
  * `mfv`/`v`/`version` query parameter, in which case it is immutable.
83
83
  *
84
- * Registered by @modern-js/prod-server next to the other fork plugins; the
85
- * middleware runs in the `pre` phase so it wraps the static-file middleware
86
- * that actually serves these assets.
84
+ * Composed with the other fork server plugins. The middleware runs in the
85
+ * `pre` phase so it wraps the static-file middleware serving these assets.
87
86
  */
88
87
  export const injectMfAssetCacheHeadersPlugin = (): ServerPlugin => ({
89
88
  name: '@modern-js/inject-mf-asset-cache-headers',
89
+ pre: ['@modern-js/inject-module-federation-css'],
90
+ post: ['@modern-js/plugin-inject-rsc-manifest'],
90
91
 
91
92
  setup(api) {
92
93
  api.onPrepare(() => {
@@ -29,14 +29,15 @@ export type ModuleFederationCssPluginOptions = {
29
29
  * being pinned at boot: remote manifests change on every remote redeploy, and
30
30
  * fetch failures must not pin an empty/partial list for the process lifetime.
31
31
  *
32
- * This plugin must be registered after `injectResourcePlugin()` (which sets
33
- * `serverManifest` on the request context). @modern-js/prod-server wires it
34
- * into its plugin assembly for both production and dev servers.
32
+ * Existing plugin ordering places this after the native resource plugin
33
+ * (which sets `serverManifest`) and before the native RSC manifest plugin.
35
34
  */
36
35
  export const injectModuleFederationCssPlugin = (
37
36
  options: ModuleFederationCssPluginOptions = {},
38
37
  ): ServerPlugin => ({
39
38
  name: '@modern-js/inject-module-federation-css',
39
+ pre: ['@modern-js/plugin-inject-resource'],
40
+ post: ['@modern-js/plugin-inject-rsc-manifest'],
40
41
 
41
42
  setup(api) {
42
43
  api.onPrepare(() => {
@@ -15,6 +15,8 @@ type FetchLike = (
15
15
  input: string,
16
16
  init?: {
17
17
  signal?: AbortSignal;
18
+ /** Trusted fetchers must honor this: reject instead of following a redirect. */
19
+ redirect?: 'error';
18
20
  },
19
21
  ) => Promise<Response>;
20
22
 
@@ -34,7 +36,7 @@ const fetchJsonWithTimeout = async (
34
36
 
35
37
  try {
36
38
  const response = await Promise.race([
37
- fetcher(url, { signal: controller.signal }),
39
+ fetcher(url, { signal: controller.signal, redirect: 'error' }),
38
40
  new Promise<Response>((_, reject) => {
39
41
  timeoutId = setTimeout(() => {
40
42
  controller.abort();