@astroscope/node 2.1.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +8 -5
  2. package/dist/boot.d.ts +2 -2
  3. package/dist/boot.d.ts.map +1 -1
  4. package/dist/csrf-middleware-entrypoint.d.ts +1 -2
  5. package/dist/csrf-middleware-entrypoint.d.ts.map +1 -1
  6. package/dist/csrf-middleware-entrypoint.js +1 -1
  7. package/dist/dev-middleware-entrypoint.d.ts +1 -2
  8. package/dist/dev-middleware-entrypoint.d.ts.map +1 -1
  9. package/dist/{prepare-CXZsyAVk.js → duplicate-slashes-C6hmOLl9.js} +94 -38
  10. package/dist/duplicate-slashes-C6hmOLl9.js.map +1 -0
  11. package/dist/{excludes-pE23EbmQ.js → excludes-10eDopVB.js} +18 -4
  12. package/dist/excludes-10eDopVB.js.map +1 -0
  13. package/dist/{excludes-BDiE3eyp.d.ts → excludes-rvkVGg6B.d.ts} +11 -3
  14. package/dist/excludes-rvkVGg6B.d.ts.map +1 -0
  15. package/dist/excludes.d.ts +2 -2
  16. package/dist/excludes.js +2 -2
  17. package/dist/graph-DdAxiaxa.js +35 -0
  18. package/dist/graph-DdAxiaxa.js.map +1 -0
  19. package/dist/health.d.ts +3 -4
  20. package/dist/health.d.ts.map +1 -1
  21. package/dist/image-endpoint.d.ts +1 -2
  22. package/dist/image-endpoint.d.ts.map +1 -1
  23. package/dist/index.d.ts +3 -3
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +38 -117
  26. package/dist/index.js.map +1 -1
  27. package/dist/islands-middleware-entrypoint.d.ts +1 -2
  28. package/dist/islands-middleware-entrypoint.d.ts.map +1 -1
  29. package/dist/islands-middleware-entrypoint.js +3 -1
  30. package/dist/islands-middleware-entrypoint.js.map +1 -1
  31. package/dist/islands.d.ts +56 -1
  32. package/dist/islands.d.ts.map +1 -0
  33. package/dist/islands.js +3 -1
  34. package/dist/log/index.d.ts +5 -5
  35. package/dist/log/index.d.ts.map +1 -1
  36. package/dist/native.d.ts +5 -6
  37. package/dist/native.d.ts.map +1 -1
  38. package/dist/{prerendered-DVjzWNbW.js → prerendered-Z-Qi-FFK.js} +4 -4
  39. package/dist/prerendered-Z-Qi-FFK.js.map +1 -0
  40. package/dist/request-route-DcnZOOM4.js.map +1 -1
  41. package/dist/route-islands-B53rE5MH.js +73 -0
  42. package/dist/route-islands-B53rE5MH.js.map +1 -0
  43. package/dist/route-middleware-entrypoint.d.ts +1 -2
  44. package/dist/route-middleware-entrypoint.d.ts.map +1 -1
  45. package/dist/route-store-neUA2nBb.d.ts.map +1 -1
  46. package/dist/routes-D1o_WrJ5.js +39 -0
  47. package/dist/routes-D1o_WrJ5.js.map +1 -0
  48. package/dist/server.d.ts +2 -3
  49. package/dist/server.d.ts.map +1 -1
  50. package/dist/server.js +68 -45
  51. package/dist/server.js.map +1 -1
  52. package/dist/telemetry-B9aziFyQ.js +202 -0
  53. package/dist/telemetry-B9aziFyQ.js.map +1 -0
  54. package/dist/telemetry.d.ts +68 -0
  55. package/dist/telemetry.d.ts.map +1 -0
  56. package/dist/telemetry.js +2 -0
  57. package/dist/transform-Bz5z5w2Y.js +594 -0
  58. package/dist/transform-Bz5z5w2Y.js.map +1 -0
  59. package/package.json +13 -11
  60. package/dist/excludes-BDiE3eyp.d.ts.map +0 -1
  61. package/dist/excludes-pE23EbmQ.js.map +0 -1
  62. package/dist/prepare-CXZsyAVk.js.map +0 -1
  63. package/dist/prerendered-DVjzWNbW.js.map +0 -1
  64. package/dist/transform-BqV8SOEm.js +0 -195
  65. package/dist/transform-BqV8SOEm.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"request-route-DcnZOOM4.js","names":[],"sources":["../src/observability/log/store.ts","../src/observability/request-route.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Logger } from 'pino';\n\n/**\n * Shared state between the public `log` proxy and the server runtime. Keyed on\n * `globalThis` because the two sides may live in different module instances\n * (bundled app vs vite module runner in dev).\n */\n\nconst STORE_KEY = Symbol.for('@astroscope/node/log');\n\nexport const EARLY_LOG_BUFFER_CAP = 100;\n\nexport interface BufferedEntry {\n level: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';\n bindings: Record<string, unknown>[];\n args: unknown[];\n time: number;\n}\n\nexport interface RequestRecord {\n logger: Logger | undefined;\n url: string;\n method: string;\n route: string | undefined;\n routeOverride: boolean;\n actionName: string | undefined;\n}\n\nexport interface LogStore {\n root: Logger | undefined;\n requestStorage: AsyncLocalStorage<RequestRecord>;\n buffer: BufferedEntry[];\n dropped: number;\n}\n\nexport function getLogStore(): LogStore {\n const g = globalThis as Record<symbol, unknown>;\n let store = g[STORE_KEY] as LogStore | undefined;\n\n if (!store) {\n store = { root: undefined, requestStorage: new AsyncLocalStorage(), buffer: [], dropped: 0 };\n g[STORE_KEY] = store;\n }\n\n return store;\n}\n\nexport function getRequestRecord(): RequestRecord | undefined {\n return getLogStore().requestStorage.getStore();\n}\n","import { trace } from '@opentelemetry/api';\nimport { getRequestRecord } from './log/store.js';\n\n/**\n * Apply a route label to the request record (final log line, request duration\n * metric) and the active server span.\n *\n * Last write wins — astro's routing stamps every pass, so a rewrite lands the\n * route that rendered. An override comes from the middleware that knows what it\n * served and outranks routing, whatever the middleware order.\n */\nfunction applyRoute(route: string, method: string, override: boolean): void {\n const record = getRequestRecord();\n\n if (record) {\n if (!override && record.routeOverride) return;\n\n record.route = route;\n\n if (override) {\n record.routeOverride = true;\n }\n }\n\n const span = trace.getActiveSpan();\n\n if (span?.isRecording()) {\n span.setAttribute('http.route', route);\n\n if (!record?.actionName) {\n span.updateName(`${method} ${route}`);\n }\n }\n}\n\n/**\n * Report the route that actually served the current request, overriding the one\n * astro's routing matched.\n *\n * A middleware that rewrites (`next(url)`) or answers with its own response\n * serves a request astro has no page for, so routing matches `/404` and that is\n * what the request is logged and measured as — every such request collapsing\n * into one `/404` bucket in the request metrics. Calling this corrects the log\n * line, the metric and the server span name together.\n *\n * Pass a templated label rather than a concrete path, so metric cardinality\n * stays bounded. No-op outside instrumented requests.\n *\n * @example\n * ```ts\n * import { overrideRequestRoute } from '@astroscope/node/log';\n *\n * export const onRequest: MiddlewareHandler = (ctx, next) => {\n * const page = lookupPage(ctx.url.pathname);\n *\n * if (!page) return next();\n *\n * overrideRequestRoute('/cms/pages/[id]');\n *\n * return next(`/cms/pages/${page.id}`);\n * };\n * ```\n */\nexport function overrideRequestRoute(route: string): void {\n applyRoute(route, getRequestRecord()?.method ?? 'GET', true);\n}\n\n/**\n * Stamp the route astro's routing matched, unless it was overridden by the\n * middleware that served the request.\n * @internal\n */\nexport function setRequestRoute(route: string, method: string): void {\n applyRoute(route, method, false);\n}\n"],"mappings":";;;;;;;;AASA,MAAM,YAAY,OAAO,IAAI,sBAAsB;AA2BnD,SAAgB,cAAwB;CACtC,MAAM,IAAI;CACV,IAAI,QAAQ,EAAE;CAEd,IAAI,CAAC,OAAO;EACV,QAAQ;GAAE,MAAM,KAAA;GAAW,gBAAgB,IAAI,kBAAkB;GAAG,QAAQ,CAAC;GAAG,SAAS;EAAE;EAC3F,EAAE,aAAa;CACjB;CAEA,OAAO;AACT;AAEA,SAAgB,mBAA8C;CAC5D,OAAO,YAAY,CAAC,CAAC,eAAe,SAAS;AAC/C;;;;;;;;;;;ACvCA,SAAS,WAAW,OAAe,QAAgB,UAAyB;CAC1E,MAAM,SAAS,iBAAiB;CAEhC,IAAI,QAAQ;EACV,IAAI,CAAC,YAAY,OAAO,eAAe;EAEvC,OAAO,QAAQ;EAEf,IAAI,UACF,OAAO,gBAAgB;CAE3B;CAEA,MAAM,OAAO,MAAM,cAAc;CAEjC,IAAI,MAAM,YAAY,GAAG;EACvB,KAAK,aAAa,cAAc,KAAK;EAErC,IAAI,CAAC,QAAQ,YACX,KAAK,WAAW,GAAG,OAAO,GAAG,OAAO;CAExC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,qBAAqB,OAAqB;CACxD,WAAW,OAAO,iBAAiB,CAAC,EAAE,UAAU,OAAO,IAAI;AAC7D;;;;;;AAOA,SAAgB,gBAAgB,OAAe,QAAsB;CACnE,WAAW,OAAO,QAAQ,KAAK;AACjC"}
1
+ {"version":3,"file":"request-route-DcnZOOM4.js","names":[],"sources":["../src/observability/log/store.ts","../src/observability/request-route.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Logger } from 'pino';\n\n/**\n * Shared state between the public `log` proxy and the server runtime. Keyed on\n * `globalThis` because the two sides may live in different module instances\n * (bundled app vs vite module runner in dev).\n */\n\nconst STORE_KEY = Symbol.for('@astroscope/node/log');\n\nexport const EARLY_LOG_BUFFER_CAP = 100;\n\nexport interface BufferedEntry {\n level: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';\n bindings: Record<string, unknown>[];\n args: unknown[];\n time: number;\n}\n\nexport interface RequestRecord {\n logger: Logger | undefined;\n url: string;\n method: string;\n route: string | undefined;\n routeOverride: boolean;\n actionName: string | undefined;\n truncated: boolean;\n}\n\nexport interface LogStore {\n root: Logger | undefined;\n requestStorage: AsyncLocalStorage<RequestRecord>;\n buffer: BufferedEntry[];\n dropped: number;\n}\n\nexport function getLogStore(): LogStore {\n const g = globalThis as Record<symbol, unknown>;\n let store = g[STORE_KEY] as LogStore | undefined;\n\n if (!store) {\n store = { root: undefined, requestStorage: new AsyncLocalStorage(), buffer: [], dropped: 0 };\n g[STORE_KEY] = store;\n }\n\n return store;\n}\n\nexport function getRequestRecord(): RequestRecord | undefined {\n return getLogStore().requestStorage.getStore();\n}\n","import { trace } from '@opentelemetry/api';\nimport { getRequestRecord } from './log/store.js';\n\n/**\n * Apply a route label to the request record (final log line, request duration\n * metric) and the active server span.\n *\n * Last write wins — astro's routing stamps every pass, so a rewrite lands the\n * route that rendered. An override comes from the middleware that knows what it\n * served and outranks routing, whatever the middleware order.\n */\nfunction applyRoute(route: string, method: string, override: boolean): void {\n const record = getRequestRecord();\n\n if (record) {\n if (!override && record.routeOverride) return;\n\n record.route = route;\n\n if (override) {\n record.routeOverride = true;\n }\n }\n\n const span = trace.getActiveSpan();\n\n if (span?.isRecording()) {\n span.setAttribute('http.route', route);\n\n if (!record?.actionName) {\n span.updateName(`${method} ${route}`);\n }\n }\n}\n\n/**\n * Report the route that actually served the current request, overriding the one\n * astro's routing matched.\n *\n * A middleware that rewrites (`next(url)`) or answers with its own response\n * serves a request astro has no page for, so routing matches `/404` and that is\n * what the request is logged and measured as — every such request collapsing\n * into one `/404` bucket in the request metrics. Calling this corrects the log\n * line, the metric and the server span name together.\n *\n * Pass a templated label rather than a concrete path, so metric cardinality\n * stays bounded. No-op outside instrumented requests.\n *\n * @example\n * ```ts\n * import { overrideRequestRoute } from '@astroscope/node/log';\n *\n * export const onRequest: MiddlewareHandler = (ctx, next) => {\n * const page = lookupPage(ctx.url.pathname);\n *\n * if (!page) return next();\n *\n * overrideRequestRoute('/cms/pages/[id]');\n *\n * return next(`/cms/pages/${page.id}`);\n * };\n * ```\n */\nexport function overrideRequestRoute(route: string): void {\n applyRoute(route, getRequestRecord()?.method ?? 'GET', true);\n}\n\n/**\n * Stamp the route astro's routing matched, unless it was overridden by the\n * middleware that served the request.\n * @internal\n */\nexport function setRequestRoute(route: string, method: string): void {\n applyRoute(route, method, false);\n}\n"],"mappings":";;;;;;;;AASA,MAAM,YAAY,OAAO,IAAI,sBAAsB;AA4BnD,SAAgB,cAAwB;CACtC,MAAM,IAAI;CACV,IAAI,QAAQ,EAAE;CAEd,IAAI,CAAC,OAAO;EACV,QAAQ;GAAE,MAAM,KAAA;GAAW,gBAAgB,IAAI,kBAAkB;GAAG,QAAQ,CAAC;GAAG,SAAS;EAAE;EAC3F,EAAE,aAAa;CACjB;CAEA,OAAO;AACT;AAEA,SAAgB,mBAA8C;CAC5D,OAAO,YAAY,CAAC,CAAC,eAAe,SAAS;AAC/C;;;;;;;;;;;ACxCA,SAAS,WAAW,OAAe,QAAgB,UAAyB;CAC1E,MAAM,SAAS,iBAAiB;CAEhC,IAAI,QAAQ;EACV,IAAI,CAAC,YAAY,OAAO,eAAe;EAEvC,OAAO,QAAQ;EAEf,IAAI,UACF,OAAO,gBAAgB;CAE3B;CAEA,MAAM,OAAO,MAAM,cAAc;CAEjC,IAAI,MAAM,YAAY,GAAG;EACvB,KAAK,aAAa,cAAc,KAAK;EAErC,IAAI,CAAC,QAAQ,YACX,KAAK,WAAW,GAAG,OAAO,GAAG,OAAO;CAExC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,qBAAqB,OAAqB;CACxD,WAAW,OAAO,iBAAiB,CAAC,EAAE,UAAU,OAAO,IAAI;AAC7D;;;;;;AAOA,SAAgB,gBAAgB,OAAe,QAAsB;CACnE,WAAW,OAAO,QAAQ,KAAK;AACjC"}
@@ -0,0 +1,73 @@
1
+ import path from "node:path";
2
+ //#region src/islands/route-islands.ts
3
+ const ACTIONS_ROUTE_PATTERN = "/_actions/[...path]";
4
+ const ACTIONS_ENTRYPOINT_MODULE_ID = "\0virtual:astro:actions/entrypoint";
5
+ const WALK_BOUNDARY_MODULE_IDS = /* @__PURE__ */ new Set(["\0virtual:astro:manifest"]);
6
+ /**
7
+ * Route modules (absolute ids) → the route patterns they serve, for the walk:
8
+ * pages and endpoints (endpoints have no islands, but consumers still want them
9
+ * as known routes), one component possibly backing several routes.
10
+ */
11
+ function routeEntrypoints(root, routes) {
12
+ const entrypoints = /* @__PURE__ */ new Map();
13
+ for (const route of routes) {
14
+ if (route.type !== "page" && route.type !== "endpoint") continue;
15
+ const id = route.pattern === ACTIONS_ROUTE_PATTERN ? ACTIONS_ENTRYPOINT_MODULE_ID : path.resolve(root, route.entrypoint);
16
+ entrypoints.set(id, [...entrypoints.get(id) ?? [], route.pattern]);
17
+ }
18
+ return entrypoints;
19
+ }
20
+ /** module ids can carry vite queries (`?astro&type=...`) — the file path is the identity */
21
+ function stripQuery(id) {
22
+ const at = id.indexOf("?");
23
+ return at === -1 ? id : id.slice(0, at);
24
+ }
25
+ /**
26
+ * `pages` maps a page component's absolute path to the patterns of the routes it
27
+ * serves (one component can back several routes).
28
+ */
29
+ async function collectRouteIslands(graph, pages) {
30
+ const patternsByModule = /* @__PURE__ */ new Map();
31
+ const routes = /* @__PURE__ */ new Map();
32
+ const islandsByModule = /* @__PURE__ */ new Map();
33
+ for (const id of graph.getModuleIds()) {
34
+ const meta = graph.getModuleInfo(id)?.meta?.["astro"];
35
+ if (!meta) continue;
36
+ const islands = [];
37
+ for (const component of [...meta.hydratedComponents ?? [], ...meta.clientOnlyComponents ?? []]) if (component.resolvedPath) islands.push(stripQuery(decodeURI(component.resolvedPath)));
38
+ else {
39
+ const resolved = await graph.resolve(component.specifier, id);
40
+ if (resolved) islands.push(stripQuery(resolved.id));
41
+ }
42
+ if (islands.length > 0) islandsByModule.set(id, islands);
43
+ }
44
+ for (const [page, patterns] of pages) {
45
+ if (!graph.getModuleInfo(page)) continue;
46
+ const islands = /* @__PURE__ */ new Set();
47
+ const visited = /* @__PURE__ */ new Set();
48
+ const stack = [page];
49
+ while (stack.length > 0) {
50
+ const id = stack.pop();
51
+ if (visited.has(id) || WALK_BOUNDARY_MODULE_IDS.has(id)) continue;
52
+ visited.add(id);
53
+ let owners = patternsByModule.get(id);
54
+ if (!owners) {
55
+ owners = /* @__PURE__ */ new Set();
56
+ patternsByModule.set(id, owners);
57
+ }
58
+ patterns.forEach((pattern) => owners.add(pattern));
59
+ islandsByModule.get(id)?.forEach((island) => islands.add(island));
60
+ const moduleInfo = graph.getModuleInfo(id);
61
+ if (moduleInfo) stack.push(...moduleInfo.importedIds, ...moduleInfo.dynamicallyImportedIds);
62
+ }
63
+ for (const pattern of patterns) routes.set(pattern, islands);
64
+ }
65
+ return {
66
+ routes,
67
+ patternsByModule
68
+ };
69
+ }
70
+ //#endregion
71
+ export { routeEntrypoints as n, stripQuery as r, collectRouteIslands as t };
72
+
73
+ //# sourceMappingURL=route-islands-B53rE5MH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-islands-B53rE5MH.js","names":[],"sources":["../src/islands/route-islands.ts"],"sourcesContent":["import path from 'node:path';\nimport type { IntegrationResolvedRoute } from 'astro';\nimport type { Rolldown } from 'vite';\n\n/**\n * Build-time attribution of islands to routes, from the server build's module\n * graph: every module reachable from a page component belongs to that page's\n * routes, and the hydrated / `client:only` components astro's compiler recorded\n * on such a module are the route's islands. Same walk astro does for its own\n * client entries, kept independent of its internals — page modules are matched by\n * the route entrypoints astro resolved, not by its virtual page wrappers.\n */\n\ntype AstroComponentMeta = { exportName: string; specifier: string; resolvedPath?: string | undefined };\n\ntype AstroModuleMeta = {\n hydratedComponents?: AstroComponentMeta[] | undefined;\n clientOnlyComponents?: AstroComponentMeta[] | undefined;\n};\n\nexport type ModuleGraph = {\n getModuleIds(): IterableIterator<string>;\n getModuleInfo(id: string): Rolldown.ModuleInfo | null;\n resolve(source: string, importer: string): Promise<{ id: string } | null>;\n};\n\nexport type RouteIslandsResult = {\n /** route pattern → island component ids (absolute module ids, query stripped); pages missing from the graph are absent */\n routes: Map<string, Set<string>>;\n /** module id → route patterns whose page reaches it, the whole server module graph */\n patternsByModule: Map<string, Set<string>>;\n};\n\n// astro's actions route module reaches the project's actions through the ssr\n// manifest, not through an import — the virtual entrypoint wrapping them is the\n// module the walk has to start from\nconst ACTIONS_ROUTE_PATTERN = '/_actions/[...path]';\nconst ACTIONS_ENTRYPOINT_MODULE_ID = '\\0virtual:astro:actions/entrypoint';\n\n// astro's application manifest imports every page and the middleware\nconst WALK_BOUNDARY_MODULE_IDS = new Set(['\\0virtual:astro:manifest']);\n\n/**\n * Route modules (absolute ids) → the route patterns they serve, for the walk:\n * pages and endpoints (endpoints have no islands, but consumers still want them\n * as known routes), one component possibly backing several routes.\n */\nexport function routeEntrypoints(root: string, routes: readonly IntegrationResolvedRoute[]): Map<string, string[]> {\n const entrypoints = new Map<string, string[]>();\n\n for (const route of routes) {\n if (route.type !== 'page' && route.type !== 'endpoint') continue;\n\n const id =\n route.pattern === ACTIONS_ROUTE_PATTERN ? ACTIONS_ENTRYPOINT_MODULE_ID : path.resolve(root, route.entrypoint);\n\n entrypoints.set(id, [...(entrypoints.get(id) ?? []), route.pattern]);\n }\n\n return entrypoints;\n}\n\n/** module ids can carry vite queries (`?astro&type=...`) — the file path is the identity */\nexport function stripQuery(id: string): string {\n const at = id.indexOf('?');\n\n return at === -1 ? id : id.slice(0, at);\n}\n\n/**\n * `pages` maps a page component's absolute path to the patterns of the routes it\n * serves (one component can back several routes).\n */\nexport async function collectRouteIslands(\n graph: ModuleGraph,\n pages: Map<string, string[]>,\n): Promise<RouteIslandsResult> {\n const patternsByModule = new Map<string, Set<string>>();\n const routes = new Map<string, Set<string>>();\n const islandsByModule = new Map<string, string[]>();\n\n for (const id of graph.getModuleIds()) {\n const meta = graph.getModuleInfo(id)?.meta?.['astro'] as AstroModuleMeta | undefined;\n\n if (!meta) {\n continue;\n }\n\n const islands: string[] = [];\n\n for (const component of [...(meta.hydratedComponents ?? []), ...(meta.clientOnlyComponents ?? [])]) {\n if (component.resolvedPath) {\n islands.push(stripQuery(decodeURI(component.resolvedPath)));\n } else {\n // `client:only` components are dropped from the server graph — resolve the specifier ourselves\n const resolved = await graph.resolve(component.specifier, id);\n\n if (resolved) {\n islands.push(stripQuery(resolved.id));\n }\n }\n }\n\n if (islands.length > 0) {\n islandsByModule.set(id, islands);\n }\n }\n\n for (const [page, patterns] of pages) {\n const info = graph.getModuleInfo(page);\n\n if (!info) {\n continue;\n }\n\n const islands = new Set<string>();\n const visited = new Set<string>();\n const stack = [page];\n\n while (stack.length > 0) {\n const id = stack.pop()!;\n\n if (visited.has(id) || WALK_BOUNDARY_MODULE_IDS.has(id)) {\n continue;\n }\n\n visited.add(id);\n\n let owners = patternsByModule.get(id);\n\n if (!owners) {\n owners = new Set();\n patternsByModule.set(id, owners);\n }\n\n patterns.forEach((pattern) => owners.add(pattern));\n islandsByModule.get(id)?.forEach((island) => islands.add(island));\n\n const moduleInfo = graph.getModuleInfo(id);\n\n if (moduleInfo) {\n stack.push(...moduleInfo.importedIds, ...moduleInfo.dynamicallyImportedIds);\n }\n }\n\n for (const pattern of patterns) {\n routes.set(pattern, islands);\n }\n }\n\n return { routes, patternsByModule };\n}\n"],"mappings":";;AAoCA,MAAM,wBAAwB;AAC9B,MAAM,+BAA+B;AAGrC,MAAM,2CAA2B,IAAI,IAAI,CAAC,0BAA0B,CAAC;;;;;;AAOrE,SAAgB,iBAAiB,MAAc,QAAoE;CACjH,MAAM,8BAAc,IAAI,IAAsB;CAE9C,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,MAAM,SAAS,UAAU,MAAM,SAAS,YAAY;EAExD,MAAM,KACJ,MAAM,YAAY,wBAAwB,+BAA+B,KAAK,QAAQ,MAAM,MAAM,UAAU;EAE9G,YAAY,IAAI,IAAI,CAAC,GAAI,YAAY,IAAI,EAAE,KAAK,CAAC,GAAI,MAAM,OAAO,CAAC;CACrE;CAEA,OAAO;AACT;;AAGA,SAAgB,WAAW,IAAoB;CAC7C,MAAM,KAAK,GAAG,QAAQ,GAAG;CAEzB,OAAO,OAAO,KAAK,KAAK,GAAG,MAAM,GAAG,EAAE;AACxC;;;;;AAMA,eAAsB,oBACpB,OACA,OAC6B;CAC7B,MAAM,mCAAmB,IAAI,IAAyB;CACtD,MAAM,yBAAS,IAAI,IAAyB;CAC5C,MAAM,kCAAkB,IAAI,IAAsB;CAElD,KAAK,MAAM,MAAM,MAAM,aAAa,GAAG;EACrC,MAAM,OAAO,MAAM,cAAc,EAAE,CAAC,EAAE,OAAO;EAE7C,IAAI,CAAC,MACH;EAGF,MAAM,UAAoB,CAAC;EAE3B,KAAK,MAAM,aAAa,CAAC,GAAI,KAAK,sBAAsB,CAAC,GAAI,GAAI,KAAK,wBAAwB,CAAC,CAAE,GAC/F,IAAI,UAAU,cACZ,QAAQ,KAAK,WAAW,UAAU,UAAU,YAAY,CAAC,CAAC;OACrD;GAEL,MAAM,WAAW,MAAM,MAAM,QAAQ,UAAU,WAAW,EAAE;GAE5D,IAAI,UACF,QAAQ,KAAK,WAAW,SAAS,EAAE,CAAC;EAExC;EAGF,IAAI,QAAQ,SAAS,GACnB,gBAAgB,IAAI,IAAI,OAAO;CAEnC;CAEA,KAAK,MAAM,CAAC,MAAM,aAAa,OAAO;EAGpC,IAAI,CAFS,MAAM,cAAc,IAEzB,GACN;EAGF,MAAM,0BAAU,IAAI,IAAY;EAChC,MAAM,0BAAU,IAAI,IAAY;EAChC,MAAM,QAAQ,CAAC,IAAI;EAEnB,OAAO,MAAM,SAAS,GAAG;GACvB,MAAM,KAAK,MAAM,IAAI;GAErB,IAAI,QAAQ,IAAI,EAAE,KAAK,yBAAyB,IAAI,EAAE,GACpD;GAGF,QAAQ,IAAI,EAAE;GAEd,IAAI,SAAS,iBAAiB,IAAI,EAAE;GAEpC,IAAI,CAAC,QAAQ;IACX,yBAAS,IAAI,IAAI;IACjB,iBAAiB,IAAI,IAAI,MAAM;GACjC;GAEA,SAAS,SAAS,YAAY,OAAO,IAAI,OAAO,CAAC;GACjD,gBAAgB,IAAI,EAAE,CAAC,EAAE,SAAS,WAAW,QAAQ,IAAI,MAAM,CAAC;GAEhE,MAAM,aAAa,MAAM,cAAc,EAAE;GAEzC,IAAI,YACF,MAAM,KAAK,GAAG,WAAW,aAAa,GAAG,WAAW,sBAAsB;EAE9E;EAEA,KAAK,MAAM,WAAW,UACpB,OAAO,IAAI,SAAS,OAAO;CAE/B;CAEA,OAAO;EAAE;EAAQ;CAAiB;AACpC"}
@@ -8,7 +8,6 @@ import { MiddlewareHandler } from "astro";
8
8
  * reports it itself via `overrideRequestRoute`, which wins over this. No-op
9
9
  * outside instrumented requests.
10
10
  */
11
- declare const onRequest: MiddlewareHandler;
11
+ export declare const onRequest: MiddlewareHandler;
12
12
  //#endregion
13
- export { onRequest };
14
13
  //# sourceMappingURL=route-middleware-entrypoint.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"route-middleware-entrypoint.d.ts","names":[],"sources":["../src/observability/route-middleware-entrypoint.ts"],"mappings":";;;;;;;;;;cAWa,WAAW"}
1
+ {"version":3,"file":"route-middleware-entrypoint.d.ts","names":[],"sources":["../src/observability/route-middleware-entrypoint.ts"],"mappings":";;;;;;;;;;qBAWa,WAAW"}
@@ -1 +1 @@
1
- {"version":3,"file":"route-store-neUA2nBb.d.ts","names":[],"sources":["../src/islands/types.ts","../src/islands/emitters.ts","../src/server/route-store.ts"],"mappings":";;;;;;;KAqBY;EACV;EACA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;KAcU;EACV;EACA;EACA;;;;;;KAOU,iBAAiB,QAAQ,YAAY,UAAU,2BAA2B;;;;KAK1E;EACV;EACA;;;;;;;KAQU,mBAAmB,SAAS,eAAe;;;;;;;;iBCvCvC,sBAAsB,SAAS;;;;;;;iBAc/B,wBAAwB,SAAS;;;iBCpBjC,oBAAoB,SAAS,SAAS,WAAW;iBAIjD,oBAAoB,SAAS,UAAU"}
1
+ {"version":3,"file":"route-store-neUA2nBb.d.ts","names":[],"sources":["../src/islands/types.ts","../src/islands/emitters.ts","../src/server/route-store.ts"],"mappings":";;;;;;;KA4BY;EACV;EACA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;KAcU;EACV;EACA;EACA;;;;;;KAOU,iBAAiB,QAAQ,YAAY,UAAU,2BAA2B;;;;KAK1E;EACV;EACA;;;;;;;KAQU,mBAAmB,SAAS,eAAe;;;;;;;;iBC9CvC,sBAAsB,SAAS;;;;;;;iBAc/B,wBAAwB,SAAS;;;iBCpBjC,oBAAoB,SAAS,SAAS,WAAW;iBAIjD,oBAAoB,SAAS,UAAU"}
@@ -0,0 +1,39 @@
1
+ import { t as createChunkGraph } from "./graph-DdAxiaxa.js";
2
+ //#region src/islands/routes.ts
3
+ const STORE = Symbol.for("@astroscope/node.routeIslands");
4
+ function installRouteIslands(manifest) {
5
+ const routes = manifest?.routes;
6
+ if (!routes) {
7
+ globalThis[STORE] = () => null;
8
+ return;
9
+ }
10
+ let graph;
11
+ const cache = /* @__PURE__ */ new Map();
12
+ globalThis[STORE] = (pattern) => {
13
+ const cached = cache.get(pattern);
14
+ if (cached) return cached;
15
+ const fileNames = routes[pattern];
16
+ if (!fileNames) return null;
17
+ graph ??= createChunkGraph(manifest);
18
+ const islands = fileNames.map((fileName) => ({
19
+ fileName,
20
+ staticClosure: [fileName, ...graph.staticClosure(fileName)],
21
+ fullClosure: [fileName, ...graph.fullClosure(fileName)]
22
+ }));
23
+ cache.set(pattern, islands);
24
+ return islands;
25
+ };
26
+ }
27
+ /**
28
+ * The islands a route's page hydrates, from the build-time attribution — `null`
29
+ * when unknown: in dev, without a manifest, or for a route whose page the server
30
+ * build did not see (astro's own injected routes, server islands). Callers
31
+ * treat `null` as "anything", never as "nothing".
32
+ */
33
+ function getRouteIslands(pattern) {
34
+ return globalThis[STORE]?.(pattern) ?? null;
35
+ }
36
+ //#endregion
37
+ export { installRouteIslands as n, getRouteIslands as t };
38
+
39
+ //# sourceMappingURL=routes-D1o_WrJ5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes-D1o_WrJ5.js","names":[],"sources":["../src/islands/routes.ts"],"sourcesContent":["import { type ChunkGraph, createChunkGraph } from './graph.js';\nimport type { IslandsManifest } from './types.js';\n\n/**\n * Route → islands at runtime, for packages that must know before rendering what a\n * page will hydrate (per-route data loading). Installed by the islands middleware\n * entry from the manifest; keyed on `globalThis` via `Symbol.for` so the\n * vite-runner and native module instances share it. Closures are dist-relative\n * chunk file names — there is no island tag to observe a public prefix on yet.\n */\nexport type RouteIsland = {\n /** the island's entry chunk, relative to the client dist (e.g. `_astro/Cart.abc123.js`) */\n fileName: string;\n /** the entry plus its transitive static imports */\n staticClosure: string[];\n /** the entry plus its transitive static and dynamic imports */\n fullClosure: string[];\n};\n\ntype Resolver = (pattern: string) => RouteIsland[] | null;\n\nconst STORE = Symbol.for('@astroscope/node.routeIslands');\n\ntype Scope = { [STORE]?: Resolver };\n\nexport function installRouteIslands(manifest: IslandsManifest | null): void {\n const routes = manifest?.routes;\n\n if (!routes) {\n (globalThis as Scope)[STORE] = () => null;\n\n return;\n }\n\n let graph: ChunkGraph | undefined;\n const cache = new Map<string, RouteIsland[]>();\n\n (globalThis as Scope)[STORE] = (pattern) => {\n const cached = cache.get(pattern);\n\n if (cached) {\n return cached;\n }\n\n const fileNames = routes[pattern];\n\n if (!fileNames) {\n return null;\n }\n\n graph ??= createChunkGraph(manifest);\n\n const islands = fileNames.map((fileName) => ({\n fileName,\n staticClosure: [fileName, ...graph!.staticClosure(fileName)],\n fullClosure: [fileName, ...graph!.fullClosure(fileName)],\n }));\n\n cache.set(pattern, islands);\n\n return islands;\n };\n}\n\n/**\n * The islands a route's page hydrates, from the build-time attribution — `null`\n * when unknown: in dev, without a manifest, or for a route whose page the server\n * build did not see (astro's own injected routes, server islands). Callers\n * treat `null` as \"anything\", never as \"nothing\".\n */\nexport function getRouteIslands(pattern: string): RouteIsland[] | null {\n return (globalThis as Scope)[STORE]?.(pattern) ?? null;\n}\n"],"mappings":";;AAqBA,MAAM,QAAQ,OAAO,IAAI,+BAA+B;AAIxD,SAAgB,oBAAoB,UAAwC;CAC1E,MAAM,SAAS,UAAU;CAEzB,IAAI,CAAC,QAAQ;EACX,WAAsB,eAAe;EAErC;CACF;CAEA,IAAI;CACJ,MAAM,wBAAQ,IAAI,IAA2B;CAE7C,WAAsB,UAAU,YAAY;EAC1C,MAAM,SAAS,MAAM,IAAI,OAAO;EAEhC,IAAI,QACF,OAAO;EAGT,MAAM,YAAY,OAAO;EAEzB,IAAI,CAAC,WACH,OAAO;EAGT,UAAU,iBAAiB,QAAQ;EAEnC,MAAM,UAAU,UAAU,KAAK,cAAc;GAC3C;GACA,eAAe,CAAC,UAAU,GAAG,MAAO,cAAc,QAAQ,CAAC;GAC3D,aAAa,CAAC,UAAU,GAAG,MAAO,YAAY,QAAQ,CAAC;EACzD,EAAE;EAEF,MAAM,IAAI,SAAS,OAAO;EAE1B,OAAO;CACT;AACF;;;;;;;AAQA,SAAgB,gBAAgB,SAAuC;CACrE,OAAQ,WAAqB,MAAM,GAAG,OAAO,KAAK;AACpD"}
package/dist/server.d.ts CHANGED
@@ -1,14 +1,13 @@
1
1
  //#region src/server/server.d.ts
2
- interface ServerHandle {
2
+ export interface ServerHandle {
3
3
  host: string;
4
4
  port: number;
5
5
  stop(): Promise<void>;
6
6
  closed(): Promise<void>;
7
7
  }
8
- declare function startServer(overrides?: {
8
+ export declare function startServer(overrides?: {
9
9
  host?: string | undefined;
10
10
  port?: number | undefined;
11
11
  }): Promise<ServerHandle>;
12
12
  //#endregion
13
- export { ServerHandle, startServer };
14
13
  //# sourceMappingURL=server.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","names":[],"sources":["../src/server/server.ts"],"mappings":";UAoFiB;EACf;EACA;EACA,QAAQ;EACR,UAAU;;iBAGU,YAAY;EAChC;EACA;IACE,QAAQ"}
1
+ {"version":3,"file":"server.d.ts","names":[],"sources":["../src/server/server.ts"],"mappings":";iBAsFiB;EACf;EACA;EACA,QAAQ;EACR,UAAU;;wBAGU,YAAY;EAChC;EACA;IACE,QAAQ"}
package/dist/server.js CHANGED
@@ -1,15 +1,17 @@
1
1
  import { n as setBootContext } from "./context-Bkg-FnnQ.js";
2
- import { a as runShutdown, i as createRequestInstrumentation, n as shutdownTelemetry, o as runStartup, r as dumpEarlyLogs, t as preparePlatform } from "./prepare-CXZsyAVk.js";
2
+ import { a as createRequestInstrumentation, i as dumpEarlyLogs, n as preparePlatform, o as runShutdown, r as shutdownTelemetry, s as runStartup, t as redirectDuplicateSlashes } from "./duplicate-slashes-C6hmOLl9.js";
3
3
  import { i as getRequestRecord } from "./request-route-DcnZOOM4.js";
4
4
  import { n as log } from "./log-B69HEBvg.js";
5
5
  import { n as dispatchNativeMount, t as clearNativeMounts } from "./native-mount-DjYEnO4X.js";
6
+ import { c as withSpan, s as startSpan } from "./telemetry-B9aziFyQ.js";
6
7
  import { n as setRequestRouteData } from "./route-store-DdxGePj2.js";
7
8
  import { n as deactivateHealthChecks, t as activateHealthChecks } from "./store-8pnTxM1x.js";
8
9
  import { n as MIME_TYPES, t as COMPRESSIBLE } from "./mime-C_GwZovh.js";
9
10
  import fs, { createReadStream } from "node:fs";
10
11
  import path from "node:path";
11
12
  import url from "node:url";
12
- import { SpanStatusCode, context, trace } from "@opentelemetry/api";
13
+ import { defined } from "@entwico/dash";
14
+ import { SpanStatusCode } from "@opentelemetry/api";
13
15
  import http from "node:http";
14
16
  import https from "node:https";
15
17
  import { checks, probes, server } from "@entwico/health-probes";
@@ -17,39 +19,8 @@ import { createApp } from "astro/app/entrypoint";
17
19
  import { setGetEnv } from "astro/env/setup";
18
20
  import { options } from "virtual:@astroscope/node/config";
19
21
  import { Readable } from "node:stream";
20
- import { createRequestFromNodeRequest, writeResponse } from "astro/app/node";
22
+ import { createRequestFromNodeRequest, getAbortControllerCleanup } from "astro/app/node";
21
23
  import send from "send";
22
- //#region src/observability/telemetry/lifecycle.ts
23
- const LIB_NAME = "@astroscope/node";
24
- /**
25
- * Lifecycle spans (`startup` / `shutdown` with phase children). No-op when no
26
- * SDK is registered — `trace.getTracer` returns the no-op tracer.
27
- */
28
- function startLifecycleSpan(name, parent) {
29
- const parentContext = parent ?? context.active();
30
- const span = trace.getTracer(LIB_NAME).startSpan(name, void 0, parentContext);
31
- return {
32
- span,
33
- context: trace.setSpan(parentContext, span)
34
- };
35
- }
36
- async function withLifecycleSpan(name, parent, fn) {
37
- const { span, context: spanContext } = startLifecycleSpan(name, parent);
38
- try {
39
- const result = await context.with(spanContext, fn);
40
- span.setStatus({ code: SpanStatusCode.OK });
41
- return result;
42
- } catch (err) {
43
- span.setStatus({
44
- code: SpanStatusCode.ERROR,
45
- message: err instanceof Error ? err.message : "unknown error"
46
- });
47
- throw err;
48
- } finally {
49
- span.end();
50
- }
51
- }
52
- //#endregion
53
24
  //#region src/server/client-dir.ts
54
25
  /**
55
26
  * Resolve the client directory at runtime relative to the built server entry.
@@ -93,6 +64,58 @@ async function readFSErrorPage(client, status) {
93
64
  }
94
65
  }
95
66
  }
67
+ function createOutgoingHttpHeaders(headers) {
68
+ const nodeHeaders = Object.fromEntries(headers.entries());
69
+ if (Object.keys(nodeHeaders).length === 0) return;
70
+ const cookies = headers.getSetCookie();
71
+ if (cookies.length > 1) nodeHeaders["set-cookie"] = cookies;
72
+ return nodeHeaders;
73
+ }
74
+ /**
75
+ * Streams the web response into the node response. A render failing after the
76
+ * first chunk cannot change the status anymore, so it is logged through the
77
+ * request logger and marked on the request record — the completion line, the
78
+ * span and `astro.render.failures` reflect it. On the wire it behaves like
79
+ * astro's own writer: an `Internal server error` marker, then the socket is
80
+ * destroyed.
81
+ */
82
+ async function writeResponse(response, res) {
83
+ res.statusMessage = response.statusText;
84
+ res.writeHead(response.status, createOutgoingHttpHeaders(response.headers));
85
+ const cleanupAbort = getAbortControllerCleanup(res.req);
86
+ if (cleanupAbort) {
87
+ const runCleanup = () => {
88
+ cleanupAbort();
89
+ res.off("finish", runCleanup);
90
+ res.off("close", runCleanup);
91
+ };
92
+ res.on("finish", runCleanup);
93
+ res.on("close", runCleanup);
94
+ }
95
+ if (!response.body) {
96
+ res.end();
97
+ return;
98
+ }
99
+ const reader = response.body.getReader();
100
+ res.on("close", () => {
101
+ reader.cancel().catch(() => void 0);
102
+ });
103
+ try {
104
+ for (let result = await reader.read(); !result.done; result = await reader.read()) res.write(result.value);
105
+ res.end();
106
+ } catch (err) {
107
+ const record = getRequestRecord();
108
+ if (record) record.truncated = true;
109
+ log.error({
110
+ ...err instanceof Error ? { err } : { reason: err },
111
+ ...record?.route && { route: record.route },
112
+ ...!record?.logger && { url: record?.url ?? res.req.url }
113
+ }, "render failed after the response started, response truncated");
114
+ res.write("Internal server error", () => {
115
+ res.destroy(err instanceof Error ? err : void 0);
116
+ });
117
+ }
118
+ }
96
119
  /**
97
120
  * Render on-demand routes: node req → web Request → `app.render()` → node res.
98
121
  * Prerendered pages never reach this handler (the static handler serves them);
@@ -138,15 +161,14 @@ function createAppHandler(app, options, client) {
138
161
  const routeData = app.match(request, true);
139
162
  const matched = routeData && !(routeData.type === "page" && routeData.prerender) ? routeData : void 0;
140
163
  if (matched) setRequestRouteData(request, matched);
141
- const response = matched ? await app.render(request, {
164
+ await writeResponse(matched ? await app.render(request, {
142
165
  addCookieHeader: true,
143
166
  routeData: matched,
144
167
  prerenderedErrorPageFetch
145
168
  }) : await app.render(request, {
146
169
  addCookieHeader: true,
147
170
  prerenderedErrorPageFetch
148
- });
149
- await writeResponse(response, res);
171
+ }), res);
150
172
  };
151
173
  }
152
174
  //#endregion
@@ -280,7 +302,7 @@ async function warmupModules() {
280
302
  app.manifest.actions,
281
303
  app.manifest.sessionDriver,
282
304
  app.manifest.serverIslandMappings
283
- ].filter((load) => load !== void 0);
305
+ ].filter(defined);
284
306
  const failures = (await Promise.allSettled(loaders.map((load) => load()))).filter((result) => result.status === "rejected");
285
307
  if (failures.length === 0) return;
286
308
  for (const failure of failures) log.error(failure.reason instanceof Error ? { err: failure.reason } : { reason: failure.reason }, "warmup import failed");
@@ -335,7 +357,7 @@ async function startServer(overrides) {
335
357
  activateHealthChecks(checks);
336
358
  log.debug("health probes listening");
337
359
  }
338
- const startup = startLifecycleSpan("startup");
360
+ const startup = startSpan("startup");
339
361
  log.info({
340
362
  host,
341
363
  port
@@ -344,7 +366,7 @@ async function startServer(overrides) {
344
366
  let bootMs = 0;
345
367
  let warmupMs = 0;
346
368
  const warmupStartedAt = performance.now();
347
- const warmupSpan = startLifecycleSpan("warmup", startup.context);
369
+ const warmupSpan = startSpan("warmup", { parent: startup.context });
348
370
  const warmup = warmupModules().then(() => {
349
371
  warmupMs = roundMs(performance.now() - warmupStartedAt);
350
372
  warmupSpan.span.end();
@@ -359,7 +381,7 @@ async function startServer(overrides) {
359
381
  });
360
382
  const shutdownLifecycle = async (shutdownContext) => {
361
383
  try {
362
- if (shutdownContext) await withLifecycleSpan("onShutdown", shutdownContext, () => runShutdown(bootModule, context));
384
+ if (shutdownContext) await withSpan("onShutdown", { parent: shutdownContext }, () => runShutdown(bootModule, context));
363
385
  else await runShutdown(bootModule, context);
364
386
  } catch (err) {
365
387
  log.error(err instanceof Error ? { err } : { reason: err }, "shutdown failed");
@@ -388,7 +410,7 @@ async function startServer(overrides) {
388
410
  try {
389
411
  const bootStartedAt = performance.now();
390
412
  bootModule = await import("virtual:@astroscope/node/boot");
391
- await withLifecycleSpan("boot", startup.context, () => runStartup(bootModule, context));
413
+ await withSpan("boot", { parent: startup.context }, () => runStartup(bootModule, context));
392
414
  bootMs = roundMs(performance.now() - bootStartedAt);
393
415
  } catch (err) {
394
416
  await failStartup(err, "startup failed");
@@ -418,13 +440,14 @@ async function startServer(overrides) {
418
440
  return;
419
441
  }
420
442
  instrument(req, res, () => {
443
+ if (redirectDuplicateSlashes(req, res)) return;
421
444
  if (dispatchNativeMount(req, res)) return;
422
445
  staticHandler(req, res, () => void appHandler(req, res));
423
446
  });
424
447
  };
425
448
  const server$1 = tls ? https.createServer(tls, listener) : http.createServer(listener);
426
449
  try {
427
- await withLifecycleSpan("listen", startup.context, () => {
450
+ await withSpan("listen", { parent: startup.context }, () => {
428
451
  return new Promise((resolve, reject) => {
429
452
  server$1.once("error", reject);
430
453
  server$1.listen(port, host, resolve);
@@ -454,8 +477,8 @@ async function startServer(overrides) {
454
477
  if (health) probes.ready.disable();
455
478
  log.info("shutdown initiated");
456
479
  const drainStartedAt = performance.now();
457
- const shutdown = startLifecycleSpan("shutdown");
458
- await withLifecycleSpan("drain", shutdown.context, async () => {
480
+ const shutdown = startSpan("shutdown");
481
+ await withSpan("drain", { parent: shutdown.context }, async () => {
459
482
  const closed = new Promise((resolve) => server$1.close(() => resolve()));
460
483
  server$1.closeIdleConnections();
461
484
  const forceTimer = setTimeout(() => server$1.closeAllConnections(), runtimeOptions.shutdownTimeout);
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["healthServer","server"],"sources":["../src/observability/telemetry/lifecycle.ts","../src/server/client-dir.ts","../src/server/serve-app.ts","../src/server/serve-static.ts","../src/server/server.ts"],"sourcesContent":["import { type Context, type Span, SpanStatusCode, context, trace } from '@opentelemetry/api';\n\nconst LIB_NAME = '@astroscope/node';\n\n/**\n * Lifecycle spans (`startup` / `shutdown` with phase children). No-op when no\n * SDK is registered — `trace.getTracer` returns the no-op tracer.\n */\n\nexport function startLifecycleSpan(name: string, parent?: Context): { span: Span; context: Context } {\n const parentContext = parent ?? context.active();\n const span = trace.getTracer(LIB_NAME).startSpan(name, undefined, parentContext);\n\n return { span, context: trace.setSpan(parentContext, span) };\n}\n\nexport async function withLifecycleSpan<T>(name: string, parent: Context, fn: () => Promise<T> | T): Promise<T> {\n const { span, context: spanContext } = startLifecycleSpan(name, parent);\n\n try {\n const result = await context.with(spanContext, fn);\n\n span.setStatus({ code: SpanStatusCode.OK });\n\n return result;\n } catch (err) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: err instanceof Error ? err.message : 'unknown error' });\n\n throw err;\n } finally {\n span.end();\n }\n}\n","import path from 'node:path';\nimport url from 'node:url';\n\n/**\n * Resolve the client directory at runtime relative to the built server entry.\n *\n * The build-time client/server URLs are only valid on the build machine; in a\n * container the deploy path differs. Walk up from `import.meta.url` of the\n * bundled server code until the server directory is found, then apply the\n * build-time server→client relative path.\n */\nexport function resolveClientDir(options: { client: string; server: string }, importMetaUrl: string): string {\n const clientPath = url.fileURLToPath(new URL(options.client));\n const serverPath = url.fileURLToPath(new URL(options.server));\n const rel = path.relative(serverPath, clientPath);\n const serverFolder = path.basename(serverPath);\n\n let serverEntryFolderURL = path.dirname(importMetaUrl);\n let previous = '';\n\n while (!serverEntryFolderURL.endsWith(serverFolder)) {\n if (serverEntryFolderURL === previous) {\n throw new Error(\n `[@astroscope/node] could not find the server directory \"${serverFolder}\" by walking up from \"${importMetaUrl}\"`,\n );\n }\n\n previous = serverEntryFolderURL;\n serverEntryFolderURL = path.dirname(serverEntryFolderURL);\n }\n\n const clientURL = new URL(rel.endsWith('/') ? rel : `${rel}/`, `${serverEntryFolderURL}/entry.mjs`);\n\n return url.fileURLToPath(clientURL);\n}\n","import { createReadStream } from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport path from 'node:path';\nimport { Readable } from 'node:stream';\nimport type { BaseApp } from 'astro/app';\nimport { createRequestFromNodeRequest, writeResponse } from 'astro/app/node';\nimport { log } from '../observability/log/index.js';\nimport { getRequestRecord } from '../observability/log/store.js';\nimport type { RuntimeOptions } from '../types.js';\nimport { setRequestRouteData } from './route-store.js';\n\nasync function readFSErrorPage(client: string, status: number): Promise<Response | undefined> {\n const filePaths = [`${status}.html`, `${status}/index.html`];\n\n for (const filePath of filePaths) {\n const fullPath = path.join(client, filePath);\n let stream: ReturnType<typeof createReadStream> | undefined;\n\n try {\n stream = createReadStream(fullPath);\n\n await new Promise<void>((resolve, reject) => {\n stream!.once('open', () => resolve());\n stream!.once('error', reject);\n });\n\n return new Response(Readable.toWeb(stream) as ReadableStream, {\n headers: { 'Content-Type': 'text/html; charset=utf-8' },\n });\n } catch {\n stream?.destroy();\n }\n }\n\n return undefined;\n}\n\n/**\n * Render on-demand routes: node req → web Request → `app.render()` → node res.\n * Prerendered pages never reach this handler (the static handler serves them);\n * requests for them landing here render the 404 route.\n */\nexport function createAppHandler(app: BaseApp, options: RuntimeOptions, client: string) {\n process.on('unhandledRejection', (reason) => {\n const requestUrl = getRequestRecord()?.url;\n\n log.error(\n {\n ...(reason instanceof Error ? { err: reason } : { reason }),\n ...(requestUrl && { url: requestUrl }),\n },\n requestUrl ? 'unhandled rejection while rendering' : 'unhandled rejection',\n );\n });\n\n const prerenderedErrorPageFetch = async (url: string): Promise<Response> => {\n const { pathname } = new URL(url);\n\n for (const status of [404, 500]) {\n if (pathname.endsWith(`/${status}.html`) || pathname.endsWith(`/${status}/index.html`)) {\n const response = await readFSErrorPage(client, status);\n\n if (response) return response;\n }\n }\n\n return new Response(null, { status: 404 });\n };\n\n const bodySizeLimit =\n options.bodySizeLimit === 0 || options.bodySizeLimit === Number.POSITIVE_INFINITY\n ? undefined\n : options.bodySizeLimit;\n\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n let request: Request;\n\n try {\n request = createRequestFromNodeRequest(req, {\n allowedDomains: app.getAllowedDomains?.() ?? [],\n ...(bodySizeLimit !== undefined && { bodySizeLimit }),\n port: options.port,\n });\n } catch (err) {\n log.error(err instanceof Error ? { err, url: req.url } : { reason: err, url: req.url }, 'could not render');\n\n res.statusCode = 500;\n res.end('Internal Server Error');\n\n return;\n }\n\n const routeData = app.match(request, true);\n const matched = routeData && !(routeData.type === 'page' && routeData.prerender) ? routeData : undefined;\n\n if (matched) {\n setRequestRouteData(request, matched);\n }\n\n const response = matched\n ? await app.render(request, { addCookieHeader: true, routeData: matched, prerenderedErrorPageFetch })\n : await app.render(request, { addCookieHeader: true, prerenderedErrorPageFetch });\n\n await writeResponse(response, res);\n };\n}\n","import fs from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport path from 'node:path';\nimport type { BaseApp } from 'astro/app';\nimport send from 'send';\nimport { COMPRESSIBLE, MIME_TYPES } from './mime.js';\n\nconst VARIANTS = [\n { encoding: 'br', suffix: '.br' },\n { encoding: 'gzip', suffix: '.gz' },\n] as const;\n\nfunction negotiateVariant(\n req: IncomingMessage,\n client: string,\n pathname: string,\n): { pathname: string; encoding: string } | undefined {\n const accept = req.headers['accept-encoding'];\n\n if (typeof accept !== 'string') return undefined;\n\n for (const { encoding, suffix } of VARIANTS) {\n if (!accept.includes(encoding)) continue;\n\n if (fs.existsSync(path.join(client, `${pathname}${suffix}`))) {\n return { pathname: `${pathname}${suffix}`, encoding };\n }\n }\n\n return undefined;\n}\n\nfunction hasFileExtension(pathname: string): boolean {\n const last = pathname.split('/').pop();\n\n return !!last && last.includes('.');\n}\n\nfunction prependForwardSlash(pathname: string): string {\n return pathname.startsWith('/') ? pathname : `/${pathname}`;\n}\n\nfunction isDirectory(client: string, urlPath: string): boolean {\n const filePath = path.join(client, urlPath);\n const resolved = path.resolve(filePath);\n const resolvedClient = path.resolve(client);\n\n // path traversal guard\n if (resolved !== resolvedClient && !resolved.startsWith(resolvedClient + path.sep)) {\n return false;\n }\n\n try {\n return fs.lstatSync(filePath).isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Serve files from the client build directory, falling through to `ssr` when\n * no file matches. Handles trailing-slash redirects per the manifest config\n * and marks hashed assets as immutable.\n */\nexport function createStaticHandler(app: BaseApp, client: string) {\n return (req: IncomingMessage, res: ServerResponse, ssr: () => void): void => {\n if (!req.url) {\n ssr();\n\n return;\n }\n\n let fullUrl = req.url;\n\n if (fullUrl.includes('#')) {\n fullUrl = fullUrl.slice(0, fullUrl.indexOf('#'));\n }\n\n const [urlPath = '', urlQuery] = fullUrl.split('?');\n let fsPath = app.removeBase(urlPath);\n\n try {\n fsPath = decodeURI(fsPath);\n } catch {\n // fall through with the raw path; send() rejects malformed paths itself\n }\n\n const dir = isDirectory(client, fsPath);\n const hasSlash = urlPath.endsWith('/');\n let pathname = urlPath;\n\n switch (app.manifest.trailingSlash) {\n case 'never': {\n if (dir && urlPath !== '/' && hasSlash) {\n res.statusCode = 301;\n res.setHeader('Location', urlPath.slice(0, -1) + (urlQuery ? `?${urlQuery}` : ''));\n res.end();\n\n return;\n }\n\n if (dir && !hasSlash) {\n pathname = `${urlPath}/index.html`;\n }\n\n break;\n }\n case 'ignore': {\n if (dir && !hasSlash) {\n pathname = `${urlPath}/index.html`;\n }\n\n break;\n }\n case 'always': {\n if (!hasSlash && !hasFileExtension(urlPath) && !urlPath.startsWith('/_')) {\n res.statusCode = 301;\n res.setHeader('Location', `${urlPath}/${urlQuery ? `?${urlQuery}` : ''}`);\n res.end();\n\n return;\n }\n\n break;\n }\n }\n\n pathname = prependForwardSlash(app.removeBase(pathname));\n\n const normalizedPathname = path.posix.normalize(pathname);\n const compressible = COMPRESSIBLE.has(path.posix.extname(normalizedPathname));\n const variant = compressible ? negotiateVariant(req, client, normalizedPathname) : undefined;\n\n const stream = send(req, variant?.pathname ?? normalizedPathname, {\n root: client,\n dotfiles: normalizedPathname.startsWith('/.well-known/') ? 'allow' : 'deny',\n // with build.format 'file' or 'preserve', pages are output as `page.html`\n // instead of `page/index.html` — let send() try appending `.html`\n extensions: app.manifest.buildFormat === 'file' || app.manifest.buildFormat === 'preserve' ? ['html'] : [],\n });\n\n let forwardError = false;\n\n stream.on('error', (err: NodeJS.ErrnoException & { statusCode?: number }) => {\n if (forwardError) {\n const status = err.statusCode ?? 500;\n\n if (status >= 500) {\n console.error(err.toString());\n }\n\n res.writeHead(status);\n res.end(status >= 500 ? 'Internal server error' : '');\n\n return;\n }\n\n ssr();\n });\n\n stream.on('file', () => {\n forwardError = true;\n });\n\n // fires before the body and before conditional-GET handling, so these\n // headers also land on 304 responses\n stream.on('headers', (headersRes: ServerResponse) => {\n if (compressible) {\n headersRes.setHeader('Vary', 'Accept-Encoding');\n }\n\n if (variant) {\n headersRes.setHeader('Content-Encoding', variant.encoding);\n headersRes.setHeader(\n 'Content-Type',\n MIME_TYPES.get(path.posix.extname(normalizedPathname)) ?? 'application/octet-stream',\n );\n }\n\n if (normalizedPathname.startsWith(`/${app.manifest.assetsDir}/`)) {\n headersRes.setHeader('Cache-Control', 'public, max-age=31536000, immutable');\n }\n });\n\n stream.pipe(res);\n };\n}\n","import fs from 'node:fs';\nimport http from 'node:http';\nimport https from 'node:https';\nimport { checks, server as healthServer, probes } from '@entwico/health-probes';\nimport { SpanStatusCode } from '@opentelemetry/api';\nimport { createApp } from 'astro/app/entrypoint';\nimport { setGetEnv } from 'astro/env/setup';\n// @ts-expect-error virtual module provided by the integration\nimport { options } from 'virtual:@astroscope/node/config';\nimport { activateHealthChecks, deactivateHealthChecks } from '../health/store.js';\nimport { setBootContext } from '../lifecycle/context.js';\nimport { type BootModule, runShutdown, runStartup } from '../lifecycle/lifecycle.js';\nimport type { BootContext } from '../lifecycle/types.js';\nimport { createRequestInstrumentation } from '../observability/instrument.js';\nimport { dumpEarlyLogs } from '../observability/log/construct.js';\nimport { log } from '../observability/log/index.js';\nimport { startLifecycleSpan, withLifecycleSpan } from '../observability/telemetry/lifecycle.js';\nimport { shutdownTelemetry } from '../observability/telemetry/sdk.js';\nimport { preparePlatform } from '../platform/prepare.js';\nimport type { RuntimeOptions } from '../types.js';\nimport { resolveClientDir } from './client-dir.js';\nimport { clearNativeMounts, dispatchNativeMount } from './native-mount.js';\nimport { createAppHandler } from './serve-app.js';\nimport { createStaticHandler } from './serve-static.js';\n\nsetGetEnv((key) => process.env[key]);\n\nconst runtimeOptions = options as RuntimeOptions;\nconst app = createApp({ streaming: true });\n\nconst roundMs = (n: number) => Math.round(n * 100) / 100;\n\n/**\n * Pre-import every lazily loaded server module (pages, middleware, actions,\n * session driver) so the first request pays no import cost. Uses the\n * manifest's own loaders — exactly what the runtime calls per request.\n */\nasync function warmupModules(): Promise<void> {\n const loaders = [\n ...(app.manifest.pageMap?.values() ?? []),\n app.manifest.middleware,\n app.manifest.actions,\n app.manifest.sessionDriver,\n app.manifest.serverIslandMappings,\n ].filter((load) => load !== undefined);\n\n const results = await Promise.allSettled(loaders.map((load) => load()));\n const failures = results.filter((result) => result.status === 'rejected');\n\n if (failures.length === 0) return;\n\n for (const failure of failures) {\n log.error(\n failure.reason instanceof Error ? { err: failure.reason } : { reason: failure.reason },\n 'warmup import failed',\n );\n }\n\n // a module that cannot even be imported would throw on its first request;\n // failing the boot turns a silently-degraded deploy into a crash the health\n // checks catch before it takes traffic\n throw new AggregateError(\n failures.map((failure) => failure.reason),\n 'warmup import failed',\n );\n}\n\n/**\n * TLS tokens from `SERVER_CERT_PATH` / `SERVER_KEY_PATH` (same contract as\n * `@astrojs/node`). Read after env loading, so the paths may come from `.env`.\n */\nfunction loadTlsOptions(): { cert: Buffer; key: Buffer } | undefined {\n const certPath = process.env['SERVER_CERT_PATH'];\n const keyPath = process.env['SERVER_KEY_PATH'];\n\n if (!certPath && !keyPath) return undefined;\n\n if (!certPath || !keyPath) {\n throw new Error('SERVER_CERT_PATH and SERVER_KEY_PATH must both be set to serve HTTPS');\n }\n\n return { cert: fs.readFileSync(certPath), key: fs.readFileSync(keyPath) };\n}\n\nexport interface ServerHandle {\n host: string;\n port: number;\n stop(): Promise<void>;\n closed(): Promise<void>;\n}\n\nexport async function startServer(overrides?: {\n host?: string | undefined;\n port?: number | undefined;\n}): Promise<ServerHandle> {\n const startedAt = performance.now();\n const host = overrides?.host ?? process.env['HOST'] ?? runtimeOptions.host;\n const port = overrides?.port ?? (process.env['PORT'] ? Number(process.env['PORT']) : runtimeOptions.port);\n const context: BootContext = { dev: false, host, port };\n const health = runtimeOptions.health;\n\n setBootContext(context);\n\n try {\n await preparePlatform({\n dev: false,\n telemetry: runtimeOptions.telemetry ? { prometheus: runtimeOptions.telemetry.prometheus } : false,\n seams: {\n config: () => import('virtual:@astroscope/node/config-entry'),\n instrumentation: () => import('virtual:@astroscope/node/instrumentation-entry'),\n log: () => import('virtual:@astroscope/node/log-entry'),\n },\n });\n } catch (err) {\n // the logger never came up — no silent phase, dump the buffer and die\n dumpEarlyLogs();\n console.error(err);\n process.exit(1);\n }\n\n if (health) {\n healthServer.start({ ...health, host: health.host ?? process.env['HEALTH_HOST'] ?? '0.0.0.0' });\n probes.live.enable();\n activateHealthChecks(checks);\n log.debug('health probes listening');\n }\n\n const startup = startLifecycleSpan('startup');\n\n log.info({ host, port }, 'starting');\n\n // the boot module graph may read config at import time, so it must only be\n // evaluated after preparePlatform() has loaded env and config\n let bootModule: BootModule = {};\n let bootMs = 0;\n let warmupMs = 0;\n\n // starts in parallel with the boot startup, awaited before listen. resolves\n // to the failure (if any) instead of rejecting, so a warmup error landing\n // before the join below is never seen as an unhandled rejection\n const warmupStartedAt = performance.now();\n const warmupSpan = startLifecycleSpan('warmup', startup.context);\n const warmup = warmupModules().then(\n () => {\n warmupMs = roundMs(performance.now() - warmupStartedAt);\n warmupSpan.span.end();\n\n return undefined;\n },\n (error: unknown) => {\n warmupMs = roundMs(performance.now() - warmupStartedAt);\n warmupSpan.span.setStatus({ code: SpanStatusCode.ERROR, message: 'warmup import failed' });\n warmupSpan.span.end();\n\n return error;\n },\n );\n\n const shutdownLifecycle = async (\n shutdownContext?: ReturnType<typeof startLifecycleSpan>['context'],\n ): Promise<void> => {\n try {\n if (shutdownContext) {\n await withLifecycleSpan('onShutdown', shutdownContext, () => runShutdown(bootModule, context));\n } else {\n await runShutdown(bootModule, context);\n }\n } catch (err) {\n log.error(err instanceof Error ? { err } : { reason: err }, 'shutdown failed');\n }\n\n clearNativeMounts();\n\n if (health) {\n deactivateHealthChecks();\n\n try {\n await healthServer.stop();\n } catch (err) {\n // a startup failure can tear the health server down before it has\n // finished binding; stopping it is best-effort\n log.debug(err instanceof Error ? { err } : { reason: err }, 'health probe server stop failed');\n }\n }\n };\n\n const failStartup = async (err: unknown, message: string): Promise<never> => {\n log.error(err instanceof Error ? { err } : { reason: err }, message);\n startup.span.setStatus({ code: SpanStatusCode.ERROR, message });\n startup.span.end();\n\n await shutdownLifecycle();\n await shutdownTelemetry();\n process.exit(1);\n };\n\n try {\n const bootStartedAt = performance.now();\n\n // @ts-expect-error virtual module provided by the integration\n bootModule = (await import('virtual:@astroscope/node/boot')) as BootModule;\n\n await withLifecycleSpan('boot', startup.context, () => runStartup(bootModule, context));\n\n bootMs = roundMs(performance.now() - bootStartedAt);\n } catch (err) {\n await failStartup(err, 'startup failed');\n }\n\n const warmupError = await warmup;\n\n if (warmupError !== undefined) {\n await failStartup(warmupError, 'warmup import failed');\n }\n\n if (health) probes.startup.enable();\n\n const client = resolveClientDir(runtimeOptions, import.meta.url);\n const appHandler = createAppHandler(app, runtimeOptions, client);\n const staticHandler = createStaticHandler(app, client);\n const instrument = createRequestInstrumentation({\n logging: runtimeOptions.logging,\n telemetry: runtimeOptions.telemetry ? { exclude: runtimeOptions.telemetry.exclude } : false,\n });\n\n let tls: { cert: Buffer; key: Buffer } | undefined;\n\n try {\n tls = loadTlsOptions();\n } catch (err) {\n await failStartup(err, 'failed to load TLS options');\n }\n\n const listener: http.RequestListener = (req, res) => {\n try {\n decodeURI(req.url ?? '');\n } catch {\n res.writeHead(400);\n res.end('Bad request.');\n\n return;\n }\n\n instrument(req, res, () => {\n if (dispatchNativeMount(req, res)) return;\n\n staticHandler(req, res, () => void appHandler(req, res));\n });\n };\n\n const server = tls ? https.createServer(tls, listener) : http.createServer(listener);\n\n try {\n await withLifecycleSpan('listen', startup.context, () => {\n return new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(port, host, resolve);\n });\n });\n } catch (err) {\n await failStartup(err, `failed to listen on ${host}:${port}`);\n }\n\n if (health) probes.ready.enable();\n\n startup.span.setStatus({ code: SpanStatusCode.OK });\n startup.span.end();\n\n log.info(\n {\n host,\n port,\n ...(tls && { https: true }),\n health: !!health,\n bootMs,\n warmupMs,\n totalMs: roundMs(performance.now() - startedAt),\n },\n 'server ready',\n );\n\n let stopPromise: Promise<void> | undefined;\n let resolveClosed!: () => void;\n\n const closedPromise = new Promise<void>((resolve) => {\n resolveClosed = resolve;\n });\n\n const doStop = async (): Promise<void> => {\n if (health) probes.ready.disable();\n\n log.info('shutdown initiated');\n\n const drainStartedAt = performance.now();\n const shutdown = startLifecycleSpan('shutdown');\n\n await withLifecycleSpan('drain', shutdown.context, async () => {\n const closed = new Promise<void>((resolve) => server.close(() => resolve()));\n\n server.closeIdleConnections();\n\n const forceTimer = setTimeout(() => server.closeAllConnections(), runtimeOptions.shutdownTimeout);\n\n await closed;\n\n clearTimeout(forceTimer);\n });\n\n const drainMs = roundMs(performance.now() - drainStartedAt);\n\n await shutdownLifecycle(shutdown.context);\n\n shutdown.span.end();\n\n log.info({ drainMs }, 'shutdown complete');\n\n await shutdownTelemetry();\n resolveClosed();\n };\n\n const stop = (): Promise<void> => (stopPromise ??= doStop());\n\n process.once('SIGTERM', () => void stop().then(() => process.exit(0)));\n process.once('SIGINT', () => void stop().then(() => process.exit(0)));\n\n return { host, port, stop, closed: () => closedPromise };\n}\n\nif (process.env['ASTROSCOPE_NODE_AUTOSTART'] !== 'disabled') {\n await startServer();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAEA,MAAM,WAAW;;;;;AAOjB,SAAgB,mBAAmB,MAAc,QAAoD;CACnG,MAAM,gBAAgB,UAAU,QAAQ,OAAO;CAC/C,MAAM,OAAO,MAAM,UAAU,QAAQ,CAAC,CAAC,UAAU,MAAM,KAAA,GAAW,aAAa;CAE/E,OAAO;EAAE;EAAM,SAAS,MAAM,QAAQ,eAAe,IAAI;CAAE;AAC7D;AAEA,eAAsB,kBAAqB,MAAc,QAAiB,IAAsC;CAC9G,MAAM,EAAE,MAAM,SAAS,gBAAgB,mBAAmB,MAAM,MAAM;CAEtE,IAAI;EACF,MAAM,SAAS,MAAM,QAAQ,KAAK,aAAa,EAAE;EAEjD,KAAK,UAAU,EAAE,MAAM,eAAe,GAAG,CAAC;EAE1C,OAAO;CACT,SAAS,KAAK;EACZ,KAAK,UAAU;GAAE,MAAM,eAAe;GAAO,SAAS,eAAe,QAAQ,IAAI,UAAU;EAAgB,CAAC;EAE5G,MAAM;CACR,UAAU;EACR,KAAK,IAAI;CACX;AACF;;;;;;;;;;;ACrBA,SAAgB,iBAAiB,SAA6C,eAA+B;CAC3G,MAAM,aAAa,IAAI,cAAc,IAAI,IAAI,QAAQ,MAAM,CAAC;CAC5D,MAAM,aAAa,IAAI,cAAc,IAAI,IAAI,QAAQ,MAAM,CAAC;CAC5D,MAAM,MAAM,KAAK,SAAS,YAAY,UAAU;CAChD,MAAM,eAAe,KAAK,SAAS,UAAU;CAE7C,IAAI,uBAAuB,KAAK,QAAQ,aAAa;CACrD,IAAI,WAAW;CAEf,OAAO,CAAC,qBAAqB,SAAS,YAAY,GAAG;EACnD,IAAI,yBAAyB,UAC3B,MAAM,IAAI,MACR,2DAA2D,aAAa,wBAAwB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AI,SAAS;CAChD,GACA,cACF;CAEA,IAAI;CACJ,IAAI;CAEJ,MAAM,gBAAgB,IAAI,SAAe,YAAY;EACnD,gBAAgB;CAClB,CAAC;CAED,MAAM,SAAS,YAA2B;EACxC,IAAI,QAAQ,OAAO,MAAM,QAAQ;EAEjC,IAAI,KAAK,oBAAoB;EAE7B,MAAM,iBAAiB,YAAY,IAAI;EACvC,MAAM,WAAW,mBAAmB,UAAU;EAE9C,MAAM,kBAAkB,SAAS,SAAS,SAAS,YAAY;GAC7D,MAAM,SAAS,IAAI,SAAe,YAAYA,SAAO,YAAY,QAAQ,CAAC,CAAC;GAE3E,SAAO,qBAAqB;GAE5B,MAAM,aAAa,iBAAiBA,SAAO,oBAAoB,GAAG,eAAe,eAAe;GAEhG,MAAM;GAEN,aAAa,UAAU;EACzB,CAAC;EAED,MAAM,UAAU,QAAQ,YAAY,IAAI,IAAI,cAAc;EAE1D,MAAM,kBAAkB,SAAS,OAAO;EAExC,SAAS,KAAK,IAAI;EAElB,IAAI,KAAK,EAAE,QAAQ,GAAG,mBAAmB;EAEzC,MAAM,kBAAkB;EACxB,cAAc;CAChB;CAEA,MAAM,aAA6B,gBAAgB,OAAO;CAE1D,QAAQ,KAAK,iBAAiB,KAAK,KAAK,CAAC,CAAC,WAAW,QAAQ,KAAK,CAAC,CAAC,CAAC;CACrE,QAAQ,KAAK,gBAAgB,KAAK,KAAK,CAAC,CAAC,WAAW,QAAQ,KAAK,CAAC,CAAC,CAAC;CAEpE,OAAO;EAAE;EAAM;EAAM;EAAM,cAAc;CAAc;AACzD;AAEA,IAAI,QAAQ,IAAI,iCAAiC,YAC/C,MAAM,YAAY"}
1
+ {"version":3,"file":"server.js","names":["healthServer","server"],"sources":["../src/server/client-dir.ts","../src/server/serve-app.ts","../src/server/serve-static.ts","../src/server/server.ts"],"sourcesContent":["import path from 'node:path';\nimport url from 'node:url';\n\n/**\n * Resolve the client directory at runtime relative to the built server entry.\n *\n * The build-time client/server URLs are only valid on the build machine; in a\n * container the deploy path differs. Walk up from `import.meta.url` of the\n * bundled server code until the server directory is found, then apply the\n * build-time server→client relative path.\n */\nexport function resolveClientDir(options: { client: string; server: string }, importMetaUrl: string): string {\n const clientPath = url.fileURLToPath(new URL(options.client));\n const serverPath = url.fileURLToPath(new URL(options.server));\n const rel = path.relative(serverPath, clientPath);\n const serverFolder = path.basename(serverPath);\n\n let serverEntryFolderURL = path.dirname(importMetaUrl);\n let previous = '';\n\n while (!serverEntryFolderURL.endsWith(serverFolder)) {\n if (serverEntryFolderURL === previous) {\n throw new Error(\n `[@astroscope/node] could not find the server directory \"${serverFolder}\" by walking up from \"${importMetaUrl}\"`,\n );\n }\n\n previous = serverEntryFolderURL;\n serverEntryFolderURL = path.dirname(serverEntryFolderURL);\n }\n\n const clientURL = new URL(rel.endsWith('/') ? rel : `${rel}/`, `${serverEntryFolderURL}/entry.mjs`);\n\n return url.fileURLToPath(clientURL);\n}\n","import { createReadStream } from 'node:fs';\nimport type { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from 'node:http';\nimport path from 'node:path';\nimport { Readable } from 'node:stream';\nimport type { BaseApp } from 'astro/app';\nimport { createRequestFromNodeRequest, getAbortControllerCleanup } from 'astro/app/node';\nimport { log } from '../observability/log/index.js';\nimport { getRequestRecord } from '../observability/log/store.js';\nimport type { RuntimeOptions } from '../types.js';\nimport { setRequestRouteData } from './route-store.js';\n\nasync function readFSErrorPage(client: string, status: number): Promise<Response | undefined> {\n const filePaths = [`${status}.html`, `${status}/index.html`];\n\n for (const filePath of filePaths) {\n const fullPath = path.join(client, filePath);\n let stream: ReturnType<typeof createReadStream> | undefined;\n\n try {\n stream = createReadStream(fullPath);\n\n await new Promise<void>((resolve, reject) => {\n stream!.once('open', () => resolve());\n stream!.once('error', reject);\n });\n\n return new Response(Readable.toWeb(stream) as ReadableStream, {\n headers: { 'Content-Type': 'text/html; charset=utf-8' },\n });\n } catch {\n stream?.destroy();\n }\n }\n\n return undefined;\n}\n\nfunction createOutgoingHttpHeaders(headers: Headers): OutgoingHttpHeaders | undefined {\n const nodeHeaders: OutgoingHttpHeaders = Object.fromEntries(headers.entries());\n\n if (Object.keys(nodeHeaders).length === 0) {\n return undefined;\n }\n\n // the entries iterator joins set-cookie values with a comma; node needs them as an array\n const cookies = headers.getSetCookie();\n\n if (cookies.length > 1) {\n nodeHeaders['set-cookie'] = cookies;\n }\n\n return nodeHeaders;\n}\n\n/**\n * Streams the web response into the node response. A render failing after the\n * first chunk cannot change the status anymore, so it is logged through the\n * request logger and marked on the request record — the completion line, the\n * span and `astro.render.failures` reflect it. On the wire it behaves like\n * astro's own writer: an `Internal server error` marker, then the socket is\n * destroyed.\n */\nexport async function writeResponse(response: Response, res: ServerResponse): Promise<void> {\n res.statusMessage = response.statusText;\n res.writeHead(response.status, createOutgoingHttpHeaders(response.headers));\n\n // astro parks the socket listener behind the request's abort signal on the node\n // request; releasing it once the response is done keeps keep-alive sockets from\n // accumulating one listener per request\n const cleanupAbort = getAbortControllerCleanup(res.req);\n\n if (cleanupAbort) {\n const runCleanup = (): void => {\n cleanupAbort();\n res.off('finish', runCleanup);\n res.off('close', runCleanup);\n };\n\n res.on('finish', runCleanup);\n res.on('close', runCleanup);\n }\n\n if (!response.body) {\n res.end();\n\n return;\n }\n\n const reader = response.body.getReader();\n\n // a client going away stops the render; on a failed stream the cancel rejects\n // with the render error, which the catch below has already reported\n res.on('close', () => {\n reader.cancel().catch(() => undefined);\n });\n\n try {\n for (let result = await reader.read(); !result.done; result = await reader.read()) {\n res.write(result.value);\n }\n\n res.end();\n } catch (err) {\n const record = getRequestRecord();\n\n if (record) {\n record.truncated = true;\n }\n\n log.error(\n {\n ...(err instanceof Error ? { err } : { reason: err }),\n ...(record?.route && { route: record.route }),\n ...(!record?.logger && { url: record?.url ?? res.req.url }),\n },\n 'render failed after the response started, response truncated',\n );\n\n res.write('Internal server error', () => {\n res.destroy(err instanceof Error ? err : undefined);\n });\n }\n}\n\n/**\n * Render on-demand routes: node req → web Request → `app.render()` → node res.\n * Prerendered pages never reach this handler (the static handler serves them);\n * requests for them landing here render the 404 route.\n */\nexport function createAppHandler(app: BaseApp, options: RuntimeOptions, client: string) {\n process.on('unhandledRejection', (reason) => {\n const requestUrl = getRequestRecord()?.url;\n\n log.error(\n {\n ...(reason instanceof Error ? { err: reason } : { reason }),\n ...(requestUrl && { url: requestUrl }),\n },\n requestUrl ? 'unhandled rejection while rendering' : 'unhandled rejection',\n );\n });\n\n const prerenderedErrorPageFetch = async (url: string): Promise<Response> => {\n const { pathname } = new URL(url);\n\n for (const status of [404, 500]) {\n if (pathname.endsWith(`/${status}.html`) || pathname.endsWith(`/${status}/index.html`)) {\n const response = await readFSErrorPage(client, status);\n\n if (response) return response;\n }\n }\n\n return new Response(null, { status: 404 });\n };\n\n const bodySizeLimit =\n options.bodySizeLimit === 0 || options.bodySizeLimit === Number.POSITIVE_INFINITY\n ? undefined\n : options.bodySizeLimit;\n\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n let request: Request;\n\n try {\n request = createRequestFromNodeRequest(req, {\n allowedDomains: app.getAllowedDomains?.() ?? [],\n ...(bodySizeLimit !== undefined && { bodySizeLimit }),\n port: options.port,\n });\n } catch (err) {\n log.error(err instanceof Error ? { err, url: req.url } : { reason: err, url: req.url }, 'could not render');\n\n res.statusCode = 500;\n res.end('Internal Server Error');\n\n return;\n }\n\n const routeData = app.match(request, true);\n const matched = routeData && !(routeData.type === 'page' && routeData.prerender) ? routeData : undefined;\n\n if (matched) {\n setRequestRouteData(request, matched);\n }\n\n const response = matched\n ? await app.render(request, { addCookieHeader: true, routeData: matched, prerenderedErrorPageFetch })\n : await app.render(request, { addCookieHeader: true, prerenderedErrorPageFetch });\n\n await writeResponse(response, res);\n };\n}\n","import fs from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport path from 'node:path';\nimport type { BaseApp } from 'astro/app';\nimport send from 'send';\nimport { COMPRESSIBLE, MIME_TYPES } from './mime.js';\n\nconst VARIANTS = [\n { encoding: 'br', suffix: '.br' },\n { encoding: 'gzip', suffix: '.gz' },\n] as const;\n\nfunction negotiateVariant(\n req: IncomingMessage,\n client: string,\n pathname: string,\n): { pathname: string; encoding: string } | undefined {\n const accept = req.headers['accept-encoding'];\n\n if (typeof accept !== 'string') return undefined;\n\n for (const { encoding, suffix } of VARIANTS) {\n if (!accept.includes(encoding)) continue;\n\n if (fs.existsSync(path.join(client, `${pathname}${suffix}`))) {\n return { pathname: `${pathname}${suffix}`, encoding };\n }\n }\n\n return undefined;\n}\n\nfunction hasFileExtension(pathname: string): boolean {\n const last = pathname.split('/').pop();\n\n return !!last && last.includes('.');\n}\n\nfunction prependForwardSlash(pathname: string): string {\n return pathname.startsWith('/') ? pathname : `/${pathname}`;\n}\n\nfunction isDirectory(client: string, urlPath: string): boolean {\n const filePath = path.join(client, urlPath);\n const resolved = path.resolve(filePath);\n const resolvedClient = path.resolve(client);\n\n // path traversal guard\n if (resolved !== resolvedClient && !resolved.startsWith(resolvedClient + path.sep)) {\n return false;\n }\n\n try {\n return fs.lstatSync(filePath).isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Serve files from the client build directory, falling through to `ssr` when\n * no file matches. Handles trailing-slash redirects per the manifest config\n * and marks hashed assets as immutable.\n */\nexport function createStaticHandler(app: BaseApp, client: string) {\n return (req: IncomingMessage, res: ServerResponse, ssr: () => void): void => {\n if (!req.url) {\n ssr();\n\n return;\n }\n\n let fullUrl = req.url;\n\n if (fullUrl.includes('#')) {\n fullUrl = fullUrl.slice(0, fullUrl.indexOf('#'));\n }\n\n const [urlPath = '', urlQuery] = fullUrl.split('?');\n let fsPath = app.removeBase(urlPath);\n\n try {\n fsPath = decodeURI(fsPath);\n } catch {\n // fall through with the raw path; send() rejects malformed paths itself\n }\n\n const dir = isDirectory(client, fsPath);\n const hasSlash = urlPath.endsWith('/');\n let pathname = urlPath;\n\n switch (app.manifest.trailingSlash) {\n case 'never': {\n if (dir && urlPath !== '/' && hasSlash) {\n res.statusCode = 301;\n res.setHeader('Location', urlPath.slice(0, -1) + (urlQuery ? `?${urlQuery}` : ''));\n res.end();\n\n return;\n }\n\n if (dir && !hasSlash) {\n pathname = `${urlPath}/index.html`;\n }\n\n break;\n }\n case 'ignore': {\n if (dir && !hasSlash) {\n pathname = `${urlPath}/index.html`;\n }\n\n break;\n }\n case 'always': {\n if (!hasSlash && !hasFileExtension(urlPath) && !urlPath.startsWith('/_')) {\n res.statusCode = 301;\n res.setHeader('Location', `${urlPath}/${urlQuery ? `?${urlQuery}` : ''}`);\n res.end();\n\n return;\n }\n\n break;\n }\n }\n\n pathname = prependForwardSlash(app.removeBase(pathname));\n\n const normalizedPathname = path.posix.normalize(pathname);\n const compressible = COMPRESSIBLE.has(path.posix.extname(normalizedPathname));\n const variant = compressible ? negotiateVariant(req, client, normalizedPathname) : undefined;\n\n const stream = send(req, variant?.pathname ?? normalizedPathname, {\n root: client,\n dotfiles: normalizedPathname.startsWith('/.well-known/') ? 'allow' : 'deny',\n // with build.format 'file' or 'preserve', pages are output as `page.html`\n // instead of `page/index.html` — let send() try appending `.html`\n extensions: app.manifest.buildFormat === 'file' || app.manifest.buildFormat === 'preserve' ? ['html'] : [],\n });\n\n let forwardError = false;\n\n stream.on('error', (err: NodeJS.ErrnoException & { statusCode?: number }) => {\n if (forwardError) {\n const status = err.statusCode ?? 500;\n\n if (status >= 500) {\n console.error(err.toString());\n }\n\n res.writeHead(status);\n res.end(status >= 500 ? 'Internal server error' : '');\n\n return;\n }\n\n ssr();\n });\n\n stream.on('file', () => {\n forwardError = true;\n });\n\n // fires before the body and before conditional-GET handling, so these\n // headers also land on 304 responses\n stream.on('headers', (headersRes: ServerResponse) => {\n if (compressible) {\n headersRes.setHeader('Vary', 'Accept-Encoding');\n }\n\n if (variant) {\n headersRes.setHeader('Content-Encoding', variant.encoding);\n headersRes.setHeader(\n 'Content-Type',\n MIME_TYPES.get(path.posix.extname(normalizedPathname)) ?? 'application/octet-stream',\n );\n }\n\n if (normalizedPathname.startsWith(`/${app.manifest.assetsDir}/`)) {\n headersRes.setHeader('Cache-Control', 'public, max-age=31536000, immutable');\n }\n });\n\n stream.pipe(res);\n };\n}\n","import fs from 'node:fs';\nimport http from 'node:http';\nimport https from 'node:https';\nimport { defined } from '@entwico/dash';\nimport { checks, server as healthServer, probes } from '@entwico/health-probes';\nimport { SpanStatusCode } from '@opentelemetry/api';\nimport { createApp } from 'astro/app/entrypoint';\nimport { setGetEnv } from 'astro/env/setup';\n// @ts-expect-error virtual module provided by the integration\nimport { options } from 'virtual:@astroscope/node/config';\nimport { activateHealthChecks, deactivateHealthChecks } from '../health/store.js';\nimport { setBootContext } from '../lifecycle/context.js';\nimport { type BootModule, runShutdown, runStartup } from '../lifecycle/lifecycle.js';\nimport type { BootContext } from '../lifecycle/types.js';\nimport { createRequestInstrumentation } from '../observability/instrument.js';\nimport { dumpEarlyLogs } from '../observability/log/construct.js';\nimport { log } from '../observability/log/index.js';\nimport { shutdownTelemetry } from '../observability/telemetry/sdk.js';\nimport { type StartedSpan, startSpan, withSpan } from '../observability/telemetry/telemetry.js';\nimport { preparePlatform } from '../platform/prepare.js';\nimport type { RuntimeOptions } from '../types.js';\nimport { resolveClientDir } from './client-dir.js';\nimport { redirectDuplicateSlashes } from './duplicate-slashes.js';\nimport { clearNativeMounts, dispatchNativeMount } from './native-mount.js';\nimport { createAppHandler } from './serve-app.js';\nimport { createStaticHandler } from './serve-static.js';\n\nsetGetEnv((key) => process.env[key]);\n\nconst runtimeOptions = options as RuntimeOptions;\nconst app = createApp({ streaming: true });\n\nconst roundMs = (n: number) => Math.round(n * 100) / 100;\n\n/**\n * Pre-import every lazily loaded server module (pages, middleware, actions,\n * session driver) so the first request pays no import cost. Uses the\n * manifest's own loaders — exactly what the runtime calls per request.\n */\nasync function warmupModules(): Promise<void> {\n const loaders = [\n ...(app.manifest.pageMap?.values() ?? []),\n app.manifest.middleware,\n app.manifest.actions,\n app.manifest.sessionDriver,\n app.manifest.serverIslandMappings,\n ].filter(defined);\n\n const results = await Promise.allSettled(loaders.map((load) => load()));\n const failures = results.filter((result) => result.status === 'rejected');\n\n if (failures.length === 0) return;\n\n for (const failure of failures) {\n log.error(\n failure.reason instanceof Error ? { err: failure.reason } : { reason: failure.reason },\n 'warmup import failed',\n );\n }\n\n // a module that cannot even be imported would throw on its first request;\n // failing the boot turns a silently-degraded deploy into a crash the health\n // checks catch before it takes traffic\n throw new AggregateError(\n failures.map((failure) => failure.reason),\n 'warmup import failed',\n );\n}\n\n/**\n * TLS tokens from `SERVER_CERT_PATH` / `SERVER_KEY_PATH` (same contract as\n * `@astrojs/node`). Read after env loading, so the paths may come from `.env`.\n */\nfunction loadTlsOptions(): { cert: Buffer; key: Buffer } | undefined {\n const certPath = process.env['SERVER_CERT_PATH'];\n const keyPath = process.env['SERVER_KEY_PATH'];\n\n if (!certPath && !keyPath) return undefined;\n\n if (!certPath || !keyPath) {\n throw new Error('SERVER_CERT_PATH and SERVER_KEY_PATH must both be set to serve HTTPS');\n }\n\n return { cert: fs.readFileSync(certPath), key: fs.readFileSync(keyPath) };\n}\n\nexport interface ServerHandle {\n host: string;\n port: number;\n stop(): Promise<void>;\n closed(): Promise<void>;\n}\n\nexport async function startServer(overrides?: {\n host?: string | undefined;\n port?: number | undefined;\n}): Promise<ServerHandle> {\n const startedAt = performance.now();\n const host = overrides?.host ?? process.env['HOST'] ?? runtimeOptions.host;\n const port = overrides?.port ?? (process.env['PORT'] ? Number(process.env['PORT']) : runtimeOptions.port);\n const context: BootContext = { dev: false, host, port };\n const health = runtimeOptions.health;\n\n setBootContext(context);\n\n try {\n await preparePlatform({\n dev: false,\n telemetry: runtimeOptions.telemetry ? { prometheus: runtimeOptions.telemetry.prometheus } : false,\n seams: {\n config: () => import('virtual:@astroscope/node/config-entry'),\n instrumentation: () => import('virtual:@astroscope/node/instrumentation-entry'),\n log: () => import('virtual:@astroscope/node/log-entry'),\n },\n });\n } catch (err) {\n // the logger never came up — no silent phase, dump the buffer and die\n dumpEarlyLogs();\n console.error(err);\n process.exit(1);\n }\n\n if (health) {\n healthServer.start({ ...health, host: health.host ?? process.env['HEALTH_HOST'] ?? '0.0.0.0' });\n probes.live.enable();\n activateHealthChecks(checks);\n log.debug('health probes listening');\n }\n\n const startup = startSpan('startup');\n\n log.info({ host, port }, 'starting');\n\n // the boot module graph may read config at import time, so it must only be\n // evaluated after preparePlatform() has loaded env and config\n let bootModule: BootModule = {};\n let bootMs = 0;\n let warmupMs = 0;\n\n // starts in parallel with the boot startup, awaited before listen. resolves\n // to the failure (if any) instead of rejecting, so a warmup error landing\n // before the join below is never seen as an unhandled rejection\n const warmupStartedAt = performance.now();\n const warmupSpan = startSpan('warmup', { parent: startup.context });\n const warmup = warmupModules().then(\n () => {\n warmupMs = roundMs(performance.now() - warmupStartedAt);\n warmupSpan.span.end();\n\n return undefined;\n },\n (error: unknown) => {\n warmupMs = roundMs(performance.now() - warmupStartedAt);\n warmupSpan.span.setStatus({ code: SpanStatusCode.ERROR, message: 'warmup import failed' });\n warmupSpan.span.end();\n\n return error;\n },\n );\n\n const shutdownLifecycle = async (shutdownContext?: StartedSpan['context']): Promise<void> => {\n try {\n if (shutdownContext) {\n await withSpan('onShutdown', { parent: shutdownContext }, () => runShutdown(bootModule, context));\n } else {\n await runShutdown(bootModule, context);\n }\n } catch (err) {\n log.error(err instanceof Error ? { err } : { reason: err }, 'shutdown failed');\n }\n\n clearNativeMounts();\n\n if (health) {\n deactivateHealthChecks();\n\n try {\n await healthServer.stop();\n } catch (err) {\n // a startup failure can tear the health server down before it has\n // finished binding; stopping it is best-effort\n log.debug(err instanceof Error ? { err } : { reason: err }, 'health probe server stop failed');\n }\n }\n };\n\n const failStartup = async (err: unknown, message: string): Promise<never> => {\n log.error(err instanceof Error ? { err } : { reason: err }, message);\n startup.span.setStatus({ code: SpanStatusCode.ERROR, message });\n startup.span.end();\n\n await shutdownLifecycle();\n await shutdownTelemetry();\n process.exit(1);\n };\n\n try {\n const bootStartedAt = performance.now();\n\n // @ts-expect-error virtual module provided by the integration\n bootModule = (await import('virtual:@astroscope/node/boot')) as BootModule;\n\n await withSpan('boot', { parent: startup.context }, () => runStartup(bootModule, context));\n\n bootMs = roundMs(performance.now() - bootStartedAt);\n } catch (err) {\n await failStartup(err, 'startup failed');\n }\n\n const warmupError = await warmup;\n\n if (warmupError !== undefined) {\n await failStartup(warmupError, 'warmup import failed');\n }\n\n if (health) probes.startup.enable();\n\n const client = resolveClientDir(runtimeOptions, import.meta.url);\n const appHandler = createAppHandler(app, runtimeOptions, client);\n const staticHandler = createStaticHandler(app, client);\n const instrument = createRequestInstrumentation({\n logging: runtimeOptions.logging,\n telemetry: runtimeOptions.telemetry ? { exclude: runtimeOptions.telemetry.exclude } : false,\n });\n\n let tls: { cert: Buffer; key: Buffer } | undefined;\n\n try {\n tls = loadTlsOptions();\n } catch (err) {\n await failStartup(err, 'failed to load TLS options');\n }\n\n const listener: http.RequestListener = (req, res) => {\n try {\n decodeURI(req.url ?? '');\n } catch {\n res.writeHead(400);\n res.end('Bad request.');\n\n return;\n }\n\n instrument(req, res, () => {\n if (redirectDuplicateSlashes(req, res)) return;\n if (dispatchNativeMount(req, res)) return;\n\n staticHandler(req, res, () => void appHandler(req, res));\n });\n };\n\n const server = tls ? https.createServer(tls, listener) : http.createServer(listener);\n\n try {\n await withSpan('listen', { parent: startup.context }, () => {\n return new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(port, host, resolve);\n });\n });\n } catch (err) {\n await failStartup(err, `failed to listen on ${host}:${port}`);\n }\n\n if (health) probes.ready.enable();\n\n startup.span.setStatus({ code: SpanStatusCode.OK });\n startup.span.end();\n\n log.info(\n {\n host,\n port,\n ...(tls && { https: true }),\n health: !!health,\n bootMs,\n warmupMs,\n totalMs: roundMs(performance.now() - startedAt),\n },\n 'server ready',\n );\n\n let stopPromise: Promise<void> | undefined;\n let resolveClosed!: () => void;\n\n const closedPromise = new Promise<void>((resolve) => {\n resolveClosed = resolve;\n });\n\n const doStop = async (): Promise<void> => {\n if (health) probes.ready.disable();\n\n log.info('shutdown initiated');\n\n const drainStartedAt = performance.now();\n const shutdown = startSpan('shutdown');\n\n await withSpan('drain', { parent: shutdown.context }, async () => {\n const closed = new Promise<void>((resolve) => server.close(() => resolve()));\n\n server.closeIdleConnections();\n\n const forceTimer = setTimeout(() => server.closeAllConnections(), runtimeOptions.shutdownTimeout);\n\n await closed;\n\n clearTimeout(forceTimer);\n });\n\n const drainMs = roundMs(performance.now() - drainStartedAt);\n\n await shutdownLifecycle(shutdown.context);\n\n shutdown.span.end();\n\n log.info({ drainMs }, 'shutdown complete');\n\n await shutdownTelemetry();\n resolveClosed();\n };\n\n const stop = (): Promise<void> => (stopPromise ??= doStop());\n\n process.once('SIGTERM', () => void stop().then(() => process.exit(0)));\n process.once('SIGINT', () => void stop().then(() => process.exit(0)));\n\n return { host, port, stop, closed: () => closedPromise };\n}\n\nif (process.env['ASTROSCOPE_NODE_AUTOSTART'] !== 'disabled') {\n await startServer();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAgB,iBAAiB,SAA6C,eAA+B;CAC3G,MAAM,aAAa,IAAI,cAAc,IAAI,IAAI,QAAQ,MAAM,CAAC;CAC5D,MAAM,aAAa,IAAI,cAAc,IAAI,IAAI,QAAQ,MAAM,CAAC;CAC5D,MAAM,MAAM,KAAK,SAAS,YAAY,UAAU;CAChD,MAAM,eAAe,KAAK,SAAS,UAAU;CAE7C,IAAI,uBAAuB,KAAK,QAAQ,aAAa;CACrD,IAAI,WAAW;CAEf,OAAO,CAAC,qBAAqB,SAAS,YAAY,GAAG;EACnD,IAAI,yBAAyB,UAC3B,MAAM,IAAI,MACR,2DAA2D,aAAa,wBAAwB,cAAc,EAChH;EAGF,WAAW;EACX,uBAAuB,KAAK,QAAQ,oBAAoB;CAC1D;CAEA,MAAM,YAAY,IAAI,IAAI,IAAI,SAAS,GAAG,IAAI,MAAM,GAAG,IAAI,I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