@stagepass/cli 2.2.6 → 2.3.0-beta.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.
Files changed (50) hide show
  1. package/README.md +61 -13
  2. package/TESTING-macos.md +35 -8
  3. package/bin/index.js +4 -1
  4. package/package.json +9 -8
  5. package/src/cli.js +62 -7
  6. package/src/commands/certs.js +375 -19
  7. package/src/commands/daemon.js +75 -7
  8. package/src/commands/dev.js +419 -0
  9. package/src/commands/link.js +66 -25
  10. package/src/commands/new.js +397 -41
  11. package/src/commands/npm-run.js +8 -0
  12. package/src/commands/reload.js +2 -2
  13. package/src/commands/setup.js +5 -5
  14. package/src/commands/start.js +386 -83
  15. package/src/commands/stop.js +50 -31
  16. package/src/commands/unlink.js +8 -6
  17. package/src/commands/upgrade.js +51 -12
  18. package/src/lib/apply-site-block.js +48 -0
  19. package/src/lib/autostart.js +300 -3
  20. package/src/lib/caddyfile.js +72 -13
  21. package/src/lib/cdn-snippets.js +145 -3
  22. package/src/lib/certs.js +334 -47
  23. package/src/lib/dev-port.js +45 -0
  24. package/src/lib/doctor-site.js +61 -5
  25. package/src/lib/doctor.js +48 -4
  26. package/src/lib/ensure-running.js +89 -0
  27. package/src/lib/exec.js +72 -24
  28. package/src/lib/live-server.js +484 -0
  29. package/src/lib/node-engine.js +55 -0
  30. package/src/lib/notify.js +62 -0
  31. package/src/lib/origins.js +27 -5
  32. package/src/lib/package-versions.js +9 -0
  33. package/src/lib/paths.js +18 -0
  34. package/src/lib/php-fpm.js +33 -0
  35. package/src/lib/project-sync.js +165 -20
  36. package/src/lib/projects.js +137 -7
  37. package/src/lib/prompts.js +19 -0
  38. package/src/lib/registry.js +27 -6
  39. package/src/lib/scaffold.js +288 -11
  40. package/src/lib/site-detect.js +78 -25
  41. package/src/lib/snippets.js +14 -11
  42. package/src/lib/spinner.js +60 -0
  43. package/src/lib/versions.js +20 -8
  44. package/templates/project/AGENTS.md.tmpl +4 -3
  45. package/templates/project/README.md.tmpl +35 -6
  46. package/templates/project/api/README.md.tmpl +7 -0
  47. package/templates/project/examples/php/README.md.tmpl +18 -0
  48. package/templates/project/examples/php/form.php +105 -0
  49. package/templates/project/examples/php/proxy.php +171 -0
  50. package/templates/project/scripts/build.mjs +200 -37
@@ -3,7 +3,7 @@ import { fileURLToPath } from 'node:url';
3
3
  import { buildWebflowSnippets } from './snippets.js';
4
4
  import { CURSOR_RULE_PATH, buildCursorRule, buildManagedBlock } from './ai-guide.js';
5
5
  import { typesForModules } from './project-modules.js';
6
- import { STAGEPASS_PACKAGES_VERSION, packagesRange } from './versions.js';
6
+ import { LOADER_VERSION, packagesRange } from './versions.js';
7
7
 
8
8
  const __filename = fileURLToPath(import.meta.url);
9
9
  const __dirname = path.dirname(__filename);
@@ -46,6 +46,25 @@ export function scaffoldTemplateMap(lang, styles) {
46
46
  ];
47
47
  }
48
48
 
49
+ /**
50
+ * Extra files when PHP is enabled for the project.
51
+ * @param {{ php?: boolean, phpExamples?: boolean }} options
52
+ * @returns {{ template: string, out: string }[]}
53
+ */
54
+ export function scaffoldPhpTemplateMap(options = {}) {
55
+ if (options.php !== true) return [];
56
+ /** @type {{ template: string, out: string }[]} */
57
+ const files = [{ template: 'api/README.md.tmpl', out: 'api/README.md' }];
58
+ if (options.phpExamples === true) {
59
+ files.push(
60
+ { template: 'examples/php/form.php', out: 'examples/php/form.php' },
61
+ { template: 'examples/php/proxy.php', out: 'examples/php/proxy.php' },
62
+ { template: 'examples/php/README.md.tmpl', out: 'examples/php/README.md' }
63
+ );
64
+ }
65
+ return files;
66
+ }
67
+
49
68
  /**
50
69
  * @typedef {object} ScaffoldOptions
51
70
  * @property {string} name
@@ -55,7 +74,10 @@ export function scaffoldTemplateMap(lang, styles) {
55
74
  * @property {'scss'|'css'} styles
56
75
  * @property {boolean} modules Add @stagepass/modules to devDependencies
57
76
  * @property {string[]} [siteModules] Declared modules the Webflow site loads (stagepass.json)
58
- * @property {string} [origin] Live site host (stagepass.json `origin`)
77
+ * @property {string} [origin] Staging / primary live host (stagepass.json `origin`)
78
+ * @property {string} [production] Optional production host (stagepass.json `production`)
79
+ * @property {boolean} [php] Enable PHP FastCGI for the linked .sp site (default false for new)
80
+ * @property {boolean} [phpExamples] Include examples/php samples (requires php)
59
81
  * @property {boolean} git
60
82
  * @property {string} [remote]
61
83
  * @property {boolean} install
@@ -72,7 +94,7 @@ export function scaffoldTemplateMap(lang, styles) {
72
94
  export function buildPackageJson(options) {
73
95
  // Never derive the range from the CLI or target version: a release can be
74
96
  // staged but unpublished (ETARGET). The major range matches the @2 embeds.
75
- const range = options.packagesRange || packagesRange(STAGEPASS_PACKAGES_VERSION);
97
+ const range = options.packagesRange || packagesRange(LOADER_VERSION);
76
98
  const isTs = options.lang === 'ts';
77
99
  const useSass = options.styles === 'scss';
78
100
 
@@ -102,6 +124,8 @@ export function buildPackageJson(options) {
102
124
  scripts: {
103
125
  build: 'node scripts/build.mjs',
104
126
  watch: 'node scripts/build.mjs --watch',
127
+ // Prefer `stagepass dev` for live reload on the linked .sp domain.
128
+ dev: 'npm run watch',
105
129
  },
106
130
  devDependencies,
107
131
  };
@@ -121,6 +145,23 @@ export function applyTemplate(source, vars) {
121
145
  });
122
146
  }
123
147
 
148
+ /**
149
+ * Extra JSON lines for stagepass.json (leading commas / newlines).
150
+ * @param {ScaffoldOptions} options
151
+ */
152
+ export function buildStagepassExtraLines(options) {
153
+ const lines = [];
154
+ if (options.origin) {
155
+ lines.push(`\n "origin": ${JSON.stringify(options.origin)},`);
156
+ }
157
+ if (options.production) {
158
+ lines.push(`\n "production": ${JSON.stringify(options.production)},`);
159
+ }
160
+ // Always record php for new projects so link/doctor can tell intentional off from legacy.
161
+ lines.push(`\n "php": ${options.php === true ? 'true' : 'false'},`);
162
+ return lines.join('');
163
+ }
164
+
124
165
  /**
125
166
  * Plan files to write for a scaffold (relative paths → contents).
126
167
  * @param {ScaffoldOptions} options
@@ -129,12 +170,14 @@ export function applyTemplate(source, vars) {
129
170
  * @returns {Promise<{ relativePath: string, contents: string }[]>}
130
171
  */
131
172
  export async function planScaffoldFiles(options, deps = {}) {
132
- const version = options.loaderVersion || STAGEPASS_PACKAGES_VERSION;
173
+ const version = options.loaderVersion || LOADER_VERSION;
133
174
  const isTs = options.lang === 'ts';
134
175
  const useSass = options.styles === 'scss';
135
176
  const entryJs = isTs ? 'src/main.ts' : 'src/main.js';
136
177
  const entryCss = useSass ? 'src/styles.scss' : 'src/styles.css';
137
178
  const configFile = isTs ? 'tsconfig.json' : 'jsconfig.json';
179
+ const php = options.php === true;
180
+ const stagingHost = options.origin || `${options.name}.webflow.io`;
138
181
 
139
182
  const siteModules = Array.isArray(options.siteModules) ? options.siteModules : [];
140
183
  const snippets = buildWebflowSnippets({
@@ -152,7 +195,7 @@ export async function planScaffoldFiles(options, deps = {}) {
152
195
  LANG: options.lang,
153
196
  STYLES: options.styles,
154
197
  MODULES_JSON: JSON.stringify(siteModules),
155
- ORIGIN_LINE: options.origin ? `\n "origin": ${JSON.stringify(options.origin)},` : '',
198
+ ORIGIN_LINE: buildStagepassExtraLines(options),
156
199
  TYPES_JSON: JSON.stringify(types),
157
200
  TYPES_INLINE: JSON.stringify(types).replace(/","/g, '", "'),
158
201
  STAGEPASS_BLOCK: buildManagedBlock(siteModules),
@@ -163,6 +206,25 @@ export async function planScaffoldFiles(options, deps = {}) {
163
206
  ENTRY_CSS: entryCss,
164
207
  USE_SASS: useSass ? 'true' : 'false',
165
208
  CONFIG_FILE: configFile,
209
+ STAGING_HOST: stagingHost,
210
+ PRODUCTION_HOST: options.production || '',
211
+ PHP_ENABLED: php ? 'true' : 'false',
212
+ PHP_SECTION: php
213
+ ? [
214
+ '## PHP',
215
+ '',
216
+ 'This project enables PHP for the linked `.sp` site (`php_fastcgi`). Put handlers under `api/`.',
217
+ options.phpExamples
218
+ ? 'Optional samples live in `examples/php/` (copy or adapt; do not expose secrets).'
219
+ : 'Optional samples: re-run scaffolding with `--php --php-examples`, or copy from the Stagepass docs.',
220
+ '',
221
+ ].join('\n')
222
+ : [
223
+ '## PHP',
224
+ '',
225
+ 'PHP is **off** for this project (no `php_fastcgi` in the Caddy site block). Enable later by setting `"php": true` in `stagepass.json` and re-running `stagepass link`.',
226
+ '',
227
+ ].join('\n'),
166
228
  };
167
229
 
168
230
  const readTemplate =
@@ -180,7 +242,10 @@ export async function planScaffoldFiles(options, deps = {}) {
180
242
  contents: `${JSON.stringify(pkg, null, 2)}\n`,
181
243
  });
182
244
 
183
- const templateMap = scaffoldTemplateMap(options.lang, options.styles);
245
+ const templateMap = [
246
+ ...scaffoldTemplateMap(options.lang, options.styles),
247
+ ...scaffoldPhpTemplateMap(options),
248
+ ];
184
249
 
185
250
  for (const item of templateMap) {
186
251
  const raw = await readTemplate(item.template);
@@ -198,19 +263,231 @@ export async function planScaffoldFiles(options, deps = {}) {
198
263
  }
199
264
 
200
265
  /**
201
- * List relative paths that already exist and would be overwritten.
266
+ * List relative paths that block scaffolding: existing files, non-directory
267
+ * intermediate segments, or any symlink on the path within the target dir.
268
+ * Uses lstat so symlinks are never followed.
269
+ *
202
270
  * @param {string} targetDir
203
271
  * @param {{ relativePath: string }[]} files
204
- * @param {{ pathExists: (p: string) => Promise<boolean> }} fs
272
+ * @param {{ lstat: (p: string) => Promise<import('node:fs').Stats> }} fs
205
273
  */
206
274
  export async function findConflicts(targetDir, files, fs) {
207
275
  /** @type {string[]} */
208
276
  const conflicts = [];
277
+ const seen = new Set();
209
278
  for (const file of files) {
210
- const abs = path.join(targetDir, file.relativePath);
211
- if (await fs.pathExists(abs)) {
212
- conflicts.push(file.relativePath);
279
+ const parts = String(file.relativePath || '')
280
+ .split(/[\\/]/)
281
+ .filter(Boolean);
282
+ let cur = targetDir;
283
+ for (let i = 0; i < parts.length; i++) {
284
+ cur = path.join(cur, parts[i]);
285
+ const rel = parts.slice(0, i + 1).join('/');
286
+ if (seen.has(rel)) {
287
+ if (conflicts.includes(rel)) break;
288
+ continue;
289
+ }
290
+ let st;
291
+ try {
292
+ st = await fs.lstat(cur);
293
+ } catch (err) {
294
+ if (err && /** @type {{ code?: string }} */ (err).code === 'ENOENT') break;
295
+ throw err;
296
+ }
297
+ const isLast = i === parts.length - 1;
298
+ if (st.isSymbolicLink()) {
299
+ conflicts.push(rel);
300
+ seen.add(rel);
301
+ break;
302
+ }
303
+ if (isLast) {
304
+ conflicts.push(rel);
305
+ seen.add(rel);
306
+ break;
307
+ }
308
+ if (!st.isDirectory()) {
309
+ conflicts.push(rel);
310
+ seen.add(rel);
311
+ break;
312
+ }
313
+ seen.add(rel);
213
314
  }
214
315
  }
215
316
  return conflicts;
216
317
  }
318
+
319
+ /**
320
+ * Ensure targetDir and its ancestors are not files (and target is not a symlink).
321
+ * @param {string} targetDir
322
+ * @param {{ lstat: (p: string) => Promise<import('node:fs').Stats> }} fs
323
+ * @returns {Promise<{ ok: true } | { ok: false, error: string }>}
324
+ */
325
+ export async function assertScaffoldParentPath(targetDir, fs) {
326
+ const resolved = path.resolve(targetDir);
327
+ let cur = resolved;
328
+ for (;;) {
329
+ let st;
330
+ try {
331
+ st = await fs.lstat(cur);
332
+ } catch (err) {
333
+ const code = err && /** @type {{ code?: string }} */ (err).code;
334
+ if (code === 'ENOENT' || code === 'ENOTDIR') {
335
+ // Missing path, or an ancestor is a file (ENOTDIR when walking through it).
336
+ if (code === 'ENOTDIR') {
337
+ const parent = path.dirname(cur);
338
+ return {
339
+ ok: false,
340
+ error: `Parent path is a file, not a directory: ${parent === cur ? cur : parent}`,
341
+ };
342
+ }
343
+ const next = path.dirname(cur);
344
+ if (next === cur) break;
345
+ cur = next;
346
+ continue;
347
+ }
348
+ throw err;
349
+ }
350
+ if (cur === resolved) {
351
+ if (st.isSymbolicLink()) {
352
+ return { ok: false, error: `Target path is a symlink: ${cur}` };
353
+ }
354
+ if (st.isFile()) {
355
+ return { ok: false, error: `Target path is a file, not a directory: ${cur}` };
356
+ }
357
+ if (!st.isDirectory()) {
358
+ return { ok: false, error: `Target path is not a directory: ${cur}` };
359
+ }
360
+ } else if (st.isFile()) {
361
+ return { ok: false, error: `Parent path is a file, not a directory: ${cur}` };
362
+ } else if (!st.isDirectory() && !st.isSymbolicLink()) {
363
+ return { ok: false, error: `Parent path is not a directory: ${cur}` };
364
+ }
365
+ const next = path.dirname(cur);
366
+ if (next === cur) break;
367
+ cur = next;
368
+ }
369
+ return { ok: true };
370
+ }
371
+
372
+ /**
373
+ * Remove paths created by this scaffold run (reverse order). Never touches
374
+ * pre-existing files. When the target dir itself was created, remove it entirely.
375
+ *
376
+ * @param {string[]} created
377
+ * @param {string | null} createdTargetDir
378
+ * @param {{ remove: (p: string) => Promise<void> }} fs
379
+ */
380
+ export async function rollbackScaffold(created, createdTargetDir, fs) {
381
+ if (createdTargetDir) {
382
+ try {
383
+ await fs.remove(createdTargetDir);
384
+ } catch {
385
+ /* best effort */
386
+ }
387
+ return;
388
+ }
389
+ for (const p of [...created].reverse()) {
390
+ try {
391
+ await fs.remove(p);
392
+ } catch {
393
+ /* best effort */
394
+ }
395
+ }
396
+ }
397
+
398
+ /**
399
+ * Create missing directories under targetRoot and record them for rollback.
400
+ * @param {string} dir
401
+ * @param {string} targetRoot
402
+ * @param {string[]} created
403
+ * @param {object} fs
404
+ */
405
+ async function ensureDirTracked(dir, targetRoot, created, fs) {
406
+ const resolved = path.resolve(dir);
407
+ /** @type {string[]} */
408
+ const missing = [];
409
+ let cur = resolved;
410
+ while (cur.startsWith(targetRoot + path.sep)) {
411
+ try {
412
+ await fs.lstat(cur);
413
+ break;
414
+ } catch (err) {
415
+ if (!(err && /** @type {{ code?: string }} */ (err).code === 'ENOENT')) throw err;
416
+ missing.push(cur);
417
+ }
418
+ const next = path.dirname(cur);
419
+ if (next === cur) break;
420
+ cur = next;
421
+ }
422
+ for (const p of missing.reverse()) {
423
+ await fs.mkdir(p);
424
+ created.push(p);
425
+ }
426
+ }
427
+
428
+ /**
429
+ * Write scaffold files with containment checks and rollback on failure.
430
+ *
431
+ * @param {string} targetDir
432
+ * @param {{ relativePath: string, contents: string }[]} files
433
+ * @param {object} fs fs-extra-like
434
+ * @returns {Promise<{ ok: true, created: string[], createdTargetDir: string | null } | { ok: false, error: string, errorObj?: unknown }>}
435
+ */
436
+ export async function writeScaffoldFiles(targetDir, files, fs) {
437
+ const resolvedTarget = path.resolve(targetDir);
438
+ /** @type {string[]} */
439
+ const created = [];
440
+ let createdTargetDir = /** @type {string | null} */ (null);
441
+ let targetExisted = false;
442
+ try {
443
+ await fs.lstat(resolvedTarget);
444
+ targetExisted = true;
445
+ } catch (err) {
446
+ if (!(err && /** @type {{ code?: string }} */ (err).code === 'ENOENT')) {
447
+ return { ok: false, error: err instanceof Error ? err.message : String(err), errorObj: err };
448
+ }
449
+ }
450
+
451
+ const fail = async (error, errorObj) => {
452
+ await rollbackScaffold(created, createdTargetDir, fs);
453
+ return { ok: false, error, errorObj };
454
+ };
455
+
456
+ try {
457
+ if (!targetExisted) {
458
+ await fs.ensureDir(resolvedTarget);
459
+ createdTargetDir = resolvedTarget;
460
+ created.push(resolvedTarget);
461
+ }
462
+
463
+ const realTarget = await fs.realpath(resolvedTarget);
464
+
465
+ for (const file of files) {
466
+ const abs = path.resolve(resolvedTarget, file.relativePath);
467
+ const relToTarget = path.relative(resolvedTarget, abs);
468
+ if (
469
+ relToTarget.startsWith('..') ||
470
+ path.isAbsolute(relToTarget) ||
471
+ relToTarget.split(path.sep).includes('..')
472
+ ) {
473
+ return fail(`Refusing to write outside project directory: ${file.relativePath}`);
474
+ }
475
+
476
+ await ensureDirTracked(path.dirname(abs), resolvedTarget, created, fs);
477
+
478
+ const realParent = await fs.realpath(path.dirname(abs));
479
+ const realAbs = path.join(realParent, path.basename(abs));
480
+ const relReal = path.relative(realTarget, realAbs);
481
+ if (relReal.startsWith('..') || path.isAbsolute(relReal)) {
482
+ return fail(`Refusing to write outside project directory: ${file.relativePath}`);
483
+ }
484
+
485
+ await fs.writeFile(abs, file.contents, 'utf8');
486
+ created.push(abs);
487
+ }
488
+
489
+ return { ok: true, created, createdTargetDir };
490
+ } catch (err) {
491
+ return fail(err instanceof Error ? err.message : String(err), err);
492
+ }
493
+ }
@@ -1,9 +1,12 @@
1
1
  /**
2
- * Detect Stagepass scripts on a live Webflow site.
3
- * Public GET only: https, no cookies/credentials; HTML scanned, never executed.
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.
4
7
  */
5
8
 
6
- import { validateOriginEntry } from './origins.js';
9
+ import { HOST_WHITESPACE_ERROR, rejectWhitespaceOrControls, validateOriginEntry } from './origins.js';
7
10
  import { MODULE_CHOICES, normalizeModulesList } from './project-modules.js';
8
11
 
9
12
  export const DETECT_TIMEOUT_MS = 5000;
@@ -11,24 +14,33 @@ export const DETECT_MAX_BYTES = 2 * 1024 * 1024;
11
14
  export const DETECT_MAX_REDIRECTS = 3;
12
15
  export const SITE_PORT_ERROR =
13
16
  'Site URL must not contain a port, also not :443. Use the host only, e.g. my-site.webflow.io.';
17
+ export { HOST_WHITESPACE_ERROR };
14
18
 
15
- // Bound attribute length so the scan stays linear on hostile input.
19
+ // Bounded attribute run keeps the scan linear on hostile input.
16
20
  const SCRIPT_TAG_RE = /<script\b[^<>]{0,4096}>/gi;
17
21
  const SRC_ATTR_RE = /\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/i;
18
- const STAGEPASS_SRC_RE =
19
- /^(?:https?:)?\/\/(cdn\.jsdelivr\.net\/npm|unpkg\.com)\/@stagepass\/(loader|modules)(?:@([0-9A-Za-z.^~_-]+))?\/dist\/([a-z]+)(?:\.min)?\.js(?:[?#].*)?$/i;
22
+ // CDN /dist/<file>.js or package-root URLs (optional slash/query); root via package `main`.
23
+ const STAGEPASS_CDN_RE =
24
+ /^(?:https?:)?\/\/(cdn\.jsdelivr\.net\/npm|unpkg\.com)\/@stagepass\/(loader|modules)(?:@([0-9A-Za-z.^~_-]+))?(?:\/dist\/([a-z]+)(?:\.min)?\.js)?\/?(?:[?#].*)?$/i;
25
+ // Self-hosted build filenames (need Stagepass path or data-* hint).
26
+ const STAGEPASS_FILE_RE = /(?:^|\/)(loader|inject|cookies|maintenance|all)(?:\.min)?\.js$/i;
27
+ // `…/stagepass/…` always; `…/@stagepass/…` only for relative src (blocks foreign-host spoofs).
28
+ const STAGEPASS_PATH_HINT_RE = /(?:^|\/)(stagepass\/|@stagepass(?:\/|$))/i;
29
+ const DATA_STAGEPASS_ATTR_RE = /\sdata-stagepass(?:-[a-z0-9-]+)?\s*=/i;
30
+ const LOADER_CONFIG_ATTR_RE =
31
+ /\sdata-stagepass-(?:version|session-hours|mute-console|cachebust|staging-hosts|alias|live-src|flag-base)\s*=/i;
32
+ const VERSION_ATTR_RE = /\sdata-stagepass-version\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/i;
33
+ const SAFE_VERSION_RE = /^[0-9A-Za-z][0-9A-Za-z.^~_-]*$/;
20
34
 
21
35
  /**
22
36
  * True when the raw URL names a port (`:443`/`:0443` included).
23
37
  * new URL drops default ports; read authority from the raw string before new URL.
38
+ * Caller must already reject whitespace/controls; do not strip them here.
24
39
  * @param {string} input
25
40
  * @returns {boolean}
26
41
  */
27
42
  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, '/');
43
+ const s = String(input == null ? '' : input).replace(/\\/g, '/');
32
44
  const scheme = /^[a-z][a-z0-9+.-]*:/i.exec(s);
33
45
  const rest = scheme ? s.slice(scheme[0].length) : s;
34
46
  // No authority without `//`.
@@ -43,13 +55,18 @@ function hasExplicitPort(input) {
43
55
  }
44
56
 
45
57
  /**
46
- * Normalize host/https URL; rejects http, wildcards, credentials, invalid hosts.
58
+ * Normalize a live site input (host or https URL) to an https URL.
59
+ * Rejects http, wildcards, credentials, whitespace/controls, and invalid hosts.
60
+ *
47
61
  * @param {string} input
48
62
  * @returns {{ ok: true, url: string, host: string } | { ok: false, error: string }}
49
63
  */
50
64
  export function normalizeSiteUrl(input) {
51
- const raw = String(input == null ? '' : input).trim();
65
+ const raw = String(input == null ? '' : input);
52
66
  if (!raw) return { ok: false, error: 'No live site given.' };
67
+ // Reject before trim / new URL (WHATWG would drop tab/LF/CR in the host).
68
+ const ws = rejectWhitespaceOrControls(raw, 'Site URL');
69
+ if (!ws.ok) return { ok: false, error: HOST_WHITESPACE_ERROR };
53
70
  const candidate = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`;
54
71
  // Port check on raw string before new URL (default ports would be dropped).
55
72
  if (hasExplicitPort(candidate)) {
@@ -80,7 +97,9 @@ export function normalizeSiteUrl(input) {
80
97
  }
81
98
 
82
99
  /**
83
- * Strip HTML comments in linear time (lazy regex is quadratic on unterminated `<!--`).
100
+ * Remove `<!-- … -->` comments in linear time (a lazy regex is quadratic on
101
+ * many unterminated `<!--`). An unterminated comment drops the rest.
102
+ *
84
103
  * @param {string} html
85
104
  * @returns {string}
86
105
  */
@@ -102,6 +121,8 @@ function stripHtmlComments(html) {
102
121
  }
103
122
 
104
123
  /**
124
+ * Parse Stagepass loader / module script tags from HTML (no execution).
125
+ *
105
126
  * @param {string} html
106
127
  * @returns {{ loader: { version: string, cdn: string } | null, modules: { id: string, version: string, cdn: string }[] }}
107
128
  */
@@ -110,32 +131,60 @@ export function parseStagepassScripts(html) {
110
131
  let loader = null;
111
132
  /** @type {Map<string, { id: string, version: string, cdn: string }>} */
112
133
  const modules = new Map();
134
+ const q = (m) => (m?.[1] ?? m?.[2] ?? m?.[3] ?? '').trim();
135
+ const take = (file, version, cdn) => {
136
+ if (file === 'loader') {
137
+ if (!loader) loader = { version, cdn };
138
+ } else if (MODULE_CHOICES.includes(file) && !modules.has(file)) {
139
+ modules.set(file, { id: file, version, cdn });
140
+ }
141
+ };
142
+ // Ignore commented-out tags; the HTML is only scanned, never executed.
113
143
  const source = stripHtmlComments(String(html || ''));
114
144
 
115
145
  for (const match of source.matchAll(SCRIPT_TAG_RE)) {
116
146
  const tag = match[0];
117
147
  const attr = SRC_ATTR_RE.exec(tag);
118
148
  if (!attr) continue;
119
- const src = (attr[1] ?? attr[2] ?? attr[3] ?? '').trim();
120
- const m = STAGEPASS_SRC_RE.exec(src);
121
- if (!m) continue;
122
- const cdn = m[1].toLowerCase().startsWith('unpkg') ? 'unpkg' : 'jsdelivr';
123
- const pkg = m[2].toLowerCase();
124
- const version = m[3] || 'latest';
125
- const file = m[4].toLowerCase();
126
- if (pkg === 'loader') {
127
- if (file === 'loader' && !loader) loader = { version, cdn };
149
+ const src = q(attr);
150
+
151
+ const cdnMatch = STAGEPASS_CDN_RE.exec(src);
152
+ if (cdnMatch) {
153
+ const pkg = cdnMatch[2].toLowerCase();
154
+ // Package-root: packages/*/package.json `main` (no CDN exports override).
155
+ const file = (cdnMatch[4] || (pkg === 'modules' ? 'all' : 'loader')).toLowerCase();
156
+ if (pkg === 'loader' ? file === 'loader' : file !== 'loader') {
157
+ take(
158
+ file,
159
+ cdnMatch[3] || 'latest',
160
+ cdnMatch[1].toLowerCase().startsWith('unpkg') ? 'unpkg' : 'jsdelivr'
161
+ );
162
+ }
128
163
  continue;
129
164
  }
130
- if (MODULE_CHOICES.includes(file) && !modules.has(file)) {
131
- modules.set(file, { id: file, version, cdn });
165
+
166
+ // Self-hosted: known filename + path/data hint, or renamed file with loader-config attrs.
167
+ const absolute = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(src);
168
+ const pathname = src.replace(/^(?:[a-z][a-z0-9+.-]*:)?\/\/[^/?#]*/i, '').split(/[?#]/)[0];
169
+ if (!pathname) continue;
170
+ const fileMatch = STAGEPASS_FILE_RE.exec(pathname);
171
+ const hint = STAGEPASS_PATH_HINT_RE.exec(pathname);
172
+ const hasPathHint = hint && (hint[1].startsWith('stagepass') || !absolute);
173
+ const vraw = q(VERSION_ATTR_RE.exec(tag));
174
+ const version = SAFE_VERSION_RE.test(vraw) ? vraw : 'latest';
175
+
176
+ if (fileMatch && (hasPathHint || DATA_STAGEPASS_ATTR_RE.test(tag))) {
177
+ take(fileMatch[1].toLowerCase(), version, 'self');
178
+ continue;
132
179
  }
180
+ if (LOADER_CONFIG_ATTR_RE.test(tag) && !loader) loader = { version, cdn: 'self' };
133
181
  }
134
182
 
135
183
  return { loader, modules: [...modules.values()] };
136
184
  }
137
185
 
138
186
  /**
187
+ * Declared-list form of detected modules (`all` wins).
139
188
  * @param {{ modules: { id: string }[] }} detection
140
189
  * @returns {string[]}
141
190
  */
@@ -145,6 +194,7 @@ export function detectedModulesList(detection) {
145
194
  }
146
195
 
147
196
  /**
197
+ * Read a response body up to `maxBytes` (truncates; never throws on size).
148
198
  * @param {Response} res
149
199
  * @param {number} maxBytes
150
200
  */
@@ -172,7 +222,9 @@ async function readCapped(res, maxBytes) {
172
222
  }
173
223
 
174
224
  /**
175
- * @param {string} siteInput
225
+ * Fetch a live page and detect Stagepass scripts.
226
+ *
227
+ * @param {string} siteInput host or https URL
176
228
  * @param {object} [deps]
177
229
  * @param {typeof fetch} [deps.fetch]
178
230
  * @param {number} [deps.timeoutMs]
@@ -247,6 +299,7 @@ export async function detectSite(siteInput, deps = {}) {
247
299
  }
248
300
 
249
301
  /**
302
+ * One-line summary of a detection result.
250
303
  * @param {Awaited<ReturnType<typeof detectSite>>} det
251
304
  */
252
305
  export function describeDetection(det) {
@@ -1,5 +1,5 @@
1
1
  import { normalizeModulesList } from './project-modules.js';
2
- import { STAGEPASS_PACKAGES_VERSION } from './versions.js';
2
+ import { LOADER_VERSION, MODULES_VERSION } from './versions.js';
3
3
 
4
4
  /**
5
5
  * Safe token for CDN pins and data-stagepass-version (blocks HTML/attr injection).
@@ -7,25 +7,27 @@ 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);
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)) {
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)) {
13
13
  throw new Error(
14
- 'Invalid version for Webflow snippets (use a stable X.Y.Z semver).'
14
+ 'Invalid version for Webflow snippets (use a semver or npm dist-tag).'
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
+ *
21
23
  * @param {object} options
22
- * @param {string} options.version
23
- * @param {boolean} [options.modules]
24
- * @param {string[]} [options.moduleList]
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`)
25
27
  * @returns {{ head: string, footer: string, majorPin: string, exactPin: string }}
26
28
  */
27
29
  export function buildWebflowSnippets(options) {
28
- const version = sanitizeSnippetVersion(options.version || STAGEPASS_PACKAGES_VERSION);
30
+ const version = sanitizeSnippetVersion(options.version || LOADER_VERSION);
29
31
  /** @type {string[]} */
30
32
  let moduleFiles = [];
31
33
  if (Array.isArray(options.moduleList)) {
@@ -77,7 +79,8 @@ export function buildWebflowSnippets(options) {
77
79
  }
78
80
 
79
81
  /**
80
- * @param {{ head: string, footer: string, exactPin?: string }} snippets
82
+ * Print head/footer snippets with section labels.
83
+ * @param {{ head: string, footer: string }} snippets
81
84
  * @param {(msg: string) => void} [log]
82
85
  */
83
86
  export function printWebflowSnippets(snippets, log = console.log) {
@@ -86,6 +89,6 @@ export function printWebflowSnippets(snippets, log = console.log) {
86
89
  log('\nWebflow Custom Code (Footer):');
87
90
  log(snippets.footer);
88
91
  log(
89
- `\nOptional exact pin example (instead of @2): replace @2 with the exact version (e.g. ${snippets.exactPin || `@${STAGEPASS_PACKAGES_VERSION}`}).`
92
+ `\nOptional exact pin example (instead of @2): loader @${LOADER_VERSION}, modules @${MODULES_VERSION}.`
90
93
  );
91
94
  }