@astroscope/node 1.3.0 → 1.4.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.
- package/README.md +1 -0
- package/dist/boot.d.ts +0 -1
- package/dist/boot.d.ts.map +1 -1
- package/dist/{construct-DgB-jR0a.d.ts → construct-BGlPfWMF.d.ts} +1 -2
- package/dist/construct-BGlPfWMF.d.ts.map +1 -0
- package/dist/csrf-middleware-entrypoint.d.ts.map +1 -1
- package/dist/dev-middleware-entrypoint.d.ts +0 -1
- package/dist/dev-middleware-entrypoint.d.ts.map +1 -1
- package/dist/{events-CUzQ2_cp.d.ts → events-u7J3ezJR.d.ts} +1 -2
- package/dist/events-u7J3ezJR.d.ts.map +1 -0
- package/dist/{excludes-DLF3A_Cf.d.ts → excludes-BDiE3eyp.d.ts} +1 -2
- package/dist/excludes-BDiE3eyp.d.ts.map +1 -0
- package/dist/excludes.d.ts +1 -1
- package/dist/health.d.ts.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +168 -0
- package/dist/index.js.map +1 -1
- package/dist/lifecycle/events.d.ts +1 -1
- package/dist/log/index.d.ts +1 -2
- package/dist/log/index.d.ts.map +1 -1
- package/dist/native.d.ts +0 -1
- package/dist/native.d.ts.map +1 -1
- package/dist/preview.d.ts +0 -1
- package/dist/preview.d.ts.map +1 -1
- package/dist/route-middleware-entrypoint.d.ts +0 -1
- package/dist/route-middleware-entrypoint.d.ts.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +19 -4
- package/dist/server.js.map +1 -1
- package/dist/types-D0uMBi2M.d.ts.map +1 -1
- package/package.json +8 -7
- package/dist/construct-DgB-jR0a.d.ts.map +0 -1
- package/dist/events-CUzQ2_cp.d.ts.map +0 -1
- package/dist/excludes-DLF3A_Cf.d.ts.map +0 -1
package/README.md
CHANGED
|
@@ -15,6 +15,7 @@ Opinionated, cloud-friendly Node adapter for Astro: boot lifecycle, health probe
|
|
|
15
15
|
- **Native mounts** — http-native handlers (`oidc-provider`, ACME) mounted on the adapter's server
|
|
16
16
|
- **Build tweaks** — SSR sourcemaps, SSR effect stripping
|
|
17
17
|
- **Dev restart machinery** — changes to the boot file or entry seams restart the dev server behind a holding page
|
|
18
|
+
- **Dev island warmup** — `.astro` sources are scanned for `client:*` components; their deps are pre-optimized and their module graphs warmed at server start, preventing "504 Outdated Optimize Dep" hydration failures from vite's lazy dep discovery
|
|
18
19
|
- **HTTPS for development** — `SERVER_CERT_PATH` / `SERVER_KEY_PATH` serve TLS directly for local runs of the built server ([HTTPS](#https)); in production, terminate TLS at the ingress
|
|
19
20
|
|
|
20
21
|
## What it does NOT do — beware
|
package/dist/boot.d.ts
CHANGED
package/dist/boot.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"boot.d.ts","names":[],"sources":["../src/lifecycle/context.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"boot.d.ts","names":[],"sources":["../src/lifecycle/context.ts"],"mappings":";;;;;;;;;;iBAiBgB,kBAAkB"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Logger, LoggerOptions } from "pino";
|
|
2
|
-
|
|
3
2
|
//#region src/observability/log/construct.d.ts
|
|
4
3
|
/**
|
|
5
4
|
* Contract of the `src/log.ts` entry seam: pino logger options, or a factory
|
|
@@ -11,4 +10,4 @@ type LoggerOptionsFactory = LoggerOptions | ((ctx: {
|
|
|
11
10
|
}) => LoggerOptions | Promise<LoggerOptions>);
|
|
12
11
|
//#endregion
|
|
13
12
|
export { LoggerOptionsFactory as t };
|
|
14
|
-
//# sourceMappingURL=construct-
|
|
13
|
+
//# sourceMappingURL=construct-BGlPfWMF.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"construct-BGlPfWMF.d.ts","names":[],"sources":["../src/observability/log/construct.ts"],"mappings":";;;;;;;KASY,uBAAuB,kBAAkB;EAAO;MAAmB,gBAAgB,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"csrf-middleware-entrypoint.d.ts","names":[],"sources":["../src/csrf/middleware-entrypoint.ts"],"mappings":";cAKa,
|
|
1
|
+
{"version":3,"file":"csrf-middleware-entrypoint.d.ts","names":[],"sources":["../src/csrf/middleware-entrypoint.ts"],"mappings":";cAKa,2BAAS"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev-middleware-entrypoint.d.ts","names":[],"sources":["../src/dev-mode/middleware-entrypoint.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"dev-middleware-entrypoint.d.ts","names":[],"sources":["../src/dev-mode/middleware-entrypoint.ts"],"mappings":";;;;;;;;;;cAWa,WAAW"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { t as BootContext } from "./types-D0uMBi2M.js";
|
|
2
|
-
|
|
3
2
|
//#region src/lifecycle/events.d.ts
|
|
4
3
|
type BootEventName = 'beforeOnStartup' | 'afterOnStartup' | 'beforeOnShutdown' | 'afterOnShutdown';
|
|
5
4
|
type BootEventHandler = (context: BootContext) => Promise<void> | void;
|
|
@@ -17,4 +16,4 @@ declare function off(event: BootEventName, handler: BootEventHandler): void;
|
|
|
17
16
|
declare function emit(event: BootEventName, context: BootContext): Promise<void>;
|
|
18
17
|
//#endregion
|
|
19
18
|
export { on as a, off as i, BootEventName as n, emit as r, BootEventHandler as t };
|
|
20
|
-
//# sourceMappingURL=events-
|
|
19
|
+
//# sourceMappingURL=events-u7J3ezJR.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"events-u7J3ezJR.d.ts","names":[],"sources":["../src/lifecycle/events.ts"],"mappings":";;KAEY;KAEA,oBAAoB,SAAS,gBAAgB;;;;iBAuBzC,GAAG,OAAO,eAAe,SAAS;;;;iBAelC,IAAI,OAAO,eAAe,SAAS;;;;iBAS7B,KAAK,OAAO,eAAe,SAAS,cAAc"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { StringPattern } from "@entwico/dash/match";
|
|
2
2
|
import { APIContext, MiddlewareHandler } from "astro";
|
|
3
|
-
|
|
4
3
|
//#region src/excludes/excludes.d.ts
|
|
5
4
|
/**
|
|
6
5
|
* Patterns accepted by @astroscope/node exclude options. The serializable
|
|
@@ -60,4 +59,4 @@ declare function shouldExclude(ctx: APIContext, exclude: readonly StringPattern[
|
|
|
60
59
|
declare function withExcluded(middleware: MiddlewareHandler, exclude: readonly StringPattern[] | ((context: APIContext) => boolean)): MiddlewareHandler;
|
|
61
60
|
//#endregion
|
|
62
61
|
export { STATIC_EXCLUDES as a, RECOMMENDED_EXCLUDES as i, DEV_EXCLUDES as n, shouldExclude as o, ExcludePattern as r, withExcluded as s, ASTRO_STATIC_EXCLUDES as t };
|
|
63
|
-
//# sourceMappingURL=excludes-
|
|
62
|
+
//# sourceMappingURL=excludes-BDiE3eyp.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"excludes-BDiE3eyp.d.ts","names":[],"sources":["../src/excludes/excludes.ts"],"mappings":";;;;;;;;KAQY,iBAAiB,QAAQ,gBAAgB;;;;cAKxC,cAAc;;;;cAWd,uBAAuB;;;;cAKvB,iBAAiB;;;;;;;;;;;;;;;;cAwBjB,sBAAsB;;;;iBAKnB,cACd,KAAK,YACL,kBAAkB,oBAAoB,SAAS;;;;;;;;;;;;;;;;;;iBA4BjC,aACd,YAAY,mBACZ,kBAAkB,oBAAoB,SAAS,0BAC9C"}
|
package/dist/excludes.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as STATIC_EXCLUDES, i as RECOMMENDED_EXCLUDES, n as DEV_EXCLUDES, o as shouldExclude, r as ExcludePattern, s as withExcluded, t as ASTRO_STATIC_EXCLUDES } from "./excludes-
|
|
1
|
+
import { a as STATIC_EXCLUDES, i as RECOMMENDED_EXCLUDES, n as DEV_EXCLUDES, o as shouldExclude, r as ExcludePattern, s as withExcluded, t as ASTRO_STATIC_EXCLUDES } from "./excludes-BDiE3eyp.js";
|
|
2
2
|
export { ASTRO_STATIC_EXCLUDES, DEV_EXCLUDES, ExcludePattern, RECOMMENDED_EXCLUDES, STATIC_EXCLUDES, shouldExclude, withExcluded };
|
package/dist/health.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"health.d.ts","names":[],"sources":["../src/health/health.ts"],"mappings":";UAEiB
|
|
1
|
+
{"version":3,"file":"health.d.ts","names":[],"sources":["../src/health/health.ts"],"mappings":";UAEiB;EACf;EACA;EACA;;UAGe;;;;EAIf;;;;;EAMA,aAAa,QAAQ,4BAA4B;;;;;EAMjD;;;;;EAMA;;;;;;;;;iBAUc,oBAAoB,YAAY"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { r as ExcludePattern } from "./excludes-
|
|
1
|
+
import { r as ExcludePattern } from "./excludes-BDiE3eyp.js";
|
|
2
|
+
import "./construct-BGlPfWMF.js";
|
|
2
3
|
import { t as BootContext } from "./types-D0uMBi2M.js";
|
|
3
|
-
import { n as BootEventName, t as BootEventHandler } from "./events-
|
|
4
|
+
import { n as BootEventName, t as BootEventHandler } from "./events-u7J3ezJR.js";
|
|
4
5
|
import { AstroIntegration } from "astro";
|
|
5
|
-
|
|
6
6
|
//#region src/types.d.ts
|
|
7
7
|
interface NodeBootOptions {
|
|
8
8
|
/**
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/integration/integration.ts","../src/platform/prepare.ts","../src/lifecycle/lifecycle.ts"],"mappings":";;;;;;UAEiB
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/integration/integration.ts","../src/platform/prepare.ts","../src/lifecycle/lifecycle.ts"],"mappings":";;;;;;UAEiB;;;;;EAKf;;;;;;EAOA;;;;;UAMe;EACf;EACA;EACA;EACA;;UAGe;;;;;EAKf;;;;;EAMA;;;;;EAMA,QAAQ;;UAGO;;;;;EAKf,UAAU;;;;;;EAOV;;;;;;EAOA;;UAGe;;;;;EAKf;;;;;EAMA;;UAGe;;;;;EAKf,UAAU;;;;;EAMV,aAAa;;;;;;EAOb;;UAGe;;;;;;;;EAQf,OAAO;;;;;;;EAQP,UAAU;;;;;;;EAQV,YAAY;;;;;;EAOZ,SAAS;;;;;;;EAQT;IAAS,UAAU;;;;;;EAMnB;;;;;;EAOA;;;;;;;;;;iBCtFsB,KAAK,UAAS,cAAmB;;;UChExC;EACf;;;;UCJe;EACf,cAAc,SAAS,gBAAgB;EACvC,eAAe,SAAS,gBAAgB"}
|
package/dist/index.js
CHANGED
|
@@ -6,8 +6,170 @@ import { r as RECOMMENDED_EXCLUDES } from "./excludes-pE23EbmQ.js";
|
|
|
6
6
|
import fs, { readFileSync } from "node:fs";
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { parse } from "@astrojs/compiler-rs";
|
|
9
10
|
import { Parser } from "acorn";
|
|
10
11
|
import MagicString from "magic-string";
|
|
12
|
+
//#region src/dev-mode/island-warmup.ts
|
|
13
|
+
function isAstNode(value) {
|
|
14
|
+
return typeof value === "object" && value !== null && typeof value.type === "string";
|
|
15
|
+
}
|
|
16
|
+
function walk$1(node, visit) {
|
|
17
|
+
if (Array.isArray(node)) {
|
|
18
|
+
for (const item of node) walk$1(item, visit);
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
if (typeof node !== "object" || node === null) return;
|
|
22
|
+
if (isAstNode(node)) visit(node);
|
|
23
|
+
for (const value of Object.values(node)) walk$1(value, visit);
|
|
24
|
+
}
|
|
25
|
+
/** local binding name → import specifier, from the frontmatter program */
|
|
26
|
+
function collectImports(program) {
|
|
27
|
+
const imports = /* @__PURE__ */ new Map();
|
|
28
|
+
walk$1(program, (node) => {
|
|
29
|
+
if (node.type !== "ImportDeclaration") return;
|
|
30
|
+
const decl = node;
|
|
31
|
+
if (decl.importKind === "type") return;
|
|
32
|
+
const specifier = typeof decl.source?.value === "string" ? decl.source.value : void 0;
|
|
33
|
+
if (!specifier) return;
|
|
34
|
+
for (const spec of decl.specifiers ?? []) {
|
|
35
|
+
if (spec.importKind === "type") continue;
|
|
36
|
+
if (typeof spec.local?.name === "string") imports.set(spec.local.name, specifier);
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
return imports;
|
|
40
|
+
}
|
|
41
|
+
/** the root identifier of a JSX tag: `Foo` → Foo, `Ns.Chart` → Ns */
|
|
42
|
+
function tagRootIdentifier(name) {
|
|
43
|
+
let current = name;
|
|
44
|
+
while (isAstNode(current) && current.type === "JSXMemberExpression") current = current.object;
|
|
45
|
+
if (isAstNode(current) && current.type === "JSXIdentifier") {
|
|
46
|
+
const identifier = current;
|
|
47
|
+
return typeof identifier.name === "string" ? identifier.name : void 0;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function hasClientDirective(attributes) {
|
|
51
|
+
if (!Array.isArray(attributes)) return false;
|
|
52
|
+
return attributes.some((attr) => {
|
|
53
|
+
if (!isAstNode(attr) || attr.type !== "JSXAttribute") return false;
|
|
54
|
+
const name = attr.name;
|
|
55
|
+
return typeof name?.name === "string" && name.name.startsWith("client:");
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Extract the import specifiers of all hydrated (`client:*`) components from
|
|
60
|
+
* raw `.astro` source. Astro components can't hydrate, so `.astro` specifiers
|
|
61
|
+
* are skipped; dynamic tags without a frontmatter import are invisible here.
|
|
62
|
+
*/
|
|
63
|
+
function scanAstroSource(source) {
|
|
64
|
+
const { ast } = parse(source);
|
|
65
|
+
const root = ast;
|
|
66
|
+
const imports = collectImports(root.frontmatter?.program);
|
|
67
|
+
if (imports.size === 0) return [];
|
|
68
|
+
const specifiers = /* @__PURE__ */ new Set();
|
|
69
|
+
walk$1(root.body, (node) => {
|
|
70
|
+
if (node.type !== "JSXOpeningElement") return;
|
|
71
|
+
const element = node;
|
|
72
|
+
if (!hasClientDirective(element.attributes)) return;
|
|
73
|
+
const rootName = tagRootIdentifier(element.name);
|
|
74
|
+
if (!rootName || /^[a-z]/.test(rootName)) return;
|
|
75
|
+
const specifier = imports.get(rootName);
|
|
76
|
+
if (specifier && !specifier.endsWith(".astro")) specifiers.add(specifier);
|
|
77
|
+
});
|
|
78
|
+
return [...specifiers];
|
|
79
|
+
}
|
|
80
|
+
/** scan all `.astro` files under `srcDir` for hydrated components */
|
|
81
|
+
async function scanProjectIslands(srcDir, logger) {
|
|
82
|
+
const islands = [];
|
|
83
|
+
let entries;
|
|
84
|
+
try {
|
|
85
|
+
entries = await fs.promises.readdir(srcDir, {
|
|
86
|
+
recursive: true,
|
|
87
|
+
withFileTypes: true
|
|
88
|
+
});
|
|
89
|
+
} catch {
|
|
90
|
+
return islands;
|
|
91
|
+
}
|
|
92
|
+
const files = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".astro")).map((entry) => path.join(entry.parentPath, entry.name));
|
|
93
|
+
await Promise.all(files.map(async (file) => {
|
|
94
|
+
try {
|
|
95
|
+
const source = await fs.promises.readFile(file, "utf8");
|
|
96
|
+
for (const specifier of scanAstroSource(source)) islands.push({
|
|
97
|
+
importer: file,
|
|
98
|
+
specifier
|
|
99
|
+
});
|
|
100
|
+
} catch (error) {
|
|
101
|
+
logger.debug(`island scan skipped ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
102
|
+
}
|
|
103
|
+
}));
|
|
104
|
+
return islands;
|
|
105
|
+
}
|
|
106
|
+
function packageNameOf(specifier) {
|
|
107
|
+
const segments = specifier.split("/");
|
|
108
|
+
return specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0] ?? specifier;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Bare package specifiers resolvable from the project's `node_modules` — these
|
|
112
|
+
* go into `optimizeDeps.include`. Anything else (relative paths, tsconfig
|
|
113
|
+
* aliases, hoisted workspace deps) is resolved through vite at server start;
|
|
114
|
+
* misclassification is harmless, just slightly later discovery.
|
|
115
|
+
*/
|
|
116
|
+
function selectBareSpecifiers(islands, root) {
|
|
117
|
+
const bare = /* @__PURE__ */ new Set();
|
|
118
|
+
for (const { specifier } of islands) {
|
|
119
|
+
if (specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("#")) continue;
|
|
120
|
+
if (fs.existsSync(path.join(root, "node_modules", packageNameOf(specifier)))) bare.add(specifier);
|
|
121
|
+
}
|
|
122
|
+
return [...bare];
|
|
123
|
+
}
|
|
124
|
+
function toRequestUrl(id, root) {
|
|
125
|
+
const normalized = id.split(path.sep).join("/");
|
|
126
|
+
const normalizedRoot = root.split(path.sep).join("/");
|
|
127
|
+
return normalized.startsWith(`${normalizedRoot}/`) ? normalized.slice(normalizedRoot.length) : `/@fs/${normalized}`;
|
|
128
|
+
}
|
|
129
|
+
function createIslandWarmup(options) {
|
|
130
|
+
const { root, srcDir, logger } = options;
|
|
131
|
+
let islands = [];
|
|
132
|
+
const warmIslands = async (server, batch, warmed) => {
|
|
133
|
+
const env = server.environments.client;
|
|
134
|
+
await Promise.all(batch.map(async ({ importer, specifier }) => {
|
|
135
|
+
try {
|
|
136
|
+
const resolved = await env.pluginContainer.resolveId(specifier, importer);
|
|
137
|
+
if (!resolved || resolved.external) return;
|
|
138
|
+
if (resolved.id.startsWith("\0") || resolved.id.includes("node_modules")) return;
|
|
139
|
+
if (warmed.has(resolved.id)) return;
|
|
140
|
+
warmed.add(resolved.id);
|
|
141
|
+
await env.warmupRequest(toRequestUrl(resolved.id, root));
|
|
142
|
+
} catch {}
|
|
143
|
+
}));
|
|
144
|
+
};
|
|
145
|
+
return {
|
|
146
|
+
name: "@astroscope/node/island-warmup",
|
|
147
|
+
async config() {
|
|
148
|
+
islands = await scanProjectIslands(srcDir, logger);
|
|
149
|
+
const include = selectBareSpecifiers(islands, root);
|
|
150
|
+
if (islands.length > 0) logger.info(`warming ${islands.length} island(s), pre-optimizing ${include.length} dependenc(ies)`);
|
|
151
|
+
return include.length > 0 ? { optimizeDeps: { include } } : void 0;
|
|
152
|
+
},
|
|
153
|
+
configureServer(server) {
|
|
154
|
+
const warmed = /* @__PURE__ */ new Set();
|
|
155
|
+
if (server.httpServer) server.httpServer.once("listening", () => void warmIslands(server, islands, warmed));
|
|
156
|
+
else warmIslands(server, islands, warmed);
|
|
157
|
+
const onWatcherEvent = (file) => {
|
|
158
|
+
if (!file.endsWith(".astro") || !file.startsWith(srcDir)) return;
|
|
159
|
+
fs.promises.readFile(file, "utf8").then((source) => {
|
|
160
|
+
const batch = scanAstroSource(source).map((specifier) => ({
|
|
161
|
+
importer: file,
|
|
162
|
+
specifier
|
|
163
|
+
}));
|
|
164
|
+
return warmIslands(server, batch, warmed);
|
|
165
|
+
}).catch(() => {});
|
|
166
|
+
};
|
|
167
|
+
server.watcher.on("add", onWatcherEvent);
|
|
168
|
+
server.watcher.on("change", onWatcherEvent);
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
//#endregion
|
|
11
173
|
//#region src/dev-mode/serialize-error.ts
|
|
12
174
|
function serializeError(error) {
|
|
13
175
|
if (error instanceof Error) return error.stack ?? error.message;
|
|
@@ -620,6 +782,11 @@ function node(options = {}) {
|
|
|
620
782
|
entrypoint: "@astroscope/node/dev-middleware",
|
|
621
783
|
order: "pre"
|
|
622
784
|
});
|
|
785
|
+
const islandWarmup = command === "dev" ? [createIslandWarmup({
|
|
786
|
+
root,
|
|
787
|
+
srcDir: fileURLToPath(config.srcDir),
|
|
788
|
+
logger
|
|
789
|
+
})] : [];
|
|
623
790
|
updateConfig({
|
|
624
791
|
build: { redirects: false },
|
|
625
792
|
...config.trailingSlash === "ignore" && { trailingSlash: "never" },
|
|
@@ -633,6 +800,7 @@ function node(options = {}) {
|
|
|
633
800
|
} },
|
|
634
801
|
vite: { plugins: [
|
|
635
802
|
...devMachinery,
|
|
803
|
+
...islandWarmup,
|
|
636
804
|
ssrSourcemapPlugin(),
|
|
637
805
|
stripSsrEffectsPlugin(),
|
|
638
806
|
{
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/dev-mode/serialize-error.ts","../src/dev-mode/scheduler.ts","../src/dev-mode/vite-env.ts","../src/dev-mode/ignored.ts","../src/dev-mode/watch.ts","../src/dev-mode/machinery.ts","../src/excludes/serialize.ts","../src/tweaks/sourcemap.ts","../src/tweaks/strip-effects.ts","../src/integration/integration.ts"],"sourcesContent":["export function serializeError(error: unknown): string {\n if (error instanceof Error) {\n return error.stack ?? error.message;\n }\n\n return JSON.stringify(error);\n}\n","import path from 'node:path';\nimport type { ViteDevServer } from 'vite';\nimport { serializeError } from './serialize-error.js';\n\ntype Logger = { info(msg: string): void; error(msg: string): void };\n\nconst FULL_RELOAD_UNKNOWN = '<unknown>';\n\n/**\n * Coordinates dev-server restarts: debounces bursts, chains a follow-up if\n * changes arrive mid-restart (vite's `ssrImport` reads disk at import time,\n * so changes during a restart would otherwise be missed), and logs once per\n * restart with what triggered it.\n *\n * One instance per integration, shared across restart-induced configureServer\n * reruns — chain coordination would be lost if recreated each time.\n */\nexport class RestartScheduler {\n private _inFlight = false;\n private _pending = false;\n private _debounceTimer: ReturnType<typeof setTimeout> | undefined;\n private _pendingBootDeps = new Set<string>();\n private _pendingFullReloads = new Set<string>();\n // set while a restart chain is running. the gate probes it (`isRestartPending`)\n // to short-circuit requests, and awaits it (`waitForRestart`) on readiness.\n private _runPromise: Promise<void> | undefined;\n // set when a restart attempt fails\n private _lastFailure: { message: string } | undefined;\n\n constructor(\n private readonly debounceMs: number,\n private readonly logger: Logger,\n ) {}\n\n // true from the moment a change is queued until the restart completes — covers\n // the debounce window too, so requests don't slip past the gate before _run starts.\n isRestartPending(): boolean {\n return !!this._runPromise || !!this._debounceTimer || !!this._lastFailure;\n }\n\n getLastFailure(): { message: string } | undefined {\n return this._lastFailure;\n }\n\n recordFailure(message: string): void {\n this._lastFailure = { message };\n }\n\n clearFailure(): void {\n this._lastFailure = undefined;\n }\n\n schedule(server: ViteDevServer, changedPath: string): void {\n this._pendingBootDeps.add(changedPath);\n this._scheduleRun(server);\n }\n\n scheduleFullReload(server: ViteDevServer, triggeredBy?: string): void {\n this._pendingFullReloads.add(triggeredBy ?? FULL_RELOAD_UNKNOWN);\n this._scheduleRun(server);\n }\n\n /**\n * Resolves when no restart is running. Loops to handle back-to-back restarts\n * (e.g. one chain ends and a queued debounce timer immediately fires a new\n * one). Never rejects, so a failed restart still releases the gate — caller\n * proceeds against the broken state rather than hanging forever.\n */\n async waitForRestart(): Promise<void> {\n while (this._runPromise) {\n try {\n await this._runPromise;\n } catch {\n // restart failed — release anyway\n }\n }\n }\n\n private _scheduleRun(server: ViteDevServer): void {\n clearTimeout(this._debounceTimer);\n this._debounceTimer = setTimeout(() => {\n this._debounceTimer = undefined;\n void this._run(server);\n }, this.debounceMs);\n }\n\n private async _run(server: ViteDevServer): Promise<void> {\n if (this._inFlight) {\n // loop driving the in-flight restart will pick up the next iteration.\n this._pending = true;\n\n return;\n }\n\n this._inFlight = true;\n\n let resolveRun!: () => void;\n\n this._runPromise = new Promise<void>((resolve) => {\n resolveRun = resolve;\n });\n\n try {\n do {\n this._pending = false;\n\n const bootDeps = [...this._pendingBootDeps].sort();\n const fullReloads = [...this._pendingFullReloads].sort();\n\n this._pendingBootDeps.clear();\n this._pendingFullReloads.clear();\n\n if (bootDeps.length > 0 || fullReloads.length > 0) {\n this.logger.info(this._formatReason(server, bootDeps, fullReloads));\n }\n\n try {\n await server.restart();\n } catch (error) {\n this.logger.error(`error during dev server restart: ${serializeError(error)}`);\n }\n } while (this._pending);\n } finally {\n this._inFlight = false;\n this._runPromise = undefined;\n resolveRun();\n }\n }\n\n private _formatReason(server: ViteDevServer, bootDeps: string[], fullReloads: string[]): string {\n const root = server.config.root;\n const rel = (p: string): string => path.relative(root, p) || p;\n const parts: string[] = [];\n\n if (bootDeps.length === 1) {\n parts.push(`boot dep changed: ${rel(bootDeps[0]!)}`);\n } else if (bootDeps.length > 1) {\n parts.push(`boot deps changed (${bootDeps.length}): ${bootDeps.map(rel).join(', ')}`);\n }\n\n if (fullReloads.length > 0) {\n const named = fullReloads.filter((p) => p !== FULL_RELOAD_UNKNOWN);\n\n if (named.length === 0) {\n parts.push('vite SSR full-reload');\n } else {\n parts.push(`vite SSR full-reload (triggered by ${named.map(rel).join(', ')})`);\n }\n }\n\n return `${parts.join(' + ')} — restarting dev server`;\n }\n}\n","import type { DevEnvironment, ViteDevServer } from 'vite';\n\ntype RunnableEnv = DevEnvironment & { runner: { import: (id: string) => Promise<unknown> } };\n\n/**\n * duck-typed runnable-env check. avoids `isRunnableDevEnvironment` which relies on\n * `instanceof RunnableDevEnvironment` — that breaks when the consumer and vite host\n * resolve to different vite installs (e.g. linked packages outside the workspace).\n */\nfunction isRunnable(env: DevEnvironment | undefined): env is RunnableEnv {\n return (\n !!env &&\n typeof (env as { runner?: unknown }).runner === 'object' &&\n typeof (env as RunnableEnv).runner.import === 'function'\n );\n}\n\n/**\n * resolve a runnable dev environment — prefers `ssr`, falls back to `astro`.\n * astro 6 exposes a separate `astro` environment when `ssr` isn't runnable\n * (see astro/core/constants.ts ASTRO_VITE_ENVIRONMENT_NAMES).\n */\nfunction getRunnableEnv(server: ViteDevServer): RunnableEnv {\n const ssr = server.environments['ssr'];\n\n if (isRunnable(ssr)) return ssr;\n\n const astro = server.environments['astro'];\n\n if (isRunnable(astro)) return astro;\n\n const names = Object.keys(server.environments);\n\n throw new Error(`no runnable dev environment found — available: ${names.join(', ')}`);\n}\n\n/**\n * load a module via the Vite Environment API.\n */\nexport async function ssrImport<T = Record<string, unknown>>(server: ViteDevServer, moduleId: string): Promise<T> {\n return getRunnableEnv(server).runner.import(moduleId) as Promise<T>;\n}\n\n/**\n * return the env whose `hot` channel should receive astro-targeted events.\n * astro listens on the env that backs its middleware runner.\n */\nexport function getAstroHotEnv(server: ViteDevServer): DevEnvironment | undefined {\n const ssr = server.environments['ssr'];\n\n if (isRunnable(ssr)) return ssr;\n\n const astro = server.environments['astro'];\n\n if (isRunnable(astro)) return astro;\n\n return undefined;\n}\n","export const ignoredSuffixes = [\n // type definitions\n '.d.ts',\n '.d.mts',\n '.d.cts',\n // images\n '.png',\n '.jpg',\n '.jpeg',\n '.gif',\n '.svg',\n '.webp',\n '.avif',\n '.ico',\n // fonts\n '.woff',\n '.woff2',\n '.ttf',\n '.otf',\n '.eot',\n // other static assets\n '.pdf',\n '.mp3',\n '.mp4',\n '.webm',\n '.ogg',\n '.wav',\n // data/config that boot typically doesn't import\n '.json',\n '.yaml',\n '.yml',\n '.toml',\n '.md',\n '.mdx',\n '.txt',\n // styles (handled by Vite's CSS HMR)\n '.css',\n '.scss',\n '.sass',\n '.less',\n];\n","import type { EventEmitter } from 'node:events';\nimport { readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { HotPayload, ViteDevServer } from 'vite';\nimport { GEN_HEADER, getCurrentGeneration } from './generation.js';\nimport { ignoredSuffixes } from './ignored.js';\nimport type { RestartScheduler } from './scheduler.js';\nimport { getAstroHotEnv } from './vite-env.js';\n\nconst RESTART_HTML = readFileSync(fileURLToPath(new URL('./restart-page.html', import.meta.url)), 'utf8');\n\nexport function setupBootWatch(server: ViteDevServer, entries: string[], scheduler: RestartScheduler): void {\n const entryFilePaths = entries.map((entry) => path.resolve(server.config.root, entry));\n\n const runnableEnv = getAstroHotEnv(server);\n const bootModuleGraph = runnableEnv?.moduleGraph;\n\n const collectBootDependencies = (): Set<string> => {\n const deps = new Set<string>();\n const seen = new Set<string>();\n\n for (const entryFilePath of entryFilePaths) {\n const entryModules = bootModuleGraph?.getModulesByFile(entryFilePath);\n const entryModule = entryModules ? [...entryModules][0] : undefined;\n\n if (!entryModule) continue;\n\n const visit = (mod: typeof entryModule): void => {\n if (!mod?.file || seen.has(mod.file)) return;\n\n seen.add(mod.file);\n deps.add(mod.file);\n\n for (const imp of mod.importedModules) visit(imp);\n };\n\n visit(entryModule);\n }\n\n return deps;\n };\n\n const shouldIgnore = (filePath: string): boolean => {\n const p = filePath.toLowerCase();\n\n return ignoredSuffixes.some((suffix) => p.endsWith(suffix));\n };\n\n const onWatcherEvent = (changedPath: string): void => {\n if (shouldIgnore(changedPath)) return;\n\n const bootDeps = collectBootDependencies();\n\n if (!bootDeps.has(changedPath)) return;\n\n scheduler.schedule(server, changedPath);\n };\n\n server.watcher.on('change', onWatcherEvent);\n server.watcher.on('add', onWatcherEvent);\n server.watcher.on('unlink', onWatcherEvent);\n\n // ignore full-reloads emitted during server startup (dep optimization, port retries).\n let handleFullReloads = false;\n\n if (server.httpServer) {\n server.httpServer.once('listening', () => {\n handleFullReloads = true;\n });\n } else {\n // middleware mode — no httpServer, enable immediately\n handleFullReloads = true;\n }\n\n // SSR full-reloads come through the runnable env's hot channel and clear\n // its module runner's cache — onStartup needs to run again on a fresh server.\n const outsideEmitter = (runnableEnv?.hot as { api?: { outsideEmitter?: EventEmitter } } | undefined)?.api\n ?.outsideEmitter;\n\n if (outsideEmitter) {\n outsideEmitter.on('send', (payload: HotPayload) => {\n if (!handleFullReloads) return;\n if (payload.type !== 'full-reload') return;\n\n const triggeredBy = 'triggeredBy' in payload ? (payload.triggeredBy as string) : undefined;\n\n scheduler.scheduleFullReload(server, triggeredBy);\n });\n }\n}\n\nconst READINESS_PATH = '/__astroscope_boot_ready';\n\n/**\n * Gate requests: show 503 holding page during restart, readiness probe for the reload.\n */\nexport function installBootGate(\n server: Pick<ViteDevServer, 'middlewares'>,\n scheduler: Pick<RestartScheduler, 'waitForRestart' | 'isRestartPending' | 'getLastFailure'>,\n): void {\n const middlewares = server.middlewares as unknown as {\n stack: { route: string; handle: unknown }[];\n };\n\n // must be `stack.unshift`ed to land before astro's handler\n middlewares.stack.unshift({\n route: '',\n handle: (async (\n req: { url?: string },\n res: {\n writeHead: (status: number, headers: Record<string, string>) => void;\n end: (body?: string) => void;\n headersSent?: boolean;\n },\n next: (err?: unknown) => void,\n ) => {\n // readiness probe: holding page polls this. blocks until no restart is in\n // flight, then 204 on success / 503 + JSON error if last attempt failed.\n if (req.url === READINESS_PATH) {\n await scheduler.waitForRestart();\n\n if (res.headersSent) return;\n\n const failure = scheduler.getLastFailure();\n\n if (failure) {\n res.writeHead(503, { 'cache-control': 'no-store', 'content-type': 'application/json' });\n res.end(JSON.stringify({ error: failure.message }));\n\n return;\n }\n\n res.writeHead(204, { 'cache-control': 'no-store' });\n res.end();\n\n return;\n }\n\n if (isDevInternalPath(req.url)) {\n next();\n\n return;\n }\n\n // respond now; awaiting the restart would let vite destroy the socket mid-response.\n if (scheduler.isRestartPending()) {\n res.writeHead(503, {\n 'content-type': 'text/html; charset=utf-8',\n 'cache-control': 'no-store',\n 'retry-after': '1',\n });\n res.end(RESTART_HTML);\n\n return;\n }\n\n next();\n }) as never,\n });\n}\n\nfunction isDevInternalPath(url: string | undefined): boolean {\n if (!url) return false;\n\n return url.startsWith('/@') || url.startsWith('/__') || url.includes('/node_modules/');\n}\n\n/**\n * Stamp the current generation onto every incoming request so the runtime\n * Astro middleware can later detect whether the request belongs to a previous\n * (now torn-down) generation\n */\nexport function installGenStamp(server: Pick<ViteDevServer, 'middlewares'>): void {\n const middlewares = server.middlewares as unknown as {\n stack: { route: string; handle: unknown }[];\n };\n\n middlewares.stack.unshift({\n route: '',\n handle: ((req: { headers: Record<string, string> }, _res: unknown, next: () => void) => {\n req.headers[GEN_HEADER] = String(getCurrentGeneration());\n next();\n }) as never,\n });\n}\n","import type { AstroConfig } from 'astro';\nimport type { Plugin } from 'vite';\nimport { setBootContext } from '../lifecycle/context.js';\nimport { type BootModule, runShutdown, runStartup } from '../lifecycle/lifecycle.js';\nimport type { BootContext } from '../lifecycle/types.js';\nimport { clearNativeMounts } from '../server/native-mount.js';\nimport { incrementGeneration } from './generation.js';\nimport { RestartScheduler } from './scheduler.js';\nimport { serializeError } from './serialize-error.js';\nimport { ssrImport } from './vite-env.js';\nimport { installBootGate, installGenStamp, setupBootWatch } from './watch.js';\n\ninterface Logger {\n info(msg: string): void;\n warn(msg: string): void;\n error(msg: string): void;\n}\n\nexport interface DevMachineryOptions {\n /** boot file path relative to the project root; undefined = no boot module */\n entry: string | undefined;\n /** restart the dev server when watched dependencies change */\n watch: boolean;\n /** extra files (relative to the root) whose changes restart the dev server */\n watchEntries: string[];\n /** platform seams; runs each generation before the boot module starts */\n prepare: (importModule: <T = Record<string, unknown>>(id: string) => Promise<T>) => Promise<void>;\n logger: Logger;\n getConfig: () => AstroConfig | null;\n}\n\n/**\n * Resolve the default host and port from the Astro server config.\n * Falls back to `localhost:4321` when no config is provided.\n */\nfunction getServerDefaults(config: AstroConfig | null): { host: string; port: number } {\n return {\n host:\n typeof config?.server?.host === 'string'\n ? config.server.host\n : config?.server?.host === true\n ? '0.0.0.0'\n : 'localhost',\n port: config?.server?.port ?? 4321,\n };\n}\n\n/**\n * Build a dev-mode boot context from the running server's address,\n * falling back to Astro config defaults if the server isn't listening yet.\n */\nfunction resolveBootContext(\n server: { httpServer?: { address(): unknown } | null | undefined },\n config: AstroConfig | null,\n): BootContext {\n const addr = server.httpServer?.address();\n\n if (addr && typeof addr === 'object' && 'address' in addr && 'port' in addr) {\n const host =\n (addr as { address: string }).address === '::' || (addr as { address: string }).address === '0.0.0.0'\n ? 'localhost'\n : (addr as { address: string }).address;\n\n return { dev: true, host, port: (addr as { port: number }).port };\n }\n\n const { host, port } = getServerDefaults(config);\n\n return { dev: true, host, port };\n}\n\n/**\n * The dev-mode boot machinery: runs the platform seams and the boot lifecycle\n * per restart generation, restarts the dev server when watched dependencies\n * change, and gates requests behind a holding page during restarts.\n */\nexport function createDevMachinery(options: DevMachineryOptions): Plugin[] {\n const { entry, logger } = options;\n\n let hasStartupSucceededOnce = false;\n // run by the next configureServer before its startup so resources (ports,\n // sockets, locks) from the previous module are released first. idempotent.\n let priorShutdown: (() => Promise<void>) | undefined;\n // shared across restart-induced configureServer reruns\n const scheduler = options.watch ? new RestartScheduler(100, logger) : undefined;\n\n return [\n // gate plugin: enforce 'post' + returned-function so our `stack.unshift`\n // (in installBootGate / installGenStamp) lands at connect position 0,\n // ahead of astro's handler.\n {\n name: '@astroscope/node/dev-gate',\n enforce: 'post',\n\n configureServer(server) {\n if (!scheduler) return;\n\n return () => {\n // gen-stamp is unshifted last so it ends up at position 0:\n // every request gets a generation header before anything else,\n // including the gate's readiness probe.\n installBootGate(server, scheduler);\n installGenStamp(server);\n };\n },\n },\n\n // startup plugin: runs after all other configureServer hooks\n {\n name: '@astroscope/node/dev-startup',\n enforce: 'post',\n\n async configureServer(server) {\n incrementGeneration();\n\n // tear down the previous module first so its resources are released\n // before the new startup tries to claim them.\n if (priorShutdown) {\n await priorShutdown();\n priorShutdown = undefined;\n }\n\n const astroConfig = options.getConfig();\n const bootContext = resolveBootContext(server, astroConfig);\n let bootModule: BootModule | undefined;\n\n setBootContext(bootContext);\n\n try {\n await options.prepare((id) => ssrImport(server, id));\n\n bootModule = entry ? await ssrImport<BootModule>(server, `/${entry}`) : {};\n\n await runStartup(bootModule, bootContext);\n } catch (error) {\n logger.error(`Error running startup script: ${serializeError(error)}`);\n\n if (bootModule) {\n try {\n await runShutdown(bootModule, bootContext);\n } catch {\n // best-effort cleanup\n }\n }\n\n // restart failure: the gate can keep the holding\n // page up with an error message instead of dropping users onto a\n // half-broken old server.\n if (hasStartupSucceededOnce) {\n scheduler?.recordFailure(serializeError(error));\n\n throw error;\n }\n\n // initial failure: exit cleanly (mirrors the production server).\n process.exit(1);\n }\n\n hasStartupSucceededOnce = true;\n scheduler?.clearFailure();\n\n // capture so shutdown sees the same instance that started.\n const startedModule = bootModule;\n let shutdownDone = false;\n\n const shutdown = async (): Promise<void> => {\n if (shutdownDone) return;\n\n shutdownDone = true;\n\n try {\n await runShutdown(startedModule, resolveBootContext(server, options.getConfig()));\n } catch (error) {\n logger.error(`Error running shutdown script: ${serializeError(error)}`);\n }\n\n // the next generation's onStartup re-registers its mounts\n clearNativeMounts();\n };\n\n priorShutdown = shutdown;\n\n // sigint/sigterm path. also fires during restart but shutdown is idempotent.\n server.httpServer?.once('close', () => {\n void shutdown();\n });\n\n if (scheduler) {\n setupBootWatch(server, [...(entry ? [entry] : []), ...options.watchEntries], scheduler);\n }\n },\n },\n ];\n}\n","import type { ExcludePattern } from './excludes.js';\n\n/**\n * Serialize exclude patterns to JavaScript code for use in virtual modules.\n * Handles RegExp objects which JSON.stringify cannot serialize.\n */\nexport function serializeExcludePatterns(patterns: ExcludePattern[]): string {\n return `[${patterns.map((p) => ('pattern' in p ? `{ pattern: ${p.pattern.toString()} }` : JSON.stringify(p))).join(', ')}]`;\n}\n","import type { Plugin } from 'vite';\n\n/**\n * emit sourcemaps only for the SSR build. client bundles are left unmapped\n * so browsers can't fetch source via `//# sourceMappingURL=`.\n *\n * vite 7's `environments.ssr.build.sourcemap` looks cleaner but wholesale\n * replaces astro's SSR build defaults (including entry file naming), which\n * breaks the embedded dev boot machinery. using `isSsrBuild` keeps the\n * rest of astro's SSR config intact.\n */\nexport function ssrSourcemapPlugin(): Plugin {\n return {\n name: '@astroscope/node/tweaks/sourcemap',\n config(_config, { isSsrBuild }) {\n if (isSsrBuild) return { build: { sourcemap: true } };\n\n return {};\n },\n };\n}\n","import { Parser } from 'acorn';\nimport MagicString from 'magic-string';\nimport type { Plugin } from 'vite';\n\nconst HOOK_NAMES = new Set(['useEffect', 'useLayoutEffect', 'useInsertionEffect']);\nconst REACT_SOURCE = /^react(\\/.*)?$/;\nconst TRANSFORMABLE = /\\.(?:[mc]?[jt]sx?)$/;\nconst EMPTY_FN = '(()=>{})';\n\n/**\n * in SSR builds, react effect hooks never execute. emptying their callbacks\n * lets rolldown drop dead branches — including dynamic imports of client-only\n * libs (maplibre-gl, hls.js, etc.) — from the server bundle, which in turn\n * stops nft from tracing them at docker-image time.\n *\n * scope is deliberately narrow: first-party code only (no node_modules), only\n * in the SSR pass, and binding-aware (the React import must resolve to the\n * real react package). raw chunks where bundling has erased the binding are\n * left alone — that's NFT's domain, not ours.\n */\nexport function stripSsrEffectsPlugin(): Plugin {\n return {\n name: '@astroscope/node/tweaks/strip-effects',\n enforce: 'post',\n transform(code, id, options) {\n if (!options?.ssr) return null;\n if (id.includes('/node_modules/')) return null;\n\n const cleanId = id.split('?')[0] ?? id;\n\n if (!TRANSFORMABLE.test(cleanId)) return null;\n if (!code.includes('useEffect') && !code.includes('useLayoutEffect') && !code.includes('useInsertionEffect')) {\n return null;\n }\n\n let ast: any;\n\n try {\n ast = Parser.parse(code, {\n ecmaVersion: 'latest',\n sourceType: 'module',\n allowReturnOutsideFunction: true,\n allowAwaitOutsideFunction: true,\n allowImportExportEverywhere: true,\n allowHashBang: true,\n });\n } catch {\n return null;\n }\n\n const directHooks = new Set<string>();\n const namespaceHooks = new Set<string>();\n\n walk(ast, (node) => {\n if (node.type !== 'ImportDeclaration') return;\n\n const src = node.source?.value;\n\n if (typeof src !== 'string' || !REACT_SOURCE.test(src)) return;\n\n for (const spec of node.specifiers ?? []) {\n if (spec.type === 'ImportSpecifier') {\n const imported = spec.imported?.name ?? spec.imported?.value;\n\n if (HOOK_NAMES.has(imported)) directHooks.add(spec.local.name);\n } else if (spec.type === 'ImportDefaultSpecifier' || spec.type === 'ImportNamespaceSpecifier') {\n namespaceHooks.add(spec.local.name);\n }\n }\n });\n\n if (directHooks.size === 0 && namespaceHooks.size === 0) return null;\n\n const replacements: { start: number; end: number }[] = [];\n\n walk(ast, (node) => {\n if (node.type !== 'CallExpression' || !node.arguments?.length) return;\n\n const callee = node.callee;\n const isDirect = callee.type === 'Identifier' && directHooks.has(callee.name);\n const isMember =\n callee.type === 'MemberExpression' &&\n !callee.computed &&\n callee.object?.type === 'Identifier' &&\n namespaceHooks.has(callee.object.name) &&\n callee.property?.type === 'Identifier' &&\n HOOK_NAMES.has(callee.property.name);\n\n if (!isDirect && !isMember) return;\n\n const arg = node.arguments[0];\n\n replacements.push({ start: arg.start, end: arg.end });\n });\n\n if (replacements.length === 0) return null;\n\n const s = new MagicString(code);\n\n for (const { start, end } of replacements) {\n s.overwrite(start, end, EMPTY_FN);\n }\n\n return { code: s.toString(), map: s.generateMap({ hires: true }) };\n },\n };\n}\n\nfunction walk(node: any, visit: (n: any) => void): void {\n if (!node || typeof node !== 'object') return;\n\n if (typeof node.type === 'string') visit(node);\n\n for (const key of Object.keys(node)) {\n const v = node[key];\n\n if (Array.isArray(v)) for (const item of v) walk(item, visit);\n else if (v && typeof v === 'object') walk(v, visit);\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { AstroConfig, AstroIntegration } from 'astro';\nimport { createDevMachinery } from '../dev-mode/machinery.js';\nimport { type ExcludePattern, RECOMMENDED_EXCLUDES } from '../excludes/excludes.js';\nimport { serializeExcludePatterns } from '../excludes/serialize.js';\nimport { createRequestInstrumentation } from '../observability/instrument.js';\nimport { preparePlatform } from '../platform/prepare.js';\nimport { dispatchNativeMount } from '../server/native-mount.js';\nimport { ssrSourcemapPlugin } from '../tweaks/sourcemap.js';\nimport { stripSsrEffectsPlugin } from '../tweaks/strip-effects.js';\nimport type { NodeOptions, RuntimeOptions } from '../types.js';\n\nexport const CONFIG_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/config';\nexport const BOOT_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/boot';\nexport const CSRF_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/csrf';\nexport const CONFIG_ENTRY_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/config-entry';\nexport const INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/instrumentation-entry';\nexport const LOG_ENTRY_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/log-entry';\n\nconst RESOLVED_CONFIG_VIRTUAL_MODULE_ID = `\\0${CONFIG_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_BOOT_VIRTUAL_MODULE_ID = `\\0${BOOT_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_CSRF_VIRTUAL_MODULE_ID = `\\0${CSRF_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_CONFIG_ENTRY_VIRTUAL_MODULE_ID = `\\0${CONFIG_ENTRY_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID = `\\0${INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_LOG_ENTRY_VIRTUAL_MODULE_ID = `\\0${LOG_ENTRY_VIRTUAL_MODULE_ID}`;\n\nconst SERVER_ENVIRONMENTS = ['ssr', 'prerender', 'astro'];\nconst DEFAULT_REQUEST_EXCLUDES: ExcludePattern[] = [...RECOMMENDED_EXCLUDES];\n\nfunction resolveHost(host: string | boolean | undefined): string {\n if (typeof host === 'string') return host;\n\n return host === true ? '0.0.0.0' : 'localhost';\n}\n\nfunction resolveBootEntry(root: string, entry: string | undefined): string | undefined {\n if (entry) {\n const abs = path.resolve(root, entry);\n\n if (!fs.existsSync(abs)) {\n throw new Error(`[@astroscope/node] boot entry not found: ${entry}`);\n }\n\n return abs;\n }\n\n for (const candidate of ['src/boot/index.ts', 'src/boot.ts']) {\n const abs = path.resolve(root, candidate);\n\n if (fs.existsSync(abs)) return abs;\n }\n\n return undefined;\n}\n\nfunction resolveSeam(root: string, candidate: string): string | undefined {\n const abs = path.resolve(root, candidate);\n\n return fs.existsSync(abs) ? abs : undefined;\n}\n\n/**\n * Node adapter for Astro with a first-class server entrypoint: the boot\n * lifecycle, module warmup, health probes, request logging and telemetry run\n * as plain code around `server.listen()` instead of being injected into the\n * build output.\n */\nexport default function node(options: NodeOptions = {}): AstroIntegration {\n const bootOptions = options.boot ?? {};\n const healthOptions = options.health ?? {};\n const csrfOptions = options.csrf ?? {};\n const loggingOptions = options.logging ?? {};\n const telemetryOptions = options.telemetry ?? {};\n\n const loggingExclude = loggingOptions ? (loggingOptions.exclude ?? DEFAULT_REQUEST_EXCLUDES) : [];\n const telemetryExclude = telemetryOptions ? (telemetryOptions.exclude ?? DEFAULT_REQUEST_EXCLUDES) : [];\n\n let astroConfig: AstroConfig | null = null;\n let bootEntry: string | undefined;\n let configSeam: string | undefined;\n let instrumentationSeam: string | undefined;\n let logSeam: string | undefined;\n let isDev = false;\n\n return {\n name: '@astroscope/node',\n hooks: {\n 'astro:config:setup': ({ command, config, updateConfig, addMiddleware, logger }) => {\n isDev = command === 'dev';\n\n // route enrichment first so csrf-rejected requests still carry a route\n if (loggingOptions || telemetryOptions) {\n addMiddleware({ order: 'pre', entrypoint: '@astroscope/node/route-middleware' });\n }\n\n if (csrfOptions) {\n addMiddleware({ order: 'pre', entrypoint: '@astroscope/node/csrf-middleware' });\n }\n\n const root = fileURLToPath(config.root);\n const watch = bootOptions === false ? false : (bootOptions.watch ?? true);\n\n bootEntry = bootOptions === false ? undefined : resolveBootEntry(root, bootOptions.entry);\n configSeam = resolveSeam(root, 'src/config.ts');\n instrumentationSeam = resolveSeam(root, 'src/instrumentation.ts');\n logSeam = resolveSeam(root, 'src/log.ts');\n\n const relativeSeam = (abs: string | undefined) =>\n abs ? path.relative(root, abs).split(path.sep).join('/') : undefined;\n\n const devMachinery =\n command === 'dev' && bootOptions !== false\n ? createDevMachinery({\n entry: bootEntry ? path.relative(root, bootEntry) : undefined,\n watch,\n // instrumentation runs once per process — watching it would\n // restart generations that can't re-apply it\n watchEntries: [relativeSeam(configSeam), relativeSeam(logSeam)].filter(\n (entry): entry is string => !!entry,\n ),\n prepare: (importModule) =>\n preparePlatform({\n dev: true,\n telemetry:\n telemetryOptions && telemetryOptions.dev\n ? { prometheus: telemetryOptions.prometheus ?? {} }\n : false,\n seams: {\n ...(configSeam && { config: () => importModule(`/${relativeSeam(configSeam)}`) }),\n ...(instrumentationSeam && {\n instrumentation: () => importModule(`/${relativeSeam(instrumentationSeam)}`),\n }),\n ...(logSeam && { log: () => importModule(`/${relativeSeam(logSeam)}`) }),\n },\n }),\n logger,\n getConfig: () => astroConfig,\n })\n : [];\n\n if (command === 'dev' && bootOptions !== false && watch) {\n // catches errors thrown by stale (post-shutdown) requests so\n // they don't pollute the logs during dev-server restarts.\n addMiddleware({ entrypoint: '@astroscope/node/dev-middleware', order: 'pre' });\n }\n\n updateConfig({\n build: { redirects: false },\n // opinionated defaults: no trailing slashes, behind LB\n ...(config.trailingSlash === 'ignore' && { trailingSlash: 'never' as const }),\n security: {\n // assumed to run behind LB\n ...(!config.security.allowedDomains?.length && { allowedDomains: [{}] }),\n // the embedded csrf middleware replaces the built-in origin check\n ...(csrfOptions && { checkOrigin: false }),\n },\n image: {\n endpoint: {\n route: config.image.endpoint.route ?? '_image',\n entrypoint:\n config.image.endpoint.entrypoint ??\n (command === 'dev' ? 'astro/assets/endpoint/dev' : 'astro/assets/endpoint/node'),\n },\n },\n vite: {\n plugins: [\n ...devMachinery,\n ssrSourcemapPlugin(),\n stripSsrEffectsPlugin(),\n {\n name: '@astroscope/node',\n\n configEnvironment(environmentName: string) {\n if (SERVER_ENVIRONMENTS.includes(environmentName)) {\n return { resolve: { noExternal: ['@astroscope/node'] } };\n }\n },\n\n resolveId(id: string) {\n if (id === CONFIG_VIRTUAL_MODULE_ID) return RESOLVED_CONFIG_VIRTUAL_MODULE_ID;\n if (id === BOOT_VIRTUAL_MODULE_ID) return RESOLVED_BOOT_VIRTUAL_MODULE_ID;\n if (id === CSRF_VIRTUAL_MODULE_ID) return RESOLVED_CSRF_VIRTUAL_MODULE_ID;\n if (id === CONFIG_ENTRY_VIRTUAL_MODULE_ID) return RESOLVED_CONFIG_ENTRY_VIRTUAL_MODULE_ID;\n if (id === INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID) {\n return RESOLVED_INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID;\n }\n if (id === LOG_ENTRY_VIRTUAL_MODULE_ID) return RESOLVED_LOG_ENTRY_VIRTUAL_MODULE_ID;\n },\n\n load(id: string) {\n if (id === RESOLVED_CONFIG_VIRTUAL_MODULE_ID) {\n if (!astroConfig) throw new Error('[@astroscope/node] astro config not resolved yet');\n\n const runtimeOptions: Omit<RuntimeOptions, 'logging' | 'telemetry'> = {\n host: resolveHost(astroConfig.server.host),\n port: astroConfig.server.port ?? 4321,\n client: astroConfig.build.client.toString(),\n server: astroConfig.build.server.toString(),\n bodySizeLimit: options.bodySizeLimit ?? 1024 * 1024 * 1024,\n shutdownTimeout: options.shutdownTimeout ?? 10_000,\n health: healthOptions\n ? {\n ...(healthOptions.host !== undefined && { host: healthOptions.host }),\n ...(healthOptions.port !== undefined && { port: healthOptions.port }),\n ...(healthOptions.paths && { paths: healthOptions.paths }),\n }\n : false,\n };\n\n // exclude patterns may contain RegExp — serialized as code, not JSON\n const logging = loggingOptions\n ? `{ exclude: ${serializeExcludePatterns(loggingExclude)}, extended: ${JSON.stringify(\n loggingOptions.extended ?? false,\n )} }`\n : 'false';\n const telemetry = telemetryOptions\n ? `{ exclude: ${serializeExcludePatterns(telemetryExclude)}, prometheus: ${JSON.stringify(\n telemetryOptions.prometheus ?? {},\n )} }`\n : 'false';\n\n return `export const options = { ...${JSON.stringify(runtimeOptions)}, logging: ${logging}, telemetry: ${telemetry} };`;\n }\n\n if (id === RESOLVED_BOOT_VIRTUAL_MODULE_ID) {\n // re-export to avoid absolute path manifest leaks\n return bootEntry ? `export * from ${JSON.stringify(bootEntry)};` : 'export {};';\n }\n\n if (id === RESOLVED_CSRF_VIRTUAL_MODULE_ID) {\n return `export const excludePatterns = ${serializeExcludePatterns(csrfOptions ? (csrfOptions.exclude ?? []) : [])};`;\n }\n\n if (id === RESOLVED_CONFIG_ENTRY_VIRTUAL_MODULE_ID) {\n // side-effect import: @entwico/zod-conf validation runs at module load\n return configSeam ? `import ${JSON.stringify(configSeam)};\\nexport {};` : 'export {};';\n }\n\n if (id === RESOLVED_INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID) {\n return instrumentationSeam ? `export * from ${JSON.stringify(instrumentationSeam)};` : 'export {};';\n }\n\n if (id === RESOLVED_LOG_ENTRY_VIRTUAL_MODULE_ID) {\n return logSeam\n ? `export { default } from ${JSON.stringify(logSeam)};`\n : 'export default undefined;';\n }\n },\n },\n ],\n },\n });\n },\n 'astro:server:setup': ({ server }) => {\n if (!isDev) return;\n\n const devLogging = loggingOptions && loggingOptions.dev;\n const devTelemetry = telemetryOptions && telemetryOptions.dev;\n\n const instrument =\n devLogging || devTelemetry\n ? createRequestInstrumentation({\n logging: devLogging ? { exclude: loggingExclude, extended: loggingOptions.extended ?? false } : false,\n telemetry: devTelemetry ? { exclude: telemetryExclude } : false,\n })\n : undefined;\n\n server.middlewares.use((req, res, next) => {\n const inner = (): void => {\n if (!dispatchNativeMount(req, res)) next();\n };\n\n if (instrument) {\n instrument(req, res, inner);\n } else {\n inner();\n }\n });\n },\n 'astro:config:done': ({ config, setAdapter }) => {\n astroConfig = config;\n\n setAdapter({\n name: '@astroscope/node',\n entrypointResolution: 'auto',\n serverEntrypoint: '@astroscope/node/server',\n previewEntrypoint: '@astroscope/node/preview',\n adapterFeatures: {\n buildOutput: 'server',\n middlewareMode: 'classic',\n },\n supportedAstroFeatures: {\n hybridOutput: 'stable',\n staticOutput: 'stable',\n serverOutput: 'stable',\n sharpImageService: 'stable',\n i18nDomains: 'experimental',\n envGetSecret: 'stable',\n },\n });\n },\n 'astro:build:done': async ({ logger }) => {\n if (!astroConfig) return;\n\n const { compressClientDir } = await import('../compress/compress.js');\n\n await compressClientDir(fileURLToPath(astroConfig.build.client), logger);\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAgB,eAAe,OAAwB;CACrD,IAAI,iBAAiB,OACnB,OAAO,MAAM,SAAS,MAAM;CAG9B,OAAO,KAAK,UAAU,KAAK;AAC7B;;;ACAA,MAAM,sBAAsB;;;;;;;;;;AAW5B,IAAa,mBAAb,MAA8B;CAaT;CACA;CAbn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
+
{"version":3,"file":"index.js","names":["walk"],"sources":["../src/dev-mode/island-warmup.ts","../src/dev-mode/serialize-error.ts","../src/dev-mode/scheduler.ts","../src/dev-mode/vite-env.ts","../src/dev-mode/ignored.ts","../src/dev-mode/watch.ts","../src/dev-mode/machinery.ts","../src/excludes/serialize.ts","../src/tweaks/sourcemap.ts","../src/tweaks/strip-effects.ts","../src/integration/integration.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { parse } from '@astrojs/compiler-rs';\nimport type { Plugin, ViteDevServer } from 'vite';\n\n/**\n * Vite discovers island dependencies lazily: astro registers no client entries,\n * so a dep like radix is first seen when an island hydrates. The optimizer then\n * re-runs, bumps the `?v=` hash and every in-flight import gets a\n * \"504 Outdated Optimize Dep\" — hydration fails until the full reload.\n *\n * This plugin scans `.astro` sources for `client:*` components at config time,\n * puts their bare package imports into `optimizeDeps.include` (initial optimize\n * pass) and warms their local module graphs at server start (vite's\n * `preTransformRequests` crawls static imports recursively), so discovery\n * happens before a browser holds stale URLs.\n */\n\ninterface Logger {\n info(msg: string): void;\n debug(msg: string): void;\n}\n\nexport interface IslandImport {\n /** absolute path of the .astro file rendering the island */\n importer: string;\n /** import specifier of the hydrated component */\n specifier: string;\n}\n\ninterface AstNode {\n type: string;\n [key: string]: unknown;\n}\n\nfunction isAstNode(value: unknown): value is AstNode {\n return typeof value === 'object' && value !== null && typeof (value as AstNode).type === 'string';\n}\n\nfunction walk(node: unknown, visit: (node: AstNode) => void): void {\n if (Array.isArray(node)) {\n for (const item of node) walk(item, visit);\n\n return;\n }\n\n if (typeof node !== 'object' || node === null) return;\n\n if (isAstNode(node)) visit(node);\n\n for (const value of Object.values(node)) walk(value, visit);\n}\n\ninterface ImportDeclarationNode {\n importKind?: string | null;\n source?: { value?: unknown } | null;\n specifiers?: { importKind?: string | null; local?: { name?: unknown } | null }[] | null;\n}\n\n/** local binding name → import specifier, from the frontmatter program */\nfunction collectImports(program: unknown): Map<string, string> {\n const imports = new Map<string, string>();\n\n walk(program, (node) => {\n if (node.type !== 'ImportDeclaration') return;\n\n const decl = node as ImportDeclarationNode;\n\n if (decl.importKind === 'type') return;\n\n const specifier = typeof decl.source?.value === 'string' ? decl.source.value : undefined;\n\n if (!specifier) return;\n\n for (const spec of decl.specifiers ?? []) {\n if (spec.importKind === 'type') continue;\n\n if (typeof spec.local?.name === 'string') {\n imports.set(spec.local.name, specifier);\n }\n }\n });\n\n return imports;\n}\n\n/** the root identifier of a JSX tag: `Foo` → Foo, `Ns.Chart` → Ns */\nfunction tagRootIdentifier(name: unknown): string | undefined {\n let current = name;\n\n while (isAstNode(current) && current.type === 'JSXMemberExpression') {\n current = (current as unknown as { object?: unknown }).object;\n }\n\n if (isAstNode(current) && current.type === 'JSXIdentifier') {\n const identifier = current as unknown as { name?: unknown };\n\n return typeof identifier.name === 'string' ? identifier.name : undefined;\n }\n\n return undefined;\n}\n\nfunction hasClientDirective(attributes: unknown): boolean {\n if (!Array.isArray(attributes)) return false;\n\n return attributes.some((attr) => {\n if (!isAstNode(attr) || attr.type !== 'JSXAttribute') return false;\n\n const name = (attr as unknown as { name?: { name?: unknown } | null }).name;\n\n return typeof name?.name === 'string' && name.name.startsWith('client:');\n });\n}\n\n/**\n * Extract the import specifiers of all hydrated (`client:*`) components from\n * raw `.astro` source. Astro components can't hydrate, so `.astro` specifiers\n * are skipped; dynamic tags without a frontmatter import are invisible here.\n */\nexport function scanAstroSource(source: string): string[] {\n const { ast } = parse(source);\n const root = ast as { frontmatter?: { program?: unknown } | null; body?: unknown };\n\n const imports = collectImports(root.frontmatter?.program);\n\n if (imports.size === 0) return [];\n\n const specifiers = new Set<string>();\n\n walk(root.body, (node) => {\n if (node.type !== 'JSXOpeningElement') return;\n\n const element = node as unknown as { attributes?: unknown; name?: unknown };\n\n if (!hasClientDirective(element.attributes)) return;\n\n const rootName = tagRootIdentifier(element.name);\n\n if (!rootName || /^[a-z]/.test(rootName)) return;\n\n const specifier = imports.get(rootName);\n\n if (specifier && !specifier.endsWith('.astro')) {\n specifiers.add(specifier);\n }\n });\n\n return [...specifiers];\n}\n\n/** scan all `.astro` files under `srcDir` for hydrated components */\nexport async function scanProjectIslands(srcDir: string, logger: Logger): Promise<IslandImport[]> {\n const islands: IslandImport[] = [];\n\n let entries: fs.Dirent[];\n\n try {\n entries = await fs.promises.readdir(srcDir, { recursive: true, withFileTypes: true });\n } catch {\n return islands;\n }\n\n const files = entries\n .filter((entry) => entry.isFile() && entry.name.endsWith('.astro'))\n .map((entry) => path.join(entry.parentPath, entry.name));\n\n await Promise.all(\n files.map(async (file) => {\n try {\n const source = await fs.promises.readFile(file, 'utf8');\n\n for (const specifier of scanAstroSource(source)) {\n islands.push({ importer: file, specifier });\n }\n } catch (error) {\n // a file mid-edit or unreadable must not break the dev server\n logger.debug(`island scan skipped ${file}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }),\n );\n\n return islands;\n}\n\nfunction packageNameOf(specifier: string): string {\n const segments = specifier.split('/');\n\n return specifier.startsWith('@') ? segments.slice(0, 2).join('/') : (segments[0] ?? specifier);\n}\n\n/**\n * Bare package specifiers resolvable from the project's `node_modules` — these\n * go into `optimizeDeps.include`. Anything else (relative paths, tsconfig\n * aliases, hoisted workspace deps) is resolved through vite at server start;\n * misclassification is harmless, just slightly later discovery.\n */\nexport function selectBareSpecifiers(islands: IslandImport[], root: string): string[] {\n const bare = new Set<string>();\n\n for (const { specifier } of islands) {\n if (specifier.startsWith('.') || specifier.startsWith('/') || specifier.startsWith('#')) continue;\n\n if (fs.existsSync(path.join(root, 'node_modules', packageNameOf(specifier)))) {\n bare.add(specifier);\n }\n }\n\n return [...bare];\n}\n\nfunction toRequestUrl(id: string, root: string): string {\n const normalized = id.split(path.sep).join('/');\n const normalizedRoot = root.split(path.sep).join('/');\n\n return normalized.startsWith(`${normalizedRoot}/`) ? normalized.slice(normalizedRoot.length) : `/@fs/${normalized}`;\n}\n\nexport interface IslandWarmupOptions {\n root: string;\n srcDir: string;\n logger: Logger;\n}\n\nexport function createIslandWarmup(options: IslandWarmupOptions): Plugin {\n const { root, srcDir, logger } = options;\n\n let islands: IslandImport[] = [];\n\n const warmIslands = async (server: ViteDevServer, batch: IslandImport[], warmed: Set<string>): Promise<void> => {\n const env = server.environments.client;\n\n await Promise.all(\n batch.map(async ({ importer, specifier }) => {\n try {\n // resolving through vite also registers still-unknown bare deps with\n // the optimizer — discovery happens now, not at hydration time\n const resolved = await env.pluginContainer.resolveId(specifier, importer);\n\n if (!resolved || resolved.external) return;\n if (resolved.id.startsWith('\\0') || resolved.id.includes('node_modules')) return;\n if (warmed.has(resolved.id)) return;\n\n warmed.add(resolved.id);\n\n await env.warmupRequest(toRequestUrl(resolved.id, root));\n } catch {\n // warmup is best-effort; a broken component surfaces on request anyway\n }\n }),\n );\n };\n\n return {\n name: '@astroscope/node/island-warmup',\n\n async config() {\n islands = await scanProjectIslands(srcDir, logger);\n\n const include = selectBareSpecifiers(islands, root);\n\n if (islands.length > 0) {\n logger.info(`warming ${islands.length} island(s), pre-optimizing ${include.length} dependenc(ies)`);\n }\n\n return include.length > 0 ? { optimizeDeps: { include } } : undefined;\n },\n\n configureServer(server) {\n const warmed = new Set<string>();\n\n // the plugin container is not initialized until the server starts\n // listening — mirror vite's own warmup timing\n if (server.httpServer) {\n server.httpServer.once('listening', () => void warmIslands(server, islands, warmed));\n } else {\n void warmIslands(server, islands, warmed);\n }\n\n // islands added mid-session get discovered at save time instead of at\n // page load; new bare deps still re-optimize, but before hydration\n const onWatcherEvent = (file: string): void => {\n if (!file.endsWith('.astro') || !file.startsWith(srcDir)) return;\n\n void fs.promises\n .readFile(file, 'utf8')\n .then((source) => {\n const batch = scanAstroSource(source).map((specifier) => ({ importer: file, specifier }));\n\n return warmIslands(server, batch, warmed);\n })\n .catch(() => {});\n };\n\n server.watcher.on('add', onWatcherEvent);\n server.watcher.on('change', onWatcherEvent);\n },\n };\n}\n","export function serializeError(error: unknown): string {\n if (error instanceof Error) {\n return error.stack ?? error.message;\n }\n\n return JSON.stringify(error);\n}\n","import path from 'node:path';\nimport type { ViteDevServer } from 'vite';\nimport { serializeError } from './serialize-error.js';\n\ntype Logger = { info(msg: string): void; error(msg: string): void };\n\nconst FULL_RELOAD_UNKNOWN = '<unknown>';\n\n/**\n * Coordinates dev-server restarts: debounces bursts, chains a follow-up if\n * changes arrive mid-restart (vite's `ssrImport` reads disk at import time,\n * so changes during a restart would otherwise be missed), and logs once per\n * restart with what triggered it.\n *\n * One instance per integration, shared across restart-induced configureServer\n * reruns — chain coordination would be lost if recreated each time.\n */\nexport class RestartScheduler {\n private _inFlight = false;\n private _pending = false;\n private _debounceTimer: ReturnType<typeof setTimeout> | undefined;\n private _pendingBootDeps = new Set<string>();\n private _pendingFullReloads = new Set<string>();\n // set while a restart chain is running. the gate probes it (`isRestartPending`)\n // to short-circuit requests, and awaits it (`waitForRestart`) on readiness.\n private _runPromise: Promise<void> | undefined;\n // set when a restart attempt fails\n private _lastFailure: { message: string } | undefined;\n\n constructor(\n private readonly debounceMs: number,\n private readonly logger: Logger,\n ) {}\n\n // true from the moment a change is queued until the restart completes — covers\n // the debounce window too, so requests don't slip past the gate before _run starts.\n isRestartPending(): boolean {\n return !!this._runPromise || !!this._debounceTimer || !!this._lastFailure;\n }\n\n getLastFailure(): { message: string } | undefined {\n return this._lastFailure;\n }\n\n recordFailure(message: string): void {\n this._lastFailure = { message };\n }\n\n clearFailure(): void {\n this._lastFailure = undefined;\n }\n\n schedule(server: ViteDevServer, changedPath: string): void {\n this._pendingBootDeps.add(changedPath);\n this._scheduleRun(server);\n }\n\n scheduleFullReload(server: ViteDevServer, triggeredBy?: string): void {\n this._pendingFullReloads.add(triggeredBy ?? FULL_RELOAD_UNKNOWN);\n this._scheduleRun(server);\n }\n\n /**\n * Resolves when no restart is running. Loops to handle back-to-back restarts\n * (e.g. one chain ends and a queued debounce timer immediately fires a new\n * one). Never rejects, so a failed restart still releases the gate — caller\n * proceeds against the broken state rather than hanging forever.\n */\n async waitForRestart(): Promise<void> {\n while (this._runPromise) {\n try {\n await this._runPromise;\n } catch {\n // restart failed — release anyway\n }\n }\n }\n\n private _scheduleRun(server: ViteDevServer): void {\n clearTimeout(this._debounceTimer);\n this._debounceTimer = setTimeout(() => {\n this._debounceTimer = undefined;\n void this._run(server);\n }, this.debounceMs);\n }\n\n private async _run(server: ViteDevServer): Promise<void> {\n if (this._inFlight) {\n // loop driving the in-flight restart will pick up the next iteration.\n this._pending = true;\n\n return;\n }\n\n this._inFlight = true;\n\n let resolveRun!: () => void;\n\n this._runPromise = new Promise<void>((resolve) => {\n resolveRun = resolve;\n });\n\n try {\n do {\n this._pending = false;\n\n const bootDeps = [...this._pendingBootDeps].sort();\n const fullReloads = [...this._pendingFullReloads].sort();\n\n this._pendingBootDeps.clear();\n this._pendingFullReloads.clear();\n\n if (bootDeps.length > 0 || fullReloads.length > 0) {\n this.logger.info(this._formatReason(server, bootDeps, fullReloads));\n }\n\n try {\n await server.restart();\n } catch (error) {\n this.logger.error(`error during dev server restart: ${serializeError(error)}`);\n }\n } while (this._pending);\n } finally {\n this._inFlight = false;\n this._runPromise = undefined;\n resolveRun();\n }\n }\n\n private _formatReason(server: ViteDevServer, bootDeps: string[], fullReloads: string[]): string {\n const root = server.config.root;\n const rel = (p: string): string => path.relative(root, p) || p;\n const parts: string[] = [];\n\n if (bootDeps.length === 1) {\n parts.push(`boot dep changed: ${rel(bootDeps[0]!)}`);\n } else if (bootDeps.length > 1) {\n parts.push(`boot deps changed (${bootDeps.length}): ${bootDeps.map(rel).join(', ')}`);\n }\n\n if (fullReloads.length > 0) {\n const named = fullReloads.filter((p) => p !== FULL_RELOAD_UNKNOWN);\n\n if (named.length === 0) {\n parts.push('vite SSR full-reload');\n } else {\n parts.push(`vite SSR full-reload (triggered by ${named.map(rel).join(', ')})`);\n }\n }\n\n return `${parts.join(' + ')} — restarting dev server`;\n }\n}\n","import type { DevEnvironment, ViteDevServer } from 'vite';\n\ntype RunnableEnv = DevEnvironment & { runner: { import: (id: string) => Promise<unknown> } };\n\n/**\n * duck-typed runnable-env check. avoids `isRunnableDevEnvironment` which relies on\n * `instanceof RunnableDevEnvironment` — that breaks when the consumer and vite host\n * resolve to different vite installs (e.g. linked packages outside the workspace).\n */\nfunction isRunnable(env: DevEnvironment | undefined): env is RunnableEnv {\n return (\n !!env &&\n typeof (env as { runner?: unknown }).runner === 'object' &&\n typeof (env as RunnableEnv).runner.import === 'function'\n );\n}\n\n/**\n * resolve a runnable dev environment — prefers `ssr`, falls back to `astro`.\n * astro 6 exposes a separate `astro` environment when `ssr` isn't runnable\n * (see astro/core/constants.ts ASTRO_VITE_ENVIRONMENT_NAMES).\n */\nfunction getRunnableEnv(server: ViteDevServer): RunnableEnv {\n const ssr = server.environments['ssr'];\n\n if (isRunnable(ssr)) return ssr;\n\n const astro = server.environments['astro'];\n\n if (isRunnable(astro)) return astro;\n\n const names = Object.keys(server.environments);\n\n throw new Error(`no runnable dev environment found — available: ${names.join(', ')}`);\n}\n\n/**\n * load a module via the Vite Environment API.\n */\nexport async function ssrImport<T = Record<string, unknown>>(server: ViteDevServer, moduleId: string): Promise<T> {\n return getRunnableEnv(server).runner.import(moduleId) as Promise<T>;\n}\n\n/**\n * return the env whose `hot` channel should receive astro-targeted events.\n * astro listens on the env that backs its middleware runner.\n */\nexport function getAstroHotEnv(server: ViteDevServer): DevEnvironment | undefined {\n const ssr = server.environments['ssr'];\n\n if (isRunnable(ssr)) return ssr;\n\n const astro = server.environments['astro'];\n\n if (isRunnable(astro)) return astro;\n\n return undefined;\n}\n","export const ignoredSuffixes = [\n // type definitions\n '.d.ts',\n '.d.mts',\n '.d.cts',\n // images\n '.png',\n '.jpg',\n '.jpeg',\n '.gif',\n '.svg',\n '.webp',\n '.avif',\n '.ico',\n // fonts\n '.woff',\n '.woff2',\n '.ttf',\n '.otf',\n '.eot',\n // other static assets\n '.pdf',\n '.mp3',\n '.mp4',\n '.webm',\n '.ogg',\n '.wav',\n // data/config that boot typically doesn't import\n '.json',\n '.yaml',\n '.yml',\n '.toml',\n '.md',\n '.mdx',\n '.txt',\n // styles (handled by Vite's CSS HMR)\n '.css',\n '.scss',\n '.sass',\n '.less',\n];\n","import type { EventEmitter } from 'node:events';\nimport { readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { HotPayload, ViteDevServer } from 'vite';\nimport { GEN_HEADER, getCurrentGeneration } from './generation.js';\nimport { ignoredSuffixes } from './ignored.js';\nimport type { RestartScheduler } from './scheduler.js';\nimport { getAstroHotEnv } from './vite-env.js';\n\nconst RESTART_HTML = readFileSync(fileURLToPath(new URL('./restart-page.html', import.meta.url)), 'utf8');\n\nexport function setupBootWatch(server: ViteDevServer, entries: string[], scheduler: RestartScheduler): void {\n const entryFilePaths = entries.map((entry) => path.resolve(server.config.root, entry));\n\n const runnableEnv = getAstroHotEnv(server);\n const bootModuleGraph = runnableEnv?.moduleGraph;\n\n const collectBootDependencies = (): Set<string> => {\n const deps = new Set<string>();\n const seen = new Set<string>();\n\n for (const entryFilePath of entryFilePaths) {\n const entryModules = bootModuleGraph?.getModulesByFile(entryFilePath);\n const entryModule = entryModules ? [...entryModules][0] : undefined;\n\n if (!entryModule) continue;\n\n const visit = (mod: typeof entryModule): void => {\n if (!mod?.file || seen.has(mod.file)) return;\n\n seen.add(mod.file);\n deps.add(mod.file);\n\n for (const imp of mod.importedModules) visit(imp);\n };\n\n visit(entryModule);\n }\n\n return deps;\n };\n\n const shouldIgnore = (filePath: string): boolean => {\n const p = filePath.toLowerCase();\n\n return ignoredSuffixes.some((suffix) => p.endsWith(suffix));\n };\n\n const onWatcherEvent = (changedPath: string): void => {\n if (shouldIgnore(changedPath)) return;\n\n const bootDeps = collectBootDependencies();\n\n if (!bootDeps.has(changedPath)) return;\n\n scheduler.schedule(server, changedPath);\n };\n\n server.watcher.on('change', onWatcherEvent);\n server.watcher.on('add', onWatcherEvent);\n server.watcher.on('unlink', onWatcherEvent);\n\n // ignore full-reloads emitted during server startup (dep optimization, port retries).\n let handleFullReloads = false;\n\n if (server.httpServer) {\n server.httpServer.once('listening', () => {\n handleFullReloads = true;\n });\n } else {\n // middleware mode — no httpServer, enable immediately\n handleFullReloads = true;\n }\n\n // SSR full-reloads come through the runnable env's hot channel and clear\n // its module runner's cache — onStartup needs to run again on a fresh server.\n const outsideEmitter = (runnableEnv?.hot as { api?: { outsideEmitter?: EventEmitter } } | undefined)?.api\n ?.outsideEmitter;\n\n if (outsideEmitter) {\n outsideEmitter.on('send', (payload: HotPayload) => {\n if (!handleFullReloads) return;\n if (payload.type !== 'full-reload') return;\n\n const triggeredBy = 'triggeredBy' in payload ? (payload.triggeredBy as string) : undefined;\n\n scheduler.scheduleFullReload(server, triggeredBy);\n });\n }\n}\n\nconst READINESS_PATH = '/__astroscope_boot_ready';\n\n/**\n * Gate requests: show 503 holding page during restart, readiness probe for the reload.\n */\nexport function installBootGate(\n server: Pick<ViteDevServer, 'middlewares'>,\n scheduler: Pick<RestartScheduler, 'waitForRestart' | 'isRestartPending' | 'getLastFailure'>,\n): void {\n const middlewares = server.middlewares as unknown as {\n stack: { route: string; handle: unknown }[];\n };\n\n // must be `stack.unshift`ed to land before astro's handler\n middlewares.stack.unshift({\n route: '',\n handle: (async (\n req: { url?: string },\n res: {\n writeHead: (status: number, headers: Record<string, string>) => void;\n end: (body?: string) => void;\n headersSent?: boolean;\n },\n next: (err?: unknown) => void,\n ) => {\n // readiness probe: holding page polls this. blocks until no restart is in\n // flight, then 204 on success / 503 + JSON error if last attempt failed.\n if (req.url === READINESS_PATH) {\n await scheduler.waitForRestart();\n\n if (res.headersSent) return;\n\n const failure = scheduler.getLastFailure();\n\n if (failure) {\n res.writeHead(503, { 'cache-control': 'no-store', 'content-type': 'application/json' });\n res.end(JSON.stringify({ error: failure.message }));\n\n return;\n }\n\n res.writeHead(204, { 'cache-control': 'no-store' });\n res.end();\n\n return;\n }\n\n if (isDevInternalPath(req.url)) {\n next();\n\n return;\n }\n\n // respond now; awaiting the restart would let vite destroy the socket mid-response.\n if (scheduler.isRestartPending()) {\n res.writeHead(503, {\n 'content-type': 'text/html; charset=utf-8',\n 'cache-control': 'no-store',\n 'retry-after': '1',\n });\n res.end(RESTART_HTML);\n\n return;\n }\n\n next();\n }) as never,\n });\n}\n\nfunction isDevInternalPath(url: string | undefined): boolean {\n if (!url) return false;\n\n return url.startsWith('/@') || url.startsWith('/__') || url.includes('/node_modules/');\n}\n\n/**\n * Stamp the current generation onto every incoming request so the runtime\n * Astro middleware can later detect whether the request belongs to a previous\n * (now torn-down) generation\n */\nexport function installGenStamp(server: Pick<ViteDevServer, 'middlewares'>): void {\n const middlewares = server.middlewares as unknown as {\n stack: { route: string; handle: unknown }[];\n };\n\n middlewares.stack.unshift({\n route: '',\n handle: ((req: { headers: Record<string, string> }, _res: unknown, next: () => void) => {\n req.headers[GEN_HEADER] = String(getCurrentGeneration());\n next();\n }) as never,\n });\n}\n","import type { AstroConfig } from 'astro';\nimport type { Plugin } from 'vite';\nimport { setBootContext } from '../lifecycle/context.js';\nimport { type BootModule, runShutdown, runStartup } from '../lifecycle/lifecycle.js';\nimport type { BootContext } from '../lifecycle/types.js';\nimport { clearNativeMounts } from '../server/native-mount.js';\nimport { incrementGeneration } from './generation.js';\nimport { RestartScheduler } from './scheduler.js';\nimport { serializeError } from './serialize-error.js';\nimport { ssrImport } from './vite-env.js';\nimport { installBootGate, installGenStamp, setupBootWatch } from './watch.js';\n\ninterface Logger {\n info(msg: string): void;\n warn(msg: string): void;\n error(msg: string): void;\n}\n\nexport interface DevMachineryOptions {\n /** boot file path relative to the project root; undefined = no boot module */\n entry: string | undefined;\n /** restart the dev server when watched dependencies change */\n watch: boolean;\n /** extra files (relative to the root) whose changes restart the dev server */\n watchEntries: string[];\n /** platform seams; runs each generation before the boot module starts */\n prepare: (importModule: <T = Record<string, unknown>>(id: string) => Promise<T>) => Promise<void>;\n logger: Logger;\n getConfig: () => AstroConfig | null;\n}\n\n/**\n * Resolve the default host and port from the Astro server config.\n * Falls back to `localhost:4321` when no config is provided.\n */\nfunction getServerDefaults(config: AstroConfig | null): { host: string; port: number } {\n return {\n host:\n typeof config?.server?.host === 'string'\n ? config.server.host\n : config?.server?.host === true\n ? '0.0.0.0'\n : 'localhost',\n port: config?.server?.port ?? 4321,\n };\n}\n\n/**\n * Build a dev-mode boot context from the running server's address,\n * falling back to Astro config defaults if the server isn't listening yet.\n */\nfunction resolveBootContext(\n server: { httpServer?: { address(): unknown } | null | undefined },\n config: AstroConfig | null,\n): BootContext {\n const addr = server.httpServer?.address();\n\n if (addr && typeof addr === 'object' && 'address' in addr && 'port' in addr) {\n const host =\n (addr as { address: string }).address === '::' || (addr as { address: string }).address === '0.0.0.0'\n ? 'localhost'\n : (addr as { address: string }).address;\n\n return { dev: true, host, port: (addr as { port: number }).port };\n }\n\n const { host, port } = getServerDefaults(config);\n\n return { dev: true, host, port };\n}\n\n/**\n * The dev-mode boot machinery: runs the platform seams and the boot lifecycle\n * per restart generation, restarts the dev server when watched dependencies\n * change, and gates requests behind a holding page during restarts.\n */\nexport function createDevMachinery(options: DevMachineryOptions): Plugin[] {\n const { entry, logger } = options;\n\n let hasStartupSucceededOnce = false;\n // run by the next configureServer before its startup so resources (ports,\n // sockets, locks) from the previous module are released first. idempotent.\n let priorShutdown: (() => Promise<void>) | undefined;\n // shared across restart-induced configureServer reruns\n const scheduler = options.watch ? new RestartScheduler(100, logger) : undefined;\n\n return [\n // gate plugin: enforce 'post' + returned-function so our `stack.unshift`\n // (in installBootGate / installGenStamp) lands at connect position 0,\n // ahead of astro's handler.\n {\n name: '@astroscope/node/dev-gate',\n enforce: 'post',\n\n configureServer(server) {\n if (!scheduler) return;\n\n return () => {\n // gen-stamp is unshifted last so it ends up at position 0:\n // every request gets a generation header before anything else,\n // including the gate's readiness probe.\n installBootGate(server, scheduler);\n installGenStamp(server);\n };\n },\n },\n\n // startup plugin: runs after all other configureServer hooks\n {\n name: '@astroscope/node/dev-startup',\n enforce: 'post',\n\n async configureServer(server) {\n incrementGeneration();\n\n // tear down the previous module first so its resources are released\n // before the new startup tries to claim them.\n if (priorShutdown) {\n await priorShutdown();\n priorShutdown = undefined;\n }\n\n const astroConfig = options.getConfig();\n const bootContext = resolveBootContext(server, astroConfig);\n let bootModule: BootModule | undefined;\n\n setBootContext(bootContext);\n\n try {\n await options.prepare((id) => ssrImport(server, id));\n\n bootModule = entry ? await ssrImport<BootModule>(server, `/${entry}`) : {};\n\n await runStartup(bootModule, bootContext);\n } catch (error) {\n logger.error(`Error running startup script: ${serializeError(error)}`);\n\n if (bootModule) {\n try {\n await runShutdown(bootModule, bootContext);\n } catch {\n // best-effort cleanup\n }\n }\n\n // restart failure: the gate can keep the holding\n // page up with an error message instead of dropping users onto a\n // half-broken old server.\n if (hasStartupSucceededOnce) {\n scheduler?.recordFailure(serializeError(error));\n\n throw error;\n }\n\n // initial failure: exit cleanly (mirrors the production server).\n process.exit(1);\n }\n\n hasStartupSucceededOnce = true;\n scheduler?.clearFailure();\n\n // capture so shutdown sees the same instance that started.\n const startedModule = bootModule;\n let shutdownDone = false;\n\n const shutdown = async (): Promise<void> => {\n if (shutdownDone) return;\n\n shutdownDone = true;\n\n try {\n await runShutdown(startedModule, resolveBootContext(server, options.getConfig()));\n } catch (error) {\n logger.error(`Error running shutdown script: ${serializeError(error)}`);\n }\n\n // the next generation's onStartup re-registers its mounts\n clearNativeMounts();\n };\n\n priorShutdown = shutdown;\n\n // sigint/sigterm path. also fires during restart but shutdown is idempotent.\n server.httpServer?.once('close', () => {\n void shutdown();\n });\n\n if (scheduler) {\n setupBootWatch(server, [...(entry ? [entry] : []), ...options.watchEntries], scheduler);\n }\n },\n },\n ];\n}\n","import type { ExcludePattern } from './excludes.js';\n\n/**\n * Serialize exclude patterns to JavaScript code for use in virtual modules.\n * Handles RegExp objects which JSON.stringify cannot serialize.\n */\nexport function serializeExcludePatterns(patterns: ExcludePattern[]): string {\n return `[${patterns.map((p) => ('pattern' in p ? `{ pattern: ${p.pattern.toString()} }` : JSON.stringify(p))).join(', ')}]`;\n}\n","import type { Plugin } from 'vite';\n\n/**\n * emit sourcemaps only for the SSR build. client bundles are left unmapped\n * so browsers can't fetch source via `//# sourceMappingURL=`.\n *\n * vite 7's `environments.ssr.build.sourcemap` looks cleaner but wholesale\n * replaces astro's SSR build defaults (including entry file naming), which\n * breaks the embedded dev boot machinery. using `isSsrBuild` keeps the\n * rest of astro's SSR config intact.\n */\nexport function ssrSourcemapPlugin(): Plugin {\n return {\n name: '@astroscope/node/tweaks/sourcemap',\n config(_config, { isSsrBuild }) {\n if (isSsrBuild) return { build: { sourcemap: true } };\n\n return {};\n },\n };\n}\n","import { Parser } from 'acorn';\nimport MagicString from 'magic-string';\nimport type { Plugin } from 'vite';\n\nconst HOOK_NAMES = new Set(['useEffect', 'useLayoutEffect', 'useInsertionEffect']);\nconst REACT_SOURCE = /^react(\\/.*)?$/;\nconst TRANSFORMABLE = /\\.(?:[mc]?[jt]sx?)$/;\nconst EMPTY_FN = '(()=>{})';\n\n/**\n * in SSR builds, react effect hooks never execute. emptying their callbacks\n * lets rolldown drop dead branches — including dynamic imports of client-only\n * libs (maplibre-gl, hls.js, etc.) — from the server bundle, which in turn\n * stops nft from tracing them at docker-image time.\n *\n * scope is deliberately narrow: first-party code only (no node_modules), only\n * in the SSR pass, and binding-aware (the React import must resolve to the\n * real react package). raw chunks where bundling has erased the binding are\n * left alone — that's NFT's domain, not ours.\n */\nexport function stripSsrEffectsPlugin(): Plugin {\n return {\n name: '@astroscope/node/tweaks/strip-effects',\n enforce: 'post',\n transform(code, id, options) {\n if (!options?.ssr) return null;\n if (id.includes('/node_modules/')) return null;\n\n const cleanId = id.split('?')[0] ?? id;\n\n if (!TRANSFORMABLE.test(cleanId)) return null;\n if (!code.includes('useEffect') && !code.includes('useLayoutEffect') && !code.includes('useInsertionEffect')) {\n return null;\n }\n\n let ast: any;\n\n try {\n ast = Parser.parse(code, {\n ecmaVersion: 'latest',\n sourceType: 'module',\n allowReturnOutsideFunction: true,\n allowAwaitOutsideFunction: true,\n allowImportExportEverywhere: true,\n allowHashBang: true,\n });\n } catch {\n return null;\n }\n\n const directHooks = new Set<string>();\n const namespaceHooks = new Set<string>();\n\n walk(ast, (node) => {\n if (node.type !== 'ImportDeclaration') return;\n\n const src = node.source?.value;\n\n if (typeof src !== 'string' || !REACT_SOURCE.test(src)) return;\n\n for (const spec of node.specifiers ?? []) {\n if (spec.type === 'ImportSpecifier') {\n const imported = spec.imported?.name ?? spec.imported?.value;\n\n if (HOOK_NAMES.has(imported)) directHooks.add(spec.local.name);\n } else if (spec.type === 'ImportDefaultSpecifier' || spec.type === 'ImportNamespaceSpecifier') {\n namespaceHooks.add(spec.local.name);\n }\n }\n });\n\n if (directHooks.size === 0 && namespaceHooks.size === 0) return null;\n\n const replacements: { start: number; end: number }[] = [];\n\n walk(ast, (node) => {\n if (node.type !== 'CallExpression' || !node.arguments?.length) return;\n\n const callee = node.callee;\n const isDirect = callee.type === 'Identifier' && directHooks.has(callee.name);\n const isMember =\n callee.type === 'MemberExpression' &&\n !callee.computed &&\n callee.object?.type === 'Identifier' &&\n namespaceHooks.has(callee.object.name) &&\n callee.property?.type === 'Identifier' &&\n HOOK_NAMES.has(callee.property.name);\n\n if (!isDirect && !isMember) return;\n\n const arg = node.arguments[0];\n\n replacements.push({ start: arg.start, end: arg.end });\n });\n\n if (replacements.length === 0) return null;\n\n const s = new MagicString(code);\n\n for (const { start, end } of replacements) {\n s.overwrite(start, end, EMPTY_FN);\n }\n\n return { code: s.toString(), map: s.generateMap({ hires: true }) };\n },\n };\n}\n\nfunction walk(node: any, visit: (n: any) => void): void {\n if (!node || typeof node !== 'object') return;\n\n if (typeof node.type === 'string') visit(node);\n\n for (const key of Object.keys(node)) {\n const v = node[key];\n\n if (Array.isArray(v)) for (const item of v) walk(item, visit);\n else if (v && typeof v === 'object') walk(v, visit);\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { AstroConfig, AstroIntegration } from 'astro';\nimport { createIslandWarmup } from '../dev-mode/island-warmup.js';\nimport { createDevMachinery } from '../dev-mode/machinery.js';\nimport { type ExcludePattern, RECOMMENDED_EXCLUDES } from '../excludes/excludes.js';\nimport { serializeExcludePatterns } from '../excludes/serialize.js';\nimport { createRequestInstrumentation } from '../observability/instrument.js';\nimport { preparePlatform } from '../platform/prepare.js';\nimport { dispatchNativeMount } from '../server/native-mount.js';\nimport { ssrSourcemapPlugin } from '../tweaks/sourcemap.js';\nimport { stripSsrEffectsPlugin } from '../tweaks/strip-effects.js';\nimport type { NodeOptions, RuntimeOptions } from '../types.js';\n\nexport const CONFIG_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/config';\nexport const BOOT_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/boot';\nexport const CSRF_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/csrf';\nexport const CONFIG_ENTRY_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/config-entry';\nexport const INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/instrumentation-entry';\nexport const LOG_ENTRY_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/log-entry';\n\nconst RESOLVED_CONFIG_VIRTUAL_MODULE_ID = `\\0${CONFIG_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_BOOT_VIRTUAL_MODULE_ID = `\\0${BOOT_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_CSRF_VIRTUAL_MODULE_ID = `\\0${CSRF_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_CONFIG_ENTRY_VIRTUAL_MODULE_ID = `\\0${CONFIG_ENTRY_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID = `\\0${INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_LOG_ENTRY_VIRTUAL_MODULE_ID = `\\0${LOG_ENTRY_VIRTUAL_MODULE_ID}`;\n\nconst SERVER_ENVIRONMENTS = ['ssr', 'prerender', 'astro'];\nconst DEFAULT_REQUEST_EXCLUDES: ExcludePattern[] = [...RECOMMENDED_EXCLUDES];\n\nfunction resolveHost(host: string | boolean | undefined): string {\n if (typeof host === 'string') return host;\n\n return host === true ? '0.0.0.0' : 'localhost';\n}\n\nfunction resolveBootEntry(root: string, entry: string | undefined): string | undefined {\n if (entry) {\n const abs = path.resolve(root, entry);\n\n if (!fs.existsSync(abs)) {\n throw new Error(`[@astroscope/node] boot entry not found: ${entry}`);\n }\n\n return abs;\n }\n\n for (const candidate of ['src/boot/index.ts', 'src/boot.ts']) {\n const abs = path.resolve(root, candidate);\n\n if (fs.existsSync(abs)) return abs;\n }\n\n return undefined;\n}\n\nfunction resolveSeam(root: string, candidate: string): string | undefined {\n const abs = path.resolve(root, candidate);\n\n return fs.existsSync(abs) ? abs : undefined;\n}\n\n/**\n * Node adapter for Astro with a first-class server entrypoint: the boot\n * lifecycle, module warmup, health probes, request logging and telemetry run\n * as plain code around `server.listen()` instead of being injected into the\n * build output.\n */\nexport default function node(options: NodeOptions = {}): AstroIntegration {\n const bootOptions = options.boot ?? {};\n const healthOptions = options.health ?? {};\n const csrfOptions = options.csrf ?? {};\n const loggingOptions = options.logging ?? {};\n const telemetryOptions = options.telemetry ?? {};\n\n const loggingExclude = loggingOptions ? (loggingOptions.exclude ?? DEFAULT_REQUEST_EXCLUDES) : [];\n const telemetryExclude = telemetryOptions ? (telemetryOptions.exclude ?? DEFAULT_REQUEST_EXCLUDES) : [];\n\n let astroConfig: AstroConfig | null = null;\n let bootEntry: string | undefined;\n let configSeam: string | undefined;\n let instrumentationSeam: string | undefined;\n let logSeam: string | undefined;\n let isDev = false;\n\n return {\n name: '@astroscope/node',\n hooks: {\n 'astro:config:setup': ({ command, config, updateConfig, addMiddleware, logger }) => {\n isDev = command === 'dev';\n\n // route enrichment first so csrf-rejected requests still carry a route\n if (loggingOptions || telemetryOptions) {\n addMiddleware({ order: 'pre', entrypoint: '@astroscope/node/route-middleware' });\n }\n\n if (csrfOptions) {\n addMiddleware({ order: 'pre', entrypoint: '@astroscope/node/csrf-middleware' });\n }\n\n const root = fileURLToPath(config.root);\n const watch = bootOptions === false ? false : (bootOptions.watch ?? true);\n\n bootEntry = bootOptions === false ? undefined : resolveBootEntry(root, bootOptions.entry);\n configSeam = resolveSeam(root, 'src/config.ts');\n instrumentationSeam = resolveSeam(root, 'src/instrumentation.ts');\n logSeam = resolveSeam(root, 'src/log.ts');\n\n const relativeSeam = (abs: string | undefined) =>\n abs ? path.relative(root, abs).split(path.sep).join('/') : undefined;\n\n const devMachinery =\n command === 'dev' && bootOptions !== false\n ? createDevMachinery({\n entry: bootEntry ? path.relative(root, bootEntry) : undefined,\n watch,\n // instrumentation runs once per process — watching it would\n // restart generations that can't re-apply it\n watchEntries: [relativeSeam(configSeam), relativeSeam(logSeam)].filter(\n (entry): entry is string => !!entry,\n ),\n prepare: (importModule) =>\n preparePlatform({\n dev: true,\n telemetry:\n telemetryOptions && telemetryOptions.dev\n ? { prometheus: telemetryOptions.prometheus ?? {} }\n : false,\n seams: {\n ...(configSeam && { config: () => importModule(`/${relativeSeam(configSeam)}`) }),\n ...(instrumentationSeam && {\n instrumentation: () => importModule(`/${relativeSeam(instrumentationSeam)}`),\n }),\n ...(logSeam && { log: () => importModule(`/${relativeSeam(logSeam)}`) }),\n },\n }),\n logger,\n getConfig: () => astroConfig,\n })\n : [];\n\n if (command === 'dev' && bootOptions !== false && watch) {\n // catches errors thrown by stale (post-shutdown) requests so\n // they don't pollute the logs during dev-server restarts.\n addMiddleware({ entrypoint: '@astroscope/node/dev-middleware', order: 'pre' });\n }\n\n const islandWarmup =\n command === 'dev' ? [createIslandWarmup({ root, srcDir: fileURLToPath(config.srcDir), logger })] : [];\n\n updateConfig({\n build: { redirects: false },\n // opinionated defaults: no trailing slashes, behind LB\n ...(config.trailingSlash === 'ignore' && { trailingSlash: 'never' as const }),\n security: {\n // assumed to run behind LB\n ...(!config.security.allowedDomains?.length && { allowedDomains: [{}] }),\n // the embedded csrf middleware replaces the built-in origin check\n ...(csrfOptions && { checkOrigin: false }),\n },\n image: {\n endpoint: {\n route: config.image.endpoint.route ?? '_image',\n entrypoint:\n config.image.endpoint.entrypoint ??\n (command === 'dev' ? 'astro/assets/endpoint/dev' : 'astro/assets/endpoint/node'),\n },\n },\n vite: {\n plugins: [\n ...devMachinery,\n ...islandWarmup,\n ssrSourcemapPlugin(),\n stripSsrEffectsPlugin(),\n {\n name: '@astroscope/node',\n\n configEnvironment(environmentName: string) {\n if (SERVER_ENVIRONMENTS.includes(environmentName)) {\n return { resolve: { noExternal: ['@astroscope/node'] } };\n }\n },\n\n resolveId(id: string) {\n if (id === CONFIG_VIRTUAL_MODULE_ID) return RESOLVED_CONFIG_VIRTUAL_MODULE_ID;\n if (id === BOOT_VIRTUAL_MODULE_ID) return RESOLVED_BOOT_VIRTUAL_MODULE_ID;\n if (id === CSRF_VIRTUAL_MODULE_ID) return RESOLVED_CSRF_VIRTUAL_MODULE_ID;\n if (id === CONFIG_ENTRY_VIRTUAL_MODULE_ID) return RESOLVED_CONFIG_ENTRY_VIRTUAL_MODULE_ID;\n if (id === INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID) {\n return RESOLVED_INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID;\n }\n if (id === LOG_ENTRY_VIRTUAL_MODULE_ID) return RESOLVED_LOG_ENTRY_VIRTUAL_MODULE_ID;\n },\n\n load(id: string) {\n if (id === RESOLVED_CONFIG_VIRTUAL_MODULE_ID) {\n if (!astroConfig) throw new Error('[@astroscope/node] astro config not resolved yet');\n\n const runtimeOptions: Omit<RuntimeOptions, 'logging' | 'telemetry'> = {\n host: resolveHost(astroConfig.server.host),\n port: astroConfig.server.port ?? 4321,\n client: astroConfig.build.client.toString(),\n server: astroConfig.build.server.toString(),\n bodySizeLimit: options.bodySizeLimit ?? 1024 * 1024 * 1024,\n shutdownTimeout: options.shutdownTimeout ?? 10_000,\n health: healthOptions\n ? {\n ...(healthOptions.host !== undefined && { host: healthOptions.host }),\n ...(healthOptions.port !== undefined && { port: healthOptions.port }),\n ...(healthOptions.paths && { paths: healthOptions.paths }),\n }\n : false,\n };\n\n // exclude patterns may contain RegExp — serialized as code, not JSON\n const logging = loggingOptions\n ? `{ exclude: ${serializeExcludePatterns(loggingExclude)}, extended: ${JSON.stringify(\n loggingOptions.extended ?? false,\n )} }`\n : 'false';\n const telemetry = telemetryOptions\n ? `{ exclude: ${serializeExcludePatterns(telemetryExclude)}, prometheus: ${JSON.stringify(\n telemetryOptions.prometheus ?? {},\n )} }`\n : 'false';\n\n return `export const options = { ...${JSON.stringify(runtimeOptions)}, logging: ${logging}, telemetry: ${telemetry} };`;\n }\n\n if (id === RESOLVED_BOOT_VIRTUAL_MODULE_ID) {\n // re-export to avoid absolute path manifest leaks\n return bootEntry ? `export * from ${JSON.stringify(bootEntry)};` : 'export {};';\n }\n\n if (id === RESOLVED_CSRF_VIRTUAL_MODULE_ID) {\n return `export const excludePatterns = ${serializeExcludePatterns(csrfOptions ? (csrfOptions.exclude ?? []) : [])};`;\n }\n\n if (id === RESOLVED_CONFIG_ENTRY_VIRTUAL_MODULE_ID) {\n // side-effect import: @entwico/zod-conf validation runs at module load\n return configSeam ? `import ${JSON.stringify(configSeam)};\\nexport {};` : 'export {};';\n }\n\n if (id === RESOLVED_INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID) {\n return instrumentationSeam ? `export * from ${JSON.stringify(instrumentationSeam)};` : 'export {};';\n }\n\n if (id === RESOLVED_LOG_ENTRY_VIRTUAL_MODULE_ID) {\n return logSeam\n ? `export { default } from ${JSON.stringify(logSeam)};`\n : 'export default undefined;';\n }\n },\n },\n ],\n },\n });\n },\n 'astro:server:setup': ({ server }) => {\n if (!isDev) return;\n\n const devLogging = loggingOptions && loggingOptions.dev;\n const devTelemetry = telemetryOptions && telemetryOptions.dev;\n\n const instrument =\n devLogging || devTelemetry\n ? createRequestInstrumentation({\n logging: devLogging ? { exclude: loggingExclude, extended: loggingOptions.extended ?? false } : false,\n telemetry: devTelemetry ? { exclude: telemetryExclude } : false,\n })\n : undefined;\n\n server.middlewares.use((req, res, next) => {\n const inner = (): void => {\n if (!dispatchNativeMount(req, res)) next();\n };\n\n if (instrument) {\n instrument(req, res, inner);\n } else {\n inner();\n }\n });\n },\n 'astro:config:done': ({ config, setAdapter }) => {\n astroConfig = config;\n\n setAdapter({\n name: '@astroscope/node',\n entrypointResolution: 'auto',\n serverEntrypoint: '@astroscope/node/server',\n previewEntrypoint: '@astroscope/node/preview',\n adapterFeatures: {\n buildOutput: 'server',\n middlewareMode: 'classic',\n },\n supportedAstroFeatures: {\n hybridOutput: 'stable',\n staticOutput: 'stable',\n serverOutput: 'stable',\n sharpImageService: 'stable',\n i18nDomains: 'experimental',\n envGetSecret: 'stable',\n },\n });\n },\n 'astro:build:done': async ({ logger }) => {\n if (!astroConfig) return;\n\n const { compressClientDir } = await import('../compress/compress.js');\n\n await compressClientDir(fileURLToPath(astroConfig.build.client), logger);\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AAmCA,SAAS,UAAU,OAAkC;CACnD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAQ,MAAkB,SAAS;AAC3F;AAEA,SAASA,OAAK,MAAe,OAAsC;CACjE,IAAI,MAAM,QAAQ,IAAI,GAAG;EACvB,KAAK,MAAM,QAAQ,MAAM,OAAK,MAAM,KAAK;EAEzC;CACF;CAEA,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM;CAE/C,IAAI,UAAU,IAAI,GAAG,MAAM,IAAI;CAE/B,KAAK,MAAM,SAAS,OAAO,OAAO,IAAI,GAAG,OAAK,OAAO,KAAK;AAC5D;;AASA,SAAS,eAAe,SAAuC;CAC7D,MAAM,0BAAU,IAAI,IAAoB;CAExC,OAAK,UAAU,SAAS;EACtB,IAAI,KAAK,SAAS,qBAAqB;EAEvC,MAA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QAGzF,IAAI,OAAO,sCACT,OAAO,UACH,2BAA2B,KAAK,UAAU,OAAO,EAAE,KACnD;OAER;MACF;KACF,EACF;IACF,CAAC;GACH;GACA,uBAAuB,EAAE,aAAa;IACpC,IAAI,CAAC,OAAO;IAEZ,MAAM,aAAa,kBAAkB,eAAe;IACpD,MAAM,eAAe,oBAAoB,iBAAiB;IAE1D,MAAM,aACJ,cAAc,eACV,6BAA6B;KAC3B,SAAS,aAAa;MAAE,SAAS;MAAgB,UAAU,eAAe,YAAY;KAAM,IAAI;KAChG,WAAW,eAAe,EAAE,SAAS,iBAAiB,IAAI;IAC5D,CAAC,IACD,KAAA;IAEN,OAAO,YAAY,KAAK,KAAK,KAAK,SAAS;KACzC,MAAM,cAAoB;MACxB,IAAI,CAAC,oBAAoB,KAAK,GAAG,GAAG,KAAK;KAC3C;KAEA,IAAI,YACF,WAAW,KAAK,KAAK,KAAK;UAE1B,MAAM;IAEV,CAAC;GACH;GACA,sBAAsB,EAAE,QAAQ,iBAAiB;IAC/C,cAAc;IAEd,WAAW;KACT,MAAM;KACN,sBAAsB;KACtB,kBAAkB;KAClB,mBAAmB;KACnB,iBAAiB;MACf,aAAa;MACb,gBAAgB;KAClB;KACA,wBAAwB;MACtB,cAAc;MACd,cAAc;MACd,cAAc;MACd,mBAAmB;MACnB,aAAa;MACb,cAAc;KAChB;IACF,CAAC;GACH;GACA,oBAAoB,OAAO,EAAE,aAAa;IACxC,IAAI,CAAC,aAAa;IAElB,MAAM,EAAE,sBAAsB,MAAM,OAAO;IAE3C,MAAM,kBAAkB,cAAc,YAAY,MAAM,MAAM,GAAG,MAAM;GACzE;EACF;CACF;AACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as on, i as off, n as BootEventName, r as emit, t as BootEventHandler } from "../events-
|
|
1
|
+
import { a as on, i as off, n as BootEventName, r as emit, t as BootEventHandler } from "../events-u7J3ezJR.js";
|
|
2
2
|
export { BootEventHandler, BootEventName, emit, off, on };
|
package/dist/log/index.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { t as LoggerOptionsFactory } from "../construct-
|
|
1
|
+
import { t as LoggerOptionsFactory } from "../construct-BGlPfWMF.js";
|
|
2
2
|
import { Bindings, Bindings as Bindings$1, Logger, Logger as Logger$1, LoggerOptions } from "pino";
|
|
3
|
-
|
|
4
3
|
//#region src/observability/request-route.d.ts
|
|
5
4
|
/**
|
|
6
5
|
* Report the route that actually served the current request, overriding the one
|
package/dist/log/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/observability/request-route.ts","../../src/observability/log/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/observability/request-route.ts","../../src/observability/log/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+DgB,qBAAqB;;;;;;;iBC5CrB;;;;UAiBC;;WAEN,OAAO;;WAEP,OAAO;;WAEP,MAAM;;WAEN,MAAM;;WAEN,OAAO;;WAEP,OAAO;;EAEhB,MAAM,UAAU,aAAW;;WAElB,KAAK;;WAEL,MAAM;;;;;;;;;;;;;;;;;;;;;cAgGJ,KAAK"}
|
package/dist/native.d.ts
CHANGED
package/dist/native.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"native.d.ts","names":[],"sources":["../src/server/native-mount.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"native.d.ts","names":[],"sources":["../src/server/native-mount.ts"],"mappings":";;KAgBY,iBAAiB,KAAK,iBAAiB,KAAK,0BAA0B;UAEjE;;EAEf;;EAGA,UAAU,KAAK;;EAGf;;;;;;;;;;;;;;;;;;;;;;;;iBAwDc,mBAAmB,SAAS,oBAAoB,SAAS;;;;;iBA2BzD;;;;;iBAsCA,oBAAoB,KAAK,iBAAiB,KAAK"}
|
package/dist/preview.d.ts
CHANGED
package/dist/preview.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preview.d.ts","names":[],"sources":["../src/server/preview.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"preview.d.ts","names":[],"sources":["../src/server/preview.ts"],"mappings":";;;;;;;cAQM,qBAAqB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-middleware-entrypoint.d.ts","names":[],"sources":["../src/observability/route-middleware-entrypoint.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"route-middleware-entrypoint.d.ts","names":[],"sources":["../src/observability/route-middleware-entrypoint.ts"],"mappings":";;;;;;;;;;cAWa,WAAW"}
|
package/dist/server.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","names":[],"sources":["../src/server/server.ts"],"mappings":";
|
|
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"}
|
package/dist/server.js
CHANGED
|
@@ -279,8 +279,10 @@ async function warmupModules() {
|
|
|
279
279
|
app.manifest.sessionDriver,
|
|
280
280
|
app.manifest.serverIslandMappings
|
|
281
281
|
].filter((load) => load !== void 0);
|
|
282
|
-
const
|
|
283
|
-
|
|
282
|
+
const failures = (await Promise.allSettled(loaders.map((load) => load()))).filter((result) => result.status === "rejected");
|
|
283
|
+
if (failures.length === 0) return;
|
|
284
|
+
for (const failure of failures) log.error(failure.reason instanceof Error ? { err: failure.reason } : { reason: failure.reason }, "warmup import failed");
|
|
285
|
+
throw new AggregateError(failures.map((failure) => failure.reason), "warmup import failed");
|
|
284
286
|
}
|
|
285
287
|
/**
|
|
286
288
|
* TLS tokens from `SERVER_CERT_PATH` / `SERVER_KEY_PATH` (same contract as
|
|
@@ -344,6 +346,14 @@ async function startServer(overrides) {
|
|
|
344
346
|
const warmup = warmupModules().then(() => {
|
|
345
347
|
warmupMs = roundMs(performance.now() - warmupStartedAt);
|
|
346
348
|
warmupSpan.span.end();
|
|
349
|
+
}, (error) => {
|
|
350
|
+
warmupMs = roundMs(performance.now() - warmupStartedAt);
|
|
351
|
+
warmupSpan.span.setStatus({
|
|
352
|
+
code: SpanStatusCode.ERROR,
|
|
353
|
+
message: "warmup import failed"
|
|
354
|
+
});
|
|
355
|
+
warmupSpan.span.end();
|
|
356
|
+
return error;
|
|
347
357
|
});
|
|
348
358
|
const shutdownLifecycle = async (shutdownContext) => {
|
|
349
359
|
try {
|
|
@@ -355,7 +365,11 @@ async function startServer(overrides) {
|
|
|
355
365
|
clearNativeMounts();
|
|
356
366
|
if (health) {
|
|
357
367
|
deactivateHealthChecks();
|
|
358
|
-
|
|
368
|
+
try {
|
|
369
|
+
await server.stop();
|
|
370
|
+
} catch (err) {
|
|
371
|
+
log.debug(err instanceof Error ? { err } : { reason: err }, "health probe server stop failed");
|
|
372
|
+
}
|
|
359
373
|
}
|
|
360
374
|
};
|
|
361
375
|
const failStartup = async (err, message) => {
|
|
@@ -377,7 +391,8 @@ async function startServer(overrides) {
|
|
|
377
391
|
} catch (err) {
|
|
378
392
|
await failStartup(err, "startup failed");
|
|
379
393
|
}
|
|
380
|
-
await warmup;
|
|
394
|
+
const warmupError = await warmup;
|
|
395
|
+
if (warmupError !== void 0) await failStartup(warmupError, "warmup import failed");
|
|
381
396
|
if (health) probes.startup.enable();
|
|
382
397
|
const client = resolveClientDir(runtimeOptions, import.meta.url);
|
|
383
398
|
const appHandler = createAppHandler(app, runtimeOptions, client);
|
package/dist/server.js.map
CHANGED
|
@@ -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';\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\n const response =\n routeData && !(routeData.type === 'page' && routeData.prerender)\n ? await app.render(request, { addCookieHeader: true, routeData, 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\n for (const result of results) {\n if (result.status === 'rejected') {\n log.error(\n result.reason instanceof Error ? { err: result.reason } : { reason: result.reason },\n 'warmup import failed',\n );\n }\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\n const warmupStartedAt = performance.now();\n const warmupSpan = startLifecycleSpan('warmup', startup.context);\n const warmup = warmupModules().then(() => {\n warmupMs = roundMs(performance.now() - warmupStartedAt);\n warmupSpan.span.end();\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 await healthServer.stop();\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 await warmup;\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;AAC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A2B;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/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';\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\n const response =\n routeData && !(routeData.type === 'page' && routeData.prerender)\n ? await app.render(request, { addCookieHeader: true, routeData, 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,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AEN,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types-D0uMBi2M.d.ts","names":[],"sources":["../src/lifecycle/types.ts"],"mappings":";UAAiB
|
|
1
|
+
{"version":3,"file":"types-D0uMBi2M.d.ts","names":[],"sources":["../src/lifecycle/types.ts"],"mappings":";UAAiB;;EAEf;;EAEA;;EAEA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astroscope/node",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "Opinionated, cloud-friendly Node adapter for Astro: boot lifecycle, health probes, request logging, telemetry, CSRF and static serving run as plain code around server.listen()",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -82,14 +82,15 @@
|
|
|
82
82
|
},
|
|
83
83
|
"homepage": "https://github.com/entwico/astroscope/tree/main/packages/node#readme",
|
|
84
84
|
"dependencies": {
|
|
85
|
-
"@
|
|
86
|
-
"@entwico/
|
|
85
|
+
"@astrojs/compiler-rs": "^0.3.1",
|
|
86
|
+
"@entwico/dash": "^1.3.0",
|
|
87
|
+
"@entwico/health-probes": "^1.1.2",
|
|
87
88
|
"@opentelemetry/api": "^1.9.1",
|
|
88
|
-
"@opentelemetry/exporter-prometheus": "^0.
|
|
89
|
+
"@opentelemetry/exporter-prometheus": "^0.220.0",
|
|
89
90
|
"@opentelemetry/host-metrics": "^0.39.0",
|
|
90
91
|
"@opentelemetry/instrumentation-runtime-node": "^0.33.0",
|
|
91
92
|
"@opentelemetry/instrumentation-undici": "^0.30.0",
|
|
92
|
-
"@opentelemetry/sdk-node": "^0.
|
|
93
|
+
"@opentelemetry/sdk-node": "^0.220.0",
|
|
93
94
|
"acorn": "^8.17.0",
|
|
94
95
|
"magic-string": "^0.30.21",
|
|
95
96
|
"pino": "^10.3.1",
|
|
@@ -97,8 +98,8 @@
|
|
|
97
98
|
},
|
|
98
99
|
"devDependencies": {
|
|
99
100
|
"@types/send": "^1.2.1",
|
|
100
|
-
"astro": "^7.0.
|
|
101
|
-
"tsdown": "^0.22.
|
|
101
|
+
"astro": "^7.0.9",
|
|
102
|
+
"tsdown": "^0.22.8",
|
|
102
103
|
"typescript": "^6.0.3"
|
|
103
104
|
},
|
|
104
105
|
"peerDependencies": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"construct-DgB-jR0a.d.ts","names":[],"sources":["../src/observability/log/construct.ts"],"mappings":";;;;;AASA;;;KAAY,oBAAA,GAAuB,aAAA,KAAkB,GAAA;EAAO,GAAA;AAAA,MAAmB,aAAA,GAAgB,OAAA,CAAQ,aAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"events-CUzQ2_cp.d.ts","names":[],"sources":["../src/lifecycle/events.ts"],"mappings":";;;KAEY,aAAA;AAAA,KAEA,gBAAA,IAAoB,OAAA,EAAS,WAAA,KAAgB,OAAO;AAFhE;;;AAAA,iBAyBgB,EAAA,CAAG,KAAA,EAAO,aAAA,EAAe,OAAA,EAAS,gBAAgB;AAzBzC;AAEzB;;AAFyB,iBAwCT,GAAA,CAAI,KAAA,EAAO,aAAA,EAAe,OAAA,EAAS,gBAAgB;;;;iBAS7C,IAAA,CAAK,KAAA,EAAO,aAAA,EAAe,OAAA,EAAS,WAAA,GAAc,OAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"excludes-DLF3A_Cf.d.ts","names":[],"sources":["../src/excludes/excludes.ts"],"mappings":";;;;;;AAQA;;;KAAY,cAAA,GAAiB,OAAO,CAAC,aAAA,GAAgB,KAAA;;;;cAKxC,YAAA,EAAc,cAAc;AALyB;AAKlE;;AALkE,cAgBrD,qBAAA,EAAuB,cAAc;;AAXT;AAWzC;cAKa,eAAA,EAAiB,cAAc;;;AALM;AAKlD;;;;AAA4C;AAwB5C;;;;AAAiD;AAKjD;;cALa,oBAAA,EAAsB,cAAc;;;;iBAKjC,aAAA,CACd,GAAA,EAAK,UAAA,EACL,OAAA,WAAkB,aAAA,OAAoB,OAAA,EAAS,UAAA;;;;;;;;;AAAmC;AA4BpF;;;;;;;;iBAAgB,YAAA,CACd,UAAA,EAAY,iBAAA,EACZ,OAAA,WAAkB,aAAA,OAAoB,OAAA,EAAS,UAAA,gBAC9C,iBAAA"}
|