@bleedingdev/modern-js-server-runtime-extensions 3.5.0-ultramodern.5 → 3.5.0-ultramodern.75

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 (179) hide show
  1. package/dist/cjs/contract-gate-snapshot-normalization.js +122 -0
  2. package/dist/cjs/contract-gate-snapshot-store/file-store.js +102 -0
  3. package/dist/cjs/contract-gate-snapshot-store/http-store.js +133 -0
  4. package/dist/cjs/contract-gate-snapshot-store/index.js +58 -0
  5. package/dist/cjs/contract-gate-snapshot-store/resolve.js +124 -0
  6. package/dist/cjs/contract-gate-snapshot-store/types.js +44 -0
  7. package/dist/cjs/contractGateAutopilot.js +22 -70
  8. package/dist/cjs/index.js +6 -25
  9. package/dist/cjs/mfCache.js +2 -2
  10. package/dist/cjs/module-federation-css/collector.js +79 -0
  11. package/dist/cjs/module-federation-css/index.js +55 -0
  12. package/dist/cjs/module-federation-css/manifest.js +129 -0
  13. package/dist/cjs/module-federation-css/plugin.js +71 -0
  14. package/dist/cjs/module-federation-css/remote.js +133 -0
  15. package/dist/cjs/runtime-fallback-signal/index.js +93 -0
  16. package/dist/cjs/runtime-fallback-signal/model.js +157 -0
  17. package/dist/cjs/runtime-fallback-signal/resolver.js +163 -0
  18. package/dist/cjs/runtime-fallback-signal/store.js +83 -0
  19. package/dist/cjs/runtimeFallbackSignal.js +32 -281
  20. package/dist/cjs/telemetry/canary.js +180 -0
  21. package/dist/cjs/telemetry/canaryEvaluation.js +79 -0
  22. package/dist/cjs/telemetry/canarySetup.js +107 -0
  23. package/dist/cjs/telemetry/envelope.js +223 -0
  24. package/dist/cjs/telemetry/exporters.js +148 -0
  25. package/dist/cjs/telemetry/lifecycle.js +98 -0
  26. package/dist/cjs/telemetry/metrics.js +115 -0
  27. package/dist/cjs/telemetry/plugin.js +185 -0
  28. package/dist/cjs/telemetry/registry.js +296 -0
  29. package/dist/cjs/telemetry/registryTypes.js +46 -0
  30. package/dist/cjs/telemetry/runtimeEndpoints.js +135 -0
  31. package/dist/cjs/telemetry.js +32 -343
  32. package/dist/cjs/telemetryCore.js +14 -767
  33. package/dist/esm/contract-gate-snapshot-normalization.mjs +81 -0
  34. package/dist/esm/contract-gate-snapshot-store/file-store.mjs +51 -0
  35. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +92 -0
  36. package/dist/esm/contract-gate-snapshot-store/index.mjs +4 -0
  37. package/dist/esm/contract-gate-snapshot-store/resolve.mjs +70 -0
  38. package/dist/esm/contract-gate-snapshot-store/types.mjs +3 -0
  39. package/dist/esm/contractGateAutopilot.mjs +21 -69
  40. package/dist/esm/index.mjs +1 -2
  41. package/dist/esm/mfCache.mjs +2 -2
  42. package/dist/esm/module-federation-css/collector.mjs +38 -0
  43. package/dist/esm/module-federation-css/index.mjs +4 -0
  44. package/dist/esm/module-federation-css/manifest.mjs +69 -0
  45. package/dist/esm/module-federation-css/plugin.mjs +33 -0
  46. package/dist/esm/module-federation-css/remote.mjs +92 -0
  47. package/dist/esm/runtime-fallback-signal/index.mjs +3 -0
  48. package/dist/esm/runtime-fallback-signal/model.mjs +73 -0
  49. package/dist/esm/runtime-fallback-signal/resolver.mjs +107 -0
  50. package/dist/esm/runtime-fallback-signal/store.mjs +39 -0
  51. package/dist/esm/runtimeFallbackSignal.mjs +1 -222
  52. package/dist/esm/telemetry/canary.mjs +142 -0
  53. package/dist/esm/telemetry/canaryEvaluation.mjs +41 -0
  54. package/dist/esm/telemetry/canarySetup.mjs +69 -0
  55. package/dist/esm/telemetry/envelope.mjs +164 -0
  56. package/dist/esm/telemetry/exporters.mjs +104 -0
  57. package/dist/esm/telemetry/lifecycle.mjs +60 -0
  58. package/dist/esm/telemetry/metrics.mjs +77 -0
  59. package/dist/esm/telemetry/plugin.mjs +87 -0
  60. package/dist/esm/telemetry/registry.mjs +258 -0
  61. package/dist/esm/telemetry/registryTypes.mjs +8 -0
  62. package/dist/esm/telemetry/runtimeEndpoints.mjs +94 -0
  63. package/dist/esm/telemetry.mjs +1 -275
  64. package/dist/esm/telemetryCore.mjs +6 -759
  65. package/dist/esm-node/contract-gate-snapshot-normalization.mjs +82 -0
  66. package/dist/esm-node/contract-gate-snapshot-store/file-store.mjs +52 -0
  67. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +93 -0
  68. package/dist/esm-node/contract-gate-snapshot-store/index.mjs +5 -0
  69. package/dist/esm-node/contract-gate-snapshot-store/resolve.mjs +71 -0
  70. package/dist/esm-node/contract-gate-snapshot-store/types.mjs +4 -0
  71. package/dist/esm-node/contractGateAutopilot.mjs +21 -69
  72. package/dist/esm-node/index.mjs +1 -2
  73. package/dist/esm-node/mfCache.mjs +2 -2
  74. package/dist/esm-node/module-federation-css/collector.mjs +39 -0
  75. package/dist/esm-node/module-federation-css/index.mjs +5 -0
  76. package/dist/esm-node/module-federation-css/manifest.mjs +70 -0
  77. package/dist/esm-node/module-federation-css/plugin.mjs +34 -0
  78. package/dist/esm-node/module-federation-css/remote.mjs +93 -0
  79. package/dist/esm-node/runtime-fallback-signal/index.mjs +4 -0
  80. package/dist/esm-node/runtime-fallback-signal/model.mjs +74 -0
  81. package/dist/esm-node/runtime-fallback-signal/resolver.mjs +108 -0
  82. package/dist/esm-node/runtime-fallback-signal/store.mjs +40 -0
  83. package/dist/esm-node/runtimeFallbackSignal.mjs +1 -222
  84. package/dist/esm-node/telemetry/canary.mjs +143 -0
  85. package/dist/esm-node/telemetry/canaryEvaluation.mjs +42 -0
  86. package/dist/esm-node/telemetry/canarySetup.mjs +70 -0
  87. package/dist/esm-node/telemetry/envelope.mjs +165 -0
  88. package/dist/esm-node/telemetry/exporters.mjs +105 -0
  89. package/dist/esm-node/telemetry/lifecycle.mjs +61 -0
  90. package/dist/esm-node/telemetry/metrics.mjs +78 -0
  91. package/dist/esm-node/telemetry/plugin.mjs +88 -0
  92. package/dist/esm-node/telemetry/registry.mjs +259 -0
  93. package/dist/esm-node/telemetry/registryTypes.mjs +9 -0
  94. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +95 -0
  95. package/dist/esm-node/telemetry.mjs +1 -275
  96. package/dist/esm-node/telemetryCore.mjs +6 -759
  97. package/dist/types/contract-gate-snapshot-normalization.d.ts +15 -0
  98. package/dist/types/contract-gate-snapshot-store/file-store.d.ts +3 -0
  99. package/dist/types/contract-gate-snapshot-store/http-store.d.ts +5 -0
  100. package/dist/types/contract-gate-snapshot-store/index.d.ts +5 -0
  101. package/dist/types/contract-gate-snapshot-store/resolve.d.ts +9 -0
  102. package/dist/types/{contractGateSnapshotStore.d.ts → contract-gate-snapshot-store/types.d.ts} +1 -11
  103. package/dist/types/contractGateAutopilot.d.ts +3 -6
  104. package/dist/types/index.d.ts +1 -2
  105. package/dist/types/module-federation-css/collector.d.ts +25 -0
  106. package/dist/types/module-federation-css/index.d.ts +8 -0
  107. package/dist/types/module-federation-css/manifest.d.ts +28 -0
  108. package/dist/types/module-federation-css/plugin.d.ts +23 -0
  109. package/dist/types/module-federation-css/remote.d.ts +20 -0
  110. package/dist/types/runtime-fallback-signal/index.d.ts +4 -0
  111. package/dist/types/runtime-fallback-signal/model.d.ts +70 -0
  112. package/dist/types/runtime-fallback-signal/resolver.d.ts +29 -0
  113. package/dist/types/runtime-fallback-signal/store.d.ts +4 -0
  114. package/dist/types/runtimeFallbackSignal.d.ts +1 -94
  115. package/dist/types/telemetry/canary.d.ts +85 -0
  116. package/dist/types/telemetry/canaryEvaluation.d.ts +20 -0
  117. package/dist/types/telemetry/canarySetup.d.ts +17 -0
  118. package/dist/types/telemetry/envelope.d.ts +55 -0
  119. package/dist/types/telemetry/exporters.d.ts +12 -0
  120. package/dist/types/telemetry/lifecycle.d.ts +18 -0
  121. package/dist/types/telemetry/metrics.d.ts +3 -0
  122. package/dist/types/telemetry/plugin.d.ts +12 -0
  123. package/dist/types/telemetry/registry.d.ts +69 -0
  124. package/dist/types/telemetry/registryTypes.d.ts +50 -0
  125. package/dist/types/telemetry/runtimeEndpoints.d.ts +35 -0
  126. package/dist/types/telemetry.d.ts +1 -12
  127. package/dist/types/telemetryCore.d.ts +6 -257
  128. package/package.json +11 -13
  129. package/src/contract-gate-snapshot-normalization.ts +155 -0
  130. package/src/contract-gate-snapshot-store/file-store.ts +83 -0
  131. package/src/contract-gate-snapshot-store/http-store.ts +159 -0
  132. package/src/contract-gate-snapshot-store/index.ts +20 -0
  133. package/src/contract-gate-snapshot-store/resolve.ts +179 -0
  134. package/src/contract-gate-snapshot-store/types.ts +64 -0
  135. package/src/contractGateAutopilot.ts +39 -131
  136. package/src/index.ts +1 -17
  137. package/src/mfCache.ts +3 -1
  138. package/src/module-federation-css/collector.ts +82 -0
  139. package/src/module-federation-css/index.ts +14 -0
  140. package/src/module-federation-css/manifest.ts +163 -0
  141. package/src/module-federation-css/plugin.ts +86 -0
  142. package/src/module-federation-css/remote.ts +165 -0
  143. package/src/runtime-fallback-signal/index.ts +34 -0
  144. package/src/runtime-fallback-signal/model.ts +230 -0
  145. package/src/runtime-fallback-signal/resolver.ts +304 -0
  146. package/src/runtime-fallback-signal/store.ts +78 -0
  147. package/src/runtimeFallbackSignal.ts +1 -584
  148. package/src/telemetry/canary.ts +291 -0
  149. package/src/telemetry/canaryEvaluation.ts +83 -0
  150. package/src/telemetry/canarySetup.ts +160 -0
  151. package/src/telemetry/envelope.ts +277 -0
  152. package/src/telemetry/exporters.ts +165 -0
  153. package/src/telemetry/lifecycle.ts +138 -0
  154. package/src/telemetry/metrics.ts +141 -0
  155. package/src/telemetry/plugin.ts +197 -0
  156. package/src/telemetry/registry.ts +424 -0
  157. package/src/telemetry/registryTypes.ts +63 -0
  158. package/src/telemetry/runtimeEndpoints.ts +172 -0
  159. package/src/telemetry.ts +1 -554
  160. package/src/telemetryCore.ts +34 -1332
  161. package/tests/contractGateAutopilot.test.ts +205 -0
  162. package/tests/contractGateSnapshotStore.test.ts +54 -1
  163. package/tests/helpers.ts +1 -0
  164. package/tests/moduleFederationCss.test.ts +1 -1
  165. package/tests/registration.test.ts +1 -1
  166. package/tests/telemetry.test.ts +51 -0
  167. package/tests/telemetryAutopilot.test.ts +141 -0
  168. package/tests/telemetryCanaryOrchestrator.test.ts +225 -0
  169. package/tests/telemetryLifecycle.test.ts +253 -2
  170. package/tests/telemetryRegistryQueueMatrix.test.ts +227 -0
  171. package/dist/cjs/contractGateSnapshotStore.js +0 -253
  172. package/dist/cjs/moduleFederationCss.js +0 -285
  173. package/dist/esm/contractGateSnapshotStore.mjs +0 -190
  174. package/dist/esm/moduleFederationCss.mjs +0 -225
  175. package/dist/esm-node/contractGateSnapshotStore.mjs +0 -192
  176. package/dist/esm-node/moduleFederationCss.mjs +0 -226
  177. package/dist/types/moduleFederationCss.d.ts +0 -87
  178. package/src/contractGateSnapshotStore.ts +0 -420
  179. package/src/moduleFederationCss.ts +0 -473
@@ -1,87 +0,0 @@
1
- import type { ServerPlugin } from '@modern-js/server-core';
2
- import type { Monitors } from '@modern-js/types';
3
- type ModuleFederationAssets = {
4
- css?: {
5
- sync?: string[];
6
- async?: string[];
7
- };
8
- };
9
- export type ModuleFederationManifest = {
10
- metaData?: {
11
- publicPath?: string;
12
- };
13
- shared?: Array<{
14
- assets?: ModuleFederationAssets;
15
- }>;
16
- remotes?: Array<{
17
- entry?: string;
18
- assets?: ModuleFederationAssets;
19
- }>;
20
- exposes?: Array<{
21
- assets?: ModuleFederationAssets;
22
- }>;
23
- };
24
- type FetchLike = (input: string, init?: {
25
- signal?: AbortSignal;
26
- }) => Promise<Response>;
27
- export type CollectDirectRemoteModuleFederationCssOptions = {
28
- fetcher?: FetchLike;
29
- monitors?: Monitors;
30
- timeout?: number;
31
- };
32
- export declare const collectModuleFederationManifestCss: (manifest: ModuleFederationManifest, manifestUrl: string) => string[];
33
- export type RemoteModuleFederationCssCollection = {
34
- assets: string[];
35
- /**
36
- * True when at least one remote manifest fetch failed, i.e. `assets` may be
37
- * incomplete and should not be cached long-term.
38
- */
39
- errored: boolean;
40
- };
41
- export declare const collectDirectRemoteModuleFederationCssWithMeta: (pwd: string, options?: CollectDirectRemoteModuleFederationCssOptions) => Promise<RemoteModuleFederationCssCollection>;
42
- export declare const collectDirectRemoteModuleFederationCss: (pwd: string, options?: CollectDirectRemoteModuleFederationCssOptions) => Promise<string[]>;
43
- export type ModuleFederationCssCollectorOptions = CollectDirectRemoteModuleFederationCssOptions & {
44
- /**
45
- * How long a successful remote CSS collection may be served from cache.
46
- * `0` disables caching (beyond in-flight request coalescing).
47
- */
48
- ttlMs?: number;
49
- /** Clock override for tests. */
50
- now?: () => number;
51
- };
52
- /**
53
- * TTL cache around remote MF CSS collection. Remote manifests mutate
54
- * independently of the host (that is the point of module federation), so the
55
- * collection must expire: a boot-time-forever cache serves stale or broken
56
- * CSS links after any remote redeploy.
57
- *
58
- * Error handling: a collection where any remote fetch failed is never cached.
59
- * The last known-good asset list is served instead (stale-on-error) and the
60
- * next request retries the collection.
61
- */
62
- export declare const createModuleFederationCssCollector: (pwd: string, options?: ModuleFederationCssCollectorOptions) => {
63
- collect(monitors?: Monitors): Promise<string[]>;
64
- };
65
- export type ModuleFederationCssPluginOptions = {
66
- /**
67
- * TTL for the cached remote CSS collection in production.
68
- *
69
- * @default 30000 in production, 0 (no caching) otherwise
70
- */
71
- remoteCssCacheTtlMs?: number;
72
- };
73
- /**
74
- * Enriches the request-scoped server manifest with CSS assets collected from
75
- * direct module federation remotes, so SSR/CSR-RSC rendering can inline
76
- * `<link>` tags for remote CSS.
77
- *
78
- * In production the collection is cached with a TTL (default 30s) instead of
79
- * being pinned at boot: remote manifests change on every remote redeploy, and
80
- * fetch failures must not pin an empty/partial list for the process lifetime.
81
- *
82
- * This plugin must be registered after `injectResourcePlugin()` (which sets
83
- * `serverManifest` on the request context). @modern-js/prod-server wires it
84
- * into its plugin assembly for both production and dev servers.
85
- */
86
- export declare const injectModuleFederationCssPlugin: (options?: ModuleFederationCssPluginOptions) => ServerPlugin;
87
- export {};
@@ -1,420 +0,0 @@
1
- import { createRequire } from 'node:module';
2
- import { fs } from '@modern-js/utils';
3
- import { promises as nodeFs } from 'fs';
4
- import path from 'path';
5
- import { parseServerRuntimeExtensionsEnv } from './env';
6
-
7
- export const CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION = 1;
8
- export const DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH =
9
- '.modern/contract-gates.json';
10
-
11
- export type GateSnapshotGateValue =
12
- | boolean
13
- | {
14
- passed?: boolean;
15
- reason?: string;
16
- updatedAt?: number;
17
- expiresAt?: number;
18
- [key: string]: unknown;
19
- };
20
-
21
- export type GateSnapshot = {
22
- schemaVersion?: number;
23
- updatedAt?: number;
24
- gates?: Record<string, GateSnapshotGateValue>;
25
- };
26
-
27
- type LoggerLike = {
28
- info?: (message: string) => void;
29
- warn?: (message: string) => void;
30
- };
31
-
32
- export type ContractGateSnapshotStore = {
33
- name: string;
34
- readSnapshot: () => Promise<GateSnapshot | undefined>;
35
- writeSnapshot: (snapshot: GateSnapshot) => Promise<void>;
36
- };
37
-
38
- export type ContractGateSnapshotStoreFactoryContext = {
39
- appDirectory: string;
40
- gateSnapshotPath: string;
41
- options?: Record<string, unknown>;
42
- logger?: LoggerLike;
43
- };
44
-
45
- export type ContractGateSnapshotStoreFactory = (
46
- context: ContractGateSnapshotStoreFactoryContext,
47
- ) => Promise<ContractGateSnapshotStore> | ContractGateSnapshotStore;
48
-
49
- export type ContractGateSnapshotStoreModule = {
50
- createContractGateSnapshotStore?: ContractGateSnapshotStoreFactory;
51
- default?:
52
- | ContractGateSnapshotStoreFactory
53
- | {
54
- createContractGateSnapshotStore?: ContractGateSnapshotStoreFactory;
55
- };
56
- };
57
-
58
- export type ContractGateSnapshotStoreUserConfig = {
59
- module: string;
60
- options?: Record<string, unknown>;
61
- };
62
-
63
- export type ContractGateSnapshotHttpStoreOptions = {
64
- endpoint: string;
65
- readMethod?: string;
66
- writeMethod?: string;
67
- headers?: Record<string, string>;
68
- timeoutMs?: number;
69
- };
70
-
71
- const DEFAULT_HTTP_STORE_TIMEOUT_MS = 5_000;
72
- const BUILTIN_HTTP_STATE_STORE_MODULES = new Set([
73
- 'http',
74
- // historical aliases kept for config compatibility with the era when these
75
- // modules lived inside @modern-js/server-core.
76
- '@modern-js/server-core/http',
77
- '@modern-js/server-core/contract-gate-http-store',
78
- '@modern-js/server-runtime-extensions/http',
79
- '@modern-js/server-runtime-extensions/contract-gate-http-store',
80
- ]);
81
-
82
- const isRecord = (value: unknown): value is Record<string, unknown> =>
83
- typeof value === 'object' && value !== null && !Array.isArray(value);
84
-
85
- const normalizeSnapshot = (snapshot: unknown): GateSnapshot | undefined => {
86
- if (!isRecord(snapshot)) {
87
- return undefined;
88
- }
89
-
90
- const schemaVersion =
91
- typeof snapshot.schemaVersion === 'number'
92
- ? snapshot.schemaVersion
93
- : CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
94
- const updatedAt =
95
- typeof snapshot.updatedAt === 'number' ? snapshot.updatedAt : Date.now();
96
- const gates = isRecord(snapshot.gates)
97
- ? (snapshot.gates as Record<string, GateSnapshotGateValue>)
98
- : {};
99
-
100
- return {
101
- schemaVersion,
102
- updatedAt,
103
- gates,
104
- };
105
- };
106
-
107
- const normalizeHttpStoreOptions = (
108
- options: Record<string, unknown> | undefined,
109
- ): ContractGateSnapshotHttpStoreOptions => {
110
- const endpoint =
111
- typeof options?.endpoint === 'string' ? options.endpoint.trim() : '';
112
- if (!endpoint) {
113
- throw new Error(
114
- '[telemetry.canary.autopilot] HTTP stateStore requires options.endpoint',
115
- );
116
- }
117
-
118
- const readMethod =
119
- typeof options?.readMethod === 'string' && options.readMethod.trim()
120
- ? options.readMethod.trim().toUpperCase()
121
- : 'GET';
122
- const writeMethod =
123
- typeof options?.writeMethod === 'string' && options.writeMethod.trim()
124
- ? options.writeMethod.trim().toUpperCase()
125
- : 'PUT';
126
-
127
- const timeoutMsRaw = Number(options?.timeoutMs);
128
- const timeoutMs =
129
- Number.isFinite(timeoutMsRaw) && timeoutMsRaw > 0
130
- ? Math.floor(timeoutMsRaw)
131
- : DEFAULT_HTTP_STORE_TIMEOUT_MS;
132
-
133
- const headersRaw = options?.headers;
134
- const headers: Record<string, string> = {};
135
- if (
136
- headersRaw &&
137
- typeof headersRaw === 'object' &&
138
- !Array.isArray(headersRaw)
139
- ) {
140
- Object.entries(headersRaw).forEach(([key, value]) => {
141
- if (typeof key === 'string' && key.trim().length > 0 && value != null) {
142
- headers[key] = String(value);
143
- }
144
- });
145
- }
146
-
147
- return {
148
- endpoint,
149
- readMethod,
150
- writeMethod,
151
- headers,
152
- timeoutMs,
153
- };
154
- };
155
-
156
- const withTimeoutAbort = (timeoutMs: number) => {
157
- const controller = new AbortController();
158
- const timer = setTimeout(() => controller.abort(), timeoutMs);
159
- return {
160
- signal: controller.signal,
161
- clear: () => clearTimeout(timer),
162
- };
163
- };
164
-
165
- export const createHttpContractGateSnapshotStore = (
166
- options: ContractGateSnapshotHttpStoreOptions,
167
- ): ContractGateSnapshotStore => {
168
- const normalized = normalizeHttpStoreOptions(
169
- options as unknown as Record<string, unknown>,
170
- );
171
- const endpoint = normalized.endpoint;
172
-
173
- return {
174
- name: `http:${endpoint}`,
175
- async readSnapshot() {
176
- const { signal, clear } = withTimeoutAbort(normalized.timeoutMs || 5_000);
177
- try {
178
- const response = await fetch(endpoint, {
179
- method: normalized.readMethod || 'GET',
180
- headers: {
181
- accept: 'application/json',
182
- ...(normalized.headers || {}),
183
- },
184
- signal,
185
- });
186
-
187
- if (response.status === 404) {
188
- return undefined;
189
- }
190
-
191
- if (!response.ok) {
192
- throw new Error(
193
- `HTTP stateStore read failed with status ${String(response.status)}`,
194
- );
195
- }
196
-
197
- const payload = await response.json();
198
- return normalizeSnapshot(payload);
199
- } finally {
200
- clear();
201
- }
202
- },
203
- async writeSnapshot(snapshot) {
204
- const body = JSON.stringify(
205
- normalizeSnapshot(snapshot) || {
206
- schemaVersion: CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
207
- updatedAt: Date.now(),
208
- gates: {},
209
- },
210
- );
211
- const { signal, clear } = withTimeoutAbort(normalized.timeoutMs || 5_000);
212
- try {
213
- const response = await fetch(endpoint, {
214
- method: normalized.writeMethod || 'PUT',
215
- headers: {
216
- 'content-type': 'application/json',
217
- ...(normalized.headers || {}),
218
- },
219
- body,
220
- signal,
221
- });
222
- if (!response.ok) {
223
- throw new Error(
224
- `HTTP stateStore write failed with status ${String(response.status)}`,
225
- );
226
- }
227
- } finally {
228
- clear();
229
- }
230
- },
231
- };
232
- };
233
-
234
- const tryResolveBuiltinSnapshotStore = (input: {
235
- stateStore: ContractGateSnapshotStoreUserConfig;
236
- }): ContractGateSnapshotStore | undefined => {
237
- const moduleName = input.stateStore.module.trim();
238
- if (!BUILTIN_HTTP_STATE_STORE_MODULES.has(moduleName)) {
239
- return undefined;
240
- }
241
-
242
- return createHttpContractGateSnapshotStore(
243
- (input.stateStore.options || {}) as ContractGateSnapshotHttpStoreOptions,
244
- );
245
- };
246
-
247
- const pickStoreFactory = (
248
- mod: ContractGateSnapshotStoreModule,
249
- ): ContractGateSnapshotStoreFactory | undefined => {
250
- if (typeof mod === 'function') {
251
- return mod as unknown as ContractGateSnapshotStoreFactory;
252
- }
253
-
254
- if (typeof mod.createContractGateSnapshotStore === 'function') {
255
- return mod.createContractGateSnapshotStore;
256
- }
257
-
258
- if (typeof mod.default === 'function') {
259
- return mod.default;
260
- }
261
-
262
- if (
263
- mod.default &&
264
- typeof mod.default === 'object' &&
265
- typeof mod.default.createContractGateSnapshotStore === 'function'
266
- ) {
267
- return mod.default.createContractGateSnapshotStore;
268
- }
269
-
270
- return undefined;
271
- };
272
-
273
- const ensureStoreShape = (
274
- store: ContractGateSnapshotStore,
275
- modulePath: string,
276
- ) => {
277
- if (
278
- !store ||
279
- typeof store !== 'object' ||
280
- typeof store.readSnapshot !== 'function' ||
281
- typeof store.writeSnapshot !== 'function'
282
- ) {
283
- throw new Error(
284
- `Invalid contract gate snapshot store from "${modulePath}". Expected { readSnapshot(), writeSnapshot() }.`,
285
- );
286
- }
287
- };
288
-
289
- /**
290
- * Resolves a user-configured stateStore module specifier from the app, not
291
- * from this framework package: relative paths resolve against appDirectory,
292
- * and bare package specifiers resolve through the app's own module graph
293
- * (`createRequire` anchored at the app package.json). Resolving from the
294
- * framework package breaks app-installed stores under pnpm's strict
295
- * node_modules layout. Bare specifiers fall back to framework-local
296
- * resolution for stores installed alongside the framework.
297
- */
298
- const resolveStoreModulePath = (appDirectory: string, modulePath: string) => {
299
- const normalized = modulePath.trim();
300
- if (!normalized) {
301
- throw new Error(
302
- 'Contract gate snapshot stateStore.module must be non-empty',
303
- );
304
- }
305
-
306
- if (path.isAbsolute(normalized)) {
307
- return normalized;
308
- }
309
-
310
- if (normalized.startsWith('.')) {
311
- return path.resolve(appDirectory, normalized);
312
- }
313
-
314
- const appRequire = createRequire(path.join(appDirectory, 'package.json'));
315
- try {
316
- return appRequire.resolve(normalized);
317
- } catch (_error) {
318
- // Fall back to this package's own resolution so stores installed next to
319
- // the framework keep working.
320
- return normalized;
321
- }
322
- };
323
-
324
- export const resolveContractGateSnapshotPath = (
325
- appDirectory: string,
326
- configuredPath: string | undefined,
327
- ) => {
328
- const rawPath =
329
- configuredPath ||
330
- parseServerRuntimeExtensionsEnv().contractGatesFile ||
331
- DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH;
332
- if (path.isAbsolute(rawPath)) {
333
- return rawPath;
334
- }
335
- return path.resolve(appDirectory, rawPath);
336
- };
337
-
338
- export const createFileContractGateSnapshotStore = (
339
- gateSnapshotPath: string,
340
- ): ContractGateSnapshotStore => {
341
- const resolvedPath = path.resolve(gateSnapshotPath);
342
- return {
343
- name: `file:${resolvedPath}`,
344
- async readSnapshot() {
345
- if (!(await fs.pathExists(resolvedPath))) {
346
- return undefined;
347
- }
348
-
349
- try {
350
- const raw = await nodeFs.readFile(resolvedPath, 'utf8');
351
- return normalizeSnapshot(JSON.parse(raw));
352
- } catch (_error) {
353
- return undefined;
354
- }
355
- },
356
- async writeSnapshot(snapshot) {
357
- const normalized = normalizeSnapshot(snapshot) || {
358
- schemaVersion: CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
359
- updatedAt: Date.now(),
360
- gates: {},
361
- };
362
- await nodeFs.mkdir(path.dirname(resolvedPath), { recursive: true });
363
- await nodeFs.writeFile(
364
- resolvedPath,
365
- `${JSON.stringify(normalized, null, 2)}\n`,
366
- );
367
- },
368
- };
369
- };
370
-
371
- export const resolveContractGateSnapshotStore = async (input: {
372
- appDirectory: string;
373
- gateSnapshotPath: string;
374
- stateStore?: ContractGateSnapshotStoreUserConfig;
375
- logger?: LoggerLike;
376
- }): Promise<ContractGateSnapshotStore> => {
377
- const { appDirectory, gateSnapshotPath, stateStore, logger } = input;
378
-
379
- if (!stateStore?.module) {
380
- return createFileContractGateSnapshotStore(gateSnapshotPath);
381
- }
382
-
383
- const builtinStore = tryResolveBuiltinSnapshotStore({ stateStore });
384
- if (builtinStore) {
385
- logger?.info?.(
386
- `[telemetry.canary.autopilot] using built-in contract gate snapshot store "${builtinStore.name}"`,
387
- );
388
- return builtinStore;
389
- }
390
-
391
- const modulePath = resolveStoreModulePath(appDirectory, stateStore.module);
392
- let mod: ContractGateSnapshotStoreModule;
393
- try {
394
- // eslint-disable-next-line import/no-dynamic-require,global-require
395
- mod = require(modulePath) as ContractGateSnapshotStoreModule;
396
- } catch (error) {
397
- throw new Error(
398
- `[telemetry.canary.autopilot] Failed to load stateStore.module "${stateStore.module}" (${modulePath}): ${error instanceof Error ? error.message : String(error)}`,
399
- );
400
- }
401
-
402
- const factory = pickStoreFactory(mod);
403
- if (!factory) {
404
- throw new Error(
405
- `[telemetry.canary.autopilot] stateStore.module "${stateStore.module}" does not export createContractGateSnapshotStore()`,
406
- );
407
- }
408
-
409
- const store = await factory({
410
- appDirectory,
411
- gateSnapshotPath,
412
- options: stateStore.options,
413
- logger,
414
- });
415
- ensureStoreShape(store, modulePath);
416
- logger?.info?.(
417
- `[telemetry.canary.autopilot] using contract gate snapshot store "${store.name || modulePath}"`,
418
- );
419
- return store;
420
- };