create-ts-monorepo-starter 0.2.0 → 0.3.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.js +555 -361
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -4,7 +4,7 @@ import { join, isAbsolute, dirname, basename, resolve, relative, sep } from 'nod
|
|
|
4
4
|
import { parseArgs, styleText, stripVTControlCharacters } from 'node:util';
|
|
5
5
|
import { spawn } from 'node:child_process';
|
|
6
6
|
import { constants, tmpdir } from 'node:os';
|
|
7
|
-
import { readFileSync, existsSync, lstatSync, readdirSync, rmSync } from 'node:fs';
|
|
7
|
+
import { readFileSync, existsSync, lstatSync, readdirSync, rmSync, rmdirSync } from 'node:fs';
|
|
8
8
|
import { fileURLToPath } from 'node:url';
|
|
9
9
|
import process$1, { stdout, stdin } from 'node:process';
|
|
10
10
|
import * as f$1 from 'node:readline';
|
|
@@ -98,6 +98,69 @@ function parse(argv) {
|
|
|
98
98
|
});
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
+
const ERROR_CODES = new Set([
|
|
102
|
+
'usage',
|
|
103
|
+
'target-not-empty',
|
|
104
|
+
'cancelled',
|
|
105
|
+
'pnpm-too-old',
|
|
106
|
+
'pnpm-switch-failed',
|
|
107
|
+
'install-failed',
|
|
108
|
+
'lockfile-changed',
|
|
109
|
+
'backup-failed',
|
|
110
|
+
'move-failed',
|
|
111
|
+
'interrupted',
|
|
112
|
+
'unexpected',
|
|
113
|
+
]);
|
|
114
|
+
const USAGE = 2;
|
|
115
|
+
const FAILURE = 1;
|
|
116
|
+
/** The machine needs fixing first (pnpm can't switch versions, or is too old); nothing was created. */
|
|
117
|
+
const TOOLCHAIN = 3;
|
|
118
|
+
const INSTALL_FAILED = 4;
|
|
119
|
+
const INTERRUPTED = 130;
|
|
120
|
+
/** The exit code for an outcome; a code this function doesn't know exits 1, never 0. */
|
|
121
|
+
function exitCode(outcome) {
|
|
122
|
+
if (outcome.ok)
|
|
123
|
+
return 0;
|
|
124
|
+
switch (outcome.error.code) {
|
|
125
|
+
case 'usage':
|
|
126
|
+
return USAGE;
|
|
127
|
+
case 'pnpm-too-old':
|
|
128
|
+
case 'pnpm-switch-failed':
|
|
129
|
+
return TOOLCHAIN;
|
|
130
|
+
case 'install-failed':
|
|
131
|
+
return INSTALL_FAILED;
|
|
132
|
+
case 'cancelled':
|
|
133
|
+
case 'interrupted':
|
|
134
|
+
return INTERRUPTED;
|
|
135
|
+
default:
|
|
136
|
+
return FAILURE;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** The error's own code if it is one of the CLI's; a Node code such as `ENOSPC` is `unexpected`. */
|
|
140
|
+
function codeOf(error) {
|
|
141
|
+
const code = error?.code;
|
|
142
|
+
return typeof code === 'string' && ERROR_CODES.has(code) ? code : 'unexpected';
|
|
143
|
+
}
|
|
144
|
+
/** A failure the CLI throws on purpose: a code, and the output lines that explain it. */
|
|
145
|
+
class CliError extends Error {
|
|
146
|
+
code;
|
|
147
|
+
lines;
|
|
148
|
+
constructor(code, message, lines = []) {
|
|
149
|
+
super(message);
|
|
150
|
+
this.code = code;
|
|
151
|
+
this.lines = lines;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Classifies an error from a step without changing it: a new error with the same message, the
|
|
156
|
+
* CLI's code, and the original as `cause`. The original keeps its own `code` (retry logic reads it).
|
|
157
|
+
*/
|
|
158
|
+
function coded(code, error) {
|
|
159
|
+
return Object.assign(new Error(error instanceof Error ? error.message : String(error), { cause: error }), {
|
|
160
|
+
code,
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
101
164
|
// `../dist/` resolves to the same folder from src/ (tests) and from the bundled dist/cli.js.
|
|
102
165
|
const dist = new URL('../dist/', import.meta.url);
|
|
103
166
|
/** Dotfiles are stored renamed in the bundle because npm and pnpm drop them from packages. */
|
|
@@ -289,15 +352,22 @@ async function detectPnpm(exec = defaultExec, cwd = tmpdir()) {
|
|
|
289
352
|
return { kind: major < 10 || (major === 10 && minor < 26) ? 'old' : 'ok', version };
|
|
290
353
|
}
|
|
291
354
|
/** A toolchain problem the user has to fix before anything is created; `lines` say how. */
|
|
292
|
-
class ToolchainError extends
|
|
293
|
-
lines
|
|
294
|
-
|
|
295
|
-
super(message);
|
|
296
|
-
this.lines = lines;
|
|
355
|
+
class ToolchainError extends CliError {
|
|
356
|
+
constructor(code, message, lines) {
|
|
357
|
+
super(code, message, lines);
|
|
297
358
|
this.name = 'ToolchainError';
|
|
298
359
|
}
|
|
299
360
|
}
|
|
300
361
|
const PNPM_HELP = 'https://github.com/prosdevlab/create-ts-monorepo-starter#pnpm';
|
|
362
|
+
/** The stop for a pnpm older than 10.26, which can't switch itself to the template's pnpm. */
|
|
363
|
+
function tooOld(found, spec) {
|
|
364
|
+
const version = spec.slice('pnpm@'.length);
|
|
365
|
+
return new ToolchainError('pnpm-too-old', `pnpm ${found} is too old for this project`, [
|
|
366
|
+
`This project needs pnpm 10.26 or newer, which switches itself to pnpm ${version}.`,
|
|
367
|
+
'Upgrade pnpm: npm install -g pnpm (or https://pnpm.io/installation)',
|
|
368
|
+
'Then run this command again. Nothing was created.',
|
|
369
|
+
]);
|
|
370
|
+
}
|
|
301
371
|
const fileExists = (path) => access(path).then(() => true, () => false);
|
|
302
372
|
/**
|
|
303
373
|
* Runs `pnpm --version` in an empty folder pinned to `spec` (`pnpm@12.15.0`), where pnpm switches
|
|
@@ -335,7 +405,7 @@ function switchFailure(spec, found, output, installer) {
|
|
|
335
405
|
.map((line) => line.trim())
|
|
336
406
|
.filter(Boolean)
|
|
337
407
|
.slice(0, 2);
|
|
338
|
-
return new ToolchainError(`pnpm ${found} couldn't switch to pnpm ${version}, which this project needs`, [
|
|
408
|
+
return new ToolchainError('pnpm-switch-failed', `pnpm ${found} couldn't switch to pnpm ${version}, which this project needs`, [
|
|
339
409
|
...said.map((line) => `pnpm: ${line}`),
|
|
340
410
|
installer
|
|
341
411
|
? `Fix: node ${installer}`
|
|
@@ -351,8 +421,6 @@ function installCommand(status, dir, lockfileOnly) {
|
|
|
351
421
|
const extra = ['--no-frozen-lockfile', ...(lockfileOnly ? ['--lockfile-only'] : [])];
|
|
352
422
|
if (status.kind === 'ok')
|
|
353
423
|
return { cmd: 'pnpm', args: ['install', ...extra], cwd: dir };
|
|
354
|
-
if (status.kind === 'old')
|
|
355
|
-
return null;
|
|
356
424
|
return {
|
|
357
425
|
cmd: 'npm',
|
|
358
426
|
args: [
|
|
@@ -409,6 +477,7 @@ async function initAndCommit(dir, message, exec = defaultExec) {
|
|
|
409
477
|
const MAX_NAME_LENGTH = 214;
|
|
410
478
|
class NameError extends Error {
|
|
411
479
|
name = 'NameError';
|
|
480
|
+
code = 'usage';
|
|
412
481
|
}
|
|
413
482
|
// Folder -> npm package name: last path segment, lowercased, unsafe runs collapsed to "-".
|
|
414
483
|
function packageNameFromFolder(folder, cwd = process.cwd()) {
|
|
@@ -442,220 +511,6 @@ function normalizeScope(input) {
|
|
|
442
511
|
return { ok: true, scope };
|
|
443
512
|
}
|
|
444
513
|
|
|
445
|
-
const NAMES = [...EXAMPLES, 'template-only'];
|
|
446
|
-
// Same patterns as the template's own marker check (scripts/check-examples.mjs).
|
|
447
|
-
const MARKER = {
|
|
448
|
-
html: /^<!--\s*(\/?)example:(\S+?)\s*-->$/,
|
|
449
|
-
hash: /^#\s*(\/?)example:(\S+)$/,
|
|
450
|
-
slash: /^\/\/\s*(\/?)example:(\S+)$/,
|
|
451
|
-
};
|
|
452
|
-
const SLASH_EXTENSIONS = ['.ts', '.mts', '.cts', '.tsx', '.js', '.mjs', '.cjs', '.jsonc'];
|
|
453
|
-
class MarkerError extends Error {
|
|
454
|
-
path;
|
|
455
|
-
line;
|
|
456
|
-
constructor(path, line, problem) {
|
|
457
|
-
super(`${path}:${line} ${problem}`);
|
|
458
|
-
this.path = path;
|
|
459
|
-
this.line = line;
|
|
460
|
-
this.name = 'MarkerError';
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
/** Marker comment style of a repo-relative path, or null when the file is left untouched. */
|
|
464
|
-
function commentStyle(path) {
|
|
465
|
-
const file = path.replaceAll('\\', '/');
|
|
466
|
-
const name = file.slice(file.lastIndexOf('/') + 1);
|
|
467
|
-
const dot = name.lastIndexOf('.');
|
|
468
|
-
const ext = dot > 0 ? name.slice(dot) : '';
|
|
469
|
-
if (ext === '.md')
|
|
470
|
-
return 'html';
|
|
471
|
-
if (ext === '.yml' || ext === '.yaml')
|
|
472
|
-
return 'hash';
|
|
473
|
-
if (name === '.gitignore' || name === '_gitignore' || file.startsWith('.husky/'))
|
|
474
|
-
return 'hash';
|
|
475
|
-
if (SLASH_EXTENSIONS.includes(ext))
|
|
476
|
-
return 'slash';
|
|
477
|
-
if (/^tsconfig.*\.json$/.test(name) || name === 'turbo.json')
|
|
478
|
-
return 'slash';
|
|
479
|
-
return null;
|
|
480
|
-
}
|
|
481
|
-
/** Drops blocks named in `remove` (plus template-only) and the marker lines of the rest. */
|
|
482
|
-
function applyMarkers(text, path, remove) {
|
|
483
|
-
const style = commentStyle(path);
|
|
484
|
-
if (!style)
|
|
485
|
-
return text;
|
|
486
|
-
const eol = text.includes('\r\n') ? '\r\n' : '\n';
|
|
487
|
-
const out = [];
|
|
488
|
-
let open = null;
|
|
489
|
-
for (const [index, raw] of text.split(/\r?\n/).entries()) {
|
|
490
|
-
const line = index + 1;
|
|
491
|
-
const match = raw.trim().match(MARKER[style]);
|
|
492
|
-
if (!match) {
|
|
493
|
-
if (!open?.drop)
|
|
494
|
-
out.push(raw);
|
|
495
|
-
continue;
|
|
496
|
-
}
|
|
497
|
-
const [, closing, name = ''] = match;
|
|
498
|
-
if (!NAMES.includes(name))
|
|
499
|
-
throw new MarkerError(path, line, `unknown example "${name}"`);
|
|
500
|
-
if (closing) {
|
|
501
|
-
if (open?.name !== name) {
|
|
502
|
-
throw new MarkerError(path, line, `example:${name} closes without a matching opening`);
|
|
503
|
-
}
|
|
504
|
-
open = null;
|
|
505
|
-
}
|
|
506
|
-
else {
|
|
507
|
-
if (open)
|
|
508
|
-
throw new MarkerError(path, line, `example:${name} opens inside example:${open.name}`);
|
|
509
|
-
open = { name, line, drop: name === 'template-only' || remove.has(name) };
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
if (open)
|
|
513
|
-
throw new MarkerError(path, open.line, `example:${open.name} is never closed`);
|
|
514
|
-
return out.join(eol);
|
|
515
|
-
}
|
|
516
|
-
|
|
517
|
-
const EXAMPLE_DIRS = {
|
|
518
|
-
lib: ['packages/shared', 'packages/lib'],
|
|
519
|
-
cli: ['packages/cli'],
|
|
520
|
-
web: ['packages/web'],
|
|
521
|
-
};
|
|
522
|
-
// Files that only make sense inside the template repo itself.
|
|
523
|
-
const TEMPLATE_ONLY_FILES = ['scripts/check-examples.mjs', 'scripts/check-examples.test.ts'];
|
|
524
|
-
// pnpm rewrites the lockfile after generation, so it is never edited here.
|
|
525
|
-
const LOCKFILE = 'pnpm-lock.yaml';
|
|
526
|
-
/** Repo-relative paths (with `/`) of every file under `dir`. */
|
|
527
|
-
async function listFiles(dir, prefix = '') {
|
|
528
|
-
const entries = await readdir(join(dir, prefix), { withFileTypes: true });
|
|
529
|
-
const nested = await Promise.all(entries.map((entry) => {
|
|
530
|
-
const path = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
531
|
-
return entry.isDirectory() ? listFiles(dir, path) : [path];
|
|
532
|
-
}));
|
|
533
|
-
return nested.flat();
|
|
534
|
-
}
|
|
535
|
-
async function isText(path) {
|
|
536
|
-
const handle = await open(path, 'r');
|
|
537
|
-
try {
|
|
538
|
-
const buffer = Buffer.alloc(8192);
|
|
539
|
-
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
540
|
-
return !buffer.subarray(0, bytesRead).includes(0);
|
|
541
|
-
}
|
|
542
|
-
finally {
|
|
543
|
-
await handle.close();
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
function identityEdits(input) {
|
|
547
|
-
const { folderName, holder, year } = input;
|
|
548
|
-
return [
|
|
549
|
-
{ file: 'package.json', from: '"name": "ts-monorepo-starter"', to: `"name": "${folderName}"` },
|
|
550
|
-
{ file: 'README.md', from: '# TypeScript Monorepo Starter', to: `# ${folderName}` },
|
|
551
|
-
{ file: 'README.md', from: /^ts-monorepo-starter\/$/m, to: `${folderName}/` },
|
|
552
|
-
{ file: 'README.md', from: 'cd ts-monorepo-starter', to: `cd ${folderName}` },
|
|
553
|
-
{
|
|
554
|
-
file: 'README.md',
|
|
555
|
-
from: 'yourusername/ts-monorepo-starter.git',
|
|
556
|
-
to: `yourusername/${folderName}.git`,
|
|
557
|
-
},
|
|
558
|
-
{
|
|
559
|
-
file: 'LICENSE',
|
|
560
|
-
from: 'Copyright (c) 2025 prosdevlab',
|
|
561
|
-
to: `Copyright (c) ${year} ${holder}`,
|
|
562
|
-
},
|
|
563
|
-
];
|
|
564
|
-
}
|
|
565
|
-
/** Writes the chosen examples of the template at `from` into `to`; touches nothing else. */
|
|
566
|
-
async function generate(input) {
|
|
567
|
-
const { from, to, scope, keep } = input;
|
|
568
|
-
await cp(from, to, { recursive: true });
|
|
569
|
-
const all = await listFiles(to);
|
|
570
|
-
for (const file of all) {
|
|
571
|
-
const name = file.slice(file.lastIndexOf('/') + 1);
|
|
572
|
-
const renamed = DOTFILE_RENAMES[name];
|
|
573
|
-
if (renamed)
|
|
574
|
-
await rename(join(to, file), join(to, file.slice(0, -name.length) + renamed));
|
|
575
|
-
}
|
|
576
|
-
const removed = EXAMPLES.filter((example) => !keep.includes(example));
|
|
577
|
-
const doomed = [...removed.flatMap((example) => EXAMPLE_DIRS[example]), ...TEMPLATE_ONLY_FILES];
|
|
578
|
-
for (const path of doomed)
|
|
579
|
-
await rm(join(to, path), { recursive: true, force: true });
|
|
580
|
-
// The template-only files may have been all of scripts/.
|
|
581
|
-
const scripts = join(to, 'scripts');
|
|
582
|
-
const left = await readdir(scripts).catch(() => null);
|
|
583
|
-
if (left?.length === 0)
|
|
584
|
-
await rmdir(scripts);
|
|
585
|
-
const remove = new Set(removed);
|
|
586
|
-
const identity = identityEdits(input);
|
|
587
|
-
const present = await listFiles(to);
|
|
588
|
-
for (const edit of identity) {
|
|
589
|
-
if (!present.includes(edit.file)) {
|
|
590
|
-
throw new Error(`Template changed: "${typeof edit.from === 'string' ? edit.from : 'ts-monorepo-starter/'}" not found in ${edit.file}`);
|
|
591
|
-
}
|
|
592
|
-
}
|
|
593
|
-
for (const file of present) {
|
|
594
|
-
if (file === LOCKFILE || !(await isText(join(to, file))))
|
|
595
|
-
continue;
|
|
596
|
-
const original = await readFile(join(to, file), 'utf8');
|
|
597
|
-
let text = commentStyle(file) ? applyMarkers(original, file, remove) : original;
|
|
598
|
-
text = text.replaceAll('@monorepo/', `${scope}/`);
|
|
599
|
-
for (const edit of identity.filter((entry) => entry.file === file)) {
|
|
600
|
-
const found = typeof edit.from === 'string' ? text.includes(edit.from) : edit.from.test(text);
|
|
601
|
-
if (!found) {
|
|
602
|
-
const shown = typeof edit.from === 'string' ? edit.from : 'ts-monorepo-starter/';
|
|
603
|
-
throw new Error(`Template changed: "${shown}" not found in ${file}`);
|
|
604
|
-
}
|
|
605
|
-
text = text.replace(edit.from, () => edit.to);
|
|
606
|
-
}
|
|
607
|
-
if (text !== original)
|
|
608
|
-
await writeFile(join(to, file), text);
|
|
609
|
-
}
|
|
610
|
-
}
|
|
611
|
-
|
|
612
|
-
/** Thrown when an install added lockfile entries the bundled lockfile lacks. */
|
|
613
|
-
class LockfileError extends Error {
|
|
614
|
-
name = 'LockfileError';
|
|
615
|
-
}
|
|
616
|
-
const SECTIONS = ['packages', 'snapshots'];
|
|
617
|
-
function unquote(key) {
|
|
618
|
-
return key.startsWith("'") && key.endsWith("'") ? key.slice(1, -1).replaceAll("''", "'") : key;
|
|
619
|
-
}
|
|
620
|
-
/** Entries as `packages: name@version` / `snapshots: name@version`, across every YAML document. */
|
|
621
|
-
function sectionEntries(text) {
|
|
622
|
-
const found = new Set();
|
|
623
|
-
for (const doc of text.split(/^---\r?$/m)) {
|
|
624
|
-
let section = null;
|
|
625
|
-
for (const line of doc.split(/\r?\n/)) {
|
|
626
|
-
if (line.startsWith('#'))
|
|
627
|
-
continue;
|
|
628
|
-
const top = /^(\w+):\s*$/.exec(line);
|
|
629
|
-
if (top) {
|
|
630
|
-
section = SECTIONS.includes(top[1])
|
|
631
|
-
? top[1]
|
|
632
|
-
: null;
|
|
633
|
-
}
|
|
634
|
-
else if (/^\S/.test(line)) {
|
|
635
|
-
section = null;
|
|
636
|
-
}
|
|
637
|
-
else if (section) {
|
|
638
|
-
// A key ends at the first `:` followed by whitespace or end of line, so `node@runtime:1.0.0:` works.
|
|
639
|
-
const key = /^ {2}('(?:[^']|'')*'|[^\s'#].*?):(?=\s|$)/.exec(line);
|
|
640
|
-
if (key)
|
|
641
|
-
found.add(`${section}: ${unquote(key[1])}`);
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
}
|
|
645
|
-
return found;
|
|
646
|
-
}
|
|
647
|
-
/** Throws unless every entry of `generated` already exists in `bundled`. */
|
|
648
|
-
function assertLockfileSubset(bundled, generated) {
|
|
649
|
-
const have = sectionEntries(bundled);
|
|
650
|
-
const added = [...sectionEntries(generated)].filter((e) => !have.has(e));
|
|
651
|
-
if (added.length === 0)
|
|
652
|
-
return;
|
|
653
|
-
const lines = added.slice(0, 10).map((e) => `+ ${e}`);
|
|
654
|
-
if (added.length > 10)
|
|
655
|
-
lines.push(`…and ${added.length - 10} more`);
|
|
656
|
-
throw new LockfileError(`Lockfile changed during install:\n${lines.join('\n')}`);
|
|
657
|
-
}
|
|
658
|
-
|
|
659
514
|
/* MAIN */
|
|
660
515
|
const getCodePointsLength = (() => {
|
|
661
516
|
const SURROGATE_PAIR_RE = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
|
|
@@ -3630,19 +3485,14 @@ function closing(result, plan) {
|
|
|
3630
3485
|
let title = 'Ready.';
|
|
3631
3486
|
let commands = [];
|
|
3632
3487
|
let notes = [];
|
|
3633
|
-
if (result.pnpm.kind === '
|
|
3634
|
-
title = 'Upgrade pnpm, then install:';
|
|
3635
|
-
commands = ['npm install -g pnpm'];
|
|
3636
|
-
notes = [`Any pnpm from 10.26 on switches itself to ${pin} for this project.`];
|
|
3637
|
-
}
|
|
3638
|
-
else if (result.pnpm.kind === 'none') {
|
|
3488
|
+
if (result.pnpm.kind === 'none') {
|
|
3639
3489
|
title = 'One step left before your first commit:';
|
|
3640
3490
|
commands = ['npm install -g pnpm'];
|
|
3641
3491
|
notes = [
|
|
3642
3492
|
`The git hooks run pnpm. Any pnpm from 10.26 on switches itself to ${pin.split('.')[0]}.`,
|
|
3643
3493
|
];
|
|
3644
3494
|
}
|
|
3645
|
-
const extra = !result.installed
|
|
3495
|
+
const extra = !result.installed
|
|
3646
3496
|
? ["Dependencies aren't installed: the first pnpm install installs them and the git hooks."]
|
|
3647
3497
|
: [];
|
|
3648
3498
|
const dir = cdPath(plan.target, result.backup !== undefined);
|
|
@@ -3768,6 +3618,7 @@ function clackUi() {
|
|
|
3768
3618
|
/** Thrown when someone cancels a prompt (Ctrl-C or Escape). */
|
|
3769
3619
|
class CancelledError extends Error {
|
|
3770
3620
|
name = 'CancelledError';
|
|
3621
|
+
code = 'cancelled';
|
|
3771
3622
|
}
|
|
3772
3623
|
function answer(value) {
|
|
3773
3624
|
if (isCancel(value))
|
|
@@ -3821,18 +3672,275 @@ function createAsk(prompts = p$1) {
|
|
|
3821
3672
|
};
|
|
3822
3673
|
}
|
|
3823
3674
|
|
|
3824
|
-
|
|
3825
|
-
|
|
3826
|
-
const
|
|
3827
|
-
|
|
3828
|
-
|
|
3829
|
-
|
|
3830
|
-
|
|
3675
|
+
/** The failure for an error: the text `report()` printed before, and the code. */
|
|
3676
|
+
function failureFrom(error) {
|
|
3677
|
+
const code = codeOf(error);
|
|
3678
|
+
if (error instanceof CancelledError)
|
|
3679
|
+
return { code, title: CANCELLED, lines: [], fixes: [] };
|
|
3680
|
+
if (error instanceof CliError) {
|
|
3681
|
+
return { code, title: error.message, lines: error.lines, fixes: [] };
|
|
3682
|
+
}
|
|
3683
|
+
const [title = 'Something went wrong', ...lines] = String(error instanceof Error ? error.message : error).split('\n');
|
|
3684
|
+
return { code, title, lines, fixes: [] };
|
|
3831
3685
|
}
|
|
3832
|
-
/**
|
|
3833
|
-
function
|
|
3834
|
-
|
|
3835
|
-
|
|
3686
|
+
/** A usage error: one line on stderr, before anything else is shown. */
|
|
3687
|
+
function usageFailure(message) {
|
|
3688
|
+
const [title = '', ...lines] = message.split('\n');
|
|
3689
|
+
return { ok: false, error: { code: 'usage', title, lines, fixes: [] } };
|
|
3690
|
+
}
|
|
3691
|
+
/** Prints an outcome as text. */
|
|
3692
|
+
function renderText(outcome, ui) {
|
|
3693
|
+
if (!outcome.ok) {
|
|
3694
|
+
const { code, title, lines } = outcome.error;
|
|
3695
|
+
if (code === 'usage')
|
|
3696
|
+
process.stderr.write(`${[title, ...lines].join('\n')}\n`);
|
|
3697
|
+
else
|
|
3698
|
+
ui.fail(title, lines);
|
|
3699
|
+
return;
|
|
3700
|
+
}
|
|
3701
|
+
if (outcome.kind === 'created') {
|
|
3702
|
+
ui.outro(outcome.result, outcome.plan);
|
|
3703
|
+
return;
|
|
3704
|
+
}
|
|
3705
|
+
const version = pnpmSpec().slice('pnpm@'.length);
|
|
3706
|
+
if (outcome.pnpm.kind === 'none') {
|
|
3707
|
+
ui.warn("pnpm isn't installed", [
|
|
3708
|
+
`Creating works: the install uses a temporary pnpm ${version} (npm exec).`,
|
|
3709
|
+
`Working in the project needs pnpm 10.26 or newer: https://pnpm.io/installation`,
|
|
3710
|
+
]);
|
|
3711
|
+
}
|
|
3712
|
+
else if (outcome.pnpm.kind === 'ok') {
|
|
3713
|
+
ui.step(`Ready: pnpm ${outcome.pnpm.version} switches to pnpm ${version} for this project`);
|
|
3714
|
+
}
|
|
3715
|
+
}
|
|
3716
|
+
|
|
3717
|
+
const NAMES = [...EXAMPLES, 'template-only'];
|
|
3718
|
+
// Same patterns as the template's own marker check (scripts/check-examples.mjs).
|
|
3719
|
+
const MARKER = {
|
|
3720
|
+
html: /^<!--\s*(\/?)example:(\S+?)\s*-->$/,
|
|
3721
|
+
hash: /^#\s*(\/?)example:(\S+)$/,
|
|
3722
|
+
slash: /^\/\/\s*(\/?)example:(\S+)$/,
|
|
3723
|
+
};
|
|
3724
|
+
const SLASH_EXTENSIONS = ['.ts', '.mts', '.cts', '.tsx', '.js', '.mjs', '.cjs', '.jsonc'];
|
|
3725
|
+
class MarkerError extends Error {
|
|
3726
|
+
path;
|
|
3727
|
+
line;
|
|
3728
|
+
constructor(path, line, problem) {
|
|
3729
|
+
super(`${path}:${line} ${problem}`);
|
|
3730
|
+
this.path = path;
|
|
3731
|
+
this.line = line;
|
|
3732
|
+
this.name = 'MarkerError';
|
|
3733
|
+
}
|
|
3734
|
+
}
|
|
3735
|
+
/** Marker comment style of a repo-relative path, or null when the file is left untouched. */
|
|
3736
|
+
function commentStyle(path) {
|
|
3737
|
+
const file = path.replaceAll('\\', '/');
|
|
3738
|
+
const name = file.slice(file.lastIndexOf('/') + 1);
|
|
3739
|
+
const dot = name.lastIndexOf('.');
|
|
3740
|
+
const ext = dot > 0 ? name.slice(dot) : '';
|
|
3741
|
+
if (ext === '.md')
|
|
3742
|
+
return 'html';
|
|
3743
|
+
if (ext === '.yml' || ext === '.yaml')
|
|
3744
|
+
return 'hash';
|
|
3745
|
+
if (name === '.gitignore' || name === '_gitignore' || file.startsWith('.husky/'))
|
|
3746
|
+
return 'hash';
|
|
3747
|
+
if (SLASH_EXTENSIONS.includes(ext))
|
|
3748
|
+
return 'slash';
|
|
3749
|
+
if (/^tsconfig.*\.json$/.test(name) || name === 'turbo.json')
|
|
3750
|
+
return 'slash';
|
|
3751
|
+
return null;
|
|
3752
|
+
}
|
|
3753
|
+
/** Drops blocks named in `remove` (plus template-only) and the marker lines of the rest. */
|
|
3754
|
+
function applyMarkers(text, path, remove) {
|
|
3755
|
+
const style = commentStyle(path);
|
|
3756
|
+
if (!style)
|
|
3757
|
+
return text;
|
|
3758
|
+
const eol = text.includes('\r\n') ? '\r\n' : '\n';
|
|
3759
|
+
const out = [];
|
|
3760
|
+
let open = null;
|
|
3761
|
+
for (const [index, raw] of text.split(/\r?\n/).entries()) {
|
|
3762
|
+
const line = index + 1;
|
|
3763
|
+
const match = raw.trim().match(MARKER[style]);
|
|
3764
|
+
if (!match) {
|
|
3765
|
+
if (!open?.drop)
|
|
3766
|
+
out.push(raw);
|
|
3767
|
+
continue;
|
|
3768
|
+
}
|
|
3769
|
+
const [, closing, name = ''] = match;
|
|
3770
|
+
if (!NAMES.includes(name))
|
|
3771
|
+
throw new MarkerError(path, line, `unknown example "${name}"`);
|
|
3772
|
+
if (closing) {
|
|
3773
|
+
if (open?.name !== name) {
|
|
3774
|
+
throw new MarkerError(path, line, `example:${name} closes without a matching opening`);
|
|
3775
|
+
}
|
|
3776
|
+
open = null;
|
|
3777
|
+
}
|
|
3778
|
+
else {
|
|
3779
|
+
if (open)
|
|
3780
|
+
throw new MarkerError(path, line, `example:${name} opens inside example:${open.name}`);
|
|
3781
|
+
open = { name, line, drop: name === 'template-only' || remove.has(name) };
|
|
3782
|
+
}
|
|
3783
|
+
}
|
|
3784
|
+
if (open)
|
|
3785
|
+
throw new MarkerError(path, open.line, `example:${open.name} is never closed`);
|
|
3786
|
+
return out.join(eol);
|
|
3787
|
+
}
|
|
3788
|
+
|
|
3789
|
+
const EXAMPLE_DIRS = {
|
|
3790
|
+
lib: ['packages/shared', 'packages/lib'],
|
|
3791
|
+
cli: ['packages/cli'],
|
|
3792
|
+
web: ['packages/web'],
|
|
3793
|
+
};
|
|
3794
|
+
// Files that only make sense inside the template repo itself.
|
|
3795
|
+
const TEMPLATE_ONLY_FILES = ['scripts/check-examples.mjs', 'scripts/check-examples.test.ts'];
|
|
3796
|
+
// pnpm rewrites the lockfile after generation, so it is never edited here.
|
|
3797
|
+
const LOCKFILE = 'pnpm-lock.yaml';
|
|
3798
|
+
/** Repo-relative paths (with `/`) of every file under `dir`. */
|
|
3799
|
+
async function listFiles(dir, prefix = '') {
|
|
3800
|
+
const entries = await readdir(join(dir, prefix), { withFileTypes: true });
|
|
3801
|
+
const nested = await Promise.all(entries.map((entry) => {
|
|
3802
|
+
const path = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
3803
|
+
return entry.isDirectory() ? listFiles(dir, path) : [path];
|
|
3804
|
+
}));
|
|
3805
|
+
return nested.flat();
|
|
3806
|
+
}
|
|
3807
|
+
async function isText(path) {
|
|
3808
|
+
const handle = await open(path, 'r');
|
|
3809
|
+
try {
|
|
3810
|
+
const buffer = Buffer.alloc(8192);
|
|
3811
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
3812
|
+
return !buffer.subarray(0, bytesRead).includes(0);
|
|
3813
|
+
}
|
|
3814
|
+
finally {
|
|
3815
|
+
await handle.close();
|
|
3816
|
+
}
|
|
3817
|
+
}
|
|
3818
|
+
function identityEdits(input) {
|
|
3819
|
+
const { folderName, holder, year } = input;
|
|
3820
|
+
return [
|
|
3821
|
+
{ file: 'package.json', from: '"name": "ts-monorepo-starter"', to: `"name": "${folderName}"` },
|
|
3822
|
+
{ file: 'README.md', from: '# TypeScript Monorepo Starter', to: `# ${folderName}` },
|
|
3823
|
+
{ file: 'README.md', from: /^ts-monorepo-starter\/$/m, to: `${folderName}/` },
|
|
3824
|
+
{ file: 'README.md', from: 'cd ts-monorepo-starter', to: `cd ${folderName}` },
|
|
3825
|
+
{
|
|
3826
|
+
file: 'README.md',
|
|
3827
|
+
from: 'yourusername/ts-monorepo-starter.git',
|
|
3828
|
+
to: `yourusername/${folderName}.git`,
|
|
3829
|
+
},
|
|
3830
|
+
{
|
|
3831
|
+
file: 'LICENSE',
|
|
3832
|
+
from: 'Copyright (c) 2025 prosdevlab',
|
|
3833
|
+
to: `Copyright (c) ${year} ${holder}`,
|
|
3834
|
+
},
|
|
3835
|
+
];
|
|
3836
|
+
}
|
|
3837
|
+
/** Writes the chosen examples of the template at `from` into `to`; touches nothing else. */
|
|
3838
|
+
async function generate(input) {
|
|
3839
|
+
const { from, to, scope, keep } = input;
|
|
3840
|
+
await cp(from, to, { recursive: true });
|
|
3841
|
+
const all = await listFiles(to);
|
|
3842
|
+
for (const file of all) {
|
|
3843
|
+
const name = file.slice(file.lastIndexOf('/') + 1);
|
|
3844
|
+
const renamed = DOTFILE_RENAMES[name];
|
|
3845
|
+
if (renamed)
|
|
3846
|
+
await rename(join(to, file), join(to, file.slice(0, -name.length) + renamed));
|
|
3847
|
+
}
|
|
3848
|
+
const removed = EXAMPLES.filter((example) => !keep.includes(example));
|
|
3849
|
+
const doomed = [...removed.flatMap((example) => EXAMPLE_DIRS[example]), ...TEMPLATE_ONLY_FILES];
|
|
3850
|
+
for (const path of doomed)
|
|
3851
|
+
await rm(join(to, path), { recursive: true, force: true });
|
|
3852
|
+
// The template-only files may have been all of scripts/.
|
|
3853
|
+
const scripts = join(to, 'scripts');
|
|
3854
|
+
const left = await readdir(scripts).catch(() => null);
|
|
3855
|
+
if (left?.length === 0)
|
|
3856
|
+
await rmdir(scripts);
|
|
3857
|
+
const remove = new Set(removed);
|
|
3858
|
+
const identity = identityEdits(input);
|
|
3859
|
+
const present = await listFiles(to);
|
|
3860
|
+
for (const edit of identity) {
|
|
3861
|
+
if (!present.includes(edit.file)) {
|
|
3862
|
+
throw new Error(`Template changed: "${typeof edit.from === 'string' ? edit.from : 'ts-monorepo-starter/'}" not found in ${edit.file}`);
|
|
3863
|
+
}
|
|
3864
|
+
}
|
|
3865
|
+
for (const file of present) {
|
|
3866
|
+
if (file === LOCKFILE || !(await isText(join(to, file))))
|
|
3867
|
+
continue;
|
|
3868
|
+
const original = await readFile(join(to, file), 'utf8');
|
|
3869
|
+
let text = commentStyle(file) ? applyMarkers(original, file, remove) : original;
|
|
3870
|
+
text = text.replaceAll('@monorepo/', `${scope}/`);
|
|
3871
|
+
for (const edit of identity.filter((entry) => entry.file === file)) {
|
|
3872
|
+
const found = typeof edit.from === 'string' ? text.includes(edit.from) : edit.from.test(text);
|
|
3873
|
+
if (!found) {
|
|
3874
|
+
const shown = typeof edit.from === 'string' ? edit.from : 'ts-monorepo-starter/';
|
|
3875
|
+
throw new Error(`Template changed: "${shown}" not found in ${file}`);
|
|
3876
|
+
}
|
|
3877
|
+
text = text.replace(edit.from, () => edit.to);
|
|
3878
|
+
}
|
|
3879
|
+
if (text !== original)
|
|
3880
|
+
await writeFile(join(to, file), text);
|
|
3881
|
+
}
|
|
3882
|
+
}
|
|
3883
|
+
|
|
3884
|
+
/** Thrown when an install added lockfile entries the bundled lockfile lacks. */
|
|
3885
|
+
class LockfileError extends Error {
|
|
3886
|
+
name = 'LockfileError';
|
|
3887
|
+
code = 'lockfile-changed';
|
|
3888
|
+
}
|
|
3889
|
+
const SECTIONS = ['packages', 'snapshots'];
|
|
3890
|
+
function unquote(key) {
|
|
3891
|
+
return key.startsWith("'") && key.endsWith("'") ? key.slice(1, -1).replaceAll("''", "'") : key;
|
|
3892
|
+
}
|
|
3893
|
+
/** Entries as `packages: name@version` / `snapshots: name@version`, across every YAML document. */
|
|
3894
|
+
function sectionEntries(text) {
|
|
3895
|
+
const found = new Set();
|
|
3896
|
+
for (const doc of text.split(/^---\r?$/m)) {
|
|
3897
|
+
let section = null;
|
|
3898
|
+
for (const line of doc.split(/\r?\n/)) {
|
|
3899
|
+
if (line.startsWith('#'))
|
|
3900
|
+
continue;
|
|
3901
|
+
const top = /^(\w+):\s*$/.exec(line);
|
|
3902
|
+
if (top) {
|
|
3903
|
+
section = SECTIONS.includes(top[1])
|
|
3904
|
+
? top[1]
|
|
3905
|
+
: null;
|
|
3906
|
+
}
|
|
3907
|
+
else if (/^\S/.test(line)) {
|
|
3908
|
+
section = null;
|
|
3909
|
+
}
|
|
3910
|
+
else if (section) {
|
|
3911
|
+
// A key ends at the first `:` followed by whitespace or end of line, so `node@runtime:1.0.0:` works.
|
|
3912
|
+
const key = /^ {2}('(?:[^']|'')*'|[^\s'#].*?):(?=\s|$)/.exec(line);
|
|
3913
|
+
if (key)
|
|
3914
|
+
found.add(`${section}: ${unquote(key[1])}`);
|
|
3915
|
+
}
|
|
3916
|
+
}
|
|
3917
|
+
}
|
|
3918
|
+
return found;
|
|
3919
|
+
}
|
|
3920
|
+
/** Throws unless every entry of `generated` already exists in `bundled`. */
|
|
3921
|
+
function assertLockfileSubset(bundled, generated) {
|
|
3922
|
+
const have = sectionEntries(bundled);
|
|
3923
|
+
const added = [...sectionEntries(generated)].filter((e) => !have.has(e));
|
|
3924
|
+
if (added.length === 0)
|
|
3925
|
+
return;
|
|
3926
|
+
const lines = added.slice(0, 10).map((e) => `+ ${e}`);
|
|
3927
|
+
if (added.length > 10)
|
|
3928
|
+
lines.push(`…and ${added.length - 10} more`);
|
|
3929
|
+
throw new LockfileError(`Lockfile changed during install:\n${lines.join('\n')}`);
|
|
3930
|
+
}
|
|
3931
|
+
|
|
3932
|
+
const RETRY_CODES = new Set(['EPERM', 'EBUSY']);
|
|
3933
|
+
const RETRY_DELAYS = [100, 200, 400, 800, 1600];
|
|
3934
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
3935
|
+
/** `<parent>/.<name>.tmp-<8 hex>`, beside the target so the final rename stays on one volume. */
|
|
3936
|
+
function tempPath(target, random = () => randomBytes(4).toString('hex')) {
|
|
3937
|
+
target = resolve(target);
|
|
3938
|
+
return join(dirname(target), `.${basename(target)}.tmp-${random()}`);
|
|
3939
|
+
}
|
|
3940
|
+
/** `<target>.backup-YYYYMMDD-HHMMSS` in local time. */
|
|
3941
|
+
function backupPath(target, now) {
|
|
3942
|
+
target = resolve(target);
|
|
3943
|
+
const date = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`;
|
|
3836
3944
|
const time = `${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
|
|
3837
3945
|
return `${target}.backup-${date}-${time}`;
|
|
3838
3946
|
}
|
|
@@ -3855,6 +3963,17 @@ async function targetState(target) {
|
|
|
3855
3963
|
return 'not-empty';
|
|
3856
3964
|
return (await readdir(target)).length === 0 ? 'empty' : 'not-empty';
|
|
3857
3965
|
}
|
|
3966
|
+
/** Never throws. Anything that exists and isn't a directory (a file as the target) is `not-empty`. */
|
|
3967
|
+
function probePath(path) {
|
|
3968
|
+
try {
|
|
3969
|
+
if (!lstatSync(path).isDirectory())
|
|
3970
|
+
return 'not-empty';
|
|
3971
|
+
return readdirSync(path).length === 0 ? 'empty' : 'not-empty';
|
|
3972
|
+
}
|
|
3973
|
+
catch (error) {
|
|
3974
|
+
return error.code === 'ENOENT' ? 'missing' : 'unreadable';
|
|
3975
|
+
}
|
|
3976
|
+
}
|
|
3858
3977
|
/** True when `child` is `parent` or inside it (a name that merely starts with `..` is inside). */
|
|
3859
3978
|
function isInside(parent, child) {
|
|
3860
3979
|
const rel = relative(parent, child);
|
|
@@ -3905,10 +4024,12 @@ async function backUp(target, now, deps = {}) {
|
|
|
3905
4024
|
candidate = `${base}-${n}`;
|
|
3906
4025
|
const move = retryingRename(deps);
|
|
3907
4026
|
if (!(await holdsCwd(target, deps.cwd))) {
|
|
4027
|
+
deps.onPath?.(candidate);
|
|
3908
4028
|
await move(target, candidate);
|
|
3909
4029
|
return candidate;
|
|
3910
4030
|
}
|
|
3911
4031
|
await mkdir(candidate);
|
|
4032
|
+
deps.onPath?.(candidate);
|
|
3912
4033
|
const entries = await readdir(target);
|
|
3913
4034
|
for (const [index, entry] of entries.entries()) {
|
|
3914
4035
|
try {
|
|
@@ -4005,11 +4126,9 @@ function onInterrupt(temp, deps = {}) {
|
|
|
4005
4126
|
}
|
|
4006
4127
|
|
|
4007
4128
|
/** A failure with the output lines that explain it. */
|
|
4008
|
-
class RunError extends
|
|
4009
|
-
lines
|
|
4010
|
-
|
|
4011
|
-
super(message);
|
|
4012
|
-
this.lines = lines;
|
|
4129
|
+
class RunError extends CliError {
|
|
4130
|
+
constructor(code, message, lines = []) {
|
|
4131
|
+
super(code, message, lines);
|
|
4013
4132
|
this.name = 'RunError';
|
|
4014
4133
|
}
|
|
4015
4134
|
}
|
|
@@ -4027,6 +4146,7 @@ function planFromOptions(o, cwd, now, holder) {
|
|
|
4027
4146
|
}
|
|
4028
4147
|
return {
|
|
4029
4148
|
target: resolve(cwd, o.folder),
|
|
4149
|
+
folder: o.folder,
|
|
4030
4150
|
folderName: packageNameFromFolder(o.folder, cwd),
|
|
4031
4151
|
scope,
|
|
4032
4152
|
keep: o.examples ?? [...EXAMPLES],
|
|
@@ -4040,20 +4160,20 @@ function lastLines(output) {
|
|
|
4040
4160
|
const lines = `${output.stdout}\n${output.stderr}`.split(/\r?\n/).filter((l) => l.trim());
|
|
4041
4161
|
return lines.slice(-20);
|
|
4042
4162
|
}
|
|
4163
|
+
/** What a failure or a Ctrl-C says about a temporary folder it couldn't delete. */
|
|
4164
|
+
const leftoverLine = (temp) => `Couldn't delete the temporary folder ${temp}: delete it yourself.`;
|
|
4043
4165
|
/** The line a Ctrl-C prints: "nothing was written" holds only until the backup starts. */
|
|
4044
4166
|
function cancelMessage(phase, plan, temp, outcome) {
|
|
4045
4167
|
const { target } = plan;
|
|
4046
4168
|
const leftover = [
|
|
4047
|
-
...(outcome.removed
|
|
4048
|
-
? []
|
|
4049
|
-
: [`Couldn't delete the temporary folder ${temp}: delete it yourself.`]),
|
|
4169
|
+
...(outcome.removed ? [] : [leftoverLine(temp)]),
|
|
4050
4170
|
...(outcome.stopped ? [] : ['pnpm may still be running in it.']),
|
|
4051
4171
|
];
|
|
4052
4172
|
switch (phase.at) {
|
|
4053
4173
|
case 'working':
|
|
4054
4174
|
return outcome.removed ? [CANCELLED, leftover] : ['Cancelled.', leftover];
|
|
4055
4175
|
case 'backing-up': {
|
|
4056
|
-
const backup = basename(backupPath(target, plan.now));
|
|
4176
|
+
const backup = basename(phase.backup ?? backupPath(target, plan.now));
|
|
4057
4177
|
const where = phase.inPlace
|
|
4058
4178
|
? `Your files are in ${target}, in ${backup} beside it, or split between the two.`
|
|
4059
4179
|
: `Your files are in ${target}, or in ${backup} beside it.`;
|
|
@@ -4071,6 +4191,53 @@ function cancelMessage(phase, plan, temp, outcome) {
|
|
|
4071
4191
|
return [`Cancelled after the project was created in ${target}.`, leftover];
|
|
4072
4192
|
}
|
|
4073
4193
|
}
|
|
4194
|
+
/**
|
|
4195
|
+
* What the run left behind, from the phase it was in and a synchronous read of the disk. Before
|
|
4196
|
+
* `onPath` has fired the phase has no backup path, so no backup is claimed.
|
|
4197
|
+
*/
|
|
4198
|
+
function leftBehind(phase, before, read, target) {
|
|
4199
|
+
const unknown = (backup) => {
|
|
4200
|
+
const found = backup && read(backup) === 'not-empty' ? backup : undefined;
|
|
4201
|
+
return { target: 'unknown', ...(found && { backup: found }) };
|
|
4202
|
+
};
|
|
4203
|
+
if (phase.at === 'working') {
|
|
4204
|
+
if (before === undefined)
|
|
4205
|
+
return { target: 'unknown' };
|
|
4206
|
+
return { target: before === 'not-empty' ? 'unchanged' : before };
|
|
4207
|
+
}
|
|
4208
|
+
if (phase.at === 'moved')
|
|
4209
|
+
return { target: 'complete', ...(phase.backup && { backup: phase.backup }) };
|
|
4210
|
+
const backup = phase.backup;
|
|
4211
|
+
if (phase.at === 'backing-up' && !backup)
|
|
4212
|
+
return { target: 'unchanged' };
|
|
4213
|
+
const now = read(target);
|
|
4214
|
+
if (now === 'unreadable')
|
|
4215
|
+
return unknown(backup);
|
|
4216
|
+
if (phase.at === 'moving') {
|
|
4217
|
+
// backUp has returned, so the files are there unless the disk says the folder is gone or empty.
|
|
4218
|
+
const kept = backup ? read(backup) : 'missing';
|
|
4219
|
+
const where = backup && kept !== 'missing' && kept !== 'empty' ? { backup } : {};
|
|
4220
|
+
if (now === 'missing' || now === 'empty')
|
|
4221
|
+
return { target: now, ...where };
|
|
4222
|
+
if (before === undefined)
|
|
4223
|
+
return { target: 'unknown', ...where };
|
|
4224
|
+
if (before === 'missing' || before === 'empty' || backup)
|
|
4225
|
+
return { target: 'partial', ...where };
|
|
4226
|
+
return { target: 'unchanged' };
|
|
4227
|
+
}
|
|
4228
|
+
const moved = read(backup);
|
|
4229
|
+
if (moved === 'unreadable')
|
|
4230
|
+
return unknown(backup);
|
|
4231
|
+
if (now === 'not-empty') {
|
|
4232
|
+
return moved === 'not-empty' ? { target: 'split', backup } : { target: 'unchanged' };
|
|
4233
|
+
}
|
|
4234
|
+
return moved === 'not-empty' ? { target: now, backup } : unknown();
|
|
4235
|
+
}
|
|
4236
|
+
const recorded = new WeakMap();
|
|
4237
|
+
/** The `left` that `run()` recorded for an error it threw, if any. */
|
|
4238
|
+
function leftOf(error) {
|
|
4239
|
+
return typeof error === 'object' && error !== null ? recorded.get(error) : undefined;
|
|
4240
|
+
}
|
|
4074
4241
|
const firstLine = (error) => (error instanceof Error ? error.message : String(error)).split('\n')[0] ?? '';
|
|
4075
4242
|
/** Generates, installs and commits in a temporary folder, then moves it to `plan.target`. */
|
|
4076
4243
|
async function run(plan, ui, deps = {}) {
|
|
@@ -4090,6 +4257,8 @@ async function run(plan, ui, deps = {}) {
|
|
|
4090
4257
|
const temp = tempPath(plan.target);
|
|
4091
4258
|
// What a Ctrl-C has to report changes once the user's folder is moved aside or ours moves in.
|
|
4092
4259
|
let phase = { at: 'working' };
|
|
4260
|
+
let before;
|
|
4261
|
+
const probe = deps.probe ?? probePath;
|
|
4093
4262
|
const unregister = (deps.onInterrupt ?? onInterrupt)(temp, {
|
|
4094
4263
|
onStart: () => {
|
|
4095
4264
|
interrupted = true;
|
|
@@ -4097,8 +4266,36 @@ async function run(plan, ui, deps = {}) {
|
|
|
4097
4266
|
exit: (code, outcome) => {
|
|
4098
4267
|
try {
|
|
4099
4268
|
ui.stop();
|
|
4269
|
+
const facts = {
|
|
4270
|
+
...(outcome.removed ? {} : { temp }),
|
|
4271
|
+
...(outcome.stopped ? {} : { running: true }),
|
|
4272
|
+
};
|
|
4273
|
+
let left;
|
|
4274
|
+
try {
|
|
4275
|
+
left = { ...leftBehind(phase, before, probe, plan.target), ...facts };
|
|
4276
|
+
}
|
|
4277
|
+
catch {
|
|
4278
|
+
left = { target: 'unknown', ...facts };
|
|
4279
|
+
}
|
|
4100
4280
|
const [title, lines] = cancelMessage(phase, plan, temp, outcome);
|
|
4101
|
-
|
|
4281
|
+
const interrupted = {
|
|
4282
|
+
ok: false,
|
|
4283
|
+
error: { code: 'interrupted', title, lines, fixes: [] },
|
|
4284
|
+
left,
|
|
4285
|
+
};
|
|
4286
|
+
renderText(interrupted, ui);
|
|
4287
|
+
try {
|
|
4288
|
+
deps.onOutcome?.(interrupted);
|
|
4289
|
+
}
|
|
4290
|
+
catch { }
|
|
4291
|
+
// Only an empty folder this run created: rmdir can't remove one with files in it.
|
|
4292
|
+
try {
|
|
4293
|
+
if (phase.at === 'backing-up' && phase.inPlace && phase.backup) {
|
|
4294
|
+
if (probe(phase.backup) === 'empty')
|
|
4295
|
+
rmdirSync(phase.backup);
|
|
4296
|
+
}
|
|
4297
|
+
}
|
|
4298
|
+
catch { }
|
|
4102
4299
|
}
|
|
4103
4300
|
finally {
|
|
4104
4301
|
process.exit(code);
|
|
@@ -4106,10 +4303,13 @@ async function run(plan, ui, deps = {}) {
|
|
|
4106
4303
|
},
|
|
4107
4304
|
});
|
|
4108
4305
|
try {
|
|
4306
|
+
before = await targetState(plan.target).catch(() => undefined);
|
|
4109
4307
|
// pnpm first: a pnpm that can't switch to the template's version stops the run before any file.
|
|
4110
4308
|
const spec = pnpmSpec(await readFile(join(from, 'package.json'), 'utf8'));
|
|
4111
4309
|
const pin = spec.slice('pnpm@'.length);
|
|
4112
4310
|
const pnpm = await detectPnpm(exec);
|
|
4311
|
+
if (pnpm.kind === 'old')
|
|
4312
|
+
throw tooOld(pnpm.version, spec);
|
|
4113
4313
|
if (pnpm.kind === 'ok')
|
|
4114
4314
|
await checkSwitch(spec, pnpm.version, exec);
|
|
4115
4315
|
await (deps.generate ?? generate)({
|
|
@@ -4148,40 +4348,29 @@ async function run(plan, ui, deps = {}) {
|
|
|
4148
4348
|
}
|
|
4149
4349
|
}
|
|
4150
4350
|
const command = installCommand(pnpm, temp, !plan.install);
|
|
4151
|
-
|
|
4152
|
-
|
|
4153
|
-
|
|
4154
|
-
|
|
4155
|
-
|
|
4156
|
-
'It would install with the wrong pnpm and Node, and skip the',
|
|
4157
|
-
'3-day release rule. Install skipped.',
|
|
4351
|
+
const what = plan.install ? 'install dependencies' : 'update the lockfile';
|
|
4352
|
+
if (pnpm.kind === 'none') {
|
|
4353
|
+
const doing = plan.install ? 'Installing' : 'Updating the lockfile';
|
|
4354
|
+
ui.warn("pnpm isn't installed", [
|
|
4355
|
+
`${doing} with a temporary pnpm ${pin} instead (npm exec).`,
|
|
4158
4356
|
]);
|
|
4159
4357
|
}
|
|
4160
|
-
|
|
4161
|
-
|
|
4162
|
-
|
|
4163
|
-
|
|
4164
|
-
|
|
4165
|
-
|
|
4166
|
-
]);
|
|
4167
|
-
}
|
|
4168
|
-
const using = pnpm.kind === 'ok' ? ` with pnpm ${pin}` : '';
|
|
4169
|
-
const started = performance.now();
|
|
4170
|
-
ui.start(plan.install ? `Installing dependencies${using}` : 'Updating the lockfile');
|
|
4171
|
-
let output;
|
|
4172
|
-
try {
|
|
4173
|
-
output = await exec(command.cmd, command.args, { cwd: command.cwd });
|
|
4174
|
-
}
|
|
4175
|
-
finally {
|
|
4176
|
-
ui.stop();
|
|
4177
|
-
}
|
|
4178
|
-
seconds = Math.round((performance.now() - started) / 1000);
|
|
4179
|
-
if (output.code !== 0) {
|
|
4180
|
-
throw new RunError(`Couldn't ${what} (pnpm exited with ${output.code})`, lastLines(output));
|
|
4181
|
-
}
|
|
4182
|
-
installed = plan.install;
|
|
4183
|
-
ui.step(plan.install ? `Installed dependencies${using} (${seconds}s)` : 'Updated the lockfile');
|
|
4358
|
+
const using = pnpm.kind === 'ok' ? ` with pnpm ${pin}` : '';
|
|
4359
|
+
const started = performance.now();
|
|
4360
|
+
ui.start(plan.install ? `Installing dependencies${using}` : 'Updating the lockfile');
|
|
4361
|
+
let output;
|
|
4362
|
+
try {
|
|
4363
|
+
output = await exec(command.cmd, command.args, { cwd: command.cwd });
|
|
4184
4364
|
}
|
|
4365
|
+
finally {
|
|
4366
|
+
ui.stop();
|
|
4367
|
+
}
|
|
4368
|
+
const seconds = Math.round((performance.now() - started) / 1000);
|
|
4369
|
+
if (output.code !== 0) {
|
|
4370
|
+
throw new RunError('install-failed', `Couldn't ${what} (pnpm exited with ${output.code})`, lastLines(output));
|
|
4371
|
+
}
|
|
4372
|
+
const installed = plan.install;
|
|
4373
|
+
ui.step(plan.install ? `Installed dependencies${using} (${seconds}s)` : 'Updated the lockfile');
|
|
4185
4374
|
assertLockfileSubset(await readFile(join(from, 'pnpm-lock.yaml'), 'utf8'), await readFile(join(temp, 'pnpm-lock.yaml'), 'utf8'));
|
|
4186
4375
|
let outcome = git === 'ready' ? 'failed' : git;
|
|
4187
4376
|
if (git === 'ready') {
|
|
@@ -4208,22 +4397,29 @@ async function run(plan, ui, deps = {}) {
|
|
|
4208
4397
|
let backup;
|
|
4209
4398
|
if (plan.replace && (await targetState(plan.target)) === 'not-empty') {
|
|
4210
4399
|
const cwd = deps.cwd ?? process.cwd();
|
|
4211
|
-
|
|
4212
|
-
|
|
4400
|
+
const inPlace = await holdsCwd(plan.target, cwd);
|
|
4401
|
+
phase = { at: 'backing-up', inPlace, backup: undefined };
|
|
4402
|
+
const onPath = (path) => {
|
|
4403
|
+
phase = { at: 'backing-up', inPlace, backup: path };
|
|
4404
|
+
};
|
|
4405
|
+
try {
|
|
4406
|
+
backup = await (deps.backUp ?? backUp)(plan.target, plan.now, { cwd, onPath });
|
|
4407
|
+
}
|
|
4408
|
+
catch (error) {
|
|
4409
|
+
throw coded('backup-failed', error);
|
|
4410
|
+
}
|
|
4213
4411
|
phase = { at: 'backed-up', backup };
|
|
4214
4412
|
ui.step(`Moved the old ${name} to ${basename(backup)}`);
|
|
4215
4413
|
}
|
|
4216
4414
|
try {
|
|
4217
4415
|
phase = { at: 'moving', ...(backup && { backup }) };
|
|
4218
4416
|
await (deps.moveIntoPlace ?? moveIntoPlace)(temp, plan.target);
|
|
4219
|
-
phase = { at: 'moved' };
|
|
4417
|
+
phase = { at: 'moved', ...(backup && { backup }) };
|
|
4220
4418
|
}
|
|
4221
4419
|
catch (error) {
|
|
4222
4420
|
if (!backup)
|
|
4223
|
-
throw error;
|
|
4224
|
-
throw new RunError(`Couldn't move the project into place: ${firstLine(error)}`, [
|
|
4225
|
-
`The old files are in ${backup}.`,
|
|
4226
|
-
]);
|
|
4421
|
+
throw coded('move-failed', error);
|
|
4422
|
+
throw new RunError('move-failed', `Couldn't move the project into place: ${firstLine(error)}`, [`The old files are in ${backup}.`]);
|
|
4227
4423
|
}
|
|
4228
4424
|
return {
|
|
4229
4425
|
pnpm,
|
|
@@ -4235,7 +4431,28 @@ async function run(plan, ui, deps = {}) {
|
|
|
4235
4431
|
};
|
|
4236
4432
|
}
|
|
4237
4433
|
catch (error) {
|
|
4238
|
-
|
|
4434
|
+
let left;
|
|
4435
|
+
try {
|
|
4436
|
+
left = leftBehind(phase, before, probe, plan.target);
|
|
4437
|
+
}
|
|
4438
|
+
catch {
|
|
4439
|
+
left = { target: 'unknown' };
|
|
4440
|
+
}
|
|
4441
|
+
try {
|
|
4442
|
+
await (deps.rm ?? rm)(temp, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
|
|
4443
|
+
}
|
|
4444
|
+
catch {
|
|
4445
|
+
// The run's own error is the one to show; `left.temp` says what stayed behind.
|
|
4446
|
+
}
|
|
4447
|
+
try {
|
|
4448
|
+
if (probe(temp) !== 'missing')
|
|
4449
|
+
left = { ...left, temp };
|
|
4450
|
+
}
|
|
4451
|
+
catch {
|
|
4452
|
+
left = { ...left, temp };
|
|
4453
|
+
}
|
|
4454
|
+
if (typeof error === 'object' && error !== null)
|
|
4455
|
+
recorded.set(error, left);
|
|
4239
4456
|
throw error;
|
|
4240
4457
|
}
|
|
4241
4458
|
finally {
|
|
@@ -4243,15 +4460,6 @@ async function run(plan, ui, deps = {}) {
|
|
|
4243
4460
|
}
|
|
4244
4461
|
}
|
|
4245
4462
|
|
|
4246
|
-
const USAGE = 2;
|
|
4247
|
-
const FAILURE = 1;
|
|
4248
|
-
/** The machine needs fixing first (pnpm can't switch versions, or is too old); nothing was created. */
|
|
4249
|
-
const TOOLCHAIN = 3;
|
|
4250
|
-
const INTERRUPTED = 130;
|
|
4251
|
-
const usage = (message) => {
|
|
4252
|
-
process.stderr.write(`${message}\n`);
|
|
4253
|
-
return USAGE;
|
|
4254
|
-
};
|
|
4255
4463
|
const nameProblem = (folder, cwd) => {
|
|
4256
4464
|
try {
|
|
4257
4465
|
packageNameFromFolder(folder, cwd);
|
|
@@ -4304,117 +4512,103 @@ async function askPlan(ask, cwd, options, now, holder) {
|
|
|
4304
4512
|
}
|
|
4305
4513
|
return { ...planFromOptions(answers, cwd, now, holder), replace };
|
|
4306
4514
|
}
|
|
4307
|
-
function report(ui, error) {
|
|
4308
|
-
if (error instanceof CancelledError) {
|
|
4309
|
-
ui.fail(CANCELLED, []);
|
|
4310
|
-
return INTERRUPTED;
|
|
4311
|
-
}
|
|
4312
|
-
if (error instanceof ToolchainError) {
|
|
4313
|
-
ui.fail(error.message, error.lines);
|
|
4314
|
-
return TOOLCHAIN;
|
|
4315
|
-
}
|
|
4316
|
-
if (error instanceof RunError) {
|
|
4317
|
-
ui.fail(error.message, error.lines);
|
|
4318
|
-
return FAILURE;
|
|
4319
|
-
}
|
|
4320
|
-
const [title = 'Something went wrong', ...lines] = String(error instanceof Error ? error.message : error).split('\n');
|
|
4321
|
-
ui.fail(title, lines);
|
|
4322
|
-
return FAILURE;
|
|
4323
|
-
}
|
|
4324
4515
|
/** `--check`: is this machine's pnpm ready for the template's? Creates nothing. */
|
|
4325
4516
|
async function check(ui, exec) {
|
|
4326
4517
|
const spec = pnpmSpec();
|
|
4327
|
-
const version = spec.slice('pnpm@'.length);
|
|
4328
4518
|
ui.intro();
|
|
4329
4519
|
const pnpm = await detectPnpm(exec);
|
|
4330
|
-
if (pnpm.kind === 'none')
|
|
4331
|
-
|
|
4332
|
-
|
|
4333
|
-
|
|
4334
|
-
]);
|
|
4335
|
-
return 0;
|
|
4336
|
-
}
|
|
4337
|
-
if (pnpm.kind === 'old') {
|
|
4338
|
-
ui.fail(`pnpm ${pnpm.version} is too old for this project`, [
|
|
4339
|
-
`This project needs pnpm 10.26 or newer, which switches itself to pnpm ${version}.`,
|
|
4340
|
-
'Upgrade pnpm (https://pnpm.io/installation), then run --check again.',
|
|
4341
|
-
]);
|
|
4342
|
-
return TOOLCHAIN;
|
|
4343
|
-
}
|
|
4520
|
+
if (pnpm.kind === 'none')
|
|
4521
|
+
return { ok: true, kind: 'checked', pnpm, warnings: [] };
|
|
4522
|
+
if (pnpm.kind === 'old')
|
|
4523
|
+
return { ok: false, error: failureFrom(tooOld(pnpm.version, spec)) };
|
|
4344
4524
|
try {
|
|
4345
4525
|
await checkSwitch(spec, pnpm.version, exec);
|
|
4346
4526
|
}
|
|
4347
4527
|
catch (error) {
|
|
4348
4528
|
if (!(error instanceof ToolchainError))
|
|
4349
4529
|
throw error;
|
|
4350
|
-
|
|
4351
|
-
return TOOLCHAIN;
|
|
4530
|
+
return { ok: false, error: failureFrom(error) };
|
|
4352
4531
|
}
|
|
4353
|
-
|
|
4354
|
-
return 0;
|
|
4532
|
+
return { ok: true, kind: 'checked', pnpm, warnings: [] };
|
|
4355
4533
|
}
|
|
4356
|
-
|
|
4357
|
-
|
|
4534
|
+
const isInteractive = (options, io) => !options.yes && (io.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY));
|
|
4535
|
+
/** The Ui a run shows: `--check` and pipes get plain text, a terminal gets the clack screens. */
|
|
4536
|
+
const chooseUi = (options, io) => io.ui ?? (!options.check && isInteractive(options, io) ? clackUi() : plainUi());
|
|
4537
|
+
/**
|
|
4538
|
+
* Runs the command and returns how it ended, without printing the result (progress goes to the Ui).
|
|
4539
|
+
* `--help` and `--version` are `main`'s: they print text and aren't an outcome.
|
|
4540
|
+
*/
|
|
4541
|
+
async function execute(argv, io = {}) {
|
|
4358
4542
|
const parsed = parseArgv(argv);
|
|
4359
4543
|
if (!parsed.ok)
|
|
4360
|
-
return
|
|
4544
|
+
return usageFailure(parsed.message);
|
|
4361
4545
|
const { options } = parsed;
|
|
4362
|
-
if (options.help) {
|
|
4363
|
-
process.stdout.write(`${helpText()}\n`);
|
|
4364
|
-
return 0;
|
|
4365
|
-
}
|
|
4366
|
-
if (options.version) {
|
|
4367
|
-
process.stdout.write(`${versionText()}\n`);
|
|
4368
|
-
return 0;
|
|
4369
|
-
}
|
|
4370
4546
|
if (options.check)
|
|
4371
|
-
return check(io
|
|
4547
|
+
return check(chooseUi(options, io), io.exec);
|
|
4372
4548
|
const cwd = io.cwd ?? process.cwd();
|
|
4373
|
-
const interactive =
|
|
4549
|
+
const interactive = isInteractive(options, io);
|
|
4374
4550
|
// A bad flag fails at once, before any question.
|
|
4375
4551
|
if (interactive) {
|
|
4376
4552
|
const problem = (options.folder !== undefined ? nameProblem(options.folder, cwd) : undefined) ??
|
|
4377
4553
|
(options.scope !== undefined ? scopeProblem(options.scope) : undefined);
|
|
4378
4554
|
if (problem)
|
|
4379
|
-
return
|
|
4555
|
+
return usageFailure(problem);
|
|
4380
4556
|
}
|
|
4381
4557
|
const now = new Date();
|
|
4382
4558
|
const holder = (await gitIdentity(cwd)).name;
|
|
4383
4559
|
let plan;
|
|
4384
4560
|
if (!interactive) {
|
|
4385
4561
|
if (options.folder === undefined) {
|
|
4386
|
-
return
|
|
4562
|
+
return usageFailure('Pass a folder name, for example: create-ts-monorepo-starter my-tools');
|
|
4387
4563
|
}
|
|
4388
4564
|
try {
|
|
4389
4565
|
plan = planFromOptions(options, cwd, now, holder);
|
|
4390
4566
|
}
|
|
4391
4567
|
catch (error) {
|
|
4392
4568
|
if (error instanceof NameError)
|
|
4393
|
-
return
|
|
4569
|
+
return usageFailure(error.message);
|
|
4394
4570
|
throw error;
|
|
4395
4571
|
}
|
|
4396
4572
|
}
|
|
4397
|
-
const ui =
|
|
4573
|
+
const ui = chooseUi(options, io);
|
|
4398
4574
|
ui.intro();
|
|
4399
4575
|
try {
|
|
4400
4576
|
if (plan && (await targetState(plan.target)) === 'not-empty') {
|
|
4401
4577
|
if (!options.force) {
|
|
4402
|
-
const
|
|
4403
|
-
|
|
4404
|
-
return FAILURE;
|
|
4578
|
+
const title = `${options.folder} isn't empty. Use another folder, or pass --force to move it aside.`;
|
|
4579
|
+
return { ok: false, error: { code: 'target-not-empty', title, lines: [], fixes: [] } };
|
|
4405
4580
|
}
|
|
4406
4581
|
plan.replace = true;
|
|
4407
4582
|
}
|
|
4408
4583
|
plan ??= await askPlan(createAsk(io.prompts), cwd, options, now, holder);
|
|
4409
|
-
const result = await run(plan, ui);
|
|
4410
|
-
|
|
4411
|
-
return
|
|
4584
|
+
const result = await run(plan, ui, io.runDeps);
|
|
4585
|
+
const left = { target: 'complete', ...(result.backup && { backup: result.backup }) };
|
|
4586
|
+
return { ok: true, kind: 'created', plan, result, warnings: [], left };
|
|
4412
4587
|
}
|
|
4413
4588
|
catch (error) {
|
|
4414
|
-
|
|
4415
|
-
|
|
4416
|
-
|
|
4589
|
+
const left = leftOf(error);
|
|
4590
|
+
const failure = failureFrom(error);
|
|
4591
|
+
// The interrupt path says this too; a failure would otherwise leave the folder unmentioned.
|
|
4592
|
+
if (left?.temp)
|
|
4593
|
+
failure.lines = [...failure.lines, leftoverLine(left.temp)];
|
|
4594
|
+
return { ok: false, error: failure, ...(left && { left }) };
|
|
4595
|
+
}
|
|
4596
|
+
}
|
|
4597
|
+
/** Runs the command, prints how it ended, and resolves with its exit code. */
|
|
4598
|
+
async function main(argv, io = {}) {
|
|
4599
|
+
const parsed = parseArgv(argv);
|
|
4600
|
+
if (parsed.ok && parsed.options.help) {
|
|
4601
|
+
process.stdout.write(`${helpText()}\n`);
|
|
4602
|
+
return 0;
|
|
4603
|
+
}
|
|
4604
|
+
if (parsed.ok && parsed.options.version) {
|
|
4605
|
+
process.stdout.write(`${versionText()}\n`);
|
|
4606
|
+
return 0;
|
|
4417
4607
|
}
|
|
4608
|
+
const ui = parsed.ok ? chooseUi(parsed.options, io) : (io.ui ?? plainUi());
|
|
4609
|
+
const outcome = await execute(argv, { ...io, ui });
|
|
4610
|
+
renderText(outcome, ui);
|
|
4611
|
+
return exitCode(outcome);
|
|
4418
4612
|
}
|
|
4419
4613
|
|
|
4420
4614
|
// Set the exit code instead of calling process.exit(), so pending output is flushed first.
|