@astroscope/wormhole 3.0.1 → 3.0.2
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/dist/{als-CntRqWdO.js → als-D5JKSoMf.js} +2 -3
- package/dist/{als-CntRqWdO.js.map → als-D5JKSoMf.js.map} +1 -1
- package/dist/{define-DAoqsUVA.js → define-DO3-gETv.js} +4 -5
- package/dist/{define-DAoqsUVA.js.map → define-DO3-gETv.js.map} +1 -1
- package/dist/index.browser.d.ts +1 -3
- package/dist/index.browser.d.ts.map +1 -1
- package/dist/index.browser.js +2 -3
- package/dist/index.d.ts +1 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -10
- package/dist/index.js.map +1 -1
- package/dist/{key-BqTy1gM3.js → key-DeXuVpLB.js} +2 -3
- package/dist/{key-BqTy1gM3.js.map → key-DeXuVpLB.js.map} +1 -1
- package/dist/middleware-entrypoint.d.ts +0 -2
- package/dist/middleware-entrypoint.d.ts.map +1 -1
- package/dist/middleware-entrypoint.js +10 -18
- package/dist/middleware-entrypoint.js.map +1 -1
- package/dist/react/index.d.ts +1 -3
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +1 -2
- package/dist/{scan-BDYo2M_0.js → scan-CpLDPkMX.js} +2 -3
- package/dist/{scan-BDYo2M_0.js.map → scan-CpLDPkMX.js.map} +1 -1
- package/dist/server.d.ts +2 -3
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +2 -3
- package/dist/{types-v_ftArqH.d.ts → types-TzBj9lJt.d.ts} +1 -3
- package/dist/types-TzBj9lJt.d.ts.map +1 -0
- package/package.json +10 -10
- package/dist/types-v_ftArqH.d.ts.map +0 -1
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
-
|
|
2
|
+
// src/als.ts
|
|
3
3
|
const als = globalThis[Symbol.for("@astroscope/wormhole/als")] ??= new AsyncLocalStorage();
|
|
4
|
-
//#endregion
|
|
5
4
|
export { als as t };
|
|
6
5
|
|
|
7
|
-
//# sourceMappingURL=als-
|
|
6
|
+
//# sourceMappingURL=als-D5JKSoMf.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"als-
|
|
1
|
+
{"version":3,"file":"als-D5JKSoMf.js","names":[],"sources":["../src/als.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\n\n// a single ALS holds an immutable map of all open wormholes (keyed by wormhole key);\n// keyed on globalThis so the vite-runner and native module instances share one context\n// eslint-disable-next-line unicorn/no-global-object-property-assignment -- `Symbol.for` slot on globalThis, shared by the vite-runner and native module instances\nexport const als: AsyncLocalStorage<ReadonlyMap<string, unknown>> = ((globalThis as any)[\n Symbol.for('@astroscope/wormhole/als')\n] ??= new AsyncLocalStorage());\n"],"mappings":";;AAKA,MAAa,MAAwD,WACnE,OAAO,IAAI,0BAA0B,OACjC,IAAI,kBAAkB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as als } from "./als-
|
|
2
|
-
import { t as wormholeKey } from "./key-
|
|
3
|
-
|
|
1
|
+
import { t as als } from "./als-D5JKSoMf.js";
|
|
2
|
+
import { t as wormholeKey } from "./key-DeXuVpLB.js";
|
|
3
|
+
// src/define.ts
|
|
4
4
|
const ASSIGN = Symbol.for("@astroscope/wormhole.assign");
|
|
5
5
|
const SOURCE = Symbol.for("@astroscope/wormhole.source");
|
|
6
6
|
/**
|
|
@@ -77,7 +77,6 @@ function assignWormholeNames(registry) {
|
|
|
77
77
|
assign(name);
|
|
78
78
|
}
|
|
79
79
|
}
|
|
80
|
-
//#endregion
|
|
81
80
|
export { getWormholeSource as i, createWormhole as n, defineWormhole as r, assignWormholeNames as t };
|
|
82
81
|
|
|
83
|
-
//# sourceMappingURL=define-
|
|
82
|
+
//# sourceMappingURL=define-DO3-gETv.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define-
|
|
1
|
+
{"version":3,"file":"define-DO3-gETv.js","names":[],"sources":["../src/define.ts"],"sourcesContent":["import type { ReadonlyDeep } from '@entwico/dash';\nimport { als } from './als.js';\nimport { wormholeKey } from './key.js';\nimport type { Wormhole, WormholeDefinition, WormholeHandler } from './types.js';\n\n// name assignment and the handler must survive dual module instances (vite runner +\n// native), so both ride the wormhole object itself under Symbol.for keys\nconst ASSIGN = Symbol.for('@astroscope/wormhole.assign');\nconst SOURCE = Symbol.for('@astroscope/wormhole.source');\n\n/** how the middleware opens a wormhole: its handler and whether every route loads it */\nexport type WormholeSource = { handler: WormholeHandler<unknown>; eager: boolean };\n\ntype Internal = Wormhole<unknown> & { [ASSIGN](next: string): void; [SOURCE]?: WormholeSource | undefined };\n\n/**\n * Define a wormhole for the `src/wormholes.ts` registry, actions-style. The\n * handler resolves the value per request; the middleware calls it only for routes\n * the build found a reader on (frontmatter, islands, scripts) — or on every\n * request with `eager: true`. The wormhole's name is the registry key, assigned\n * when the registry is passed to `createWormholeMiddleware()` (or\n * `assignWormholeNames()`).\n *\n * **Security:** wormhole data is serialized into the HTML and sent to the browser.\n * Never store secrets (tokens, API keys, credentials) in a wormhole.\n *\n * @example\n * ```typescript\n * export const wormholes = {\n * cart: defineWormhole({ handler: (ctx) => ctx.locals.cart }),\n * config: defineWormhole({ handler: () => loadConfig(), eager: true }),\n * };\n * ```\n */\nexport function defineWormhole<T>(definition: WormholeDefinition<T>): Wormhole<T> {\n const wormhole = createWormhole() as Internal;\n\n wormhole[SOURCE] = { handler: definition.handler as WormholeHandler<unknown>, eager: definition.eager ?? false };\n\n return wormhole as Wormhole<T>;\n}\n\n/** the server-side wormhole object without a handler — the `wormholes` proxy stubs (internal) */\nexport function createWormhole<T>(): Wormhole<T> {\n let name: string | undefined;\n\n const requireName = (): string => {\n if (name === undefined) {\n throw new Error('wormhole is not registered — pass its registry to createWormholeMiddleware()');\n }\n\n return name;\n };\n\n const key = (): string => wormholeKey(requireName());\n\n // methods must not rely on `this` — consumers pass them around detached\n // (e.g. useSyncExternalStore(wormhole.subscribe, wormhole.get, wormhole.get))\n const wormhole: Wormhole<T> & { [ASSIGN](next: string): void } = {\n get name() {\n return requireName();\n },\n\n get key() {\n return key();\n },\n\n get(): ReadonlyDeep<T> {\n const value = als.getStore()?.get(key());\n\n if (value === undefined) {\n throw new Error(\n `wormhole \"${requireName()}\" is not open for this request — is it provided by the wormhole middleware?`,\n );\n }\n\n return value as ReadonlyDeep<T>;\n },\n\n set(): void {\n throw new Error(\n `wormhole \"${requireName()}\" set() cannot be called on the server — values are request-scoped and provided by the middleware`,\n );\n },\n\n subscribe(): () => void {\n // server values never change within a request — nothing to notify\n return () => {};\n },\n\n [ASSIGN](next: string): void {\n if (name !== undefined && name !== next) {\n throw new Error(`wormhole is registered under two names: \"${name}\" and \"${next}\"`);\n }\n\n name = next;\n },\n };\n\n return wormhole;\n}\n\n/** the definition a registry entry was created with — undefined for proxy stubs */\nexport function getWormholeSource<T>(wormhole: Wormhole<T>): WormholeSource | undefined {\n return (wormhole as unknown as Internal)[SOURCE];\n}\n\n/**\n * Assign each wormhole its registry key as name. Called by `createWormholeMiddleware()`;\n * exposed for setups that read wormholes on the server without the middleware.\n */\nexport function assignWormholeNames(registry: Record<string, object>): void {\n for (const [name, wormhole] of Object.entries(registry)) {\n const assign = (wormhole as { [ASSIGN]?: (next: string) => void })[ASSIGN];\n\n if (typeof assign !== 'function') {\n throw new TypeError(\n `registry entry \"${name}\" is not a wormhole — the registry must contain defineWormhole() values only`,\n );\n }\n\n assign(name);\n }\n}\n"],"mappings":";;;AAOA,MAAM,SAAS,OAAO,IAAI,6BAA6B;AACvD,MAAM,SAAS,OAAO,IAAI,6BAA6B;;;;;;;;;;;;;;;;;;;;AA0BvD,SAAgB,eAAkB,YAAgD;CAChF,MAAM,WAAW,eAAe;CAEhC,SAAS,UAAU;EAAE,SAAS,WAAW;EAAqC,OAAO,WAAW,SAAS;CAAM;CAE/G,OAAO;AACT;;AAGA,SAAgB,iBAAiC;CAC/C,IAAI;CAEJ,MAAM,oBAA4B;EAChC,IAAI,SAAS,KAAA,GACX,MAAM,IAAI,MAAM,8EAA8E;EAGhG,OAAO;CACT;CAEA,MAAM,YAAoB,YAAY,YAAY,CAAC;CA6CnD,OAAO;EAxCL,IAAI,OAAO;GACT,OAAO,YAAY;EACrB;EAEA,IAAI,MAAM;GACR,OAAO,IAAI;EACb;EAEA,MAAuB;GACrB,MAAM,QAAQ,IAAI,SAAS,CAAC,EAAE,IAAI,IAAI,CAAC;GAEvC,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MACR,aAAa,YAAY,EAAE,4EAC7B;GAGF,OAAO;EACT;EAEA,MAAY;GACV,MAAM,IAAI,MACR,aAAa,YAAY,EAAE,kGAC7B;EACF;EAEA,YAAwB;GAEtB,aAAa,CAAC;EAChB;EAEA,CAAC,QAAQ,MAAoB;GAC3B,IAAI,SAAS,KAAA,KAAa,SAAS,MACjC,MAAM,IAAI,MAAM,4CAA4C,KAAK,SAAS,KAAK,EAAE;GAGnF,OAAO;EACT;CAGY;AAChB;;AAGA,SAAgB,kBAAqB,UAAmD;CACtF,OAAQ,SAAiC;AAC3C;;;;;AAMA,SAAgB,oBAAoB,UAAwC;CAC1E,KAAK,MAAM,CAAC,MAAM,aAAa,OAAO,QAAQ,QAAQ,GAAG;EACvD,MAAM,SAAU,SAAmD;EAEnE,IAAI,OAAO,WAAW,YACpB,MAAM,IAAI,UACR,mBAAmB,KAAK,6EAC1B;EAGF,OAAO,IAAI;CACb;AACF"}
|
package/dist/index.browser.d.ts
CHANGED
|
@@ -1,9 +1,7 @@
|
|
|
1
|
-
import { a as WormholeMap, i as WormholeHandler, n as Wormhole, o as WormholeRegistry, r as WormholeDefinition, t as UnwrapWormholes } from "./types-
|
|
2
|
-
//#region src/index.browser.d.ts
|
|
1
|
+
import { a as WormholeMap, i as WormholeHandler, n as Wormhole, o as WormholeRegistry, r as WormholeDefinition, t as UnwrapWormholes } from "./types-TzBj9lJt.js";
|
|
3
2
|
export declare const wormholes: WormholeMap;
|
|
4
3
|
export declare function defineWormhole(): never;
|
|
5
4
|
export declare function assignWormholeNames(): never;
|
|
6
5
|
export default function wormholeIntegration(): never;
|
|
7
|
-
//#endregion
|
|
8
6
|
export type { UnwrapWormholes, Wormhole, WormholeDefinition, WormholeHandler, WormholeMap, WormholeRegistry };
|
|
9
7
|
//# sourceMappingURL=index.browser.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.browser.d.ts","names":[],"sources":["../src/index.browser.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.browser.d.ts","names":[],"sources":["../src/index.browser.ts"],"mappings":";qBA0Ea,WAAW;wBAMR;wBAMA;wBAIQ"}
|
package/dist/index.browser.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as wormholeKey } from "./key-
|
|
2
|
-
|
|
1
|
+
import { t as wormholeKey } from "./key-DeXuVpLB.js";
|
|
2
|
+
// src/index.browser.ts
|
|
3
3
|
const store = globalThis.__wormholes__ ??= {};
|
|
4
4
|
const stubs = /* @__PURE__ */ new Map();
|
|
5
5
|
function stub(name) {
|
|
@@ -42,7 +42,6 @@ function assignWormholeNames() {
|
|
|
42
42
|
function wormholeIntegration() {
|
|
43
43
|
throw new Error("the @astroscope/wormhole integration is server-only");
|
|
44
44
|
}
|
|
45
|
-
//#endregion
|
|
46
45
|
export { assignWormholeNames, wormholeIntegration as default, defineWormhole, wormholes };
|
|
47
46
|
|
|
48
47
|
//# sourceMappingURL=index.browser.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { a as WormholeMap, i as WormholeHandler, n as Wormhole, o as WormholeRegistry, r as WormholeDefinition, t as UnwrapWormholes } from "./types-
|
|
1
|
+
import { a as WormholeMap, i as WormholeHandler, n as Wormhole, o as WormholeRegistry, r as WormholeDefinition, t as UnwrapWormholes } from "./types-TzBj9lJt.js";
|
|
2
2
|
import { ExcludePattern } from "@astroscope/node/excludes";
|
|
3
3
|
import { AstroIntegration } from "astro";
|
|
4
|
-
//#region src/integration.d.ts
|
|
5
4
|
type WormholeIntegrationOptions = {
|
|
6
5
|
/** patterns the middleware skips — no handler runs, nothing is delivered; defaults to RECOMMENDED_EXCLUDES */
|
|
7
6
|
exclude?: ExcludePattern[] | undefined;
|
|
@@ -19,8 +18,6 @@ type WormholeIntegrationOptions = {
|
|
|
19
18
|
* island's slice before its tag.
|
|
20
19
|
*/
|
|
21
20
|
export default function wormholeIntegration(options?: WormholeIntegrationOptions): AstroIntegration;
|
|
22
|
-
//#endregion
|
|
23
|
-
//#region src/define.d.ts
|
|
24
21
|
/**
|
|
25
22
|
* Define a wormhole for the `src/wormholes.ts` registry, actions-style. The
|
|
26
23
|
* handler resolves the value per request; the middleware calls it only for routes
|
|
@@ -46,8 +43,6 @@ export declare function defineWormhole<T>(definition: WormholeDefinition<T>): Wo
|
|
|
46
43
|
* exposed for setups that read wormholes on the server without the middleware.
|
|
47
44
|
*/
|
|
48
45
|
export declare function assignWormholeNames(registry: Record<string, object>): void;
|
|
49
|
-
//#endregion
|
|
50
|
-
//#region src/index.d.ts
|
|
51
46
|
/**
|
|
52
47
|
* Access wormholes by name — `wormholes.cart.get()`. This is the server side of the
|
|
53
48
|
* proxy (the browser build ships its own): values come from the request's
|
|
@@ -56,6 +51,5 @@ export declare function assignWormholeNames(registry: Record<string, object>): v
|
|
|
56
51
|
* generates from `src/wormholes.ts`.
|
|
57
52
|
*/
|
|
58
53
|
export declare const wormholes: WormholeMap;
|
|
59
|
-
//#endregion
|
|
60
54
|
export type { UnwrapWormholes, Wormhole, WormholeDefinition, WormholeHandler, WormholeIntegrationOptions, WormholeMap, WormholeRegistry };
|
|
61
55
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/integration.ts","../src/define.ts","../src/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/integration.ts","../src/define.ts","../src/index.ts"],"mappings":";;;KAQY;;EAEV,UAAU;;;;;;;;;;;;;;wBAeY,oBAAoB,UAAS,6BAAkC;;;;;;;;;;;;;;;;;;;;wBCSvE,eAAe,GAAG,YAAY,mBAAmB,KAAK,SAAS;;;;;wBA6E/D,oBAAoB,UAAU;;;;;;;;qBC1EjC,WAAW"}
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { n as createWormhole, r as defineWormhole, t as assignWormholeNames } from "./define-
|
|
1
|
+
import { n as createWormhole, r as defineWormhole, t as assignWormholeNames } from "./define-DO3-gETv.js";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
-
import { collectRouteIslands, routeEntrypoints, stripQuery } from "@astroscope/node/islands";
|
|
5
|
+
import { collectRouteIslands, isScriptEntry, routeEntrypoints, stripQuery } from "@astroscope/node/islands";
|
|
6
6
|
import { serializeExcludePatterns } from "@astroscope/node/excludes";
|
|
7
|
-
|
|
7
|
+
// src/extraction/vite-plugin.ts
|
|
8
8
|
const WORMHOLE_VIRTUAL_MODULE_ID = "virtual:@astroscope/wormhole/manifest";
|
|
9
9
|
const REGISTRY_VIRTUAL_MODULE_ID = "virtual:@astroscope/wormhole/registry";
|
|
10
10
|
const CONFIG_VIRTUAL_MODULE_ID = "virtual:@astroscope/wormhole/config";
|
|
@@ -78,7 +78,7 @@ export { manifest };
|
|
|
78
78
|
const file = extensions.some((ext) => id.endsWith(ext)) ? id : stripQuery(id);
|
|
79
79
|
if (extensions.every((ext) => !file.endsWith(ext))) return;
|
|
80
80
|
if (!code.includes("@astroscope/wormhole")) return;
|
|
81
|
-
const { scanWormholeAccess } = await import("./scan-
|
|
81
|
+
const { scanWormholeAccess } = await import("./scan-CpLDPkMX.js");
|
|
82
82
|
const scan = scanWormholeAccess(code, file);
|
|
83
83
|
if (scan) (client ? clientScans : serverScans).set(client ? id : stripQuery(id), scan);
|
|
84
84
|
},
|
|
@@ -122,7 +122,7 @@ export { manifest };
|
|
|
122
122
|
if (chunkNames.length > 0) chunks[chunkFileNameToName(chunk.fileName)] = chunkNames;
|
|
123
123
|
chunkNamesByFileName.set(chunk.fileName, chunkNames);
|
|
124
124
|
chunkEdges.set(chunk.fileName, [...chunk.imports, ...chunk.dynamicImports]);
|
|
125
|
-
if ((chunk.isEntry || chunk.isDynamicEntry) && chunk.facadeModuleId
|
|
125
|
+
if ((chunk.isEntry || chunk.isDynamicEntry) && isScriptEntry(chunk.facadeModuleId)) scriptEntries.push(chunk.fileName);
|
|
126
126
|
}
|
|
127
127
|
const scriptNames = /* @__PURE__ */ new Set();
|
|
128
128
|
for (const entry of scriptEntries) {
|
|
@@ -156,8 +156,7 @@ export { manifest };
|
|
|
156
156
|
}
|
|
157
157
|
};
|
|
158
158
|
}
|
|
159
|
-
|
|
160
|
-
//#region src/integration.ts
|
|
159
|
+
// src/integration.ts
|
|
161
160
|
/**
|
|
162
161
|
* Astro integration for wormholes with per-route loading and per-island delivery.
|
|
163
162
|
*
|
|
@@ -212,8 +211,7 @@ declare module '@astroscope/wormhole' {
|
|
|
212
211
|
}
|
|
213
212
|
};
|
|
214
213
|
}
|
|
215
|
-
|
|
216
|
-
//#region src/index.ts
|
|
214
|
+
// src/index.ts
|
|
217
215
|
const stubs = /* @__PURE__ */ new Map();
|
|
218
216
|
function stub(name) {
|
|
219
217
|
let wormhole = stubs.get(name);
|
|
@@ -234,7 +232,6 @@ function stub(name) {
|
|
|
234
232
|
const wormholes = new Proxy({}, { get(_target, prop) {
|
|
235
233
|
return typeof prop === "string" ? stub(prop) : void 0;
|
|
236
234
|
} });
|
|
237
|
-
//#endregion
|
|
238
235
|
export { assignWormholeNames, wormholeIntegration as default, defineWormhole, wormholes };
|
|
239
236
|
|
|
240
237
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/extraction/vite-plugin.ts","../src/integration.ts","../src/index.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { type ExcludePattern, serializeExcludePatterns } from '@astroscope/node/excludes';\nimport { collectRouteIslands, stripQuery } from '@astroscope/node/islands';\nimport type { Plugin } from 'vite';\nimport type { WormholeScan } from './scan.js';\nimport type { WormholeManifest } from './types.js';\n\nexport const WORMHOLE_VIRTUAL_MODULE_ID = 'virtual:@astroscope/wormhole/manifest';\nexport const REGISTRY_VIRTUAL_MODULE_ID = 'virtual:@astroscope/wormhole/registry';\nexport const CONFIG_VIRTUAL_MODULE_ID = 'virtual:@astroscope/wormhole/config';\n\nconst RESOLVED_VIRTUAL_MODULE_ID = `\\0${WORMHOLE_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_REGISTRY_STUB_ID = `\\0${REGISTRY_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_CONFIG_VIRTUAL_MODULE_ID = `\\0${CONFIG_VIRTUAL_MODULE_ID}`;\n\nconst MANIFEST_FILE_NAME = 'wormhole-manifest.json';\n\nconst SCAN_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];\n// compiled astro components are plain modules in the server build\nconst SERVER_SCAN_EXTENSIONS = [...SCAN_EXTENSIONS, '.astro'];\n\n/** chunk file name → manifest key, e.g. `_astro/Counter.abc.js` → `Counter.abc` */\nfunction chunkFileNameToName(fileName: string): string {\n return fileName.slice(fileName.lastIndexOf('/') + 1).replace(/\\.js$/, '');\n}\n\n/**\n * Build-time side of wormhole slicing: scans modules for `wormholes.<name>`\n * accesses — server modules are attributed to the routes whose page or endpoint\n * reaches them (what the middleware must load), client modules to the emitted\n * chunks (what each island receives) — and drops the manifest next to the server\n * chunks, where the virtual module reads it back at runtime, mirroring the islands\n * and i18n manifests. Dev needs none of this: without a manifest the middleware\n * loads and ships all wormholes with every page.\n */\nexport type WormholeVitePluginOptions = {\n /** absolute path of `src/wormholes.ts` (or `wormholes/index.ts`), null when the project has none */\n registryPath: string | null;\n /** the middleware's exclude patterns, null for the default */\n exclude: ExcludePattern[] | null;\n /**\n * route modules (absolute ids) → the route patterns they serve, see `routeEntrypoints`\n * of `@astroscope/node/islands`\n */\n pages: () => Map<string, string[]>;\n};\n\nexport function wormholeVitePlugin(options: WormholeVitePluginOptions): Plugin {\n let isBuild = false;\n const clientScans = new Map<string, WormholeScan>();\n const serverScans = new Map<string, WormholeScan>();\n // names read on the server per route pattern, and the routes reaching each server\n // module — carried from the server build to the client build, where `<script>`\n // entries are attributed to routes through the component file owning them\n const routeNames = new Map<string, Set<string>>();\n const patternsByFile = new Map<string, Set<string>>();\n\n return {\n name: '@astroscope/wormhole/extract',\n\n configResolved(config) {\n isBuild = config.command === 'build';\n },\n\n resolveId(id) {\n if (id === WORMHOLE_VIRTUAL_MODULE_ID) return RESOLVED_VIRTUAL_MODULE_ID;\n if (id === CONFIG_VIRTUAL_MODULE_ID) return RESOLVED_CONFIG_VIRTUAL_MODULE_ID;\n\n // the registry virtual resolves straight to the project's own module, so the\n // middleware and user imports share one instance; without a registry file it\n // falls back to an empty stub (the middleware then opens nothing)\n if (id === REGISTRY_VIRTUAL_MODULE_ID) return options.registryPath ?? RESOLVED_REGISTRY_STUB_ID;\n },\n\n load(id) {\n if (id === RESOLVED_REGISTRY_STUB_ID) {\n return 'export const wormholes = {};';\n }\n\n if (id === RESOLVED_CONFIG_VIRTUAL_MODULE_ID) {\n // exclude patterns may contain RegExp — serialized as code, not JSON\n return `export const exclude = ${options.exclude ? serializeExcludePatterns(options.exclude) : 'null'};`;\n }\n\n // the registry carries the handlers, and with them the project's server code\n // eslint-disable-next-line unicorn/no-this-outside-of-class -- `this` is the vite plugin context api\n if (id === options.registryPath && this.environment?.name === 'client') {\n throw new Error(\n `[@astroscope/wormhole] ${path.relative(process.cwd(), id)} is server-only — client code reads wormholes through the \\`wormholes\\` proxy from '@astroscope/wormhole'`,\n );\n }\n\n if (id !== RESOLVED_VIRTUAL_MODULE_ID) return;\n\n if (!isBuild) {\n return 'export const manifest = null;';\n }\n\n // the manifest only exists after the client build — read it at runtime. astro\n // bundles middleware at the server root and other code under chunks/, so\n // probe both relative to wherever this module ended up\n return `\nimport { readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\n\nconst dir = dirname(fileURLToPath(import.meta.url));\n\nlet manifest = null;\n\nfor (const candidate of [\n join(dir, '${MANIFEST_FILE_NAME}'),\n join(dir, 'chunks', '${MANIFEST_FILE_NAME}'),\n join(dir, '..', 'chunks', '${MANIFEST_FILE_NAME}'),\n]) {\n try {\n manifest = JSON.parse(readFileSync(candidate, 'utf-8'));\n break;\n } catch {\n manifest = null;\n }\n}\n\nexport { manifest };\n`;\n },\n\n async transform(code, id) {\n // eslint-disable-next-line unicorn/no-this-outside-of-class -- `this` is the vite plugin context api\n if (!isBuild || !this.environment) return;\n if (id.includes('node_modules')) return;\n\n // eslint-disable-next-line unicorn/no-this-outside-of-class -- `this` is the vite plugin context api\n const client = this.environment.name === 'client';\n const extensions = client ? SCAN_EXTENSIONS : SERVER_SCAN_EXTENSIONS;\n // astro `<script>` modules carry their language in the query (`?astro&type=script&…&lang.ts`),\n // other virtual variants (`?astroPropagatedAssets`) keep the file's own extension\n const file = extensions.some((ext) => id.endsWith(ext)) ? id : stripQuery(id);\n\n if (extensions.every((ext) => !file.endsWith(ext))) return;\n if (!code.includes('@astroscope/wormhole')) return;\n\n // dynamic import keeps the parser out of the SSR runtime bundle\n const { scanWormholeAccess } = await import('./scan.js');\n const scan = scanWormholeAccess(code, file);\n\n if (scan) {\n (client ? clientScans : serverScans).set(client ? id : stripQuery(id), scan);\n }\n },\n\n async generateBundle() {\n // eslint-disable-next-line unicorn/no-this-outside-of-class -- `this` is the vite plugin context api\n if (this.environment.name === 'client') return;\n\n // eslint-disable-next-line unicorn/no-this-outside-of-class -- `this` is the vite plugin context api\n const { routes, patternsByModule } = await collectRouteIslands(this, options.pages());\n\n for (const pattern of routes.keys()) {\n routeNames.set(pattern, routeNames.get(pattern) ?? new Set());\n }\n\n for (const [id, patterns] of patternsByModule) {\n const file = stripQuery(id);\n let owners = patternsByFile.get(file);\n\n if (!owners) {\n owners = new Set();\n patternsByFile.set(file, owners);\n }\n\n patterns.forEach((pattern) => owners.add(pattern));\n\n const scan = serverScans.get(file);\n\n if (!scan) continue;\n\n for (const pattern of patterns) {\n const names = routeNames.get(pattern)!;\n\n scan.names.forEach((name) => names.add(name));\n\n if (scan.dynamic) {\n names.add('*');\n }\n }\n }\n },\n\n writeBundle(outputOptions, bundle) {\n // eslint-disable-next-line unicorn/no-this-outside-of-class -- `this` is the vite plugin context api\n if (this.environment.name !== 'client' || !outputOptions.dir) return;\n\n const chunks: WormholeManifest['chunks'] = {};\n const chunkNamesByFileName = new Map<string, string[]>();\n const chunkEdges = new Map<string, string[]>();\n const scriptEntries: string[] = [];\n\n for (const chunk of Object.values(bundle)) {\n if (chunk.type !== 'chunk') continue;\n\n const names = new Set<string>();\n let dynamic = false;\n\n for (const moduleId of chunk.moduleIds) {\n const scan = clientScans.get(moduleId);\n\n scan?.names.forEach((name) => names.add(name));\n dynamic ||= scan?.dynamic ?? false;\n }\n\n const chunkNames = [...(dynamic ? ['*'] : []), ...names];\n\n if (chunkNames.length > 0) {\n chunks[chunkFileNameToName(chunk.fileName)] = chunkNames;\n }\n\n chunkNamesByFileName.set(chunk.fileName, chunkNames);\n chunkEdges.set(chunk.fileName, [...chunk.imports, ...chunk.dynamicImports]);\n\n // astro `<script>` entries are not islands, so no island emission covers\n // them — their reachable names ship at stream end instead\n if ((chunk.isEntry || chunk.isDynamicEntry) && chunk.facadeModuleId?.includes('astro&type=script')) {\n scriptEntries.push(chunk.fileName);\n }\n }\n\n const scriptNames = new Set<string>();\n\n for (const entry of scriptEntries) {\n const names = new Set<string>();\n const visited = new Set<string>();\n\n const walk = (fileName: string): void => {\n if (visited.has(fileName)) return;\n\n visited.add(fileName);\n chunkNamesByFileName.get(fileName)?.forEach((name) => names.add(name));\n chunkEdges.get(fileName)?.forEach((imported) => walk(imported));\n };\n\n walk(entry);\n names.forEach((name) => scriptNames.add(name));\n\n // the script belongs to the routes reaching the component it sits in;\n // an owner the server build never saw means every route may need it\n const owner = bundle[entry]?.type === 'chunk' ? stripQuery(bundle[entry].facadeModuleId ?? '') : '';\n const owners = patternsByFile.get(owner) ?? routeNames.keys();\n\n for (const pattern of owners) {\n const route = routeNames.get(pattern);\n\n names.forEach((name) => route?.add(name));\n }\n }\n\n const routes: WormholeManifest['routes'] = {};\n\n for (const [pattern, names] of routeNames) {\n routes[pattern] = [...names];\n }\n\n const manifest: WormholeManifest = { chunks, scripts: [...scriptNames], routes };\n const chunksDir = path.resolve(outputOptions.dir, '..', 'server', 'chunks');\n\n if (fs.existsSync(chunksDir)) {\n fs.writeFileSync(path.join(chunksDir, MANIFEST_FILE_NAME), JSON.stringify(manifest));\n } else {\n console.error(\n `[@astroscope/wormhole] server chunks directory not found, cannot write manifest to ${chunksDir}`,\n );\n }\n },\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ExcludePattern } from '@astroscope/node/excludes';\nimport { routeEntrypoints } from '@astroscope/node/islands';\nimport type { AstroIntegration, IntegrationResolvedRoute } from 'astro';\nimport { wormholeVitePlugin } from './extraction/vite-plugin.js';\n\nexport type WormholeIntegrationOptions = {\n /** patterns the middleware skips — no handler runs, nothing is delivered; defaults to RECOMMENDED_EXCLUDES */\n exclude?: ExcludePattern[] | undefined;\n};\n\n/**\n * Astro integration for wormholes with per-route loading and per-island delivery.\n *\n * Resolves the `src/wormholes.ts` registry and exposes it to the middleware as a\n * virtual module, injects the middleware after the project's own (so handlers see\n * everything earlier middleware put on `locals`), registers the vite plugin that\n * scans server and client code for `wormholes.<name>` accesses and maps them onto\n * routes and chunks, and generates the registry type stub that types the\n * `wormholes` proxy. Delivery happens at runtime: the middleware runs the handlers\n * the route needs, and the islands emitter (via `@astroscope/node`) writes each\n * island's slice before its tag.\n */\nexport default function wormholeIntegration(options: WormholeIntegrationOptions = {}): AstroIntegration {\n const resolveRegistryPath = (srcDir: URL): string | null =>\n ['wormholes.ts', path.join('wormholes', 'index.ts')]\n .map((candidate) => path.join(fileURLToPath(srcDir), candidate))\n .find((candidate) => fs.existsSync(candidate)) ?? null;\n\n let root = '';\n let resolvedRoutes: IntegrationResolvedRoute[] = [];\n\n return {\n name: '@astroscope/wormhole',\n hooks: {\n 'astro:config:setup': ({ config, updateConfig, addMiddleware }) => {\n root = fileURLToPath(config.root);\n\n addMiddleware({ order: 'post', entrypoint: '@astroscope/wormhole/middleware' });\n\n updateConfig({\n vite: {\n plugins: [\n wormholeVitePlugin({\n registryPath: resolveRegistryPath(config.srcDir),\n exclude: options.exclude ?? null,\n pages: () => routeEntrypoints(root, resolvedRoutes),\n }),\n ],\n },\n });\n },\n\n 'astro:routes:resolved': ({ routes }) => {\n resolvedRoutes = routes;\n },\n\n 'astro:config:done': ({ config, injectTypes, logger }) => {\n const registryPath = resolveRegistryPath(config.srcDir);\n\n if (!registryPath) {\n logger.warn('no src/wormholes.ts registry found — the wormholes proxy stays untyped');\n\n return;\n }\n\n // the specifier is relative to the stub's own directory, whose documented\n // location is `.astro/integrations/<normalized integration name>/` — the\n // url injectTypes returns verifies the assumption below, so a layout change\n // in astro fails loudly at sync time instead of silently untyping the proxy\n const stubFile = path.join(\n fileURLToPath(config.root),\n '.astro',\n 'integrations',\n '_astroscope_wormhole',\n 'registry.d.ts',\n );\n const relative = path.relative(path.dirname(stubFile), registryPath.replace(/([/\\\\]index)?\\.ts$/, ''));\n const specifier = relative.split(path.sep).join('/');\n\n const written = injectTypes({\n filename: 'registry.d.ts',\n content:\n `import type { UnwrapWormholes } from '@astroscope/wormhole';\\n\\n` +\n `declare module '@astroscope/wormhole' {\\n` +\n ` interface WormholeRegistry extends UnwrapWormholes<typeof import(${JSON.stringify(specifier)}).wormholes> {}\\n` +\n `}\\n`,\n });\n\n if (path.resolve(fileURLToPath(written)) !== path.resolve(stubFile)) {\n logger.error(\n `registry type stub landed at ${fileURLToPath(written)} instead of the expected ${stubFile} — ` +\n `its relative import is now wrong and the wormholes proxy is untyped; please report this to @astroscope/wormhole`,\n );\n }\n },\n },\n };\n}\n","import { assignWormholeNames, createWormhole } from './define.js';\nimport type { Wormhole, WormholeMap } from './types.js';\n\nexport { default } from './integration.js';\nexport type { WormholeIntegrationOptions } from './integration.js';\nexport { defineWormhole, assignWormholeNames } from './define.js';\nexport type {\n UnwrapWormholes,\n Wormhole,\n WormholeDefinition,\n WormholeHandler,\n WormholeMap,\n WormholeRegistry,\n} from './types.js';\n\nconst stubs = new Map<string, Wormhole<unknown>>();\n\nfunction stub(name: string): Wormhole<unknown> {\n let wormhole = stubs.get(name);\n\n if (!wormhole) {\n wormhole = createWormhole();\n\n assignWormholeNames({ [name]: wormhole });\n stubs.set(name, wormhole);\n }\n\n return wormhole;\n}\n\n/**\n * Access wormholes by name — `wormholes.cart.get()`. This is the server side of the\n * proxy (the browser build ships its own): values come from the request's\n * wormhole middleware scope, so it works in frontmatter, endpoints, and\n * server-rendered islands alike. Typed via the registry type stub the integration\n * generates from `src/wormholes.ts`.\n */\nexport const wormholes: WormholeMap = new Proxy({} as WormholeMap, {\n get(_target, prop) {\n return typeof prop === 'string' ? stub(prop) : undefined;\n },\n});\n"],"mappings":";;;;;;;AAQA,MAAa,6BAA6B;AAC1C,MAAa,6BAA6B;AAC1C,MAAa,2BAA2B;AAExC,MAAM,6BAA6B,KAAK;AACxC,MAAM,4BAA4B,KAAK;AACvC,MAAM,oCAAoC,KAAK;AAE/C,MAAM,qBAAqB;AAE3B,MAAM,kBAAkB;CAAC;CAAO;CAAQ;CAAO;AAAM;AAErD,MAAM,yBAAyB,CAAC,GAAG,iBAAiB,QAAQ;;AAG5D,SAAS,oBAAoB,UAA0B;CACrD,OAAO,SAAS,M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OAAO,KAAK,wEAAwE;KAEpF;IACF;IAMA,MAAM,WAAW,KAAK,KACpB,cAAc,OAAO,IAAI,GACzB,UACA,gBACA,wBACA,eACF;IAEA,MAAM,YADW,KAAK,SAAS,KAAK,QAAQ,QAAQ,GAAG,aAAa,QAAQ,sBAAsB,EAAE,CAC3E,CAAC,CAAC,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;IAEnD,MAAM,UAAU,YAAY;KAC1B,UAAU;KACV,SACE;;;qEAEsE,KAAK,UAAU,SAAS,EAAE;IAEpG,CAAC;IAED,IAAI,KAAK,QAAQ,cAAc,OAAO,CAAC,MAAM,KAAK,QAAQ,QAAQ,GAChE,OAAO,MACL,gCAAgC,cAAc,OAAO,EAAE,2BAA2B,SAAS,mHAE7F;GAEJ;EACF;CACF;AACF;;;ACrFA,MAAM,wBAAQ,IAAI,IAA+B;AAEjD,SAAS,KAAK,MAAiC;CAC7C,IAAI,WAAW,MAAM,IAAI,IAAI;CAE7B,IAAI,CAAC,UAAU;EACb,WAAW,eAAe;EAE1B,oBAAoB,GAAG,OAAO,SAAS,CAAC;EACxC,MAAM,IAAI,MAAM,QAAQ;CAC1B;CAEA,OAAO;AACT;;;;;;;;AASA,MAAa,YAAyB,IAAI,MAAM,CAAC,GAAkB,EACjE,IAAI,SAAS,MAAM;CACjB,OAAO,OAAO,SAAS,WAAW,KAAK,IAAI,IAAI,KAAA;AACjD,EACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/extraction/vite-plugin.ts","../src/integration.ts","../src/index.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { type ExcludePattern, serializeExcludePatterns } from '@astroscope/node/excludes';\nimport { collectRouteIslands, isScriptEntry, stripQuery } from '@astroscope/node/islands';\nimport type { Plugin } from 'vite';\nimport type { WormholeScan } from './scan.js';\nimport type { WormholeManifest } from './types.js';\n\nexport const WORMHOLE_VIRTUAL_MODULE_ID = 'virtual:@astroscope/wormhole/manifest';\nexport const REGISTRY_VIRTUAL_MODULE_ID = 'virtual:@astroscope/wormhole/registry';\nexport const CONFIG_VIRTUAL_MODULE_ID = 'virtual:@astroscope/wormhole/config';\n\nconst RESOLVED_VIRTUAL_MODULE_ID = `\\0${WORMHOLE_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_REGISTRY_STUB_ID = `\\0${REGISTRY_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_CONFIG_VIRTUAL_MODULE_ID = `\\0${CONFIG_VIRTUAL_MODULE_ID}`;\n\nconst MANIFEST_FILE_NAME = 'wormhole-manifest.json';\n\nconst SCAN_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];\n// compiled astro components are plain modules in the server build\nconst SERVER_SCAN_EXTENSIONS = [...SCAN_EXTENSIONS, '.astro'];\n\n/** chunk file name → manifest key, e.g. `_astro/Counter.abc.js` → `Counter.abc` */\nfunction chunkFileNameToName(fileName: string): string {\n return fileName.slice(fileName.lastIndexOf('/') + 1).replace(/\\.js$/, '');\n}\n\n/**\n * Build-time side of wormhole slicing: scans modules for `wormholes.<name>`\n * accesses — server modules are attributed to the routes whose page or endpoint\n * reaches them (what the middleware must load), client modules to the emitted\n * chunks (what each island receives) — and drops the manifest next to the server\n * chunks, where the virtual module reads it back at runtime, mirroring the islands\n * and i18n manifests. Dev needs none of this: without a manifest the middleware\n * loads and ships all wormholes with every page.\n */\nexport type WormholeVitePluginOptions = {\n /** absolute path of `src/wormholes.ts` (or `wormholes/index.ts`), null when the project has none */\n registryPath: string | null;\n /** the middleware's exclude patterns, null for the default */\n exclude: ExcludePattern[] | null;\n /**\n * route modules (absolute ids) → the route patterns they serve, see `routeEntrypoints`\n * of `@astroscope/node/islands`\n */\n pages: () => Map<string, string[]>;\n};\n\nexport function wormholeVitePlugin(options: WormholeVitePluginOptions): Plugin {\n let isBuild = false;\n const clientScans = new Map<string, WormholeScan>();\n const serverScans = new Map<string, WormholeScan>();\n // names read on the server per route pattern, and the routes reaching each server\n // module — carried from the server build to the client build, where `<script>`\n // entries are attributed to routes through the component file owning them\n const routeNames = new Map<string, Set<string>>();\n const patternsByFile = new Map<string, Set<string>>();\n\n return {\n name: '@astroscope/wormhole/extract',\n\n configResolved(config) {\n isBuild = config.command === 'build';\n },\n\n resolveId(id) {\n if (id === WORMHOLE_VIRTUAL_MODULE_ID) return RESOLVED_VIRTUAL_MODULE_ID;\n if (id === CONFIG_VIRTUAL_MODULE_ID) return RESOLVED_CONFIG_VIRTUAL_MODULE_ID;\n\n // the registry virtual resolves straight to the project's own module, so the\n // middleware and user imports share one instance; without a registry file it\n // falls back to an empty stub (the middleware then opens nothing)\n if (id === REGISTRY_VIRTUAL_MODULE_ID) return options.registryPath ?? RESOLVED_REGISTRY_STUB_ID;\n },\n\n load(id) {\n if (id === RESOLVED_REGISTRY_STUB_ID) {\n return 'export const wormholes = {};';\n }\n\n if (id === RESOLVED_CONFIG_VIRTUAL_MODULE_ID) {\n // exclude patterns may contain RegExp — serialized as code, not JSON\n return `export const exclude = ${options.exclude ? serializeExcludePatterns(options.exclude) : 'null'};`;\n }\n\n // the registry carries the handlers, and with them the project's server code\n // eslint-disable-next-line unicorn/no-this-outside-of-class -- `this` is the vite plugin context api\n if (id === options.registryPath && this.environment?.name === 'client') {\n throw new Error(\n `[@astroscope/wormhole] ${path.relative(process.cwd(), id)} is server-only — client code reads wormholes through the \\`wormholes\\` proxy from '@astroscope/wormhole'`,\n );\n }\n\n if (id !== RESOLVED_VIRTUAL_MODULE_ID) return;\n\n if (!isBuild) {\n return 'export const manifest = null;';\n }\n\n // the manifest only exists after the client build — read it at runtime. astro\n // bundles middleware at the server root and other code under chunks/, so\n // probe both relative to wherever this module ended up\n return `\nimport { readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\n\nconst dir = dirname(fileURLToPath(import.meta.url));\n\nlet manifest = null;\n\nfor (const candidate of [\n join(dir, '${MANIFEST_FILE_NAME}'),\n join(dir, 'chunks', '${MANIFEST_FILE_NAME}'),\n join(dir, '..', 'chunks', '${MANIFEST_FILE_NAME}'),\n]) {\n try {\n manifest = JSON.parse(readFileSync(candidate, 'utf-8'));\n break;\n } catch {\n manifest = null;\n }\n}\n\nexport { manifest };\n`;\n },\n\n async transform(code, id) {\n // eslint-disable-next-line unicorn/no-this-outside-of-class -- `this` is the vite plugin context api\n if (!isBuild || !this.environment) return;\n if (id.includes('node_modules')) return;\n\n // eslint-disable-next-line unicorn/no-this-outside-of-class -- `this` is the vite plugin context api\n const client = this.environment.name === 'client';\n const extensions = client ? SCAN_EXTENSIONS : SERVER_SCAN_EXTENSIONS;\n // astro `<script>` modules carry their language in the query (`?astro&type=script&…&lang.ts`),\n // other virtual variants (`?astroPropagatedAssets`) keep the file's own extension\n const file = extensions.some((ext) => id.endsWith(ext)) ? id : stripQuery(id);\n\n if (extensions.every((ext) => !file.endsWith(ext))) return;\n if (!code.includes('@astroscope/wormhole')) return;\n\n // dynamic import keeps the parser out of the SSR runtime bundle\n const { scanWormholeAccess } = await import('./scan.js');\n const scan = scanWormholeAccess(code, file);\n\n if (scan) {\n (client ? clientScans : serverScans).set(client ? id : stripQuery(id), scan);\n }\n },\n\n async generateBundle() {\n // eslint-disable-next-line unicorn/no-this-outside-of-class -- `this` is the vite plugin context api\n if (this.environment.name === 'client') return;\n\n // eslint-disable-next-line unicorn/no-this-outside-of-class -- `this` is the vite plugin context api\n const { routes, patternsByModule } = await collectRouteIslands(this, options.pages());\n\n for (const pattern of routes.keys()) {\n routeNames.set(pattern, routeNames.get(pattern) ?? new Set());\n }\n\n for (const [id, patterns] of patternsByModule) {\n const file = stripQuery(id);\n let owners = patternsByFile.get(file);\n\n if (!owners) {\n owners = new Set();\n patternsByFile.set(file, owners);\n }\n\n patterns.forEach((pattern) => owners.add(pattern));\n\n const scan = serverScans.get(file);\n\n if (!scan) continue;\n\n for (const pattern of patterns) {\n const names = routeNames.get(pattern)!;\n\n scan.names.forEach((name) => names.add(name));\n\n if (scan.dynamic) {\n names.add('*');\n }\n }\n }\n },\n\n writeBundle(outputOptions, bundle) {\n // eslint-disable-next-line unicorn/no-this-outside-of-class -- `this` is the vite plugin context api\n if (this.environment.name !== 'client' || !outputOptions.dir) return;\n\n const chunks: WormholeManifest['chunks'] = {};\n const chunkNamesByFileName = new Map<string, string[]>();\n const chunkEdges = new Map<string, string[]>();\n const scriptEntries: string[] = [];\n\n for (const chunk of Object.values(bundle)) {\n if (chunk.type !== 'chunk') continue;\n\n const names = new Set<string>();\n let dynamic = false;\n\n for (const moduleId of chunk.moduleIds) {\n const scan = clientScans.get(moduleId);\n\n scan?.names.forEach((name) => names.add(name));\n dynamic ||= scan?.dynamic ?? false;\n }\n\n const chunkNames = [...(dynamic ? ['*'] : []), ...names];\n\n if (chunkNames.length > 0) {\n chunks[chunkFileNameToName(chunk.fileName)] = chunkNames;\n }\n\n chunkNamesByFileName.set(chunk.fileName, chunkNames);\n chunkEdges.set(chunk.fileName, [...chunk.imports, ...chunk.dynamicImports]);\n\n // astro `<script>` entries and the page script integrations inject are not islands, so\n // no island emission covers them — their reachable names ship at stream end instead\n if ((chunk.isEntry || chunk.isDynamicEntry) && isScriptEntry(chunk.facadeModuleId)) {\n scriptEntries.push(chunk.fileName);\n }\n }\n\n const scriptNames = new Set<string>();\n\n for (const entry of scriptEntries) {\n const names = new Set<string>();\n const visited = new Set<string>();\n\n const walk = (fileName: string): void => {\n if (visited.has(fileName)) return;\n\n visited.add(fileName);\n chunkNamesByFileName.get(fileName)?.forEach((name) => names.add(name));\n chunkEdges.get(fileName)?.forEach((imported) => walk(imported));\n };\n\n walk(entry);\n names.forEach((name) => scriptNames.add(name));\n\n // the script belongs to the routes reaching the component it sits in;\n // an owner the server build never saw means every route may need it\n const owner = bundle[entry]?.type === 'chunk' ? stripQuery(bundle[entry].facadeModuleId ?? '') : '';\n const owners = patternsByFile.get(owner) ?? routeNames.keys();\n\n for (const pattern of owners) {\n const route = routeNames.get(pattern);\n\n names.forEach((name) => route?.add(name));\n }\n }\n\n const routes: WormholeManifest['routes'] = {};\n\n for (const [pattern, names] of routeNames) {\n routes[pattern] = [...names];\n }\n\n const manifest: WormholeManifest = { chunks, scripts: [...scriptNames], routes };\n const chunksDir = path.resolve(outputOptions.dir, '..', 'server', 'chunks');\n\n if (fs.existsSync(chunksDir)) {\n fs.writeFileSync(path.join(chunksDir, MANIFEST_FILE_NAME), JSON.stringify(manifest));\n } else {\n console.error(\n `[@astroscope/wormhole] server chunks directory not found, cannot write manifest to ${chunksDir}`,\n );\n }\n },\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ExcludePattern } from '@astroscope/node/excludes';\nimport { routeEntrypoints } from '@astroscope/node/islands';\nimport type { AstroIntegration, IntegrationResolvedRoute } from 'astro';\nimport { wormholeVitePlugin } from './extraction/vite-plugin.js';\n\nexport type WormholeIntegrationOptions = {\n /** patterns the middleware skips — no handler runs, nothing is delivered; defaults to RECOMMENDED_EXCLUDES */\n exclude?: ExcludePattern[] | undefined;\n};\n\n/**\n * Astro integration for wormholes with per-route loading and per-island delivery.\n *\n * Resolves the `src/wormholes.ts` registry and exposes it to the middleware as a\n * virtual module, injects the middleware after the project's own (so handlers see\n * everything earlier middleware put on `locals`), registers the vite plugin that\n * scans server and client code for `wormholes.<name>` accesses and maps them onto\n * routes and chunks, and generates the registry type stub that types the\n * `wormholes` proxy. Delivery happens at runtime: the middleware runs the handlers\n * the route needs, and the islands emitter (via `@astroscope/node`) writes each\n * island's slice before its tag.\n */\nexport default function wormholeIntegration(options: WormholeIntegrationOptions = {}): AstroIntegration {\n const resolveRegistryPath = (srcDir: URL): string | null =>\n ['wormholes.ts', path.join('wormholes', 'index.ts')]\n .map((candidate) => path.join(fileURLToPath(srcDir), candidate))\n .find((candidate) => fs.existsSync(candidate)) ?? null;\n\n let root = '';\n let resolvedRoutes: IntegrationResolvedRoute[] = [];\n\n return {\n name: '@astroscope/wormhole',\n hooks: {\n 'astro:config:setup': ({ config, updateConfig, addMiddleware }) => {\n root = fileURLToPath(config.root);\n\n addMiddleware({ order: 'post', entrypoint: '@astroscope/wormhole/middleware' });\n\n updateConfig({\n vite: {\n plugins: [\n wormholeVitePlugin({\n registryPath: resolveRegistryPath(config.srcDir),\n exclude: options.exclude ?? null,\n pages: () => routeEntrypoints(root, resolvedRoutes),\n }),\n ],\n },\n });\n },\n\n 'astro:routes:resolved': ({ routes }) => {\n resolvedRoutes = routes;\n },\n\n 'astro:config:done': ({ config, injectTypes, logger }) => {\n const registryPath = resolveRegistryPath(config.srcDir);\n\n if (!registryPath) {\n logger.warn('no src/wormholes.ts registry found — the wormholes proxy stays untyped');\n\n return;\n }\n\n // the specifier is relative to the stub's own directory, whose documented\n // location is `.astro/integrations/<normalized integration name>/` — the\n // url injectTypes returns verifies the assumption below, so a layout change\n // in astro fails loudly at sync time instead of silently untyping the proxy\n const stubFile = path.join(\n fileURLToPath(config.root),\n '.astro',\n 'integrations',\n '_astroscope_wormhole',\n 'registry.d.ts',\n );\n const relative = path.relative(path.dirname(stubFile), registryPath.replace(/([/\\\\]index)?\\.ts$/, ''));\n const specifier = relative.split(path.sep).join('/');\n\n const written = injectTypes({\n filename: 'registry.d.ts',\n content:\n `import type { UnwrapWormholes } from '@astroscope/wormhole';\\n\\n` +\n `declare module '@astroscope/wormhole' {\\n` +\n ` interface WormholeRegistry extends UnwrapWormholes<typeof import(${JSON.stringify(specifier)}).wormholes> {}\\n` +\n `}\\n`,\n });\n\n if (path.resolve(fileURLToPath(written)) !== path.resolve(stubFile)) {\n logger.error(\n `registry type stub landed at ${fileURLToPath(written)} instead of the expected ${stubFile} — ` +\n `its relative import is now wrong and the wormholes proxy is untyped; please report this to @astroscope/wormhole`,\n );\n }\n },\n },\n };\n}\n","import { assignWormholeNames, createWormhole } from './define.js';\nimport type { Wormhole, WormholeMap } from './types.js';\n\nexport { default } from './integration.js';\nexport type { WormholeIntegrationOptions } from './integration.js';\nexport { defineWormhole, assignWormholeNames } from './define.js';\nexport type {\n UnwrapWormholes,\n Wormhole,\n WormholeDefinition,\n WormholeHandler,\n WormholeMap,\n WormholeRegistry,\n} from './types.js';\n\nconst stubs = new Map<string, Wormhole<unknown>>();\n\nfunction stub(name: string): Wormhole<unknown> {\n let wormhole = stubs.get(name);\n\n if (!wormhole) {\n wormhole = createWormhole();\n\n assignWormholeNames({ [name]: wormhole });\n stubs.set(name, wormhole);\n }\n\n return wormhole;\n}\n\n/**\n * Access wormholes by name — `wormholes.cart.get()`. This is the server side of the\n * proxy (the browser build ships its own): values come from the request's\n * wormhole middleware scope, so it works in frontmatter, endpoints, and\n * server-rendered islands alike. Typed via the registry type stub the integration\n * generates from `src/wormholes.ts`.\n */\nexport const wormholes: WormholeMap = new Proxy({} as WormholeMap, {\n get(_target, prop) {\n return typeof prop === 'string' ? stub(prop) : undefined;\n },\n});\n"],"mappings":";;;;;;;AAQA,MAAa,6BAA6B;AAC1C,MAAa,6BAA6B;AAC1C,MAAa,2BAA2B;AAExC,MAAM,6BAA6B,KAAK;AACxC,MAAM,4BAA4B,KAAK;AACvC,MAAM,oCAAoC,KAAK;AAE/C,MAAM,qBAAqB;AAE3B,MAAM,kBAAkB;CAAC;CAAO;CAAQ;CAAO;AAAM;AAErD,MAAM,yBAAyB,CAAC,GAAG,iBAAiB,QAAQ;;AAG5D,SAAS,oBAAoB,UAA0B;CACrD,OAAO,SAAS,MAAM,SAAS,YAAY,GAAG,IAAI,CAAC,CAAC,CAAC,QAAQ,SAAS,EAAE;AAC1E;AAuBA,SAAgB,mBAAmB,SAA4C;CAC7E,IAAI,UAAU;CACd,MAAM,8BAAc,IAAI,IAA0B;CAClD,MAAM,8BAAc,IAAI,IAA0B;CAIlD,MAAM,6BAAa,IAAI,IAAyB;CAChD,MAAM,iCAAiB,IAAI,IAAyB;CAEpD,OAAO;EACL,MAAM;EAEN,eAAe,QAAQ;GACrB,UAAU,OAAO,YAAY;EAC/B;EAEA,UAAU,IAAI;GACZ,IAA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AQ,cAAc,OAAO,CAAC,MAAM,KAAK,QAAQ,QAAQ,GAChE,OAAO,MACL,gCAAgC,cAAc,OAAO,EAAE,2BAA2B,SAAS,mHAE7F;GAEJ;EACF;CACF;AACF;;ACrFA,MAAM,wBAAQ,IAAI,IAA+B;AAEjD,SAAS,KAAK,MAAiC;CAC7C,IAAI,WAAW,MAAM,IAAI,IAAI;CAE7B,IAAI,CAAC,UAAU;EACb,WAAW,eAAe;EAE1B,oBAAoB,GAAG,OAAO,SAAS,CAAC;EACxC,MAAM,IAAI,MAAM,QAAQ;CAC1B;CAEA,OAAO;AACT;;;;;;;;AASA,MAAa,YAAyB,IAAI,MAAM,CAAC,GAAkB,EACjE,IAAI,SAAS,MAAM;CACjB,OAAO,OAAO,SAAS,WAAW,KAAK,IAAI,IAAI,KAAA;AACjD,EACF,CAAC"}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
// src/key.ts
|
|
2
2
|
/** the shared key format for a wormhole's ALS entry — kept free of node imports for the browser build */
|
|
3
3
|
function wormholeKey(name) {
|
|
4
4
|
return `__wormhole_${name}__`;
|
|
5
5
|
}
|
|
6
|
-
//#endregion
|
|
7
6
|
export { wormholeKey as t };
|
|
8
7
|
|
|
9
|
-
//# sourceMappingURL=key-
|
|
8
|
+
//# sourceMappingURL=key-DeXuVpLB.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"key-
|
|
1
|
+
{"version":3,"file":"key-DeXuVpLB.js","names":[],"sources":["../src/key.ts"],"sourcesContent":["/** the shared key format for a wormhole's ALS entry — kept free of node imports for the browser build */\nexport function wormholeKey(name: string): string {\n return `__wormhole_${name}__`;\n}\n"],"mappings":";;AACA,SAAgB,YAAY,MAAsB;CAChD,OAAO,cAAc,KAAK;AAC5B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware-entrypoint.d.ts","names":[],"sources":["../src/middleware-entrypoint.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"middleware-entrypoint.d.ts","names":[],"sources":["../src/middleware-entrypoint.ts"],"mappings":"A,qBAGa,2BAAS"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as als } from "./als-
|
|
2
|
-
import { i as getWormholeSource, t as assignWormholeNames } from "./define-
|
|
1
|
+
import { t as als } from "./als-D5JKSoMf.js";
|
|
2
|
+
import { i as getWormholeSource, t as assignWormholeNames } from "./define-DO3-gETv.js";
|
|
3
3
|
import { getRouteIslands, registerDocumentEmitter, registerIslandEmitter } from "@astroscope/node/islands";
|
|
4
4
|
import { RECOMMENDED_EXCLUDES, shouldExclude } from "@astroscope/node/excludes";
|
|
5
5
|
import { exclude } from "virtual:@astroscope/wormhole/config";
|
|
@@ -8,7 +8,7 @@ import { wormholes } from "virtual:@astroscope/wormhole/registry";
|
|
|
8
8
|
import { log } from "@astroscope/node/log";
|
|
9
9
|
import { manifest } from "virtual:@astroscope/wormhole/manifest";
|
|
10
10
|
import { DURATION_BUCKETS, createCounter, createHistogram, errorType, withSpan } from "@astroscope/node/telemetry";
|
|
11
|
-
|
|
11
|
+
// src/client-state.ts
|
|
12
12
|
/**
|
|
13
13
|
* Script generation for wormhole delivery, shipped through the `@astroscope/node`
|
|
14
14
|
* islands pipeline (see islands-emitter.ts for the placement policy).
|
|
@@ -24,14 +24,12 @@ function jsonForScript(value) {
|
|
|
24
24
|
function createWormholeMergeScript(entries) {
|
|
25
25
|
return `<script>{const s=self.__wormholes__??={},d=${jsonForScript(entries)};for(const n in d){const e=s[n]??={};e.v=d[n];e.l&&e.l.forEach(f=>f(e.v))}}<\/script>`;
|
|
26
26
|
}
|
|
27
|
-
|
|
28
|
-
//#region src/manifest.ts
|
|
27
|
+
// src/manifest.ts
|
|
29
28
|
/** null in dev and when the build produced no manifest (broken deploy → full delivery fallback) */
|
|
30
29
|
function getWormholeManifest() {
|
|
31
30
|
return manifest;
|
|
32
31
|
}
|
|
33
|
-
|
|
34
|
-
//#region src/reachable.ts
|
|
32
|
+
// src/reachable.ts
|
|
35
33
|
/**
|
|
36
34
|
* public url or dist-relative file name of a chunk → manifest chunk name,
|
|
37
35
|
* e.g. `…/_astro/Counter.abc.js` → `Counter.abc`
|
|
@@ -54,8 +52,7 @@ function namesInClosure(closure, manifest) {
|
|
|
54
52
|
}
|
|
55
53
|
return [...names];
|
|
56
54
|
}
|
|
57
|
-
|
|
58
|
-
//#region src/request-store.ts
|
|
55
|
+
// src/request-store.ts
|
|
59
56
|
const requestWormholes = /* @__PURE__ */ new WeakMap();
|
|
60
57
|
function setRequestWormholes(request, wormholes) {
|
|
61
58
|
requestWormholes.set(request, wormholes);
|
|
@@ -63,8 +60,7 @@ function setRequestWormholes(request, wormholes) {
|
|
|
63
60
|
function getRequestWormholes(request) {
|
|
64
61
|
return requestWormholes.get(request);
|
|
65
62
|
}
|
|
66
|
-
|
|
67
|
-
//#region src/islands-emitter.ts
|
|
63
|
+
// src/islands-emitter.ts
|
|
68
64
|
/**
|
|
69
65
|
* Contributes each island's wormhole slice: an inline merge script with the values
|
|
70
66
|
* of every open wormhole the island's full chunk closure (dynamic imports included)
|
|
@@ -138,8 +134,7 @@ function registerWormholeEmitters() {
|
|
|
138
134
|
return { html: createWormholeMergeScript(entries) };
|
|
139
135
|
});
|
|
140
136
|
}
|
|
141
|
-
|
|
142
|
-
//#region src/telemetry.ts
|
|
137
|
+
// src/telemetry.ts
|
|
143
138
|
const SCOPE = "@astroscope/wormhole";
|
|
144
139
|
const handlerDuration = createHistogram("astro.wormhole.handler.duration", {
|
|
145
140
|
scope: SCOPE,
|
|
@@ -191,8 +186,7 @@ function measureHandler(name, run) {
|
|
|
191
186
|
}, fail);
|
|
192
187
|
});
|
|
193
188
|
}
|
|
194
|
-
|
|
195
|
-
//#region src/middleware.ts
|
|
189
|
+
// src/middleware.ts
|
|
196
190
|
/**
|
|
197
191
|
* The wormhole middleware, injected by the integration after the project's own
|
|
198
192
|
* middleware: runs the handlers of the wormholes the request's route can read —
|
|
@@ -260,10 +254,8 @@ function createWormholeMiddleware(options = {}) {
|
|
|
260
254
|
});
|
|
261
255
|
};
|
|
262
256
|
}
|
|
263
|
-
|
|
264
|
-
//#region src/middleware-entrypoint.ts
|
|
257
|
+
// src/middleware-entrypoint.ts
|
|
265
258
|
const onRequest = createWormholeMiddleware({ exclude: exclude ?? void 0 });
|
|
266
|
-
//#endregion
|
|
267
259
|
export { onRequest };
|
|
268
260
|
|
|
269
261
|
//# sourceMappingURL=middleware-entrypoint.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware-entrypoint.js","names":["registry"],"sources":["../src/client-state.ts","../src/manifest.ts","../src/reachable.ts","../src/request-store.ts","../src/islands-emitter.ts","../src/telemetry.ts","../src/middleware.ts","../src/middleware-entrypoint.ts"],"sourcesContent":["/**\n * Script generation for wormhole delivery, shipped through the `@astroscope/node`\n * islands pipeline (see islands-emitter.ts for the placement policy).\n */\n\n/** values may contain `</script>` — escape `<` so they cannot end the tag */\nexport function jsonForScript(value: unknown): string {\n return JSON.stringify(value).replaceAll('<', String.raw`\\u003c`);\n}\n\n/**\n * Inline script writing entries onto `self.__wormholes__` and notifying listeners —\n * the counterpart of the browser proxy's entry protocol, safe in either order.\n */\nexport function createWormholeMergeScript(entries: Record<string, unknown>): string {\n return (\n `<script>{const s=self.__wormholes__??={},d=${jsonForScript(entries)};` +\n `for(const n in d){const e=s[n]??={};e.v=d[n];e.l&&e.l.forEach(f=>f(e.v))}}</script>`\n );\n}\n","import { manifest } from 'virtual:@astroscope/wormhole/manifest';\nimport type { WormholeManifest } from './extraction/types.js';\n\n/** null in dev and when the build produced no manifest (broken deploy → full delivery fallback) */\nexport function getWormholeManifest(): WormholeManifest | null {\n return manifest;\n}\n","import type { WormholeManifest } from './extraction/types.js';\n\n/**\n * public url or dist-relative file name of a chunk → manifest chunk name,\n * e.g. `…/_astro/Counter.abc.js` → `Counter.abc`\n */\nexport function chunkName(url: string): string {\n return url.slice(url.lastIndexOf('/') + 1).replace(/\\.js$/, '');\n}\n\n/**\n * The wormhole names the chunks of a closure can reach; `null` when one of them\n * reads dynamically (`*` — all open wormholes).\n */\nexport function namesInClosure(closure: Iterable<string>, manifest: WormholeManifest): string[] | null {\n const names = new Set<string>();\n\n for (const url of closure) {\n const chunkReads = manifest.chunks[chunkName(url)] ?? [];\n\n for (const name of chunkReads) {\n if (name === '*') {\n return null;\n }\n\n names.add(name);\n }\n }\n\n return [...names];\n}\n","/**\n * Per-request wormhole values for the islands emitter and the stream-end script —\n * both run while the response streams, outside the middleware's ALS scope, so the\n * request object is the only stable handle (same pattern as the i18n locale).\n */\nexport type RequestWormholes = {\n /** wormhole name → serializable value, as resolved by the middleware */\n values: ReadonlyMap<string, unknown>;\n /** names already written into the document by the islands emitter */\n emitted: Set<string>;\n};\n\nconst requestWormholes = new WeakMap<Request, RequestWormholes>();\n\nexport function setRequestWormholes(request: Request, wormholes: RequestWormholes): void {\n requestWormholes.set(request, wormholes);\n}\n\nexport function getRequestWormholes(request: Request): RequestWormholes | undefined {\n return requestWormholes.get(request);\n}\n","import {\n type DocumentEmitter,\n type IslandInfo,\n registerDocumentEmitter,\n registerIslandEmitter,\n} from '@astroscope/node/islands';\nimport { log } from '@astroscope/node/log';\nimport { createWormholeMergeScript } from './client-state.js';\nimport type { WormholeManifest } from './extraction/types.js';\nimport { getWormholeManifest } from './manifest.js';\nimport { namesInClosure } from './reachable.js';\nimport { getRequestWormholes } from './request-store.js';\n\n/**\n * Contributes each island's wormhole slice: an inline merge script with the values\n * of every open wormhole the island's full chunk closure (dynamic imports included)\n * can reach, emitted before the island tag — parsed strictly before the island\n * connects, even mid-stream. Names already written earlier in the document are\n * skipped; a `*` chunk (dynamic proxy access) degrades to all open wormholes.\n */\n\n// vite defines import.meta.env when bundling the middleware; typed structurally\n// so the package compiles without vite's global client types\nconst IS_DEV = !!(import.meta as { env?: { DEV?: boolean } }).env?.DEV;\n\nlet registered = false;\nlet warnedMissingManifest = false;\n\n/** the wormhole names an island's full closure can reach; `null` when a chunk reads dynamically (all open) */\ntype Reachable = string[] | null;\n\n// islands arrive as the same object per component/renderer/directive and the\n// manifest is loaded once, so the intersection is computed once per island\nconst reachableByManifest = new WeakMap<WormholeManifest, WeakMap<IslandInfo, Reachable>>();\n\nfunction reachableFor(island: IslandInfo, manifest: WormholeManifest): Reachable {\n let byIsland = reachableByManifest.get(manifest);\n\n if (!byIsland) {\n byIsland = new WeakMap();\n reachableByManifest.set(manifest, byIsland);\n }\n\n const cached = byIsland.get(island);\n\n if (cached !== undefined) {\n return cached;\n }\n\n const reachable = namesInClosure(island.fullClosure, manifest);\n\n byIsland.set(island, reachable);\n\n return reachable;\n}\n\n/**\n * The document-level wormhole delivery, exported for tests: everything open as\n * `head` content in dev (or without a manifest), script-entry names as `end`\n * content in prod — running after the rewriter, names the islands emitter\n * already wrote are skipped race-free.\n */\nexport function createWormholeDocumentEmitter(dev: boolean = IS_DEV): DocumentEmitter {\n return (context) => {\n const request = getRequestWormholes(context.request);\n\n if (!request || request.values.size === 0) {\n return null;\n }\n\n if (dev) {\n return { head: createWormholeMergeScript(Object.fromEntries(request.values)) };\n }\n\n const manifest = getWormholeManifest();\n\n if (!manifest) {\n if (!warnedMissingManifest) {\n warnedMissingManifest = true;\n log.error(\n 'wormhole manifest not found — delivering all open wormholes with every page (is the integration configured?)',\n );\n }\n\n return { head: createWormholeMergeScript(Object.fromEntries(request.values)) };\n }\n\n const names = manifest.scripts.includes('*')\n ? request.values.keys().toArray()\n : manifest.scripts.filter((name) => request.values.has(name));\n\n if (names.length === 0) {\n return null;\n }\n\n return {\n end: () => {\n const fresh = names.filter((name) => !request.emitted.has(name));\n\n if (fresh.length === 0) {\n return null;\n }\n\n return createWormholeMergeScript(Object.fromEntries(fresh.map((name) => [name, request.values.get(name)])));\n },\n };\n };\n}\n\nexport function registerWormholeEmitters(): void {\n if (registered) {\n return;\n }\n\n registered = true;\n\n registerDocumentEmitter(createWormholeDocumentEmitter());\n\n registerIslandEmitter((island, context) => {\n // no request context (prerendered build pass) — values are per-request, nothing to emit\n if (!context) {\n return null;\n }\n\n const request = getRequestWormholes(context.request);\n const manifest = getWormholeManifest();\n\n if (!request || !manifest || request.values.size === 0) {\n return null;\n }\n\n const candidates = reachableFor(island, manifest) ?? request.values.keys();\n const entries: Record<string, unknown> = {};\n let count = 0;\n\n for (const name of candidates) {\n if (!request.values.has(name) || request.emitted.has(name)) {\n continue;\n }\n\n request.emitted.add(name);\n entries[name] = request.values.get(name);\n count++;\n }\n\n if (count === 0) {\n return null;\n }\n\n return { html: createWormholeMergeScript(entries) };\n });\n}\n","import { log } from '@astroscope/node/log';\nimport { DURATION_BUCKETS, createCounter, createHistogram, errorType, withSpan } from '@astroscope/node/telemetry';\nimport { type MaybePromise, maybeThen } from '@entwico/dash';\n\nconst SCOPE = '@astroscope/wormhole';\n\nconst handlerDuration = createHistogram('astro.wormhole.handler.duration', {\n scope: SCOPE,\n description: 'Wormhole handler execution per request',\n unit: 's',\n buckets: DURATION_BUCKETS.io,\n});\n\nconst handlerFailures = createCounter('astro.wormhole.handler.failures', {\n scope: SCOPE,\n description: 'Wormhole handlers that threw',\n unit: '{handler}',\n});\n\n/**\n * Runs one handler under its own span (child of the request span — the\n * handlers run in parallel, so the trace shows which one holds the page's\n * first byte), records its duration and counts and logs a failure. A\n * synchronous handler stays synchronous.\n */\nexport function measureHandler<T>(name: string, run: () => MaybePromise<T>): MaybePromise<T> {\n const attributes = { 'astro.wormhole.name': name };\n const started = performance.now();\n\n const fail = (error: unknown): never => {\n handlerFailures.add(1, { ...attributes, 'error.type': errorType(error) });\n log.error(\n error instanceof Error ? { err: error, wormhole: name } : { reason: error, wormhole: name },\n 'wormhole handler failed',\n );\n\n throw error;\n };\n\n return withSpan(`wormhole ${name}`, { scope: SCOPE, attributes }, () => {\n let result: MaybePromise<T>;\n\n try {\n result = run();\n } catch (error) {\n return fail(error);\n }\n\n return maybeThen(\n result,\n (value) => {\n handlerDuration.record((performance.now() - started) / 1000, attributes);\n\n return value;\n },\n fail,\n );\n });\n}\n","import { type ExcludePattern, RECOMMENDED_EXCLUDES, shouldExclude } from '@astroscope/node/excludes';\nimport { getRouteIslands } from '@astroscope/node/islands';\nimport { maybeAll, maybeThen } from '@entwico/dash';\nimport type { MiddlewareHandler } from 'astro';\nimport { wormholes as registry } from 'virtual:@astroscope/wormhole/registry';\nimport { als } from './als.js';\nimport { type WormholeSource, assignWormholeNames, getWormholeSource } from './define.js';\nimport { registerWormholeEmitters } from './islands-emitter.js';\nimport { getWormholeManifest } from './manifest.js';\nimport { namesInClosure } from './reachable.js';\nimport { setRequestWormholes } from './request-store.js';\nimport { measureHandler } from './telemetry.js';\nimport type { WormholeHandler } from './types.js';\n\nexport type WormholeMiddlewareOptions = {\n /** patterns to exclude from wormhole loading; defaults to RECOMMENDED_EXCLUDES */\n exclude?: ExcludePattern[] | undefined;\n};\n\n/**\n * The wormhole middleware, injected by the integration after the project's own\n * middleware: runs the handlers of the wormholes the request's route can read —\n * server and `<script>` reads from the manifest, island reads through the route's\n * islands from `@astroscope/node`, and eager wormholes — makes the values\n * readable on the server for the duration of the request, and hands them to the\n * islands pipeline for delivery. Routes the build could not attribute (dev, no\n * manifest, astro's own routes) load everything.\n */\nexport function createWormholeMiddleware(options: WormholeMiddlewareOptions = {}): MiddlewareHandler {\n assignWormholeNames(registry);\n registerWormholeEmitters();\n\n const sources = new Map<string, WormholeSource>();\n\n for (const [name, wormhole] of Object.entries(registry)) {\n const source = getWormholeSource(wormhole);\n\n if (!source) {\n throw new Error(`wormhole \"${name}\" has no handler — define it with defineWormhole({ handler: (ctx) => ... })`);\n }\n\n sources.set(name, source);\n }\n\n const everything = sources.keys().toArray();\n const eager = everything.filter((name) => sources.get(name)!.eager);\n\n // what a route opens, resolved once per route: the name, the handler and the ALS key\n type Entry = { name: string; key: string; handler: WormholeHandler<unknown> };\n\n const entriesByRoute = new Map<string, Entry[]>();\n\n // null: the route's readers are unknown, load everything\n const routeNames = (pattern: string): string[] | null => {\n const manifest = getWormholeManifest();\n\n if (!manifest) {\n return null;\n }\n\n const server = manifest.routes[pattern];\n const islands = getRouteIslands(pattern);\n\n if (!server || !islands || server.includes('*')) {\n return null;\n }\n\n const names = new Set([...eager, ...server]);\n\n for (const island of islands) {\n const reachable = namesInClosure(island.fullClosure, manifest);\n\n if (!reachable) {\n return null;\n }\n\n reachable.forEach((name) => names.add(name));\n }\n\n return [...names].filter((name) => sources.has(name));\n };\n\n const entriesFor = (pattern: string): Entry[] => {\n let entries = entriesByRoute.get(pattern);\n\n if (!entries) {\n entries = (routeNames(pattern) ?? everything).map((name) => ({\n name,\n key: registry[name]!.key,\n handler: sources.get(name)!.handler,\n }));\n entriesByRoute.set(pattern, entries);\n }\n\n return entries;\n };\n\n return (ctx, next) => {\n if (shouldExclude(ctx, options.exclude ?? RECOMMENDED_EXCLUDES)) {\n return next();\n }\n\n const entries = entriesFor(ctx.routePattern);\n\n // synchronous handlers — the common case — open the scope without a promise\n // allocation or a microtask hop; async ones settle together\n return maybeThen(\n maybeAll(entries.map((entry) => measureHandler(entry.name, () => entry.handler(ctx)))),\n (loaded) => {\n const open = new Map<string, unknown>();\n const scope = new Map<string, unknown>(als.getStore());\n\n for (const [i, entry] of entries.entries()) {\n const data = loaded[i];\n\n if (data === undefined) {\n continue;\n }\n\n open.set(entry!.name, data);\n scope.set(entry!.key, data);\n }\n\n // the islands emitter and the stream-end script run while the response streams,\n // outside this ALS scope — the request object carries the values to them\n setRequestWormholes(ctx.request, { values: open, emitted: new Set() });\n\n return als.run(scope, () => next());\n },\n );\n };\n}\n","import { exclude } from 'virtual:@astroscope/wormhole/config';\nimport { createWormholeMiddleware } from './middleware.js';\n\nexport const onRequest = createWormholeMiddleware({ exclude: exclude ?? undefined });\n"],"mappings":";;;;;;;;;;;;;;;;AAMA,SAAgB,cAAc,OAAwB;CACpD,OAAO,KAAK,UAAU,KAAK,CAAC,CAAC,WAAW,KAAK,OAAO,GAAG,QAAQ;AACjE;;;;;A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AAQ,WAAW,oBAAoB,GAC5D,OAAO,KAAK;EAGd,MAAM,UAAU,WAAW,IAAI,YAAY;EAI3C,OAAO,UACL,SAAS,QAAQ,KAAK,UAAU,eAAe,MAAM,YAAY,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,IACpF,WAAW;GACV,MAAM,uBAAO,IAAI,IAAqB;GACtC,MAAM,QAAQ,IAAI,IAAqB,IAAI,SAAS,CAAC;GAErD,KAAK,MAAM,CAAC,GAAG,UAAU,QAAQ,QAAQ,GAAG;IAC1C,MAAM,OAAO,OAAO;IAEpB,IAAI,SAAS,KAAA,GACX;IAGF,KAAK,IAAI,MAAO,MAAM,IAAI;IAC1B,MAAM,IAAI,MAAO,KAAK,IAAI;GAC5B;GAIA,oBAAoB,IAAI,SAAS;IAAE,QAAQ;IAAM,yBAAS,IAAI,IAAI;GAAE,CAAC;GAErE,OAAO,IAAI,IAAI,aAAa,KAAK,CAAC;EACpC,CACF;CACF;AACF;;;AChIA,MAAa,YAAY,yBAAyB,EAAE,SAAS,WAAW,KAAA,EAAU,CAAC"}
|
|
1
|
+
{"version":3,"file":"middleware-entrypoint.js","names":["registry"],"sources":["../src/client-state.ts","../src/manifest.ts","../src/reachable.ts","../src/request-store.ts","../src/islands-emitter.ts","../src/telemetry.ts","../src/middleware.ts","../src/middleware-entrypoint.ts"],"sourcesContent":["/**\n * Script generation for wormhole delivery, shipped through the `@astroscope/node`\n * islands pipeline (see islands-emitter.ts for the placement policy).\n */\n\n/** values may contain `</script>` — escape `<` so they cannot end the tag */\nexport function jsonForScript(value: unknown): string {\n return JSON.stringify(value).replaceAll('<', String.raw`\\u003c`);\n}\n\n/**\n * Inline script writing entries onto `self.__wormholes__` and notifying listeners —\n * the counterpart of the browser proxy's entry protocol, safe in either order.\n */\nexport function createWormholeMergeScript(entries: Record<string, unknown>): string {\n return (\n `<script>{const s=self.__wormholes__??={},d=${jsonForScript(entries)};` +\n `for(const n in d){const e=s[n]??={};e.v=d[n];e.l&&e.l.forEach(f=>f(e.v))}}</script>`\n );\n}\n","import { manifest } from 'virtual:@astroscope/wormhole/manifest';\nimport type { WormholeManifest } from './extraction/types.js';\n\n/** null in dev and when the build produced no manifest (broken deploy → full delivery fallback) */\nexport function getWormholeManifest(): WormholeManifest | null {\n return manifest;\n}\n","import type { WormholeManifest } from './extraction/types.js';\n\n/**\n * public url or dist-relative file name of a chunk → manifest chunk name,\n * e.g. `…/_astro/Counter.abc.js` → `Counter.abc`\n */\nexport function chunkName(url: string): string {\n return url.slice(url.lastIndexOf('/') + 1).replace(/\\.js$/, '');\n}\n\n/**\n * The wormhole names the chunks of a closure can reach; `null` when one of them\n * reads dynamically (`*` — all open wormholes).\n */\nexport function namesInClosure(closure: Iterable<string>, manifest: WormholeManifest): string[] | null {\n const names = new Set<string>();\n\n for (const url of closure) {\n const chunkReads = manifest.chunks[chunkName(url)] ?? [];\n\n for (const name of chunkReads) {\n if (name === '*') {\n return null;\n }\n\n names.add(name);\n }\n }\n\n return [...names];\n}\n","/**\n * Per-request wormhole values for the islands emitter and the stream-end script —\n * both run while the response streams, outside the middleware's ALS scope, so the\n * request object is the only stable handle (same pattern as the i18n locale).\n */\nexport type RequestWormholes = {\n /** wormhole name → serializable value, as resolved by the middleware */\n values: ReadonlyMap<string, unknown>;\n /** names already written into the document by the islands emitter */\n emitted: Set<string>;\n};\n\nconst requestWormholes = new WeakMap<Request, RequestWormholes>();\n\nexport function setRequestWormholes(request: Request, wormholes: RequestWormholes): void {\n requestWormholes.set(request, wormholes);\n}\n\nexport function getRequestWormholes(request: Request): RequestWormholes | undefined {\n return requestWormholes.get(request);\n}\n","import {\n type DocumentEmitter,\n type IslandInfo,\n registerDocumentEmitter,\n registerIslandEmitter,\n} from '@astroscope/node/islands';\nimport { log } from '@astroscope/node/log';\nimport { createWormholeMergeScript } from './client-state.js';\nimport type { WormholeManifest } from './extraction/types.js';\nimport { getWormholeManifest } from './manifest.js';\nimport { namesInClosure } from './reachable.js';\nimport { getRequestWormholes } from './request-store.js';\n\n/**\n * Contributes each island's wormhole slice: an inline merge script with the values\n * of every open wormhole the island's full chunk closure (dynamic imports included)\n * can reach, emitted before the island tag — parsed strictly before the island\n * connects, even mid-stream. Names already written earlier in the document are\n * skipped; a `*` chunk (dynamic proxy access) degrades to all open wormholes.\n */\n\n// vite defines import.meta.env when bundling the middleware; typed structurally\n// so the package compiles without vite's global client types\nconst IS_DEV = !!(import.meta as { env?: { DEV?: boolean } }).env?.DEV;\n\nlet registered = false;\nlet warnedMissingManifest = false;\n\n/** the wormhole names an island's full closure can reach; `null` when a chunk reads dynamically (all open) */\ntype Reachable = string[] | null;\n\n// islands arrive as the same object per component/renderer/directive and the\n// manifest is loaded once, so the intersection is computed once per island\nconst reachableByManifest = new WeakMap<WormholeManifest, WeakMap<IslandInfo, Reachable>>();\n\nfunction reachableFor(island: IslandInfo, manifest: WormholeManifest): Reachable {\n let byIsland = reachableByManifest.get(manifest);\n\n if (!byIsland) {\n byIsland = new WeakMap();\n reachableByManifest.set(manifest, byIsland);\n }\n\n const cached = byIsland.get(island);\n\n if (cached !== undefined) {\n return cached;\n }\n\n const reachable = namesInClosure(island.fullClosure, manifest);\n\n byIsland.set(island, reachable);\n\n return reachable;\n}\n\n/**\n * The document-level wormhole delivery, exported for tests: everything open as\n * `head` content in dev (or without a manifest), script-entry names as `end`\n * content in prod — running after the rewriter, names the islands emitter\n * already wrote are skipped race-free.\n */\nexport function createWormholeDocumentEmitter(dev: boolean = IS_DEV): DocumentEmitter {\n return (context) => {\n const request = getRequestWormholes(context.request);\n\n if (!request || request.values.size === 0) {\n return null;\n }\n\n if (dev) {\n return { head: createWormholeMergeScript(Object.fromEntries(request.values)) };\n }\n\n const manifest = getWormholeManifest();\n\n if (!manifest) {\n if (!warnedMissingManifest) {\n warnedMissingManifest = true;\n log.error(\n 'wormhole manifest not found — delivering all open wormholes with every page (is the integration configured?)',\n );\n }\n\n return { head: createWormholeMergeScript(Object.fromEntries(request.values)) };\n }\n\n const names = manifest.scripts.includes('*')\n ? request.values.keys().toArray()\n : manifest.scripts.filter((name) => request.values.has(name));\n\n if (names.length === 0) {\n return null;\n }\n\n return {\n end: () => {\n const fresh = names.filter((name) => !request.emitted.has(name));\n\n if (fresh.length === 0) {\n return null;\n }\n\n return createWormholeMergeScript(Object.fromEntries(fresh.map((name) => [name, request.values.get(name)])));\n },\n };\n };\n}\n\nexport function registerWormholeEmitters(): void {\n if (registered) {\n return;\n }\n\n registered = true;\n\n registerDocumentEmitter(createWormholeDocumentEmitter());\n\n registerIslandEmitter((island, context) => {\n // no request context (prerendered build pass) — values are per-request, nothing to emit\n if (!context) {\n return null;\n }\n\n const request = getRequestWormholes(context.request);\n const manifest = getWormholeManifest();\n\n if (!request || !manifest || request.values.size === 0) {\n return null;\n }\n\n const candidates = reachableFor(island, manifest) ?? request.values.keys();\n const entries: Record<string, unknown> = {};\n let count = 0;\n\n for (const name of candidates) {\n if (!request.values.has(name) || request.emitted.has(name)) {\n continue;\n }\n\n request.emitted.add(name);\n entries[name] = request.values.get(name);\n count++;\n }\n\n if (count === 0) {\n return null;\n }\n\n return { html: createWormholeMergeScript(entries) };\n });\n}\n","import { log } from '@astroscope/node/log';\nimport { DURATION_BUCKETS, createCounter, createHistogram, errorType, withSpan } from '@astroscope/node/telemetry';\nimport { type MaybePromise, maybeThen } from '@entwico/dash';\n\nconst SCOPE = '@astroscope/wormhole';\n\nconst handlerDuration = createHistogram('astro.wormhole.handler.duration', {\n scope: SCOPE,\n description: 'Wormhole handler execution per request',\n unit: 's',\n buckets: DURATION_BUCKETS.io,\n});\n\nconst handlerFailures = createCounter('astro.wormhole.handler.failures', {\n scope: SCOPE,\n description: 'Wormhole handlers that threw',\n unit: '{handler}',\n});\n\n/**\n * Runs one handler under its own span (child of the request span — the\n * handlers run in parallel, so the trace shows which one holds the page's\n * first byte), records its duration and counts and logs a failure. A\n * synchronous handler stays synchronous.\n */\nexport function measureHandler<T>(name: string, run: () => MaybePromise<T>): MaybePromise<T> {\n const attributes = { 'astro.wormhole.name': name };\n const started = performance.now();\n\n const fail = (error: unknown): never => {\n handlerFailures.add(1, { ...attributes, 'error.type': errorType(error) });\n log.error(\n error instanceof Error ? { err: error, wormhole: name } : { reason: error, wormhole: name },\n 'wormhole handler failed',\n );\n\n throw error;\n };\n\n return withSpan(`wormhole ${name}`, { scope: SCOPE, attributes }, () => {\n let result: MaybePromise<T>;\n\n try {\n result = run();\n } catch (error) {\n return fail(error);\n }\n\n return maybeThen(\n result,\n (value) => {\n handlerDuration.record((performance.now() - started) / 1000, attributes);\n\n return value;\n },\n fail,\n );\n });\n}\n","import { type ExcludePattern, RECOMMENDED_EXCLUDES, shouldExclude } from '@astroscope/node/excludes';\nimport { getRouteIslands } from '@astroscope/node/islands';\nimport { maybeAll, maybeThen } from '@entwico/dash';\nimport type { MiddlewareHandler } from 'astro';\nimport { wormholes as registry } from 'virtual:@astroscope/wormhole/registry';\nimport { als } from './als.js';\nimport { type WormholeSource, assignWormholeNames, getWormholeSource } from './define.js';\nimport { registerWormholeEmitters } from './islands-emitter.js';\nimport { getWormholeManifest } from './manifest.js';\nimport { namesInClosure } from './reachable.js';\nimport { setRequestWormholes } from './request-store.js';\nimport { measureHandler } from './telemetry.js';\nimport type { WormholeHandler } from './types.js';\n\nexport type WormholeMiddlewareOptions = {\n /** patterns to exclude from wormhole loading; defaults to RECOMMENDED_EXCLUDES */\n exclude?: ExcludePattern[] | undefined;\n};\n\n/**\n * The wormhole middleware, injected by the integration after the project's own\n * middleware: runs the handlers of the wormholes the request's route can read —\n * server and `<script>` reads from the manifest, island reads through the route's\n * islands from `@astroscope/node`, and eager wormholes — makes the values\n * readable on the server for the duration of the request, and hands them to the\n * islands pipeline for delivery. Routes the build could not attribute (dev, no\n * manifest, astro's own routes) load everything.\n */\nexport function createWormholeMiddleware(options: WormholeMiddlewareOptions = {}): MiddlewareHandler {\n assignWormholeNames(registry);\n registerWormholeEmitters();\n\n const sources = new Map<string, WormholeSource>();\n\n for (const [name, wormhole] of Object.entries(registry)) {\n const source = getWormholeSource(wormhole);\n\n if (!source) {\n throw new Error(`wormhole \"${name}\" has no handler — define it with defineWormhole({ handler: (ctx) => ... })`);\n }\n\n sources.set(name, source);\n }\n\n const everything = sources.keys().toArray();\n const eager = everything.filter((name) => sources.get(name)!.eager);\n\n // what a route opens, resolved once per route: the name, the handler and the ALS key\n type Entry = { name: string; key: string; handler: WormholeHandler<unknown> };\n\n const entriesByRoute = new Map<string, Entry[]>();\n\n // null: the route's readers are unknown, load everything\n const routeNames = (pattern: string): string[] | null => {\n const manifest = getWormholeManifest();\n\n if (!manifest) {\n return null;\n }\n\n const server = manifest.routes[pattern];\n const islands = getRouteIslands(pattern);\n\n if (!server || !islands || server.includes('*')) {\n return null;\n }\n\n const names = new Set([...eager, ...server]);\n\n for (const island of islands) {\n const reachable = namesInClosure(island.fullClosure, manifest);\n\n if (!reachable) {\n return null;\n }\n\n reachable.forEach((name) => names.add(name));\n }\n\n return [...names].filter((name) => sources.has(name));\n };\n\n const entriesFor = (pattern: string): Entry[] => {\n let entries = entriesByRoute.get(pattern);\n\n if (!entries) {\n entries = (routeNames(pattern) ?? everything).map((name) => ({\n name,\n key: registry[name]!.key,\n handler: sources.get(name)!.handler,\n }));\n entriesByRoute.set(pattern, entries);\n }\n\n return entries;\n };\n\n return (ctx, next) => {\n if (shouldExclude(ctx, options.exclude ?? RECOMMENDED_EXCLUDES)) {\n return next();\n }\n\n const entries = entriesFor(ctx.routePattern);\n\n // synchronous handlers — the common case — open the scope without a promise\n // allocation or a microtask hop; async ones settle together\n return maybeThen(\n maybeAll(entries.map((entry) => measureHandler(entry.name, () => entry.handler(ctx)))),\n (loaded) => {\n const open = new Map<string, unknown>();\n const scope = new Map<string, unknown>(als.getStore());\n\n for (const [i, entry] of entries.entries()) {\n const data = loaded[i];\n\n if (data === undefined) {\n continue;\n }\n\n open.set(entry!.name, data);\n scope.set(entry!.key, data);\n }\n\n // the islands emitter and the stream-end script run while the response streams,\n // outside this ALS scope — the request object carries the values to them\n setRequestWormholes(ctx.request, { values: open, emitted: new Set() });\n\n return als.run(scope, () => next());\n },\n );\n };\n}\n","import { exclude } from 'virtual:@astroscope/wormhole/config';\nimport { createWormholeMiddleware } from './middleware.js';\n\nexport const onRequest = createWormholeMiddleware({ exclude: exclude ?? undefined });\n"],"mappings":";;;;;;;;;;;;;;;;AAMA,SAAgB,cAAc,OAAwB;CACpD,OAAO,KAAK,UAAU,KAAK,CAAC,CAAC,WAAW,KAAK,OAAO,GAAG,QAAQ;AACjE;;;;;AAMA,SAAgB,0BAA0B,SAA0C;CAClF,OACE,8CAA8C,cAAc,OAAO,EAAE;AAGzE;;;ACfA,SAAgB,sBAA+C;CAC7D,OAAO;AACT;;;;;;ACAA,SAAgB,UAAU,KAAqB;CAC7C,OAAO,IAAI,MAAM,IAAI,YAAY,GAAG,IAAI,CAAC,CAAC,CAAC,QAAQ,SAAS,EAAE;AAChE;;;;;AAMA,SAAgB,eAAe,SAA2B,UAA6C;CACrG,MAAM,wBAAQ,IAAI,IAAY;CAE9B,KAAK,MAAM,OAAO,SAAS;EACzB,MAAM,aAAa,SAAS,OAAO,UAAU,GAAG,MAAM,CAAC;EAEvD,KAAK,MAAM,QAAQ,YAAY;GAC7B,IAAI,SAAS,KACX,OAAO;GAGT,MAAM,IAAI,IAAI;EAChB;CACF;CAEA,OAAO,CAAC,GAAG,KAAK;AAClB;;AClBA,MAAM,mCAAmB,IAAI,QAAmC;AAEhE,SAAgB,oBAAoB,SAAkB,WAAmC;CACvF,iBAAiB,IAAI,SAAS,SAAS;AACzC;AAEA,SAAgB,oBAAoB,SAAgD;CAClF,OAAO,iBAAiB,IAAI,OAAO;AACrC;;;;;;;;;ACGA,MAAM,SAAS,CAAC,CAAE,YAA4C,KAAK;AAEnE,IAAI,aAAa;AACjB,IAAI,wBAAwB;AAO5B,MAAM,sCAAsB,IAAI,QAA0D;AAE1F,SAAS,aAAa,QAAoB,UAAuC;CAC/E,IAAI,WAAW,oBAAoB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AAM,cAAc,YAA6B;EAC/C,IAAI,UAAU,eAAe,IAAI,OAAO;EAExC,IAAI,CAAC,SAAS;GACZ,WAAW,WAAW,OAAO,KAAK,WAAA,CAAY,KAAK,UAAU;IAC3D;IACA,KAAKA,UAAS,KAAK,CAAE;IACrB,SAAS,QAAQ,IAAI,IAAI,CAAC,CAAE;GAC9B,EAAE;GACF,eAAe,IAAI,SAAS,OAAO;EACrC;EAEA,OAAO;CACT;CAEA,QAAQ,KAAK,SAAS;EACpB,IAAI,cAAc,KAAK,QAAQ,WAAW,oBAAoB,GAC5D,OAAO,KAAK;EAGd,MAAM,UAAU,WAAW,IAAI,YAAY;EAI3C,OAAO,UACL,SAAS,QAAQ,KAAK,UAAU,eAAe,MAAM,YAAY,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,IACpF,WAAW;GACV,MAAM,uBAAO,IAAI,IAAqB;GACtC,MAAM,QAAQ,IAAI,IAAqB,IAAI,SAAS,CAAC;GAErD,KAAK,MAAM,CAAC,GAAG,UAAU,QAAQ,QAAQ,GAAG;IAC1C,MAAM,OAAO,OAAO;IAEpB,IAAI,SAAS,KAAA,GACX;IAGF,KAAK,IAAI,MAAO,MAAM,IAAI;IAC1B,MAAM,IAAI,MAAO,KAAK,IAAI;GAC5B;GAIA,oBAAoB,IAAI,SAAS;IAAE,QAAQ;IAAM,yBAAS,IAAI,IAAI;GAAE,CAAC;GAErE,OAAO,IAAI,IAAI,aAAa,KAAK,CAAC;EACpC,CACF;CACF;AACF;;AChIA,MAAa,YAAY,yBAAyB,EAAE,SAAS,WAAW,KAAA,EAAU,CAAC"}
|
package/dist/react/index.d.ts
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
import { n as Wormhole } from "../types-
|
|
1
|
+
import { n as Wormhole } from "../types-TzBj9lJt.js";
|
|
2
2
|
import { ReadonlyDeep } from "@entwico/dash";
|
|
3
|
-
//#region src/react/index.d.ts
|
|
4
3
|
export declare function useWormhole<T>(wormhole: Wormhole<T>): ReadonlyDeep<T>;
|
|
5
|
-
//#endregion
|
|
6
4
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/react/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/react/index.ts"],"mappings":";;wBAIgB,YAAY,GAAG,UAAU,SAAS,KAAK,aAAa"}
|
package/dist/react/index.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { useSyncExternalStore } from "react";
|
|
2
|
-
|
|
2
|
+
// src/react/index.ts
|
|
3
3
|
function useWormhole(wormhole) {
|
|
4
4
|
return useSyncExternalStore(wormhole.subscribe, wormhole.get, wormhole.get);
|
|
5
5
|
}
|
|
6
|
-
//#endregion
|
|
7
6
|
export { useWormhole };
|
|
8
7
|
|
|
9
8
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { parse } from "@babel/parser";
|
|
2
|
-
|
|
2
|
+
// src/extraction/scan.ts
|
|
3
3
|
const PACKAGE_NAME = "@astroscope/wormhole";
|
|
4
4
|
const TYPE_ONLY_NODES = /* @__PURE__ */ new Set([
|
|
5
5
|
"TSTypeAnnotation",
|
|
@@ -75,7 +75,6 @@ function scanWormholeAccess(code, id) {
|
|
|
75
75
|
}, null, "");
|
|
76
76
|
return scan;
|
|
77
77
|
}
|
|
78
|
-
//#endregion
|
|
79
78
|
export { scanWormholeAccess };
|
|
80
79
|
|
|
81
|
-
//# sourceMappingURL=scan-
|
|
80
|
+
//# sourceMappingURL=scan-CpLDPkMX.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scan-
|
|
1
|
+
{"version":3,"file":"scan-CpLDPkMX.js","names":[],"sources":["../src/extraction/scan.ts"],"sourcesContent":["import { parse } from '@babel/parser';\n\nconst PACKAGE_NAME = '@astroscope/wormhole';\n\n/**\n * Which wormhole names a module can reach through the `wormhole` proxy.\n *\n * `wormholes.cart` and `wormholes['cart']` yield names; anything the scan cannot\n * resolve statically — computed access, aliasing the proxy into a variable,\n * namespace imports, re-exports — sets `dynamic`, which the manifest records as\n * `*` (all open wormholes). The failure mode is therefore over-emission, never\n * missing data.\n */\nexport type WormholeScan = { names: Set<string>; dynamic: boolean };\n\n// type-only subtrees are erased at runtime — identifiers inside them are not accesses\nconst TYPE_ONLY_NODES = new Set([\n 'TSTypeAnnotation',\n 'TSTypeParameterDeclaration',\n 'TSTypeParameterInstantiation',\n 'TSTypeQuery',\n 'TSTypeAliasDeclaration',\n 'TSInterfaceDeclaration',\n]);\n\ntype Node = { type: string; [key: string]: unknown };\n\nfunction isNode(value: unknown): value is Node {\n return typeof value === 'object' && value !== null && typeof (value as Node).type === 'string';\n}\n\nfunction walk(\n node: Node,\n visit: (node: Node, parent: Node | null, key: string) => void,\n parent: Node | null,\n key: string,\n): void {\n if (TYPE_ONLY_NODES.has(node.type)) {\n return;\n }\n\n visit(node, parent, key);\n\n for (const [childKey, value] of Object.entries(node)) {\n if (childKey === 'loc') {\n continue;\n }\n\n if (isNode(value)) {\n walk(value, visit, node, childKey);\n } else if (Array.isArray(value)) {\n for (const item of value) {\n if (isNode(item)) {\n walk(item, visit, node, childKey);\n }\n }\n }\n }\n}\n\nfunction isMember(node: Node | null): node is Node {\n return node?.type === 'MemberExpression' || node?.type === 'OptionalMemberExpression';\n}\n\nexport function scanWormholeAccess(code: string, id: string): WormholeScan | null {\n const isTs = id.endsWith('.ts') || id.endsWith('.tsx') || id.endsWith('.astro');\n const plugins: ('typescript' | 'jsx')[] = [];\n\n if (isTs) {\n plugins.push('typescript');\n }\n\n // compiled astro output is not jsx\n if (!id.endsWith('.ts') && !id.endsWith('.astro')) {\n plugins.push('jsx');\n }\n\n let program: Node;\n\n try {\n program = parse(code, { sourceType: 'module', plugins }).program as unknown as Node;\n } catch {\n // an unparseable module that mentions the package cannot be scanned — degrade soundly\n return { names: new Set(), dynamic: true };\n }\n\n const locals = new Set<string>();\n const scan: WormholeScan = { names: new Set(), dynamic: false };\n const body = program['body'] as Node[];\n\n for (const statement of body) {\n const source = (statement['source'] as Node | null)?.['value'];\n\n if (source !== PACKAGE_NAME) {\n continue;\n }\n\n if (statement.type === 'ImportDeclaration') {\n const specifiers = statement['specifiers'] as Node[];\n\n for (const specifier of specifiers) {\n if (specifier.type === 'ImportSpecifier') {\n const imported = specifier['imported'] as Node;\n const name = imported.type === 'Identifier' ? (imported['name'] as string) : (imported['value'] as string);\n\n if (name === 'wormholes') {\n locals.add((specifier['local'] as Node)['name'] as string);\n }\n } else if (specifier.type === 'ImportNamespaceSpecifier') {\n scan.dynamic = true;\n }\n }\n } else {\n // export { wormhole } from '...' / export * from '...' — accesses happen elsewhere\n scan.dynamic = true;\n }\n }\n\n if (locals.size === 0 && !scan.dynamic) {\n return null;\n }\n\n walk(\n program,\n (node, parent, key) => {\n if (!parent || node.type !== 'Identifier' || !locals.has(node['name'] as string)) {\n return;\n }\n\n if (parent.type === 'ImportSpecifier') {\n return;\n }\n\n if (key === 'object' && isMember(parent)) {\n const property = parent['property'] as Node;\n\n if (!parent['computed'] && property.type === 'Identifier') {\n scan.names.add(property['name'] as string);\n } else if (parent['computed'] && property.type === 'StringLiteral') {\n scan.names.add(property['value'] as string);\n } else {\n scan.dynamic = true;\n }\n\n return;\n }\n\n // a same-named identifier in a non-computed name position cannot reference the proxy value\n if ((key === 'property' || key === 'key') && !(parent['computed'] as boolean)) {\n return;\n }\n\n // the proxy escapes (aliased, passed, re-exported) — its accesses are untrackable\n scan.dynamic = true;\n },\n null,\n '',\n );\n\n return scan;\n}\n"],"mappings":";;AAEA,MAAM,eAAe;AAcrB,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAID,SAAS,OAAO,OAA+B;CAC7C,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAQ,MAAe,SAAS;AACxF;AAEA,SAAS,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WAAW,UAAU;IAG3B,KAFa,SAAS,SAAS,eAAgB,SAAS,UAAsB,SAAS,cAE1E,aACX,OAAO,IAAK,UAAU,QAAQ,CAAU,OAAiB;GAE7D,OAAO,IAAI,UAAU,SAAS,4BAC5B,KAAK,UAAU;EAGrB,OAEE,KAAK,UAAU;CAEnB;CAEA,IAAI,OAAO,SAAS,KAAK,CAAC,KAAK,SAC7B,OAAO;CAGT,KACE,UACC,MAAM,QAAQ,QAAQ;EACrB,IAAI,CAAC,UAAU,KAAK,SAAS,gBAAgB,CAAC,OAAO,IAAI,KAAK,OAAiB,GAC7E;EAGF,IAAI,OAAO,SAAS,mBAClB;EAGF,IAAI,QAAQ,YAAY,SAAS,MAAM,GAAG;GACxC,MAAM,WAAW,OAAO;GAExB,IAAI,CAAC,OAAO,eAAe,SAAS,SAAS,cAC3C,KAAK,MAAM,IAAI,SAAS,OAAiB;QACpC,IAAI,OAAO,eAAe,SAAS,SAAS,iBACjD,KAAK,MAAM,IAAI,SAAS,QAAkB;QAE1C,KAAK,UAAU;GAGjB;EACF;EAGA,KAAK,QAAQ,cAAc,QAAQ,UAAU,CAAE,OAAO,aACpD;EAIF,KAAK,UAAU;CACjB,GACA,MACA,EACF;CAEA,OAAO;AACT"}
|
package/dist/server.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { n as Wormhole } from "./types-
|
|
1
|
+
import { n as Wormhole } from "./types-TzBj9lJt.js";
|
|
2
2
|
import { ReadonlyDeep } from "@entwico/dash";
|
|
3
|
-
//#region src/server.d.ts
|
|
4
3
|
/** One [wormhole, data] pair per element — data is checked against its own wormhole's T. */
|
|
5
4
|
type WormholeEntries<Ts extends readonly unknown[]> = { [K in keyof Ts]: readonly [Wormhole<Ts[K]>, ReadonlyDeep<Ts[K]>]; };
|
|
6
5
|
/**
|
|
@@ -15,5 +14,5 @@ export declare function openWormholes<T, R>(wormhole: Wormhole<T>, data: Readonl
|
|
|
15
14
|
* `[wormhole, data]` pairs, each checked against its own wormhole.
|
|
16
15
|
*/
|
|
17
16
|
export declare function openWormholes<Ts extends readonly unknown[], R>(entries: readonly [...WormholeEntries<Ts>], fn: () => R): R;
|
|
18
|
-
|
|
17
|
+
export {};
|
|
19
18
|
//# sourceMappingURL=server.d.ts.map
|
package/dist/server.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","names":[],"sources":["../src/server.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"server.d.ts","names":[],"sources":["../src/server.ts"],"mappings":";;;KAKK,gBAAgB,oCAClB,WAAW,eAAe,SAAS,GAAG,KAAK,aAAa,GAAG;;;;;;;wBAS9C,cAAc,GAAG,GAAG,UAAU,SAAS,IAAI,MAAM,aAAa,IAAI,UAAU,IAAI;;;;;wBAKhF,cAAc,+BAA+B,GAC3D,sBAAsB,gBAAgB,MACtC,UAAU,IACT"}
|
package/dist/server.js
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
|
-
import { t as als } from "./als-
|
|
2
|
-
|
|
1
|
+
import { t as als } from "./als-D5JKSoMf.js";
|
|
2
|
+
// src/server.ts
|
|
3
3
|
function openWormholes(...args) {
|
|
4
4
|
const [entries, fn] = Array.isArray(args[0]) ? args : [[[args[0], args[1]]], args[2]];
|
|
5
5
|
const ctx = new Map(als.getStore());
|
|
6
6
|
for (const [wormhole, data] of entries) ctx.set(wormhole.key, data);
|
|
7
7
|
return als.run(ctx, fn);
|
|
8
8
|
}
|
|
9
|
-
//#endregion
|
|
10
9
|
export { openWormholes };
|
|
11
10
|
|
|
12
11
|
//# sourceMappingURL=server.js.map
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { ReadonlyDeep } from "@entwico/dash";
|
|
2
2
|
import { APIContext } from "astro";
|
|
3
|
-
//#region src/types.d.ts
|
|
4
3
|
/**
|
|
5
4
|
* A wormhole transfers state from server middleware to client-side components.
|
|
6
5
|
*
|
|
@@ -48,6 +47,5 @@ interface WormholeRegistry {}
|
|
|
48
47
|
type UnwrapWormholes<R> = { [K in keyof R]: R[K] extends Wormhole<infer T> ? T : never; };
|
|
49
48
|
/** the shape of the `wormholes` proxy: one typed accessor per registry entry */
|
|
50
49
|
type WormholeMap = { readonly [K in keyof WormholeRegistry]: Wormhole<WormholeRegistry[K]>; };
|
|
51
|
-
//#endregion
|
|
52
50
|
export { WormholeMap as a, WormholeHandler as i, Wormhole as n, WormholeRegistry as o, WormholeDefinition as r, UnwrapWormholes as t };
|
|
53
|
-
//# sourceMappingURL=types-
|
|
51
|
+
//# sourceMappingURL=types-TzBj9lJt.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-TzBj9lJt.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;;;;;;;UAciB,gBAAgB;WACtB;WACA;EACT,OAAO,aAAa;;;;;;EAMpB,IAAI,MAAM,aAAa;EACvB,UAAU,KAAK,MAAM,aAAa;;;;;;;KAQxB,gBAAgB,MAAM,SAAS,eAAe,gBAAgB,QAAQ;;KAGtE,mBAAmB;EAC7B,SAAS,gBAAgB;;;;;;EAMzB;;;;;;;UASe;;KAGL,gBAAgB,QAAQ,WAAW,IAAI,EAAE,WAAW,eAAe,KAAK;;KAGxE,0BAA0B,WAAW,mBAAmB,SAAS,iBAAiB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astroscope/wormhole",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.2",
|
|
4
4
|
"description": "Share dynamic server data with React islands and client scripts — typed, loaded per route, streamed with the HTML, sliced per island",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -51,22 +51,22 @@
|
|
|
51
51
|
},
|
|
52
52
|
"homepage": "https://github.com/entwico/astroscope/tree/main/packages/wormhole#readme",
|
|
53
53
|
"dependencies": {
|
|
54
|
-
"@babel/parser": "^8.0.
|
|
54
|
+
"@babel/parser": "^8.0.10",
|
|
55
55
|
"@entwico/dash": "^1.3.0"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
|
-
"@astroscope/node": "^4.
|
|
59
|
-
"@types/node": "^26.6.
|
|
58
|
+
"@astroscope/node": "^4.2.0",
|
|
59
|
+
"@types/node": "^26.6.6",
|
|
60
60
|
"@types/react": "^19.3.0",
|
|
61
|
-
"astro": "^7.
|
|
62
|
-
"react": "^19.3.
|
|
63
|
-
"tsdown": "^0.23.
|
|
61
|
+
"astro": "^7.4.4",
|
|
62
|
+
"react": "^19.3.1",
|
|
63
|
+
"tsdown": "^0.23.4",
|
|
64
64
|
"typescript": "^6.0.3",
|
|
65
|
-
"vite": "^8.3.
|
|
66
|
-
"vitest": "^5.0.
|
|
65
|
+
"vite": "^8.3.5",
|
|
66
|
+
"vitest": "^5.0.5"
|
|
67
67
|
},
|
|
68
68
|
"peerDependencies": {
|
|
69
|
-
"@astroscope/node": "^4.
|
|
69
|
+
"@astroscope/node": "^4.2.0",
|
|
70
70
|
"astro": "^7.0.0",
|
|
71
71
|
"react": "^18.0.0 || ^19.0.0",
|
|
72
72
|
"vite": "^8.0.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types-v_ftArqH.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;;;;;;;;UAciB,gBAAgB;WACtB;WACA;EACT,OAAO,aAAa;;;;;;EAMpB,IAAI,MAAM,aAAa;EACvB,UAAU,KAAK,MAAM,aAAa;;;;;;;KAQxB,gBAAgB,MAAM,SAAS,eAAe,gBAAgB,QAAQ;;KAGtE,mBAAmB;EAC7B,SAAS,gBAAgB;;;;;;EAMzB;;;;;;;UASe;;KAGL,gBAAgB,QAAQ,WAAW,IAAI,EAAE,WAAW,eAAe,KAAK;;KAGxE,0BAA0B,WAAW,mBAAmB,SAAS,iBAAiB"}
|