@stagepass/cli 2.2.1 → 2.2.7

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.
@@ -1,39 +1,31 @@
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
- */
1
+ /** Read-only npm registry lookups for @stagepass/* packages. */
9
2
 
10
3
  import fs from 'fs-extra';
11
4
  import path from 'node:path';
12
5
  import { defaultExec } from './exec.js';
13
6
  import { MODULE_IDS } from './project-modules.js';
7
+ import { STAGEPASS_PACKAGES_VERSION } from './versions.js';
14
8
 
15
- /** Major range used for new projects (matches the `@2` CDN embed policy). */
9
+ /** Major range for new projects (matches `@2` CDN embed policy). */
16
10
  export const PACKAGES_MAJOR_RANGE = '^2';
17
11
 
18
- /** First @stagepass/modules release with per-module type entry points. */
12
+ /** First @stagepass/modules release with per-module type entry points. */
19
13
  export const PER_MODULE_TYPES_SINCE = '2.2.0';
20
14
 
21
- const SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
15
+ const SEMVER_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?$/;
22
16
  const PKG_NAME_RE = /^@stagepass\/[a-z0-9][a-z0-9._-]*$/;
23
17
 
24
18
  /**
25
- * Parse a semver string (prerelease kept as a flag).
26
19
  * @param {string} version
27
20
  * @returns {{ major: number, minor: number, patch: number, pre: boolean } | null}
28
21
  */
29
22
  export function parseSemver(version) {
30
- const m = SEMVER_RE.exec(String(version).trim());
23
+ const m = SEMVER_RE.exec(String(version));
31
24
  if (!m) return null;
32
- return { major: +m[1], minor: +m[2], patch: +m[3], pre: String(version).includes('-') };
25
+ return { major: +m[1], minor: +m[2], patch: +m[3], pre: Boolean(m[4]) };
33
26
  }
34
27
 
35
28
  /**
36
- * Compare two semver strings (prerelease suffix ignored for ordering).
37
29
  * @param {string} a
38
30
  * @param {string} b
39
31
  * @returns {number}
@@ -46,8 +38,6 @@ export function compareSemver(a, b) {
46
38
  }
47
39
 
48
40
  /**
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
41
  * @param {string} version
52
42
  * @param {string} range
53
43
  * @returns {boolean}
@@ -80,7 +70,6 @@ export function satisfiesSimple(version, range) {
80
70
  }
81
71
 
82
72
  /**
83
- * Highest published stable version satisfying a range.
84
73
  * @param {string[]} versions
85
74
  * @param {string} range
86
75
  * @returns {string | null}
@@ -94,9 +83,6 @@ export function maxSatisfying(versions, range) {
94
83
  }
95
84
 
96
85
  /**
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
86
  * @param {string} name
101
87
  * @param {{ exec?: import('./exec.js').ExecFn, timeoutMs?: number }} [deps]
102
88
  * @returns {Promise<{ distTags: Record<string, string>, versions: string[] } | null>}
@@ -140,9 +126,7 @@ export async function fetchPublished(name, deps = {}) {
140
126
  }
141
127
 
142
128
  /**
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
129
+ * @param {string[] | null | undefined} versions
146
130
  * @param {string} range
147
131
  * @returns {boolean | null} null when unknown (no registry data)
148
132
  */
@@ -154,8 +138,7 @@ export function rangeHasPerModuleTypes(versions, range) {
154
138
  }
155
139
 
156
140
  /**
157
- * Whether the installed @stagepass/modules ships per-module types.
158
- * @param {string} cwd project directory
141
+ * @param {string} cwd
159
142
  * @param {typeof fs} [fse]
160
143
  * @returns {Promise<boolean | null>} null when not installed
161
144
  */
@@ -167,3 +150,35 @@ export async function installedHasPerModuleTypes(cwd, fse = fs) {
167
150
  }
168
151
  return true;
169
152
  }
153
+
154
+ /**
155
+ * @param {string} cwd
156
+ * @param {typeof fs} [fse]
157
+ * @returns {Promise<string | null>}
158
+ */
159
+ export async function installedLoaderVersion(cwd, fse = fs) {
160
+ const file = path.join(cwd, 'node_modules', '@stagepass', 'loader', 'package.json');
161
+ try {
162
+ if (!(await fse.pathExists(file))) return null;
163
+ const pkg = await fse.readJson(file);
164
+ const version = typeof pkg?.version === 'string' ? pkg.version : '';
165
+ return satisfiesSimple(version, PACKAGES_MAJOR_RANGE) ? version : null;
166
+ } catch {
167
+ return null;
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Loader version for Webflow snippets (AC-14); never the CLI version.
173
+ * @param {object} options
174
+ * @param {{ distTags: Record<string, string>, versions: string[] } | null} options.published
175
+ * @param {string} options.cwd
176
+ * @param {string} [options.bundled]
177
+ * @param {typeof fs} [options.fse]
178
+ * @returns {Promise<string>}
179
+ */
180
+ export async function resolveSnippetLoaderVersion({ published, cwd, bundled, fse = fs }) {
181
+ const best = published ? maxSatisfying(published.versions, PACKAGES_MAJOR_RANGE) : null;
182
+ if (best) return best;
183
+ return (await installedLoaderVersion(cwd, fse)) || bundled || STAGEPASS_PACKAGES_VERSION;
184
+ }
@@ -1,9 +1,6 @@
1
1
  /**
2
- * Detect which Stagepass scripts a live Webflow site loads.
3
- *
4
- * Public GET only: https, no cookies or auth headers, max 3 redirects,
5
- * ~5 s timeout, size cap. The fetched HTML is parsed with regexes for
6
- * <script src> values and is never executed.
2
+ * Detect Stagepass scripts on a live Webflow site.
3
+ * Public GET only: https, no cookies/credentials; HTML scanned, never executed.
7
4
  */
8
5
 
9
6
  import { validateOriginEntry } from './origins.js';
@@ -12,26 +9,55 @@ import { MODULE_CHOICES, normalizeModulesList } from './project-modules.js';
12
9
  export const DETECT_TIMEOUT_MS = 5000;
13
10
  export const DETECT_MAX_BYTES = 2 * 1024 * 1024;
14
11
  export const DETECT_MAX_REDIRECTS = 3;
12
+ export const SITE_PORT_ERROR =
13
+ 'Site URL must not contain a port, also not :443. Use the host only, e.g. my-site.webflow.io.';
15
14
 
16
- // Bounded attribute run keeps the scan linear on hostile input.
15
+ // Bound attribute length so the scan stays linear on hostile input.
17
16
  const SCRIPT_TAG_RE = /<script\b[^<>]{0,4096}>/gi;
18
17
  const SRC_ATTR_RE = /\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/i;
19
18
  const STAGEPASS_SRC_RE =
20
19
  /^(?:https?:)?\/\/(cdn\.jsdelivr\.net\/npm|unpkg\.com)\/@stagepass\/(loader|modules)(?:@([0-9A-Za-z.^~_-]+))?\/dist\/([a-z]+)(?:\.min)?\.js(?:[?#].*)?$/i;
21
20
 
22
21
  /**
23
- * Normalize a live site input (host or https URL) to an https URL.
24
- * Rejects http, wildcards, credentials, and invalid hosts.
25
- *
22
+ * True when the raw URL names a port (`:443`/`:0443` included).
23
+ * new URL drops default ports; read authority from the raw string before new URL.
24
+ * @param {string} input
25
+ * @returns {boolean}
26
+ */
27
+ function hasExplicitPort(input) {
28
+ const s = String(input == null ? '' : input)
29
+ .replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g, '')
30
+ .replace(/[\t\n\r]/g, '')
31
+ .replace(/\\/g, '/');
32
+ const scheme = /^[a-z][a-z0-9+.-]*:/i.exec(s);
33
+ const rest = scheme ? s.slice(scheme[0].length) : s;
34
+ // No authority without `//`.
35
+ if (!rest.startsWith('//')) return false;
36
+ const authority = rest.replace(/^\/+/, '').split(/[/?#]/, 1)[0];
37
+ const hostPort = authority.slice(authority.lastIndexOf('@') + 1);
38
+ if (hostPort.startsWith('[')) {
39
+ const end = hostPort.indexOf(']');
40
+ return end === -1 || hostPort.slice(end + 1).includes(':');
41
+ }
42
+ return hostPort.includes(':');
43
+ }
44
+
45
+ /**
46
+ * Normalize host/https URL; rejects http, wildcards, credentials, invalid hosts.
26
47
  * @param {string} input
27
48
  * @returns {{ ok: true, url: string, host: string } | { ok: false, error: string }}
28
49
  */
29
50
  export function normalizeSiteUrl(input) {
30
51
  const raw = String(input == null ? '' : input).trim();
31
52
  if (!raw) return { ok: false, error: 'No live site given.' };
53
+ const candidate = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`;
54
+ // Port check on raw string before new URL (default ports would be dropped).
55
+ if (hasExplicitPort(candidate)) {
56
+ return { ok: false, error: SITE_PORT_ERROR };
57
+ }
32
58
  let url;
33
59
  try {
34
- url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`);
60
+ url = new URL(candidate);
35
61
  } catch {
36
62
  return { ok: false, error: `Invalid site URL: ${raw}` };
37
63
  }
@@ -42,7 +68,7 @@ export function normalizeSiteUrl(input) {
42
68
  return { ok: false, error: 'Site URL must not contain credentials.' };
43
69
  }
44
70
  if (url.port) {
45
- return { ok: false, error: 'Site URL must not contain a port.' };
71
+ return { ok: false, error: SITE_PORT_ERROR };
46
72
  }
47
73
  const host = url.hostname.toLowerCase();
48
74
  const check = validateOriginEntry(host);
@@ -54,9 +80,7 @@ export function normalizeSiteUrl(input) {
54
80
  }
55
81
 
56
82
  /**
57
- * Remove `<!-- … -->` comments in linear time (a lazy regex is quadratic on
58
- * many unterminated `<!--`). An unterminated comment drops the rest.
59
- *
83
+ * Strip HTML comments in linear time (lazy regex is quadratic on unterminated `<!--`).
60
84
  * @param {string} html
61
85
  * @returns {string}
62
86
  */
@@ -78,8 +102,6 @@ function stripHtmlComments(html) {
78
102
  }
79
103
 
80
104
  /**
81
- * Parse Stagepass loader / module script tags from HTML (no execution).
82
- *
83
105
  * @param {string} html
84
106
  * @returns {{ loader: { version: string, cdn: string } | null, modules: { id: string, version: string, cdn: string }[] }}
85
107
  */
@@ -88,7 +110,6 @@ export function parseStagepassScripts(html) {
88
110
  let loader = null;
89
111
  /** @type {Map<string, { id: string, version: string, cdn: string }>} */
90
112
  const modules = new Map();
91
- // Ignore commented-out tags; the HTML is only scanned, never executed.
92
113
  const source = stripHtmlComments(String(html || ''));
93
114
 
94
115
  for (const match of source.matchAll(SCRIPT_TAG_RE)) {
@@ -115,7 +136,6 @@ export function parseStagepassScripts(html) {
115
136
  }
116
137
 
117
138
  /**
118
- * Declared-list form of detected modules (`all` wins).
119
139
  * @param {{ modules: { id: string }[] }} detection
120
140
  * @returns {string[]}
121
141
  */
@@ -125,7 +145,6 @@ export function detectedModulesList(detection) {
125
145
  }
126
146
 
127
147
  /**
128
- * Read a response body up to `maxBytes` (truncates; never throws on size).
129
148
  * @param {Response} res
130
149
  * @param {number} maxBytes
131
150
  */
@@ -153,9 +172,7 @@ async function readCapped(res, maxBytes) {
153
172
  }
154
173
 
155
174
  /**
156
- * Fetch a live page and detect Stagepass scripts.
157
- *
158
- * @param {string} siteInput host or https URL
175
+ * @param {string} siteInput
159
176
  * @param {object} [deps]
160
177
  * @param {typeof fetch} [deps.fetch]
161
178
  * @param {number} [deps.timeoutMs]
@@ -200,6 +217,10 @@ export async function detectSite(siteInput, deps = {}) {
200
217
  if (next.username || next.password) {
201
218
  return { ok: false, url: current, error: 'Redirect URL contains credentials.' };
202
219
  }
220
+ // Port check on raw Location before following (URL drops default ports).
221
+ if (next.port || hasExplicitPort(location)) {
222
+ return { ok: false, url: current, error: 'Redirect URL contains a port and was not followed.' };
223
+ }
203
224
  current = next.toString();
204
225
  continue;
205
226
  }
@@ -226,7 +247,6 @@ export async function detectSite(siteInput, deps = {}) {
226
247
  }
227
248
 
228
249
  /**
229
- * One-line summary of a detection result.
230
250
  * @param {Awaited<ReturnType<typeof detectSite>>} det
231
251
  */
232
252
  export function describeDetection(det) {
@@ -7,23 +7,21 @@ import { STAGEPASS_PACKAGES_VERSION } from './versions.js';
7
7
  * @returns {string}
8
8
  */
9
9
  export function sanitizeSnippetVersion(version) {
10
- const value = String(version == null ? '' : version).trim();
11
- // Allow optional ^/~ range prefixes used in package.json; reject quotes and HTML.
12
- if (!/^[~^]?[0-9A-Za-z][0-9A-Za-z._+-]*$/.test(value)) {
10
+ const value = String(version == null ? '' : version);
11
+ // Exact stable X.Y.Z only (no prerelease, build metadata, or ranges).
12
+ if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value)) {
13
13
  throw new Error(
14
- 'Invalid version for Webflow snippets (use a semver or npm dist-tag).'
14
+ 'Invalid version for Webflow snippets (use a stable X.Y.Z semver).'
15
15
  );
16
16
  }
17
17
  return value;
18
18
  }
19
19
 
20
20
  /**
21
- * Build recommended Webflow Custom Code snippets (jsDelivr major pin @2).
22
- *
23
21
  * @param {object} options
24
- * @param {string} options.version Exact package version for data-stagepass-version / docs
25
- * @param {boolean} [options.modules] Legacy: true = inject + cookies tags
26
- * @param {string[]} [options.moduleList] Declared modules (wins over `modules`)
22
+ * @param {string} options.version
23
+ * @param {boolean} [options.modules]
24
+ * @param {string[]} [options.moduleList]
27
25
  * @returns {{ head: string, footer: string, majorPin: string, exactPin: string }}
28
26
  */
29
27
  export function buildWebflowSnippets(options) {
@@ -79,8 +77,7 @@ export function buildWebflowSnippets(options) {
79
77
  }
80
78
 
81
79
  /**
82
- * Print head/footer snippets with section labels.
83
- * @param {{ head: string, footer: string }} snippets
80
+ * @param {{ head: string, footer: string, exactPin?: string }} snippets
84
81
  * @param {(msg: string) => void} [log]
85
82
  */
86
83
  export function printWebflowSnippets(snippets, log = console.log) {
@@ -89,6 +86,6 @@ export function printWebflowSnippets(snippets, log = console.log) {
89
86
  log('\nWebflow Custom Code (Footer):');
90
87
  log(snippets.footer);
91
88
  log(
92
- `\nOptional exact pin example (instead of @2): replace @2 with the exact version (e.g. @${STAGEPASS_PACKAGES_VERSION}).`
89
+ `\nOptional exact pin example (instead of @2): replace @2 with the exact version (e.g. ${snippets.exactPin || `@${STAGEPASS_PACKAGES_VERSION}`}).`
93
90
  );
94
91
  }
@@ -0,0 +1,60 @@
1
+ import ora from 'ora';
2
+
3
+ const FALLBACK_COLUMNS = 80;
4
+ const FALLBACK_ROWS = 24;
5
+
6
+ /**
7
+ * Ora uses `stream.columns ?? 80`; a literal `0` bypasses that fallback and
8
+ * yields Infinity line clears (runaway ANSI). Floor first so values in (0,1)
9
+ * cannot become 0 after Math.floor and re-enter the unsafe path.
10
+ * @param {unknown} columns
11
+ * @param {number} [fallback]
12
+ * @returns {number}
13
+ */
14
+ export function resolveSpinnerColumns(columns, fallback = FALLBACK_COLUMNS) {
15
+ if (typeof columns !== 'number' || !Number.isFinite(columns)) return fallback;
16
+ const width = Math.floor(columns);
17
+ return width > 0 ? width : fallback;
18
+ }
19
+
20
+ /**
21
+ * @param {unknown} rows
22
+ * @param {number} [fallback]
23
+ * @returns {number}
24
+ */
25
+ export function resolveSpinnerRows(rows, fallback = FALLBACK_ROWS) {
26
+ if (typeof rows !== 'number' || !Number.isFinite(rows)) return fallback;
27
+ const value = Math.floor(rows);
28
+ return value > 0 ? value : fallback;
29
+ }
30
+
31
+ /**
32
+ * Always wrap: TTY geometry can change after spinner creation (e.g. 80→0).
33
+ * @param {NodeJS.WritableStream & { columns?: number, rows?: number, isTTY?: boolean }} stream
34
+ */
35
+ export function withSafeGeometry(stream) {
36
+ return new Proxy(stream, {
37
+ get(target, prop, receiver) {
38
+ if (prop === 'columns') return resolveSpinnerColumns(target.columns);
39
+ if (prop === 'rows') return resolveSpinnerRows(target.rows);
40
+ const value = Reflect.get(target, prop, receiver);
41
+ return typeof value === 'function' ? value.bind(target) : value;
42
+ },
43
+ });
44
+ }
45
+
46
+ /**
47
+ * Create an ora spinner that never treats TTY width 0/NaN/Infinity as valid.
48
+ * Positive finite TTY geometry stays positive; live resizes are re-checked.
49
+ * @param {string} [text]
50
+ * @param {import('ora').Options} [options]
51
+ */
52
+ export function createSpinner(text = '', options = {}) {
53
+ const stream = options.stream ?? process.stderr;
54
+ const safeStream = withSafeGeometry(stream);
55
+ return ora({
56
+ ...options,
57
+ text,
58
+ stream: safeStream,
59
+ });
60
+ }
@@ -6,7 +6,7 @@
6
6
  * `stagepass upgrade` only writes ranges a published version satisfies.
7
7
  * A monorepo test keeps this in sync with packages/loader and packages/modules.
8
8
  */
9
- export const STAGEPASS_PACKAGES_VERSION = '2.2.0';
9
+ export const STAGEPASS_PACKAGES_VERSION = '2.2.2';
10
10
 
11
11
  /**
12
12
  * Major caret range for a version (e.g. 2.2.0 → ^2), matching the `@2` CDN