@stagepass/cli 2.2.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.
package/README.md CHANGED
@@ -93,7 +93,7 @@ Scaffold a project with flags for every choice (interactive prompts only on a TT
93
93
  | `-y, --yes` | Non-interactive; use defaults for omitted flags. |
94
94
  | `--dry-run` | Print the file plan without writing. |
95
95
 
96
- The name must be DNS-safe (lowercase `a-z`, `0-9`, hyphens; 1 to 63 chars; no leading/trailing hyphen). Existing files are never overwritten. Generated projects include `scripts/build.mjs` (content-hashed `dist/` + `manifest.json`), Webflow head/footer snippets (jsDelivr `@2`, loader plus the declared modules), `stagepass.json`, an `AGENTS.md` with the full `sp` API reference, `.cursor/rules/stagepass.mdc`, and a `.gitignore`. `@stagepass/loader` / `@stagepass/modules` are added as `^2.2.0` (same major as the CDN pin `@2`, minor that ships the per-module types).
96
+ The name must be DNS-safe (lowercase `a-z`, `0-9`, hyphens; 1 to 63 chars; no leading/trailing hyphen). Existing files are never overwritten. Generated projects include `scripts/build.mjs` (content-hashed `dist/` + `manifest.json`), Webflow head/footer snippets (jsDelivr `@2`, loader plus the declared modules), `stagepass.json`, an `AGENTS.md` with the full `sp` API reference, `.cursor/rules/stagepass.mdc`, and a `.gitignore`. `@stagepass/loader` / `@stagepass/modules` are added as `^2` (same major as the CDN pin `@2`; npm installs the newest published 2.x). Per-module types are written only when the published or installed `@stagepass/modules` ships them (2.2.0 and later); otherwise `types` lists the umbrella `@stagepass/modules`.
97
97
 
98
98
  Interactively, `new` asks for the live site after the styles question, shows the detected modules and asks for confirmation; otherwise it asks for the list directly. Without a TTY (or with `--yes`) it uses `--site-modules`, then `--site` detection, else `[]` with a hint.
99
99
 
@@ -109,7 +109,7 @@ Interactively, `new` asks for the live site after the styles question, shows the
109
109
  - `.cursor/rules/stagepass.mdc` (globs `src/**`) with the same content;
110
110
  - `compilerOptions.types` in `tsconfig.json` / `jsconfig.json`: `@stagepass/loader` plus `@stagepass/modules/<module>` for each declared module (`@stagepass/modules` for `all`), so undeclared modules are type errors.
111
111
 
112
- The legacy boolean `"modules": true|false` is still read; `upgrade` replaces it with a list.
112
+ The legacy boolean `"modules": true|false` is still read; `upgrade` replaces it with a list (`true` becomes `["all"]` without a TTY).
113
113
 
114
114
  ### Live site detection
115
115
 
@@ -119,7 +119,7 @@ The legacy boolean `"modules": true|false` is still read; `upgrade` replaces it
119
119
 
120
120
  | Option | Behaviour |
121
121
  | :--- | :--- |
122
- | `--version <x>` | Target loader/modules version (default: the version this CLI targets, currently `2.2.0`). Dist-tags such as `latest` resolve via `npm view`. (Implemented as `--target` internally so it does not collide with `stagepass --version`.) |
122
+ | `--version <x>` | Target loader/modules version, range or dist-tag. It must be published on npm (staged releases are refused until approved). Default: `^<latest published 2.x>` from `npm view`, or `^2` when the registry is not reachable. (Implemented as `--target` internally so it does not collide with `stagepass --version`.) |
123
123
  | `--site <host>` | Live site to detect modules from (default: the origin linked in `~/.stagepass/projects.json` for this folder). Stored in `stagepass.json` when given. |
124
124
  | `--site-modules <list>` | Set the modules list directly (`none`, `all`, or a comma list). |
125
125
  | `--skip-site` | Do not fetch the live site. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stagepass/cli",
3
- "version": "2.2.0",
3
+ "version": "2.2.1",
4
4
  "description": "Local Development Orchestrator for Webflow",
5
5
  "type": "module",
6
6
  "main": "bin/index.js",
package/src/cli.js CHANGED
@@ -267,7 +267,7 @@ export function createProgram(deps = {}) {
267
267
  .option('-y, --yes', 'Non-interactive; accept detected or existing modules')
268
268
  .option(
269
269
  '--target <version>',
270
- 'Target loader/modules version (default: the version this CLI targets; dist-tags use npm view)'
270
+ 'Target version, range or dist-tag; must be published on npm (default: ^<latest published 2.x>, ^2 offline)'
271
271
  )
272
272
  // Public docs use `--version`; rewriteArgvForUpgrade maps it to `--target`
273
273
  // so it does not collide with the root `stagepass --version` handler.
@@ -20,6 +20,17 @@ import {
20
20
  import { STAGEPASS_PACKAGES_VERSION } from '../lib/versions.js';
21
21
  import { formatModules, normalizeModulesList } from '../lib/project-modules.js';
22
22
  import { describeDetection, detectSite, normalizeSiteUrl } from '../lib/site-detect.js';
23
+ import {
24
+ PACKAGES_MAJOR_RANGE,
25
+ fetchPublished,
26
+ installedHasPerModuleTypes,
27
+ rangeHasPerModuleTypes,
28
+ } from '../lib/registry.js';
29
+ import { updateConfigTypes } from '../lib/project-sync.js';
30
+
31
+ const PER_MODULE_TYPES_HINT =
32
+ '@stagepass/modules on npm has no per-module types yet (needs 2.2.0); ' +
33
+ 'types use "@stagepass/modules" for now. Run `stagepass upgrade` once it is published to narrow them.';
23
34
 
24
35
  /**
25
36
  * Resolve a boolean flag that may appear as --foo / --no-foo.
@@ -284,6 +295,34 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
284
295
  };
285
296
  }
286
297
 
298
+ /**
299
+ * After `npm install`, align tsconfig/jsconfig types with the installed
300
+ * @stagepass/modules (per-module entries only when it ships them).
301
+ *
302
+ * @param {string} targetDir
303
+ * @param {{ siteModules: string[], perModuleTypes?: boolean }} config
304
+ * @param {typeof fs} fse
305
+ * @param {(msg?: string) => void} log
306
+ */
307
+ async function reconcileInstalledTypes(targetDir, config, fse, log) {
308
+ const installed = await installedHasPerModuleTypes(targetDir, fse);
309
+ if (installed === null || installed === (config.perModuleTypes !== false)) return;
310
+ for (const name of ['tsconfig.json', 'jsconfig.json']) {
311
+ const file = path.join(targetDir, name);
312
+ if (!(await fse.pathExists(file))) continue;
313
+ const raw = await fse.readFile(file, 'utf8');
314
+ const result = updateConfigTypes(raw, config.siteModules, {
315
+ modulesDependency: true,
316
+ perModuleTypes: installed,
317
+ });
318
+ if (result.status === 'updated' && result.content) {
319
+ await fse.writeFile(file, result.content, 'utf8');
320
+ log(chalk.dim(`${name}: types ${result.types.join(', ')} (matches installed @stagepass/modules)`));
321
+ }
322
+ }
323
+ if (!installed) log(chalk.yellow(PER_MODULE_TYPES_HINT));
324
+ }
325
+
287
326
  /**
288
327
  * Scaffold a new Stagepass project.
289
328
  *
@@ -336,6 +375,20 @@ export async function createNew(nameArg, options = {}, deps = {}) {
336
375
  }
337
376
  };
338
377
 
378
+ // Single-module types (`@stagepass/modules/cookies`) exist since modules
379
+ // 2.2.0. Only use them when a published release in range ships them;
380
+ // otherwise (or offline) fall back to the umbrella types so tsc passes.
381
+ const singleModuleTypes =
382
+ config.modules === true &&
383
+ config.siteModules.length > 0 &&
384
+ !config.siteModules.includes('all');
385
+ if (singleModuleTypes && !config.dryRun) {
386
+ const published = await (deps.fetchPublished || fetchPublished)('@stagepass/modules', { exec });
387
+ config.perModuleTypes =
388
+ rangeHasPerModuleTypes(published ? published.versions : null, PACKAGES_MAJOR_RANGE) === true;
389
+ if (!config.perModuleTypes) log(chalk.yellow(PER_MODULE_TYPES_HINT));
390
+ }
391
+
339
392
  let files;
340
393
  try {
341
394
  files = await planScaffoldFiles(config, { readTemplate });
@@ -423,6 +476,9 @@ export async function createNew(nameArg, options = {}, deps = {}) {
423
476
  error(chalk.red(`npm install exited with code ${result.code}`));
424
477
  return typeof result.code === 'number' ? result.code : 1;
425
478
  }
479
+ if (singleModuleTypes) {
480
+ await reconcileInstalledTypes(targetDir, config, fse, log);
481
+ }
426
482
  } catch (err) {
427
483
  error(
428
484
  chalk.red(
@@ -10,6 +10,14 @@ import {
10
10
  import readline from 'node:readline/promises';
11
11
  import { stdin as input, stdout as output } from 'node:process';
12
12
  import { STAGEPASS_PACKAGES_VERSION } from '../lib/versions.js';
13
+ import {
14
+ PACKAGES_MAJOR_RANGE,
15
+ fetchPublished,
16
+ installedHasPerModuleTypes,
17
+ maxSatisfying,
18
+ rangeHasPerModuleTypes,
19
+ satisfiesSimple,
20
+ } from '../lib/registry.js';
13
21
  import { detectSite } from '../lib/site-detect.js';
14
22
  import {
15
23
  applyProjectSync,
@@ -20,13 +28,13 @@ import {
20
28
 
21
29
  const STAGEPASS_SCOPE = '@stagepass/';
22
30
 
31
+ const SAFE_SPEC_RE = /^[~^]?[0-9A-Za-z][0-9A-Za-z._+-]*$/;
32
+
23
33
  /**
24
- * True when the version looks like an npm dist-tag that needs resolution.
34
+ * True when the version looks like an npm dist-tag (bare word, e.g. latest).
25
35
  * @param {string} version
26
36
  */
27
- function needsNpmView(version) {
28
- if (!version) return false;
29
- // Semver-ish or range: treat as literal. Dist-tags are bare words.
37
+ function isDistTag(version) {
30
38
  if (/^[0-9]/.test(version) || version.startsWith('^') || version.startsWith('~')) {
31
39
  return false;
32
40
  }
@@ -35,47 +43,80 @@ function needsNpmView(version) {
35
43
  }
36
44
 
37
45
  /**
38
- * Resolve target version. Defaults to the @stagepass/loader + modules version
39
- * this CLI targets (not the CLI's own version, which can differ on CLI patches).
40
- * Contacts the network only when `--version` is an npm dist-tag (e.g. latest).
46
+ * Resolve the range to write for one @stagepass/* package.
47
+ *
48
+ * Never writes a version or range that no published release satisfies
49
+ * (releases can be staged but not yet approved, which gives ETARGET):
50
+ * - default: `^<latest>` when latest is in the current major, else
51
+ * `^<highest published 2.x>`; `^2` when npm is unreachable
52
+ * - `--version <semver|range>`: must match a published version
53
+ * - `--version <dist-tag>`: the published version behind that tag
41
54
  *
55
+ * @param {string} name
42
56
  * @param {string|undefined} requested
43
- * @param {object} deps
44
- * @param {import('../lib/exec.js').ExecFn} [deps.exec]
45
- * @param {string} [deps.packagesVersion]
46
- * @param {string} [deps.cliVersion] Legacy alias for packagesVersion (tests)
47
- * @returns {Promise<string>}
57
+ * @param {{ distTags: Record<string, string>, versions: string[] } | null} published
58
+ * @returns {{ spec: string, resolved: string | null, offline: boolean }}
48
59
  */
49
- export async function resolveUpgradeVersion(requested, deps = {}) {
50
- const exec = deps.exec || defaultExec;
51
- const fallback =
52
- deps.packagesVersion || deps.cliVersion || STAGEPASS_PACKAGES_VERSION;
60
+ export function resolvePackageTarget(name, requested, published) {
61
+ const value = requested == null ? '' : String(requested).trim().replace(/^v(?=\d)/i, '');
62
+ if (value && !SAFE_SPEC_RE.test(value)) {
63
+ throw new Error('Invalid --version value (use a semver, range prefix ^/~, or npm dist-tag).');
64
+ }
53
65
 
54
- if (!requested || String(requested).trim() === '') {
55
- return fallback;
66
+ if (!value) {
67
+ if (!published) return { spec: PACKAGES_MAJOR_RANGE, resolved: null, offline: true };
68
+ const latest = published.distTags.latest;
69
+ const best =
70
+ latest && satisfiesSimple(latest, PACKAGES_MAJOR_RANGE)
71
+ ? latest
72
+ : maxSatisfying(published.versions, PACKAGES_MAJOR_RANGE);
73
+ if (!best) return { spec: PACKAGES_MAJOR_RANGE, resolved: null, offline: false };
74
+ return { spec: `^${best}`, resolved: best, offline: false };
56
75
  }
57
76
 
58
- const value = String(requested).trim();
59
- if (!needsNpmView(value)) {
60
- const literal = value.replace(/^v/i, '');
61
- // Keep package.json / snippet versions free of shell or HTML metacharacters.
62
- if (!/^[~^]?[0-9A-Za-z][0-9A-Za-z._+-]*$/.test(literal)) {
63
- throw new Error(
64
- 'Invalid --version value (use a semver, range prefix ^/~, or npm dist-tag).'
65
- );
66
- }
67
- return literal;
77
+ if (!published) {
78
+ throw new Error(
79
+ `Could not check ${name}@${value} on npm (offline?). Retry online, or run without --version to use ${PACKAGES_MAJOR_RANGE}.`
80
+ );
68
81
  }
69
82
 
70
- const { stdout } = await exec('npm', ['view', `@stagepass/cli@${value}`, 'version']);
71
- const resolved = String(stdout || '').trim();
72
- if (!resolved) {
73
- throw new Error(`Could not resolve version for dist-tag "${value}".`);
83
+ if (isDistTag(value)) {
84
+ const tagged = published.distTags[value];
85
+ if (!tagged) throw new Error(`${name} has no dist-tag "${value}".`);
86
+ return { spec: tagged, resolved: tagged, offline: false };
87
+ }
88
+
89
+ const best = maxSatisfying(published.versions, value);
90
+ if (!best) {
91
+ throw new Error(
92
+ `No published ${name} matches ${value} (staged releases cannot be installed until they are approved).`
93
+ );
74
94
  }
75
- if (!/^[~^]?[0-9A-Za-z][0-9A-Za-z._+-]*$/.test(resolved)) {
76
- throw new Error(`Resolved version looks unsafe: ${resolved}`);
95
+ return { spec: value, resolved: best, offline: false };
96
+ }
97
+
98
+ /**
99
+ * Resolve target ranges for every @stagepass/* dependency in package.json.
100
+ *
101
+ * @param {string|undefined} requested `--version`
102
+ * @param {string[]} names package names
103
+ * @param {object} [deps]
104
+ * @param {(name: string) => Promise<{ distTags: Record<string, string>, versions: string[] } | null>} [deps.fetchPublished]
105
+ * @param {import('../lib/exec.js').ExecFn} [deps.exec]
106
+ * @returns {Promise<{ targets: Record<string, { spec: string, resolved: string | null, offline: boolean }>, published: Record<string, { distTags: Record<string, string>, versions: string[] } | null> }>}
107
+ */
108
+ export async function resolveUpgradeTargets(requested, names, deps = {}) {
109
+ const lookup =
110
+ deps.fetchPublished || ((name) => fetchPublished(name, { exec: deps.exec || defaultExec }));
111
+ /** @type {Record<string, any>} */
112
+ const targets = {};
113
+ /** @type {Record<string, any>} */
114
+ const published = {};
115
+ for (const name of [...new Set(names)]) {
116
+ published[name] = await lookup(name);
117
+ targets[name] = resolvePackageTarget(name, requested, published[name]);
77
118
  }
78
- return resolved;
119
+ return { targets, published };
79
120
  }
80
121
 
81
122
  /**
@@ -101,17 +142,17 @@ export function findStagepassDeps(pkg) {
101
142
  /**
102
143
  * Rewrite @stagepass/* versions in a package.json object (mutates a copy).
103
144
  * @param {object} pkg
104
- * @param {string} targetVersion
145
+ * @param {string | Record<string, string>} target one spec for all, or per package name
105
146
  * @returns {{ next: object, changes: { name: string, from: string, to: string, section: string }[] }}
106
147
  */
107
- export function applyStagepassVersions(pkg, targetVersion) {
148
+ export function applyStagepassVersions(pkg, target) {
108
149
  const next = structuredClone(pkg);
109
150
  const changes = [];
110
- const target = String(targetVersion);
111
151
 
112
152
  for (const { section, name, from } of findStagepassDeps(pkg)) {
113
153
  if (!next[section]) continue;
114
- const to = target;
154
+ const to = typeof target === 'string' ? target : target[name];
155
+ if (!to) continue;
115
156
  if (String(from) !== to) {
116
157
  changes.push({ name, from: String(from), to, section });
117
158
  }
@@ -137,7 +178,7 @@ export function applyStagepassVersions(pkg, targetVersion) {
137
178
  * @param {typeof fs} [deps.fs]
138
179
  * @param {string} [deps.cwd]
139
180
  * @param {import('../lib/exec.js').ExecFn} [deps.exec]
140
- * @param {string} [deps.cliVersion]
181
+ * @param {(name: string) => Promise<{ distTags: Record<string, string>, versions: string[] } | null>} [deps.fetchPublished]
141
182
  * @param {(msg?: string) => void} [deps.log]
142
183
  * @returns {Promise<number>} exit code
143
184
  */
@@ -152,17 +193,6 @@ export async function upgrade(options = {}, deps = {}) {
152
193
  return 1;
153
194
  }
154
195
 
155
- let targetVersion;
156
- try {
157
- targetVersion = await resolveUpgradeVersion(options.version, {
158
- exec: deps.exec || defaultExec,
159
- packagesVersion: deps.packagesVersion || deps.cliVersion,
160
- });
161
- } catch (error) {
162
- log(chalk.red(error instanceof Error ? error.message : String(error)));
163
- return 1;
164
- }
165
-
166
196
  const raw = await fse.readFile(pkgPath, 'utf8');
167
197
  let pkg;
168
198
  try {
@@ -172,22 +202,53 @@ export async function upgrade(options = {}, deps = {}) {
172
202
  return 1;
173
203
  }
174
204
 
175
- const { next, changes } = applyStagepassVersions(pkg, targetVersion);
205
+ const names = findStagepassDeps(pkg).map((d) => d.name);
206
+ let resolvedTargets;
207
+ try {
208
+ resolvedTargets = await resolveUpgradeTargets(options.version, names, {
209
+ exec: deps.exec || defaultExec,
210
+ fetchPublished: deps.fetchPublished,
211
+ });
212
+ } catch (error) {
213
+ log(chalk.red(error instanceof Error ? error.message : String(error)));
214
+ return 1;
215
+ }
216
+ const { targets, published } = resolvedTargets;
217
+ /** @type {Record<string, string>} */
218
+ const specs = Object.fromEntries(Object.entries(targets).map(([n, t]) => [n, t.spec]));
219
+ if (Object.values(targets).some((t) => t.offline)) {
220
+ log(chalk.yellow(`npm registry not reachable: using ${PACKAGES_MAJOR_RANGE} (resolves to the newest published 2.x).`));
221
+ }
222
+
223
+ const { next, changes } = applyStagepassVersions(pkg, specs);
176
224
 
177
225
  if (changes.length === 0) {
178
- const existing = findStagepassDeps(pkg);
179
- if (existing.length === 0) {
226
+ if (names.length === 0) {
180
227
  log(chalk.yellow('No @stagepass/* packages found in package.json.'));
181
228
  } else {
182
- log(chalk.green(`@stagepass/* already at ${targetVersion}.`));
229
+ log(chalk.green('@stagepass/* already at the newest published ranges.'));
183
230
  }
184
231
  } else {
185
- log(chalk.bold(`Upgrade @stagepass/* → ${targetVersion}`));
232
+ log(chalk.bold('Upgrade @stagepass/* (published versions only)'));
186
233
  for (const change of changes) {
187
234
  log(` ${change.name}: ${change.from} → ${change.to} (${change.section})`);
188
235
  }
189
236
  }
190
237
 
238
+ // Per-module types need @stagepass/modules >= 2.2.0 resolvable from the range.
239
+ /** @type {boolean | undefined} */
240
+ let perModuleTypes;
241
+ const modulesSpec =
242
+ next?.dependencies?.['@stagepass/modules'] || next?.devDependencies?.['@stagepass/modules'];
243
+ if (modulesSpec) {
244
+ const fromRegistry = rangeHasPerModuleTypes(
245
+ published['@stagepass/modules'] ? published['@stagepass/modules'].versions : null,
246
+ String(modulesSpec)
247
+ );
248
+ perModuleTypes =
249
+ fromRegistry != null ? fromRegistry : (await installedHasPerModuleTypes(cwd, fse)) === true;
250
+ }
251
+
191
252
  // Declared modules: live site first, then stagepass.json, then ask.
192
253
  const sp = await readStagepassJson(cwd, fse);
193
254
  if (sp.error) log(chalk.yellow(sp.error));
@@ -235,6 +296,7 @@ export async function upgrade(options = {}, deps = {}) {
235
296
  modules: resolved.modules,
236
297
  origin: options.site ? resolved.origin : null,
237
298
  pkg: next,
299
+ perModuleTypes,
238
300
  },
239
301
  fse
240
302
  );
@@ -249,6 +311,13 @@ export async function upgrade(options = {}, deps = {}) {
249
311
  for (const note of plan.notes) {
250
312
  log(chalk.yellow(` note: ${note}`));
251
313
  }
314
+ if (perModuleTypes === false && resolved.modules.length > 0 && !resolved.modules.includes('all')) {
315
+ log(
316
+ chalk.yellow(
317
+ ' note: the published @stagepass/modules has no per-module types yet (needs 2.2.0); types use "@stagepass/modules". Run `stagepass upgrade` again once it is published.'
318
+ )
319
+ );
320
+ }
252
321
 
253
322
  if (options.dryRun) {
254
323
  log(chalk.dim('\nDry run: no files were modified.'));
@@ -264,7 +333,7 @@ export async function upgrade(options = {}, deps = {}) {
264
333
  }
265
334
 
266
335
  const snippets = buildWebflowSnippets({
267
- version: targetVersion,
336
+ version: targets['@stagepass/loader']?.resolved || STAGEPASS_PACKAGES_VERSION,
268
337
  moduleList: resolved.modules,
269
338
  });
270
339
  printWebflowSnippets(snippets, log);
@@ -71,12 +71,22 @@ export function isStagepassModulesTypeEntry(entry) {
71
71
  /**
72
72
  * `compilerOptions.types` entries for a declared list.
73
73
  * @param {string[]} modules normalized list
74
- * @param {{ modulesDependency?: boolean }} [opts] module types need the npm dep
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
75
81
  * @returns {string[]}
76
82
  */
77
83
  export function typesForModules(modules, opts = {}) {
78
84
  const types = ['@stagepass/loader'];
79
85
  if (opts.modulesDependency === false) return types;
86
+ if (modules.length > 0 && opts.perModuleTypes === false) {
87
+ types.push('@stagepass/modules');
88
+ return types;
89
+ }
80
90
  if (modules.includes('all')) {
81
91
  types.push('@stagepass/modules');
82
92
  } else {
@@ -179,9 +179,20 @@ export async function resolveUpgradeModules(input, deps) {
179
179
  source = 'stagepass.json';
180
180
  }
181
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
+
182
190
  if (!deps.interactive) {
183
191
  if (candidate) {
184
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
+ }
185
196
  return { ok: true, modules: candidate, source, origin, detection };
186
197
  }
187
198
  if (hasModulesDep) {
@@ -221,7 +232,7 @@ export async function resolveUpgradeModules(input, deps) {
221
232
  *
222
233
  * @param {string} raw file contents
223
234
  * @param {string[]} modules
224
- * @param {{ modulesDependency: boolean }} opts
235
+ * @param {{ modulesDependency: boolean, perModuleTypes?: boolean }} opts
225
236
  * @returns {{ status: 'updated' | 'unchanged' | 'skipped', content?: string, reason?: string, types?: string[] }}
226
237
  */
227
238
  export function updateConfigTypes(raw, modules, opts) {
@@ -269,6 +280,7 @@ export function updateConfigTypes(raw, modules, opts) {
269
280
  * @param {string[]} input.modules
270
281
  * @param {string | null} [input.origin] stored in stagepass.json when set
271
282
  * @param {object} input.pkg package.json
283
+ * @param {boolean} [input.perModuleTypes] false when @stagepass/modules has no per-module types (umbrella entry)
272
284
  * @param {typeof fs} [fse]
273
285
  * @returns {Promise<{ writes: { file: string, content: string, action: string }[], notes: string[] }>}
274
286
  */
@@ -281,6 +293,7 @@ export async function planProjectSync(input, fse = fs) {
281
293
  const modulesDependency = Boolean(
282
294
  pkg?.dependencies?.['@stagepass/modules'] || pkg?.devDependencies?.['@stagepass/modules']
283
295
  );
296
+ const perModuleTypes = input.perModuleTypes;
284
297
 
285
298
  // stagepass.json
286
299
  const sp = await readStagepassJson(cwd, fse);
@@ -356,9 +369,9 @@ export async function planProjectSync(input, fse = fs) {
356
369
  if (!(await fse.pathExists(file))) continue;
357
370
  sawConfig = true;
358
371
  const raw = await fse.readFile(file, 'utf8');
359
- const result = updateConfigTypes(raw, modules, { modulesDependency });
372
+ const result = updateConfigTypes(raw, modules, { modulesDependency, perModuleTypes });
360
373
  if (result.status === 'skipped') {
361
- const wanted = JSON.stringify(typesForModules(modules, { modulesDependency }));
374
+ const wanted = JSON.stringify(typesForModules(modules, { modulesDependency, perModuleTypes }));
362
375
  notes.push(`${name} ${result.reason}: "types": ${wanted}`);
363
376
  } else if (result.status === 'updated') {
364
377
  writes.push({ file: name, content: result.content, action: `types: ${result.types.join(', ')}` });
@@ -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
+ }
@@ -61,7 +61,8 @@ export function scaffoldTemplateMap(lang, styles) {
61
61
  * @property {boolean} install
62
62
  * @property {boolean} dryRun
63
63
  * @property {string} [loaderVersion] @stagepass/loader + modules version (snippets)
64
- * @property {string} [packagesRange] Override for package.json ranges (default ^<major>.<minor>.0)
64
+ * @property {string} [packagesRange] Override for package.json ranges (default ^<major>, e.g. ^2)
65
+ * @property {boolean} [perModuleTypes] false: use the umbrella `@stagepass/modules` types (modules < 2.2.0)
65
66
  */
66
67
 
67
68
  /**
@@ -69,9 +70,9 @@ export function scaffoldTemplateMap(lang, styles) {
69
70
  * @returns {Record<string, string>}
70
71
  */
71
72
  export function buildPackageJson(options) {
72
- const range =
73
- options.packagesRange ||
74
- packagesRange(options.loaderVersion || STAGEPASS_PACKAGES_VERSION);
73
+ // Never derive the range from the CLI or target version: a release can be
74
+ // staged but unpublished (ETARGET). The major range matches the @2 embeds.
75
+ const range = options.packagesRange || packagesRange(STAGEPASS_PACKAGES_VERSION);
75
76
  const isTs = options.lang === 'ts';
76
77
  const useSass = options.styles === 'scss';
77
78
 
@@ -140,7 +141,10 @@ export async function planScaffoldFiles(options, deps = {}) {
140
141
  version,
141
142
  moduleList: siteModules,
142
143
  });
143
- const types = typesForModules(siteModules, { modulesDependency: options.modules === true });
144
+ const types = typesForModules(siteModules, {
145
+ modulesDependency: options.modules === true,
146
+ perModuleTypes: options.perModuleTypes,
147
+ });
144
148
 
145
149
  const vars = {
146
150
  NAME: options.name,
@@ -1,27 +1,25 @@
1
1
  /**
2
2
  * Version of @stagepass/loader and @stagepass/modules this CLI targets.
3
3
  *
4
- * The CLI can ship patch releases on its own (e.g. cli 2.2.1 while loader and
5
- * modules stay at 2.2.0), so generated projects and `stagepass upgrade` must
6
- * not reuse the CLI version. A monorepo test keeps this in sync with
7
- * packages/loader and packages/modules.
4
+ * Used for docs and snippet examples only. Dependency ranges never come from
5
+ * this or the CLI version: new projects use the major range (`^2`) and
6
+ * `stagepass upgrade` only writes ranges a published version satisfies.
7
+ * A monorepo test keeps this in sync with packages/loader and packages/modules.
8
8
  */
9
9
  export const STAGEPASS_PACKAGES_VERSION = '2.2.0';
10
10
 
11
11
  /**
12
- * Caret range from the major.minor of a version (e.g. 2.2.0 → ^2.2.0).
13
- * Stays within the major (CDN default `@2`) but requires the minor that
14
- * ships the features generated projects rely on (per-module types in 2.2).
15
- * npm resolves it once published, even while the release only carries the
16
- * `next` dist-tag (latest 2.0.0 does not satisfy it).
12
+ * Major caret range for a version (e.g. 2.2.0 → ^2), matching the `@2` CDN
13
+ * embed policy. Generated projects use it so `npm install` works with
14
+ * whatever 2.x is published; staged but unpublished releases never break it.
17
15
  *
18
16
  * @param {string} [version]
19
17
  * @returns {string}
20
18
  */
21
19
  export function packagesRange(version = STAGEPASS_PACKAGES_VERSION) {
22
- const match = /^[~^]?(\d+)\.(\d+)\./.exec(String(version).trim());
20
+ const match = /^[~^]?(\d+)(?:\.\d+){0,2}$/.exec(String(version).trim());
23
21
  if (!match) {
24
22
  throw new Error(`Invalid @stagepass package version: ${version}`);
25
23
  }
26
- return `^${match[1]}.${match[2]}.0`;
24
+ return `^${match[1]}`;
27
25
  }
@@ -13,7 +13,7 @@
13
13
  };
14
14
 
15
15
  const start = () => {
16
- const w = window;
16
+ const w = /** @type {Window & { Webflow?: { push?: (fn: () => void) => void } }} */ (window);
17
17
  if (w.Webflow && typeof w.Webflow.push === 'function') {
18
18
  w.Webflow.push(run);
19
19
  return;