dreamteamer 0.46.1 → 0.48.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/README.md +71 -6
- package/package.json +8 -3
- package/skills/using-dreamteamer/SKILL.md +7 -4
- package/skills/using-dreamteamer/references/extensions.md +41 -0
- package/skills/using-dreamteamer/references/getting-started.md +8 -8
- package/skills/using-dreamteamer/references/setup.md +122 -0
- package/skills/using-dreamteamer/references/writing-a-module.md +132 -0
- package/src/api.js +14 -2
- package/src/check-alone.js +121 -0
- package/src/checkout.js +253 -1
- package/src/cli.js +110 -24
- package/src/collections-cli.js +4 -2
- package/src/compile.js +1 -1
- package/src/doctor.js +10 -0
- package/src/env-write.js +162 -0
- package/src/extensions.js +36 -6
- package/src/init.js +30 -12
- package/src/install-modules.js +383 -0
- package/src/scaffold-templates.js +85 -0
- package/src/schema-ops.js +27 -4
- package/src/setup-contract.js +101 -0
- package/src/setup.js +506 -0
- package/src/testing.d.ts +29 -0
- package/src/testing.js +86 -0
- package/src/update.js +89 -0
package/src/init.js
CHANGED
|
@@ -63,10 +63,10 @@ const ENV_EXAMPLE = `# secrets for skills and modules go here (copy to .env; .en
|
|
|
63
63
|
# modules declare the env keys they require in their package.json dreamteamer.env list.
|
|
64
64
|
`;
|
|
65
65
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
66
|
+
/** The `dreamteamer` block init leaves in package.json: its seeds, under whatever the EXISTING block
|
|
67
|
+
* already says — the existing key always wins over a flag. One function, because `init --ready` must
|
|
68
|
+
* judge exactly the paths init will write, and a second copy of this precedence is how it did not. */
|
|
69
|
+
export function seedBlock(flags = {}, existing = {}) {
|
|
70
70
|
// EVERY known harness by default, and this is the operator's explicit call over the architecture
|
|
71
71
|
// review's dissent — recorded, not elided: it writes AGENTS.md, GEMINI.md and .cursor/rules/ into
|
|
72
72
|
// every new workspace, which is real clutter. The decision stands on the ASYMMETRY. A missing
|
|
@@ -78,12 +78,8 @@ export function init({ flags = {} } = {}) {
|
|
|
78
78
|
const harnesses = typeof flags.harnesses === 'string'
|
|
79
79
|
? flags.harnesses.split(',').map((s) => s.trim())
|
|
80
80
|
: [...KNOWN_HARNESSES];
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
const pkgPath = path.join(root, 'package.json');
|
|
84
|
-
const pkg = fs.existsSync(pkgPath) ? JSON.parse(fs.readFileSync(pkgPath, 'utf8')) : { name, private: true, version: '0.0.1' };
|
|
85
|
-
pkg.dreamteamer = {
|
|
86
|
-
'data_path': dataPath,
|
|
81
|
+
return {
|
|
82
|
+
'data_path': flags.data_path ?? 'data',
|
|
87
83
|
harnesses,
|
|
88
84
|
gitignore_runtime_folder: true,
|
|
89
85
|
// The workspace's own sources live in `modules/default/`, and the folder is named for its ROLE,
|
|
@@ -99,9 +95,30 @@ export function init({ flags = {} } = {}) {
|
|
|
99
95
|
'workspace_module': flags.workspace_module ?? 'default',
|
|
100
96
|
'git_modules': {},
|
|
101
97
|
disable: [],
|
|
102
|
-
...
|
|
98
|
+
...existing,
|
|
103
99
|
};
|
|
104
|
-
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Every path `init` writes or creates for this effective block, root-relative. ⚠ The data folder is
|
|
103
|
+
* the FLAG's (or `data`), not the block's — what init has always created, so both are listed. */
|
|
104
|
+
export function initFootprint(block, flags = {}) {
|
|
105
|
+
const wm = block.workspace_module, base = wm ? `modules/${wm}` : '.';
|
|
106
|
+
return ['package.json', '.gitignore', '.env.example', '.vscode/extensions.json', flags.data_path ?? 'data', block.data_path,
|
|
107
|
+
...SKELETON_KINDS.map((k) => `${base}/${k}`), ...(wm ? [`${base}/package.json`] : []), `${base}/collections/notes.collection.yaml`];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// `commit: false` is `init --ready`'s: a bootstrap writes and never commits (checkout.js `bootstrap`).
|
|
111
|
+
export function init({ flags = {}, root = process.cwd(), commit = true } = {}) {
|
|
112
|
+
const name = flags.name ?? path.basename(root);
|
|
113
|
+
const dataPath = flags.data_path ?? 'data';
|
|
114
|
+
// package.json: create or update — the single manifest
|
|
115
|
+
const pkgPath = path.join(root, 'package.json');
|
|
116
|
+
const pkg = fs.existsSync(pkgPath) ? JSON.parse(fs.readFileSync(pkgPath, 'utf8')) : { name, private: true, version: '0.0.1' };
|
|
117
|
+
const existed = fs.existsSync(pkgPath), had = pkg.dreamteamer ?? {};
|
|
118
|
+
pkg.dreamteamer = seedBlock(flags, pkg.dreamteamer);
|
|
119
|
+
// an existing block already holding every seeded key is left BYTE-FOR-BYTE: re-running init (or a
|
|
120
|
+
// repeated `init --ready`) must not reformat the operator's file into a diff that changes nothing
|
|
121
|
+
if (!existed || Object.keys(pkg.dreamteamer).some((k) => !(k in had))) fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, '\t') + '\n');
|
|
105
122
|
|
|
106
123
|
// folder skeleton — the workspace's own sources are an inline module, kinds FLAT at its root
|
|
107
124
|
const wm = pkg.dreamteamer.workspace_module;
|
|
@@ -154,6 +171,7 @@ export function init({ flags = {} } = {}) {
|
|
|
154
171
|
// `git add --all`, which in an existing repo swept every unrelated staged and unstaged change into
|
|
155
172
|
// a commit titled "init workspace": the one write in this engine that was not pathspec-scoped.
|
|
156
173
|
// `commit -- <paths>` also leaves anything the operator had already staged exactly as it was.
|
|
174
|
+
if (!commit) return 0;
|
|
157
175
|
const written = ['package.json', '.gitignore', '.env.example', '.vscode/extensions.json',
|
|
158
176
|
...(wm ? [path.join('modules', wm, 'package.json')] : []), path.relative(root, starter)]
|
|
159
177
|
.filter((f) => fs.existsSync(path.join(root, f)));
|
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
// `dt install <spec…>` — bring a module into this workspace: resolve the closure and refuse early,
|
|
2
|
+
// npm install --save-exact, verify, compile (and restore on refusal), the safe part of the module's
|
|
3
|
+
// setup, one scoped commit. The engine names no module and resolves no version itself: npm resolves
|
|
4
|
+
// ranges, and the closure is the presence graph modules already declare (`dreamteamer.dependencies`,
|
|
5
|
+
// the key compile enforces for cross-module references). A folder of tarballs (`--from <dir>`) stands
|
|
6
|
+
// in for the registry — the offline form candidates and acceptance use.
|
|
7
|
+
//
|
|
8
|
+
// The other `install` forms — make THIS checkout ready, `--clone`, `repos/<id>`, `--hook` — stay in
|
|
9
|
+
// src/checkout.js and src/init.js; this file is only the spec form.
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import zlib from 'node:zlib';
|
|
14
|
+
import { spawnSync, execFileSync } from 'node:child_process';
|
|
15
|
+
import { satisfies } from './semver.js';
|
|
16
|
+
import { engineVersion } from './runtime.js';
|
|
17
|
+
import { parseEnvValues } from './env-vars.js';
|
|
18
|
+
import { compile, discoverModules, staleness } from './compile.js';
|
|
19
|
+
import { resolveNpm, childEnv } from './checkout.js';
|
|
20
|
+
import { units, runUnit, fillInputs, parseInputFlags, parseAllow, skippedUnits, fold, SetupUsage, EXIT, ttyIO, droppedKeys } from './setup.js';
|
|
21
|
+
|
|
22
|
+
const EXACT = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
|
|
23
|
+
/** Numeric major.minor.patch order; a prerelease sorts below its release. */
|
|
24
|
+
export function compareVersions(a, b) {
|
|
25
|
+
const pa = String(a).split(/[-+]/)[0].split('.').map(Number), pb = String(b).split(/[-+]/)[0].split('.').map(Number);
|
|
26
|
+
for (let i = 0; i < 3; i++) if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) - (pb[i] ?? 0);
|
|
27
|
+
return (a.includes('-') ? 0 : 1) - (b.includes('-') ? 0 : 1);
|
|
28
|
+
}
|
|
29
|
+
export const NPM_FLOOR = '>=7.0.0';
|
|
30
|
+
|
|
31
|
+
export class InstallRefusal extends Error { constructor(m) { super(m); this.code = EXIT.failed; } }
|
|
32
|
+
const refuse = (m) => new InstallRefusal(m);
|
|
33
|
+
|
|
34
|
+
// ---- reading manifests ----------------------------------------------------------------------------
|
|
35
|
+
|
|
36
|
+
/** `package/package.json` out of an npm tarball: gunzip, then walk the ustar headers (512-byte
|
|
37
|
+
* blocks; the size is octal at offset 124; a `./` prefix is tolerated). No dependency, no shell. */
|
|
38
|
+
export function readTarballManifest(file) {
|
|
39
|
+
const buf = zlib.gunzipSync(fs.readFileSync(file));
|
|
40
|
+
let at = 0;
|
|
41
|
+
while (at + 512 <= buf.length) {
|
|
42
|
+
const name = buf.toString('utf8', at, at + 100).replace(/\0.*$/s, '');
|
|
43
|
+
if (!name) break;
|
|
44
|
+
const size = parseInt(buf.toString('utf8', at + 124, at + 136).replace(/\0.*$/s, '').trim() || '0', 8);
|
|
45
|
+
const type = buf[at + 156];
|
|
46
|
+
const prefix = buf.toString('utf8', at + 345, at + 500).replace(/\0.*$/s, '');
|
|
47
|
+
const full = (prefix ? `${prefix}/${name}` : name).replace(/^\.\//, '');
|
|
48
|
+
if ((type === 48 || type === 0) && full === 'package/package.json') return JSON.parse(buf.toString('utf8', at + 512, at + 512 + size));
|
|
49
|
+
at += 512 + Math.ceil(size / 512) * 512;
|
|
50
|
+
}
|
|
51
|
+
throw refuse(`${file}: no package/package.json inside the tarball`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Every tarball in a folder, indexed by package name, newest first (npm's own semver order via
|
|
55
|
+
* `satisfies`): file names are never parsed — `npm pack` writes `fix-a-1.0.0.tgz` for `@fix/a`. */
|
|
56
|
+
export function indexFolder(dir) {
|
|
57
|
+
const index = new Map();
|
|
58
|
+
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw refuse(`--from ${dir}: not a folder`);
|
|
59
|
+
for (const f of fs.readdirSync(dir).filter((n) => n.endsWith('.tgz')).sort()) {
|
|
60
|
+
const file = path.join(dir, f);
|
|
61
|
+
let m;
|
|
62
|
+
try { m = readTarballManifest(file); } catch { continue; }
|
|
63
|
+
if (!m?.name || !m.version) continue;
|
|
64
|
+
(index.get(m.name) ?? index.set(m.name, []).get(m.name)).push({ version: m.version, file, manifest: m });
|
|
65
|
+
}
|
|
66
|
+
for (const list of index.values()) list.sort((a, b) => compareVersions(b.version, a.version));
|
|
67
|
+
return index;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const splitSpec = (spec) => {
|
|
71
|
+
const at = spec.startsWith('@') ? spec.indexOf('@', 1) : spec.indexOf('@');
|
|
72
|
+
return at > 0 ? { name: spec.slice(0, at), version: spec.slice(at + 1) } : { name: spec, version: null };
|
|
73
|
+
};
|
|
74
|
+
const isPathSpec = (spec, cwd) => (spec.startsWith('.') || path.isAbsolute(spec) || spec.startsWith('file:')) && fs.existsSync(path.resolve(cwd, spec.replace(/^file:/, '')));
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* One spec → its manifest and the spec npm will be handed. Kinds: `tarball` (a .tgz path, or a name
|
|
78
|
+
* resolved from `--from`), `folder` (a development link), `registry` (a name, read with one
|
|
79
|
+
* `npm view` — the only network call; `github:` and git URLs go the same way).
|
|
80
|
+
*/
|
|
81
|
+
export function readSpecManifest(spec, { from = null, index = null, npm = resolveNpm(), cwd = process.cwd() } = {}) {
|
|
82
|
+
if (isPathSpec(spec, cwd)) {
|
|
83
|
+
const abs = path.resolve(cwd, spec.replace(/^file:/, ''));
|
|
84
|
+
if (fs.statSync(abs).isDirectory()) {
|
|
85
|
+
const file = path.join(abs, 'package.json');
|
|
86
|
+
if (!fs.existsSync(file)) throw refuse(`${spec}: a folder with no package.json`);
|
|
87
|
+
return { kind: 'folder', spec: abs, manifest: JSON.parse(fs.readFileSync(file, 'utf8')) };
|
|
88
|
+
}
|
|
89
|
+
return { kind: 'tarball', spec: abs, manifest: readTarballManifest(abs) };
|
|
90
|
+
}
|
|
91
|
+
const { name, version } = splitSpec(spec);
|
|
92
|
+
if (from) {
|
|
93
|
+
const idx = index ?? indexFolder(from);
|
|
94
|
+
const candidates = idx.get(name) ?? [];
|
|
95
|
+
const pick = version ? candidates.find((c) => c.version === version) : candidates[0];
|
|
96
|
+
if (!pick) throw refuse(`no ${version ? `${name}@${version}` : name} in ${from}${candidates.length ? ` (it has ${candidates.map((c) => c.version).join(', ')})` : ''}`);
|
|
97
|
+
return { kind: 'tarball', spec: pick.file, manifest: pick.manifest };
|
|
98
|
+
}
|
|
99
|
+
if (!npm) throw refuse('cannot read the registry — node found, npm not on PATH');
|
|
100
|
+
const r = spawnSync(npm, ['view', spec, 'name', 'version', 'dreamteamer', 'peerDependencies', 'dependencies', '--json'], { encoding: 'utf8', cwd, env: childEnv(), timeout: 120_000 });
|
|
101
|
+
if (r.status !== 0) throw refuse(`npm view ${spec} failed${r.stderr ? ` — ${r.stderr.trim().split('\n').filter((l) => /E404|ETARGET|ENOTFOUND|EAI_AGAIN/.test(l))[0] ?? r.stderr.trim().split('\n')[0]}` : ''}`);
|
|
102
|
+
let out;
|
|
103
|
+
try { out = JSON.parse(r.stdout); } catch { throw refuse(`npm view ${spec}: unreadable answer`); }
|
|
104
|
+
const manifest = Array.isArray(out) ? out.at(-1) : out; // a range answers with every match; the last is the newest
|
|
105
|
+
if (!manifest?.name) throw refuse(`npm view ${spec}: no such package`);
|
|
106
|
+
return { kind: 'registry', spec: `${manifest.name}@${manifest.version}`, manifest };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ---- the closure --------------------------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
/** The modules already here, by package name: version, whether it is a development link, its manifest. */
|
|
112
|
+
export function installedModules(ws) {
|
|
113
|
+
const out = new Map();
|
|
114
|
+
const { modules } = discoverModules(ws.root, ws.pkg);
|
|
115
|
+
for (const m of modules) {
|
|
116
|
+
let manifest = {};
|
|
117
|
+
try { manifest = JSON.parse(fs.readFileSync(path.join(m.root, 'package.json'), 'utf8')); } catch { /* a module with no manifest is not a package */ }
|
|
118
|
+
const name = manifest.name ?? m.name;
|
|
119
|
+
let linked = false;
|
|
120
|
+
try { linked = fs.lstatSync(path.join(ws.root, 'node_modules', name)).isSymbolicLink(); } catch { /* not under node_modules */ }
|
|
121
|
+
out.set(name, { name, version: manifest.version ?? null, linked, manifest, channel: m.channel });
|
|
122
|
+
}
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Resolve the specs and the closure of their `dreamteamer.dependencies`, and refuse — before npm
|
|
128
|
+
* writes anything — a package that is not a module, an engine floor this engine does not meet, a
|
|
129
|
+
* ring, a version already installed differently, and `provides` conflicts in both directions.
|
|
130
|
+
* Returns the ordered install list (dependencies first) and the names already satisfied.
|
|
131
|
+
*/
|
|
132
|
+
export function resolveClosure(specs, { installed, from = null, npm = resolveNpm(), cwd = process.cwd(), engine = engineVersion() } = {}) {
|
|
133
|
+
const index = from ? indexFolder(from) : null;
|
|
134
|
+
const list = [];
|
|
135
|
+
const already = [];
|
|
136
|
+
const seen = new Map(); // name → entry
|
|
137
|
+
// a package an INSTALLED one already provides: present for the walk (never resolved again), and refused
|
|
138
|
+
// the moment it is asked for by name — before any of its dependencies are looked up anywhere
|
|
139
|
+
const providedBy = (name) => [...installed].find(([, i]) => (i.manifest?.dreamteamer?.provides ?? []).includes(name))?.[0] ?? null;
|
|
140
|
+
const judge = (entry, askedAs, stack = []) => {
|
|
141
|
+
const m = entry.manifest;
|
|
142
|
+
if (!m.dreamteamer || typeof m.dreamteamer !== 'object') throw refuse(`${m.name}@${m.version} is not a dreamteamer module (no dreamteamer key in its package.json)${stack.length ? ` — needed by ${stack.at(-1)}` : ''}`);
|
|
143
|
+
const provider = providedBy(m.name);
|
|
144
|
+
if (provider) throw refuse(`${provider} already provides ${m.name} — it is installed; nothing to add`);
|
|
145
|
+
const range = m.dreamteamer.engine;
|
|
146
|
+
if (range && satisfies(engine, range) === false) throw refuse(`${m.name}@${m.version} needs engine "${range}" — this is ${engine}; choose a version: dt install ${m.name}@<version>`);
|
|
147
|
+
const here = installed.get(m.name);
|
|
148
|
+
if (here?.linked) throw refuse(`${m.name} is a development link (not pinned) — remove the link to pin a version`);
|
|
149
|
+
if (here && here.version && here.version !== m.version && askedAs === 'spec') throw refuse(`${m.name} is installed at ${here.version}, not ${m.version} — move it on purpose: dt update ${m.name}@${m.version}`);
|
|
150
|
+
};
|
|
151
|
+
const walk = (spec, stack, askedAs) => {
|
|
152
|
+
// asked for by name and already provided: refuse by name, without reading any manifest
|
|
153
|
+
if (askedAs === 'spec' && !isPathSpec(spec, cwd)) { const p = providedBy(splitSpec(spec).name); if (p) throw refuse(`${p} already provides ${splitSpec(spec).name} — it is installed; nothing to add`); }
|
|
154
|
+
const entry = readSpecManifest(spec, { from, index, npm, cwd });
|
|
155
|
+
const name = entry.manifest.name;
|
|
156
|
+
if (stack.includes(name)) throw refuse(`ring in dreamteamer.dependencies: ${[...stack.slice(stack.indexOf(name)), name].join(' → ')}`);
|
|
157
|
+
if (seen.has(name)) {
|
|
158
|
+
// the same module asked for twice at different versions is a conflict, never a silent first-wins
|
|
159
|
+
const prev = seen.get(name).manifest.version;
|
|
160
|
+
if (askedAs === 'spec' && prev !== entry.manifest.version) throw refuse(`${name} is asked for at ${prev} and at ${entry.manifest.version} — one version per call`);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
judge(entry, askedAs, stack);
|
|
164
|
+
const here = installed.get(name);
|
|
165
|
+
if (here && here.version === entry.manifest.version) { already.push(name); seen.set(name, entry); return; }
|
|
166
|
+
seen.set(name, entry);
|
|
167
|
+
for (const dep of entry.manifest.dreamteamer.dependencies ?? []) {
|
|
168
|
+
if ((installed.has(dep) || providedBy(dep)) && !stack.includes(dep)) continue; // present (or composed in): its own closure was judged when it came in
|
|
169
|
+
walk(dep, [...stack, name], 'dependency');
|
|
170
|
+
}
|
|
171
|
+
list.push(entry);
|
|
172
|
+
};
|
|
173
|
+
for (const s of specs) walk(s, [], 'spec');
|
|
174
|
+
// provides, both ways — against what is installed and within the call itself
|
|
175
|
+
const names = new Set(list.map((e) => e.manifest.name));
|
|
176
|
+
for (const e of list) {
|
|
177
|
+
const name = e.manifest.name;
|
|
178
|
+
for (const p of e.manifest.dreamteamer.provides ?? []) {
|
|
179
|
+
if (installed.has(p)) throw refuse(`${name} provides ${p}, which is installed — remove ${p} first (npm uninstall ${p}, then dt compile), or keep the small modules`);
|
|
180
|
+
if (names.has(p)) throw refuse(`${name} provides ${p} — install one or the other, not both in one call`);
|
|
181
|
+
}
|
|
182
|
+
for (const o of list) if (o !== e && (o.manifest.dreamteamer.provides ?? []).includes(name)) throw refuse(`${o.manifest.name} provides ${name} — install one or the other, not both in one call`);
|
|
183
|
+
}
|
|
184
|
+
return { list, already };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The npm on PATH is at least NPM_FLOOR, or the refusal naming both. */
|
|
188
|
+
export function npmFloor(npm = resolveNpm()) {
|
|
189
|
+
if (!npm) return 'cannot install — node found, npm not on PATH';
|
|
190
|
+
const r = spawnSync(npm, ['--version'], { encoding: 'utf8', env: childEnv(), timeout: 30_000 });
|
|
191
|
+
const v = (r.stdout ?? '').trim();
|
|
192
|
+
if (r.status !== 0 || !EXACT.test(v)) return `cannot read npm's version (${r.stderr?.trim() || v || 'no output'})`;
|
|
193
|
+
return satisfies(v, NPM_FLOOR) === false ? `dt install needs npm >=${NPM_FLOOR.slice(2).replace(/\.0\.0$/, '')} (this is ${v}) — npm install -g npm` : null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ---- the verb -----------------------------------------------------------------------------------
|
|
197
|
+
|
|
198
|
+
const gitOk = (root, args) => { try { execFileSync('git', args, { cwd: root, stdio: 'ignore' }); return true; } catch { return false; } };
|
|
199
|
+
const gitIgnored = (root, rel) => gitOk(root, ['check-ignore', '-q', '--', rel]);
|
|
200
|
+
/** `git status --porcelain` of one path: '' when clean (modified AND untracked both count as dirty). */
|
|
201
|
+
const gitStatus = (root, rel) => { try { return execFileSync('git', ['status', '--porcelain', '--', rel], { cwd: root, encoding: 'utf8' }).trim(); } catch { return ''; } };
|
|
202
|
+
|
|
203
|
+
// ---- steps 2–4 and 5–6, shared with `dt update` (install one pin later) ----------------------------
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Steps 2–4: npm on the resolved list (the two files it rewrites copied aside), verify every package
|
|
207
|
+
* resolves at the version asked for, compile (a refusal restores the pre-image and prunes). Returns
|
|
208
|
+
* `{ fresh }`, or `{ code }`.
|
|
209
|
+
*/
|
|
210
|
+
export async function npmAndCompile(ws, list, { npm = resolveNpm(), open, json = false, log = console.log, hooks = {}, what = 'install' } = {}) {
|
|
211
|
+
const names = list.map((e) => e.manifest.name);
|
|
212
|
+
const pkgFile = path.join(ws.root, 'package.json'), lockFile = path.join(ws.root, 'package-lock.json');
|
|
213
|
+
const versionOf = (n) => { try { return JSON.parse(fs.readFileSync(path.join(ws.root, 'node_modules', n, 'package.json'), 'utf8')).version ?? null; } catch { return null; } };
|
|
214
|
+
// the pre-image: the two files npm rewrites, and the version each named package had (an update replaces one)
|
|
215
|
+
const before = { pkg: fs.readFileSync(pkgFile, 'utf8'), lock: fs.existsSync(lockFile) ? fs.readFileSync(lockFile, 'utf8') : null, versions: Object.fromEntries(names.map((n) => [n, versionOf(n)])) };
|
|
216
|
+
const args = ['install', '--save-exact', '--no-audit', '--no-fund', ...list.map((e) => e.spec)];
|
|
217
|
+
log(`▶ npm ${args.join(' ')}`);
|
|
218
|
+
const r = spawnSync(npm, args, { cwd: ws.root, stdio: json ? ['ignore', 2, 2] : 'inherit', env: childEnv(), timeout: 600_000 });
|
|
219
|
+
if (r.status !== 0) { console.error(`✖ npm exited ${r.status ?? r.error?.message} — package.json and package-lock.json may have changed; run the same command again to resume`); return { code: EXIT.failed }; }
|
|
220
|
+
if (hooks.afterNpm) hooks.afterNpm();
|
|
221
|
+
// 3. verify every package in the list resolves, at the version asked for (a folder link at whatever it holds)
|
|
222
|
+
const still = list.filter((e) => { const v = versionOf(e.manifest.name); return v === null || (e.kind !== 'folder' && v !== e.manifest.version); }).map((e) => e.manifest.name);
|
|
223
|
+
if (still.length) { console.error(`✖ npm exited 0, but ${still.join(', ')} still do${still.length === 1 ? 'es' : ''} not resolve in node_modules at the version asked for`); return { code: EXIT.failed }; }
|
|
224
|
+
// 4. compile — a refusal restores the pre-image and prunes
|
|
225
|
+
try {
|
|
226
|
+
const fresh = await open(ws.root);
|
|
227
|
+
const stdout = console.log;
|
|
228
|
+
if (json) console.log = console.error;
|
|
229
|
+
try { compile(fresh); } finally { console.log = stdout; }
|
|
230
|
+
return { fresh };
|
|
231
|
+
} catch (e) {
|
|
232
|
+
fs.writeFileSync(pkgFile, before.pkg);
|
|
233
|
+
if (before.lock !== null) fs.writeFileSync(lockFile, before.lock); else fs.rmSync(lockFile, { force: true });
|
|
234
|
+
// the packages this call added go, then npm prunes to the restored lockfile; an emptied scope folder goes too
|
|
235
|
+
for (const n of names) {
|
|
236
|
+
fs.rmSync(path.join(ws.root, 'node_modules', n), { recursive: true, force: true });
|
|
237
|
+
const scope = path.dirname(path.join(ws.root, 'node_modules', n));
|
|
238
|
+
try { if (n.startsWith('@') && fs.readdirSync(scope).length === 0) fs.rmdirSync(scope); } catch { /* not empty, or gone */ }
|
|
239
|
+
}
|
|
240
|
+
const back = spawnSync(npm, ['install', '--no-audit', '--no-fund'], { cwd: ws.root, stdio: 'ignore', env: childEnv(), timeout: 600_000 });
|
|
241
|
+
// the restore is checked, never assumed: npm's exit, and every package that had a version before the call is at it again
|
|
242
|
+
const notBack = names.filter((n) => before.versions[n] && versionOf(n) !== before.versions[n]);
|
|
243
|
+
if (back.status !== 0 || notBack.length) {
|
|
244
|
+
console.error(`✖ ${what} refused: ${e.message.split('\n')[0]}\n restore FAILED (npm exited ${back.status ?? back.error?.message})${notBack.length ? `: ${notBack.map((n) => `${n} is not back at ${before.versions[n]}`).join(', ')}` : ''} — package.json and package-lock.json were put back; node_modules was NOT: run npm install to bring it back`);
|
|
245
|
+
return { code: EXIT.failed };
|
|
246
|
+
}
|
|
247
|
+
console.error(`✖ ${what} refused: ${e.message.split('\n')[0]}\n package.json, package-lock.json and node_modules are as before the call`);
|
|
248
|
+
return { code: EXIT.failed };
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Steps 5–6: the safe part of the named packages' units (inputs filled leniently — npm has written,
|
|
254
|
+
* so a mistyped --input is a named warning, never an abort), then one scoped commit: the two files
|
|
255
|
+
* npm rewrites, .env.example if compile touched it, and every path an applied action reported that
|
|
256
|
+
* git does not ignore. Returns `{ code, results, committed, ignored }`.
|
|
257
|
+
*/
|
|
258
|
+
export async function setupAndCommit(ws, fresh, names, { subject, inputFlags = [], allow = new Set(), tty = false, noInput = true, io = null, processEnv = process.env, noCommit = false } = {}) {
|
|
259
|
+
const skipped = new Set(skippedUnits(fresh));
|
|
260
|
+
const fresh_units = units(fresh).filter((u) => names.includes(u.module) && !skipped.has(u.id));
|
|
261
|
+
let code = EXIT.done;
|
|
262
|
+
const results = [];
|
|
263
|
+
let ignored = [];
|
|
264
|
+
if (fresh_units.length) {
|
|
265
|
+
const term = tty && !noInput && !io ? ttyIO() : null;
|
|
266
|
+
try {
|
|
267
|
+
const filled = await fillInputs(fresh_units, { flags: inputFlags, env: { ...dotenv(fresh), ...processEnv }, tty, noInput, prompt: io?.prompt ?? term?.prompt ?? null, lenient: true });
|
|
268
|
+
ignored = filled.ignored;
|
|
269
|
+
const written = new Map(); // one run never lets two units disagree on a key (he3)
|
|
270
|
+
for (const u of fresh_units) {
|
|
271
|
+
const res = await runUnit(fresh, u, { inputs: filled.inputs.get(u.id) ?? {}, allow, tty, ask: io?.ask ?? term?.ask ?? null, authorize: false, verify: false, processEnv, drop: droppedKeys(filled.problems, u.id), written });
|
|
272
|
+
const problems = filled.problems.filter((m) => m.unit === u.id);
|
|
273
|
+
const missing = [...filled.missing.filter((m) => m.unit === u.id).map((m) => m.id), ...problems.filter((m) => m.required).map((m) => m.id)];
|
|
274
|
+
const f = fold(res.failed.length ? [...res.checks, ...res.failed.map((x) => ({ id: x.id, status: 'blocked', title: x.id, detail: x.message }))] : res.checks, {});
|
|
275
|
+
results.push({ id: u.id, module: u.module, ...f, applied: res.applied, pending: res.pending, failed: res.failed, problems, needs: [...new Set([...missing, ...res.needs])] });
|
|
276
|
+
if (missing.length) code = Math.max(code, EXIT.needsInput);
|
|
277
|
+
else if (res.failed.length && code === EXIT.done) code = EXIT.failed; // D57: a failed apply is a failure; the install itself stands and is committed
|
|
278
|
+
}
|
|
279
|
+
} finally { term?.close(); }
|
|
280
|
+
}
|
|
281
|
+
let committed = null;
|
|
282
|
+
if (!noCommit && gitOk(ws.root, ['rev-parse', '--git-dir'])) {
|
|
283
|
+
const changed = results.flatMap((r) => r.applied.flatMap((a) => a.changed ?? [])).map((p) => path.relative(ws.root, path.resolve(ws.root, p))).filter((rel) => rel && !rel.startsWith('..') && !path.isAbsolute(rel) && fs.existsSync(path.join(ws.root, rel)) && !gitIgnored(ws.root, rel));
|
|
284
|
+
const paths = [...new Set(['package.json', 'package-lock.json', '.env.example', ...changed])].filter((rel) => fs.existsSync(path.join(ws.root, rel)));
|
|
285
|
+
if (gitOk(ws.root, ['add', '--', ...paths]) && gitOk(ws.root, ['commit', '--quiet', '-m', subject, '--', ...paths])) committed = paths;
|
|
286
|
+
}
|
|
287
|
+
return { code, results, committed, ignored };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** The unit lines a verb prints after setupAndCommit, one block per unit. */
|
|
291
|
+
export function printUnitResults(results, ignored, log) {
|
|
292
|
+
for (const text of ignored) log(`⚠ ${text} — ignored`);
|
|
293
|
+
for (const r of results) {
|
|
294
|
+
const verified = r.verified ? ` · verified ${r.verified}` : '';
|
|
295
|
+
log(`${r.state === 'ready' ? '✔' : r.state === 'blocked' ? '✖' : '—'} ${r.id}: ${r.state}${verified}${r.detail ? ` — ${r.detail}` : ''}`);
|
|
296
|
+
for (const a of r.applied) log(` ✔ ${a.id}${a.message ? ` — ${a.message}` : ''}`);
|
|
297
|
+
for (const f of r.failed) log(` ✖ ${f.id} — ${f.message}`);
|
|
298
|
+
for (const p of r.problems ?? []) log(` ✖ ${p.id} — ${p.reason}`);
|
|
299
|
+
for (const p of r.pending) log(` … ${p.id} (${p.why})${p.reason ? ` — ${p.reason}` : ''}`);
|
|
300
|
+
if (r.needs.length) log(` needs input: ${r.needs.join(', ')} — dt setup ${r.id} --input ${r.needs[0]}=<value>`);
|
|
301
|
+
if (ownerStepPending(r)) log(` the owner's step (opens a browser): dt setup ${r.id}${r.needs.map((n) => ` --input ${n}=<value>`).join('')} --authorize`);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
/** Whether a unit still has a step only the owner runs — a sign-in, a consent — pending. */
|
|
305
|
+
export const ownerStepPending = (r) => (r.pending ?? []).some((p) => p.runBy === 'owner' || (p.effects ?? []).some((e) => e.kind === 'account'));
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* `dt install <spec…> [--from <dir>] [--input k=v]… [--allow <kind>]… [--no-input] [--no-commit] [--json]`
|
|
309
|
+
* `hooks.afterNpm` is a test seam the CLI never sets (an interruption between npm and compile).
|
|
310
|
+
*/
|
|
311
|
+
export async function installModules(ws, argv, { open, npm = resolveNpm(), verify = null, hooks = {}, log: logOut = console.log, processEnv = process.env, tty = !!(process.stdin.isTTY && process.stdout.isTTY), io = null } = {}) {
|
|
312
|
+
if (typeof open !== 'function') throw new Error('installModules: opts.open (an extension-activating opener) is required');
|
|
313
|
+
const json = argv.includes('--json');
|
|
314
|
+
// with --json, stdout is the payload and nothing else: every line of chatter goes to stderr
|
|
315
|
+
const log = json ? console.error : logOut;
|
|
316
|
+
const noInput = json || argv.includes('--no-input');
|
|
317
|
+
const noCommit = argv.includes('--no-commit');
|
|
318
|
+
const fromAt = argv.indexOf('--from');
|
|
319
|
+
const from = fromAt > -1 ? path.resolve(ws.root, argv[fromAt + 1] ?? '') : null;
|
|
320
|
+
if (fromAt > -1 && !argv[fromAt + 1]) { console.error('✖ --from takes a folder of tarballs'); return EXIT.usage; }
|
|
321
|
+
const valueFlags = new Set(['--from', '--input', '--allow']);
|
|
322
|
+
const specs = argv.filter((a, i) => !a.startsWith('--') && !valueFlags.has(argv[i - 1]));
|
|
323
|
+
if (!specs.length) { console.error('✖ dt install takes one or more specs: a name, name@version, ./file.tgz, ./folder or a git URL'); return EXIT.usage; }
|
|
324
|
+
let allow, inputFlags;
|
|
325
|
+
try { allow = parseAllow(argv); inputFlags = parseInputFlags(argv); } catch (e) { if (e instanceof SetupUsage) { console.error(`✖ ${e.message}`); return EXIT.usage; } throw e; }
|
|
326
|
+
|
|
327
|
+
const floor = npmFloor(npm);
|
|
328
|
+
if (floor) { console.error(`✖ ${floor}`); return EXIT.failed; }
|
|
329
|
+
|
|
330
|
+
// 1. resolve and refuse early — nothing is written before step 2
|
|
331
|
+
const installed = installedModules(ws);
|
|
332
|
+
let plan;
|
|
333
|
+
try { plan = resolveClosure(specs, { installed, from, npm, cwd: ws.root }); } catch (e) { if (e instanceof InstallRefusal) { console.error(`✖ ${e.message}`); return EXIT.failed; } throw e; }
|
|
334
|
+
const setupOpts = { inputFlags, allow, tty, noInput, io, processEnv, noCommit };
|
|
335
|
+
if (!plan.list.length) {
|
|
336
|
+
// everything is here — but an earlier run cut off anywhere after npm (a kill, a Ctrl-D at a prompt,
|
|
337
|
+
// a refused input) may have left the runtime stale, npm's files uncommitted or the setup unrun;
|
|
338
|
+
// resuming means finishing those steps, never re-running npm. Clean, compiled and no inputs
|
|
339
|
+
// given is nothing to do; inputs given go to the installed units' setup.
|
|
340
|
+
const names = plan.already;
|
|
341
|
+
const s = staleness(ws.root);
|
|
342
|
+
const stale = !s.compiled || s.stale.length > 0;
|
|
343
|
+
const pending = ['package.json', 'package-lock.json', '.env.example'].filter((rel) => fs.existsSync(path.join(ws.root, rel)) && gitStatus(ws.root, rel) !== '');
|
|
344
|
+
if (!stale && !pending.length && !inputFlags.length) { log(`✔ already installed: ${names.join(', ')} — nothing to do`); return EXIT.done; }
|
|
345
|
+
let fresh;
|
|
346
|
+
try {
|
|
347
|
+
fresh = await open(ws.root);
|
|
348
|
+
if (stale) { const stdout = console.log; if (json) console.log = console.error; try { compile(fresh); } finally { console.log = stdout; } }
|
|
349
|
+
} catch (e) { console.error(`✖ compile: ${e.message.split('\n')[0]}`); return EXIT.failed; }
|
|
350
|
+
const out = await setupAndCommit(ws, fresh, names, { subject: `dreamteamer: install ${names.join(', ')}`, ...setupOpts });
|
|
351
|
+
const did = [stale ? 'the stale runtime was compiled' : null, out.committed ? `the pending changes were committed (${out.committed.join(', ')})` : null, out.results.length ? 'the setup ran' : null].filter(Boolean);
|
|
352
|
+
if (json) { logOut(JSON.stringify({ workspace: { root: ws.root }, installed: [], already: names, committed: out.committed, units: out.results }, null, 2)); return out.code; }
|
|
353
|
+
log(`✔ already installed: ${names.join(', ')} — ${did.join('; ') || 'nothing to do'}`);
|
|
354
|
+
printUnitResults(out.results, out.ignored, log);
|
|
355
|
+
return out.code;
|
|
356
|
+
}
|
|
357
|
+
const names = plan.list.map((e) => e.manifest.name);
|
|
358
|
+
log(`▶ install: ${plan.list.map((e) => `${e.manifest.name}@${e.manifest.version}${e.kind === 'folder' ? ' (linked)' : ''}`).join(', ')}${plan.already.length ? ` — already here: ${plan.already.join(', ')}` : ''}`);
|
|
359
|
+
|
|
360
|
+
// 2–4. npm, verify, compile (a refusal restores the pre-image)
|
|
361
|
+
const step = await npmAndCompile(ws, plan.list, { npm, open, json, log, hooks, what: 'install' });
|
|
362
|
+
if (step.code !== undefined) return step.code;
|
|
363
|
+
const fresh = step.fresh;
|
|
364
|
+
if (verify) {
|
|
365
|
+
const stdout = console.log;
|
|
366
|
+
if (json) console.log = console.error;
|
|
367
|
+
let bad;
|
|
368
|
+
try { bad = await verify(fresh); } finally { console.log = stdout; }
|
|
369
|
+
if (bad) log('⚠ check reported violations (above) — the install stands; fix the records, or the module\'s rules');
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// 5–6. the safe part of the new units' setup, one scoped commit
|
|
373
|
+
const out = await setupAndCommit(ws, fresh, names, { subject: `dreamteamer: install ${names.join(', ')}`, ...setupOpts });
|
|
374
|
+
if (json) { logOut(JSON.stringify({ workspace: { root: ws.root }, installed: names, already: plan.already, committed: out.committed, units: out.results }, null, 2)); return out.code; }
|
|
375
|
+
log(`✔ installed ${names.join(', ')} — compiled${out.committed ? `, committed (${out.committed.join(', ')})` : noCommit ? ', not committed (--no-commit)' : ', not committed (not a git repository)'}`);
|
|
376
|
+
printUnitResults(out.results, out.ignored, log);
|
|
377
|
+
return out.code;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const dotenv = (ws) => {
|
|
381
|
+
const file = path.join(ws.root, '.env');
|
|
382
|
+
return fs.existsSync(file) ? Object.fromEntries(parseEnvValues(fs.readFileSync(file, 'utf8'))) : {};
|
|
383
|
+
};
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// The text `dt add modules` writes beside a new module's package.json (cr-dt-007, G4): a README with the
|
|
2
|
+
// install line, and — under `--extension` — an extension entry whose one setup unit asks for one token and
|
|
3
|
+
// lets the engine write it into .env (the env action, D61). Pure: strings in, strings out.
|
|
4
|
+
|
|
5
|
+
/** `acme-crm` → `ACME_CRM_TOKEN`: the one env key the scaffolded unit declares. */
|
|
6
|
+
export const scaffoldKey = (id) => `${id.toUpperCase().replace(/-/g, '_')}_TOKEN`;
|
|
7
|
+
|
|
8
|
+
export function readmeText({ id, pkgName, description, extension }) {
|
|
9
|
+
const key = scaffoldKey(id);
|
|
10
|
+
return [
|
|
11
|
+
`# ${pkgName}`,
|
|
12
|
+
'',
|
|
13
|
+
description || 'A dreamteamer module.',
|
|
14
|
+
'',
|
|
15
|
+
'```bash',
|
|
16
|
+
`dt install ${pkgName}`,
|
|
17
|
+
...(extension ? [`dt setup ${id} --input token=<token> # writes ${key} into .env`] : []),
|
|
18
|
+
'```',
|
|
19
|
+
'',
|
|
20
|
+
'## Developing it',
|
|
21
|
+
'',
|
|
22
|
+
'```bash',
|
|
23
|
+
'dt compile && dt status # the inline module is live in this workspace',
|
|
24
|
+
'npm test # node --test on dreamteamer/testing',
|
|
25
|
+
`dt check modules/${id} --alone # exit 0: publishable`,
|
|
26
|
+
'```',
|
|
27
|
+
'',
|
|
28
|
+
'Writing a module: the `using-dreamteamer` skill, references/writing-a-module.md.',
|
|
29
|
+
'',
|
|
30
|
+
].join('\n');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function extensionText({ id }) {
|
|
34
|
+
const key = scaffoldKey(id);
|
|
35
|
+
return `// ${id} — the extension entry. \`activate(dt)\` receives the running engine's API; it returns what this
|
|
36
|
+
// module contributes. The one setup unit asks for a token and names the .env write; the engine performs
|
|
37
|
+
// it (confined, fingerprint-checked, never printed). Add commands, check, doctor or next as you need them.
|
|
38
|
+
const KEY = '${key}';
|
|
39
|
+
|
|
40
|
+
/** Read-only and synchronous: what is set up, from the environment the engine hands over. */
|
|
41
|
+
function inspect(ctx) {
|
|
42
|
+
return { checks: [{ id: '${id}.token', status: ctx.env[KEY] ? 'configured' : 'missing', title: KEY, fix: 'dt setup ${id} --input token=<token>' }] };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** What would run: one env action, ready once the token is known. */
|
|
46
|
+
function plan(ctx, inputs) {
|
|
47
|
+
const token = inputs.token ?? ctx.env[KEY];
|
|
48
|
+
return {
|
|
49
|
+
checks: inspect({ ...ctx, env: { ...ctx.env, ...(token ? { [KEY]: token } : {}) } }).checks,
|
|
50
|
+
actions: [{ id: 'set-token', title: \`write \${KEY} into .env\`, env: { [KEY]: token }, state: token ? 'ready' : 'needs-input' }],
|
|
51
|
+
needs: token ? [] : ['token'],
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const apiVersion = 1;
|
|
56
|
+
|
|
57
|
+
export default function activate(dt) {
|
|
58
|
+
return {
|
|
59
|
+
setup: [{
|
|
60
|
+
id: '${id}', version: 1,
|
|
61
|
+
inputs: [{ id: 'token', kind: 'string', env: KEY, required: true, title: '${id} token', prompt: 'The token for ${id}' }],
|
|
62
|
+
inspect, plan,
|
|
63
|
+
}],
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The one test a new module starts with: installed the way a stranger installs it, on the engine that
|
|
70
|
+
* runs the test, and checked. `npm test` runs it (`node --test`). */
|
|
71
|
+
export function testText({ id }) {
|
|
72
|
+
return `// ${id} — installed into a fresh workspace on the engine running this test, the way a stranger installs it.
|
|
73
|
+
import { test } from 'node:test';
|
|
74
|
+
import assert from 'node:assert/strict';
|
|
75
|
+
import { fileURLToPath } from 'node:url';
|
|
76
|
+
import { createWorkspace, install, run } from 'dreamteamer/testing';
|
|
77
|
+
|
|
78
|
+
test('${id} installs into a fresh workspace and checks clean', () => {
|
|
79
|
+
const ws = createWorkspace();
|
|
80
|
+
const r = install(ws, fileURLToPath(new URL('..', import.meta.url))); // packed with npm pack, then dt install
|
|
81
|
+
assert.ok([0, 3].includes(r.status), r.stdout + r.stderr); // 3: an input is still to be given
|
|
82
|
+
assert.equal(run(ws, ['check']).status, 0);
|
|
83
|
+
});
|
|
84
|
+
`;
|
|
85
|
+
}
|
package/src/schema-ops.js
CHANGED
|
@@ -22,6 +22,7 @@ import { FIELD_OPTIONS, TEMPLATE_OPTIONS, viewOverlayOf } from './views.js';
|
|
|
22
22
|
const GIT_QUIET = ['ignore', 'pipe', 'ignore'];
|
|
23
23
|
import { walk, idFromRecordPath, parseRecord, EXT } from './records.js';
|
|
24
24
|
import { Store, serialize, atomicWrite } from './store.js';
|
|
25
|
+
import { readmeText, extensionText, testText, scaffoldKey } from './scaffold-templates.js';
|
|
25
26
|
|
|
26
27
|
// ---- the gate -------------------------------------------------------------------
|
|
27
28
|
|
|
@@ -297,8 +298,18 @@ function editWorkspacePkg(ws, mutate) {
|
|
|
297
298
|
return file;
|
|
298
299
|
}
|
|
299
300
|
|
|
300
|
-
|
|
301
|
+
const NPM_NAME = /^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
|
|
302
|
+
const ENGINE_VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
303
|
+
|
|
304
|
+
export function createModule(ws, store, { name, description, namespace, extension = false, pkg: pkgName = null }) {
|
|
301
305
|
if (!name || name === true) throw new Error('missing module name — dreamteamer add modules --name <id>');
|
|
306
|
+
if (pkgName === true) throw new Error('--package takes the npm name: dreamteamer add modules --name <id> --package @scope/<id>');
|
|
307
|
+
if (pkgName && (pkgName.length > 214 || !NPM_NAME.test(pkgName))) throw new Error(`"${pkgName}" is not an npm package name — lowercase, URL-safe, optionally @scope/name`);
|
|
308
|
+
if (extension && !/^[a-z]/.test(name)) throw new Error(`--extension needs a module id that starts with a letter — "${name}" becomes the setup unit's id and its env key (${scaffoldKey(name)}), and both must start with one`);
|
|
309
|
+
if (pkgName) {
|
|
310
|
+
const holder = discoverModules(ws.root, ws.pkg).modules.find((m) => { try { return JSON.parse(fs.readFileSync(path.join(m.root, 'package.json'), 'utf8')).name === pkgName; } catch { return false; } });
|
|
311
|
+
if (holder) throw new Error(`${pkgName} is already the package name of ${path.relative(ws.root, holder.root) || holder.root} — two modules under one name would shadow each other; pick another --package`);
|
|
312
|
+
}
|
|
302
313
|
if (!MODULE_ID.test(name)) {
|
|
303
314
|
throw new Error(`invalid module id "${name}" — lowercase alphanumeric with single hyphens. It becomes a folder name, a package name and a record id at once, so there is only one spelling.`);
|
|
304
315
|
}
|
|
@@ -329,12 +340,23 @@ export function createModule(ws, store, { name, description, namespace }) {
|
|
|
329
340
|
}
|
|
330
341
|
// `files` is the npm publish surface: every kind a module CAN ship, so a kind added to the engine
|
|
331
342
|
// does not silently stop being packaged.
|
|
332
|
-
|
|
343
|
+
// `engine` is the floor the module is written against: the engine that scaffolded it (cr-dt-007)
|
|
344
|
+
dt.engine = `>=${ENGINE_VERSION}`;
|
|
345
|
+
if (extension) { dt.extension = './src/extension.js'; dt.env = [scaffoldKey(name)]; }
|
|
346
|
+
const files = [...KINDS, ...(extension ? ['src'] : []), 'README.md'];
|
|
347
|
+
// `--package` makes it publishable: its npm name (the module id stays the folder), a first version,
|
|
348
|
+
// and the engine as a devDependency for its own tests — never `dependencies`, which would nest a second engine (D66)
|
|
349
|
+
const mpkg = pkgName
|
|
350
|
+
? { name: pkgName, version: '0.1.0', type: 'module', files, scripts: { test: 'node --test' }, devDependencies: { dreamteamer: ENGINE_VERSION }, dreamteamer: dt }
|
|
351
|
+
: { name, private: true, version: '0.0.1', type: 'module', files, scripts: { test: 'node --test' }, dreamteamer: dt };
|
|
333
352
|
const pkgFile = path.join(root, 'package.json');
|
|
353
|
+
const written = { 'README.md': readmeText({ id: name, pkgName: mpkg.name, description, extension }), 'test/module.test.mjs': testText({ id: name }), ...(extension ? { 'src/extension.js': extensionText({ id: name }) } : {}) };
|
|
334
354
|
|
|
335
355
|
const out = gatedTreeOp(ws, store, {
|
|
336
356
|
subject: `dreamteamer: modules add ${name}`,
|
|
337
|
-
|
|
357
|
+
// compile regenerates .env.example from the declared keys, so a module that declares one (--extension)
|
|
358
|
+
// changes it — it rides in the same commit rather than being left modified outside it
|
|
359
|
+
paths: [path.relative(ws.root, pkgFile), ...Object.keys(written).map((f) => path.relative(ws.root, path.join(root, f))), ...(extension && fs.existsSync(path.join(ws.root, '.env.example')) ? ['.env.example'] : [])],
|
|
338
360
|
mutate: () => {
|
|
339
361
|
// ⚠ SCAFFOLD EVERY KIND FOLDER. Not decoration: it is what makes the module's shape
|
|
340
362
|
// self-documenting the moment it exists, and compile's "contributed no recognised sources"
|
|
@@ -343,10 +365,11 @@ export function createModule(ws, store, { name, description, namespace }) {
|
|
|
343
365
|
// git cannot track an empty directory, so only package.json is in the pathspec.
|
|
344
366
|
for (const kind of KINDS) fs.mkdirSync(path.join(root, kind), { recursive: true });
|
|
345
367
|
fs.writeFileSync(pkgFile, JSON.stringify(mpkg, null, '\t') + '\n');
|
|
368
|
+
for (const [f, text] of Object.entries(written)) { fs.mkdirSync(path.dirname(path.join(root, f)), { recursive: true }); fs.writeFileSync(path.join(root, f), text); }
|
|
346
369
|
},
|
|
347
370
|
undo: () => fs.rmSync(root, { recursive: true, force: true }),
|
|
348
371
|
});
|
|
349
|
-
return { id: name, root: path.relative(ws.root, root), file: pkgFile, namespace: ns || null, commits: out.commits };
|
|
372
|
+
return { id: name, root: path.relative(ws.root, root), file: pkgFile, files: ['package.json', ...Object.keys(written)], namespace: ns || null, commits: out.commits };
|
|
350
373
|
}
|
|
351
374
|
|
|
352
375
|
/** The settable fields of a `modules` record, and how each translates from the record-shaped value
|