@zerosumstudio/spool 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/dist/vite.js ADDED
@@ -0,0 +1,1068 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+
4
+ // src/util/errors.ts
5
+ /** Bad input from the caller: exits 2, so scripts can tell it apart from a real failure. */
6
+ const USAGE_ERROR_CODES = [
7
+ "USAGE",
8
+ "INVALID_NAME",
9
+ "INVALID_PATH",
10
+ "INVALID_VALUE",
11
+ "INPUT_REQUIRED",
12
+ "CONFIRMATION_REQUIRED"
13
+ ];
14
+ const FAILURE_ERROR_CODES = [
15
+ "NO_WORKSPACE",
16
+ "MANIFEST_INVALID",
17
+ "MANIFEST_VERSION",
18
+ "APP_NOT_FOUND",
19
+ "TARGET_EXISTS",
20
+ "TARGET_NOT_EMPTY",
21
+ "UNSAFE_PATH",
22
+ "BUILD_FAILED",
23
+ "DEPLOY_FAILED",
24
+ "PORT_IN_USE",
25
+ "CHECK_FAILED",
26
+ "FAILED",
27
+ "INTERNAL"
28
+ ];
29
+ const ERROR_CODES = [
30
+ ...USAGE_ERROR_CODES,
31
+ ...FAILURE_ERROR_CODES,
32
+ "CANCELLED"
33
+ ];
34
+ const USAGE_CODES = new Set(USAGE_ERROR_CODES);
35
+ /**
36
+ * An error whose message is shown to the user as-is. The entry point prints it
37
+ * without a stack trace and exits with `exitCodeFor(error)`. `data` is merged
38
+ * into the `--json` document, so a failed build can still report its results.
39
+ */
40
+ var CliError = class extends Error {
41
+ code;
42
+ data;
43
+ constructor(message, code = "FAILED", data) {
44
+ super(message);
45
+ this.name = "CliError";
46
+ this.code = code;
47
+ this.data = data;
48
+ }
49
+ };
50
+
51
+ // src/util/names.ts
52
+ /** "@scope/pkg/subpath" and "pkg/subpath" resolve to the installable package. */
53
+ function packageName(specifier) {
54
+ const parts = specifier.split("/");
55
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? specifier;
56
+ }
57
+ /** Env var that overrides where hosts load a remote from, e.g. SPOOL_REMOTE_MY_APP. */
58
+ function remoteEnvVar(name) {
59
+ return `SPOOL_REMOTE_${name.toUpperCase().replace(/-/g, "_")}`;
60
+ }
61
+ /**
62
+ * Workspace and app names become folder names, npm package names, federation
63
+ * container names and (via PascalCase) React component identifiers. Restrict
64
+ * them to a safe, portable subset: lowercase, starts with a letter, single
65
+ * hyphens between segments. This also blocks path traversal (`..`, slashes).
66
+ */
67
+ const NAME_PATTERN = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
68
+ const MAX_NAME_LENGTH = 64;
69
+ /**
70
+ * Windows treats these as devices in any folder, with any extension, and with spaces or
71
+ * dots after the name (`con .txt`, `con.`), so a workspace holding one cannot be cloned
72
+ * there. Banned on every OS.
73
+ */
74
+ const DEVICE_NAME = /^(?:con|prn|aux|nul|conin\$|conout\$|clock\$|com[0-9¹²³]|lpt[0-9¹²³])[\s.]*(?:\..*)?$/i;
75
+ /**
76
+ * A remote `name` is imported as `name/<expose>`, so an app that shares a
77
+ * package's name would shadow it. The manifest's own `shared` list adds to these.
78
+ */
79
+ const SHARED_PACKAGE_NAMES = [
80
+ "react",
81
+ "react-dom",
82
+ "vue",
83
+ "svelte",
84
+ "vite"
85
+ ];
86
+ function isDeviceName(segment) {
87
+ return DEVICE_NAME.test(segment);
88
+ }
89
+ /** Returns an error message if `value` is not a valid name, else undefined. */
90
+ function validateName(value, label = "name", options = {}) {
91
+ const trimmed = value.trim();
92
+ if (!trimmed) return `Please enter a ${label}.`;
93
+ if (trimmed !== value) return `Invalid ${label} "${value}": remove the spaces around it.`;
94
+ if (trimmed.length > 64) return `Invalid ${label}: at most ${64} characters.`;
95
+ if (!NAME_PATTERN.test(trimmed)) return `Invalid ${label} "${value}". Use lowercase letters, digits and single hyphens, starting with a letter (e.g. "dashboard").`;
96
+ if (isDeviceName(trimmed)) return `Invalid ${label} "${value}": Windows reserves it as a device name, so the workspace could not be cloned there.`;
97
+ if ([...SHARED_PACKAGE_NAMES, ...options.shared ?? []].includes(trimmed)) return `Invalid ${label} "${value}": it is the name of a shared package, and "${trimmed}/<module>" would clash with it.`;
98
+ }
99
+ /** An app's folder, relative to the workspace root. No `.`, `..`, uppercase or odd characters. */
100
+ const APP_PATH_PATTERN = /^[a-z0-9][a-z0-9._-]*(\/[a-z0-9][a-z0-9._-]*)*$/;
101
+ /** The module an expose points at, relative to its app. */
102
+ const EXPOSE_SOURCE_PATTERN = /^(?:\.\/)?[A-Za-z0-9_][\w.-]*(\/[A-Za-z0-9_][\w.-]*)*$/;
103
+ /** An expose key: `./` and a path, which a host imports as `remote/<key>`. */
104
+ const EXPOSE_KEY_PATTERN = /^\.\/[A-Za-z0-9_][\w.-]*(\/[A-Za-z0-9_][\w.-]*)*$/;
105
+ const CONTROL_CHARACTER = /[\x00-\x1f\x7f]/;
106
+ const FORBIDDEN_SEGMENT_CHARACTER = /[<>:"|?*]/;
107
+ /**
108
+ * True for a relative path that stays inside the folder it is joined to.
109
+ * Rejects absolute paths, UNC (`\\server\share`), drive-relative paths (`C:foo`),
110
+ * `:` anywhere (an NTFS alternate data stream, `a:b`), control characters and `..`.
111
+ */
112
+ function isConfinedPath(value) {
113
+ if (!value || CONTROL_CHARACTER.test(value)) return false;
114
+ if (value.startsWith("/") || value.startsWith("\\") || value.includes(":")) return false;
115
+ return !value.split(/[\\/]/).some((segment) => segment === "..");
116
+ }
117
+ /** True for a single folder or file name that Windows and POSIX both accept as-is. */
118
+ function isSafeSegment(segment) {
119
+ if (!segment || segment === ".." || isDeviceName(segment)) return false;
120
+ if (CONTROL_CHARACTER.test(segment) || FORBIDDEN_SEGMENT_CHARACTER.test(segment)) return false;
121
+ return segment === "." || !/[. ]$/.test(segment);
122
+ }
123
+ /** Returns an error message if `path` is not a valid app folder, else undefined. */
124
+ function validateAppPath(path) {
125
+ if (!isConfinedPath(path) || path.endsWith("/")) return `"${path}" must be a relative path inside the workspace, with no "..", no drive or UNC prefix and no trailing slash.`;
126
+ if (!APP_PATH_PATTERN.test(path)) return `"${path}" may only use lowercase letters, digits, ".", "_" and "-", in folders separated by "/".`;
127
+ return path.split("/").every(isSafeSegment) ? void 0 : `"${path}" has a segment Windows reserves or cannot store.`;
128
+ }
129
+ /** Returns an error message if `source` is not a valid expose source, else undefined. */
130
+ function validateExposeSource(source) {
131
+ if (!isConfinedPath(source) || !EXPOSE_SOURCE_PATTERN.test(source)) return `"${source}" must be a relative file path inside the app, like "./src/app.tsx".`;
132
+ return source.split("/").every(isSafeSegment) ? void 0 : `"${source}" has a segment Windows reserves or cannot store.`;
133
+ }
134
+ const HEADER_NAME_PATTERN = /^[A-Za-z0-9-]+$/;
135
+ /** A header value must stay on one line: CR, LF and other control characters split a header file. */
136
+ function isSafeHeaderValue(value) {
137
+ return !/[\x00-\x08\x0a-\x1f\x7f]/.test(value);
138
+ }
139
+ /** A CSP source expression: no whitespace, `;` or `,`, which would add directives or sources. */
140
+ function isSafeCspSource(value) {
141
+ return value !== "" && !/[\s;,]/.test(value) && !CONTROL_CHARACTER.test(value);
142
+ }
143
+ function isHttpUrl(value) {
144
+ try {
145
+ const url = new URL(value);
146
+ return url.protocol === "http:" || url.protocol === "https:";
147
+ } catch {
148
+ return false;
149
+ }
150
+ }
151
+ /** An http(s) URL with no `user:password@`, which would ship in the public bundle. */
152
+ function isPublicHttpUrl(value) {
153
+ if (!isHttpUrl(value)) return false;
154
+ const url = new URL(value);
155
+ return url.username === "" && url.password === "";
156
+ }
157
+ /** An environment name, as `deploy --env`, `dev --rest env:<name>` and `urls` keys spell it. */
158
+ const ENV_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
159
+ /** `https://host[:port]` exactly: no path, query, fragment, trailing slash or credentials. */
160
+ function isOrigin(value) {
161
+ if (!isHttpUrl(value)) return false;
162
+ return new URL(value).origin === value;
163
+ }
164
+
165
+ // src/core/config.ts
166
+ /** Manifest file name that marks a spool workspace root. */
167
+ const MANIFEST_FILE = "spool.json";
168
+ /** Manifest schema version this CLI reads and writes. */
169
+ const MANIFEST_VERSION = 2;
170
+ const FRAMEWORKS = [
171
+ "react",
172
+ "svelte",
173
+ "vue"
174
+ ];
175
+ /** Framework scaffolded when nothing picks one explicitly. */
176
+ const DEFAULT_FRAMEWORK = "react";
177
+ const APP_TYPES = ["host", "remote"];
178
+ const PACKAGE_MANAGERS = [
179
+ "pnpm",
180
+ "npm",
181
+ "yarn"
182
+ ];
183
+ const SHARE_STRATEGIES = ["version-first", "loaded-first"];
184
+ const CSP_MODES = ["default", "strict"];
185
+ const ADDON_NAME_VALUES = [
186
+ "ladle",
187
+ "playwright",
188
+ "lint",
189
+ "test",
190
+ "turbo",
191
+ "state",
192
+ "sentry",
193
+ "navigation"
194
+ ];
195
+ /** Was an addon in earlier versions; every host has it now, so it is accepted and ignored. */
196
+ const RETIRED_ADDON = "federation";
197
+ function isRecord(value) {
198
+ return typeof value === "object" && value !== null && !Array.isArray(value);
199
+ }
200
+ /** Collects problems with `spool.json` so one parse reports all of them. */
201
+ var Reader = class {
202
+ issues = [];
203
+ add(path, message) {
204
+ this.issues.push({
205
+ path: path.join(".") || "(root)",
206
+ message
207
+ });
208
+ }
209
+ /** Strict: a key nobody reads is almost always a typo. */
210
+ object(value, path, allowed) {
211
+ if (!isRecord(value)) {
212
+ this.add(path, "must be an object");
213
+ return;
214
+ }
215
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) this.add([...path, key], "is not a known setting");
216
+ return value;
217
+ }
218
+ string(value, path) {
219
+ if (typeof value === "string") return value;
220
+ this.add(path, "must be a string");
221
+ }
222
+ boolean(value, path) {
223
+ if (typeof value === "boolean") return value;
224
+ this.add(path, "must be true or false");
225
+ }
226
+ choice(value, path, options, fallback) {
227
+ if (value === void 0 && fallback !== void 0) return fallback;
228
+ const match = options.find((option) => option === value);
229
+ if (match !== void 0) return match;
230
+ this.add(path, `must be one of ${options.map((option) => `"${option}"`).join(", ")}`);
231
+ }
232
+ list(value, path, readItem, fallback) {
233
+ if (value === void 0 && fallback !== void 0) return fallback;
234
+ if (!Array.isArray(value)) {
235
+ this.add(path, "must be an array");
236
+ return;
237
+ }
238
+ const items = [];
239
+ value.forEach((item, index) => {
240
+ const parsed = readItem(item, [...path, index]);
241
+ if (parsed !== void 0) items.push(parsed);
242
+ });
243
+ return items;
244
+ }
245
+ record(value, path, readValue, checkKey) {
246
+ if (!isRecord(value)) {
247
+ this.add(path, "must be an object");
248
+ return;
249
+ }
250
+ const out = Object.create(null);
251
+ for (const [key, item] of Object.entries(value)) {
252
+ const keyError = checkKey?.(key);
253
+ if (keyError) this.add([...path, key], keyError);
254
+ const parsed = readValue(item, [...path, key]);
255
+ if (parsed !== void 0) out[key] = parsed;
256
+ }
257
+ return out;
258
+ }
259
+ /** A setting that may be left out: reads it when it is there and hands the result on. */
260
+ optional(raw, key, path, read, assign) {
261
+ if (raw[key] === void 0) return;
262
+ const parsed = read(raw[key], [...path, key]);
263
+ if (parsed !== void 0) assign(parsed);
264
+ }
265
+ /** An http(s) URL, without credentials: it is compiled into the public bundle. */
266
+ url(value, path) {
267
+ const text = this.string(value, path);
268
+ if (text === void 0) return void 0;
269
+ if (isPublicHttpUrl(text)) return text;
270
+ this.add(path, isHttpUrl(text) ? "must not contain a username or password" : "must be an http or https URL");
271
+ }
272
+ origin(value, path) {
273
+ const text = this.string(value, path);
274
+ if (text === void 0) return void 0;
275
+ if (isOrigin(text)) return text;
276
+ this.add(path, "must be an origin like \"https://app.example.com\": no path, query or trailing slash");
277
+ }
278
+ headers(value, path) {
279
+ return this.record(value, path, (item, itemPath) => {
280
+ const text = this.string(item, itemPath);
281
+ if (text === void 0) return void 0;
282
+ if (isSafeHeaderValue(text)) return text;
283
+ this.add(itemPath, "must not contain line breaks or control characters");
284
+ }, (key) => HEADER_NAME_PATTERN.test(key) ? void 0 : "is not a valid header name");
285
+ }
286
+ };
287
+ const MANIFEST_KEYS = [
288
+ "name",
289
+ "version",
290
+ "packageManager",
291
+ "bundler",
292
+ "shared",
293
+ "shareStrategy",
294
+ "csp",
295
+ "server",
296
+ "addons",
297
+ "apps",
298
+ "overrides"
299
+ ];
300
+ const APP_KEYS = [
301
+ "type",
302
+ "framework",
303
+ "path",
304
+ "port",
305
+ "url",
306
+ "urls",
307
+ "deploy",
308
+ "deployEnv",
309
+ "remotes",
310
+ "exposes",
311
+ "headers",
312
+ "frameAncestors"
313
+ ];
314
+ /** What a manifest means when it leaves a setting out. `saveManifest` leaves these out again. */
315
+ const MANIFEST_DEFAULTS = {
316
+ packageManager: "pnpm",
317
+ bundler: "vite",
318
+ shared: ["react", "react-dom"],
319
+ shareStrategy: "loaded-first",
320
+ csp: "default",
321
+ addons: []
322
+ };
323
+ const APP_DEFAULTS = {
324
+ framework: DEFAULT_FRAMEWORK,
325
+ remotes: [],
326
+ exposes: {}
327
+ };
328
+ const SERVER_KEYS = [
329
+ "proxy",
330
+ "headers",
331
+ "host",
332
+ "cors",
333
+ "fs"
334
+ ];
335
+ const PROXY_KEYS = [
336
+ "target",
337
+ "changeOrigin",
338
+ "secure",
339
+ "ws"
340
+ ];
341
+ const SECRET_NAME = /^[A-Z][A-Z0-9_]*$/;
342
+ const FILESYSTEM_ROOT = /^(?:[\\/]+|[a-zA-Z]:[\\/]*)$/;
343
+ function readProxy(reader, value, path) {
344
+ if (typeof value === "string") return value;
345
+ const raw = reader.object(value, path, PROXY_KEYS);
346
+ if (!raw) return void 0;
347
+ const target = reader.string(raw.target, [...path, "target"]);
348
+ if (target === void 0) return void 0;
349
+ const entry = { target };
350
+ for (const key of [
351
+ "changeOrigin",
352
+ "secure",
353
+ "ws"
354
+ ]) {
355
+ if (raw[key] === void 0) continue;
356
+ const flag = reader.boolean(raw[key], [...path, key]);
357
+ if (flag !== void 0) entry[key] = flag;
358
+ }
359
+ return entry;
360
+ }
361
+ function readFsAllow(reader, value, path) {
362
+ const entry = reader.string(value, path);
363
+ if (entry === void 0) return void 0;
364
+ if (entry.trim() === "") {
365
+ reader.add(path, "cannot be empty");
366
+ return;
367
+ }
368
+ if (FILESYSTEM_ROOT.test(entry.trim())) {
369
+ reader.add(path, "cannot be the filesystem root; that would let the dev server read any file on disk");
370
+ return;
371
+ }
372
+ return entry;
373
+ }
374
+ function readHost(reader, value, path) {
375
+ if (typeof value === "boolean" || typeof value === "string") return value;
376
+ reader.add(path, "must be true, false or a host name");
377
+ }
378
+ function readCors(reader, value, path) {
379
+ if (typeof value === "boolean") {
380
+ reader.add(path, "must be a list of origins. A boolean was the version 1 form; run `spool upgrade`");
381
+ return;
382
+ }
383
+ return reader.list(value, path, (item, itemPath) => reader.origin(item, itemPath));
384
+ }
385
+ function readFs(reader, value, path) {
386
+ const fs = reader.object(value, path, ["allow"]);
387
+ if (!fs) return void 0;
388
+ const allow = reader.list(fs.allow, [...path, "allow"], (item, itemPath) => readFsAllow(reader, item, itemPath));
389
+ return allow ? { allow } : void 0;
390
+ }
391
+ function readServer(reader, value, path) {
392
+ const raw = reader.object(value, path, SERVER_KEYS);
393
+ if (!raw) return void 0;
394
+ const server = {};
395
+ reader.optional(raw, "proxy", path, (item, itemPath) => reader.record(item, itemPath, (entry, entryPath) => readProxy(reader, entry, entryPath)), (proxy) => server.proxy = proxy);
396
+ reader.optional(raw, "headers", path, (item, itemPath) => reader.headers(item, itemPath), (headers) => server.headers = headers);
397
+ reader.optional(raw, "host", path, (item, itemPath) => readHost(reader, item, itemPath), (host) => server.host = host);
398
+ reader.optional(raw, "cors", path, (item, itemPath) => readCors(reader, item, itemPath), (cors) => server.cors = cors);
399
+ reader.optional(raw, "fs", path, (item, itemPath) => readFs(reader, item, itemPath), (fs) => server.fs = fs);
400
+ return server;
401
+ }
402
+ function readExposes(reader, value, path) {
403
+ return reader.record(value, path, (item, itemPath) => {
404
+ const source = reader.string(item, itemPath);
405
+ if (source === void 0) return void 0;
406
+ const error = validateExposeSource(source);
407
+ if (error === void 0) return source;
408
+ reader.add(itemPath, error);
409
+ }, (key) => EXPOSE_KEY_PATTERN.test(key) ? void 0 : "must start with \"./\" and use letters, digits, \".\", \"_\" and \"-\" in \"/\" separated parts");
410
+ }
411
+ function readFrameAncestor(reader, value, path) {
412
+ const source = reader.string(value, path);
413
+ if (source === void 0) return void 0;
414
+ if (isSafeCspSource(source)) return source;
415
+ reader.add(path, "must be one source with no spaces, \";\" or \",\"");
416
+ }
417
+ function readDeployEnvName(reader, value, path) {
418
+ const name = reader.string(value, path);
419
+ if (name === void 0) return void 0;
420
+ if (SECRET_NAME.test(name)) return name;
421
+ reader.add(path, "must be an upper case variable name like \"CLOUDFLARE_API_TOKEN\"");
422
+ }
423
+ function readDeployEnv(reader, value, path) {
424
+ const names = reader.list(value, path, (item, itemPath) => readDeployEnvName(reader, item, itemPath));
425
+ if (names && new Set(names).size !== names.length) reader.add(path, "lists a name more than once");
426
+ return names;
427
+ }
428
+ function readFrameAncestors(reader, value, path) {
429
+ const ancestors = reader.list(value, path, (item, itemPath) => readFrameAncestor(reader, item, itemPath));
430
+ if (ancestors?.includes("edge") && ancestors.length > 1) reader.add(path, "\"edge\" stands alone; the edge sets the header, so list nothing else");
431
+ return ancestors;
432
+ }
433
+ function readAppPath(reader, value, path) {
434
+ const appPath = reader.string(value, path);
435
+ if (appPath === void 0) return void 0;
436
+ const error = validateAppPath(appPath);
437
+ if (error) reader.add(path, error);
438
+ return appPath;
439
+ }
440
+ /** The settings an app may leave out. */
441
+ function readAppOptions(reader, raw, path, app) {
442
+ reader.optional(raw, "url", path, (item, itemPath) => reader.url(item, itemPath), (url) => app.url = url);
443
+ reader.optional(raw, "urls", path, (item, itemPath) => reader.record(item, itemPath, (entry, entryPath) => reader.url(entry, entryPath), (key) => ENV_NAME.test(key) ? void 0 : "is not a valid environment name"), (urls) => app.urls = urls);
444
+ reader.optional(raw, "deploy", path, (item, itemPath) => reader.string(item, itemPath), (deploy) => app.deploy = deploy);
445
+ reader.optional(raw, "deployEnv", path, (item, itemPath) => readDeployEnv(reader, item, itemPath), (names) => app.deployEnv = names);
446
+ reader.optional(raw, "headers", path, (item, itemPath) => reader.headers(item, itemPath), (headers) => app.headers = headers);
447
+ reader.optional(raw, "frameAncestors", path, (item, itemPath) => readFrameAncestors(reader, item, itemPath), (ancestors) => app.frameAncestors = ancestors);
448
+ }
449
+ function readApp(reader, value, path) {
450
+ const raw = reader.object(value, path, APP_KEYS);
451
+ if (!raw) return void 0;
452
+ const app = assembleApp({
453
+ type: reader.choice(raw.type, [...path, "type"], APP_TYPES),
454
+ framework: reader.choice(raw.framework, [...path, "framework"], FRAMEWORKS, APP_DEFAULTS.framework),
455
+ path: readAppPath(reader, raw.path, [...path, "path"]),
456
+ port: readPort(reader, raw.port, [...path, "port"]),
457
+ remotes: reader.list(raw.remotes, [...path, "remotes"], (item, itemPath) => reader.string(item, itemPath), []),
458
+ exposes: raw.exposes === void 0 ? {} : readExposes(reader, raw.exposes, [...path, "exposes"])
459
+ });
460
+ if (app) readAppOptions(reader, raw, path, app);
461
+ return app;
462
+ }
463
+ /** The app, once every required setting read cleanly. */
464
+ function assembleApp(parts) {
465
+ const { type, framework, path, port, remotes, exposes } = parts;
466
+ if (!type || !framework || path === void 0 || port === void 0 || !remotes || !exposes) return;
467
+ return {
468
+ type,
469
+ framework,
470
+ path,
471
+ port,
472
+ remotes,
473
+ exposes
474
+ };
475
+ }
476
+ function readPort(reader, value, path) {
477
+ if (typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 65535) return value;
478
+ reader.add(path, "must be a whole number from 1 to 65535");
479
+ }
480
+ function readName(reader, value, path, label, shared) {
481
+ const name = reader.string(value, path);
482
+ if (name === void 0) return void 0;
483
+ const error = validateName(name, label, { shared });
484
+ if (error === void 0) return name;
485
+ reader.add(path, error);
486
+ }
487
+ function readSharedEntry(reader, item, path) {
488
+ const dep = reader.string(item, path);
489
+ if (dep === void 0) return void 0;
490
+ if (dep.trim() === "") {
491
+ reader.add(path, "cannot be empty");
492
+ return;
493
+ }
494
+ return dep;
495
+ }
496
+ /** The server and overrides blocks, present only when the file has them. */
497
+ function readManifestExtras(reader, raw) {
498
+ const extras = {};
499
+ reader.optional(raw, "server", [], (item, path) => readServer(reader, item, path), (server) => extras.server = server);
500
+ reader.optional(raw, "overrides", [], (item, path) => {
501
+ const overrides = reader.object(item, path, ["origins"]);
502
+ const origins = overrides ? reader.list(overrides.origins, [...path, "origins"], (entry, entryPath) => reader.origin(entry, entryPath)) : void 0;
503
+ return origins ? { origins } : void 0;
504
+ }, (overrides) => extras.overrides = overrides);
505
+ return extras;
506
+ }
507
+ /** The manifest, once every required setting read cleanly. */
508
+ function assembleManifest(parts, extras) {
509
+ const { name, shared, packageManager, bundler, shareStrategy, csp, addons, apps } = parts;
510
+ if (!name || !shared || !packageManager || !bundler || !shareStrategy || !csp || !addons || !apps) return;
511
+ return {
512
+ name,
513
+ version: 2,
514
+ packageManager,
515
+ bundler,
516
+ shared,
517
+ shareStrategy,
518
+ csp,
519
+ addons,
520
+ apps,
521
+ ...extras
522
+ };
523
+ }
524
+ /** `raw` must already be version 2. Use `parseManifest` unless the version is known. */
525
+ function readManifest(raw, reader) {
526
+ const shared = reader.list(raw.shared, ["shared"], (item, path) => readSharedEntry(reader, item, path), [...MANIFEST_DEFAULTS.shared]);
527
+ const sharedNames = shared ?? [];
528
+ const name = readName(reader, raw.name, ["name"], "workspace name", sharedNames);
529
+ const packageManager = reader.choice(raw.packageManager, ["packageManager"], PACKAGE_MANAGERS, MANIFEST_DEFAULTS.packageManager);
530
+ const bundler = reader.choice(raw.bundler, ["bundler"], ["vite"], MANIFEST_DEFAULTS.bundler);
531
+ const shareStrategy = reader.choice(raw.shareStrategy, ["shareStrategy"], SHARE_STRATEGIES, MANIFEST_DEFAULTS.shareStrategy);
532
+ const csp = reader.choice(raw.csp, ["csp"], CSP_MODES, MANIFEST_DEFAULTS.csp);
533
+ const addons = reader.list(raw.addons, ["addons"], (item, path) => item === RETIRED_ADDON ? void 0 : reader.choice(item, path, ADDON_NAME_VALUES), []);
534
+ const apps = raw.apps === void 0 ? {} : reader.record(raw.apps, ["apps"], (item, path) => readApp(reader, item, path), (key) => validateName(key, "app name", { shared: sharedNames }));
535
+ const extras = readManifestExtras(reader, raw);
536
+ const parsed = assembleManifest({
537
+ name,
538
+ shared,
539
+ packageManager,
540
+ bundler,
541
+ shareStrategy,
542
+ csp,
543
+ addons,
544
+ apps
545
+ }, extras);
546
+ if (!parsed) return void 0;
547
+ validateRemotes(parsed, reader);
548
+ return parsed;
549
+ }
550
+ function validateRemotes(manifest, reader) {
551
+ for (const [name, app] of Object.entries(manifest.apps)) {
552
+ const seen = /* @__PURE__ */ new Set();
553
+ app.remotes.forEach((remote, index) => {
554
+ const path = [
555
+ "apps",
556
+ name,
557
+ "remotes",
558
+ index
559
+ ];
560
+ if (remote === name) {
561
+ reader.add(path, `App "${name}" lists itself as a remote.`);
562
+ return;
563
+ }
564
+ if (seen.has(remote)) {
565
+ reader.add(path, `App "${name}" lists remote "${remote}" more than once.`);
566
+ return;
567
+ }
568
+ seen.add(remote);
569
+ if (!(remote in manifest.apps)) reader.add(path, `App "${name}" lists remote "${remote}", which is not in this workspace.`);
570
+ });
571
+ }
572
+ const cycle = findRemoteCycle(manifest);
573
+ if (cycle) reader.add(["apps"], `Remotes form a cycle: ${cycle.join(" -> ")}.`);
574
+ }
575
+ /** Depth-first search for a cycle in the remotes graph; returns the first one found. */
576
+ function findRemoteCycle(manifest) {
577
+ const state = /* @__PURE__ */ new Map();
578
+ const stack = [];
579
+ function visit(name) {
580
+ const app = manifest.apps[name];
581
+ if (!app) return void 0;
582
+ state.set(name, "visiting");
583
+ stack.push(name);
584
+ for (const remote of app.remotes) {
585
+ if (!(remote in manifest.apps)) continue;
586
+ if (state.get(remote) === "visiting") {
587
+ const start = stack.indexOf(remote);
588
+ return [...stack.slice(start), remote];
589
+ }
590
+ if (state.get(remote) !== "done") {
591
+ const found = visit(remote);
592
+ if (found) return found;
593
+ }
594
+ }
595
+ stack.pop();
596
+ state.set(name, "done");
597
+ }
598
+ for (const name of Object.keys(manifest.apps)) {
599
+ if (state.get(name) === "done") continue;
600
+ const found = visit(name);
601
+ if (found) return found;
602
+ }
603
+ }
604
+ /** Reads the schema version of a parsed `spool.json`. A missing version means 1. */
605
+ function manifestVersionOf(raw) {
606
+ return isRecord(raw) ? raw.version ?? 1 : void 0;
607
+ }
608
+ /** Validates a parsed `spool.json`. Throws `MANIFEST_VERSION` for version 1 and `MANIFEST_INVALID` for a bad file. */
609
+ function parseManifest(raw) {
610
+ if (!isRecord(raw)) throw new CliError(`Invalid ${MANIFEST_FILE}: it must contain a JSON object.`, "MANIFEST_INVALID");
611
+ const version = manifestVersionOf(raw);
612
+ if (version === 1) throw new CliError(`This workspace uses ${MANIFEST_FILE} version 1, but this CLI reads version ${2}. Run \`spool upgrade\` to migrate it.`, "MANIFEST_VERSION");
613
+ if (version !== 2) throw new CliError(`This workspace uses ${MANIFEST_FILE} version ${String(version)}, but this CLI only understands version ${2}. Upgrade spool and try again.`, "MANIFEST_VERSION");
614
+ const reader = new Reader();
615
+ for (const key of Object.keys(raw)) if (!MANIFEST_KEYS.includes(key)) reader.add([key], "is not a known setting");
616
+ const manifest = readManifest(raw, reader);
617
+ if (!manifest || reader.issues.length) {
618
+ const details = reader.issues.map((issue) => ` - ${issue.path}: ${issue.message}`).join("\n");
619
+ throw new CliError(`Invalid ${MANIFEST_FILE}:\n${details}`, "MANIFEST_INVALID");
620
+ }
621
+ return manifest;
622
+ }
623
+ /** The app called `name`, or an APP_NOT_FOUND error that says where to look. */
624
+ function getApp(manifest, name) {
625
+ const app = manifest.apps[name];
626
+ if (!app) throw new CliError(`No app named "${name}" in this workspace. Check the names in spool.json.`, "APP_NOT_FOUND");
627
+ return app;
628
+ }
629
+
630
+ // src/vite/headers.ts
631
+ /** `self`/`none` become quoted CSP keywords; anything else is a source, written as-is. */
632
+ function frameAncestorsValue(tokens) {
633
+ if (!tokens?.length) return "'self'";
634
+ return tokens.map((token) => token === "self" || token === "none" ? `'${token}'` : token).join(" ");
635
+ }
636
+ function originOf(url) {
637
+ try {
638
+ return new URL(url).origin;
639
+ } catch {
640
+ return;
641
+ }
642
+ }
643
+ /**
644
+ * Where a host may load code and data from in production: the origins of every remote it
645
+ * consumes (each environment's url, and the one this build resolves through SPOOL_REMOTE_*)
646
+ * and the origins a runtime override may use.
647
+ */
648
+ function strictSources(manifest, app, env = process.env) {
649
+ const origins = [...app.remotes.flatMap((name) => {
650
+ const remote = manifest.apps[name];
651
+ return [
652
+ remote?.url,
653
+ ...Object.values(remote?.urls ?? {}),
654
+ env[remoteEnvVar(name)]
655
+ ];
656
+ }).map((url) => url ? originOf(url) : void 0), ...manifest.overrides?.origins ?? []];
657
+ return [...new Set(origins.filter((origin) => origin !== void 0))];
658
+ }
659
+ /**
660
+ * The Content-Security-Policy value for an app. Every app gets `object-src 'none'` and
661
+ * `base-uri 'self'`. `frame-ancestors` is left to the edge when the app lists `edge`, since
662
+ * two CSP headers intersect. `csp: "strict"` adds `script-src` and `connect-src` for builds.
663
+ */
664
+ function contentSecurityPolicy(manifest, app, options) {
665
+ const directives = [];
666
+ if (app.frameAncestors?.[0] !== "edge") directives.push(`frame-ancestors ${frameAncestorsValue(app.frameAncestors)}`);
667
+ directives.push("object-src 'none'", "base-uri 'self'");
668
+ if (manifest.csp === "strict" && options.mode !== "dev") {
669
+ const sources = ["'self'", ...strictSources(manifest, app, options.env)];
670
+ const connect = [.../* @__PURE__ */ new Set([...sources, ...options.connectOrigins ?? []])];
671
+ directives.push(`script-src ${sources.join(" ")}`, `connect-src ${connect.join(" ")}`);
672
+ }
673
+ return directives.join("; ");
674
+ }
675
+ /** A header name or value that would add lines to a headers file or a response. */
676
+ function assertSafe(name, value) {
677
+ if (HEADER_NAME_PATTERN.test(name) && isSafeHeaderValue(value)) return;
678
+ throw new CliError(`Refusing header "${name}": its name or value has characters that split headers.`, "INVALID_VALUE");
679
+ }
680
+ /** The header rules for an app, in the order a `_headers` file lists them. */
681
+ function headerRules(manifest, app, options) {
682
+ const { mode } = options;
683
+ const cors = app.type === "remote" && mode === "build" ? { "Access-Control-Allow-Origin": "*" } : {};
684
+ const policy = contentSecurityPolicy(manifest, app, {
685
+ mode,
686
+ ...options.env ? { env: options.env } : {},
687
+ ...options.connectOrigins ? { connectOrigins: options.connectOrigins } : {}
688
+ });
689
+ const custom = Object.entries(app.headers ?? {});
690
+ for (const [key, value] of custom) assertSafe(key, value);
691
+ return [
692
+ {
693
+ path: "/mf-manifest.json",
694
+ headers: {
695
+ ...cors,
696
+ "Cache-Control": "no-cache"
697
+ }
698
+ },
699
+ {
700
+ path: "/remoteEntry.js",
701
+ headers: {
702
+ ...cors,
703
+ "Cache-Control": "no-cache"
704
+ }
705
+ },
706
+ ...mode === "dev" ? [] : [{
707
+ path: "/assets/*",
708
+ headers: {
709
+ ...cors,
710
+ "Cache-Control": "public, max-age=31536000, immutable"
711
+ }
712
+ }],
713
+ {
714
+ path: "/*",
715
+ headers: {
716
+ "X-Content-Type-Options": "nosniff",
717
+ "Content-Security-Policy": policy,
718
+ ...Object.fromEntries(custom)
719
+ }
720
+ }
721
+ ];
722
+ }
723
+ /** The headers a dev or preview server sends for an app, on every response. */
724
+ function serverHeaders(manifest, app, mode = "dev", connectOrigins = []) {
725
+ return {
726
+ "X-Content-Type-Options": "nosniff",
727
+ "Content-Security-Policy": contentSecurityPolicy(manifest, app, {
728
+ mode,
729
+ connectOrigins
730
+ }),
731
+ ...app.headers,
732
+ ...manifest.server?.headers
733
+ };
734
+ }
735
+ /** The `_headers` file a static host reads: CORS and caching for remotes, and the policy for every page. */
736
+ function headersFile(name, manifest, app, env = process.env, connectOrigins = []) {
737
+ return `# Generated by spool for ${name}. Edit spool.json's headers, frameAncestors and csp, not this file.${app.frameAncestors?.[0] === "edge" ? "\n# frame-ancestors is set by the edge for this app." : ""}\n${headerRules(manifest, app, {
738
+ mode: "build",
739
+ env,
740
+ connectOrigins
741
+ }).map((rule) => {
742
+ const lines = Object.entries(rule.headers).map(([key, value]) => ` ${key}: ${value}`);
743
+ return [rule.path, ...lines].join("\n");
744
+ }).join("\n\n")}\n`;
745
+ }
746
+ /** True when a request path falls under a rule the way a `_headers` file reads it. */
747
+ function ruleMatches(rulePath, requestPath) {
748
+ if (rulePath === "/*") return true;
749
+ if (rulePath.endsWith("/*")) return requestPath.startsWith(rulePath.slice(0, -1));
750
+ return requestPath === rulePath;
751
+ }
752
+ /** Sets every matching rule's headers on a response, so dev and preview answer like a static host. */
753
+ function rulesMiddleware(rules) {
754
+ return (request, response, next) => {
755
+ const path = (request.url ?? "/").split("?")[0] ?? "/";
756
+ for (const rule of rules) {
757
+ if (!ruleMatches(rule.path, path)) continue;
758
+ for (const [key, value] of Object.entries(rule.headers)) response.setHeader(key, value);
759
+ }
760
+ next();
761
+ };
762
+ }
763
+
764
+ // src/core/manifest-file.ts
765
+ /** The folder holding spool.json, looking up from `cwd`, or null when there is none. */
766
+ function findWorkspaceRoot(cwd = process.cwd()) {
767
+ let dir = resolve(cwd);
768
+ for (;;) {
769
+ if (existsSync(join(dir, "spool.json"))) return dir;
770
+ const parent = dirname(dir);
771
+ if (parent === dir) return null;
772
+ dir = parent;
773
+ }
774
+ }
775
+ function requireWorkspaceRoot(cwd = process.cwd()) {
776
+ const root = findWorkspaceRoot(cwd);
777
+ if (root) return root;
778
+ throw new CliError(`No ${MANIFEST_FILE} found. Run \`spool create\` first, or cd into a spool workspace.`, "NO_WORKSPACE");
779
+ }
780
+ /** Parses `spool.json` text, turning a syntax error into a message instead of a stack trace. */
781
+ function parseJson(text) {
782
+ try {
783
+ return JSON.parse(text);
784
+ } catch (error) {
785
+ const reason = error instanceof Error ? error.message : String(error);
786
+ throw new CliError(`${MANIFEST_FILE} is not valid JSON: ${reason}`, "MANIFEST_INVALID");
787
+ }
788
+ }
789
+
790
+ // src/vite/manifest.ts
791
+ /** Reads and validates spool.json with the same parser as the CLI, so a bad file fails at config load. */
792
+ function loadManifest(from) {
793
+ const root = requireWorkspaceRoot(from);
794
+ const raw = parseJson(readFileSync(join(root, MANIFEST_FILE), "utf8"));
795
+ return {
796
+ manifest: parseManifest(raw),
797
+ root
798
+ };
799
+ }
800
+
801
+ // src/vite/sentry-dsn.ts
802
+ const DSN_VARIABLE = "VITE_SENTRY_DSN";
803
+ /** `KEY=value` lines of a dotenv file, the way vite reads them: quotes stripped, `#` comments skipped. */
804
+ function readEnvFile(path) {
805
+ if (!existsSync(path)) return {};
806
+ const values = {};
807
+ for (const line of readFileSync(path, "utf8").split(/\r?\n/)) {
808
+ const [, key, value] = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line) ?? [];
809
+ if (key === void 0 || value === void 0) continue;
810
+ values[key] = value.replace(/^(['"])(.*)\1$/, "$2");
811
+ }
812
+ return values;
813
+ }
814
+ /**
815
+ * The `VITE_SENTRY_DSN` a build would bake in: the environment first, then the app's dotenv
816
+ * files in the order vite loads them (a later file wins).
817
+ */
818
+ function resolveDsn(root, mode, env) {
819
+ if (env[DSN_VARIABLE]) return env[DSN_VARIABLE];
820
+ let dsn;
821
+ for (const file of [
822
+ ".env",
823
+ ".env.local",
824
+ `.env.${mode}`,
825
+ `.env.${mode}.local`
826
+ ]) dsn = readEnvFile(join(root, file))[DSN_VARIABLE] ?? dsn;
827
+ return dsn || void 0;
828
+ }
829
+ /**
830
+ * The origins Sentry events go to, which a strict `connect-src` has to allow. Nothing when the
831
+ * workspace has no sentry addon or no DSN is set, so a build without one stays as tight as it was.
832
+ */
833
+ function sentryConnectOrigins(manifest, root, mode, env = process.env) {
834
+ if (!manifest.addons.includes("sentry")) return [];
835
+ const dsn = resolveDsn(root, mode, env);
836
+ if (!dsn) return [];
837
+ try {
838
+ const url = new URL(dsn);
839
+ return url.protocol === "https:" || url.protocol === "http:" ? [url.origin] : [];
840
+ } catch {
841
+ return [];
842
+ }
843
+ }
844
+
845
+ // src/vite/plugin.ts
846
+ const OVERRIDE_ORIGINS_DEFINE = "__SPOOL_OVERRIDE_ORIGINS__";
847
+ /**
848
+ * The origins a runtime override may load from. A build gets only `overrides.origins`, so
849
+ * production stays as locked down as spool.json says. A dev server also gets every app's own
850
+ * localhost origin, so pointing a host at a local remote needs no configuration.
851
+ */
852
+ function overrideOrigins(manifest, command) {
853
+ const configured = manifest.overrides?.origins ?? [];
854
+ if (command === "build") return configured;
855
+ const local = Object.values(manifest.apps).map((entry) => `http://localhost:${entry.port}`);
856
+ return [.../* @__PURE__ */ new Set([...configured, ...local])];
857
+ }
858
+ /**
859
+ * Preview sets its headers before the build output is known, so a DSN that exists only as a
860
+ * build-time variable cannot reach its `connect-src`. Say so, once, instead of blocking Sentry silently.
861
+ */
862
+ function warnIfSentryOriginMissing(manifest, name, root, connectOrigins) {
863
+ if (manifest.csp !== "strict" || !manifest.addons.includes("sentry")) return;
864
+ if (root === void 0 || connectOrigins.length) return;
865
+ console.warn(`[spool] preview found no VITE_SENTRY_DSN in apps/${name}/.env, so connect-src leaves out Sentry. Put the DSN in .env to preview with it.`);
866
+ }
867
+ /**
868
+ * Defines the origins a runtime override may use, makes the dev and preview servers answer with
869
+ * the same per-path headers a static host would, and writes `_headers` into the build output
870
+ * from spool.json, so the shipped file cannot go stale.
871
+ */
872
+ function spoolPlugin(name, manifest, app, command = "build", options = {}) {
873
+ const origins = overrideOrigins(manifest, command);
874
+ const env = options.env ?? process.env;
875
+ let mode = command === "build" ? "production" : "development";
876
+ const connectOrigins = () => options.root === void 0 ? [] : sentryConnectOrigins(manifest, options.root, mode, env);
877
+ return {
878
+ name: "spool",
879
+ enforce: "pre",
880
+ config: (_userConfig, viteEnv) => {
881
+ if (viteEnv?.mode) mode = viteEnv.mode;
882
+ if (viteEnv?.isPreview) warnIfSentryOriginMissing(manifest, name, options.root, connectOrigins());
883
+ return {
884
+ define: { [OVERRIDE_ORIGINS_DEFINE]: JSON.stringify(origins) },
885
+ preview: { headers: serverHeaders(manifest, app, "preview", connectOrigins()) }
886
+ };
887
+ },
888
+ configureServer: (server) => {
889
+ server.middlewares.use(rulesMiddleware(headerRules(manifest, app, {
890
+ mode: "dev",
891
+ env
892
+ })));
893
+ },
894
+ configurePreviewServer: (server) => {
895
+ server.middlewares.use(rulesMiddleware(headerRules(manifest, app, {
896
+ mode: "preview",
897
+ env,
898
+ connectOrigins: connectOrigins()
899
+ })));
900
+ },
901
+ generateBundle() {
902
+ this.emitFile({
903
+ type: "asset",
904
+ fileName: "_headers",
905
+ source: headersFile(name, manifest, app, env, connectOrigins())
906
+ });
907
+ }
908
+ };
909
+ }
910
+
911
+ // src/vite/watchdog.ts
912
+ const PARENT_CHECK_INTERVAL_MS = 1e3;
913
+ let isWatching = false;
914
+ function isProcessAlive(pid) {
915
+ try {
916
+ process.kill(pid, 0);
917
+ return true;
918
+ } catch {
919
+ return false;
920
+ }
921
+ }
922
+ /**
923
+ * spool sets SPOOL_PARENT_PID on every vite process it starts. Poll for it rather than
924
+ * rely on the child being told: a killed or crashed spool leaves no other signal.
925
+ */
926
+ function watchParent(env = process.env, exit = (code) => process.exit(code), isAlive = isProcessAlive) {
927
+ if (isWatching || !env.SPOOL_PARENT_PID) return;
928
+ const parentPid = Number(env.SPOOL_PARENT_PID);
929
+ if (!Number.isInteger(parentPid) || parentPid <= 0) return;
930
+ isWatching = true;
931
+ setInterval(() => {
932
+ if (!isAlive(parentPid)) exit(0);
933
+ }, PARENT_CHECK_INTERVAL_MS).unref();
934
+ }
935
+
936
+ // src/vite/app.ts
937
+ /**
938
+ * Remote lookup order: the SPOOL_REMOTE_<NAME> env var, then the remote's url for the
939
+ * current SPOOL_ENV, then its plain url, then the local dev server. Only builds read the
940
+ * deployed urls, so dev always stays on localhost.
941
+ */
942
+ function resolveRemoteUrl(name, app, command) {
943
+ const environment = process.env.SPOOL_ENV;
944
+ const deployed = command === "build" ? (environment === void 0 ? void 0 : app.urls?.[environment]) ?? app.url : void 0;
945
+ const override = process.env[remoteEnvVar(name)];
946
+ if (override !== void 0 && !isPublicHttpUrl(override)) throw new CliError(`${remoteEnvVar(name)} must be an http or https URL without a username or password.`, "INVALID_VALUE");
947
+ return override ?? deployed ?? `http://localhost:${app.port}/mf-manifest.json`;
948
+ }
949
+ /**
950
+ * A shared dep the app has not declared in its own package.json is dropped, so apps on
951
+ * different frameworks never share something they do not install.
952
+ */
953
+ function filterDeclaredShared(dir, deps) {
954
+ if (!deps.length) return deps;
955
+ let declared;
956
+ try {
957
+ const packageJson = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
958
+ declared = /* @__PURE__ */ new Set([...Object.keys(packageJson.dependencies ?? {}), ...Object.keys(packageJson.devDependencies ?? {})]);
959
+ } catch {
960
+ console.warn(`[spool] could not read ${join(dir, "package.json")}; sharing no deps for this app. Run spool doctor.`);
961
+ return [];
962
+ }
963
+ return deps.filter((dep) => declared.has(packageName(dep)));
964
+ }
965
+ /** Svelte is never shared, whatever spool.json lists: see docs/adr/0008. */
966
+ function withoutSvelte(deps) {
967
+ return deps.filter((dep) => dep !== "svelte" && !dep.startsWith("svelte/"));
968
+ }
969
+ /** Only these prefixes expand, so a spool.json edit cannot send an unrelated secret anywhere. */
970
+ const EXPANDABLE_ENV = /^(?:SPOOL_|VITE_)/;
971
+ const ENV_REF = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
972
+ /**
973
+ * Expands ${VAR} and ${VAR:-fallback} through the manifest server block, so a proxy target
974
+ * can differ per machine without anyone editing a vite config.
975
+ */
976
+ function expandEnv(value) {
977
+ if (typeof value === "string") return value.replace(ENV_REF, (_, name, fallback) => EXPANDABLE_ENV.test(name) ? process.env[name] ?? fallback ?? "" : fallback ?? "");
978
+ if (Array.isArray(value)) return value.map(expandEnv);
979
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, expandEnv(inner)]));
980
+ return value;
981
+ }
982
+ /** Mirrors vite's searchForWorkspaceRoot, which this file cannot import: vite lives in each app. */
983
+ function findViteWorkspaceRoot(from) {
984
+ const isWorkspace = (dir) => {
985
+ if (existsSync(join(dir, "pnpm-workspace.yaml")) || existsSync(join(dir, "lerna.json"))) return true;
986
+ try {
987
+ const packageJson = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
988
+ return Boolean(packageJson.workspaces);
989
+ } catch {
990
+ return false;
991
+ }
992
+ };
993
+ let packageRoot;
994
+ let dir = resolve(from);
995
+ for (;;) {
996
+ if (isWorkspace(dir)) return dir;
997
+ if (packageRoot === void 0 && existsSync(join(dir, "package.json"))) packageRoot = dir;
998
+ const parent = dirname(dir);
999
+ if (parent === dir) return packageRoot ?? resolve(from);
1000
+ dir = parent;
1001
+ }
1002
+ }
1003
+ /**
1004
+ * Setting server.fs.allow drops vite's default of the workspace root, so it is put back
1005
+ * first. Entries resolve against the spool.json folder.
1006
+ */
1007
+ function buildFsAllow(entries, workspaceRoot, appDir) {
1008
+ const dirs = entries.map((entry) => {
1009
+ const dir = resolve(workspaceRoot, entry);
1010
+ if (entry.trim() === "" || dirname(dir) === dir) throw new CliError(`server.fs.allow entry "${entry}" resolves to "${dir}". Use a folder below the filesystem root.`, "INVALID_PATH");
1011
+ return dir;
1012
+ });
1013
+ return [.../* @__PURE__ */ new Set([findViteWorkspaceRoot(appDir), ...dirs])];
1014
+ }
1015
+ function buildServer(manifest, app, root, appDir) {
1016
+ const origins = manifest.server?.cors ?? Object.values(manifest.apps).map((entry) => `http://localhost:${entry.port}`);
1017
+ const { headers: _headers, fs, cors: _cors, ...rest } = expandEnv(manifest.server ?? {});
1018
+ return {
1019
+ ...rest,
1020
+ port: app.port,
1021
+ strictPort: true,
1022
+ cors: { origin: origins },
1023
+ ...fs ? { fs: { allow: buildFsAllow(fs.allow, root, appDir) } } : {},
1024
+ headers: serverHeaders(manifest, app)
1025
+ };
1026
+ }
1027
+ /**
1028
+ * Everything an app's vite config needs from spool.json: the dev and preview server, the
1029
+ * federation options, and the plugin that writes `_headers`. spool.json is validated with the
1030
+ * CLI's own parser, so a typo fails here with the same message `spool doctor` gives.
1031
+ */
1032
+ function spoolApp(name, options) {
1033
+ try {
1034
+ return createSpoolApp(name, options);
1035
+ } catch (error) {
1036
+ throw addPrefix(error);
1037
+ }
1038
+ }
1039
+ /** One `[spool]` prefix on everything the vite entry throws, like the warnings it logs. */
1040
+ function addPrefix(error) {
1041
+ if (!(error instanceof CliError) || error.message.startsWith("[spool]")) return error;
1042
+ return new CliError(`[spool] ${error.message}`, error.code, error.data);
1043
+ }
1044
+ function createSpoolApp(name, options) {
1045
+ const { root: appDir, command = "build" } = options;
1046
+ watchParent();
1047
+ const { manifest, root } = loadManifest(appDir);
1048
+ const app = getApp(manifest, name);
1049
+ const federation = {
1050
+ name,
1051
+ manifest: true,
1052
+ shared: Object.fromEntries(withoutSvelte(filterDeclaredShared(appDir, manifest.shared)).map((dep) => [dep, { singleton: true }])),
1053
+ shareStrategy: manifest.shareStrategy,
1054
+ dts: false
1055
+ };
1056
+ if (app.remotes.length) federation.remotes = Object.fromEntries(app.remotes.map((remote) => [remote, resolveRemoteUrl(remote, getApp(manifest, remote), command)]));
1057
+ if (app.type === "remote") {
1058
+ federation.filename = "remoteEntry.js";
1059
+ federation.exposes = app.exposes;
1060
+ }
1061
+ return {
1062
+ server: buildServer(manifest, app, root, appDir),
1063
+ federation,
1064
+ plugin: spoolPlugin(name, manifest, app, command, { root: appDir })
1065
+ };
1066
+ }
1067
+
1068
+ export { spoolApp };