@satilian/plugin-mf 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +522 -2
- package/dist/build/bootstrap.d.ts +9 -0
- package/dist/build/bootstrap.js +51 -0
- package/dist/build/build-expose.d.ts +11 -0
- package/dist/build/build-expose.js +142 -0
- package/dist/build/build-release.d.ts +12 -0
- package/dist/build/build-release.js +61 -0
- package/dist/build/build-types.d.ts +7 -0
- package/dist/build/build-types.js +88 -0
- package/dist/build/config.d.ts +14 -0
- package/dist/build/config.js +1 -0
- package/dist/build/format-stats.d.ts +8 -0
- package/dist/build/format-stats.js +35 -0
- package/dist/build/plugin.d.ts +3 -0
- package/dist/build/plugin.js +87 -0
- package/dist/build/resolver.d.ts +1 -0
- package/dist/build/resolver.js +13 -0
- package/dist/build/shared-dependencies.d.ts +2 -0
- package/dist/build/shared-dependencies.js +56 -0
- package/dist/build/sync-types.d.ts +7 -0
- package/dist/build/sync-types.js +202 -0
- package/dist/build/type-cache.d.ts +13 -0
- package/dist/build/type-cache.js +160 -0
- package/dist/build/types-cli.d.ts +2 -0
- package/dist/build/types-cli.js +99 -0
- package/dist/build/types-options.d.ts +11 -0
- package/dist/build/types-options.js +10 -0
- package/dist/client.d.ts +12 -0
- package/dist/client.js +6 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +2 -0
- package/dist/protocol/asset-path.d.ts +1 -0
- package/dist/protocol/asset-path.js +10 -0
- package/dist/protocol/load-error.d.ts +29 -0
- package/dist/protocol/load-error.js +17 -0
- package/dist/protocol/module.d.ts +12 -0
- package/dist/protocol/module.js +1 -0
- package/dist/protocol/network-policy.d.ts +5 -0
- package/dist/protocol/network-policy.js +1 -0
- package/dist/protocol/observability.d.ts +26 -0
- package/dist/protocol/observability.js +1 -0
- package/dist/protocol/preload.d.ts +16 -0
- package/dist/protocol/preload.js +1 -0
- package/dist/protocol/registry.d.ts +17 -0
- package/dist/protocol/registry.js +75 -0
- package/dist/protocol/release-manifest.d.ts +17 -0
- package/dist/protocol/release-manifest.js +29 -0
- package/dist/protocol/remote-manifest.d.ts +13 -0
- package/dist/protocol/remote-manifest.js +27 -0
- package/dist/protocol/shared-dependencies.d.ts +19 -0
- package/dist/protocol/shared-dependencies.js +20 -0
- package/dist/protocol/ssr-releases.d.ts +4 -0
- package/dist/protocol/ssr-releases.js +22 -0
- package/dist/protocol/type-manifest.d.ts +9 -0
- package/dist/protocol/type-manifest.js +19 -0
- package/dist/protocol/types-lock.d.ts +11 -0
- package/dist/protocol/types-lock.js +33 -0
- package/dist/release-manifest.test.d.ts +1 -0
- package/dist/release-manifest.test.js +119 -0
- package/dist/runtime/client/runtime.d.ts +12 -0
- package/dist/runtime/client/runtime.js +115 -0
- package/dist/runtime/client/runtime.js.LICENSE.txt +1 -0
- package/dist/runtime/core/manifest-loader.d.ts +6 -0
- package/dist/runtime/core/manifest-loader.js +29 -0
- package/dist/runtime/core/preload.d.ts +8 -0
- package/dist/runtime/core/preload.js +45 -0
- package/dist/runtime/core/remote-source.d.ts +32 -0
- package/dist/runtime/core/remote-source.js +159 -0
- package/dist/runtime/react/remote.d.ts +8 -0
- package/dist/runtime/react/remote.js +42 -0
- package/dist/runtime/server/cache/config.d.ts +11 -0
- package/dist/runtime/server/cache/config.js +1 -0
- package/dist/runtime/server/cache/disk-cache.d.ts +10 -0
- package/dist/runtime/server/cache/disk-cache.js +172 -0
- package/dist/runtime/server/cache/entry.d.ts +13 -0
- package/dist/runtime/server/cache/entry.js +47 -0
- package/dist/runtime/server/cache/lock.d.ts +3 -0
- package/dist/runtime/server/cache/lock.js +115 -0
- package/dist/runtime/server/cache/paths.d.ts +2 -0
- package/dist/runtime/server/cache/paths.js +17 -0
- package/dist/runtime/server/cache/prune.d.ts +4 -0
- package/dist/runtime/server/cache/prune.js +88 -0
- package/dist/runtime/server/loader.d.ts +11 -0
- package/dist/runtime/server/loader.js +49 -0
- package/dist/runtime/server/runtime.d.ts +18 -0
- package/dist/runtime/server/runtime.js +106 -0
- package/dist/server.d.ts +13 -0
- package/dist/server.js +6 -0
- package/dist/shared.d.ts +2 -0
- package/dist/shared.js +1 -0
- package/dist/sharing/registry.d.ts +13 -0
- package/dist/sharing/registry.js +69 -0
- package/dist/transport/loading.d.ts +16 -0
- package/dist/transport/loading.js +186 -0
- package/dist/transport/network-policy.d.ts +4 -0
- package/dist/transport/network-policy.js +30 -0
- package/dist/transport/observability.d.ts +9 -0
- package/dist/transport/observability.js +111 -0
- package/dist/transport/registry.d.ts +14 -0
- package/dist/transport/registry.js +96 -0
- package/dist/transport/release-loader.d.ts +4 -0
- package/dist/transport/release-loader.js +12 -0
- package/package.json +74 -6
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import node_path from "node:path";
|
|
3
|
+
import { setTimeout as promises_setTimeout } from "node:timers/promises";
|
|
4
|
+
function hasCode(error, code) {
|
|
5
|
+
return error instanceof Error && "code" in error && error.code === code;
|
|
6
|
+
}
|
|
7
|
+
function isProcessAlive(pid) {
|
|
8
|
+
try {
|
|
9
|
+
process.kill(pid, 0);
|
|
10
|
+
return true;
|
|
11
|
+
} catch (error) {
|
|
12
|
+
if (hasCode(error, "ESRCH")) return false;
|
|
13
|
+
if (hasCode(error, "EPERM")) return true;
|
|
14
|
+
throw error;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
async function ownerIsAlive(directory) {
|
|
18
|
+
try {
|
|
19
|
+
const owner = JSON.parse(await readFile(node_path.join(directory, "owner.json"), "utf8"));
|
|
20
|
+
if (!owner || "object" != typeof owner || !("pid" in owner) || "number" != typeof owner.pid || !Number.isSafeInteger(owner.pid) || owner.pid <= 0) throw new Error(`[plugin-mf] Invalid cache lock owner in ${directory}`);
|
|
21
|
+
return isProcessAlive(owner.pid);
|
|
22
|
+
} catch (error) {
|
|
23
|
+
if (hasCode(error, "ENOENT")) return true;
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
async function tryAcquire(staging, target) {
|
|
28
|
+
try {
|
|
29
|
+
await rename(staging, target);
|
|
30
|
+
return true;
|
|
31
|
+
} catch (error) {
|
|
32
|
+
if (hasCode(error, "EEXIST") || hasCode(error, "ENOTEMPTY") || hasCode(error, "EPERM") || hasCode(error, "EACCES")) try {
|
|
33
|
+
await readFile(node_path.join(target, "owner.json"));
|
|
34
|
+
return false;
|
|
35
|
+
} catch (readError) {
|
|
36
|
+
if (!hasCode(readError, "ENOENT")) throw readError;
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
async function renameLock(source, target, timeoutMs) {
|
|
43
|
+
const deadline = performance.now() + timeoutMs;
|
|
44
|
+
while(true)try {
|
|
45
|
+
await rename(source, target);
|
|
46
|
+
return;
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if ("win32" !== process.platform || performance.now() >= deadline || !(hasCode(error, "EPERM") || hasCode(error, "EACCES") || hasCode(error, "EBUSY"))) throw error;
|
|
49
|
+
await promises_setTimeout(25);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async function withCacheLock(root, timeoutMs, callback, deadlineSignal) {
|
|
53
|
+
const staging = await mkdtemp(node_path.join(root, ".lock-owner-"));
|
|
54
|
+
const target = node_path.join(root, ".lock");
|
|
55
|
+
const recovery = node_path.join(root, ".recovery");
|
|
56
|
+
const deadline = performance.now() + timeoutMs;
|
|
57
|
+
let acquired = false;
|
|
58
|
+
try {
|
|
59
|
+
await writeFile(node_path.join(staging, "owner.json"), JSON.stringify({
|
|
60
|
+
pid: process.pid
|
|
61
|
+
}), "utf8");
|
|
62
|
+
while(!acquired){
|
|
63
|
+
deadlineSignal?.throwIfAborted();
|
|
64
|
+
let recovering = false;
|
|
65
|
+
try {
|
|
66
|
+
await readFile(node_path.join(recovery, "owner.json"));
|
|
67
|
+
recovering = true;
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (!hasCode(error, "ENOENT")) throw error;
|
|
70
|
+
}
|
|
71
|
+
if (recovering && !await ownerIsAlive(recovery)) throw new Error(`[plugin-mf] Interrupted cache lock recovery in ${root}; stop cache users before removing .recovery`);
|
|
72
|
+
if (!recovering) {
|
|
73
|
+
acquired = await tryAcquire(staging, target);
|
|
74
|
+
if (!acquired && !await ownerIsAlive(target)) {
|
|
75
|
+
const recoveryOwner = await mkdtemp(node_path.join(root, ".recovery-owner-"));
|
|
76
|
+
await writeFile(node_path.join(recoveryOwner, "owner.json"), JSON.stringify({
|
|
77
|
+
pid: process.pid
|
|
78
|
+
}), "utf8");
|
|
79
|
+
if (await tryAcquire(recoveryOwner, recovery)) try {
|
|
80
|
+
if (!await ownerIsAlive(target)) {
|
|
81
|
+
const retired = await mkdtemp(node_path.join(root, ".retired-lock-"));
|
|
82
|
+
await rm(retired, {
|
|
83
|
+
recursive: true
|
|
84
|
+
});
|
|
85
|
+
await renameLock(target, retired, timeoutMs);
|
|
86
|
+
await rm(retired, {
|
|
87
|
+
recursive: true
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
} finally{
|
|
91
|
+
await renameLock(recovery, recoveryOwner, timeoutMs);
|
|
92
|
+
await rm(recoveryOwner, {
|
|
93
|
+
recursive: true
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
else await rm(recoveryOwner, {
|
|
97
|
+
recursive: true
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (!acquired) {
|
|
102
|
+
if (performance.now() >= deadline) throw new Error(`[plugin-mf] Timed out waiting for cache lock in ${root}`);
|
|
103
|
+
await promises_setTimeout(25);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return await callback();
|
|
107
|
+
} finally{
|
|
108
|
+
if (acquired) await renameLock(target, staging, timeoutMs);
|
|
109
|
+
await rm(staging, {
|
|
110
|
+
recursive: true,
|
|
111
|
+
force: true
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
export { hasCode, isProcessAlive, withCacheLock };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { lstat, realpath } from "node:fs/promises";
|
|
2
|
+
import node_path from "node:path";
|
|
3
|
+
function inside(root, relative) {
|
|
4
|
+
const target = node_path.resolve(root, relative);
|
|
5
|
+
const difference = node_path.relative(root, target);
|
|
6
|
+
if (!difference || ".." === difference || difference.startsWith(`..${node_path.sep}`) || node_path.isAbsolute(difference)) throw new Error("[plugin-mf] Cache path escapes its directory");
|
|
7
|
+
return target;
|
|
8
|
+
}
|
|
9
|
+
async function regularFile(root, file) {
|
|
10
|
+
const target = inside(root, file);
|
|
11
|
+
const info = await lstat(target);
|
|
12
|
+
if (!info.isFile() || info.isSymbolicLink()) throw new Error(`[plugin-mf] Invalid cached file: ${file}`);
|
|
13
|
+
const canonical = await realpath(target);
|
|
14
|
+
inside(root, node_path.relative(root, canonical));
|
|
15
|
+
return info.size;
|
|
16
|
+
}
|
|
17
|
+
export { inside, regularFile };
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { CachePruneResult } from "./config.ts";
|
|
2
|
+
export declare function isPinned(directory: string): Promise<boolean>;
|
|
3
|
+
export declare function entrySize(directory: string): Promise<number>;
|
|
4
|
+
export declare function prune(root: string, maxBytes: number, protectedDirectory?: string, staging?: string): Promise<CachePruneResult>;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { lstat, readdir, rm, stat } from "node:fs/promises";
|
|
2
|
+
import node_path from "node:path";
|
|
3
|
+
import { hasCode, isProcessAlive } from "./lock.js";
|
|
4
|
+
import { inside } from "./paths.js";
|
|
5
|
+
import { emitLoadingEvent } from "../../../transport/observability.js";
|
|
6
|
+
async function isPinned(directory) {
|
|
7
|
+
const pins = node_path.join(directory, ".pins");
|
|
8
|
+
let names;
|
|
9
|
+
try {
|
|
10
|
+
if ((await lstat(pins)).isSymbolicLink()) throw new Error("[plugin-mf] Cache lease directory must not be a symbolic link");
|
|
11
|
+
names = await readdir(pins);
|
|
12
|
+
} catch (error) {
|
|
13
|
+
if (hasCode(error, "ENOENT")) return false;
|
|
14
|
+
throw error;
|
|
15
|
+
}
|
|
16
|
+
let active = false;
|
|
17
|
+
for (const name of names){
|
|
18
|
+
if (!/^\d+$/.test(name)) throw new Error("[plugin-mf] Invalid cache lease");
|
|
19
|
+
const pid = Number(name);
|
|
20
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error("[plugin-mf] Invalid cache lease PID");
|
|
21
|
+
if (isProcessAlive(pid)) active = true;
|
|
22
|
+
else await rm(node_path.join(pins, name), {
|
|
23
|
+
force: true
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
return active;
|
|
27
|
+
}
|
|
28
|
+
async function entrySize(directory) {
|
|
29
|
+
if ((await lstat(directory)).isSymbolicLink()) throw new Error("[plugin-mf] Cache entry must not be a symbolic link");
|
|
30
|
+
let bytes = 0;
|
|
31
|
+
for (const item of (await readdir(directory, {
|
|
32
|
+
withFileTypes: true
|
|
33
|
+
}))){
|
|
34
|
+
if (".pins" === item.name) continue;
|
|
35
|
+
if (item.isSymbolicLink()) throw new Error("[plugin-mf] Cache entry contains a symbolic link");
|
|
36
|
+
const file = node_path.join(directory, item.name);
|
|
37
|
+
bytes += item.isDirectory() ? await entrySize(file) : (await stat(file)).size;
|
|
38
|
+
}
|
|
39
|
+
return bytes;
|
|
40
|
+
}
|
|
41
|
+
async function prune(root, maxBytes, protectedDirectory, staging) {
|
|
42
|
+
for (const name of (await readdir(root))){
|
|
43
|
+
if (!/^\.download-[a-zA-Z0-9]+$/.test(name)) continue;
|
|
44
|
+
const directory = inside(root, name);
|
|
45
|
+
if (directory !== staging) await rm(directory, {
|
|
46
|
+
recursive: true,
|
|
47
|
+
force: true
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
const entries = node_path.join(root, "entries");
|
|
51
|
+
const candidates = [];
|
|
52
|
+
for (const name of (await readdir(entries)).sort()){
|
|
53
|
+
if (!/^[a-f0-9]{64}$/.test(name)) throw new Error("[plugin-mf] Unexpected directory in server cache");
|
|
54
|
+
const directory = inside(entries, name);
|
|
55
|
+
candidates.push({
|
|
56
|
+
directory,
|
|
57
|
+
bytes: await entrySize(directory),
|
|
58
|
+
pinned: directory === protectedDirectory || await isPinned(directory)
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
let bytes = candidates.reduce((sum, entry)=>sum + entry.bytes, 0);
|
|
62
|
+
const protectedBytes = candidates.filter((entry)=>entry.pinned).reduce((sum, entry)=>sum + entry.bytes, 0);
|
|
63
|
+
let removedEntries = 0;
|
|
64
|
+
for (const entry of candidates){
|
|
65
|
+
if (bytes <= maxBytes) break;
|
|
66
|
+
if (!entry.pinned) {
|
|
67
|
+
await rm(entry.directory, {
|
|
68
|
+
recursive: true
|
|
69
|
+
});
|
|
70
|
+
emitLoadingEvent({
|
|
71
|
+
remote: "cache://server",
|
|
72
|
+
stage: "module",
|
|
73
|
+
type: "prune",
|
|
74
|
+
operation: "disk",
|
|
75
|
+
bytes: entry.bytes
|
|
76
|
+
});
|
|
77
|
+
bytes -= entry.bytes;
|
|
78
|
+
removedEntries++;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
bytes,
|
|
83
|
+
protectedBytes,
|
|
84
|
+
removedEntries,
|
|
85
|
+
overBudgetBytes: Math.max(0, bytes - maxBytes)
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
export { entrySize, isPinned, prune };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ModuleLoadContext, ModuleLoader, RemoteModule } from "../../protocol/module.ts";
|
|
2
|
+
import type { ServerCacheOptions, CachePruneResult } from "./cache/config.ts";
|
|
3
|
+
export type { ServerCacheOptions, CachePruneResult } from "./cache/config.ts";
|
|
4
|
+
export type ServerModule = RemoteModule;
|
|
5
|
+
export declare class Loader implements ModuleLoader {
|
|
6
|
+
#private;
|
|
7
|
+
constructor(options?: string | ServerCacheOptions);
|
|
8
|
+
load(url: string, context?: ModuleLoadContext): Promise<RemoteModule>;
|
|
9
|
+
pruneCache(): Promise<CachePruneResult>;
|
|
10
|
+
clearCache(): Promise<CachePruneResult>;
|
|
11
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { pathToFileURL } from "node:url";
|
|
2
|
+
import { DiskCache } from "./cache/disk-cache.js";
|
|
3
|
+
import { describe } from "./cache/entry.js";
|
|
4
|
+
import { loadingPolicy, withDeadline } from "../../transport/loading.js";
|
|
5
|
+
import { emitLoadingEvent, observeLoading } from "../../transport/observability.js";
|
|
6
|
+
class Loader {
|
|
7
|
+
#import = new Function("fileUrl", "return import(fileUrl)");
|
|
8
|
+
#cache = new Map();
|
|
9
|
+
#disk;
|
|
10
|
+
constructor(options = {}){
|
|
11
|
+
this.#disk = new DiskCache(options);
|
|
12
|
+
}
|
|
13
|
+
load(url, context) {
|
|
14
|
+
const entry = describe(url, context);
|
|
15
|
+
const memoryKey = entry.key + ":" + url;
|
|
16
|
+
const loadContext = {
|
|
17
|
+
remote: context?.provider ?? new URL(".", url).href,
|
|
18
|
+
releaseId: context?.releaseId,
|
|
19
|
+
stage: "module"
|
|
20
|
+
};
|
|
21
|
+
const cached = this.#cache.get(memoryKey);
|
|
22
|
+
if (cached) {
|
|
23
|
+
emitLoadingEvent({
|
|
24
|
+
...loadContext,
|
|
25
|
+
type: "cache-hit",
|
|
26
|
+
operation: "module"
|
|
27
|
+
});
|
|
28
|
+
return cached;
|
|
29
|
+
}
|
|
30
|
+
const promise = observeLoading(loadContext, "module", ()=>withDeadline(loadContext, loadingPolicy().moduleTimeoutMs, (deadlineSignal)=>this.#load(entry, loadContext, deadlineSignal))).catch((error)=>{
|
|
31
|
+
this.#cache.delete(memoryKey);
|
|
32
|
+
throw error;
|
|
33
|
+
});
|
|
34
|
+
this.#cache.set(memoryKey, promise);
|
|
35
|
+
return promise;
|
|
36
|
+
}
|
|
37
|
+
async #load(entry, context, deadlineSignal) {
|
|
38
|
+
const localPath = await this.#disk.resolve(entry, context, deadlineSignal);
|
|
39
|
+
deadlineSignal.throwIfAborted();
|
|
40
|
+
return this.#import(pathToFileURL(localPath).href);
|
|
41
|
+
}
|
|
42
|
+
pruneCache() {
|
|
43
|
+
return this.#disk.pruneCache();
|
|
44
|
+
}
|
|
45
|
+
clearCache() {
|
|
46
|
+
return this.#disk.clearCache();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export { Loader };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Remote } from "../react/remote.ts";
|
|
2
|
+
import { type ComponentType } from "react";
|
|
3
|
+
import { type SSRReleases } from "../../protocol/ssr-releases.ts";
|
|
4
|
+
import { type ServerCacheOptions } from "./loader.ts";
|
|
5
|
+
import type { PreloadOptions, PreloadTarget } from "../../protocol/preload.ts";
|
|
6
|
+
export { Loader } from "./loader.ts";
|
|
7
|
+
export type { ServerCacheOptions, CachePruneResult } from "./loader.ts";
|
|
8
|
+
export declare function configureServerCache(options: ServerCacheOptions): void;
|
|
9
|
+
export declare function runWithMFRequest<T>(callback: () => T, options?: {
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
requestId?: string;
|
|
12
|
+
selectionKey?: string;
|
|
13
|
+
}): T;
|
|
14
|
+
export declare function getMFReleases(): SSRReleases;
|
|
15
|
+
export declare function serializeMFReleases(): string;
|
|
16
|
+
export declare function getRemote(name: string): Remote;
|
|
17
|
+
export declare function preloadRemotes(targets: PreloadTarget[], options?: PreloadOptions): Promise<void>;
|
|
18
|
+
export declare function createRemoteComponent<Props extends object = Record<string, unknown>>(remoteName: string, expose: string): ComponentType<Props>;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { Remote } from "../react/remote.js";
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
import { createElement } from "react";
|
|
4
|
+
import { MF_RELEASES_ELEMENT_ID } from "../../protocol/ssr-releases.js";
|
|
5
|
+
import { Loader } from "./loader.js";
|
|
6
|
+
import { configureLoading } from "../../transport/loading.js";
|
|
7
|
+
import { RemoteLoadError } from "../../protocol/load-error.js";
|
|
8
|
+
import { configureNetwork } from "../../transport/network-policy.js";
|
|
9
|
+
import { setObservationContext } from "../../transport/observability.js";
|
|
10
|
+
import { preload } from "../core/preload.js";
|
|
11
|
+
import { getRegistryOverrides, registerStaticRemotes } from "../../transport/registry.js";
|
|
12
|
+
import { MF_REGISTRY_ELEMENT_ID, findRegistrySelection } from "../../protocol/registry.js";
|
|
13
|
+
const remotes = new Map();
|
|
14
|
+
let registryInitialized = false;
|
|
15
|
+
const registryKey = Symbol.for("plugin-mf.ssr-request-registry");
|
|
16
|
+
const registryGlobal = globalThis;
|
|
17
|
+
const requestRegistry = registryGlobal[registryKey] ??= new AsyncLocalStorage();
|
|
18
|
+
const requestContextKey = Symbol.for("plugin-mf.ssr-request-context");
|
|
19
|
+
const requestGlobal = globalThis;
|
|
20
|
+
const requestContext = requestGlobal[requestContextKey] ??= new AsyncLocalStorage();
|
|
21
|
+
const signalKey = Symbol.for("plugin-mf.ssr-request-signal");
|
|
22
|
+
const signalGlobal = globalThis;
|
|
23
|
+
const requestSignal = signalGlobal[signalKey] ??= new AsyncLocalStorage();
|
|
24
|
+
const traceKey = Symbol.for("plugin-mf.ssr-request-trace");
|
|
25
|
+
const traceGlobal = globalThis;
|
|
26
|
+
const requestTrace = traceGlobal[traceKey] ??= new AsyncLocalStorage();
|
|
27
|
+
setObservationContext(()=>({
|
|
28
|
+
requestId: requestTrace.getStore()
|
|
29
|
+
}));
|
|
30
|
+
const runtimeKey = Symbol.for("plugin-mf.server-runtime");
|
|
31
|
+
const runtimeGlobal = globalThis;
|
|
32
|
+
const runtime = runtimeGlobal[runtimeKey] ??= {};
|
|
33
|
+
function configureServerCache(options) {
|
|
34
|
+
if (runtime.loader) throw new Error("[plugin-mf] Configure the server cache before creating remotes");
|
|
35
|
+
runtime.options = {
|
|
36
|
+
...options
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function getLoader() {
|
|
40
|
+
return runtime.loader ??= new Loader(runtime.options);
|
|
41
|
+
}
|
|
42
|
+
function runWithMFRequest(callback, options = {}) {
|
|
43
|
+
initializeRegistry();
|
|
44
|
+
return requestRegistry.run(getRegistryOverrides(options.selectionKey), ()=>requestTrace.run(options.requestId, ()=>requestSignal.run(options.signal, ()=>requestContext.run(new Map(), callback))));
|
|
45
|
+
}
|
|
46
|
+
function getMFReleases() {
|
|
47
|
+
const requestRemotes = requestContext.getStore();
|
|
48
|
+
if (!requestRemotes) throw new Error("[plugin-mf] getMFReleases requires runWithMFRequest");
|
|
49
|
+
const releases = {};
|
|
50
|
+
for (const [url, remote] of requestRemotes){
|
|
51
|
+
const release = remote.getSelectedRelease();
|
|
52
|
+
if (void 0 !== release) releases[url] = release;
|
|
53
|
+
}
|
|
54
|
+
return releases;
|
|
55
|
+
}
|
|
56
|
+
function serializeMFReleases() {
|
|
57
|
+
const json = JSON.stringify(getMFReleases()).replace(/</g, "\\u003c");
|
|
58
|
+
const registry = JSON.stringify(requestRegistry.getStore() ?? {}).replace(/</g, "\\u003c");
|
|
59
|
+
return `<script id="${MF_RELEASES_ELEMENT_ID}" type="application/json">${json}</script><script id="${MF_REGISTRY_ELEMENT_ID}" type="application/json">${registry}</script>`;
|
|
60
|
+
}
|
|
61
|
+
if ("u" > typeof __MF_NETWORK__) configureNetwork(__MF_NETWORK__);
|
|
62
|
+
if ("u" > typeof __MF_LOADING__) configureLoading(__MF_LOADING__);
|
|
63
|
+
function initializeRegistry() {
|
|
64
|
+
if (registryInitialized) return;
|
|
65
|
+
registerStaticRemotes("u" < typeof __MF_REMOTES__ ? {} : __MF_REMOTES__ ?? {});
|
|
66
|
+
registryInitialized = true;
|
|
67
|
+
}
|
|
68
|
+
function getRemote(name) {
|
|
69
|
+
initializeRegistry();
|
|
70
|
+
const selection = findRegistrySelection(name, "u" < typeof __MF_REMOTES__ ? void 0 : __MF_REMOTES__?.[name], requestRegistry.getStore() ?? getRegistryOverrides());
|
|
71
|
+
if (!selection || false === selection.enabled) throw new RemoteLoadError({
|
|
72
|
+
remote: name,
|
|
73
|
+
stage: "module"
|
|
74
|
+
}, "LOAD_FAILED", selection ? "Remote is disabled" : "Remote not found in registry");
|
|
75
|
+
const requestRemotes = requestContext.getStore();
|
|
76
|
+
if (requestRemotes) {
|
|
77
|
+
const key = selection.url;
|
|
78
|
+
let remote = requestRemotes.get(key);
|
|
79
|
+
if (!remote) {
|
|
80
|
+
remote = new Remote(selection.url, getLoader(), "server", ()=>selection.release, requestSignal.getStore());
|
|
81
|
+
requestRemotes.set(key, remote);
|
|
82
|
+
}
|
|
83
|
+
return remote;
|
|
84
|
+
}
|
|
85
|
+
const identity = JSON.stringify(selection);
|
|
86
|
+
const cached = remotes.get(name);
|
|
87
|
+
if (cached?.identity === identity) return cached.remote;
|
|
88
|
+
const remote = new Remote(selection.url, getLoader(), "server", ()=>selection.release);
|
|
89
|
+
remotes.set(name, {
|
|
90
|
+
identity,
|
|
91
|
+
remote
|
|
92
|
+
});
|
|
93
|
+
return remote;
|
|
94
|
+
}
|
|
95
|
+
function preloadRemotes(targets, options) {
|
|
96
|
+
return preload(targets.map(({ remote, expose })=>({
|
|
97
|
+
source: getRemote(remote),
|
|
98
|
+
expose
|
|
99
|
+
})), options);
|
|
100
|
+
}
|
|
101
|
+
function createRemoteComponent(remoteName, expose) {
|
|
102
|
+
return function(props) {
|
|
103
|
+
return createElement(getRemote(remoteName).lazyComponent(expose), props);
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
export { Loader, configureServerCache, createRemoteComponent, getMFReleases, getRemote, preloadRemotes, runWithMFRequest, serializeMFReleases };
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { Loader, configureServerCache, runWithMFRequest, getMFReleases, serializeMFReleases, getRemote, createRemoteComponent, preloadRemotes } from "./runtime/server/runtime.ts";
|
|
2
|
+
export type { PreloadTarget, PreloadOptions } from "./protocol/preload.ts";
|
|
3
|
+
export { configureRegistry, refreshRegistry, getRegistrySnapshot } from "./transport/registry.ts";
|
|
4
|
+
export type { RegistryOptions } from "./transport/registry.ts";
|
|
5
|
+
export type { RegistryConfig, RegistryEntry, RegistrySelection, RegistrySnapshot } from "./protocol/registry.ts";
|
|
6
|
+
export type { ServerCacheOptions, CachePruneResult } from "./runtime/server/runtime.ts";
|
|
7
|
+
export { configureLoading } from "./transport/loading.ts";
|
|
8
|
+
export { configureObservability, getLoadingMetrics } from "./transport/observability.ts";
|
|
9
|
+
export type { LoadingEvent, LoadingEventHandler, LoadingMetrics } from "./protocol/observability.ts";
|
|
10
|
+
export { configureNetwork } from "./transport/network-policy.ts";
|
|
11
|
+
export type { NetworkOptions } from "./protocol/network-policy.ts";
|
|
12
|
+
export { RemoteLoadError } from "./protocol/load-error.ts";
|
|
13
|
+
export type { LoadingOptions, LoadStage, LoadErrorCode } from "./protocol/load-error.ts";
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { Loader, configureServerCache, createRemoteComponent, getMFReleases, getRemote, preloadRemotes, runWithMFRequest, serializeMFReleases } from "./runtime/server/runtime.js";
|
|
2
|
+
export { configureRegistry, getRegistrySnapshot, refreshRegistry } from "./transport/registry.js";
|
|
3
|
+
export { configureLoading } from "./transport/loading.js";
|
|
4
|
+
export { configureObservability, getLoadingMetrics } from "./transport/observability.js";
|
|
5
|
+
export { configureNetwork } from "./transport/network-policy.js";
|
|
6
|
+
export { RemoteLoadError } from "./protocol/load-error.js";
|
package/dist/shared.d.ts
ADDED
package/dist/shared.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { assertSharedRequirements, getShareScope, getShared, registerShared } from "./sharing/registry.js";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { SharedRequirements } from "../protocol/shared-dependencies.ts";
|
|
2
|
+
type SharedEntry = {
|
|
3
|
+
get: () => Promise<unknown>;
|
|
4
|
+
loaded: boolean;
|
|
5
|
+
version: string;
|
|
6
|
+
module: unknown;
|
|
7
|
+
singleton: boolean;
|
|
8
|
+
};
|
|
9
|
+
export declare function registerShared(name: string, module: unknown, version?: string, scope?: string, singleton?: boolean): void;
|
|
10
|
+
export declare function getShared(name: string, scope?: string, requiredVersion?: string): unknown;
|
|
11
|
+
export declare function assertSharedRequirements(requirements: SharedRequirements, scope?: string): void;
|
|
12
|
+
export declare function getShareScope(): Record<string, Record<string, SharedEntry>>;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import satisfies from "semver/functions/satisfies.js";
|
|
2
|
+
import rcompare from "semver/functions/rcompare.js";
|
|
3
|
+
import valid from "semver/functions/valid.js";
|
|
4
|
+
const key = Symbol.for("plugin-mf.shared-registry");
|
|
5
|
+
const sharedGlobal = globalThis;
|
|
6
|
+
const registry = sharedGlobal[key] ??= new Map();
|
|
7
|
+
function registerShared(name, module, version = "0.0.0", scope = "default", singleton = true) {
|
|
8
|
+
if (!valid(version)) throw new Error(`[plugin-mf] Invalid shared version for ${name}: ${version}`);
|
|
9
|
+
let bucket = registry.get(scope);
|
|
10
|
+
if (!bucket) registry.set(scope, bucket = new Map());
|
|
11
|
+
let versions = bucket.get(name);
|
|
12
|
+
if (!versions) bucket.set(name, versions = new Map());
|
|
13
|
+
const existing = versions.get(version);
|
|
14
|
+
if (existing) {
|
|
15
|
+
existing.singleton ||= singleton;
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
if (versions.size && (singleton || [
|
|
19
|
+
...versions.values()
|
|
20
|
+
].some((entry)=>entry.singleton))) throw new Error(`[plugin-mf] Shared singleton ${name} already registered at ${[
|
|
21
|
+
...versions.keys()
|
|
22
|
+
].join(", ")}; cannot register ${version}`);
|
|
23
|
+
versions.set(version, {
|
|
24
|
+
get: ()=>Promise.resolve(module),
|
|
25
|
+
module,
|
|
26
|
+
loaded: true,
|
|
27
|
+
version,
|
|
28
|
+
singleton
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
function getShared(name, scope = "default", requiredVersion = "*") {
|
|
32
|
+
const versions = registry.get(scope)?.get(name);
|
|
33
|
+
const version = versions && [
|
|
34
|
+
...versions.keys()
|
|
35
|
+
].sort(rcompare).find((version)=>satisfies(version, requiredVersion));
|
|
36
|
+
if (!version) throw new Error(`[plugin-mf] Shared ${name} requires ${requiredVersion}; registered: ${versions ? [
|
|
37
|
+
...versions.keys()
|
|
38
|
+
].join(", ") : "none"}`);
|
|
39
|
+
return versions?.get(version)?.module;
|
|
40
|
+
}
|
|
41
|
+
function assertSharedRequirements(requirements, scope = "default") {
|
|
42
|
+
for (const [name, requirement] of Object.entries(requirements)){
|
|
43
|
+
const versions = registry.get(scope)?.get(name);
|
|
44
|
+
if (requirement.singleton && versions && versions.size > 1) throw new Error(`[plugin-mf] Shared ${name} requires a singleton; registered: ${[
|
|
45
|
+
...versions.keys()
|
|
46
|
+
].join(", ")}`);
|
|
47
|
+
getShared(name, scope, requirement.requiredVersion);
|
|
48
|
+
if (requirement.singleton && versions) for (const entry of versions.values())entry.singleton = true;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function getShareScope() {
|
|
52
|
+
return Object.fromEntries([
|
|
53
|
+
...registry
|
|
54
|
+
].map(([scope, modules])=>[
|
|
55
|
+
scope,
|
|
56
|
+
Object.fromEntries([
|
|
57
|
+
...modules
|
|
58
|
+
].map(([name, versions])=>{
|
|
59
|
+
const entry = [
|
|
60
|
+
...versions.values()
|
|
61
|
+
].sort((a, b)=>rcompare(a.version, b.version))[0];
|
|
62
|
+
return [
|
|
63
|
+
name,
|
|
64
|
+
entry
|
|
65
|
+
];
|
|
66
|
+
}))
|
|
67
|
+
]));
|
|
68
|
+
}
|
|
69
|
+
export { assertSharedRequirements, getShareScope, getShared, registerShared };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { RemoteLoadError, type LoadContext, type LoadingOptions } from "../protocol/load-error.ts";
|
|
2
|
+
type Policy = Required<Omit<LoadingOptions, "circuitBreaker">> & {
|
|
3
|
+
circuitBreaker: {
|
|
4
|
+
failureThreshold: number;
|
|
5
|
+
cooldownMs: number;
|
|
6
|
+
};
|
|
7
|
+
};
|
|
8
|
+
export declare function configureLoading(options: LoadingOptions): void;
|
|
9
|
+
export declare function loadingPolicy(): Readonly<Policy>;
|
|
10
|
+
export declare function loadError(error: unknown, context: LoadContext): RemoteLoadError;
|
|
11
|
+
export declare function withDeadline<T>(context: LoadContext, timeoutMs: number, callback: (signal: AbortSignal) => Promise<T>, parent?: AbortSignal): Promise<T>;
|
|
12
|
+
export declare function retryNetwork<T>(callback: (attempt: number) => Promise<T>, signal: AbortSignal, retryable?: (error: unknown) => boolean, context?: LoadContext): Promise<T>;
|
|
13
|
+
export declare function fetchResource<T>(url: string, context: LoadContext, read: (response: Response) => Promise<T>, signal?: AbortSignal): Promise<T>;
|
|
14
|
+
export declare function fetchResource<T>(url: string, context: LoadContext, read: (response: Response) => Promise<T>, signal: AbortSignal | undefined, allow404: true): Promise<T | undefined>;
|
|
15
|
+
export declare function withProvider<T>(context: LoadContext, callback: () => Promise<T>): Promise<T>;
|
|
16
|
+
export {};
|