@dokebi/cli 0.4.90 → 0.4.91

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/server.js CHANGED
@@ -44,8 +44,9 @@ import { CliError } from './errors.js';
44
44
  import { askLogWriter, CONTROL_HOST } from './log-writer-control.js';
45
45
  import { redactNpmOutput } from './npm-client.js';
46
46
  import { endLeftovers, holdTermination, killGroup, PROCESS_GROUPS } from './process-group.js';
47
+ import { listens, PROCESS_VARIABLE, processIssues, processSetOf, readProcessSet, tagLines, webProcess, } from './processes.js';
47
48
  import { ProjectInspector } from './project-inspector.js';
48
- import { logFiles } from './rotating-log.js';
49
+ import { LineBuffer, logFiles } from './rotating-log.js';
49
50
  import { ViteHostProcess, viteHostScript } from './vite-host-process.js';
50
51
  const exec = promisify(execFile);
51
52
  const ENTRY = 'src/main.ts';
@@ -410,6 +411,7 @@ async function statusOf(root, read, kill, locked) {
410
411
  proof,
411
412
  log,
412
413
  ...logs,
414
+ ...(record.processes ? { processes: record.processes } : {}),
413
415
  ...(record.logWriter !== undefined
414
416
  ? {
415
417
  logWriter: {
@@ -472,6 +474,15 @@ async function configuredWeb(root) {
472
474
  return undefined;
473
475
  }
474
476
  try {
477
+ // D-0251: with processes, the web settings of the first process of run that listens (none
478
+ // listens: as listen: false).
479
+ const set = processSetOf(source);
480
+ if (set) {
481
+ const name = webProcess(set);
482
+ if (name === undefined)
483
+ return { listen: false };
484
+ return (set.options.get(name)?.['dokebi-web'] ?? {});
485
+ }
475
486
  return (parseProjectConfig(source).options['dokebi-web'] ?? {});
476
487
  }
477
488
  catch (error) {
@@ -780,6 +791,19 @@ check = checkProject) {
780
791
  });
781
792
  const entry = await check(root);
782
793
  interrupted();
794
+ // D-0251: the processes of `run`, each started with DOKEBI_PROCESS; what the set leaves
795
+ // undone is said, and two processes on one port refuse the start.
796
+ const set = await readProcessSet(root);
797
+ if (set) {
798
+ const issues = processIssues(set);
799
+ const blocking = issues.filter((issue) => issue.severity === 'error');
800
+ if (blocking.length)
801
+ throw new CliError('PROCESS_SET_INVALID', blocking.map((issue) => issue.message).join('; '), {
802
+ details: { issues: blocking, fix: blocking[0]?.fix },
803
+ });
804
+ for (const issue of issues)
805
+ warnings.push(`${issue.code}: ${issue.message} (${issue.fix})`);
806
+ }
783
807
  // The project's .env under the CLI's environment (D-0073); a malformed file stops here.
784
808
  const token = randomBytes(24).toString('base64url');
785
809
  const env = appEnvironment(root, 'production', {
@@ -807,6 +831,7 @@ check = checkProject) {
807
831
  String(maxBytes),
808
832
  String(keep),
809
833
  entry,
834
+ ...(set?.run ?? []),
810
835
  ], {
811
836
  cwd: root,
812
837
  detached: true,
@@ -884,6 +909,7 @@ check = checkProject) {
884
909
  logFiles: keep,
885
910
  token,
886
911
  ...(state.control !== undefined ? { control: state.control } : {}),
912
+ ...(set ? { processes: [...set.run] } : {}),
887
913
  };
888
914
  await save(recorded);
889
915
  debug('App process spawned; waiting for the start line', { pid: state.pid });
@@ -920,6 +946,7 @@ check = checkProject) {
920
946
  ready,
921
947
  urls,
922
948
  listen,
949
+ ...(set ? { processes: set.run } : {}),
923
950
  ms: Math.round(performance.now() - began),
924
951
  warnings,
925
952
  };
@@ -1555,6 +1582,38 @@ function inertiaDevServer(root) {
1555
1582
  /** Files the Vite dev server owns: a change reaches the browser by HMR, not by a restart. */
1556
1583
  const VIEW_FILE = /(^|[\\/])views[\\/].*\.(js|mjs|ts)$|\.(vue|css|scss|sass|less)$/;
1557
1584
  let devReloadId = 0;
1585
+ /** How bad a reload answer is: the worst one of several processes is theirs together. */
1586
+ const ANSWER_RANK = {
1587
+ unchanged: 0,
1588
+ applied: 1,
1589
+ unsupported: 2,
1590
+ 'restart-required': 3,
1591
+ invalid: 4,
1592
+ };
1593
+ /**
1594
+ * D-0251: asks every process `dokebi dev` runs to read the settings again. One process: its
1595
+ * answer. Several: undefined (a restart) when one cannot answer, else the worst answer, with the
1596
+ * paths and restart-required paths of all.
1597
+ */
1598
+ async function askAll(apps, timeoutMs) {
1599
+ const answers = await Promise.all([...apps.values()].map((app) => askDevReload(app, timeoutMs)));
1600
+ if (answers.length === 1)
1601
+ return answers[0];
1602
+ if (answers.some((answer) => answer === undefined))
1603
+ return undefined;
1604
+ const known = answers;
1605
+ const worst = known.reduce((a, b) => (ANSWER_RANK[b.outcome] ?? 5) > (ANSWER_RANK[a.outcome] ?? 5) ? b : a);
1606
+ if ((ANSWER_RANK[worst.outcome] ?? 5) > 4)
1607
+ return undefined;
1608
+ const all = (pick) => [
1609
+ ...new Set(known.flatMap((answer) => pick(answer) ?? [])),
1610
+ ];
1611
+ return {
1612
+ ...worst,
1613
+ paths: all((answer) => answer.paths),
1614
+ restartRequired: all((answer) => answer.restartRequired),
1615
+ };
1616
+ }
1558
1617
  /**
1559
1618
  * D-0154: asks the app `dokebi dev` runs to read dokebi.yaml again (through the IPC channel of
1560
1619
  * its preload, dev-guard.ts). Resolves with its answer, or undefined when it cannot be asked,
@@ -1649,7 +1708,11 @@ export async function dev(root, print) {
1649
1708
  // The project's .env (D-0073), read again before every (re)start: a change restarts the app
1650
1709
  // with the new values. A malformed file fails here and, later, fails that restart only.
1651
1710
  let fileEnv = readEnvFile(root);
1652
- let app;
1711
+ /**
1712
+ * The running app processes (D-0251): one per process of `run` (keyed by its name), or one
1713
+ * keyed '' when the settings declare no processes.
1714
+ */
1715
+ let apps = new Map();
1653
1716
  let exiting = false;
1654
1717
  const hasVite = ['vite.config.ts', 'vite.config.mjs', 'vite.config.js'].some((name) => existsSync(join(root, name)));
1655
1718
  const hot = hasVite && inertiaDevServer(root);
@@ -1673,7 +1736,9 @@ export async function dev(root, print) {
1673
1736
  const colour = process.stdout.isTTY
1674
1737
  ? { DOKEBI_LOG_COLOR: '1', FORCE_COLOR: '1' }
1675
1738
  : {};
1676
- const child = (args, extra = {}, group = false) => {
1739
+ const child = (args, extra = {}, group = false,
1740
+ /** D-0251: the process whose lines are tagged with its name (several processes). */
1741
+ tag) => {
1677
1742
  const started = spawn(process.execPath, ['--import', guard, ...args], {
1678
1743
  cwd: root,
1679
1744
  stdio: ['inherit', 'pipe', 'pipe', 'ipc'],
@@ -1681,6 +1746,38 @@ export async function dev(root, print) {
1681
1746
  // DOKEBI_DEV: a cluster app runs one worker (@dokebi/cluster, DOKEBI_DEV_WORKERS for more).
1682
1747
  env: appEnvironment(root, 'development', { DOKEBI_DEV: '1', ...colour, ...(hot ? { DOKEBI_VITE_DEV: '1' } : {}), ...extra }, fileEnv),
1683
1748
  });
1749
+ if (tag !== undefined) {
1750
+ // Whole lines, each with the process name (a record's `process` field, else `[name] `).
1751
+ for (const [stream, out] of [
1752
+ [started.stdout, process.stdout],
1753
+ [started.stderr, process.stderr],
1754
+ ]) {
1755
+ const lines = new LineBuffer();
1756
+ let timer;
1757
+ const write = (data) => {
1758
+ if (!data.length)
1759
+ return;
1760
+ const tagged = tagLines(tag, data);
1761
+ // dokebi-check: allow console-output dev passes the app's own output on to the terminal, tagged with its process (D-0251)
1762
+ out.write(tagged);
1763
+ devLog.write(tagged);
1764
+ };
1765
+ stream?.on('data', (chunk) => {
1766
+ const whole = lines.push(chunk);
1767
+ if (whole)
1768
+ write(whole);
1769
+ clearTimeout(timer);
1770
+ if (lines.pending)
1771
+ timer = setTimeout(() => write(lines.take()), 200);
1772
+ });
1773
+ stream?.once('close', () => {
1774
+ clearTimeout(timer);
1775
+ if (lines.pending)
1776
+ write(lines.take());
1777
+ });
1778
+ }
1779
+ return started;
1780
+ }
1684
1781
  started.stdout?.on('data', (chunk) => {
1685
1782
  // dokebi-check: allow console-output dev passes the app's own output on to the terminal as it was (D-0201)
1686
1783
  process.stdout.write(chunk);
@@ -1707,23 +1804,56 @@ export async function dev(root, print) {
1707
1804
  // Reported by the caller (DEV_START_FAILED / DEV_RESTART_FAILED); the next change retries.
1708
1805
  throw error;
1709
1806
  }
1807
+ // D-0251: the processes of `run`, read again at every (re)start (a change of processes or
1808
+ // run applies on the restart it causes).
1809
+ const set = await readProcessSet(root);
1810
+ const said = set
1811
+ ? processIssues(set).map((issue) => `${issue.code}: ${issue.message} (${issue.fix})`)
1812
+ : [];
1813
+ const named = set ? `${set.run.join(' ')}|${said.join('|')}` : '';
1814
+ if (named !== lastSet) {
1815
+ lastSet = named;
1816
+ if (set)
1817
+ say(`processes: ${set.run.join(', ')}${set.run.length < set.declared.length ? ` (declared but not run here: ${set.declared.filter((name) => !set.run.includes(name)).join(', ')})` : ''}`);
1818
+ for (const line of said)
1819
+ say(line);
1820
+ }
1821
+ const blocking = set ? processIssues(set).filter((issue) => issue.severity === 'error') : [];
1822
+ if (blocking.length)
1823
+ throw new CliError('PROCESS_SET_INVALID', blocking.map((issue) => issue.message).join('; '), {
1824
+ details: { issues: blocking, fix: blocking[0]?.fix },
1825
+ });
1826
+ // Processes that open no web port get no Vite: template-inertia 0.4.14 then reads no manifest
1827
+ // either (D-0251). An older one would, so they share the host as before.
1828
+ const quiet = !hot || newer(installedVersion(root, '@dokebi/template-inertia') ?? [0, 0, 0], [0, 4, 14]);
1829
+ const needsVite = (name) => {
1830
+ const options = set?.options.get(name);
1831
+ return options === undefined || listens(options) || !quiet;
1832
+ };
1710
1833
  let extra = {};
1711
- if (viteHost) {
1834
+ if (viteHost && (set?.run ?? ['']).some(needsVite)) {
1712
1835
  const address = await viteHost.ensure();
1713
1836
  // Said by the host process; the next change starts it again.
1714
1837
  if (!address || exiting)
1715
1838
  return;
1716
1839
  extra = { DOKEBI_VITE_DEV_URL: address.url, DOKEBI_VITE_DEV_KEY: address.key };
1717
1840
  }
1718
- app = child([entry], extra, true);
1719
- const current = app;
1720
- current.once('exit', (code, signal) => {
1721
- if (app === current && !exiting)
1722
- say(`app exited (${signal ?? code}); waiting for a change to restart`);
1723
- if (current.pid !== undefined)
1724
- void leftovers(current.pid);
1725
- });
1841
+ const started = new Map();
1842
+ for (const name of set?.run ?? ['']) {
1843
+ // Only processes that open the web port get Vite (a worker renders no page).
1844
+ const vite = needsVite(name) ? extra : { DOKEBI_VITE_DEV: '0' };
1845
+ const current = child([entry], { ...vite, ...(name ? { [PROCESS_VARIABLE]: name } : {}) }, true, set && set.run.length > 1 ? name : undefined);
1846
+ started.set(name, current);
1847
+ current.once('exit', (code, signal) => {
1848
+ if (apps.get(name) === current && !exiting)
1849
+ say(`${name ? `process ${name}` : 'app'} exited (${signal ?? code}); waiting for a change to restart`);
1850
+ if (current.pid !== undefined)
1851
+ void leftovers(current.pid);
1852
+ });
1853
+ }
1854
+ apps = started;
1726
1855
  };
1856
+ let lastSet;
1727
1857
  /** Ends what an exited app left in its process group, and says so. */
1728
1858
  const ended = new Map();
1729
1859
  const leftovers = (pid) => {
@@ -1831,8 +1961,8 @@ export async function dev(root, print) {
1831
1961
  .then(async () => {
1832
1962
  if (exiting)
1833
1963
  return;
1834
- if (batch.config && batch.other === undefined && app) {
1835
- const answer = await askDevReload(app, await devReloadTimeout(root));
1964
+ if (batch.config && batch.other === undefined && apps.size) {
1965
+ const answer = await askAll(apps, await devReloadTimeout(root));
1836
1966
  debug('dev: reload answer', {
1837
1967
  outcome: answer?.outcome ?? 'no-answer',
1838
1968
  code: answer?.code,
@@ -1855,9 +1985,9 @@ export async function dev(root, print) {
1855
1985
  }
1856
1986
  const what = batch.other ?? settingsName;
1857
1987
  say(`${what} changed; restarting`);
1858
- const previous = app;
1859
- app = undefined;
1860
- await halt(previous, undefined, true);
1988
+ const previous = apps;
1989
+ apps = new Map();
1990
+ await Promise.all([...previous.values()].map((target) => halt(target, undefined, true)));
1861
1991
  if (!exiting)
1862
1992
  await run();
1863
1993
  })
@@ -1919,7 +2049,7 @@ export async function dev(root, print) {
1919
2049
  return await new Promise((resolve) => {
1920
2050
  const finish = async () => {
1921
2051
  if (exiting) {
1922
- for (const target of new Set([...(app ? [app] : []), ...halting])) {
2052
+ for (const target of new Set([...apps.values(), ...halting])) {
1923
2053
  target.kill('SIGKILL');
1924
2054
  if (target.pid !== undefined && PROCESS_GROUPS)
1925
2055
  killGroup(target.pid, 'SIGKILL');
@@ -1937,7 +2067,7 @@ export async function dev(root, print) {
1937
2067
  watcher.close();
1938
2068
  await restarting;
1939
2069
  await Promise.all([
1940
- halt(app, undefined, true),
2070
+ ...[...apps.values()].map((target) => halt(target, undefined, true)),
1941
2071
  ...helpers.map((helper) => halt(helper, 5000)),
1942
2072
  ]);
1943
2073
  // After the app: its requests and server renders go to the host until it has drained.
@@ -2002,7 +2132,9 @@ async function reloadSupport(root, record) {
2002
2132
  return undefined;
2003
2133
  }
2004
2134
  /** The first reload outcome the app logged after `offset` of app.log (a SIGHUP's, `trigger: signal`). */
2005
- async function reloadOutcome(log, offset) {
2135
+ async function reloadOutcome(log, offset,
2136
+ /** D-0251: only lines of this process (their `process` field). */
2137
+ name) {
2006
2138
  let text;
2007
2139
  try {
2008
2140
  const handle = await open(log, 'r');
@@ -2038,11 +2170,48 @@ async function reloadOutcome(log, offset) {
2038
2170
  }
2039
2171
  if (typeof record.code === 'string' &&
2040
2172
  RELOAD_OUTCOMES.has(record.code) &&
2041
- record.trigger === 'signal')
2173
+ record.trigger === 'signal' &&
2174
+ (name === undefined || record.process === name))
2042
2175
  return record;
2043
2176
  }
2044
2177
  return undefined;
2045
2178
  }
2179
+ /** Worse reload outcomes first; a code not listed is worse than every listed one. */
2180
+ const OUTCOME_RANK = {
2181
+ CONFIG_RELOAD_UNCHANGED: 0,
2182
+ CONFIG_RELOADED: 1,
2183
+ CONFIG_RELOAD_UNAVAILABLE: 2,
2184
+ CONFIG_RELOAD_PARTIAL: 3,
2185
+ CONFIG_RELOAD_TIMEOUT: 4,
2186
+ CONFIG_RELOAD_FAILED: 5,
2187
+ CONFIG_RELOAD_RESTART_REQUIRED: 6,
2188
+ CONFIG_RELOAD_INVALID: 7,
2189
+ };
2190
+ /**
2191
+ * D-0251: the reload outcome of several processes together: the worst one (its `process` named),
2192
+ * with the paths and restart-required paths of all and each process's code in `processes`.
2193
+ */
2194
+ function worstOutcome(outcomes, names) {
2195
+ if (!names)
2196
+ return outcomes[0];
2197
+ const rank = (outcome) => OUTCOME_RANK[String(outcome.code)] ?? 8;
2198
+ let worst = 0;
2199
+ for (const [index, outcome] of outcomes.entries())
2200
+ if (rank(outcome) > rank(outcomes[worst]))
2201
+ worst = index;
2202
+ const all = (key) => [
2203
+ ...new Set(outcomes.flatMap((outcome) => Array.isArray(outcome[key]) ? outcome[key].map(String) : [])),
2204
+ ];
2205
+ const paths = all('paths');
2206
+ const restartRequired = all('restartRequired');
2207
+ return {
2208
+ ...outcomes[worst],
2209
+ process: names[worst],
2210
+ processes: Object.fromEntries(names.map((name, index) => [name, outcomes[index]?.code])),
2211
+ ...(paths.length ? { paths } : {}),
2212
+ ...(restartRequired.length ? { restartRequired } : {}),
2213
+ };
2214
+ }
2046
2215
  /**
2047
2216
  * `dokebi reload` (D-0154): asks the background app to read dokebi.yaml again (SIGHUP to the pid
2048
2217
  * `start` recorded, proven like `stop`; through its log writer when this shell may not signal
@@ -2081,7 +2250,10 @@ export async function reload(root, timeoutMs, read = readProcess, kill = signalP
2081
2250
  const wait = timeoutMs ?? (await devReloadTimeout(root));
2082
2251
  const { log, reloadStatus } = paths(root);
2083
2252
  // The outcome file of the app (whatever its log level) is preferred; the log is the fallback.
2084
- const before = await reloadStatusOf(reloadStatus);
2253
+ // D-0251: several processes each write their own file (process-set.ts) and tag their lines.
2254
+ const names = record.processes && record.processes.length > 1 ? record.processes : undefined;
2255
+ const statusFiles = names ? names.map((name) => `${reloadStatus}.${name}`) : [reloadStatus];
2256
+ const befores = await Promise.all(statusFiles.map((file) => reloadStatusOf(file)));
2085
2257
  const offset = await stat(log).then((info) => info.size, (error) => {
2086
2258
  if (isMissing(error))
2087
2259
  return 0;
@@ -2116,20 +2288,28 @@ export async function reload(root, timeoutMs, read = readProcess, kill = signalP
2116
2288
  await throughWriter(error);
2117
2289
  }
2118
2290
  const until = performance.now() + wait;
2119
- let outcome;
2291
+ const outcomes = statusFiles.map(() => undefined);
2120
2292
  while (performance.now() < until) {
2121
- const status = await reloadStatusOf(reloadStatus);
2122
- if (status &&
2123
- (status.pid !== before?.pid || status.sequence !== before?.sequence) &&
2124
- typeof status.code === 'string') {
2125
- outcome = status;
2126
- break;
2293
+ for (const [index, file] of statusFiles.entries()) {
2294
+ if (outcomes[index])
2295
+ continue;
2296
+ const status = await reloadStatusOf(file);
2297
+ const before = befores[index];
2298
+ if (status &&
2299
+ (status.pid !== before?.pid || status.sequence !== before?.sequence) &&
2300
+ typeof status.code === 'string')
2301
+ outcomes[index] = status;
2302
+ else
2303
+ outcomes[index] = await reloadOutcome(log, offset, names?.[index]);
2127
2304
  }
2128
- outcome = await reloadOutcome(log, offset);
2129
- if (outcome)
2305
+ if (outcomes.every(Boolean))
2130
2306
  break;
2131
2307
  await delay(100);
2132
2308
  }
2309
+ const missing = names?.filter((_, index) => !outcomes[index]) ?? [];
2310
+ const outcome = missing.length || !outcomes.every(Boolean)
2311
+ ? undefined
2312
+ : worstOutcome(outcomes, names);
2133
2313
  const ms = Math.round(performance.now() - began);
2134
2314
  const list = (value) => Array.isArray(value) ? value.slice(0, 64).map((item) => String(item)) : undefined;
2135
2315
  if (!outcome)
@@ -2141,7 +2321,7 @@ export async function reload(root, timeoutMs, read = readProcess, kill = signalP
2141
2321
  proof,
2142
2322
  via,
2143
2323
  warnings: [
2144
- `no reload outcome in ${log} within ${wait} ms: the app may log above info (options.logging.level), or be busy; npx dokebi logs shows what it said`,
2324
+ `no reload outcome${missing.length ? ` of process ${missing.join(', ')}` : ''} in ${log} within ${wait} ms: the app may log above info (options.logging.level), or be busy; npx dokebi logs shows what it said`,
2145
2325
  ],
2146
2326
  };
2147
2327
  const code = String(outcome.code);
@@ -2154,6 +2334,7 @@ export async function reload(root, timeoutMs, read = readProcess, kill = signalP
2154
2334
  code,
2155
2335
  ...(typeof outcome.revision === 'number' ? { revision: outcome.revision } : {}),
2156
2336
  ...(paths_ ? { paths: paths_ } : {}),
2337
+ ...(names ? { processes: outcome.processes } : {}),
2157
2338
  ms,
2158
2339
  proof,
2159
2340
  via,
@@ -2161,6 +2342,8 @@ export async function reload(root, timeoutMs, read = readProcess, kill = signalP
2161
2342
  const details = {
2162
2343
  pid: record.pid,
2163
2344
  code,
2345
+ ...(typeof outcome.process === 'string' ? { process: outcome.process } : {}),
2346
+ ...(names ? { processes: outcome.processes } : {}),
2164
2347
  ...(paths_ ? { paths: paths_ } : {}),
2165
2348
  ...(list(outcome.restartRequired) ? { restartRequired: list(outcome.restartRequired) } : {}),
2166
2349
  ...(list(outcome.issues) ? { issues: list(outcome.issues) } : {}),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/cli",
3
- "version": "0.4.90",
3
+ "version": "0.4.91",
4
4
  "description": "Project scaffolding, plugin catalog, recipes, install and verification CLI for Dokebi.",
5
5
  "keywords": [
6
6
  "dokebi",
@@ -35,7 +35,7 @@
35
35
  "dependencies": {
36
36
  "semver": "7.8.5",
37
37
  "@dokebi/core": "^0.4.3",
38
- "@dokebi/config": "^0.4.4",
38
+ "@dokebi/config": "^0.4.7",
39
39
  "yaml": "2.9.1"
40
40
  },
41
41
  "devDependencies": {