@revenexx/integrations-node-devkit 0.3.0 → 0.5.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/cli.cjs CHANGED
@@ -28,15 +28,194 @@ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${_
28
28
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
29
29
 
30
30
  // src/cli.ts
31
- var import_node_fs6 = require("fs");
31
+ var import_node_fs8 = require("fs");
32
32
  var import_node_http2 = require("http");
33
33
  var import_node_module = require("module");
34
- var import_node_path5 = require("path");
34
+ var import_node_path7 = require("path");
35
35
  var import_node_url3 = require("url");
36
36
 
37
- // src/env.ts
37
+ // src/cli-args.ts
38
38
  var import_node_fs = require("fs");
39
39
  var import_node_path = require("path");
40
+
41
+ // src/errors.ts
42
+ var DevApiError = class extends Error {
43
+ constructor(status, message, errors) {
44
+ super(message);
45
+ this.status = status;
46
+ this.errors = errors;
47
+ this.name = "DevApiError";
48
+ }
49
+ status;
50
+ errors;
51
+ };
52
+ var CliError = class extends Error {
53
+ constructor(message) {
54
+ super(message);
55
+ this.name = "CliError";
56
+ }
57
+ };
58
+
59
+ // src/ports.ts
60
+ var import_node_net = require("net");
61
+ var DEFAULT_LIMIT = 20;
62
+ async function listenWithFallback(server, options) {
63
+ const limit = options.strict ? 1 : options.limit ?? DEFAULT_LIMIT;
64
+ const first = options.port;
65
+ for (let port = first; port < first + limit; port += 1) {
66
+ const bound = await bind(server, port);
67
+ if (bound !== null) {
68
+ return bound;
69
+ }
70
+ }
71
+ throw options.strict ? new CliError(`Port ${first} is already in use. Stop whatever is holding it, or pass a different --port.`) : new CliError(`No free port between ${first} and ${first + limit - 1}. Pass --port <n> to choose one explicitly.`);
72
+ }
73
+ function bind(server, port) {
74
+ return new Promise((resolvePort, reject) => {
75
+ const onError = (err) => {
76
+ server.removeListener("listening", onListening);
77
+ if (err.code === "EADDRINUSE") {
78
+ resolvePort(null);
79
+ return;
80
+ }
81
+ reject(err);
82
+ };
83
+ const onListening = () => {
84
+ server.removeListener("error", onError);
85
+ const address = server.address();
86
+ resolvePort(typeof address === "object" && address !== null ? address.port : port);
87
+ };
88
+ server.once("error", onError);
89
+ server.once("listening", onListening);
90
+ server.listen(port);
91
+ });
92
+ }
93
+ async function findFreePort(base, limit = DEFAULT_LIMIT) {
94
+ for (let port = base; port < base + limit; port += 1) {
95
+ if (await isFree(port)) {
96
+ return port;
97
+ }
98
+ }
99
+ throw new CliError(`No free port between ${base} and ${base + limit - 1} for the preview UI.`);
100
+ }
101
+ function isFree(port) {
102
+ return new Promise((resolveFree) => {
103
+ const probe = (0, import_node_net.createServer)();
104
+ probe.once("error", () => resolveFree(false));
105
+ probe.once("listening", () => probe.close(() => resolveFree(true)));
106
+ probe.listen(port);
107
+ });
108
+ }
109
+ function parsePort(value, flag) {
110
+ if (value === void 0 || value.startsWith("-")) {
111
+ throw new CliError(`${flag} needs a port number, e.g. \`${flag} 4000\`.`);
112
+ }
113
+ const port = Number(value);
114
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
115
+ throw new CliError(`${flag} expects an integer between 1 and 65535, got \`${value}\`.`);
116
+ }
117
+ return port;
118
+ }
119
+
120
+ // src/cli-args.ts
121
+ var DEFAULT_PORT = 3555;
122
+ function parseArgs(argv, env = process.env) {
123
+ const cwd = process.cwd();
124
+ const opts = {
125
+ entry: "",
126
+ seedDir: (0, import_node_path.resolve)(cwd, "dev/seeds"),
127
+ stateFile: (0, import_node_path.resolve)(cwd, ".revenexx-dev/state.json"),
128
+ persist: true,
129
+ port: env.PORT === void 0 ? DEFAULT_PORT : parsePort(env.PORT, "$PORT"),
130
+ portExplicit: env.PORT !== void 0,
131
+ uiDir: null,
132
+ serveUi: true,
133
+ open: false,
134
+ previewDir: null,
135
+ force: false,
136
+ parallel: false
137
+ };
138
+ let command = null;
139
+ for (let i = 0; i < argv.length; i++) {
140
+ const arg = argv[i];
141
+ switch (arg) {
142
+ case "reset":
143
+ command = "reset";
144
+ break;
145
+ case "init-preview":
146
+ command = "init-preview";
147
+ break;
148
+ case "preview":
149
+ command = "preview";
150
+ break;
151
+ case "--dir":
152
+ opts.previewDir = (0, import_node_path.resolve)(cwd, argv[++i] ?? "");
153
+ break;
154
+ case "--force":
155
+ opts.force = true;
156
+ break;
157
+ case "--parallel":
158
+ opts.parallel = true;
159
+ break;
160
+ case "--entry":
161
+ opts.entry = (0, import_node_path.resolve)(cwd, argv[++i] ?? "");
162
+ break;
163
+ case "--seed":
164
+ opts.seedDir = (0, import_node_path.resolve)(cwd, argv[++i] ?? "");
165
+ break;
166
+ case "--state":
167
+ opts.stateFile = (0, import_node_path.resolve)(cwd, argv[++i] ?? "");
168
+ break;
169
+ case "--no-persist":
170
+ opts.persist = false;
171
+ break;
172
+ case "--port":
173
+ opts.port = parsePort(argv[++i], "--port");
174
+ opts.portExplicit = true;
175
+ break;
176
+ case "--ui":
177
+ opts.uiDir = (0, import_node_path.resolve)(cwd, argv[++i] ?? "");
178
+ break;
179
+ case "--no-ui":
180
+ opts.serveUi = false;
181
+ break;
182
+ case "--open":
183
+ opts.open = true;
184
+ break;
185
+ // Both are consumed by loadEnvFile() before parsing; listed here so they
186
+ // do not fall through to the unknown-option branch. A repeated `--env`
187
+ // resolves to the last one, so each occurrence skips its own value.
188
+ case "--env":
189
+ i++;
190
+ break;
191
+ case "--no-env":
192
+ break;
193
+ case "--version":
194
+ case "-v":
195
+ command = "version";
196
+ break;
197
+ default:
198
+ if (arg?.startsWith("--env-file")) {
199
+ if (!arg.includes("=")) {
200
+ i++;
201
+ }
202
+ break;
203
+ }
204
+ if (arg?.startsWith("-")) {
205
+ throw new CliError(`Unknown option: ${arg}`);
206
+ }
207
+ }
208
+ }
209
+ if (!opts.entry) {
210
+ const src = (0, import_node_path.resolve)(cwd, "src/index.ts");
211
+ opts.entry = (0, import_node_fs.existsSync)(src) ? src : (0, import_node_path.resolve)(cwd, "dist/index.js");
212
+ }
213
+ return { command, options: opts };
214
+ }
215
+
216
+ // src/env.ts
217
+ var import_node_fs2 = require("fs");
218
+ var import_node_path2 = require("path");
40
219
  var ENV_FILE_MIN_NODE = "20.12";
41
220
  var NODE_OWNED_FLAGS = ["--env-file", "--env-file-if-exists"];
42
221
  function nodeOwnedEnvFlag(argv) {
@@ -55,13 +234,13 @@ function resolveEnvFile(argv, cwd = process.cwd()) {
55
234
  if (!value || value.startsWith("-")) {
56
235
  throw new Error("--env requires a path.");
57
236
  }
58
- named = { path: (0, import_node_path.resolve)(cwd, value), explicit: true, raw: value };
237
+ named = { path: (0, import_node_path2.resolve)(cwd, value), explicit: true, raw: value };
59
238
  }
60
- return named ?? { path: (0, import_node_path.resolve)(cwd, ".env"), explicit: false };
239
+ return named ?? { path: (0, import_node_path2.resolve)(cwd, ".env"), explicit: false };
61
240
  }
62
241
  function missingFileMessage(choice, cwd) {
63
242
  const raw = choice.raw;
64
- if (raw && raw === (0, import_node_path.basename)(raw) && (0, import_node_fs.existsSync)((0, import_node_path.resolve)(cwd, `.env.${raw}`))) {
243
+ if (raw && raw === (0, import_node_path2.basename)(raw) && (0, import_node_fs2.existsSync)((0, import_node_path2.resolve)(cwd, `.env.${raw}`))) {
65
244
  return `--env: ${choice.path} does not exist. Did you mean --env .env.${raw}? The flag takes a path, not an environment name.`;
66
245
  }
67
246
  return `--env: ${choice.path} does not exist.`;
@@ -76,7 +255,7 @@ function loadEnvFile(argv, options = {}) {
76
255
  if (!choice.path) {
77
256
  return null;
78
257
  }
79
- if (!(0, import_node_fs.existsSync)(choice.path)) {
258
+ if (!(0, import_node_fs2.existsSync)(choice.path)) {
80
259
  if (choice.explicit) {
81
260
  throw new Error(missingFileMessage(choice, cwd));
82
261
  }
@@ -91,40 +270,28 @@ function loadEnvFile(argv, options = {}) {
91
270
  }
92
271
 
93
272
  // src/index.ts
94
- var import_node_fs4 = require("fs");
95
-
96
- // src/errors.ts
97
- var DevApiError = class extends Error {
98
- constructor(status, message, errors) {
99
- super(message);
100
- this.status = status;
101
- this.errors = errors;
102
- this.name = "DevApiError";
103
- }
104
- status;
105
- errors;
106
- };
273
+ var import_node_fs5 = require("fs");
107
274
 
108
275
  // src/loader.ts
109
- var import_node_fs2 = require("fs");
110
- var import_node_path2 = require("path");
276
+ var import_node_fs3 = require("fs");
277
+ var import_node_path3 = require("path");
111
278
  var import_node_url = require("url");
112
279
  var import_integrations_node_sdk = require("@revenexx/integrations-node-sdk");
113
280
  var UNKNOWN_PACKAGE = { name: "unknown", version: "0.0.0", label: "Local package" };
114
281
  function readPackageInfo(entryPath) {
115
- let dir = (0, import_node_path2.dirname)(entryPath);
282
+ let dir = (0, import_node_path3.dirname)(entryPath);
116
283
  for (let up = 0; up < 6; up += 1) {
117
- const candidate = (0, import_node_path2.join)(dir, "package.json");
118
- if ((0, import_node_fs2.existsSync)(candidate)) {
284
+ const candidate = (0, import_node_path3.join)(dir, "package.json");
285
+ if ((0, import_node_fs3.existsSync)(candidate)) {
119
286
  try {
120
- const pkg = JSON.parse((0, import_node_fs2.readFileSync)(candidate, "utf-8"));
287
+ const pkg = JSON.parse((0, import_node_fs3.readFileSync)(candidate, "utf-8"));
121
288
  if (pkg.name) {
122
289
  return { name: pkg.name, version: pkg.version ?? "0.0.0", label: pkg.name.split("/").pop() ?? pkg.name };
123
290
  }
124
291
  } catch {
125
292
  }
126
293
  }
127
- const parent = (0, import_node_path2.dirname)(dir);
294
+ const parent = (0, import_node_path3.dirname)(dir);
128
295
  if (parent === dir) break;
129
296
  dir = parent;
130
297
  }
@@ -177,8 +344,8 @@ async function loadPackageFromEntry(entryPath) {
177
344
  }
178
345
 
179
346
  // src/persistence.ts
180
- var import_node_fs3 = require("fs");
181
- var import_node_path3 = require("path");
347
+ var import_node_fs4 = require("fs");
348
+ var import_node_path4 = require("path");
182
349
 
183
350
  // src/store.ts
184
351
  var import_node_crypto = require("crypto");
@@ -492,12 +659,12 @@ function applySeeds(store, seeds, env = process.env) {
492
659
  }
493
660
  }
494
661
  function loadState(file, log = console.warn) {
495
- if (!(0, import_node_fs3.existsSync)(file)) {
662
+ if (!(0, import_node_fs4.existsSync)(file)) {
496
663
  return null;
497
664
  }
498
665
  let parsed;
499
666
  try {
500
- parsed = JSON.parse((0, import_node_fs3.readFileSync)(file, "utf-8"));
667
+ parsed = JSON.parse((0, import_node_fs4.readFileSync)(file, "utf-8"));
501
668
  } catch {
502
669
  log(`Ignoring ${file}: not valid JSON.`);
503
670
  return null;
@@ -509,14 +676,14 @@ function loadState(file, log = console.warn) {
509
676
  return parsed;
510
677
  }
511
678
  function saveState(file, snapshot) {
512
- (0, import_node_fs3.mkdirSync)((0, import_node_path3.dirname)(file), { recursive: true });
513
- (0, import_node_fs3.writeFileSync)(file, JSON.stringify(snapshot, null, 2), "utf-8");
679
+ (0, import_node_fs4.mkdirSync)((0, import_node_path4.dirname)(file), { recursive: true });
680
+ (0, import_node_fs4.writeFileSync)(file, JSON.stringify(snapshot, null, 2), "utf-8");
514
681
  }
515
682
  var SEED_ENTRY_CANDIDATES = ["index.ts", "index.mjs", "index.js", "seeds.ts", "seeds.js"];
516
683
  async function loadSeedsFromDir(dir) {
517
684
  for (const candidate of SEED_ENTRY_CANDIDATES) {
518
- const path = (0, import_node_path3.resolve)(dir, candidate);
519
- if ((0, import_node_fs3.existsSync)(path)) {
685
+ const path = (0, import_node_path4.resolve)(dir, candidate);
686
+ if ((0, import_node_fs4.existsSync)(path)) {
520
687
  const mod = await importFresh(path);
521
688
  return mod.default ?? mod.seeds ?? {};
522
689
  }
@@ -1450,37 +1617,71 @@ async function handleWorkflows(req, res, method, store, seg) {
1450
1617
 
1451
1618
  // src/index.ts
1452
1619
  var manifestUrl = new URL("../package.json", importMetaUrl);
1453
- var DEVKIT_VERSION = JSON.parse((0, import_node_fs4.readFileSync)(manifestUrl, "utf8")).version;
1620
+ var DEVKIT_VERSION = JSON.parse((0, import_node_fs5.readFileSync)(manifestUrl, "utf8")).version;
1621
+
1622
+ // src/preview/child-env.ts
1623
+ function previewChildEnv(options) {
1624
+ const env = { ...options.base };
1625
+ delete env.PORT;
1626
+ return {
1627
+ ...env,
1628
+ NUXT_PUBLIC_INTEGRATIONS_API: options.apiUrl,
1629
+ NUXT_PUBLIC_DEV_TOKEN: options.base.NUXT_PUBLIC_DEV_TOKEN ?? "dev",
1630
+ NUXT_PUBLIC_DEV_TENANT: options.base.NUXT_PUBLIC_DEV_TENANT ?? "dev-tenant",
1631
+ NUXT_PORT: String(options.uiPort),
1632
+ DEVKIT_NUXT_BUILD_DIR: options.buildDir,
1633
+ DEVKIT_VITE_CACHE_DIR: options.viteCacheDir
1634
+ };
1635
+ }
1454
1636
 
1455
1637
  // src/preview/host.ts
1456
1638
  var import_node_crypto2 = require("crypto");
1457
- var import_node_fs5 = require("fs");
1639
+ var import_node_fs6 = require("fs");
1458
1640
  var import_node_os = require("os");
1459
- var import_node_path4 = require("path");
1641
+ var import_node_path5 = require("path");
1460
1642
  var import_node_url2 = require("url");
1643
+
1644
+ // src/preview/pid.ts
1645
+ function pidIsAlive(pid) {
1646
+ if (!Number.isInteger(pid) || pid <= 0) {
1647
+ return false;
1648
+ }
1649
+ try {
1650
+ process.kill(pid, 0);
1651
+ return true;
1652
+ } catch (err) {
1653
+ return err.code === "EPERM";
1654
+ }
1655
+ }
1656
+
1657
+ // src/preview/host.ts
1461
1658
  var INSTALL_MARKER = ".devkit-install-complete";
1462
1659
  var COPY_MARKER = ".devkit-copy-complete";
1660
+ var INSTALL_LOCK = ".devkit-install.lock";
1463
1661
  var HOST_GITIGNORE = `node_modules/
1464
1662
  .nuxt/
1465
1663
  .nuxt-*/
1664
+ .vite-*/
1466
1665
  .output/
1467
1666
  .data/
1468
- .env
1667
+ .env*
1668
+ previews/
1469
1669
  ${COPY_MARKER}
1470
1670
  ${INSTALL_MARKER}
1671
+ ${INSTALL_LOCK}
1471
1672
  `;
1472
1673
  function resolveHostDir(options) {
1473
- const root = options.cacheRoot ?? process.env.XDG_CACHE_HOME ?? (0, import_node_path4.join)((0, import_node_os.homedir)(), ".cache");
1474
- return (0, import_node_path4.join)(root, "revenexx", "devkit-preview", options.version);
1674
+ const root = options.cacheRoot ?? process.env.XDG_CACHE_HOME ?? (0, import_node_path5.join)((0, import_node_os.homedir)(), ".cache");
1675
+ return (0, import_node_path5.join)(root, "revenexx", "devkit-preview", options.version);
1475
1676
  }
1476
1677
  function shippedHostDir() {
1477
- let dir = (0, import_node_path4.dirname)((0, import_node_url2.fileURLToPath)(importMetaUrl));
1678
+ let dir = (0, import_node_path5.dirname)((0, import_node_url2.fileURLToPath)(importMetaUrl));
1478
1679
  for (let up = 0; up < 5; up += 1) {
1479
- const candidate = (0, import_node_path4.join)(dir, "preview-host");
1480
- if ((0, import_node_fs5.existsSync)((0, import_node_path4.join)(candidate, "nuxt.config.ts"))) {
1680
+ const candidate = (0, import_node_path5.join)(dir, "preview-host");
1681
+ if ((0, import_node_fs6.existsSync)((0, import_node_path5.join)(candidate, "nuxt.config.ts"))) {
1481
1682
  return candidate;
1482
1683
  }
1483
- const parent = (0, import_node_path4.dirname)(dir);
1684
+ const parent = (0, import_node_path5.dirname)(dir);
1484
1685
  if (parent === dir) break;
1485
1686
  dir = parent;
1486
1687
  }
@@ -1490,172 +1691,246 @@ function materializeHost(options) {
1490
1691
  const log = options.log ?? (() => {
1491
1692
  });
1492
1693
  const source = options.sourceDir ?? shippedHostDir();
1493
- const dir = (0, import_node_path4.resolve)(options.targetDir);
1694
+ const dir = (0, import_node_path5.resolve)(options.targetDir);
1494
1695
  const managed = options.managed ?? false;
1495
- const intact = managed ? hostIsComplete(dir) : hostExists(dir);
1696
+ const intact = managed ? hostIsComplete(dir) && copyIsCurrent(dir, source) : hostExists(dir);
1496
1697
  const alreadyIntact = intact && !options.force;
1497
1698
  if (!alreadyIntact) {
1498
- (0, import_node_fs5.mkdirSync)(dir, { recursive: true });
1499
- (0, import_node_fs5.rmSync)((0, import_node_path4.join)(dir, COPY_MARKER), { force: true });
1500
- (0, import_node_fs5.cpSync)(source, dir, { recursive: true, filter: (src) => !isInsideNodeModules(source, src) });
1501
- (0, import_node_fs5.writeFileSync)((0, import_node_path4.join)(dir, COPY_MARKER), `${(/* @__PURE__ */ new Date()).toISOString()}
1699
+ (0, import_node_fs6.mkdirSync)(dir, { recursive: true });
1700
+ (0, import_node_fs6.rmSync)((0, import_node_path5.join)(dir, COPY_MARKER), { force: true });
1701
+ (0, import_node_fs6.cpSync)(source, dir, { recursive: true, filter: (src) => !isInsideNodeModules(source, src) });
1702
+ (0, import_node_fs6.writeFileSync)((0, import_node_path5.join)(dir, COPY_MARKER), `${sourceFingerprint(source)}
1703
+ ${(/* @__PURE__ */ new Date()).toISOString()}
1502
1704
  `, "utf-8");
1503
- (0, import_node_fs5.writeFileSync)((0, import_node_path4.join)(dir, ".gitignore"), HOST_GITIGNORE, "utf-8");
1705
+ (0, import_node_fs6.writeFileSync)((0, import_node_path5.join)(dir, ".gitignore"), HOST_GITIGNORE, "utf-8");
1504
1706
  log(`Preview host ready in ${dir}`);
1505
1707
  }
1506
- const envPath = (0, import_node_path4.join)(dir, ".env");
1507
- if (managed || !(0, import_node_fs5.existsSync)(envPath)) {
1508
- (0, import_node_fs5.writeFileSync)(envPath, envFile(options), "utf-8");
1708
+ const envPath = (0, import_node_path5.join)(dir, options.dotenvName ?? ".env");
1709
+ if (managed || !(0, import_node_fs6.existsSync)(envPath)) {
1710
+ (0, import_node_fs6.writeFileSync)(envPath, envFile(options), "utf-8");
1509
1711
  }
1510
1712
  return { dir, copied: !alreadyIntact };
1511
1713
  }
1512
1714
  function isInsideNodeModules(source, src) {
1513
- const rel = (0, import_node_path4.relative)(source, src);
1514
- return rel !== "" && rel.split(import_node_path4.sep).includes("node_modules");
1715
+ const rel = (0, import_node_path5.relative)(source, src);
1716
+ return rel !== "" && rel.split(import_node_path5.sep).includes("node_modules");
1717
+ }
1718
+ function sourceFingerprint(source) {
1719
+ const hash = (0, import_node_crypto2.createHash)("sha256");
1720
+ for (const file of listFiles(source, source).sort()) {
1721
+ hash.update(file);
1722
+ hash.update((0, import_node_fs6.readFileSync)((0, import_node_path5.join)(source, file)));
1723
+ }
1724
+ return hash.digest("hex").slice(0, 16);
1725
+ }
1726
+ function listFiles(root, dir) {
1727
+ const files = [];
1728
+ for (const entry of (0, import_node_fs6.readdirSync)(dir, { withFileTypes: true })) {
1729
+ if (entry.name === "node_modules") {
1730
+ continue;
1731
+ }
1732
+ const full = (0, import_node_path5.join)(dir, entry.name);
1733
+ if (entry.isDirectory()) {
1734
+ files.push(...listFiles(root, full));
1735
+ } else if (entry.isFile()) {
1736
+ files.push((0, import_node_path5.relative)(root, full));
1737
+ }
1738
+ }
1739
+ return files;
1740
+ }
1741
+ function copyIsCurrent(dir, source) {
1742
+ try {
1743
+ const recorded = (0, import_node_fs6.readFileSync)((0, import_node_path5.join)(dir, COPY_MARKER), "utf-8").split("\n")[0]?.trim();
1744
+ return recorded === sourceFingerprint(source);
1745
+ } catch {
1746
+ return false;
1747
+ }
1515
1748
  }
1516
1749
  function envFile(options) {
1750
+ const name = options.dotenvName ?? ".env";
1751
+ const manual = name === ".env" ? "npm run dev" : `npm run dev -- --dotenv ${name}`;
1517
1752
  return `# Generated by integrations-devkit \u2014 overrides the Nuxt runtimeConfig.public.* values.
1518
1753
  # The \`preview\` command also passes these to the Nuxt child process; this file is
1519
- # what makes a manual \`npm run dev\` in this directory work.
1754
+ # what makes a manual \`${manual}\` in this directory work.
1520
1755
  NUXT_PUBLIC_INTEGRATIONS_API=${options.integrationsApiUrl}
1521
1756
  NUXT_PUBLIC_DEV_TOKEN=${options.devToken ?? "dev"}
1522
1757
  NUXT_PUBLIC_DEV_TENANT=${options.devTenant ?? "dev-tenant"}
1523
1758
  `;
1524
1759
  }
1760
+ function consumerKey(consumerDir) {
1761
+ return (0, import_node_crypto2.createHash)("sha256").update(consumerDir).digest("hex").slice(0, 12);
1762
+ }
1525
1763
  function hostBuildDir(hostDir, consumerDir) {
1526
- const key = (0, import_node_crypto2.createHash)("sha256").update(consumerDir).digest("hex").slice(0, 12);
1527
- return (0, import_node_path4.join)(hostDir, `.nuxt-${key}`);
1764
+ return (0, import_node_path5.join)(hostDir, `.nuxt-${consumerKey(consumerDir)}`);
1765
+ }
1766
+ function hostViteCacheDir(hostDir, consumerDir) {
1767
+ return (0, import_node_path5.join)(hostDir, `.vite-${consumerKey(consumerDir)}`);
1768
+ }
1769
+ function hostDotenvName(consumerDir) {
1770
+ return `.env.${consumerKey(consumerDir)}`;
1528
1771
  }
1529
1772
  function hostExists(dir) {
1530
- return (0, import_node_fs5.existsSync)((0, import_node_path4.join)(dir, "package.json")) && (0, import_node_fs5.existsSync)((0, import_node_path4.join)(dir, "nuxt.config.ts"));
1773
+ return (0, import_node_fs6.existsSync)((0, import_node_path5.join)(dir, "package.json")) && (0, import_node_fs6.existsSync)((0, import_node_path5.join)(dir, "nuxt.config.ts"));
1531
1774
  }
1532
1775
  function hostIsComplete(dir) {
1533
- return hostExists(dir) && (0, import_node_fs5.existsSync)((0, import_node_path4.join)(dir, COPY_MARKER));
1776
+ return hostExists(dir) && (0, import_node_fs6.existsSync)((0, import_node_path5.join)(dir, COPY_MARKER));
1534
1777
  }
1535
1778
  function hostNeedsInstall(dir) {
1536
- const marker = (0, import_node_path4.join)(dir, INSTALL_MARKER);
1537
- if (!(0, import_node_fs5.existsSync)((0, import_node_path4.join)(dir, "node_modules")) || !(0, import_node_fs5.existsSync)(marker)) {
1779
+ const marker = (0, import_node_path5.join)(dir, INSTALL_MARKER);
1780
+ if (!(0, import_node_fs6.existsSync)((0, import_node_path5.join)(dir, "node_modules")) || !(0, import_node_fs6.existsSync)(marker)) {
1538
1781
  return true;
1539
1782
  }
1540
1783
  try {
1541
- return (0, import_node_fs5.readFileSync)(marker, "utf-8").trim() !== manifestFingerprint(dir);
1784
+ return (0, import_node_fs6.readFileSync)(marker, "utf-8").trim() !== manifestFingerprint(dir);
1542
1785
  } catch {
1543
1786
  return true;
1544
1787
  }
1545
1788
  }
1546
1789
  function markHostInstalled(dir) {
1547
- (0, import_node_fs5.writeFileSync)((0, import_node_path4.join)(dir, INSTALL_MARKER), `${manifestFingerprint(dir)}
1790
+ (0, import_node_fs6.writeFileSync)((0, import_node_path5.join)(dir, INSTALL_MARKER), `${manifestFingerprint(dir)}
1548
1791
  `, "utf-8");
1549
1792
  }
1550
1793
  function clearHostInstallMarker(dir) {
1551
- (0, import_node_fs5.rmSync)((0, import_node_path4.join)(dir, INSTALL_MARKER), { force: true });
1794
+ (0, import_node_fs6.rmSync)((0, import_node_path5.join)(dir, INSTALL_MARKER), { force: true });
1795
+ }
1796
+ async function withInstallLock(dir, install, options = {}) {
1797
+ const isAlive = options.isAlive ?? pidIsAlive;
1798
+ const log = options.log ?? (() => {
1799
+ });
1800
+ const timeoutMs = options.timeoutMs ?? 20 * 6e4;
1801
+ const pollMs = options.pollMs ?? 500;
1802
+ const lockPath = (0, import_node_path5.join)(dir, INSTALL_LOCK);
1803
+ const deadline = Date.now() + timeoutMs;
1804
+ let waitingFor = null;
1805
+ while (!acquire(lockPath)) {
1806
+ const holder = lockHolder(lockPath);
1807
+ if (holder === null || !isAlive(holder)) {
1808
+ (0, import_node_fs6.rmSync)(lockPath, { force: true });
1809
+ continue;
1810
+ }
1811
+ if (holder !== waitingFor) {
1812
+ waitingFor = holder;
1813
+ log(`Another devkit (PID ${holder}) is installing the preview host's dependencies \u2014 waiting for it to finish\u2026`);
1814
+ }
1815
+ if (Date.now() > deadline) {
1816
+ throw new CliError(`Timed out after ${Math.round(timeoutMs / 6e4)} min waiting for PID ${holder} to finish installing in ${dir}. If that process is gone, delete ${lockPath}.`);
1817
+ }
1818
+ await new Promise((done) => setTimeout(done, pollMs));
1819
+ }
1820
+ try {
1821
+ if (options.needsInstall && !options.needsInstall()) {
1822
+ return null;
1823
+ }
1824
+ return await install();
1825
+ } finally {
1826
+ (0, import_node_fs6.rmSync)(lockPath, { force: true });
1827
+ }
1828
+ }
1829
+ function acquire(lockPath) {
1830
+ try {
1831
+ (0, import_node_fs6.mkdirSync)((0, import_node_path5.dirname)(lockPath), { recursive: true });
1832
+ (0, import_node_fs6.writeFileSync)(lockPath, `${process.pid}
1833
+ ${(/* @__PURE__ */ new Date()).toISOString()}
1834
+ `, { encoding: "utf-8", flag: "wx" });
1835
+ return true;
1836
+ } catch {
1837
+ return false;
1838
+ }
1839
+ }
1840
+ function lockHolder(lockPath) {
1841
+ try {
1842
+ const pid = Number.parseInt((0, import_node_fs6.readFileSync)(lockPath, "utf-8").split("\n")[0] ?? "", 10);
1843
+ return Number.isInteger(pid) ? pid : null;
1844
+ } catch {
1845
+ return null;
1846
+ }
1552
1847
  }
1553
1848
  function manifestFingerprint(dir) {
1554
- const pkg = JSON.parse((0, import_node_fs5.readFileSync)((0, import_node_path4.join)(dir, "package.json"), "utf-8"));
1849
+ const pkg = JSON.parse((0, import_node_fs6.readFileSync)((0, import_node_path5.join)(dir, "package.json"), "utf-8"));
1555
1850
  return JSON.stringify({ dependencies: pkg.dependencies ?? {}, devDependencies: pkg.devDependencies ?? {} });
1556
1851
  }
1557
1852
 
1558
- // src/cli.ts
1559
- function parseArgs(argv) {
1560
- const cwd = process.cwd();
1561
- const opts = {
1562
- entry: "",
1563
- seedDir: (0, import_node_path5.resolve)(cwd, "dev/seeds"),
1564
- stateFile: (0, import_node_path5.resolve)(cwd, ".revenexx-dev/state.json"),
1565
- persist: true,
1566
- port: Number.parseInt(process.env.PORT ?? "3555", 10),
1567
- uiDir: null,
1568
- serveUi: true,
1569
- open: false,
1570
- previewDir: null,
1571
- force: false
1572
- };
1573
- let command = null;
1574
- for (let i = 0; i < argv.length; i++) {
1575
- const arg = argv[i];
1576
- switch (arg) {
1577
- case "reset":
1578
- command = "reset";
1579
- break;
1580
- case "init-preview":
1581
- command = "init-preview";
1582
- break;
1583
- case "preview":
1584
- command = "preview";
1585
- break;
1586
- case "--dir":
1587
- opts.previewDir = (0, import_node_path5.resolve)(cwd, argv[++i] ?? "");
1588
- break;
1589
- case "--force":
1590
- opts.force = true;
1591
- break;
1592
- case "--entry":
1593
- opts.entry = (0, import_node_path5.resolve)(cwd, argv[++i] ?? "");
1594
- break;
1595
- case "--seed":
1596
- opts.seedDir = (0, import_node_path5.resolve)(cwd, argv[++i] ?? "");
1597
- break;
1598
- case "--state":
1599
- opts.stateFile = (0, import_node_path5.resolve)(cwd, argv[++i] ?? "");
1600
- break;
1601
- case "--no-persist":
1602
- opts.persist = false;
1603
- break;
1604
- case "--port":
1605
- opts.port = Number.parseInt(argv[++i] ?? "3555", 10);
1606
- break;
1607
- case "--ui":
1608
- opts.uiDir = (0, import_node_path5.resolve)(cwd, argv[++i] ?? "");
1609
- break;
1610
- case "--no-ui":
1611
- opts.serveUi = false;
1612
- break;
1613
- case "--open":
1614
- opts.open = true;
1615
- break;
1616
- // Both are consumed by loadEnvFile() before parsing; listed here so they
1617
- // do not fall through to the unknown-option branch. A repeated `--env`
1618
- // resolves to the last one, so each occurrence skips its own value.
1619
- case "--env":
1620
- i++;
1621
- break;
1622
- case "--no-env":
1623
- break;
1624
- case "--version":
1625
- case "-v":
1626
- command = "version";
1627
- break;
1628
- default:
1629
- if (arg?.startsWith("--env-file")) {
1630
- if (!arg.includes("=")) {
1631
- i++;
1632
- }
1633
- break;
1634
- }
1635
- if (arg?.startsWith("-")) {
1636
- console.error(`Unknown option: ${arg}`);
1637
- process.exit(1);
1638
- }
1853
+ // src/preview/registry.ts
1854
+ var import_node_fs7 = require("fs");
1855
+ var import_node_path6 = require("path");
1856
+ var REGISTRY_DIR = "previews";
1857
+ function readLivePreviews(hostDir, isAlive = pidIsAlive) {
1858
+ const dir = (0, import_node_path6.join)(hostDir, REGISTRY_DIR);
1859
+ if (!(0, import_node_fs7.existsSync)(dir)) {
1860
+ return [];
1861
+ }
1862
+ const live = [];
1863
+ for (const file of (0, import_node_fs7.readdirSync)(dir)) {
1864
+ if (!file.endsWith(".json")) {
1865
+ continue;
1866
+ }
1867
+ const path = (0, import_node_path6.join)(dir, file);
1868
+ const entry = readEntry(path);
1869
+ if (entry && isAlive(entry.pid)) {
1870
+ live.push(entry);
1871
+ } else {
1872
+ (0, import_node_fs7.rmSync)(path, { force: true });
1639
1873
  }
1640
1874
  }
1641
- if (!opts.entry) {
1642
- const src = (0, import_node_path5.resolve)(cwd, "src/index.ts");
1643
- opts.entry = (0, import_node_fs6.existsSync)(src) ? src : (0, import_node_path5.resolve)(cwd, "dist/index.js");
1875
+ return live.sort((a, b) => a.startedAt.localeCompare(b.startedAt));
1876
+ }
1877
+ function readEntry(path) {
1878
+ try {
1879
+ const parsed = JSON.parse((0, import_node_fs7.readFileSync)(path, "utf-8"));
1880
+ return Number.isInteger(parsed?.pid) ? parsed : null;
1881
+ } catch {
1882
+ return null;
1644
1883
  }
1645
- return { command, options: opts };
1646
1884
  }
1885
+ function registerPreview(hostDir, entry) {
1886
+ const dir = (0, import_node_path6.join)(hostDir, REGISTRY_DIR);
1887
+ (0, import_node_fs7.mkdirSync)(dir, { recursive: true });
1888
+ (0, import_node_fs7.writeFileSync)((0, import_node_path6.join)(dir, `${entry.pid}.json`), `${JSON.stringify(entry, null, 2)}
1889
+ `, "utf-8");
1890
+ }
1891
+ function unregisterPreview(hostDir, pid = process.pid) {
1892
+ (0, import_node_fs7.rmSync)((0, import_node_path6.join)(hostDir, REGISTRY_DIR, `${pid}.json`), { force: true });
1893
+ }
1894
+ function describePreview(entry) {
1895
+ return `${(0, import_node_path6.basename)(entry.cwd)} (PID ${entry.pid}, mock :${entry.mockPort}, UI :${entry.uiPort}) \u2014 ${entry.cwd}`;
1896
+ }
1897
+ function previewConflict(running, options) {
1898
+ const sameRepo = running.find((entry) => entry.cwd === options.cwd);
1899
+ if (sameRepo) {
1900
+ return [
1901
+ `A preview of this very package is already running: ${describePreview(sameRepo)}`,
1902
+ "",
1903
+ "Two previews of one package share a build directory and would serve each other's",
1904
+ "output, so this is refused even with --parallel. Stop that one first."
1905
+ ].join("\n");
1906
+ }
1907
+ if (options.force && running.length > 0) {
1908
+ return `--force reinstalls the host's dependencies, which would pull node_modules out from under the preview still running in ${running[0]?.cwd}. Stop it first.`;
1909
+ }
1910
+ if (running.length > 0 && !options.parallel) {
1911
+ return [
1912
+ `A preview is already running out of ${options.hostDir}:`,
1913
+ ...running.map((entry) => ` ${describePreview(entry)}`),
1914
+ "",
1915
+ "Stop it (Ctrl-C in its terminal), or run this one alongside it with --parallel."
1916
+ ].join("\n");
1917
+ }
1918
+ return null;
1919
+ }
1920
+
1921
+ // src/cli.ts
1647
1922
  function loadSchemas() {
1648
1923
  const here = (0, import_node_url3.fileURLToPath)(new URL(".", importMetaUrl));
1649
- const schemasDir = (0, import_node_path5.resolve)(here, "..", "assets", "schemas");
1924
+ const schemasDir = (0, import_node_path7.resolve)(here, "..", "assets", "schemas");
1650
1925
  const schemas = {};
1651
- if (!(0, import_node_fs6.existsSync)(schemasDir)) {
1926
+ if (!(0, import_node_fs8.existsSync)(schemasDir)) {
1652
1927
  return schemas;
1653
1928
  }
1654
- for (const file of (0, import_node_fs6.readdirSync)(schemasDir)) {
1655
- if ((0, import_node_path5.extname)(file) !== ".json") {
1929
+ for (const file of (0, import_node_fs8.readdirSync)(schemasDir)) {
1930
+ if ((0, import_node_path7.extname)(file) !== ".json") {
1656
1931
  continue;
1657
1932
  }
1658
- const parsed = JSON.parse((0, import_node_fs6.readFileSync)((0, import_node_path5.join)(schemasDir, file), "utf-8"));
1933
+ const parsed = JSON.parse((0, import_node_fs8.readFileSync)((0, import_node_path7.join)(schemasDir, file), "utf-8"));
1659
1934
  const base = file.replace(/\.json$/, "");
1660
1935
  const dash = base.indexOf("-");
1661
1936
  if (dash > 0) {
@@ -1671,15 +1946,15 @@ function loadSchemas() {
1671
1946
  }
1672
1947
  function resolveUiDir(explicit) {
1673
1948
  if (explicit) {
1674
- return (0, import_node_fs6.existsSync)(explicit) ? explicit : null;
1949
+ return (0, import_node_fs8.existsSync)(explicit) ? explicit : null;
1675
1950
  }
1676
1951
  const candidates = ["@revenexx/studio-integrations"];
1677
1952
  const req = (0, import_node_module.createRequire)(importMetaUrl);
1678
1953
  for (const pkg of candidates) {
1679
1954
  try {
1680
1955
  const entry = req.resolve(`${pkg}/package.json`);
1681
- const dist = (0, import_node_path5.resolve)(entry, "..", "dist");
1682
- if ((0, import_node_fs6.existsSync)((0, import_node_path5.join)(dist, "index.html"))) {
1956
+ const dist = (0, import_node_path7.resolve)(entry, "..", "dist");
1957
+ if ((0, import_node_fs8.existsSync)((0, import_node_path7.join)(dist, "index.html"))) {
1683
1958
  return dist;
1684
1959
  }
1685
1960
  } catch {
@@ -1701,16 +1976,16 @@ var MIME = {
1701
1976
  function serveStatic(uiDir, req, res) {
1702
1977
  const url = new URL(req.url ?? "/", "http://localhost");
1703
1978
  const relative2 = url.pathname === "/" ? "index.html" : url.pathname.replace(/^\/+/, "");
1704
- let filePath = (0, import_node_path5.resolve)(uiDir, relative2);
1705
- if (!filePath.startsWith(uiDir) || !(0, import_node_fs6.existsSync)(filePath)) {
1706
- filePath = (0, import_node_path5.join)(uiDir, "index.html");
1979
+ let filePath = (0, import_node_path7.resolve)(uiDir, relative2);
1980
+ if (!filePath.startsWith(uiDir) || !(0, import_node_fs8.existsSync)(filePath)) {
1981
+ filePath = (0, import_node_path7.join)(uiDir, "index.html");
1707
1982
  }
1708
- if (!(0, import_node_fs6.existsSync)(filePath)) {
1983
+ if (!(0, import_node_fs8.existsSync)(filePath)) {
1709
1984
  res.writeHead(404).end("UI build not found");
1710
1985
  return;
1711
1986
  }
1712
- res.writeHead(200, { "Content-Type": MIME[(0, import_node_path5.extname)(filePath)] ?? "application/octet-stream" });
1713
- res.end((0, import_node_fs6.readFileSync)(filePath));
1987
+ res.writeHead(200, { "Content-Type": MIME[(0, import_node_path7.extname)(filePath)] ?? "application/octet-stream" });
1988
+ res.end((0, import_node_fs8.readFileSync)(filePath));
1714
1989
  }
1715
1990
  async function startMock(options) {
1716
1991
  let loaded = await loadPackageFromEntry(options.entry);
@@ -1746,7 +2021,10 @@ async function startMock(options) {
1746
2021
  );
1747
2022
  }
1748
2023
  });
1749
- await new Promise((r) => server.listen(options.port, r));
2024
+ const port = await listenWithFallback(server, { port: options.port, strict: options.portExplicit });
2025
+ if (port !== options.port) {
2026
+ console.log(`Port ${options.port} was taken \u2014 the mock is on ${port} instead.`);
2027
+ }
1750
2028
  const stopWatch = watchAndReload(options.entry, async () => {
1751
2029
  try {
1752
2030
  loaded = await loadPackageFromEntry(options.entry);
@@ -1757,6 +2035,7 @@ async function startMock(options) {
1757
2035
  });
1758
2036
  return {
1759
2037
  uiDir,
2038
+ port,
1760
2039
  dispose() {
1761
2040
  if (options.persist) {
1762
2041
  saveState(options.stateFile, store.toSnapshot());
@@ -1768,7 +2047,7 @@ async function startMock(options) {
1768
2047
  }
1769
2048
  async function run(options) {
1770
2049
  const mock = await startMock(options);
1771
- const urlBase = `http://localhost:${options.port}`;
2050
+ const urlBase = `http://localhost:${mock.port}`;
1772
2051
  console.log(`
1773
2052
  Mock Integrations API ${urlBase}/api/v1`);
1774
2053
  console.log(mock.uiDir ? ` Preview UI ${urlBase}` : ` Preview UI API-only \u2014 set your Nuxt host's integrationsApi to ${urlBase}/api/v1`);
@@ -1784,10 +2063,10 @@ async function run(options) {
1784
2063
  process.on("SIGTERM", shutdown);
1785
2064
  }
1786
2065
  function watchAndReload(entry, onChange) {
1787
- const dir = (0, import_node_path5.resolve)(entry, "..");
2066
+ const dir = (0, import_node_path7.resolve)(entry, "..");
1788
2067
  let timer;
1789
2068
  try {
1790
- const watcher = (0, import_node_fs6.watch)(dir, { recursive: true }, (_event, file) => {
2069
+ const watcher = (0, import_node_fs8.watch)(dir, { recursive: true }, (_event, file) => {
1791
2070
  if (file && isReloadableSource(file.toString())) {
1792
2071
  clearTimeout(timer);
1793
2072
  timer = setTimeout(onChange, 200);
@@ -1808,63 +2087,92 @@ async function runNpmInstall(dir) {
1808
2087
  });
1809
2088
  }
1810
2089
  function noteLegacyPreviewDir() {
1811
- const legacy = (0, import_node_path5.resolve)(process.cwd(), ".revenexx-dev/preview");
1812
- if ((0, import_node_fs6.existsSync)(legacy)) {
2090
+ const legacy = (0, import_node_path7.resolve)(process.cwd(), ".revenexx-dev/preview");
2091
+ if ((0, import_node_fs8.existsSync)(legacy)) {
1813
2092
  console.log(`Note: ${legacy} is no longer used \u2014 the preview host now lives in a shared cache. You can delete it to reclaim the space.`);
1814
2093
  }
1815
2094
  }
2095
+ var UI_PORT = 3e3;
1816
2096
  async function preview(options) {
1817
- const apiUrl = `http://localhost:${options.port}/api/v1`;
2097
+ const cwd = process.cwd();
1818
2098
  const managed = options.previewDir === null;
1819
- const targetDir = options.previewDir ?? resolveHostDir({ version: DEVKIT_VERSION });
1820
- noteLegacyPreviewDir();
1821
- const { dir } = materializeHost({
1822
- targetDir,
1823
- integrationsApiUrl: apiUrl,
1824
- force: options.force,
1825
- managed,
1826
- log: (msg) => console.log(msg)
1827
- });
1828
- if (managed) {
1829
- console.log(` Host (devkit ${DEVKIT_VERSION}, shared across repos) ${dir}`);
1830
- }
1831
- if (options.force) {
1832
- clearHostInstallMarker(dir);
1833
- }
1834
- if (hostNeedsInstall(dir)) {
1835
- console.log("Installing preview-host dependencies (this pulls Nuxt + the studio packages and may take a while)\u2026");
1836
- await runNpmInstall(dir);
1837
- markHostInstalled(dir);
2099
+ const hostDir = (0, import_node_path7.resolve)(options.previewDir ?? resolveHostDir({ version: DEVKIT_VERSION }));
2100
+ const running = readLivePreviews(hostDir);
2101
+ const conflict = previewConflict(running, { cwd, hostDir, parallel: options.parallel, force: options.force });
2102
+ if (conflict) {
2103
+ throw new CliError(conflict);
1838
2104
  }
2105
+ noteLegacyPreviewDir();
1839
2106
  const mock = await startMock({ ...options, serveUi: false });
1840
- console.log(`
1841
- Mock Integrations API ${apiUrl}`);
1842
- console.log(" Preview UI http://localhost:3000/integrations (Nuxt starting\u2026)\n");
1843
- const { spawn } = await import("child_process");
1844
- const child = spawn("npm", ["run", "dev"], {
1845
- cwd: dir,
1846
- stdio: "inherit",
1847
- env: {
1848
- ...process.env,
1849
- NUXT_PUBLIC_INTEGRATIONS_API: apiUrl,
1850
- NUXT_PUBLIC_DEV_TOKEN: process.env.NUXT_PUBLIC_DEV_TOKEN ?? "dev",
1851
- NUXT_PUBLIC_DEV_TENANT: process.env.NUXT_PUBLIC_DEV_TENANT ?? "dev-tenant",
1852
- // Keep the shared host's dependency install shared but its BUILD per repo,
1853
- // so two node packages previewing at once do not compile over each other.
1854
- DEVKIT_NUXT_BUILD_DIR: hostBuildDir(dir, process.cwd())
2107
+ const apiUrl = `http://localhost:${mock.port}/api/v1`;
2108
+ try {
2109
+ const { dir } = materializeHost({
2110
+ targetDir: hostDir,
2111
+ integrationsApiUrl: apiUrl,
2112
+ dotenvName: managed ? hostDotenvName(cwd) : void 0,
2113
+ force: options.force,
2114
+ managed,
2115
+ log: (msg) => console.log(msg)
2116
+ });
2117
+ if (options.force) {
2118
+ clearHostInstallMarker(dir);
2119
+ }
2120
+ if (hostNeedsInstall(dir)) {
2121
+ await withInstallLock(
2122
+ dir,
2123
+ async () => {
2124
+ console.log("Installing preview-host dependencies (this pulls Nuxt + the studio packages and may take a while)\u2026");
2125
+ await runNpmInstall(dir);
2126
+ markHostInstalled(dir);
2127
+ },
2128
+ { needsInstall: () => hostNeedsInstall(dir), log: (msg) => console.log(msg) }
2129
+ );
1855
2130
  }
1856
- });
1857
- const shutdown = () => {
1858
- child.kill("SIGTERM");
1859
- mock.dispose();
1860
- process.exit(0);
1861
- };
1862
- process.on("SIGINT", shutdown);
1863
- process.on("SIGTERM", shutdown);
1864
- child.on("exit", (code) => {
2131
+ const uiPort = process.env.NUXT_PORT ? Number(process.env.NUXT_PORT) : await findFreePort(UI_PORT);
2132
+ console.log(`
2133
+ Previewing ${(0, import_node_path7.basename)(cwd)} (${cwd})`);
2134
+ console.log(` Mock Integrations API ${apiUrl}`);
2135
+ if (managed) {
2136
+ console.log(` Host (devkit ${DEVKIT_VERSION}, shared across repos) ${dir}`);
2137
+ }
2138
+ console.log(` Preview UI starting on port ${uiPort} \u2014 Nuxt prints the URL it got, below.`);
2139
+ for (const entry of running) {
2140
+ console.log(` Also running ${describePreview(entry)}`);
2141
+ }
2142
+ console.log("");
2143
+ const { spawn } = await import("child_process");
2144
+ const args = managed ? ["run", "dev", "--", "--dotenv", hostDotenvName(cwd)] : ["run", "dev"];
2145
+ const child = spawn("npm", args, {
2146
+ cwd: dir,
2147
+ stdio: "inherit",
2148
+ env: previewChildEnv({
2149
+ base: process.env,
2150
+ apiUrl,
2151
+ uiPort,
2152
+ buildDir: hostBuildDir(dir, cwd),
2153
+ viteCacheDir: hostViteCacheDir(dir, cwd)
2154
+ })
2155
+ });
2156
+ registerPreview(dir, { pid: process.pid, cwd, mockPort: mock.port, uiPort, startedAt: (/* @__PURE__ */ new Date()).toISOString() });
2157
+ const cleanUp = () => {
2158
+ unregisterPreview(dir);
2159
+ mock.dispose();
2160
+ };
2161
+ const shutdown = () => {
2162
+ child.kill("SIGTERM");
2163
+ cleanUp();
2164
+ process.exit(0);
2165
+ };
2166
+ process.on("SIGINT", shutdown);
2167
+ process.on("SIGTERM", shutdown);
2168
+ child.on("exit", (code) => {
2169
+ cleanUp();
2170
+ process.exit(code ?? 0);
2171
+ });
2172
+ } catch (err) {
1865
2173
  mock.dispose();
1866
- process.exit(code ?? 0);
1867
- });
2174
+ throw err;
2175
+ }
1868
2176
  }
1869
2177
  async function openBrowser(url) {
1870
2178
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
@@ -1883,8 +2191,8 @@ async function main() {
1883
2191
  console.log(`Loaded env from ${envFile2}`);
1884
2192
  }
1885
2193
  if (command === "reset") {
1886
- const { rmSync: rmSync2 } = await import("fs");
1887
- rmSync2(options.stateFile, { force: true });
2194
+ const { rmSync: rmSync3 } = await import("fs");
2195
+ rmSync3(options.stateFile, { force: true });
1888
2196
  console.log(`Removed ${options.stateFile}`);
1889
2197
  return;
1890
2198
  }
@@ -1913,7 +2221,7 @@ async function main() {
1913
2221
  await run(options);
1914
2222
  }
1915
2223
  main().catch((err) => {
1916
- console.error(err);
2224
+ console.error(err instanceof CliError ? err.message : err);
1917
2225
  process.exit(1);
1918
2226
  });
1919
2227
  //# sourceMappingURL=cli.cjs.map