@stagepass/cli 2.1.0 → 2.2.1

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.
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Declared Stagepass modules for a project (`stagepass.json` → `modules`).
3
+ *
4
+ * Modules are separate script tags in Webflow Custom Code, so the npm
5
+ * dependency alone does not prove which ones run on the site. The declared
6
+ * list is the source of truth for AI guidance and TypeScript types.
7
+ */
8
+
9
+ /** Individual module ids (each has `modules/dist/<id>.min.js`). */
10
+ export const MODULE_IDS = Object.freeze(['inject', 'cookies', 'maintenance']);
11
+
12
+ /** Accepted values in the declared list (`all` = every module). */
13
+ export const MODULE_CHOICES = Object.freeze([...MODULE_IDS, 'all']);
14
+
15
+ /**
16
+ * Normalize a declared modules value.
17
+ * Accepts an array, a comma/space separated string, `none`, or `all`.
18
+ * Returns a sorted, deduped list; `all` is exclusive (`['all']`).
19
+ *
20
+ * @param {unknown} value
21
+ * @returns {{ ok: true, modules: string[] } | { ok: false, error: string }}
22
+ */
23
+ export function normalizeModulesList(value) {
24
+ /** @type {unknown[]} */
25
+ let items;
26
+ if (Array.isArray(value)) {
27
+ items = value;
28
+ } else if (typeof value === 'string') {
29
+ const trimmed = value.trim().toLowerCase();
30
+ if (trimmed === '' || trimmed === 'none' || trimmed === '[]') {
31
+ return { ok: true, modules: [] };
32
+ }
33
+ items = trimmed.split(/[\s,]+/).filter(Boolean);
34
+ } else {
35
+ return {
36
+ ok: false,
37
+ error: 'modules must be a list such as ["cookies"], ["all"] or [].',
38
+ };
39
+ }
40
+
41
+ const out = new Set();
42
+ for (const raw of items) {
43
+ const id = String(raw).trim().toLowerCase();
44
+ if (!MODULE_CHOICES.includes(id)) {
45
+ return {
46
+ ok: false,
47
+ error: `Unknown module "${String(raw)}". Use ${MODULE_CHOICES.join(', ')} or none.`,
48
+ };
49
+ }
50
+ out.add(id);
51
+ }
52
+ if (out.has('all')) return { ok: true, modules: ['all'] };
53
+ return { ok: true, modules: MODULE_IDS.filter((id) => out.has(id)) };
54
+ }
55
+
56
+ /**
57
+ * Expand `all` into the individual module ids.
58
+ * @param {string[]} modules normalized list
59
+ * @returns {string[]}
60
+ */
61
+ export function expandModules(modules) {
62
+ if (modules.includes('all')) return [...MODULE_IDS];
63
+ return MODULE_IDS.filter((id) => modules.includes(id));
64
+ }
65
+
66
+ /** Whether a module type entry belongs to Stagepass modules. */
67
+ export function isStagepassModulesTypeEntry(entry) {
68
+ return entry === '@stagepass/modules' || String(entry).startsWith('@stagepass/modules/');
69
+ }
70
+
71
+ /**
72
+ * `compilerOptions.types` entries for a declared list.
73
+ * @param {string[]} modules normalized list
74
+ * Single modules use `@stagepass/modules/<id>` (modules >= 2.2.0). When the
75
+ * installed or resolvable @stagepass/modules has no per-module types
76
+ * (`perModuleTypes: false`, e.g. only 2.0.0 published), the umbrella
77
+ * `@stagepass/modules` is used so the project still type-checks.
78
+ *
79
+ * @param {string[]} modules normalized list
80
+ * @param {{ modulesDependency?: boolean, perModuleTypes?: boolean }} [opts] module types need the npm dep
81
+ * @returns {string[]}
82
+ */
83
+ export function typesForModules(modules, opts = {}) {
84
+ const types = ['@stagepass/loader'];
85
+ if (opts.modulesDependency === false) return types;
86
+ if (modules.length > 0 && opts.perModuleTypes === false) {
87
+ types.push('@stagepass/modules');
88
+ return types;
89
+ }
90
+ if (modules.includes('all')) {
91
+ types.push('@stagepass/modules');
92
+ } else {
93
+ for (const id of expandModules(modules)) types.push(`@stagepass/modules/${id}`);
94
+ }
95
+ return types;
96
+ }
97
+
98
+ /** Human-readable list (`none` when empty). */
99
+ export function formatModules(modules) {
100
+ return modules.length === 0 ? 'none' : modules.join(', ');
101
+ }
102
+
103
+ /** Same list (order-insensitive). */
104
+ export function sameModules(a, b) {
105
+ const x = [...a].sort().join(',');
106
+ const y = [...b].sort().join(',');
107
+ return x === y;
108
+ }
@@ -0,0 +1,407 @@
1
+ /**
2
+ * Sync generated project files with the declared Stagepass modules
3
+ * (used by `stagepass upgrade` and `stagepass doctor`).
4
+ *
5
+ * Writes only:
6
+ * - stagepass.json `modules` (and `origin` when passed via --site)
7
+ * - AGENTS.md managed block (created when missing)
8
+ * - .cursor/rules/stagepass.mdc (created when missing, managed block refreshed)
9
+ * - tsconfig.json / jsconfig.json `compilerOptions.types` (plain JSON only)
10
+ */
11
+
12
+ import path from 'node:path';
13
+ import fs from 'fs-extra';
14
+ import {
15
+ BLOCK_BEGIN,
16
+ CURSOR_RULE_PATH,
17
+ buildCursorRule,
18
+ buildManagedBlock,
19
+ upsertManagedBlock,
20
+ } from './ai-guide.js';
21
+ import {
22
+ formatModules,
23
+ isStagepassModulesTypeEntry,
24
+ normalizeModulesList,
25
+ typesForModules,
26
+ } from './project-modules.js';
27
+ import { loadProjects } from './projects.js';
28
+ import { describeDetection, normalizeSiteUrl } from './site-detect.js';
29
+
30
+ /**
31
+ * Read and parse stagepass.json (null when missing or invalid).
32
+ * @param {string} cwd
33
+ * @param {typeof fs} [fse]
34
+ * @returns {Promise<{ exists: boolean, data: Record<string, unknown> | null, raw: string, error?: string }>}
35
+ */
36
+ export async function readStagepassJson(cwd, fse = fs) {
37
+ const file = path.join(cwd, 'stagepass.json');
38
+ if (!(await fse.pathExists(file))) return { exists: false, data: null, raw: '' };
39
+ const raw = await fse.readFile(file, 'utf8');
40
+ try {
41
+ const data = JSON.parse(raw);
42
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
43
+ return { exists: true, data: null, raw, error: 'stagepass.json is not a JSON object.' };
44
+ }
45
+ return { exists: true, data, raw };
46
+ } catch {
47
+ return { exists: true, data: null, raw, error: 'stagepass.json is not valid JSON.' };
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Declared modules from stagepass.json (`null` when missing or legacy boolean).
53
+ * @param {Record<string, unknown> | null} data
54
+ * @returns {string[] | null}
55
+ */
56
+ export function declaredModules(data) {
57
+ if (!data || !Array.isArray(data.modules)) return null;
58
+ const result = normalizeModulesList(data.modules);
59
+ return result.ok ? result.modules : null;
60
+ }
61
+
62
+ /**
63
+ * Live origin for a project: stagepass.json `origin`, else the first concrete
64
+ * (non-wildcard) origin stored by `stagepass link` for this project folder.
65
+ *
66
+ * @param {string} cwd
67
+ * @param {Record<string, unknown> | null} data
68
+ * @param {{ loadProjects?: typeof loadProjects, realpath?: (p: string) => Promise<string> }} [deps]
69
+ * @returns {Promise<{ origin: string, source: 'stagepass.json' | 'stagepass link' } | null>}
70
+ */
71
+ export async function resolveProjectOrigin(cwd, data, deps = {}) {
72
+ if (data && typeof data.origin === 'string' && data.origin.trim() !== '') {
73
+ const check = normalizeSiteUrl(data.origin);
74
+ if (check.ok) return { origin: check.host, source: 'stagepass.json' };
75
+ }
76
+ const load = deps.loadProjects || loadProjects;
77
+ const realpath = deps.realpath || ((p) => fs.realpath(p));
78
+ let doc;
79
+ try {
80
+ doc = await load();
81
+ } catch {
82
+ return null;
83
+ }
84
+ let here = path.resolve(cwd);
85
+ try {
86
+ here = await realpath(here);
87
+ } catch {
88
+ // keep resolved path
89
+ }
90
+ for (const entry of Object.values(doc.projects || {})) {
91
+ if (!entry || typeof entry !== 'object' || typeof entry.root !== 'string') continue;
92
+ let root = path.resolve(entry.root);
93
+ try {
94
+ root = await realpath(root);
95
+ } catch {
96
+ // keep
97
+ }
98
+ if (root !== here) continue;
99
+ for (const origin of Array.isArray(entry.origins) ? entry.origins : []) {
100
+ const check = normalizeSiteUrl(String(origin));
101
+ if (check.ok) return { origin: check.host, source: 'stagepass link' };
102
+ }
103
+ }
104
+ return null;
105
+ }
106
+
107
+ /**
108
+ * Decide the declared modules list for `upgrade`.
109
+ * Order: --site-modules flag, live site detection, existing stagepass.json,
110
+ * interactive prompt. The npm dependency is only mentioned as a hint.
111
+ *
112
+ * @param {object} input
113
+ * @param {string} input.cwd
114
+ * @param {Record<string, unknown> | null} input.data stagepass.json
115
+ * @param {object} input.pkg package.json
116
+ * @param {object} input.options { siteModules?, site?, skipSite?, yes? }
117
+ * @param {object} deps
118
+ * @param {(site: string) => Promise<any>} deps.detectSite
119
+ * @param {(question: string, def: string) => Promise<string>} [deps.ask]
120
+ * @param {(question: string, defYes: boolean) => Promise<boolean>} [deps.confirm]
121
+ * @param {boolean} deps.interactive
122
+ * @param {(msg: string) => void} deps.log
123
+ * @param {typeof loadProjects} [deps.loadProjects]
124
+ * @returns {Promise<{ ok: true, modules: string[], source: string, origin: string | null, detection: any } | { ok: false, error: string }>}
125
+ */
126
+ export async function resolveUpgradeModules(input, deps) {
127
+ const { cwd, data, pkg, options } = input;
128
+ const log = deps.log;
129
+ const existing = declaredModules(data);
130
+
131
+ if (options.siteModules != null) {
132
+ const parsed = normalizeModulesList(options.siteModules);
133
+ if (!parsed.ok) return { ok: false, error: parsed.error };
134
+ let flagOrigin = null;
135
+ if (options.site) {
136
+ const check = normalizeSiteUrl(options.site);
137
+ if (!check.ok) return { ok: false, error: check.error };
138
+ flagOrigin = check.host;
139
+ }
140
+ return { ok: true, modules: parsed.modules, source: '--site-modules', origin: flagOrigin, detection: null };
141
+ }
142
+
143
+ /** @type {string | null} */
144
+ let origin = null;
145
+ if (options.site) {
146
+ const check = normalizeSiteUrl(options.site);
147
+ if (!check.ok) return { ok: false, error: check.error };
148
+ origin = check.host;
149
+ } else {
150
+ const found = await resolveProjectOrigin(cwd, data, { loadProjects: deps.loadProjects });
151
+ origin = found ? found.origin : null;
152
+ }
153
+
154
+ let detection = null;
155
+ /** @type {string[] | null} */
156
+ let candidate = null;
157
+ let source = '';
158
+
159
+ if (origin && options.skipSite !== true) {
160
+ log(`Checking live site https://${origin}/ for Stagepass script tags...`);
161
+ detection = await deps.detectSite(origin);
162
+ log(` ${describeDetection(detection)}`);
163
+ if (detection.ok && detection.loader) {
164
+ candidate = detection.list;
165
+ source = `live site ${origin}`;
166
+ } else if (detection.ok) {
167
+ log(' The page does not load @stagepass/loader, so modules cannot be detected.');
168
+ }
169
+ } else if (!origin) {
170
+ log('No live site known (add "origin" to stagepass.json, pass --site, or link with --origin).');
171
+ }
172
+
173
+ const hasModulesDep = Boolean(
174
+ pkg?.dependencies?.['@stagepass/modules'] || pkg?.devDependencies?.['@stagepass/modules']
175
+ );
176
+
177
+ if (!candidate && existing) {
178
+ candidate = existing;
179
+ source = 'stagepass.json';
180
+ }
181
+
182
+ // Legacy `"modules": true` (CLI 2.0/2.1) meant "modules included", typed via
183
+ // `@stagepass/modules` (all modules). Keep that as `["all"]` so an upgrade
184
+ // without a live site result never removes types the project relied on.
185
+ if (!candidate && data?.modules === true) {
186
+ candidate = ['all'];
187
+ source = 'legacy "modules": true in stagepass.json';
188
+ }
189
+
190
+ if (!deps.interactive) {
191
+ if (candidate) {
192
+ log(`Modules: ${formatModules(candidate)} (inferred from ${source}). Check it, or pass --site-modules.`);
193
+ if (candidate.includes('all') && source.startsWith('legacy')) {
194
+ log('Hint: narrow it to the module tags your site loads, e.g. stagepass upgrade --site-modules cookies.');
195
+ }
196
+ return { ok: true, modules: candidate, source, origin, detection };
197
+ }
198
+ if (hasModulesDep) {
199
+ log('Hint: package.json has @stagepass/modules, but that does not show which module tags run on the site.');
200
+ }
201
+ log('Modules: none (no live site result and no list in stagepass.json). Pass --site-modules or run upgrade in a terminal.');
202
+ return { ok: true, modules: [], source: 'default', origin, detection };
203
+ }
204
+
205
+ if (candidate && source.startsWith('live site')) {
206
+ const yes = await deps.confirm(
207
+ `Use modules detected on the live site: ${formatModules(candidate)}?`,
208
+ true
209
+ );
210
+ if (yes) return { ok: true, modules: candidate, source, origin, detection };
211
+ }
212
+
213
+ if (hasModulesDep && !candidate) {
214
+ log('Hint: package.json has @stagepass/modules; enter the modules whose script tags are on the site.');
215
+ }
216
+ for (let attempt = 0; attempt < 3; attempt++) {
217
+ const answer = await deps.ask(
218
+ 'Modules your Webflow site loads (none | all | inject,cookies,maintenance)',
219
+ candidate ? formatModules(candidate) : 'none'
220
+ );
221
+ const parsed = normalizeModulesList(answer);
222
+ if (parsed.ok) {
223
+ return { ok: true, modules: parsed.modules, source: 'confirmed', origin, detection };
224
+ }
225
+ log(parsed.error);
226
+ }
227
+ return { ok: false, error: 'No valid modules list entered.' };
228
+ }
229
+
230
+ /**
231
+ * Update `compilerOptions.types` in a tsconfig/jsconfig source.
232
+ *
233
+ * @param {string} raw file contents
234
+ * @param {string[]} modules
235
+ * @param {{ modulesDependency: boolean, perModuleTypes?: boolean }} opts
236
+ * @returns {{ status: 'updated' | 'unchanged' | 'skipped', content?: string, reason?: string, types?: string[] }}
237
+ */
238
+ export function updateConfigTypes(raw, modules, opts) {
239
+ let json;
240
+ try {
241
+ json = JSON.parse(raw);
242
+ } catch {
243
+ const hasComments = /(^|[^:"'])\/\/|\/\*/.test(raw);
244
+ return {
245
+ status: 'skipped',
246
+ reason: hasComments
247
+ ? 'contains comments (JSONC); edit compilerOptions.types by hand'
248
+ : 'is not valid JSON; edit compilerOptions.types by hand',
249
+ };
250
+ }
251
+ if (!json || typeof json !== 'object' || Array.isArray(json)) {
252
+ return { status: 'skipped', reason: 'is not a JSON object' };
253
+ }
254
+ const co = json.compilerOptions;
255
+ if (!co || typeof co !== 'object' || !Array.isArray(co.types)) {
256
+ return {
257
+ status: 'skipped',
258
+ reason:
259
+ 'has no compilerOptions.types array (adding one would hide other @types); add the entries by hand',
260
+ };
261
+ }
262
+ const wanted = typesForModules(modules, opts);
263
+ const kept = co.types.filter(
264
+ (t) => typeof t !== 'string' || (t !== '@stagepass/loader' && !isStagepassModulesTypeEntry(t))
265
+ );
266
+ const nextTypes = [...wanted, ...kept];
267
+ const same =
268
+ nextTypes.length === co.types.length && nextTypes.every((t, i) => t === co.types[i]);
269
+ if (same) return { status: 'unchanged', types: nextTypes };
270
+ json.compilerOptions = { ...co, types: nextTypes };
271
+ const trailing = raw.endsWith('\n') ? '\n' : '';
272
+ return { status: 'updated', content: `${JSON.stringify(json, null, 2)}${trailing}`, types: nextTypes };
273
+ }
274
+
275
+ /**
276
+ * Plan file changes for the declared modules (pure, no writes).
277
+ *
278
+ * @param {object} input
279
+ * @param {string} input.cwd
280
+ * @param {string[]} input.modules
281
+ * @param {string | null} [input.origin] stored in stagepass.json when set
282
+ * @param {object} input.pkg package.json
283
+ * @param {boolean} [input.perModuleTypes] false when @stagepass/modules has no per-module types (umbrella entry)
284
+ * @param {typeof fs} [fse]
285
+ * @returns {Promise<{ writes: { file: string, content: string, action: string }[], notes: string[] }>}
286
+ */
287
+ export async function planProjectSync(input, fse = fs) {
288
+ const { cwd, modules, pkg } = input;
289
+ /** @type {{ file: string, content: string, action: string }[]} */
290
+ const writes = [];
291
+ /** @type {string[]} */
292
+ const notes = [];
293
+ const modulesDependency = Boolean(
294
+ pkg?.dependencies?.['@stagepass/modules'] || pkg?.devDependencies?.['@stagepass/modules']
295
+ );
296
+ const perModuleTypes = input.perModuleTypes;
297
+
298
+ // stagepass.json
299
+ const sp = await readStagepassJson(cwd, fse);
300
+ if (sp.exists && !sp.data) {
301
+ notes.push(`stagepass.json skipped: ${sp.error}`);
302
+ } else {
303
+ /** @type {Record<string, unknown>} */
304
+ let data;
305
+ if (sp.data) {
306
+ data = { ...sp.data, modules };
307
+ } else {
308
+ data = typeof pkg?.name === 'string' ? { name: pkg.name, modules } : { modules };
309
+ }
310
+ const before = JSON.stringify(sp.data || {});
311
+ if (input.origin) data.origin = input.origin;
312
+ if (!sp.exists) data.version = 1;
313
+ if (JSON.stringify(data) !== before || !sp.exists) {
314
+ const content = `${JSON.stringify(data, null, 2)}\n`;
315
+ writes.push({
316
+ file: 'stagepass.json',
317
+ content,
318
+ action: sp.exists ? `modules: ${formatModules(modules)}` : 'created',
319
+ });
320
+ }
321
+ }
322
+
323
+ // AGENTS.md
324
+ const block = buildManagedBlock(modules);
325
+ const agentsPath = path.join(cwd, 'AGENTS.md');
326
+ if (await fse.pathExists(agentsPath)) {
327
+ const raw = await fse.readFile(agentsPath, 'utf8');
328
+ const result = upsertManagedBlock(raw, block);
329
+ if (result.action === 'invalid') {
330
+ notes.push('AGENTS.md skipped: stagepass markers are incomplete; fix or remove them and rerun.');
331
+ } else if (result.action !== 'unchanged') {
332
+ writes.push({
333
+ file: 'AGENTS.md',
334
+ content: result.content,
335
+ action: result.action === 'inserted' ? 'managed block added' : 'managed block refreshed',
336
+ });
337
+ }
338
+ } else {
339
+ const title = typeof pkg?.name === 'string' ? pkg.name : path.basename(cwd);
340
+ writes.push({
341
+ file: 'AGENTS.md',
342
+ content: `# ${title} (Stagepass project)\n\n${block}\n`,
343
+ action: 'created',
344
+ });
345
+ }
346
+
347
+ // Cursor rule
348
+ const rulePath = path.join(cwd, CURSOR_RULE_PATH);
349
+ if (await fse.pathExists(rulePath)) {
350
+ const raw = await fse.readFile(rulePath, 'utf8');
351
+ if (raw.includes(BLOCK_BEGIN)) {
352
+ const result = upsertManagedBlock(raw, block);
353
+ if (result.action === 'invalid') {
354
+ notes.push(`${CURSOR_RULE_PATH} skipped: stagepass markers are incomplete.`);
355
+ } else if (result.action !== 'unchanged') {
356
+ writes.push({ file: CURSOR_RULE_PATH, content: result.content, action: 'managed block refreshed' });
357
+ }
358
+ } else {
359
+ notes.push(`${CURSOR_RULE_PATH} exists without stagepass markers; left unchanged.`);
360
+ }
361
+ } else {
362
+ writes.push({ file: CURSOR_RULE_PATH, content: buildCursorRule(modules), action: 'created' });
363
+ }
364
+
365
+ // tsconfig / jsconfig
366
+ let sawConfig = false;
367
+ for (const name of ['tsconfig.json', 'jsconfig.json']) {
368
+ const file = path.join(cwd, name);
369
+ if (!(await fse.pathExists(file))) continue;
370
+ sawConfig = true;
371
+ const raw = await fse.readFile(file, 'utf8');
372
+ const result = updateConfigTypes(raw, modules, { modulesDependency, perModuleTypes });
373
+ if (result.status === 'skipped') {
374
+ const wanted = JSON.stringify(typesForModules(modules, { modulesDependency, perModuleTypes }));
375
+ notes.push(`${name} ${result.reason}: "types": ${wanted}`);
376
+ } else if (result.status === 'updated') {
377
+ writes.push({ file: name, content: result.content, action: `types: ${result.types.join(', ')}` });
378
+ }
379
+ }
380
+ if (!sawConfig) {
381
+ notes.push('No tsconfig.json or jsconfig.json found; types not configured.');
382
+ }
383
+ if (!modulesDependency && modules.length > 0) {
384
+ notes.push('Module types need @stagepass/modules in devDependencies (npm install -D @stagepass/modules).');
385
+ }
386
+
387
+ return { writes, notes };
388
+ }
389
+
390
+ /**
391
+ * Write planned changes (skips when dryRun).
392
+ * @param {string} cwd
393
+ * @param {{ file: string, content: string }[]} writes
394
+ * @param {typeof fs} [fse]
395
+ */
396
+ export async function applyProjectSync(cwd, writes, fse = fs) {
397
+ const root = path.resolve(cwd);
398
+ for (const w of writes) {
399
+ const abs = path.resolve(root, w.file);
400
+ const rel = path.relative(root, abs);
401
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
402
+ throw new Error(`Refusing to write outside the project: ${w.file}`);
403
+ }
404
+ await fse.ensureDir(path.dirname(abs));
405
+ await fse.writeFile(abs, w.content, 'utf8');
406
+ }
407
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Read-only npm registry lookups for @stagepass/* packages.
3
+ *
4
+ * Versions of @stagepass/cli, loader and modules are decoupled, and a release
5
+ * can be staged on npm long before it is published. Generated projects and
6
+ * `stagepass upgrade` therefore never derive a dependency range from the CLI's
7
+ * own version: they only write ranges that a published version satisfies.
8
+ */
9
+
10
+ import fs from 'fs-extra';
11
+ import path from 'node:path';
12
+ import { defaultExec } from './exec.js';
13
+ import { MODULE_IDS } from './project-modules.js';
14
+
15
+ /** Major range used for new projects (matches the `@2` CDN embed policy). */
16
+ export const PACKAGES_MAJOR_RANGE = '^2';
17
+
18
+ /** First @stagepass/modules release with per-module type entry points. */
19
+ export const PER_MODULE_TYPES_SINCE = '2.2.0';
20
+
21
+ const SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
22
+ const PKG_NAME_RE = /^@stagepass\/[a-z0-9][a-z0-9._-]*$/;
23
+
24
+ /**
25
+ * Parse a semver string (prerelease kept as a flag).
26
+ * @param {string} version
27
+ * @returns {{ major: number, minor: number, patch: number, pre: boolean } | null}
28
+ */
29
+ export function parseSemver(version) {
30
+ const m = SEMVER_RE.exec(String(version).trim());
31
+ if (!m) return null;
32
+ return { major: +m[1], minor: +m[2], patch: +m[3], pre: String(version).includes('-') };
33
+ }
34
+
35
+ /**
36
+ * Compare two semver strings (prerelease suffix ignored for ordering).
37
+ * @param {string} a
38
+ * @param {string} b
39
+ * @returns {number}
40
+ */
41
+ export function compareSemver(a, b) {
42
+ const x = parseSemver(a);
43
+ const y = parseSemver(b);
44
+ if (!x || !y) return 0;
45
+ return x.major - y.major || x.minor - y.minor || x.patch - y.patch;
46
+ }
47
+
48
+ /**
49
+ * Whether a stable version satisfies a simple range: exact `1.2.3`,
50
+ * caret `^2`, `^2.2`, `^2.2.0`, or tilde `~2.2.0`. Prereleases never match.
51
+ * @param {string} version
52
+ * @param {string} range
53
+ * @returns {boolean}
54
+ */
55
+ export function satisfiesSimple(version, range) {
56
+ const v = parseSemver(version);
57
+ if (!v || v.pre) return false;
58
+ const r = String(range).trim();
59
+ const m = /^([~^]?)(\d+)(?:\.(\d+))?(?:\.(\d+))?$/.exec(r);
60
+ if (!m) return false;
61
+ const [, op, majS, minS, patS] = m;
62
+ const maj = +majS;
63
+ const min = minS == null ? 0 : +minS;
64
+ const pat = patS == null ? 0 : +patS;
65
+ const base = `${maj}.${min}.${pat}`;
66
+ if (op === '') {
67
+ if (minS == null || patS == null) {
68
+ return v.major === maj && (minS == null || v.minor === min);
69
+ }
70
+ return compareSemver(version, base) === 0;
71
+ }
72
+ if (compareSemver(version, base) < 0) return false;
73
+ if (op === '~') {
74
+ return v.major === maj && (minS == null ? true : v.minor === min);
75
+ }
76
+ // caret (major >= 1 for all @stagepass releases)
77
+ if (maj > 0) return v.major === maj;
78
+ if (min > 0) return v.major === 0 && v.minor === min;
79
+ return v.major === 0 && v.minor === 0 && v.patch === pat;
80
+ }
81
+
82
+ /**
83
+ * Highest published stable version satisfying a range.
84
+ * @param {string[]} versions
85
+ * @param {string} range
86
+ * @returns {string | null}
87
+ */
88
+ export function maxSatisfying(versions, range) {
89
+ let best = null;
90
+ for (const v of versions || []) {
91
+ if (satisfiesSimple(v, range) && (best == null || compareSemver(v, best) > 0)) best = v;
92
+ }
93
+ return best;
94
+ }
95
+
96
+ /**
97
+ * Published dist-tags and versions of a package, or null when npm or the
98
+ * network is unavailable (callers fall back to the major range).
99
+ *
100
+ * @param {string} name
101
+ * @param {{ exec?: import('./exec.js').ExecFn, timeoutMs?: number }} [deps]
102
+ * @returns {Promise<{ distTags: Record<string, string>, versions: string[] } | null>}
103
+ */
104
+ export async function fetchPublished(name, deps = {}) {
105
+ if (!PKG_NAME_RE.test(name)) throw new Error(`Invalid package name: ${name}`);
106
+ const exec = deps.exec || defaultExec;
107
+ let stdout;
108
+ try {
109
+ const result = await exec('npm', ['view', name, 'dist-tags', 'versions', '--json'], {
110
+ timeout: deps.timeoutMs ?? 15000,
111
+ });
112
+ if (result && typeof result.code === 'number' && result.code !== 0) return null;
113
+ stdout = String(result?.stdout || '');
114
+ } catch {
115
+ return null;
116
+ }
117
+ let data;
118
+ try {
119
+ data = JSON.parse(stdout);
120
+ } catch {
121
+ return null;
122
+ }
123
+ if (!data || typeof data !== 'object') return null;
124
+ const rawVersions = Array.isArray(data.versions)
125
+ ? data.versions
126
+ : typeof data.versions === 'string'
127
+ ? [data.versions]
128
+ : [];
129
+ const versions = rawVersions.filter((v) => typeof v === 'string' && parseSemver(v));
130
+ /** @type {Record<string, string>} */
131
+ const distTags = {};
132
+ const tags = data['dist-tags'];
133
+ if (tags && typeof tags === 'object') {
134
+ for (const [tag, v] of Object.entries(tags)) {
135
+ if (/^[a-z][a-z0-9_-]*$/i.test(tag) && typeof v === 'string' && parseSemver(v)) distTags[tag] = v;
136
+ }
137
+ }
138
+ if (versions.length === 0) return null;
139
+ return { distTags, versions };
140
+ }
141
+
142
+ /**
143
+ * Whether the @stagepass/modules version a range resolves to ships
144
+ * per-module types (`@stagepass/modules/<id>`).
145
+ * @param {string[] | null | undefined} versions published versions
146
+ * @param {string} range
147
+ * @returns {boolean | null} null when unknown (no registry data)
148
+ */
149
+ export function rangeHasPerModuleTypes(versions, range) {
150
+ if (!versions) return null;
151
+ const best = maxSatisfying(versions, range);
152
+ if (!best) return false;
153
+ return compareSemver(best, PER_MODULE_TYPES_SINCE) >= 0;
154
+ }
155
+
156
+ /**
157
+ * Whether the installed @stagepass/modules ships per-module types.
158
+ * @param {string} cwd project directory
159
+ * @param {typeof fs} [fse]
160
+ * @returns {Promise<boolean | null>} null when not installed
161
+ */
162
+ export async function installedHasPerModuleTypes(cwd, fse = fs) {
163
+ const dir = path.join(cwd, 'node_modules', '@stagepass', 'modules');
164
+ if (!(await fse.pathExists(path.join(dir, 'package.json')))) return null;
165
+ for (const id of MODULE_IDS) {
166
+ if (!(await fse.pathExists(path.join(dir, `${id}.d.ts`)))) return false;
167
+ }
168
+ return true;
169
+ }