@bleedingdev/modern-js-server-runtime-extensions 3.5.0-ultramodern.4 → 3.5.0-ultramodern.41

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 (175) 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/module-federation-css/collector.js +79 -0
  10. package/dist/cjs/module-federation-css/index.js +55 -0
  11. package/dist/cjs/module-federation-css/manifest.js +129 -0
  12. package/dist/cjs/module-federation-css/plugin.js +71 -0
  13. package/dist/cjs/module-federation-css/remote.js +133 -0
  14. package/dist/cjs/runtime-fallback-signal/index.js +93 -0
  15. package/dist/cjs/runtime-fallback-signal/model.js +157 -0
  16. package/dist/cjs/runtime-fallback-signal/resolver.js +163 -0
  17. package/dist/cjs/runtime-fallback-signal/store.js +83 -0
  18. package/dist/cjs/runtimeFallbackSignal.js +32 -281
  19. package/dist/cjs/telemetry/canary.js +180 -0
  20. package/dist/cjs/telemetry/canaryEvaluation.js +79 -0
  21. package/dist/cjs/telemetry/canarySetup.js +107 -0
  22. package/dist/cjs/telemetry/envelope.js +223 -0
  23. package/dist/cjs/telemetry/exporters.js +148 -0
  24. package/dist/cjs/telemetry/lifecycle.js +98 -0
  25. package/dist/cjs/telemetry/metrics.js +115 -0
  26. package/dist/cjs/telemetry/plugin.js +185 -0
  27. package/dist/cjs/telemetry/registry.js +296 -0
  28. package/dist/cjs/telemetry/registryTypes.js +46 -0
  29. package/dist/cjs/telemetry/runtimeEndpoints.js +135 -0
  30. package/dist/cjs/telemetry.js +32 -343
  31. package/dist/cjs/telemetryCore.js +14 -767
  32. package/dist/esm/contract-gate-snapshot-normalization.mjs +81 -0
  33. package/dist/esm/contract-gate-snapshot-store/file-store.mjs +51 -0
  34. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +92 -0
  35. package/dist/esm/contract-gate-snapshot-store/index.mjs +4 -0
  36. package/dist/esm/contract-gate-snapshot-store/resolve.mjs +70 -0
  37. package/dist/esm/contract-gate-snapshot-store/types.mjs +3 -0
  38. package/dist/esm/contractGateAutopilot.mjs +21 -69
  39. package/dist/esm/index.mjs +1 -2
  40. package/dist/esm/module-federation-css/collector.mjs +38 -0
  41. package/dist/esm/module-federation-css/index.mjs +4 -0
  42. package/dist/esm/module-federation-css/manifest.mjs +69 -0
  43. package/dist/esm/module-federation-css/plugin.mjs +33 -0
  44. package/dist/esm/module-federation-css/remote.mjs +92 -0
  45. package/dist/esm/runtime-fallback-signal/index.mjs +3 -0
  46. package/dist/esm/runtime-fallback-signal/model.mjs +73 -0
  47. package/dist/esm/runtime-fallback-signal/resolver.mjs +107 -0
  48. package/dist/esm/runtime-fallback-signal/store.mjs +39 -0
  49. package/dist/esm/runtimeFallbackSignal.mjs +1 -222
  50. package/dist/esm/telemetry/canary.mjs +142 -0
  51. package/dist/esm/telemetry/canaryEvaluation.mjs +41 -0
  52. package/dist/esm/telemetry/canarySetup.mjs +69 -0
  53. package/dist/esm/telemetry/envelope.mjs +164 -0
  54. package/dist/esm/telemetry/exporters.mjs +104 -0
  55. package/dist/esm/telemetry/lifecycle.mjs +60 -0
  56. package/dist/esm/telemetry/metrics.mjs +77 -0
  57. package/dist/esm/telemetry/plugin.mjs +87 -0
  58. package/dist/esm/telemetry/registry.mjs +258 -0
  59. package/dist/esm/telemetry/registryTypes.mjs +8 -0
  60. package/dist/esm/telemetry/runtimeEndpoints.mjs +94 -0
  61. package/dist/esm/telemetry.mjs +1 -275
  62. package/dist/esm/telemetryCore.mjs +6 -759
  63. package/dist/esm-node/contract-gate-snapshot-normalization.mjs +82 -0
  64. package/dist/esm-node/contract-gate-snapshot-store/file-store.mjs +52 -0
  65. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +93 -0
  66. package/dist/esm-node/contract-gate-snapshot-store/index.mjs +5 -0
  67. package/dist/esm-node/contract-gate-snapshot-store/resolve.mjs +71 -0
  68. package/dist/esm-node/contract-gate-snapshot-store/types.mjs +4 -0
  69. package/dist/esm-node/contractGateAutopilot.mjs +21 -69
  70. package/dist/esm-node/index.mjs +1 -2
  71. package/dist/esm-node/module-federation-css/collector.mjs +39 -0
  72. package/dist/esm-node/module-federation-css/index.mjs +5 -0
  73. package/dist/esm-node/module-federation-css/manifest.mjs +70 -0
  74. package/dist/esm-node/module-federation-css/plugin.mjs +34 -0
  75. package/dist/esm-node/module-federation-css/remote.mjs +93 -0
  76. package/dist/esm-node/runtime-fallback-signal/index.mjs +4 -0
  77. package/dist/esm-node/runtime-fallback-signal/model.mjs +74 -0
  78. package/dist/esm-node/runtime-fallback-signal/resolver.mjs +108 -0
  79. package/dist/esm-node/runtime-fallback-signal/store.mjs +40 -0
  80. package/dist/esm-node/runtimeFallbackSignal.mjs +1 -222
  81. package/dist/esm-node/telemetry/canary.mjs +143 -0
  82. package/dist/esm-node/telemetry/canaryEvaluation.mjs +42 -0
  83. package/dist/esm-node/telemetry/canarySetup.mjs +70 -0
  84. package/dist/esm-node/telemetry/envelope.mjs +165 -0
  85. package/dist/esm-node/telemetry/exporters.mjs +105 -0
  86. package/dist/esm-node/telemetry/lifecycle.mjs +61 -0
  87. package/dist/esm-node/telemetry/metrics.mjs +78 -0
  88. package/dist/esm-node/telemetry/plugin.mjs +88 -0
  89. package/dist/esm-node/telemetry/registry.mjs +259 -0
  90. package/dist/esm-node/telemetry/registryTypes.mjs +9 -0
  91. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +95 -0
  92. package/dist/esm-node/telemetry.mjs +1 -275
  93. package/dist/esm-node/telemetryCore.mjs +6 -759
  94. package/dist/types/contract-gate-snapshot-normalization.d.ts +15 -0
  95. package/dist/types/contract-gate-snapshot-store/file-store.d.ts +3 -0
  96. package/dist/types/contract-gate-snapshot-store/http-store.d.ts +5 -0
  97. package/dist/types/contract-gate-snapshot-store/index.d.ts +5 -0
  98. package/dist/types/contract-gate-snapshot-store/resolve.d.ts +9 -0
  99. package/dist/types/{contractGateSnapshotStore.d.ts → contract-gate-snapshot-store/types.d.ts} +1 -11
  100. package/dist/types/contractGateAutopilot.d.ts +3 -6
  101. package/dist/types/index.d.ts +1 -2
  102. package/dist/types/module-federation-css/collector.d.ts +25 -0
  103. package/dist/types/module-federation-css/index.d.ts +8 -0
  104. package/dist/types/module-federation-css/manifest.d.ts +28 -0
  105. package/dist/types/module-federation-css/plugin.d.ts +23 -0
  106. package/dist/types/module-federation-css/remote.d.ts +20 -0
  107. package/dist/types/runtime-fallback-signal/index.d.ts +4 -0
  108. package/dist/types/runtime-fallback-signal/model.d.ts +70 -0
  109. package/dist/types/runtime-fallback-signal/resolver.d.ts +29 -0
  110. package/dist/types/runtime-fallback-signal/store.d.ts +4 -0
  111. package/dist/types/runtimeFallbackSignal.d.ts +1 -94
  112. package/dist/types/telemetry/canary.d.ts +85 -0
  113. package/dist/types/telemetry/canaryEvaluation.d.ts +20 -0
  114. package/dist/types/telemetry/canarySetup.d.ts +17 -0
  115. package/dist/types/telemetry/envelope.d.ts +55 -0
  116. package/dist/types/telemetry/exporters.d.ts +12 -0
  117. package/dist/types/telemetry/lifecycle.d.ts +18 -0
  118. package/dist/types/telemetry/metrics.d.ts +3 -0
  119. package/dist/types/telemetry/plugin.d.ts +12 -0
  120. package/dist/types/telemetry/registry.d.ts +69 -0
  121. package/dist/types/telemetry/registryTypes.d.ts +50 -0
  122. package/dist/types/telemetry/runtimeEndpoints.d.ts +35 -0
  123. package/dist/types/telemetry.d.ts +1 -12
  124. package/dist/types/telemetryCore.d.ts +6 -257
  125. package/package.json +9 -9
  126. package/src/contract-gate-snapshot-normalization.ts +155 -0
  127. package/src/contract-gate-snapshot-store/file-store.ts +83 -0
  128. package/src/contract-gate-snapshot-store/http-store.ts +159 -0
  129. package/src/contract-gate-snapshot-store/index.ts +20 -0
  130. package/src/contract-gate-snapshot-store/resolve.ts +179 -0
  131. package/src/contract-gate-snapshot-store/types.ts +64 -0
  132. package/src/contractGateAutopilot.ts +39 -131
  133. package/src/index.ts +1 -17
  134. package/src/module-federation-css/collector.ts +82 -0
  135. package/src/module-federation-css/index.ts +14 -0
  136. package/src/module-federation-css/manifest.ts +163 -0
  137. package/src/module-federation-css/plugin.ts +86 -0
  138. package/src/module-federation-css/remote.ts +165 -0
  139. package/src/runtime-fallback-signal/index.ts +34 -0
  140. package/src/runtime-fallback-signal/model.ts +230 -0
  141. package/src/runtime-fallback-signal/resolver.ts +304 -0
  142. package/src/runtime-fallback-signal/store.ts +78 -0
  143. package/src/runtimeFallbackSignal.ts +1 -584
  144. package/src/telemetry/canary.ts +291 -0
  145. package/src/telemetry/canaryEvaluation.ts +83 -0
  146. package/src/telemetry/canarySetup.ts +160 -0
  147. package/src/telemetry/envelope.ts +277 -0
  148. package/src/telemetry/exporters.ts +165 -0
  149. package/src/telemetry/lifecycle.ts +138 -0
  150. package/src/telemetry/metrics.ts +141 -0
  151. package/src/telemetry/plugin.ts +197 -0
  152. package/src/telemetry/registry.ts +424 -0
  153. package/src/telemetry/registryTypes.ts +63 -0
  154. package/src/telemetry/runtimeEndpoints.ts +172 -0
  155. package/src/telemetry.ts +1 -554
  156. package/src/telemetryCore.ts +34 -1332
  157. package/tests/contractGateAutopilot.test.ts +205 -0
  158. package/tests/contractGateSnapshotStore.test.ts +54 -1
  159. package/tests/helpers.ts +1 -0
  160. package/tests/moduleFederationCss.test.ts +1 -1
  161. package/tests/registration.test.ts +1 -1
  162. package/tests/telemetry.test.ts +51 -0
  163. package/tests/telemetryAutopilot.test.ts +141 -0
  164. package/tests/telemetryCanaryOrchestrator.test.ts +225 -0
  165. package/tests/telemetryLifecycle.test.ts +253 -2
  166. package/tests/telemetryRegistryQueueMatrix.test.ts +227 -0
  167. package/dist/cjs/contractGateSnapshotStore.js +0 -253
  168. package/dist/cjs/moduleFederationCss.js +0 -285
  169. package/dist/esm/contractGateSnapshotStore.mjs +0 -190
  170. package/dist/esm/moduleFederationCss.mjs +0 -225
  171. package/dist/esm-node/contractGateSnapshotStore.mjs +0 -192
  172. package/dist/esm-node/moduleFederationCss.mjs +0 -226
  173. package/dist/types/moduleFederationCss.d.ts +0 -87
  174. package/src/contractGateSnapshotStore.ts +0 -420
  175. package/src/moduleFederationCss.ts +0 -473
@@ -0,0 +1,227 @@
1
+ import {
2
+ type TelemetryEnvelope,
3
+ type TelemetryExporter,
4
+ TelemetryRegistry,
5
+ type TelemetrySloAlert,
6
+ } from '../src/telemetry';
7
+
8
+ const createEnvelope = (
9
+ partial: Partial<TelemetryEnvelope> = {},
10
+ ): TelemetryEnvelope => ({
11
+ timestamp: Date.now(),
12
+ service: 'svc',
13
+ module: 'server',
14
+ environment: 'test',
15
+ signalType: 'metric',
16
+ name: 'server.handle.request',
17
+ value: 1,
18
+ unit: 'count',
19
+ ...partial,
20
+ });
21
+
22
+ const createRegistry = (
23
+ options: Partial<ConstructorParameters<typeof TelemetryRegistry>[0]> = {},
24
+ ) =>
25
+ new TelemetryRegistry({
26
+ service: 'svc',
27
+ module: 'server',
28
+ environment: 'test',
29
+ flushIntervalMs: 60_000,
30
+ maxBatchSize: 100,
31
+ ...options,
32
+ });
33
+
34
+ const createMemoryExporter = (
35
+ batches: TelemetryEnvelope[][],
36
+ ): TelemetryExporter => ({
37
+ name: 'memory',
38
+ emit(batch) {
39
+ batches.push([...batch]);
40
+ },
41
+ });
42
+
43
+ describe('telemetry registry queue matrix', () => {
44
+ test.each([
45
+ {
46
+ name: 'below-threshold drops remain window-scoped across flushes',
47
+ dropsPerWindow: [1, 1],
48
+ expectedDropAlertValues: [],
49
+ expectedDropAlertTotals: [],
50
+ },
51
+ {
52
+ name: 'threshold drops alert once per window with lifetime totals attached',
53
+ dropsPerWindow: [2, 2],
54
+ expectedDropAlertValues: [2, 2],
55
+ expectedDropAlertTotals: [2, 4],
56
+ },
57
+ ])('$name', async ({
58
+ dropsPerWindow,
59
+ expectedDropAlertValues,
60
+ expectedDropAlertTotals,
61
+ }) => {
62
+ const alerts: TelemetrySloAlert[] = [];
63
+ const batches: TelemetryEnvelope[][] = [];
64
+ const registry = createRegistry({
65
+ maxQueueSize: 2,
66
+ slo: {
67
+ queueUtilizationWarnThreshold: 1,
68
+ queueDroppedWarnThreshold: 2,
69
+ alertCooldownMs: 0,
70
+ onAlert(alert) {
71
+ alerts.push(alert);
72
+ },
73
+ },
74
+ });
75
+ await registry.register(createMemoryExporter(batches));
76
+
77
+ let totalDropped = 0;
78
+ for (const [windowIndex, dropCount] of dropsPerWindow.entries()) {
79
+ for (let index = 0; index < 2 + dropCount; index++) {
80
+ registry.enqueue(
81
+ createEnvelope({
82
+ name: `window.${windowIndex}.event.${index}`,
83
+ }),
84
+ );
85
+ }
86
+
87
+ totalDropped += dropCount;
88
+ expect(registry.getQueueStats()).toEqual({
89
+ depth: 2,
90
+ capacity: 2,
91
+ utilization: 1,
92
+ pendingDropped: dropCount,
93
+ totalDropped,
94
+ });
95
+
96
+ await registry.flush();
97
+ expect(registry.getQueueStats()).toEqual({
98
+ depth: 0,
99
+ capacity: 2,
100
+ utilization: 0,
101
+ pendingDropped: 0,
102
+ totalDropped,
103
+ });
104
+ expect(batches).toHaveLength(windowIndex + 1);
105
+ expect(batches[windowIndex]).toHaveLength(5);
106
+ }
107
+
108
+ const emitted = batches.flat();
109
+ expect(
110
+ emitted
111
+ .filter(item => item.name === 'telemetry.queue.dropped')
112
+ .map(item => item.value),
113
+ ).toEqual(dropsPerWindow);
114
+ expect(
115
+ emitted
116
+ .filter(item => item.name === 'telemetry.queue.depth')
117
+ .map(item => item.value),
118
+ ).toEqual([2, 2]);
119
+ expect(
120
+ emitted
121
+ .filter(item => item.name === 'telemetry.queue.utilization')
122
+ .map(item => item.value),
123
+ ).toEqual([1, 1]);
124
+
125
+ const utilizationAlerts = alerts.filter(
126
+ alert => alert.type === 'queue.utilization',
127
+ );
128
+ expect(utilizationAlerts.length).toBeGreaterThan(0);
129
+ expect(utilizationAlerts.every(alert => alert.value === 1)).toBe(true);
130
+
131
+ const dropAlerts = alerts.filter(alert => alert.type === 'queue.drop');
132
+ expect(dropAlerts.map(alert => alert.value)).toEqual(
133
+ expectedDropAlertValues,
134
+ );
135
+ expect(dropAlerts.map(alert => alert.totalDropped)).toEqual(
136
+ expectedDropAlertTotals,
137
+ );
138
+ expect(dropAlerts.every(alert => alert.threshold === 2)).toBe(true);
139
+
140
+ await registry.shutdown();
141
+ });
142
+
143
+ test('aggregates exporter health across successful and failed emitters', async () => {
144
+ const batches: TelemetryEnvelope[][] = [];
145
+ const registry = createRegistry({ maxQueueSize: 4 });
146
+ const failingExporter = {
147
+ name: 'failing',
148
+ async emit() {
149
+ throw new Error('export failed');
150
+ },
151
+ } satisfies TelemetryExporter;
152
+
153
+ await registry.register(createMemoryExporter(batches));
154
+ await registry.register(failingExporter);
155
+
156
+ registry.enqueue(createEnvelope({ name: 'health.sample' }));
157
+ await registry.flush();
158
+
159
+ const healthByName = new Map(
160
+ registry.getExporterHealth().map(item => [item.name, item]),
161
+ );
162
+ expect(healthByName.get('memory')).toMatchObject({
163
+ name: 'memory',
164
+ healthy: true,
165
+ failures: 0,
166
+ });
167
+ expect(healthByName.get('memory')?.lastSuccessAt).toEqual(
168
+ expect.any(Number),
169
+ );
170
+ expect(healthByName.get('failing')).toMatchObject({
171
+ name: 'failing',
172
+ healthy: false,
173
+ failures: 1,
174
+ lastError: 'export failed',
175
+ });
176
+ expect(healthByName.get('failing')?.lastFailureAt).toEqual(
177
+ expect.any(Number),
178
+ );
179
+ expect(batches).toHaveLength(1);
180
+ expect(batches[0].some(item => item.name === 'health.sample')).toBe(true);
181
+
182
+ await registry.shutdown();
183
+ });
184
+
185
+ test('clamps NaN queue utilization SLO threshold before alerting', async () => {
186
+ const alerts: TelemetrySloAlert[] = [];
187
+ const registry = createRegistry({
188
+ maxQueueSize: 2,
189
+ slo: {
190
+ queueUtilizationWarnThreshold: Number.NaN,
191
+ alertCooldownMs: 0,
192
+ onAlert(alert) {
193
+ alerts.push(alert);
194
+ },
195
+ },
196
+ });
197
+
198
+ registry.enqueue(createEnvelope({ name: 'half-full' }));
199
+ expect(registry.getQueueStats()).toEqual({
200
+ depth: 1,
201
+ capacity: 2,
202
+ utilization: 0.5,
203
+ pendingDropped: 0,
204
+ totalDropped: 0,
205
+ });
206
+ expect(alerts.filter(alert => alert.type === 'queue.utilization')).toEqual(
207
+ [],
208
+ );
209
+
210
+ registry.enqueue(createEnvelope({ name: 'full' }));
211
+ const utilizationAlerts = alerts.filter(
212
+ alert => alert.type === 'queue.utilization',
213
+ );
214
+ expect(utilizationAlerts).toHaveLength(1);
215
+ expect(utilizationAlerts[0]).toMatchObject({
216
+ type: 'queue.utilization',
217
+ value: 1,
218
+ threshold: 1,
219
+ queueDepth: 2,
220
+ queueCapacity: 2,
221
+ queueUtilization: 1,
222
+ totalDropped: 0,
223
+ });
224
+
225
+ await registry.shutdown();
226
+ });
227
+ });
@@ -1,253 +0,0 @@
1
- "use strict";
2
- var __webpack_require__ = {};
3
- (()=>{
4
- __webpack_require__.n = (module)=>{
5
- var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
6
- __webpack_require__.d(getter, {
7
- a: getter
8
- });
9
- return getter;
10
- };
11
- })();
12
- (()=>{
13
- __webpack_require__.d = (exports1, getters, values)=>{
14
- var define = (defs, kind)=>{
15
- for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
16
- enumerable: true,
17
- [kind]: defs[key]
18
- });
19
- };
20
- define(getters, "get");
21
- define(values, "value");
22
- };
23
- })();
24
- (()=>{
25
- __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
26
- })();
27
- (()=>{
28
- __webpack_require__.r = (exports1)=>{
29
- if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
30
- value: 'Module'
31
- });
32
- Object.defineProperty(exports1, '__esModule', {
33
- value: true
34
- });
35
- };
36
- })();
37
- var __webpack_exports__ = {};
38
- __webpack_require__.r(__webpack_exports__);
39
- __webpack_require__.d(__webpack_exports__, {
40
- CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION: ()=>CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
41
- DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH: ()=>DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH,
42
- createFileContractGateSnapshotStore: ()=>createFileContractGateSnapshotStore,
43
- createHttpContractGateSnapshotStore: ()=>createHttpContractGateSnapshotStore,
44
- resolveContractGateSnapshotPath: ()=>resolveContractGateSnapshotPath,
45
- resolveContractGateSnapshotStore: ()=>resolveContractGateSnapshotStore
46
- });
47
- const external_node_module_namespaceObject = require("node:module");
48
- const utils_namespaceObject = require("@modern-js/utils");
49
- const external_fs_namespaceObject = require("fs");
50
- const external_path_namespaceObject = require("path");
51
- var external_path_default = /*#__PURE__*/ __webpack_require__.n(external_path_namespaceObject);
52
- const external_env_js_namespaceObject = require("./env.js");
53
- const CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION = 1;
54
- const DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH = '.modern/contract-gates.json';
55
- const DEFAULT_HTTP_STORE_TIMEOUT_MS = 5000;
56
- const BUILTIN_HTTP_STATE_STORE_MODULES = new Set([
57
- 'http',
58
- '@modern-js/server-core/http',
59
- '@modern-js/server-core/contract-gate-http-store',
60
- '@modern-js/server-runtime-extensions/http',
61
- '@modern-js/server-runtime-extensions/contract-gate-http-store'
62
- ]);
63
- const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
64
- const normalizeSnapshot = (snapshot)=>{
65
- if (!isRecord(snapshot)) return;
66
- const schemaVersion = 'number' == typeof snapshot.schemaVersion ? snapshot.schemaVersion : CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
67
- const updatedAt = 'number' == typeof snapshot.updatedAt ? snapshot.updatedAt : Date.now();
68
- const gates = isRecord(snapshot.gates) ? snapshot.gates : {};
69
- return {
70
- schemaVersion,
71
- updatedAt,
72
- gates
73
- };
74
- };
75
- const normalizeHttpStoreOptions = (options)=>{
76
- const endpoint = 'string' == typeof options?.endpoint ? options.endpoint.trim() : '';
77
- if (!endpoint) throw new Error('[telemetry.canary.autopilot] HTTP stateStore requires options.endpoint');
78
- const readMethod = 'string' == typeof options?.readMethod && options.readMethod.trim() ? options.readMethod.trim().toUpperCase() : 'GET';
79
- const writeMethod = 'string' == typeof options?.writeMethod && options.writeMethod.trim() ? options.writeMethod.trim().toUpperCase() : 'PUT';
80
- const timeoutMsRaw = Number(options?.timeoutMs);
81
- const timeoutMs = Number.isFinite(timeoutMsRaw) && timeoutMsRaw > 0 ? Math.floor(timeoutMsRaw) : DEFAULT_HTTP_STORE_TIMEOUT_MS;
82
- const headersRaw = options?.headers;
83
- const headers = {};
84
- if (headersRaw && 'object' == typeof headersRaw && !Array.isArray(headersRaw)) Object.entries(headersRaw).forEach(([key, value])=>{
85
- if ('string' == typeof key && key.trim().length > 0 && null != value) headers[key] = String(value);
86
- });
87
- return {
88
- endpoint,
89
- readMethod,
90
- writeMethod,
91
- headers,
92
- timeoutMs
93
- };
94
- };
95
- const withTimeoutAbort = (timeoutMs)=>{
96
- const controller = new AbortController();
97
- const timer = setTimeout(()=>controller.abort(), timeoutMs);
98
- return {
99
- signal: controller.signal,
100
- clear: ()=>clearTimeout(timer)
101
- };
102
- };
103
- const createHttpContractGateSnapshotStore = (options)=>{
104
- const normalized = normalizeHttpStoreOptions(options);
105
- const endpoint = normalized.endpoint;
106
- return {
107
- name: `http:${endpoint}`,
108
- async readSnapshot () {
109
- const { signal, clear } = withTimeoutAbort(normalized.timeoutMs || 5000);
110
- try {
111
- const response = await fetch(endpoint, {
112
- method: normalized.readMethod || 'GET',
113
- headers: {
114
- accept: 'application/json',
115
- ...normalized.headers || {}
116
- },
117
- signal
118
- });
119
- if (404 === response.status) return;
120
- if (!response.ok) throw new Error(`HTTP stateStore read failed with status ${String(response.status)}`);
121
- const payload = await response.json();
122
- return normalizeSnapshot(payload);
123
- } finally{
124
- clear();
125
- }
126
- },
127
- async writeSnapshot (snapshot) {
128
- const body = JSON.stringify(normalizeSnapshot(snapshot) || {
129
- schemaVersion: CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
130
- updatedAt: Date.now(),
131
- gates: {}
132
- });
133
- const { signal, clear } = withTimeoutAbort(normalized.timeoutMs || 5000);
134
- try {
135
- const response = await fetch(endpoint, {
136
- method: normalized.writeMethod || 'PUT',
137
- headers: {
138
- 'content-type': 'application/json',
139
- ...normalized.headers || {}
140
- },
141
- body,
142
- signal
143
- });
144
- if (!response.ok) throw new Error(`HTTP stateStore write failed with status ${String(response.status)}`);
145
- } finally{
146
- clear();
147
- }
148
- }
149
- };
150
- };
151
- const tryResolveBuiltinSnapshotStore = (input)=>{
152
- const moduleName = input.stateStore.module.trim();
153
- if (!BUILTIN_HTTP_STATE_STORE_MODULES.has(moduleName)) return;
154
- return createHttpContractGateSnapshotStore(input.stateStore.options || {});
155
- };
156
- const pickStoreFactory = (mod)=>{
157
- if ('function' == typeof mod) return mod;
158
- if ('function' == typeof mod.createContractGateSnapshotStore) return mod.createContractGateSnapshotStore;
159
- if ('function' == typeof mod.default) return mod.default;
160
- if (mod.default && 'object' == typeof mod.default && 'function' == typeof mod.default.createContractGateSnapshotStore) return mod.default.createContractGateSnapshotStore;
161
- };
162
- const ensureStoreShape = (store, modulePath)=>{
163
- if (!store || 'object' != typeof store || 'function' != typeof store.readSnapshot || 'function' != typeof store.writeSnapshot) throw new Error(`Invalid contract gate snapshot store from "${modulePath}". Expected { readSnapshot(), writeSnapshot() }.`);
164
- };
165
- const resolveStoreModulePath = (appDirectory, modulePath)=>{
166
- const normalized = modulePath.trim();
167
- if (!normalized) throw new Error('Contract gate snapshot stateStore.module must be non-empty');
168
- if (external_path_default().isAbsolute(normalized)) return normalized;
169
- if (normalized.startsWith('.')) return external_path_default().resolve(appDirectory, normalized);
170
- const appRequire = (0, external_node_module_namespaceObject.createRequire)(external_path_default().join(appDirectory, 'package.json'));
171
- try {
172
- return appRequire.resolve(normalized);
173
- } catch (_error) {
174
- return normalized;
175
- }
176
- };
177
- const resolveContractGateSnapshotPath = (appDirectory, configuredPath)=>{
178
- const rawPath = configuredPath || (0, external_env_js_namespaceObject.parseServerRuntimeExtensionsEnv)().contractGatesFile || DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH;
179
- if (external_path_default().isAbsolute(rawPath)) return rawPath;
180
- return external_path_default().resolve(appDirectory, rawPath);
181
- };
182
- const createFileContractGateSnapshotStore = (gateSnapshotPath)=>{
183
- const resolvedPath = external_path_default().resolve(gateSnapshotPath);
184
- return {
185
- name: `file:${resolvedPath}`,
186
- async readSnapshot () {
187
- if (!await utils_namespaceObject.fs.pathExists(resolvedPath)) return;
188
- try {
189
- const raw = await external_fs_namespaceObject.promises.readFile(resolvedPath, 'utf8');
190
- return normalizeSnapshot(JSON.parse(raw));
191
- } catch (_error) {
192
- return;
193
- }
194
- },
195
- async writeSnapshot (snapshot) {
196
- const normalized = normalizeSnapshot(snapshot) || {
197
- schemaVersion: CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
198
- updatedAt: Date.now(),
199
- gates: {}
200
- };
201
- await external_fs_namespaceObject.promises.mkdir(external_path_default().dirname(resolvedPath), {
202
- recursive: true
203
- });
204
- await external_fs_namespaceObject.promises.writeFile(resolvedPath, `${JSON.stringify(normalized, null, 2)}\n`);
205
- }
206
- };
207
- };
208
- const resolveContractGateSnapshotStore = async (input)=>{
209
- const { appDirectory, gateSnapshotPath, stateStore, logger } = input;
210
- if (!stateStore?.module) return createFileContractGateSnapshotStore(gateSnapshotPath);
211
- const builtinStore = tryResolveBuiltinSnapshotStore({
212
- stateStore
213
- });
214
- if (builtinStore) {
215
- logger?.info?.(`[telemetry.canary.autopilot] using built-in contract gate snapshot store "${builtinStore.name}"`);
216
- return builtinStore;
217
- }
218
- const modulePath = resolveStoreModulePath(appDirectory, stateStore.module);
219
- let mod;
220
- try {
221
- mod = require(modulePath);
222
- } catch (error) {
223
- throw new Error(`[telemetry.canary.autopilot] Failed to load stateStore.module "${stateStore.module}" (${modulePath}): ${error instanceof Error ? error.message : String(error)}`);
224
- }
225
- const factory = pickStoreFactory(mod);
226
- if (!factory) throw new Error(`[telemetry.canary.autopilot] stateStore.module "${stateStore.module}" does not export createContractGateSnapshotStore()`);
227
- const store = await factory({
228
- appDirectory,
229
- gateSnapshotPath,
230
- options: stateStore.options,
231
- logger
232
- });
233
- ensureStoreShape(store, modulePath);
234
- logger?.info?.(`[telemetry.canary.autopilot] using contract gate snapshot store "${store.name || modulePath}"`);
235
- return store;
236
- };
237
- exports.CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION = __webpack_exports__.CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
238
- exports.DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH = __webpack_exports__.DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH;
239
- exports.createFileContractGateSnapshotStore = __webpack_exports__.createFileContractGateSnapshotStore;
240
- exports.createHttpContractGateSnapshotStore = __webpack_exports__.createHttpContractGateSnapshotStore;
241
- exports.resolveContractGateSnapshotPath = __webpack_exports__.resolveContractGateSnapshotPath;
242
- exports.resolveContractGateSnapshotStore = __webpack_exports__.resolveContractGateSnapshotStore;
243
- for(var __rspack_i in __webpack_exports__)if (-1 === [
244
- "CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION",
245
- "DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH",
246
- "createFileContractGateSnapshotStore",
247
- "createHttpContractGateSnapshotStore",
248
- "resolveContractGateSnapshotPath",
249
- "resolveContractGateSnapshotStore"
250
- ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
251
- Object.defineProperty(exports, '__esModule', {
252
- value: true
253
- });