@bleedingdev/modern-js-prod-server 3.2.0-ultramodern.120 → 3.2.0-ultramodern.121

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 (48) hide show
  1. package/dist/cjs/apply.js +5 -3
  2. package/dist/cjs/index.js +8 -8
  3. package/dist/esm/apply.mjs +6 -4
  4. package/dist/esm/index.mjs +1 -1
  5. package/dist/esm-node/apply.mjs +6 -4
  6. package/dist/esm-node/index.mjs +1 -1
  7. package/dist/types/index.d.ts +2 -2
  8. package/package.json +6 -5
  9. package/dist/cjs/libs/contractGateAutopilot.js +0 -40
  10. package/dist/cjs/libs/loadConfig.js +0 -76
  11. package/dist/cjs/libs/metrics.js +0 -45
  12. package/dist/cjs/libs/render/index.js +0 -129
  13. package/dist/cjs/libs/render/ssr.js +0 -122
  14. package/dist/cjs/libs/render/utils.js +0 -76
  15. package/dist/cjs/libs/runtimeFallbackWorkerLane.js +0 -171
  16. package/dist/cjs/libs/telemetry.js +0 -91
  17. package/dist/cjs/server/index.js +0 -583
  18. package/dist/cjs/server/modernServer.js +0 -476
  19. package/dist/cjs/server/modernServerSplit.js +0 -42
  20. package/dist/cjs/utils.js +0 -42
  21. package/dist/esm/libs/contractGateAutopilot.mjs +0 -1
  22. package/dist/esm/libs/loadConfig.mjs +0 -22
  23. package/dist/esm/libs/metrics.mjs +0 -7
  24. package/dist/esm/libs/render/index.mjs +0 -81
  25. package/dist/esm/libs/render/ssr.mjs +0 -73
  26. package/dist/esm/libs/render/utils.mjs +0 -35
  27. package/dist/esm/libs/runtimeFallbackWorkerLane.mjs +0 -130
  28. package/dist/esm/libs/telemetry.mjs +0 -1
  29. package/dist/esm/rslib-runtime.mjs +0 -18
  30. package/dist/esm/server/index.mjs +0 -535
  31. package/dist/esm/server/modernServer.mjs +0 -419
  32. package/dist/esm/server/modernServerSplit.mjs +0 -4
  33. package/dist/esm/utils.mjs +0 -4
  34. package/dist/esm-node/libs/contractGateAutopilot.mjs +0 -2
  35. package/dist/esm-node/libs/loadConfig.mjs +0 -23
  36. package/dist/esm-node/libs/metrics.mjs +0 -8
  37. package/dist/esm-node/libs/render/index.mjs +0 -82
  38. package/dist/esm-node/libs/render/ssr.mjs +0 -75
  39. package/dist/esm-node/libs/render/utils.mjs +0 -36
  40. package/dist/esm-node/libs/runtimeFallbackWorkerLane.mjs +0 -131
  41. package/dist/esm-node/libs/telemetry.mjs +0 -2
  42. package/dist/esm-node/rslib-runtime.mjs +0 -19
  43. package/dist/esm-node/server/index.mjs +0 -536
  44. package/dist/esm-node/server/modernServer.mjs +0 -421
  45. package/dist/esm-node/server/modernServerSplit.mjs +0 -5
  46. package/dist/esm-node/utils.mjs +0 -5
  47. package/dist/types/libs/metrics.d.ts +0 -8
  48. package/dist/types/libs/telemetry.d.ts +0 -2
@@ -1,583 +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
- Server: ()=>Server
41
- });
42
- const server_core_namespaceObject = require("@modern-js/server-core");
43
- const utils_namespaceObject = require("@modern-js/utils");
44
- const external_fs_namespaceObject = require("fs");
45
- const external_path_namespaceObject = require("path");
46
- var external_path_default = /*#__PURE__*/ __webpack_require__.n(external_path_namespaceObject);
47
- const contractGateAutopilot_js_namespaceObject = require("../libs/contractGateAutopilot.js");
48
- const loadConfig_js_namespaceObject = require("../libs/loadConfig.js");
49
- const metrics_js_namespaceObject = require("../libs/metrics.js");
50
- const runtimeFallbackWorkerLane_js_namespaceObject = require("../libs/runtimeFallbackWorkerLane.js");
51
- const telemetry_js_namespaceObject = require("../libs/telemetry.js");
52
- const external_utils_js_namespaceObject = require("../utils.js");
53
- const external_modernServerSplit_js_namespaceObject = require("./modernServerSplit.js");
54
- const CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION = 1;
55
- const DEFAULT_RUNTIME_FALLBACK_GATE_NAME = 'runtime-mf-fallback-health';
56
- const DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS = 300000;
57
- const DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES = 16384;
58
- class Server {
59
- async init({ disableHttpServer = false } = {
60
- disableHttpServer: false
61
- }) {
62
- const { options } = this;
63
- await this.loadServerEnv(options);
64
- this.initServerConfig(options);
65
- await this.injectContext(this.runner, options);
66
- this.runner = await this.createHookRunner();
67
- await this.initConfig(this.runner, options);
68
- await this.initTelemetry(options);
69
- await this.injectContext(this.runner, options);
70
- this.server = this.serverImpl(options);
71
- await this.runPrepareHook(this.runner);
72
- if (!disableHttpServer) this.app = await this.server.createHTTPServer(this.getRequestHandler());
73
- {
74
- const result = await this.runner.beforeServerInit({
75
- app: this.app,
76
- server: this.server
77
- });
78
- ({ app: this.app = this.app, server: this.server } = result);
79
- }
80
- await this.server.onInit(this.runner, this.app);
81
- {
82
- const result = await this.runner.afterServerInit({
83
- app: this.app,
84
- server: this.server
85
- });
86
- ({ app: this.app = this.app, server: this.server } = result);
87
- }
88
- return this;
89
- }
90
- runConfigHook(runner, serverConfig) {
91
- const newServerConfig = runner.config(serverConfig || {});
92
- return newServerConfig;
93
- }
94
- async runPrepareHook(runner) {
95
- runner.prepare();
96
- }
97
- initServerConfig(options) {
98
- const { pwd, serverConfigFile } = options;
99
- const distDirectory = external_path_default().join(pwd, options.config.output.path || 'dist');
100
- const serverConfigPath = (0, loadConfig_js_namespaceObject.getServerConfigPath)(distDirectory, serverConfigFile);
101
- const serverConfig = (0, loadConfig_js_namespaceObject.requireConfig)(serverConfigPath);
102
- this.serverConfig = serverConfig;
103
- }
104
- async initConfig(runner, options) {
105
- const { pwd, config } = options;
106
- const { serverConfig } = this;
107
- const finalServerConfig = this.runConfigHook(runner, serverConfig);
108
- const resolvedConfigPath = (0, utils_namespaceObject.ensureAbsolutePath)(pwd, external_path_default().join(config.output.path || 'dist', utils_namespaceObject.OUTPUT_CONFIG_FILE));
109
- options.config = (0, loadConfig_js_namespaceObject.loadConfig)({
110
- cliConfig: config,
111
- serverConfig: finalServerConfig,
112
- resolvedConfigPath
113
- });
114
- }
115
- async initTelemetry(options) {
116
- const telemetryConfig = options.config.server?.telemetry;
117
- if (!telemetryConfig) return;
118
- const hasEnabledExporters = (0, telemetry_js_namespaceObject.hasEnabledTelemetryExporters)(telemetryConfig);
119
- if (true !== telemetryConfig.enabled && !hasEnabledExporters) return;
120
- const registry = new telemetry_js_namespaceObject.TelemetryRegistry({
121
- service: telemetryConfig.service || options.appContext?.metaName || 'modern-js',
122
- module: telemetryConfig.module || 'server',
123
- environment: telemetryConfig.environment || process.env.MODERN_ENV || process.env.NODE_ENV || 'development',
124
- samplingRate: telemetryConfig.samplingRate,
125
- flushIntervalMs: telemetryConfig.flushIntervalMs,
126
- maxBatchSize: telemetryConfig.maxBatchSize,
127
- maxQueueSize: telemetryConfig.maxQueueSize,
128
- redactionKeys: telemetryConfig.redactionKeys,
129
- slo: {
130
- queueUtilizationWarnThreshold: telemetryConfig.slo?.queueUtilizationWarnThreshold,
131
- queueDroppedWarnThreshold: telemetryConfig.slo?.queueDroppedWarnThreshold,
132
- alertCooldownMs: telemetryConfig.slo?.alertCooldownMs,
133
- onAlert: (alert)=>{
134
- options.logger?.warn(`[telemetry.slo] ${alert.type} threshold=${alert.threshold} value=${alert.value} depth=${alert.queueDepth}/${alert.queueCapacity} dropped=${alert.totalDropped}`);
135
- }
136
- }
137
- });
138
- if (telemetryConfig.exporters?.otlp?.enabled) await registry.register((0, telemetry_js_namespaceObject.createOtlpTelemetryExporter)(telemetryConfig.exporters.otlp));
139
- if (telemetryConfig.exporters?.victoriaMetrics?.enabled) await registry.register((0, telemetry_js_namespaceObject.createVictoriaMetricsTelemetryExporter)(telemetryConfig.exporters.victoriaMetrics));
140
- try {
141
- await registry.startupHealthCheck({
142
- failLoud: telemetryConfig.failLoudStartup ?? true
143
- });
144
- } catch (error) {
145
- await registry.shutdown();
146
- throw error;
147
- }
148
- options.metrics = (0, telemetry_js_namespaceObject.createTelemetryAwareMetrics)(options.metrics || metrics_js_namespaceObject.metrics, registry);
149
- this.telemetryRegistry = registry;
150
- const canaryConfig = telemetryConfig.canary;
151
- if (canaryConfig?.enabled) {
152
- const contractGates = canaryConfig.contractGates;
153
- const orchestrator = new telemetry_js_namespaceObject.TelemetryCanaryOrchestrator({
154
- registry,
155
- evaluationIntervalMs: canaryConfig.evaluationIntervalMs,
156
- minConsecutiveHealthyEvaluations: canaryConfig.minConsecutiveHealthyEvaluations,
157
- rollbackConsecutiveFailures: canaryConfig.rollbackConsecutiveFailures,
158
- maxQueueUtilization: canaryConfig.maxQueueUtilization,
159
- maxTotalDropped: canaryConfig.maxTotalDropped,
160
- maxUnhealthyExporters: canaryConfig.maxUnhealthyExporters,
161
- requiredContractGates: Object.keys(contractGates || {}),
162
- onPromote: (decision)=>{
163
- options.logger?.info(`[telemetry.canary] promoted after ${decision.consecutiveHealthy} healthy evaluations`);
164
- this.emitCanaryDecisionMetric(registry, decision, 'promote');
165
- },
166
- onRollback: (decision)=>{
167
- options.logger?.error(`[telemetry.canary] rollback triggered failures=${decision.failures.map((item)=>item.reason).join(',')}`);
168
- this.emitCanaryDecisionMetric(registry, decision, 'rollback');
169
- }
170
- });
171
- if (contractGates) orchestrator.setContractGates(contractGates);
172
- this.canaryOrchestrator = orchestrator;
173
- orchestrator.start();
174
- const autopilotEnabled = canaryConfig.autopilot?.enabled ?? true;
175
- if (autopilotEnabled) {
176
- const gateSnapshotPath = this.resolveContractGateSnapshotPath(options, canaryConfig.autopilot?.gateSnapshotPath);
177
- this.contractGateAutopilot = new contractGateAutopilot_js_namespaceObject.ContractGateAutopilot({
178
- orchestrator,
179
- gateSnapshotPath,
180
- pollIntervalMs: canaryConfig.autopilot?.pollIntervalMs,
181
- gateStaleAfterMs: canaryConfig.autopilot?.gateStaleAfterMs,
182
- logger: {
183
- info: (message)=>{
184
- options.logger?.info(message);
185
- },
186
- warn: (message)=>{
187
- options.logger?.warn(message);
188
- }
189
- }
190
- });
191
- await this.contractGateAutopilot.start();
192
- const runtimeSignalConfig = canaryConfig.autopilot?.runtimeFallbackSignal;
193
- const runtimeSignalEnabled = runtimeSignalConfig?.enabled ?? true;
194
- if (runtimeSignalEnabled) {
195
- const workerLaneConfig = runtimeSignalConfig?.workerLane;
196
- const workerLaneEnabledFromEnv = 'true' === process.env.MODERN_RUNTIME_FALLBACK_WORKER_LANE;
197
- const workerLaneEnabled = 'boolean' == typeof workerLaneConfig?.enabled ? workerLaneConfig.enabled : workerLaneEnabledFromEnv;
198
- this.runtimeFallbackSignalConfig = {
199
- endpoint: (0, telemetry_js_namespaceObject.resolveRuntimeFallbackSignalEndpoint)(runtimeSignalConfig?.endpoint),
200
- gateName: runtimeSignalConfig?.gateName?.trim() || DEFAULT_RUNTIME_FALLBACK_GATE_NAME,
201
- gateSnapshotPath,
202
- failureHoldMs: Math.max(1000, runtimeSignalConfig?.failureHoldMs ?? DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS),
203
- maxBodyBytes: Math.max(512, runtimeSignalConfig?.maxBodyBytes ?? DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES),
204
- auth: (0, telemetry_js_namespaceObject.normalizeRuntimeFallbackSignalAuthConfig)(runtimeSignalConfig?.auth),
205
- trustPolicy: (0, telemetry_js_namespaceObject.normalizeRuntimeFallbackTrustPolicy)(runtimeSignalConfig?.trustPolicy),
206
- runtimeState: (0, telemetry_js_namespaceObject.createRuntimeFallbackSignalRuntimeState)(),
207
- workerLane: {
208
- enabled: workerLaneEnabled,
209
- timeoutMs: Math.max(25, workerLaneConfig?.timeoutMs ?? runtimeFallbackWorkerLane_js_namespaceObject.DEFAULT_RUNTIME_FALLBACK_WORKER_TIMEOUT_MS),
210
- workerSuccessCount: 0,
211
- fallbackToMainThreadCount: 0
212
- }
213
- };
214
- }
215
- }
216
- orchestrator.evaluate();
217
- }
218
- }
219
- resolveContractGateSnapshotPath(options, configuredPath) {
220
- const rawPath = configuredPath || process.env.MODERN_CONTRACT_GATES_FILE || '.modern/contract-gates.json';
221
- if (external_path_default().isAbsolute(rawPath)) return rawPath;
222
- return external_path_default().resolve(options.pwd, rawPath);
223
- }
224
- emitCanaryDecisionMetric(registry, decision, action) {
225
- try {
226
- registry.enqueueMetric({
227
- name: `telemetry.canary.${action}`,
228
- value: 1,
229
- unit: 'count',
230
- tags: {
231
- action,
232
- state: decision.state,
233
- failures: String(decision.failures.length)
234
- }
235
- });
236
- } catch (_error) {}
237
- }
238
- async close() {
239
- if (this.contractGateAutopilot) {
240
- this.contractGateAutopilot.stop();
241
- this.contractGateAutopilot = void 0;
242
- }
243
- this.runtimeFallbackSignalConfig = void 0;
244
- if (this.canaryOrchestrator) this.canaryOrchestrator.stop();
245
- if (this.telemetryRegistry) await this.telemetryRegistry.shutdown();
246
- if (!this.app) return;
247
- await new Promise((resolve)=>{
248
- this.app.close(()=>resolve());
249
- });
250
- }
251
- listen(options, listener) {
252
- const callback = ()=>{
253
- listener?.();
254
- };
255
- if ('object' == typeof options) {
256
- if (process.env.PORT) Object.assign(options, {
257
- port: process.env.PORT
258
- });
259
- this.app.listen(options, callback);
260
- } else this.app.listen(process.env.PORT || options || 8080, callback);
261
- }
262
- getRequestHandler() {
263
- const requestHandler = this.server.getRequestHandler();
264
- return (req, res, next)=>{
265
- if (this.shouldHandleRuntimeStatus(req)) return void this.handleRuntimeStatus(req, res);
266
- if (this.shouldHandleRuntimeFallbackSignal(req)) return void this.handleRuntimeFallbackSignal(req, res);
267
- return requestHandler(req, res, next);
268
- };
269
- }
270
- shouldHandleRuntimeFallbackSignal(req) {
271
- const runtimeSignalConfig = this.runtimeFallbackSignalConfig;
272
- if (!runtimeSignalConfig) return false;
273
- if ('POST' !== (req.method || 'GET').toUpperCase()) return false;
274
- const pathName = this.getRequestPath(req.url);
275
- return pathName === runtimeSignalConfig.endpoint;
276
- }
277
- shouldHandleRuntimeStatus(req) {
278
- if ('GET' !== (req.method || 'GET').toUpperCase()) return false;
279
- const pathName = this.getRequestPath(req.url);
280
- return pathName === this.runtimeStatusEndpoint;
281
- }
282
- getRequestPath(urlValue) {
283
- try {
284
- const requestUrl = new URL(urlValue || '/', 'http://127.0.0.1');
285
- return requestUrl.pathname;
286
- } catch (_error) {
287
- return '/';
288
- }
289
- }
290
- async readRequestBody(req, maxBodyBytes) {
291
- return new Promise((resolve, reject)=>{
292
- const chunks = [];
293
- let totalBytes = 0;
294
- let done = false;
295
- const cleanup = ()=>{
296
- req.off('data', onData);
297
- req.off('end', onEnd);
298
- req.off('error', onError);
299
- };
300
- const onData = (chunk)=>{
301
- if (done) return;
302
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
303
- totalBytes += buffer.length;
304
- if (totalBytes > maxBodyBytes) {
305
- const error = new Error('runtime fallback signal payload too large');
306
- error.code = 'PAYLOAD_TOO_LARGE';
307
- done = true;
308
- cleanup();
309
- reject(error);
310
- return;
311
- }
312
- chunks.push(buffer);
313
- };
314
- const onEnd = ()=>{
315
- if (done) return;
316
- done = true;
317
- cleanup();
318
- resolve(Buffer.concat(chunks).toString('utf8'));
319
- };
320
- const onError = (error)=>{
321
- if (done) return;
322
- done = true;
323
- cleanup();
324
- reject(error);
325
- };
326
- req.on('data', onData);
327
- req.on('end', onEnd);
328
- req.on('error', onError);
329
- });
330
- }
331
- async handleRuntimeFallbackSignal(req, res) {
332
- const runtimeSignalConfig = this.runtimeFallbackSignalConfig;
333
- if (!runtimeSignalConfig) {
334
- res.statusCode = 404;
335
- res.end();
336
- return;
337
- }
338
- try {
339
- (0, telemetry_js_namespaceObject.enforceRuntimeFallbackSignalAuthToken)(this.getRequestHeader(req, runtimeSignalConfig.auth.headerName), runtimeSignalConfig.auth);
340
- const rawBody = await this.readRequestBody(req, runtimeSignalConfig.maxBodyBytes);
341
- const payload = (0, telemetry_js_namespaceObject.parseRuntimeFallbackSignalPayloadFromRawBody)(rawBody, runtimeSignalConfig.maxBodyBytes);
342
- const trustResult = (0, telemetry_js_namespaceObject.enforceRuntimeFallbackSignalTrustPolicy)(payload, {
343
- trustPolicy: runtimeSignalConfig.trustPolicy,
344
- runtimeState: runtimeSignalConfig.runtimeState
345
- });
346
- if (trustResult.deduped) {
347
- res.statusCode = 202;
348
- res.setHeader('content-type', 'application/json');
349
- res.end('{"ok":true,"deduped":true}');
350
- return;
351
- }
352
- let persistedByWorkerLane = false;
353
- if (runtimeSignalConfig.workerLane.enabled) {
354
- const workerResult = await (0, runtimeFallbackWorkerLane_js_namespaceObject.persistRuntimeFallbackContractGateInWorker)({
355
- snapshotPath: runtimeSignalConfig.gateSnapshotPath,
356
- gateName: runtimeSignalConfig.gateName,
357
- failureHoldMs: runtimeSignalConfig.failureHoldMs,
358
- payload: payload,
359
- schemaVersion: CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION
360
- }, {
361
- enabled: true,
362
- timeoutMs: runtimeSignalConfig.workerLane.timeoutMs
363
- });
364
- if (workerResult.ok) {
365
- persistedByWorkerLane = true;
366
- runtimeSignalConfig.workerLane.workerSuccessCount += 1;
367
- runtimeSignalConfig.workerLane.lastError = void 0;
368
- const payloadRecord = payload;
369
- const reason = 'string' == typeof payloadRecord.reason ? payloadRecord.reason : 'runtime_fallback';
370
- const phase = 'string' == typeof payloadRecord.phase ? payloadRecord.phase : 'unknown';
371
- const appName = 'string' == typeof payloadRecord.appName ? payloadRecord.appName : 'unknown';
372
- this.options.logger?.warn(`[telemetry.canary.autopilot] runtime fallback signal gate=${runtimeSignalConfig.gateName} reason=${reason} phase=${phase} app=${appName} workerLane=true`);
373
- } else {
374
- runtimeSignalConfig.workerLane.fallbackToMainThreadCount += 1;
375
- runtimeSignalConfig.workerLane.lastError = workerResult.error;
376
- this.options.logger?.warn(`[telemetry.canary.autopilot] runtime fallback worker lane fallback: ${workerResult.error || 'unknown_error'}`);
377
- }
378
- }
379
- if (!persistedByWorkerLane) await this.persistRuntimeFallbackContractGate(payload, runtimeSignalConfig);
380
- res.statusCode = 202;
381
- res.setHeader('content-type', 'application/json');
382
- res.end('{"ok":true}');
383
- } catch (error) {
384
- const signalError = error;
385
- res.statusCode = (0, telemetry_js_namespaceObject.getRuntimeSignalErrorStatusCode)(signalError);
386
- res.setHeader('content-type', 'application/json');
387
- res.end(`{"ok":false,"error":${JSON.stringify(signalError instanceof Error ? signalError.message : String(signalError))}}`);
388
- this.options.logger?.warn(`[telemetry.canary.autopilot] runtime fallback signal rejected: ${error instanceof Error ? error.message : String(error)}`);
389
- }
390
- }
391
- async handleRuntimeStatus(req, res) {
392
- try {
393
- if (this.runtimeFallbackSignalConfig?.auth.enabled) (0, telemetry_js_namespaceObject.enforceRuntimeFallbackSignalAuthToken)(this.getRequestHeader(req, this.runtimeFallbackSignalConfig.auth.headerName), this.runtimeFallbackSignalConfig.auth);
394
- res.statusCode = 200;
395
- res.setHeader('content-type', 'application/json');
396
- res.end(JSON.stringify(this.buildRuntimeStatusPayload()));
397
- } catch (error) {
398
- const signalError = error;
399
- res.statusCode = (0, telemetry_js_namespaceObject.getRuntimeSignalErrorStatusCode)(signalError);
400
- res.setHeader('content-type', 'application/json');
401
- res.end(`{"ok":false,"error":${JSON.stringify(signalError instanceof Error ? signalError.message : String(signalError))}}`);
402
- }
403
- }
404
- buildRuntimeStatusPayload() {
405
- const telemetry = this.telemetryRegistry ? {
406
- enabled: true,
407
- queueStats: this.telemetryRegistry.getQueueStats(),
408
- exporterHealth: this.telemetryRegistry.getExporterHealth()
409
- } : {
410
- enabled: false,
411
- queueStats: null,
412
- exporterHealth: []
413
- };
414
- const canary = this.canaryOrchestrator ? {
415
- enabled: true,
416
- ...this.canaryOrchestrator.getStatusSnapshot()
417
- } : {
418
- enabled: false
419
- };
420
- const runtimeFallbackSignal = this.runtimeFallbackSignalConfig ? {
421
- enabled: true,
422
- endpoint: this.runtimeFallbackSignalConfig.endpoint,
423
- gateName: this.runtimeFallbackSignalConfig.gateName,
424
- failureHoldMs: this.runtimeFallbackSignalConfig.failureHoldMs,
425
- maxBodyBytes: this.runtimeFallbackSignalConfig.maxBodyBytes,
426
- auth: {
427
- enabled: this.runtimeFallbackSignalConfig.auth.enabled,
428
- headerName: this.runtimeFallbackSignalConfig.auth.headerName
429
- },
430
- trustPolicy: {
431
- allowedApps: this.runtimeFallbackSignalConfig.trustPolicy.allowedApps,
432
- allowedEntryOrigins: this.runtimeFallbackSignalConfig.trustPolicy.allowedEntryOrigins,
433
- enforceRuntimeDigest: this.runtimeFallbackSignalConfig.trustPolicy.enforceRuntimeDigest,
434
- expectedRuntimeDigestsCount: Object.keys(this.runtimeFallbackSignalConfig.trustPolicy.expectedRuntimeDigests).length,
435
- maxSignalsPerWindow: this.runtimeFallbackSignalConfig.trustPolicy.maxSignalsPerWindow,
436
- windowMs: this.runtimeFallbackSignalConfig.trustPolicy.windowMs,
437
- dedupeWindowMs: this.runtimeFallbackSignalConfig.trustPolicy.dedupeWindowMs
438
- },
439
- workerLane: {
440
- enabled: this.runtimeFallbackSignalConfig.workerLane.enabled,
441
- timeoutMs: this.runtimeFallbackSignalConfig.workerLane.timeoutMs,
442
- workerSuccessCount: this.runtimeFallbackSignalConfig.workerLane.workerSuccessCount,
443
- fallbackToMainThreadCount: this.runtimeFallbackSignalConfig.workerLane.fallbackToMainThreadCount,
444
- lastError: this.runtimeFallbackSignalConfig.workerLane.lastError
445
- }
446
- } : {
447
- enabled: false
448
- };
449
- return {
450
- ok: true,
451
- timestamp: Date.now(),
452
- telemetry,
453
- canary,
454
- runtimeFallbackSignal
455
- };
456
- }
457
- getRequestHeader(req, headerName) {
458
- const raw = req.headers[headerName.toLowerCase()];
459
- if (Array.isArray(raw)) return raw[0];
460
- if ('string' == typeof raw) return raw;
461
- }
462
- async persistRuntimeFallbackContractGate(payload, runtimeSignalConfig) {
463
- const now = Date.now();
464
- const snapshotPath = runtimeSignalConfig.gateSnapshotPath;
465
- let snapshot = {
466
- schemaVersion: CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
467
- updatedAt: now,
468
- gates: {}
469
- };
470
- if (await utils_namespaceObject.fs.pathExists(snapshotPath)) try {
471
- const raw = await external_fs_namespaceObject.promises.readFile(snapshotPath, 'utf8');
472
- const parsed = JSON.parse(raw);
473
- if (parsed && 'object' == typeof parsed) snapshot = {
474
- schemaVersion: 'number' == typeof parsed.schemaVersion ? parsed.schemaVersion : CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
475
- updatedAt: 'number' == typeof parsed.updatedAt ? parsed.updatedAt : now,
476
- gates: parsed.gates && 'object' == typeof parsed.gates ? parsed.gates : {}
477
- };
478
- } catch (_error) {
479
- snapshot = {
480
- schemaVersion: CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
481
- updatedAt: now,
482
- gates: {}
483
- };
484
- }
485
- const reason = 'string' == typeof payload.reason ? payload.reason : 'runtime_fallback';
486
- const phase = 'string' == typeof payload.phase ? payload.phase : 'unknown';
487
- const appName = 'string' == typeof payload.appName ? payload.appName : 'unknown';
488
- const entry = 'string' == typeof payload.entry ? payload.entry : void 0;
489
- snapshot.schemaVersion = CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
490
- snapshot.updatedAt = now;
491
- snapshot.gates = snapshot.gates || {};
492
- snapshot.gates[runtimeSignalConfig.gateName] = {
493
- passed: false,
494
- reason: `runtime_fallback:${reason} phase=${phase} app=${appName}${entry ? ` entry=${entry}` : ''}`,
495
- updatedAt: now,
496
- expiresAt: now + runtimeSignalConfig.failureHoldMs,
497
- source: 'runtime-mf-fallback-signal',
498
- metadata: payload
499
- };
500
- await external_fs_namespaceObject.promises.mkdir(external_path_default().dirname(snapshotPath), {
501
- recursive: true
502
- });
503
- await external_fs_namespaceObject.promises.writeFile(snapshotPath, `${JSON.stringify(snapshot, null, 2)}\n`);
504
- this.options.logger?.warn(`[telemetry.canary.autopilot] runtime fallback signal gate=${runtimeSignalConfig.gateName} reason=${reason} phase=${phase} app=${appName}`);
505
- }
506
- async render(req, res, url) {
507
- return this.server.render(req, res, url);
508
- }
509
- async createHookRunner() {
510
- server_core_namespaceObject.serverManager.clear();
511
- const { options } = this;
512
- const { internalPlugins = utils_namespaceObject.INTERNAL_SERVER_PLUGINS, pwd, plugins = [] } = options;
513
- const serverPlugins = this.serverConfig.plugins || [];
514
- const loadedPlugins = (0, server_core_namespaceObject.loadPlugins)(pwd, [
515
- ...serverPlugins,
516
- ...plugins
517
- ], {
518
- internalPlugins
519
- });
520
- (0, external_utils_js_namespaceObject.debug)('plugins', loadedPlugins);
521
- loadedPlugins.forEach((p)=>{
522
- server_core_namespaceObject.serverManager.usePlugin(p);
523
- });
524
- const hooksRunner = await server_core_namespaceObject.serverManager.init();
525
- return hooksRunner;
526
- }
527
- async injectContext(runner, options) {
528
- const appContext = this.initAppContext();
529
- const { config, pwd } = options;
530
- server_core_namespaceObject.ConfigContext.set(config);
531
- server_core_namespaceObject.AppContext.set({
532
- ...appContext,
533
- distDirectory: external_path_default().join(pwd, config.output.path || 'dist')
534
- });
535
- }
536
- initAppContext() {
537
- const { options } = this;
538
- const { pwd: appDirectory, plugins = [], config, appContext } = options;
539
- const serverPlugins = plugins.map((p)=>({
540
- server: p
541
- }));
542
- return {
543
- appDirectory,
544
- apiDirectory: appContext?.apiDirectory,
545
- lambdaDirectory: appContext?.lambdaDirectory,
546
- sharedDirectory: appContext?.sharedDirectory || external_path_default().resolve(appDirectory, utils_namespaceObject.SHARED_DIR),
547
- distDirectory: external_path_default().join(appDirectory, config.output.path || 'dist'),
548
- plugins: serverPlugins
549
- };
550
- }
551
- async loadServerEnv(options) {
552
- const { pwd: appDirectory } = options;
553
- const serverEnv = process.env.MODERN_ENV;
554
- const defaultEnvPath = external_path_default().resolve(appDirectory, ".env");
555
- const serverEnvPath = external_path_default().resolve(appDirectory, `.env.${serverEnv}`);
556
- for (const envPath of [
557
- serverEnvPath,
558
- defaultEnvPath
559
- ])if (await utils_namespaceObject.fs.pathExists(envPath) && !(await utils_namespaceObject.fs.stat(envPath)).isDirectory()) {
560
- const envConfig = utils_namespaceObject.dotenv.config({
561
- path: envPath
562
- });
563
- (0, utils_namespaceObject.dotenvExpand)(envConfig);
564
- }
565
- }
566
- constructor(options){
567
- this.serverImpl = external_modernServerSplit_js_namespaceObject.createProdServer;
568
- this.runtimeStatusEndpoint = telemetry_js_namespaceObject.DEFAULT_RUNTIME_STATUS_ENDPOINT;
569
- options.logger = options.logger || (0, utils_namespaceObject.createLogger)({
570
- level: 'warn'
571
- });
572
- options.metrics = options.metrics || metrics_js_namespaceObject.metrics;
573
- this.options = options;
574
- this.serverConfig = {};
575
- }
576
- }
577
- exports.Server = __webpack_exports__.Server;
578
- for(var __rspack_i in __webpack_exports__)if (-1 === [
579
- "Server"
580
- ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
581
- Object.defineProperty(exports, '__esModule', {
582
- value: true
583
- });