1
-import { chmod, copyFile, mkdir, readdir, stat, writeFile } from 'node:fs/promises';
1
+import { builtinModules } from 'node:module';
2
+import { chmod, copyFile, mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises';
3
import * as path from 'node:path';
4
import process from 'node:process';
5
import { Cause, Effect, Exit } from 'effect';
6
import type { Teardown } from '@effect/platform/Runtime';
6
-import {
7
- collectRunCompanionAssetRelativePaths,
8
- RUN_COMPANION_MODULE_BASENAMES,
9
-} from '../src/services/run-companion-modules';
7
+import { RUN_COMPANION_MODULE_BASENAMES } from '../src/services/run-companion-modules';
8
import { materializeAcpAdaptersCache } from './_acp-adapters';
9
10
+const RUN_COMPANION_SERVICE_ENTRY_MAP = Object.fromEntries(
11
+ RUN_COMPANION_MODULE_BASENAMES.map(name => [`services/${name}`, `src/services/${name}.ts`])
12
+) satisfies Record<string, string>;
13
+
14
+const allowedRuntimeSpecifiers = new Set(
15
+ builtinModules.flatMap(specifier =>
16
+ specifier.startsWith('node:')
17
+ ? [specifier, specifier.slice('node:'.length)]
18
+ : [specifier, `node:${specifier}`]
19
+ )
20
+);
21
+
22
+const importStatementPattern = /(?:^|[;\n])\s*import\s+(?:[^'"`\n]+?\s+from\s+)?["']([^"']+)["']/gm;
23
+const exportStatementPattern =
24
+ /(?:^|[;\n])\s*export\s+(?:\*\s+from\s+|\{[^}\n]+\}\s+from\s+)["']([^"']+)["']/gm;
25
+const runtimeImportCallPattern = /(?:^|[^\w$.])(?:__require|require|import)\(\s*["']([^"']+)["']/g;
26
+
27
const copyDirectoryRecursive = async (sourceDir: string, targetDir: string): Promise<void> => {
28
await mkdir(targetDir, { recursive: true });
29
45
const copyBundledAcpAdapters = async (outputDir: string): Promise<void> => {
46
const acpAdaptersCacheDir = await materializeAcpAdaptersCache();
47
const acpOutputDir = path.join(outputDir, 'acp-adapters');
48
+ await rm(acpOutputDir, { force: true, recursive: true });
49
await copyDirectoryRecursive(acpAdaptersCacheDir, acpOutputDir);
50
};
51
52
+const isAllowedRuntimeSpecifier = (specifier: string): boolean =>
53
+ specifier.startsWith('.') ||
54
+ specifier.startsWith('/') ||
55
+ specifier.startsWith('data:') ||
56
+ specifier === 'bun' ||
57
+ specifier.startsWith('bun:') ||
58
+ allowedRuntimeSpecifiers.has(specifier);
59
+
60
+const stripStringsAndComments = (source: string): string => {
61
+ let result = '';
62
+ let index = 0;
63
+
64
+ const appendSpace = (char: string) => {
65
+ result += char === '\n' ? '\n' : ' ';
66
+ };
67
+
68
+ while (index < source.length) {
69
+ const char = source[index];
70
+ const next = source[index + 1];
71
+
72
+ if (char === "'" || char === '"' || char === '`') {
73
+ const quote = char;
74
+ appendSpace(char);
75
+ index += 1;
76
+
77
+ while (index < source.length) {
78
+ const current = source[index];
79
+ appendSpace(current);
80
+ index += 1;
81
+
82
+ if (current === '\\') {
83
+ if (index < source.length) {
84
+ appendSpace(source[index]!);
85
+ index += 1;
86
+ }
87
+ continue;
88
+ }
89
+
90
+ if (current === quote) {
91
+ break;
92
+ }
93
+ }
94
+
95
+ continue;
96
+ }
97
+
98
+ if (char === '/' && next === '/') {
99
+ appendSpace(char);
100
+ appendSpace(next);
101
+ index += 2;
102
+
103
+ while (index < source.length) {
104
+ const current = source[index];
105
+ appendSpace(current);
106
+ index += 1;
107
+ if (current === '\n') {
108
+ break;
109
+ }
110
+ }
111
+
112
+ continue;
113
+ }
114
+
115
+ if (char === '/' && next === '*') {
116
+ appendSpace(char);
117
+ appendSpace(next);
118
+ index += 2;
119
+
120
+ while (index < source.length) {
121
+ const current = source[index];
122
+ const following = source[index + 1];
123
+ appendSpace(current);
124
+ index += 1;
125
+ if (current === '*' && following === '/') {
126
+ appendSpace(following);
127
+ index += 1;
128
+ break;
129
+ }
130
+ }
131
+
132
+ continue;
133
+ }
134
+
135
+ result += char;
136
+ index += 1;
137
+ }
138
+
139
+ return result;
140
+};
141
+
142
+const collectBundledSpecifiers = (source: string): ReadonlyArray<string> => {
143
+ const sanitizedSource = stripStringsAndComments(source);
144
+ const specifiers = new Set<string>();
145
+
146
+ for (const pattern of [
147
+ importStatementPattern,
148
+ exportStatementPattern,
149
+ runtimeImportCallPattern,
150
+ ]) {
151
+ for (const match of sanitizedSource.matchAll(pattern)) {
152
+ const specifier = match[1];
153
+ if (specifier) {
154
+ specifiers.add(specifier);
155
+ }
156
+ }
157
+ }
158
+
159
+ return [...specifiers];
160
+};
161
+
162
+const collectJavaScriptFiles = async (directory: string): Promise<ReadonlyArray<string>> => {
163
+ const collected: string[] = [];
164
+
165
+ const walk = async (directory: string): Promise<void> => {
166
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
167
+ const entryPath = path.join(directory, entry.name);
168
+ if (entry.isDirectory()) {
169
+ await walk(entryPath);
170
+ continue;
171
+ }
172
+
173
+ if (/\.(?:m?js|cjs)$/.test(entry.name)) {
174
+ collected.push(entryPath);
175
+ }
176
+ }
177
+ };
178
+
179
+ await walk(directory);
180
+ return collected.sort();
181
+};
182
+
183
+const collectRuntimeFiles = async (rootDir: string): Promise<ReadonlyArray<string>> => {
184
+ const collected = new Set<string>();
185
+
186
+ for (const baseName of RUN_COMPANION_MODULE_BASENAMES) {
187
+ const wrapperPath = path.join(rootDir, `${baseName}.mjs`);
188
+ if (await Bun.file(wrapperPath).exists()) {
189
+ collected.add(wrapperPath);
190
+ }
191
+ }
192
+
193
+ for (const relativeDir of ['services', 'acp-adapters']) {
194
+ const absoluteDir = path.join(rootDir, relativeDir);
195
+ const exists = await stat(absoluteDir)
196
+ .then(stats => stats.isDirectory())
197
+ .catch(() => false);
198
+ if (!exists) {
199
+ continue;
200
+ }
201
+
202
+ for (const filePath of await collectJavaScriptFiles(absoluteDir)) {
203
+ collected.add(filePath);
204
+ }
205
+ }
206
+
207
+ return [...collected].sort();
208
+};
209
+
210
+const assertBundledRuntimeFiles = async (rootDir: string): Promise<void> => {
211
+ const files = await collectRuntimeFiles(rootDir);
212
+ const violations: string[] = [];
213
+
214
+ for (const filePath of files) {
215
+ const source = await Bun.file(filePath).text();
216
+ for (const specifier of collectBundledSpecifiers(source)) {
217
+ if (!specifier || isAllowedRuntimeSpecifier(specifier)) {
218
+ continue;
219
+ }
220
+
221
+ violations.push(`${path.relative(rootDir, filePath)} -> ${specifier}`);
222
+ }
223
+ }
224
+
225
+ if (violations.length > 0) {
226
+ throw new Error(
227
+ [
228
+ 'Generated runtime support files still reference external packages:',
229
+ ...violations.map(violation => ` - ${violation}`),
230
+ ].join('\n')
231
+ );
232
+ }
233
+};
234
+
235
+const buildCompanionServiceBundles = async (outputDir: string): Promise<void> => {
236
+ const servicesOutputDir = path.join(outputDir, 'services');
237
+ await rm(servicesOutputDir, { force: true, recursive: true });
238
+ await mkdir(servicesOutputDir, { recursive: true });
239
+
240
+ for (const [entryName, entryPath] of Object.entries(RUN_COMPANION_SERVICE_ENTRY_MAP)) {
241
+ const relativeOutputPath = `${entryName}.mjs`;
242
+ const outputDirectory = path.join(outputDir, path.dirname(relativeOutputPath));
243
+ const outputFileName = path.basename(relativeOutputPath);
244
+ await mkdir(outputDirectory, { recursive: true });
245
+
246
+ const result = await Bun.build({
247
+ entrypoints: [path.resolve(entryPath)],
248
+ outdir: outputDirectory,
249
+ naming: outputFileName,
250
+ target: 'bun',
251
+ format: 'esm',
252
+ packages: 'bundle',
253
+ sourcemap: 'none',
254
+ });
255
+
256
+ if (!result.success) {
257
+ const details = result.logs
258
+ .map(log => log.message)
259
+ .filter(message => message.length > 0)
260
+ .join('\n');
261
+ throw new Error(
262
+ details.length > 0
263
+ ? `Failed to bundle ${entryName}:\n${details}`
264
+ : `Failed to bundle ${entryName}.`
265
+ );
266
+ }
267
+ }
268
+};
269
+
270
/**
271
* Shared teardown for all CLI scripts.
272
*
283
Effect.gen(function* () {
284
yield* Effect.tryPromise(() => mkdir(outputDir, { recursive: true }));
285
52
- const compiledRootDir = path.resolve('./dist');
53
- const companionRelativePaths = collectRunCompanionAssetRelativePaths(compiledRootDir);
54
- if (companionRelativePaths.length === 0) {
55
- return yield* Effect.fail(
56
- new Error('Missing compiled run companion modules. Run `pnpm build:packages` first.')
57
- );
58
- }
59
-
60
- for (const relativePath of companionRelativePaths) {
61
- const sourcePath = path.join(compiledRootDir, relativePath);
62
- const targetPath = path.join(outputDir, relativePath);
63
-
64
- yield* Effect.tryPromise(async () => {
65
- if (!(await Bun.file(sourcePath).exists())) {
66
- throw new Error(`Missing companion module: ${sourcePath}`);
67
- }
68
- if (path.resolve(sourcePath) === path.resolve(targetPath)) {
69
- return;
70
- }
71
-
72
- await mkdir(path.dirname(targetPath), { recursive: true });
73
- await copyFile(sourcePath, targetPath);
74
- });
75
- }
286
+ yield* Effect.tryPromise(() => buildCompanionServiceBundles(outputDir));
287
288
for (const name of RUN_COMPANION_MODULE_BASENAMES) {
289
const wrapperPath = path.join(outputDir, `${name}.mjs`);
292
}
293
294
yield* Effect.tryPromise(() => copyBundledAcpAdapters(outputDir));
295
+ yield* Effect.tryPromise(() => assertBundledRuntimeFiles(outputDir));
296
});