@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.
Files changed (103) hide show
  1. package/README.md +522 -2
  2. package/dist/build/bootstrap.d.ts +9 -0
  3. package/dist/build/bootstrap.js +51 -0
  4. package/dist/build/build-expose.d.ts +11 -0
  5. package/dist/build/build-expose.js +142 -0
  6. package/dist/build/build-release.d.ts +12 -0
  7. package/dist/build/build-release.js +61 -0
  8. package/dist/build/build-types.d.ts +7 -0
  9. package/dist/build/build-types.js +88 -0
  10. package/dist/build/config.d.ts +14 -0
  11. package/dist/build/config.js +1 -0
  12. package/dist/build/format-stats.d.ts +8 -0
  13. package/dist/build/format-stats.js +35 -0
  14. package/dist/build/plugin.d.ts +3 -0
  15. package/dist/build/plugin.js +87 -0
  16. package/dist/build/resolver.d.ts +1 -0
  17. package/dist/build/resolver.js +13 -0
  18. package/dist/build/shared-dependencies.d.ts +2 -0
  19. package/dist/build/shared-dependencies.js +56 -0
  20. package/dist/build/sync-types.d.ts +7 -0
  21. package/dist/build/sync-types.js +202 -0
  22. package/dist/build/type-cache.d.ts +13 -0
  23. package/dist/build/type-cache.js +160 -0
  24. package/dist/build/types-cli.d.ts +2 -0
  25. package/dist/build/types-cli.js +99 -0
  26. package/dist/build/types-options.d.ts +11 -0
  27. package/dist/build/types-options.js +10 -0
  28. package/dist/client.d.ts +12 -0
  29. package/dist/client.js +6 -0
  30. package/dist/index.d.ts +8 -0
  31. package/dist/index.js +2 -0
  32. package/dist/protocol/asset-path.d.ts +1 -0
  33. package/dist/protocol/asset-path.js +10 -0
  34. package/dist/protocol/load-error.d.ts +29 -0
  35. package/dist/protocol/load-error.js +17 -0
  36. package/dist/protocol/module.d.ts +12 -0
  37. package/dist/protocol/module.js +1 -0
  38. package/dist/protocol/network-policy.d.ts +5 -0
  39. package/dist/protocol/network-policy.js +1 -0
  40. package/dist/protocol/observability.d.ts +26 -0
  41. package/dist/protocol/observability.js +1 -0
  42. package/dist/protocol/preload.d.ts +16 -0
  43. package/dist/protocol/preload.js +1 -0
  44. package/dist/protocol/registry.d.ts +17 -0
  45. package/dist/protocol/registry.js +75 -0
  46. package/dist/protocol/release-manifest.d.ts +17 -0
  47. package/dist/protocol/release-manifest.js +29 -0
  48. package/dist/protocol/remote-manifest.d.ts +13 -0
  49. package/dist/protocol/remote-manifest.js +27 -0
  50. package/dist/protocol/shared-dependencies.d.ts +19 -0
  51. package/dist/protocol/shared-dependencies.js +20 -0
  52. package/dist/protocol/ssr-releases.d.ts +4 -0
  53. package/dist/protocol/ssr-releases.js +22 -0
  54. package/dist/protocol/type-manifest.d.ts +9 -0
  55. package/dist/protocol/type-manifest.js +19 -0
  56. package/dist/protocol/types-lock.d.ts +11 -0
  57. package/dist/protocol/types-lock.js +33 -0
  58. package/dist/release-manifest.test.d.ts +1 -0
  59. package/dist/release-manifest.test.js +119 -0
  60. package/dist/runtime/client/runtime.d.ts +12 -0
  61. package/dist/runtime/client/runtime.js +115 -0
  62. package/dist/runtime/client/runtime.js.LICENSE.txt +1 -0
  63. package/dist/runtime/core/manifest-loader.d.ts +6 -0
  64. package/dist/runtime/core/manifest-loader.js +29 -0
  65. package/dist/runtime/core/preload.d.ts +8 -0
  66. package/dist/runtime/core/preload.js +45 -0
  67. package/dist/runtime/core/remote-source.d.ts +32 -0
  68. package/dist/runtime/core/remote-source.js +159 -0
  69. package/dist/runtime/react/remote.d.ts +8 -0
  70. package/dist/runtime/react/remote.js +42 -0
  71. package/dist/runtime/server/cache/config.d.ts +11 -0
  72. package/dist/runtime/server/cache/config.js +1 -0
  73. package/dist/runtime/server/cache/disk-cache.d.ts +10 -0
  74. package/dist/runtime/server/cache/disk-cache.js +172 -0
  75. package/dist/runtime/server/cache/entry.d.ts +13 -0
  76. package/dist/runtime/server/cache/entry.js +47 -0
  77. package/dist/runtime/server/cache/lock.d.ts +3 -0
  78. package/dist/runtime/server/cache/lock.js +115 -0
  79. package/dist/runtime/server/cache/paths.d.ts +2 -0
  80. package/dist/runtime/server/cache/paths.js +17 -0
  81. package/dist/runtime/server/cache/prune.d.ts +4 -0
  82. package/dist/runtime/server/cache/prune.js +88 -0
  83. package/dist/runtime/server/loader.d.ts +11 -0
  84. package/dist/runtime/server/loader.js +49 -0
  85. package/dist/runtime/server/runtime.d.ts +18 -0
  86. package/dist/runtime/server/runtime.js +106 -0
  87. package/dist/server.d.ts +13 -0
  88. package/dist/server.js +6 -0
  89. package/dist/shared.d.ts +2 -0
  90. package/dist/shared.js +1 -0
  91. package/dist/sharing/registry.d.ts +13 -0
  92. package/dist/sharing/registry.js +69 -0
  93. package/dist/transport/loading.d.ts +16 -0
  94. package/dist/transport/loading.js +186 -0
  95. package/dist/transport/network-policy.d.ts +4 -0
  96. package/dist/transport/network-policy.js +30 -0
  97. package/dist/transport/observability.d.ts +9 -0
  98. package/dist/transport/observability.js +111 -0
  99. package/dist/transport/registry.d.ts +14 -0
  100. package/dist/transport/registry.js +96 -0
  101. package/dist/transport/release-loader.d.ts +4 -0
  102. package/dist/transport/release-loader.js +12 -0
  103. package/package.json +74 -6
@@ -0,0 +1,202 @@
1
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import node_path from "node:path";
3
+ import { parseTypeManifest } from "../protocol/type-manifest.js";
4
+ import { parseTypesLock } from "../protocol/types-lock.js";
5
+ import { loadReleaseManifest } from "../transport/release-loader.js";
6
+ import { fetchResource, loadingPolicy, withDeadline, withProvider } from "../transport/loading.js";
7
+ import { atomicWrite, hasCode, publishTypes, readCachedTypes } from "./type-cache.js";
8
+ import { validateTypesOptions } from "./types-options.js";
9
+ import { emitLoadingEvent } from "../transport/observability.js";
10
+ const running = new Map();
11
+ function limiter(concurrency) {
12
+ let active = 0;
13
+ const queue = [];
14
+ return async (callback, signal)=>{
15
+ if (active >= concurrency) await new Promise((resolve)=>queue.push(resolve));
16
+ else active++;
17
+ try {
18
+ signal.throwIfAborted();
19
+ return await callback();
20
+ } finally{
21
+ const next = queue.shift();
22
+ if (next) next();
23
+ else active--;
24
+ }
25
+ };
26
+ }
27
+ function syncTypes(options) {
28
+ const root = node_path.resolve(options.rootPath);
29
+ const previous = running.get(root) ?? Promise.resolve();
30
+ const operation = previous.then(()=>synchronize({
31
+ ...options,
32
+ rootPath: root
33
+ }), ()=>synchronize({
34
+ ...options,
35
+ rootPath: root
36
+ }));
37
+ running.set(root, operation);
38
+ return operation.finally(()=>{
39
+ if (running.get(root) === operation) running.delete(root);
40
+ });
41
+ }
42
+ async function synchronize({ remotes, rootPath, types = {} }) {
43
+ validateTypesOptions(types);
44
+ const mode = types.mode ?? "best-effort";
45
+ if ("off" === mode) return;
46
+ const selected = new Set(types.remotes ?? Object.keys(remotes));
47
+ for (const name of selected)if (!Object.hasOwn(remotes, name)) throw new Error(`[plugin-mf] Unknown types remote: ${name}`);
48
+ const cacheRoot = node_path.join(rootPath, "node_modules", ".cache", "mf-types");
49
+ const lockPath = node_path.resolve(rootPath, types.lockfile ?? "mf-types.lock.json");
50
+ let lock = {
51
+ version: 1,
52
+ remotes: {}
53
+ };
54
+ try {
55
+ lock = parseTypesLock(JSON.parse(await readFile(lockPath, "utf8")));
56
+ } catch (error) {
57
+ if (!hasCode(error, "ENOENT")) throw error;
58
+ if (types.frozenLockfile || types.offline) throw new Error(`[plugin-mf] Types lock file is required: ${lockPath}`, {
59
+ cause: error
60
+ });
61
+ }
62
+ const next = {
63
+ version: 1,
64
+ remotes: {
65
+ ...lock.remotes
66
+ }
67
+ };
68
+ if (types.frozenLockfile) {
69
+ for (const name of selected)if (lock.remotes[name]?.provider !== remotes[name].replace(/\/$/, "")) throw new Error(`[plugin-mf] No matching locked types for remote "${name}"`);
70
+ }
71
+ const limit = limiter(types.concurrency ?? 8);
72
+ const results = await Promise.allSettled(Object.entries(remotes).map(async ([name, url])=>{
73
+ const provider = url.replace(/\/$/, "");
74
+ const previous = lock.remotes[name]?.provider === provider ? lock.remotes[name] : void 0;
75
+ try {
76
+ if (!selected.has(name)) return previous ? await readCachedTypes(cacheRoot, previous) : void 0;
77
+ if ((types.frozenLockfile || types.offline) && !previous) throw new Error(`[plugin-mf] No locked types for remote "${name}"`);
78
+ let cached;
79
+ if (previous) try {
80
+ cached = await readCachedTypes(cacheRoot, previous);
81
+ } catch (error) {
82
+ if (types.offline) throw error;
83
+ console.warn(`[plugin-mf] Types cache unavailable for "${name}": ${message(error)}; downloading locked declarations`);
84
+ }
85
+ if (cached && !types.updateLock) {
86
+ emitLoadingEvent({
87
+ remote: provider,
88
+ releaseId: cached.entry.releaseId,
89
+ stage: "types",
90
+ type: "cache-hit",
91
+ operation: "types"
92
+ });
93
+ return cached;
94
+ }
95
+ if (types.offline) throw new Error(`[plugin-mf] No cached types for remote "${name}"`);
96
+ const context = {
97
+ remote: provider,
98
+ releaseId: previous?.releaseId,
99
+ stage: "types"
100
+ };
101
+ const result = await withProvider(context, ()=>withDeadline(context, loadingPolicy().typesTimeoutMs, (signal)=>downloadTypes(cacheRoot, provider, previous, types.updateLock ?? false, cached, context, signal, limit)));
102
+ next.remotes = {
103
+ ...next.remotes,
104
+ [name]: result.entry
105
+ };
106
+ return result;
107
+ } catch (error) {
108
+ if ("strict" === mode) throw error;
109
+ if (previous) try {
110
+ const cached = await readCachedTypes(cacheRoot, previous);
111
+ console.warn(`[plugin-mf] Using last successful types for "${name}" (release ${previous.releaseId ?? "legacy"}): ${message(error)}`);
112
+ return cached;
113
+ } catch (cacheError) {
114
+ console.warn(`[plugin-mf] Last successful types unavailable for "${name}": ${message(cacheError)}`);
115
+ }
116
+ console.warn(`[plugin-mf] Types unavailable for "${name}"; emitting unknown fallback: ${message(error)}`);
117
+ return;
118
+ }
119
+ }));
120
+ const failures = results.filter((result)=>"rejected" === result.status);
121
+ if (failures.length) throw new AggregateError(failures.map((result)=>result.reason), "[plugin-mf] Types synchronization failed");
122
+ const declarations = [];
123
+ Object.keys(remotes).forEach((name, index)=>{
124
+ const result = results[index];
125
+ if ("fulfilled" !== result.status) return;
126
+ const cached = result.value;
127
+ if (!cached) {
128
+ if (selected.has(name) || lock.remotes[name]) declarations.push(fallbackDeclaration(name));
129
+ return;
130
+ }
131
+ for (const [expose, info] of Object.entries(cached.manifest.exposes)){
132
+ const relative = node_path.relative(node_path.join(rootPath, "src"), node_path.join(cached.directory, info.path)).replace(/\\/g, "/").replace(/\.d\.ts$/, "");
133
+ declarations.push([
134
+ `declare module ${JSON.stringify(`${name}/${expose}`)} {`,
135
+ ` const remote: typeof import(${JSON.stringify(relative.startsWith(".") ? relative : `./${relative}`)})[${JSON.stringify(info.export)}];`,
136
+ " export default remote;",
137
+ "}"
138
+ ].join("\n"));
139
+ }
140
+ });
141
+ if (!types.frozenLockfile && !types.offline && JSON.stringify(next) !== JSON.stringify(lock)) {
142
+ next.remotes = Object.fromEntries(Object.entries(next.remotes).sort(([a], [b])=>a.localeCompare(b)));
143
+ await atomicWrite(lockPath, JSON.stringify(next, null, 2) + "\n");
144
+ }
145
+ await atomicWrite(node_path.join(rootPath, "src", "mf-types.d.ts"), declarations.join("\n") + "\n");
146
+ }
147
+ async function downloadTypes(cacheRoot, provider, previous, update, cached, context, signal, limit) {
148
+ let selection;
149
+ if (previous && !update) selection = previous;
150
+ else {
151
+ const release = await limit(()=>loadReleaseManifest(`${provider}/manifest.json`, {
152
+ remote: provider,
153
+ stage: "release-manifest"
154
+ }, signal), signal);
155
+ selection = {
156
+ provider,
157
+ ...release ? {
158
+ releaseId: release.manifest.releaseId
159
+ } : {},
160
+ manifestUrl: release ? new URL(release.manifest.types, release.baseUrl).href : `${provider}/types/manifest.json`
161
+ };
162
+ }
163
+ context.releaseId = selection.releaseId;
164
+ if (cached && void 0 !== selection.releaseId && previous?.releaseId === selection.releaseId && previous.manifestUrl === selection.manifestUrl) return cached;
165
+ const { manifest, baseUrl } = await limit(()=>fetchResource(selection.manifestUrl, context, async (response)=>({
166
+ manifest: parseTypeManifest(await response.json()),
167
+ baseUrl: new URL(".", response.url)
168
+ }), signal), signal);
169
+ await mkdir(cacheRoot, {
170
+ recursive: true
171
+ });
172
+ const staging = await mkdtemp(node_path.join(cacheRoot, ".download-"));
173
+ try {
174
+ const results = await Promise.allSettled(manifest.files.map((file)=>limit(async ()=>{
175
+ const source = await fetchResource(new URL(file, baseUrl).href, context, (response)=>response.text(), signal);
176
+ signal.throwIfAborted();
177
+ const destination = node_path.join(staging, file);
178
+ await mkdir(node_path.dirname(destination), {
179
+ recursive: true
180
+ });
181
+ await writeFile(destination, source, "utf8");
182
+ }, signal)));
183
+ const failed = results.find((result)=>"rejected" === result.status);
184
+ if (failed?.status === "rejected") throw failed.reason;
185
+ signal.throwIfAborted();
186
+ const result = await publishTypes(cacheRoot, staging, selection, manifest);
187
+ if (previous && !update && result.entry.cacheKey !== previous.cacheKey) throw new Error("[plugin-mf] Locked declarations changed; restore the provider artifact or explicitly update the lock");
188
+ return result;
189
+ } finally{
190
+ await rm(staging, {
191
+ recursive: true,
192
+ force: true
193
+ });
194
+ }
195
+ }
196
+ function fallbackDeclaration(name) {
197
+ return `declare module ${JSON.stringify(`${name}/*`)} {\n const remote: unknown;\n export default remote;\n}`;
198
+ }
199
+ function message(error) {
200
+ return error instanceof Error ? error.message : String(error);
201
+ }
202
+ export { syncTypes };
@@ -0,0 +1,13 @@
1
+ import { type RemoteTypeManifest } from "../protocol/type-manifest.ts";
2
+ import { type TypesLockEntry } from "../protocol/types-lock.ts";
3
+ export type CachedTypes = {
4
+ entry: TypesLockEntry;
5
+ directory: string;
6
+ manifest: RemoteTypeManifest;
7
+ };
8
+ export declare function digest(value: string): string;
9
+ export declare function cacheDirectory(root: string, entry: TypesLockEntry): string;
10
+ export declare function readCachedTypes(root: string, entry: TypesLockEntry): Promise<CachedTypes>;
11
+ export declare function publishTypes(root: string, staging: string, selection: Omit<TypesLockEntry, "cacheKey">, manifest: RemoteTypeManifest): Promise<CachedTypes>;
12
+ export declare function hasCode(error: unknown, code: string): boolean;
13
+ export declare function atomicWrite(file: string, source: string): Promise<void>;
@@ -0,0 +1,160 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import node_path from "node:path";
4
+ import typescript from "typescript";
5
+ import { setTimeout as promises_setTimeout } from "node:timers/promises";
6
+ import { parseTypeManifest } from "../protocol/type-manifest.js";
7
+ import { parseTypesLock } from "../protocol/types-lock.js";
8
+ function digest(value) {
9
+ return createHash("sha256").update(value).digest("hex");
10
+ }
11
+ function keyFor(entry, manifest, hashes) {
12
+ return digest(JSON.stringify([
13
+ entry.provider,
14
+ entry.releaseId ?? null,
15
+ entry.manifestUrl,
16
+ manifest,
17
+ Object.entries(hashes).sort(([a], [b])=>a.localeCompare(b))
18
+ ]));
19
+ }
20
+ function cacheDirectory(root, entry) {
21
+ return node_path.join(root, entry.releaseId ?? "legacy", entry.cacheKey);
22
+ }
23
+ async function readCachedTypes(root, entry) {
24
+ const directory = cacheDirectory(root, entry);
25
+ const metadata = JSON.parse(await readFile(node_path.join(directory, ".ready.json"), "utf8"));
26
+ if (!metadata || "object" != typeof metadata || !("manifest" in metadata) || !("entry" in metadata) || !("hashes" in metadata) || !metadata.hashes || "object" != typeof metadata.hashes) throw new Error("[plugin-mf] Invalid types cache metadata");
27
+ const stored = parseTypesLock({
28
+ version: 1,
29
+ remotes: {
30
+ cached: metadata.entry
31
+ }
32
+ }).remotes.cached;
33
+ if (stored.provider !== entry.provider || stored.releaseId !== entry.releaseId || stored.manifestUrl !== entry.manifestUrl || stored.cacheKey !== entry.cacheKey) throw new Error("[plugin-mf] Types cache identity mismatch");
34
+ const manifest = parseTypeManifest(metadata.manifest);
35
+ const hashes = {};
36
+ for (const file of manifest.files){
37
+ const filePath = node_path.join(directory, file);
38
+ if (!(await lstat(filePath)).isFile()) throw new Error("[plugin-mf] Invalid cached declaration file");
39
+ const hash = digest(await readFile(filePath, "utf8"));
40
+ if (!(file in metadata.hashes) || Reflect.get(metadata.hashes, file) !== hash) throw new Error(`[plugin-mf] Corrupted cached declaration: ${file}`);
41
+ hashes[file] = hash;
42
+ }
43
+ if (keyFor(entry, manifest, hashes) !== entry.cacheKey) throw new Error("[plugin-mf] Types cache checksum mismatch");
44
+ return {
45
+ entry,
46
+ directory,
47
+ manifest
48
+ };
49
+ }
50
+ async function publishTypes(root, staging, selection, manifest) {
51
+ const files = manifest.files.map((file)=>node_path.join(staging, file));
52
+ const available = new Set(files);
53
+ for (const file of files){
54
+ const source = typescript.preProcessFile(await readFile(file, "utf8"), true);
55
+ const references = [
56
+ ...source.importedFiles.filter((item)=>item.fileName.startsWith(".")),
57
+ ...source.referencedFiles
58
+ ];
59
+ for (const reference of references){
60
+ const target = node_path.resolve(node_path.dirname(file), reference.fileName);
61
+ const withoutExtension = target.replace(/\.[cm]?jsx?$/, "");
62
+ if (![
63
+ target,
64
+ `${withoutExtension}.d.ts`,
65
+ node_path.join(target, "index.d.ts")
66
+ ].some((candidate)=>available.has(candidate))) throw new Error(`[plugin-mf] Missing relative declaration: ${reference.fileName} in ${node_path.relative(staging, file)}`);
67
+ }
68
+ }
69
+ const program = typescript.createProgram(files, {
70
+ noEmit: true,
71
+ skipLibCheck: true,
72
+ target: typescript.ScriptTarget.ESNext
73
+ });
74
+ const diagnostics = program.getSyntacticDiagnostics();
75
+ if (diagnostics.length) throw new Error(typescript.formatDiagnostics(diagnostics, {
76
+ getCanonicalFileName: (file)=>file,
77
+ getCurrentDirectory: ()=>staging,
78
+ getNewLine: ()=>"\n"
79
+ }));
80
+ const checker = program.getTypeChecker();
81
+ for (const [name, expose] of Object.entries(manifest.exposes)){
82
+ const source = program.getSourceFile(node_path.join(staging, expose.path));
83
+ const symbol = source && checker.getSymbolAtLocation(source);
84
+ if (!symbol || !checker.getExportsOfModule(symbol).some((item)=>item.name === expose.export)) throw new Error(`[plugin-mf] Declaration export missing: ${name}/${expose.export}`);
85
+ }
86
+ const hashes = {};
87
+ for (const file of manifest.files)hashes[file] = digest(await readFile(node_path.join(staging, file), "utf8"));
88
+ const entry = {
89
+ ...selection,
90
+ cacheKey: keyFor(selection, manifest, hashes)
91
+ };
92
+ const metadata = {
93
+ entry,
94
+ manifest,
95
+ hashes
96
+ };
97
+ await writeFile(node_path.join(staging, ".ready.json"), JSON.stringify(metadata), "utf8");
98
+ const directory = cacheDirectory(root, entry);
99
+ await mkdir(node_path.dirname(directory), {
100
+ recursive: true
101
+ });
102
+ try {
103
+ await rename(staging, directory);
104
+ } catch (error) {
105
+ if (!hasCode(error, "EEXIST") && !hasCode(error, "ENOTEMPTY") && !hasCode(error, "EPERM")) throw error;
106
+ try {
107
+ return await readCachedTypes(root, entry);
108
+ } catch (cacheError) {
109
+ const info = await lstat(directory);
110
+ if (!info.isDirectory() || info.isSymbolicLink()) throw cacheError;
111
+ const retired = node_path.join(root, `.corrupt-${randomUUID()}`);
112
+ await rename(directory, retired);
113
+ try {
114
+ await rename(staging, directory);
115
+ } catch (publishError) {
116
+ await rename(retired, directory);
117
+ throw publishError;
118
+ }
119
+ await rm(retired, {
120
+ recursive: true,
121
+ force: true
122
+ });
123
+ }
124
+ }
125
+ return {
126
+ entry,
127
+ directory,
128
+ manifest
129
+ };
130
+ }
131
+ function hasCode(error, code) {
132
+ return error instanceof Error && "code" in error && error.code === code;
133
+ }
134
+ async function atomicWrite(file, source) {
135
+ try {
136
+ if (await readFile(file, "utf8") === source) return;
137
+ } catch (error) {
138
+ if (!hasCode(error, "ENOENT")) throw error;
139
+ }
140
+ await mkdir(node_path.dirname(file), {
141
+ recursive: true
142
+ });
143
+ const temporary = `${file}.${randomUUID()}.tmp`;
144
+ try {
145
+ await writeFile(temporary, source, "utf8");
146
+ const deadline = performance.now() + 1000;
147
+ while(true)try {
148
+ await rename(temporary, file);
149
+ break;
150
+ } catch (error) {
151
+ if ("win32" !== process.platform || performance.now() >= deadline || !(hasCode(error, "EPERM") || hasCode(error, "EACCES") || hasCode(error, "EBUSY"))) throw error;
152
+ await promises_setTimeout(25);
153
+ }
154
+ } finally{
155
+ await rm(temporary, {
156
+ force: true
157
+ });
158
+ }
159
+ }
160
+ export { atomicWrite, cacheDirectory, digest, hasCode, publishTypes, readCachedTypes };
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,99 @@
1
+ #!/usr/bin/env node
2
+ import { readFile } from "node:fs/promises";
3
+ import node_path from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ import { syncTypes } from "./sync-types.js";
6
+ import { validateTypesOptions } from "./types-options.js";
7
+ async function main() {
8
+ const { values } = parseArgs({
9
+ options: {
10
+ config: {
11
+ type: "string",
12
+ default: "mf-types.config.json"
13
+ },
14
+ mode: {
15
+ type: "string"
16
+ },
17
+ remote: {
18
+ type: "string",
19
+ multiple: true
20
+ },
21
+ offline: {
22
+ type: "boolean"
23
+ },
24
+ "frozen-lockfile": {
25
+ type: "boolean"
26
+ },
27
+ "update-lock": {
28
+ type: "boolean"
29
+ },
30
+ help: {
31
+ type: "boolean",
32
+ short: "h"
33
+ }
34
+ }
35
+ });
36
+ if (values.help) return void console.log("plugin-mf-types [--config mf-types.config.json] [--mode strict|best-effort|off] [--remote name] [--offline] [--frozen-lockfile] [--update-lock]");
37
+ const configPath = node_path.resolve(values.config);
38
+ const config = JSON.parse(await readFile(configPath, "utf8"));
39
+ if (!config || "object" != typeof config || !("remotes" in config) || !config.remotes || "object" != typeof config.remotes || Array.isArray(config.remotes)) throw new Error("[plugin-mf] Types config must contain a remotes object");
40
+ const remotes = {};
41
+ for (const [name, url] of Object.entries(config.remotes)){
42
+ if ("string" != typeof url || ![
43
+ "http:",
44
+ "https:"
45
+ ].includes(new URL(url).protocol)) throw new Error(`[plugin-mf] Invalid provider URL: ${name}`);
46
+ Object.defineProperty(remotes, name, {
47
+ value: url,
48
+ enumerable: true
49
+ });
50
+ }
51
+ const types = {};
52
+ if ("types" in config) {
53
+ if (!config.types || "object" != typeof config.types || Array.isArray(config.types)) throw new Error("[plugin-mf] Invalid types options");
54
+ const options = config.types;
55
+ if ("mode" in options) {
56
+ if ("strict" !== options.mode && "best-effort" !== options.mode && "off" !== options.mode) throw new Error("[plugin-mf] Invalid types mode");
57
+ types.mode = options.mode;
58
+ }
59
+ if ("remotes" in options) {
60
+ if (!Array.isArray(options.remotes) || !options.remotes.every((name)=>"string" == typeof name)) throw new Error("[plugin-mf] Invalid types remotes");
61
+ types.remotes = options.remotes;
62
+ }
63
+ if ("concurrency" in options) {
64
+ if ("number" != typeof options.concurrency) throw new Error("[plugin-mf] Invalid types concurrency");
65
+ types.concurrency = options.concurrency;
66
+ }
67
+ if ("lockfile" in options) {
68
+ if ("string" != typeof options.lockfile) throw new Error("[plugin-mf] Invalid types lockfile");
69
+ types.lockfile = options.lockfile;
70
+ }
71
+ for (const name of [
72
+ "offline",
73
+ "frozenLockfile",
74
+ "updateLock"
75
+ ])if (name in options) {
76
+ const value = Reflect.get(options, name);
77
+ if ("boolean" != typeof value) throw new Error(`[plugin-mf] Invalid types option: ${name}`);
78
+ types[name] = value;
79
+ }
80
+ }
81
+ if (void 0 !== values.mode) {
82
+ if ("strict" !== values.mode && "best-effort" !== values.mode && "off" !== values.mode) throw new Error("[plugin-mf] Invalid types mode");
83
+ types.mode = values.mode;
84
+ }
85
+ if (values.remote) types.remotes = values.remote;
86
+ if (void 0 !== values.offline) types.offline = values.offline;
87
+ if (void 0 !== values["frozen-lockfile"]) types.frozenLockfile = values["frozen-lockfile"];
88
+ if (void 0 !== values["update-lock"]) types.updateLock = values["update-lock"];
89
+ validateTypesOptions(types);
90
+ await syncTypes({
91
+ remotes,
92
+ rootPath: node_path.dirname(configPath),
93
+ types
94
+ });
95
+ }
96
+ main().catch((error)=>{
97
+ console.error(error);
98
+ process.exitCode = 1;
99
+ });
@@ -0,0 +1,11 @@
1
+ export type TypesSyncMode = "strict" | "best-effort" | "off";
2
+ export type TypesSyncOptions = {
3
+ mode?: TypesSyncMode;
4
+ remotes?: string[];
5
+ concurrency?: number;
6
+ offline?: boolean;
7
+ frozenLockfile?: boolean;
8
+ updateLock?: boolean;
9
+ lockfile?: string;
10
+ };
11
+ export declare function validateTypesOptions(options: TypesSyncOptions): void;
@@ -0,0 +1,10 @@
1
+ function validateTypesOptions(options) {
2
+ if (void 0 !== options.mode && ![
3
+ "strict",
4
+ "best-effort",
5
+ "off"
6
+ ].includes(options.mode)) throw new Error("[plugin-mf] Invalid types synchronization mode");
7
+ if (void 0 !== options.concurrency && (!Number.isSafeInteger(options.concurrency) || options.concurrency < 1)) throw new Error("[plugin-mf] Types concurrency must be a positive safe integer");
8
+ if (options.updateLock && (options.offline || options.frozenLockfile)) throw new Error("[plugin-mf] updateLock cannot be combined with offline or frozenLockfile");
9
+ }
10
+ export { validateTypesOptions };
@@ -0,0 +1,12 @@
1
+ export { Loader, getRemote, initializeMFReleases, createRemoteComponent, preloadRemotes } from "./runtime/client/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 { configureLoading } from "./transport/loading.ts";
7
+ export { configureObservability, getLoadingMetrics } from "./transport/observability.ts";
8
+ export type { LoadingEvent, LoadingEventHandler, LoadingMetrics } from "./protocol/observability.ts";
9
+ export { configureNetwork } from "./transport/network-policy.ts";
10
+ export type { NetworkOptions } from "./protocol/network-policy.ts";
11
+ export { RemoteLoadError } from "./protocol/load-error.ts";
12
+ export type { LoadingOptions, LoadStage, LoadErrorCode } from "./protocol/load-error.ts";
package/dist/client.js ADDED
@@ -0,0 +1,6 @@
1
+ export { Loader, createRemoteComponent, getRemote, initializeMFReleases, preloadRemotes } from "./runtime/client/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";
@@ -0,0 +1,8 @@
1
+ export { pluginMF } from "./build/plugin.ts";
2
+ export type { PluginMFConfig } from "./build/config.ts";
3
+ export type { NetworkOptions } from "./protocol/network-policy.ts";
4
+ export type { SharedConfig, SharedDependency } from "./protocol/shared-dependencies.ts";
5
+ export type { LoadingOptions } from "./protocol/load-error.ts";
6
+ export { syncTypes } from "./build/sync-types.ts";
7
+ export type { SyncTypesOptions } from "./build/sync-types.ts";
8
+ export type { TypesSyncOptions, TypesSyncMode } from "./build/types-options.ts";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { pluginMF } from "./build/plugin.js";
2
+ export { syncTypes } from "./build/sync-types.js";
@@ -0,0 +1 @@
1
+ export declare function validateAssetPath(value: string): void;
@@ -0,0 +1,10 @@
1
+ function validateAssetPath(value) {
2
+ let decoded;
3
+ try {
4
+ decoded = decodeURIComponent(value);
5
+ } catch {
6
+ throw new Error(`[plugin-mf] Invalid asset path: ${value}`);
7
+ }
8
+ if (!value || /[\\\x00-\x1f\x7f:?#]/.test(decoded) || decoded.split("/").length !== value.split("/").length || decoded.split("/").some((part)=>!part || "." === part || ".." === part || /[. ]$/.test(part) || ".pins" === part.toLowerCase())) throw new Error(`[plugin-mf] Invalid asset path: ${value}`);
9
+ }
10
+ export { validateAssetPath };
@@ -0,0 +1,29 @@
1
+ export type LoadStage = "release-manifest" | "manifest" | "module" | "types";
2
+ export type LoadErrorCode = "LOAD_FAILED" | "HTTP_ERROR" | "TIMEOUT" | "ABORTED" | "CIRCUIT_OPEN";
3
+ export type LoadContext = {
4
+ remote: string;
5
+ releaseId?: string;
6
+ stage: LoadStage;
7
+ };
8
+ export declare class RemoteLoadError extends Error {
9
+ readonly remote: string;
10
+ readonly releaseId?: string;
11
+ readonly stage: LoadStage;
12
+ readonly code: LoadErrorCode;
13
+ readonly status?: number;
14
+ constructor(context: LoadContext, code: LoadErrorCode, message: string, options?: {
15
+ cause?: unknown;
16
+ status?: number;
17
+ });
18
+ }
19
+ export type LoadingOptions = {
20
+ manifestTimeoutMs?: number;
21
+ moduleTimeoutMs?: number;
22
+ typesTimeoutMs?: number;
23
+ retries?: number;
24
+ retryDelayMs?: number;
25
+ circuitBreaker?: {
26
+ failureThreshold?: number;
27
+ cooldownMs?: number;
28
+ };
29
+ };
@@ -0,0 +1,17 @@
1
+ class RemoteLoadError extends Error {
2
+ remote;
3
+ releaseId;
4
+ stage;
5
+ code;
6
+ status;
7
+ constructor(context, code, message, options){
8
+ super(`[plugin-mf] ${context.remote} (${context.releaseId ?? "unselected"}, ${context.stage}): ${message}`, options);
9
+ this.name = "RemoteLoadError";
10
+ this.remote = context.remote;
11
+ this.releaseId = context.releaseId;
12
+ this.stage = context.stage;
13
+ this.code = code;
14
+ this.status = options?.status;
15
+ }
16
+ }
17
+ export { RemoteLoadError };
@@ -0,0 +1,12 @@
1
+ export type ModuleLoadContext = {
2
+ provider: string;
3
+ releaseId?: string;
4
+ baseUrl: string;
5
+ files: string[];
6
+ integrity?: Record<string, string>;
7
+ };
8
+ export type RemoteScope = "client" | "server";
9
+ export type RemoteModule = Record<string, unknown>;
10
+ export interface ModuleLoader {
11
+ load(url: string, context?: ModuleLoadContext): Promise<RemoteModule>;
12
+ }
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,5 @@
1
+ export type NetworkOptions = {
2
+ allowedProtocols?: ("http:" | "https:")[];
3
+ allowedOrigins?: string[];
4
+ requireServerIntegrity?: boolean;
5
+ };
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,26 @@
1
+ import type { LoadContext } from "./load-error.ts";
2
+ export type LoadingEvent = LoadContext & {
3
+ type: "start" | "success" | "error" | "cache-hit" | "retry" | "download" | "prune";
4
+ operation: "remote" | "fetch" | "module" | "disk" | "types";
5
+ durationMs?: number;
6
+ requestId?: string;
7
+ loadId?: number;
8
+ bytes?: number;
9
+ attempt?: number;
10
+ error?: {
11
+ code: string;
12
+ status?: number;
13
+ };
14
+ };
15
+ export type LoadingEventHandler = (event: Readonly<LoadingEvent>) => void | Promise<void>;
16
+ export type LoadingMetrics = {
17
+ starts: number;
18
+ successes: number;
19
+ errors: number;
20
+ cacheHits: number;
21
+ retries: number;
22
+ downloadedBytes: number;
23
+ diskHits: number;
24
+ diskDownloads: number;
25
+ prunedBytes: number;
26
+ };
@@ -0,0 +1 @@
1
+ export { };