@stagepass/cli 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +87 -7
  2. package/TESTING-macos.md +58 -0
  3. package/bin/index.js +2 -2
  4. package/package.json +3 -1
  5. package/src/cli.js +204 -0
  6. package/src/commands/autostart.js +85 -0
  7. package/src/commands/certs.js +185 -0
  8. package/src/commands/daemon.js +126 -0
  9. package/src/commands/doctor.js +57 -0
  10. package/src/commands/new.js +455 -0
  11. package/src/commands/npm-run.js +84 -0
  12. package/src/commands/stop.js +15 -0
  13. package/src/commands/upgrade.js +276 -0
  14. package/src/lib/ai-guide.js +161 -0
  15. package/src/lib/autostart.js +360 -0
  16. package/src/lib/cdn-snippets.js +27 -0
  17. package/src/lib/certs.js +476 -0
  18. package/src/lib/doctor-site.js +89 -0
  19. package/src/lib/doctor.js +521 -0
  20. package/src/lib/exec.js +71 -0
  21. package/src/lib/paths.js +58 -0
  22. package/src/lib/platform.js +47 -0
  23. package/src/lib/project-modules.js +98 -0
  24. package/src/lib/project-name.js +47 -0
  25. package/src/lib/project-sync.js +394 -0
  26. package/src/lib/remote-url.js +63 -0
  27. package/src/lib/scaffold.js +212 -0
  28. package/src/lib/site-detect.js +242 -0
  29. package/src/lib/snippets.js +94 -0
  30. package/src/lib/spawn.js +30 -0
  31. package/src/lib/versions.js +27 -0
  32. package/templates/project/AGENTS.md.tmpl +39 -0
  33. package/templates/project/README.md.tmpl +44 -0
  34. package/templates/project/gitignore +7 -0
  35. package/templates/project/jsconfig.json.tmpl +14 -0
  36. package/templates/project/scripts/build.mjs +110 -0
  37. package/templates/project/src/main.js.tmpl +29 -0
  38. package/templates/project/src/main.ts.tmpl +29 -0
  39. package/templates/project/src/styles.css.tmpl +8 -0
  40. package/templates/project/src/styles.scss.tmpl +8 -0
  41. package/templates/project/stagepass.json.tmpl +8 -0
  42. package/templates/project/tsconfig.json.tmpl +13 -0
@@ -0,0 +1,212 @@
1
+ import path from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { buildWebflowSnippets } from './snippets.js';
4
+ import { CURSOR_RULE_PATH, buildCursorRule, buildManagedBlock } from './ai-guide.js';
5
+ import { typesForModules } from './project-modules.js';
6
+ import { STAGEPASS_PACKAGES_VERSION, packagesRange } from './versions.js';
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = path.dirname(__filename);
10
+
11
+ /** Absolute path to packaged templates/project */
12
+ export function defaultTemplatesRoot() {
13
+ return path.join(__dirname, '../../templates/project');
14
+ }
15
+
16
+ /**
17
+ * Template file → output path. Dotfiles are stored without the leading dot
18
+ * because npm pack / publish drops `.gitignore` (and `.npmignore`) files.
19
+ * Never add a template whose name starts with `.` (a test enforces this).
20
+ *
21
+ * @param {'ts'|'js'} lang
22
+ * @param {'scss'|'css'} styles
23
+ * @returns {{ template: string, out: string }[]}
24
+ */
25
+ export function scaffoldTemplateMap(lang, styles) {
26
+ const isTs = lang === 'ts';
27
+ const useSass = styles === 'scss';
28
+ return [
29
+ { template: 'scripts/build.mjs', out: 'scripts/build.mjs' },
30
+ { template: 'gitignore', out: '.gitignore' },
31
+ { template: 'README.md.tmpl', out: 'README.md' },
32
+ { template: 'AGENTS.md.tmpl', out: 'AGENTS.md' },
33
+ { template: 'stagepass.json.tmpl', out: 'stagepass.json' },
34
+ {
35
+ template: isTs ? 'src/main.ts.tmpl' : 'src/main.js.tmpl',
36
+ out: isTs ? 'src/main.ts' : 'src/main.js',
37
+ },
38
+ {
39
+ template: useSass ? 'src/styles.scss.tmpl' : 'src/styles.css.tmpl',
40
+ out: useSass ? 'src/styles.scss' : 'src/styles.css',
41
+ },
42
+ {
43
+ template: isTs ? 'tsconfig.json.tmpl' : 'jsconfig.json.tmpl',
44
+ out: isTs ? 'tsconfig.json' : 'jsconfig.json',
45
+ },
46
+ ];
47
+ }
48
+
49
+ /**
50
+ * @typedef {object} ScaffoldOptions
51
+ * @property {string} name
52
+ * @property {string} dir Absolute or relative target directory
53
+ * @property {string} [author]
54
+ * @property {'ts'|'js'} lang
55
+ * @property {'scss'|'css'} styles
56
+ * @property {boolean} modules Add @stagepass/modules to devDependencies
57
+ * @property {string[]} [siteModules] Declared modules the Webflow site loads (stagepass.json)
58
+ * @property {string} [origin] Live site host (stagepass.json `origin`)
59
+ * @property {boolean} git
60
+ * @property {string} [remote]
61
+ * @property {boolean} install
62
+ * @property {boolean} dryRun
63
+ * @property {string} [loaderVersion] @stagepass/loader + modules version (snippets)
64
+ * @property {string} [packagesRange] Override for package.json ranges (default ^<major>.<minor>.0)
65
+ */
66
+
67
+ /**
68
+ * @param {ScaffoldOptions} options
69
+ * @returns {Record<string, string>}
70
+ */
71
+ export function buildPackageJson(options) {
72
+ const range =
73
+ options.packagesRange ||
74
+ packagesRange(options.loaderVersion || STAGEPASS_PACKAGES_VERSION);
75
+ const isTs = options.lang === 'ts';
76
+ const useSass = options.styles === 'scss';
77
+
78
+ /** @type {Record<string, string>} */
79
+ const devDependencies = {
80
+ '@stagepass/loader': range,
81
+ esbuild: '^0.25.0',
82
+ };
83
+
84
+ if (options.modules) {
85
+ devDependencies['@stagepass/modules'] = range;
86
+ }
87
+ if (isTs) {
88
+ devDependencies.typescript = '^5.6.0';
89
+ }
90
+ if (useSass) {
91
+ devDependencies.sass = '^1.80.0';
92
+ }
93
+
94
+ return {
95
+ name: options.name,
96
+ private: true,
97
+ version: '0.0.0',
98
+ description: `Stagepass project ${options.name}`,
99
+ author: options.author || '',
100
+ type: 'module',
101
+ scripts: {
102
+ build: 'node scripts/build.mjs',
103
+ watch: 'node scripts/build.mjs --watch',
104
+ },
105
+ devDependencies,
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Apply {{TOKEN}} replacements. Unknown tokens left intact.
111
+ * @param {string} source
112
+ * @param {Record<string, string>} vars
113
+ */
114
+ export function applyTemplate(source, vars) {
115
+ return source.replace(/\{\{([A-Z0-9_]+)\}\}/g, (match, key) => {
116
+ if (Object.prototype.hasOwnProperty.call(vars, key)) {
117
+ return vars[key];
118
+ }
119
+ return match;
120
+ });
121
+ }
122
+
123
+ /**
124
+ * Plan files to write for a scaffold (relative paths → contents).
125
+ * @param {ScaffoldOptions} options
126
+ * @param {object} [deps]
127
+ * @param {(rel: string) => Promise<string>} [deps.readTemplate]
128
+ * @returns {Promise<{ relativePath: string, contents: string }[]>}
129
+ */
130
+ export async function planScaffoldFiles(options, deps = {}) {
131
+ const version = options.loaderVersion || STAGEPASS_PACKAGES_VERSION;
132
+ const isTs = options.lang === 'ts';
133
+ const useSass = options.styles === 'scss';
134
+ const entryJs = isTs ? 'src/main.ts' : 'src/main.js';
135
+ const entryCss = useSass ? 'src/styles.scss' : 'src/styles.css';
136
+ const configFile = isTs ? 'tsconfig.json' : 'jsconfig.json';
137
+
138
+ const siteModules = Array.isArray(options.siteModules) ? options.siteModules : [];
139
+ const snippets = buildWebflowSnippets({
140
+ version,
141
+ moduleList: siteModules,
142
+ });
143
+ const types = typesForModules(siteModules, { modulesDependency: options.modules === true });
144
+
145
+ const vars = {
146
+ NAME: options.name,
147
+ AUTHOR: options.author || '',
148
+ LANG: options.lang,
149
+ STYLES: options.styles,
150
+ MODULES_JSON: JSON.stringify(siteModules),
151
+ ORIGIN_LINE: options.origin ? `\n "origin": ${JSON.stringify(options.origin)},` : '',
152
+ TYPES_JSON: JSON.stringify(types),
153
+ TYPES_INLINE: JSON.stringify(types).replace(/","/g, '", "'),
154
+ STAGEPASS_BLOCK: buildManagedBlock(siteModules),
155
+ LOADER_VERSION: version,
156
+ HEAD_SNIPPET: snippets.head,
157
+ FOOTER_SNIPPET: snippets.footer,
158
+ ENTRY_JS: entryJs,
159
+ ENTRY_CSS: entryCss,
160
+ USE_SASS: useSass ? 'true' : 'false',
161
+ CONFIG_FILE: configFile,
162
+ };
163
+
164
+ const readTemplate =
165
+ deps.readTemplate ||
166
+ (async () => {
167
+ throw new Error('readTemplate dependency required');
168
+ });
169
+
170
+ /** @type {{ relativePath: string, contents: string }[]} */
171
+ const files = [];
172
+
173
+ const pkg = buildPackageJson(options);
174
+ files.push({
175
+ relativePath: 'package.json',
176
+ contents: `${JSON.stringify(pkg, null, 2)}\n`,
177
+ });
178
+
179
+ const templateMap = scaffoldTemplateMap(options.lang, options.styles);
180
+
181
+ for (const item of templateMap) {
182
+ const raw = await readTemplate(item.template);
183
+ files.push({
184
+ relativePath: item.out,
185
+ contents: applyTemplate(raw, vars),
186
+ });
187
+ }
188
+
189
+ // Generated in code (not a template): npm drops dotfiles and dot folders
190
+ // are easy to lose in the published package.
191
+ files.push({ relativePath: CURSOR_RULE_PATH, contents: buildCursorRule(siteModules) });
192
+
193
+ return files;
194
+ }
195
+
196
+ /**
197
+ * List relative paths that already exist and would be overwritten.
198
+ * @param {string} targetDir
199
+ * @param {{ relativePath: string }[]} files
200
+ * @param {{ pathExists: (p: string) => Promise<boolean> }} fs
201
+ */
202
+ export async function findConflicts(targetDir, files, fs) {
203
+ /** @type {string[]} */
204
+ const conflicts = [];
205
+ for (const file of files) {
206
+ const abs = path.join(targetDir, file.relativePath);
207
+ if (await fs.pathExists(abs)) {
208
+ conflicts.push(file.relativePath);
209
+ }
210
+ }
211
+ return conflicts;
212
+ }
@@ -0,0 +1,242 @@
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.
7
+ */
8
+
9
+ import { validateOriginEntry } from './origins.js';
10
+ import { MODULE_CHOICES, normalizeModulesList } from './project-modules.js';
11
+
12
+ export const DETECT_TIMEOUT_MS = 5000;
13
+ export const DETECT_MAX_BYTES = 2 * 1024 * 1024;
14
+ export const DETECT_MAX_REDIRECTS = 3;
15
+
16
+ // Bounded attribute run keeps the scan linear on hostile input.
17
+ const SCRIPT_TAG_RE = /<script\b[^<>]{0,4096}>/gi;
18
+ const SRC_ATTR_RE = /\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/i;
19
+ const STAGEPASS_SRC_RE =
20
+ /^(?:https?:)?\/\/(cdn\.jsdelivr\.net\/npm|unpkg\.com)\/@stagepass\/(loader|modules)(?:@([0-9A-Za-z.^~_-]+))?\/dist\/([a-z]+)(?:\.min)?\.js(?:[?#].*)?$/i;
21
+
22
+ /**
23
+ * Normalize a live site input (host or https URL) to an https URL.
24
+ * Rejects http, wildcards, credentials, and invalid hosts.
25
+ *
26
+ * @param {string} input
27
+ * @returns {{ ok: true, url: string, host: string } | { ok: false, error: string }}
28
+ */
29
+ export function normalizeSiteUrl(input) {
30
+ const raw = String(input == null ? '' : input).trim();
31
+ if (!raw) return { ok: false, error: 'No live site given.' };
32
+ let url;
33
+ try {
34
+ url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`);
35
+ } catch {
36
+ return { ok: false, error: `Invalid site URL: ${raw}` };
37
+ }
38
+ if (url.protocol !== 'https:') {
39
+ return { ok: false, error: 'Live site must use https.' };
40
+ }
41
+ if (url.username || url.password) {
42
+ return { ok: false, error: 'Site URL must not contain credentials.' };
43
+ }
44
+ if (url.port) {
45
+ return { ok: false, error: 'Site URL must not contain a port.' };
46
+ }
47
+ const host = url.hostname.toLowerCase();
48
+ const check = validateOriginEntry(host);
49
+ if (!check.ok || check.value.startsWith('*.')) {
50
+ return { ok: false, error: `Not a usable site host: ${host}` };
51
+ }
52
+ const path = url.pathname && url.pathname !== '' ? url.pathname : '/';
53
+ return { ok: true, url: `https://${host}${path}`, host };
54
+ }
55
+
56
+ /**
57
+ * Remove `<!-- … -->` comments in linear time (a lazy regex is quadratic on
58
+ * many unterminated `<!--`). An unterminated comment drops the rest.
59
+ *
60
+ * @param {string} html
61
+ * @returns {string}
62
+ */
63
+ function stripHtmlComments(html) {
64
+ let out = '';
65
+ let pos = 0;
66
+ while (pos < html.length) {
67
+ const start = html.indexOf('<!--', pos);
68
+ if (start === -1) {
69
+ out += html.slice(pos);
70
+ break;
71
+ }
72
+ out += html.slice(pos, start);
73
+ const end = html.indexOf('-->', start + 4);
74
+ if (end === -1) break;
75
+ pos = end + 3;
76
+ }
77
+ return out;
78
+ }
79
+
80
+ /**
81
+ * Parse Stagepass loader / module script tags from HTML (no execution).
82
+ *
83
+ * @param {string} html
84
+ * @returns {{ loader: { version: string, cdn: string } | null, modules: { id: string, version: string, cdn: string }[] }}
85
+ */
86
+ export function parseStagepassScripts(html) {
87
+ /** @type {{ version: string, cdn: string } | null} */
88
+ let loader = null;
89
+ /** @type {Map<string, { id: string, version: string, cdn: string }>} */
90
+ const modules = new Map();
91
+ // Ignore commented-out tags; the HTML is only scanned, never executed.
92
+ const source = stripHtmlComments(String(html || ''));
93
+
94
+ for (const match of source.matchAll(SCRIPT_TAG_RE)) {
95
+ const tag = match[0];
96
+ const attr = SRC_ATTR_RE.exec(tag);
97
+ if (!attr) continue;
98
+ const src = (attr[1] ?? attr[2] ?? attr[3] ?? '').trim();
99
+ const m = STAGEPASS_SRC_RE.exec(src);
100
+ if (!m) continue;
101
+ const cdn = m[1].toLowerCase().startsWith('unpkg') ? 'unpkg' : 'jsdelivr';
102
+ const pkg = m[2].toLowerCase();
103
+ const version = m[3] || 'latest';
104
+ const file = m[4].toLowerCase();
105
+ if (pkg === 'loader') {
106
+ if (file === 'loader' && !loader) loader = { version, cdn };
107
+ continue;
108
+ }
109
+ if (MODULE_CHOICES.includes(file) && !modules.has(file)) {
110
+ modules.set(file, { id: file, version, cdn });
111
+ }
112
+ }
113
+
114
+ return { loader, modules: [...modules.values()] };
115
+ }
116
+
117
+ /**
118
+ * Declared-list form of detected modules (`all` wins).
119
+ * @param {{ modules: { id: string }[] }} detection
120
+ * @returns {string[]}
121
+ */
122
+ export function detectedModulesList(detection) {
123
+ const result = normalizeModulesList(detection.modules.map((m) => m.id));
124
+ return result.ok ? result.modules : [];
125
+ }
126
+
127
+ /**
128
+ * Read a response body up to `maxBytes` (truncates; never throws on size).
129
+ * @param {Response} res
130
+ * @param {number} maxBytes
131
+ */
132
+ async function readCapped(res, maxBytes) {
133
+ if (!res.body || typeof res.body.getReader !== 'function') {
134
+ const text = await res.text();
135
+ return text.slice(0, maxBytes);
136
+ }
137
+ const reader = res.body.getReader();
138
+ const chunks = [];
139
+ let total = 0;
140
+ while (total < maxBytes) {
141
+ const { done, value } = await reader.read();
142
+ if (done) break;
143
+ chunks.push(value);
144
+ total += value.byteLength;
145
+ }
146
+ try {
147
+ await reader.cancel();
148
+ } catch {
149
+ // ignore
150
+ }
151
+ const buf = Buffer.concat(chunks.map((c) => Buffer.from(c)));
152
+ return buf.subarray(0, maxBytes).toString('utf8');
153
+ }
154
+
155
+ /**
156
+ * Fetch a live page and detect Stagepass scripts.
157
+ *
158
+ * @param {string} siteInput host or https URL
159
+ * @param {object} [deps]
160
+ * @param {typeof fetch} [deps.fetch]
161
+ * @param {number} [deps.timeoutMs]
162
+ * @param {number} [deps.maxBytes]
163
+ * @returns {Promise<{ ok: true, url: string, loader: { version: string, cdn: string } | null, modules: { id: string, version: string, cdn: string }[], list: string[] } | { ok: false, url?: string, error: string }>}
164
+ */
165
+ export async function detectSite(siteInput, deps = {}) {
166
+ const normalized = normalizeSiteUrl(siteInput);
167
+ if (!normalized.ok) return { ok: false, error: normalized.error };
168
+
169
+ const fetchImpl = deps.fetch || globalThis.fetch;
170
+ if (typeof fetchImpl !== 'function') {
171
+ return { ok: false, url: normalized.url, error: 'fetch is not available in this Node.js version.' };
172
+ }
173
+ const timeoutMs = deps.timeoutMs ?? DETECT_TIMEOUT_MS;
174
+ const maxBytes = deps.maxBytes ?? DETECT_MAX_BYTES;
175
+ const controller = new AbortController();
176
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
177
+
178
+ let current = normalized.url;
179
+ try {
180
+ for (let hop = 0; hop <= DETECT_MAX_REDIRECTS; hop++) {
181
+ const res = await fetchImpl(current, {
182
+ method: 'GET',
183
+ redirect: 'manual',
184
+ credentials: 'omit',
185
+ signal: controller.signal,
186
+ headers: {
187
+ accept: 'text/html,application/xhtml+xml',
188
+ 'user-agent': 'stagepass-cli (site check)',
189
+ },
190
+ });
191
+ if (res.status >= 300 && res.status < 400) {
192
+ const location = res.headers.get('location');
193
+ if (!location) {
194
+ return { ok: false, url: current, error: `Redirect without Location (${res.status}).` };
195
+ }
196
+ const next = new URL(location, current);
197
+ if (next.protocol !== 'https:') {
198
+ return { ok: false, url: current, error: 'Redirect to a non-https URL was not followed.' };
199
+ }
200
+ if (next.username || next.password) {
201
+ return { ok: false, url: current, error: 'Redirect URL contains credentials.' };
202
+ }
203
+ current = next.toString();
204
+ continue;
205
+ }
206
+ if (!res.ok) {
207
+ return { ok: false, url: current, error: `Site answered HTTP ${res.status}.` };
208
+ }
209
+ const html = await readCapped(res, maxBytes);
210
+ const parsed = parseStagepassScripts(html);
211
+ return { ok: true, url: current, ...parsed, list: detectedModulesList(parsed) };
212
+ }
213
+ return { ok: false, url: current, error: `More than ${DETECT_MAX_REDIRECTS} redirects.` };
214
+ } catch (err) {
215
+ const aborted = controller.signal.aborted || (err && err.name === 'AbortError');
216
+ return {
217
+ ok: false,
218
+ url: current,
219
+ error: aborted
220
+ ? `Site did not answer within ${Math.round(timeoutMs / 1000)} s.`
221
+ : `Site not reachable: ${err instanceof Error ? err.message : String(err)}`,
222
+ };
223
+ } finally {
224
+ clearTimeout(timer);
225
+ }
226
+ }
227
+
228
+ /**
229
+ * One-line summary of a detection result.
230
+ * @param {Awaited<ReturnType<typeof detectSite>>} det
231
+ */
232
+ export function describeDetection(det) {
233
+ if (!det.ok) return det.error;
234
+ const loader = det.loader
235
+ ? `loader @${det.loader.version} (${det.loader.cdn})`
236
+ : 'no Stagepass loader';
237
+ const mods =
238
+ det.modules.length === 0
239
+ ? 'no modules'
240
+ : `modules ${det.modules.map((m) => `${m.id}@${m.version}`).join(', ')}`;
241
+ return `${loader}, ${mods}`;
242
+ }
@@ -0,0 +1,94 @@
1
+ import { normalizeModulesList } from './project-modules.js';
2
+ import { STAGEPASS_PACKAGES_VERSION } from './versions.js';
3
+
4
+ /**
5
+ * Safe token for CDN pins and data-stagepass-version (blocks HTML/attr injection).
6
+ * @param {unknown} version
7
+ * @returns {string}
8
+ */
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)) {
13
+ throw new Error(
14
+ 'Invalid version for Webflow snippets (use a semver or npm dist-tag).'
15
+ );
16
+ }
17
+ return value;
18
+ }
19
+
20
+ /**
21
+ * Build recommended Webflow Custom Code snippets (jsDelivr major pin @2).
22
+ *
23
+ * @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`)
27
+ * @returns {{ head: string, footer: string, majorPin: string, exactPin: string }}
28
+ */
29
+ export function buildWebflowSnippets(options) {
30
+ const version = sanitizeSnippetVersion(options.version || STAGEPASS_PACKAGES_VERSION);
31
+ /** @type {string[]} */
32
+ let moduleFiles = [];
33
+ if (Array.isArray(options.moduleList)) {
34
+ const parsed = normalizeModulesList(options.moduleList);
35
+ if (!parsed.ok) throw new Error(parsed.error);
36
+ moduleFiles = parsed.modules;
37
+ } else if (options.modules === true) {
38
+ moduleFiles = ['inject', 'cookies'];
39
+ }
40
+ const majorPin = '@2';
41
+ const exactPin = `@${version}`;
42
+
43
+ const loaderLines = [
44
+ '<!-- Stagepass loader (major pin @2; optional exact pin shown in data-stagepass-version) -->',
45
+ '<script',
46
+ ` src="https://cdn.jsdelivr.net/npm/@stagepass/loader${majorPin}/dist/loader.min.js"`,
47
+ ` data-stagepass-version="${version}"`,
48
+ '></script>',
49
+ ];
50
+
51
+ for (const id of moduleFiles) {
52
+ loaderLines.push(
53
+ `<script src="https://cdn.jsdelivr.net/npm/@stagepass/modules${majorPin}/dist/${id}.min.js"></script>`
54
+ );
55
+ }
56
+
57
+ const footerLines = [
58
+ '<!-- Project assets: production URLs in data-src / data-href; local paths for Stagepass -->',
59
+ '<!-- After `npm run build`, check dist/manifest.json for content-hashed filenames. -->',
60
+ '<script',
61
+ ' data-src="https://cdn.example.com/js/main.js"',
62
+ ' data-stagepass="true"',
63
+ ' data-stagepass-path="dist/main.js"',
64
+ '></script>',
65
+ '<link',
66
+ ' rel="stylesheet"',
67
+ ' data-href="https://cdn.example.com/css/styles.css"',
68
+ ' data-stagepass="true"',
69
+ ' data-stagepass-path="dist/styles.css"',
70
+ '>',
71
+ ];
72
+
73
+ return {
74
+ head: loaderLines.join('\n'),
75
+ footer: footerLines.join('\n'),
76
+ majorPin,
77
+ exactPin,
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Print head/footer snippets with section labels.
83
+ * @param {{ head: string, footer: string }} snippets
84
+ * @param {(msg: string) => void} [log]
85
+ */
86
+ export function printWebflowSnippets(snippets, log = console.log) {
87
+ log('\nWebflow Custom Code (Head):');
88
+ log(snippets.head);
89
+ log('\nWebflow Custom Code (Footer):');
90
+ log(snippets.footer);
91
+ log(
92
+ `\nOptional exact pin example (instead of @2): replace @2 with the exact version (e.g. @${STAGEPASS_PACKAGES_VERSION}).`
93
+ );
94
+ }
@@ -0,0 +1,30 @@
1
+ import { spawn as nodeSpawn } from 'node:child_process';
2
+
3
+ /**
4
+ * @typedef {object} SpawnResult
5
+ * @property {number|null} code
6
+ * @property {NodeJS.Signals|null} [signal]
7
+ */
8
+
9
+ /**
10
+ * @typedef {(command: string, args?: string[], options?: object) => Promise<SpawnResult>} SpawnFn
11
+ */
12
+
13
+ /**
14
+ * Spawn without a shell. Forwards stdio by default.
15
+ * Always forces shell:false after spreading options so callers cannot enable a shell.
16
+ * @type {SpawnFn}
17
+ */
18
+ export function defaultSpawn(command, args = [], options = {}) {
19
+ return new Promise((resolve, reject) => {
20
+ const child = nodeSpawn(command, args, {
21
+ stdio: 'inherit',
22
+ ...options,
23
+ shell: false,
24
+ });
25
+ child.on('error', reject);
26
+ child.on('close', (code, signal) => {
27
+ resolve({ code, signal });
28
+ });
29
+ });
30
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Version of @stagepass/loader and @stagepass/modules this CLI targets.
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.
8
+ */
9
+ export const STAGEPASS_PACKAGES_VERSION = '2.2.0';
10
+
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).
17
+ *
18
+ * @param {string} [version]
19
+ * @returns {string}
20
+ */
21
+ export function packagesRange(version = STAGEPASS_PACKAGES_VERSION) {
22
+ const match = /^[~^]?(\d+)\.(\d+)\./.exec(String(version).trim());
23
+ if (!match) {
24
+ throw new Error(`Invalid @stagepass package version: ${version}`);
25
+ }
26
+ return `^${match[1]}.${match[2]}.0`;
27
+ }
@@ -0,0 +1,39 @@
1
+ # {{NAME}} (Stagepass project)
2
+
3
+ Profile for AI coding agents and humans working on this Webflow + Stagepass project.
4
+
5
+ ## Stagepass feature set
6
+
7
+ - **CLI:** local `.sp` HTTPS domains (Caddy), DNS, optional PHP, `link` / `unlink` / `start` / `stop` / `reload`, plus `doctor` / `certs` / `autostart` / `daemon` and project helpers `new` / `build` / `watch` / `upgrade`
8
+ - **Loader:** swaps tagged production assets for local URLs when a session is active (`?stagepass={{NAME}}.sp`)
9
+ - **Session:** `localStorage` JSON `{ domain, expires }` (default 12 h)
10
+ - **Modules (optional):** separate script tags after `loader.min.js`: `inject`, `cookies`, `maintenance`, or `all`. This project declares the modules its Webflow site loads in `stagepass.json` (`modules`); the API reference below only covers those.
11
+ - **Runtime API:** use `sp` (see "Stagepass runtime API" below)
12
+ - **CDN:** Prefer jsDelivr with major pin `@2` (exact pin optional), e.g. `https://cdn.jsdelivr.net/npm/@stagepass/loader@2/dist/loader.min.js`. unpkg serves the same paths if you need an alternative CDN.
13
+
14
+ ## Safe development rules (beginners)
15
+
16
+ 1. **No secrets in frontend code.** API keys, tokens, and passwords must never ship in JS/CSS served to the browser.
17
+ 2. **No `innerHTML` with untrusted data.** Prefer `textContent`, `createElement`, or trusted, sanitized markup only.
18
+ 3. **No `eval` or string-built scripts** with user or CMS input.
19
+ 4. **Pin versions** for production embeds (`@2` major pin, or an exact pin when you need a lockstep deploy).
20
+ 5. **Review before publishing.** Read the diff for asset tags, CORS origins, and anything that touches live Webflow Custom Code.
21
+ 6. **Keep Stagepass tags intact.** Use `data-src` / `data-href` + `data-stagepass` (+ optional `data-stagepass-path`) so production users keep production URLs.
22
+ 7. **Do not commit secrets.** Keep `.env*` out of git (see `.gitignore`).
23
+
24
+ ## Local workflow
25
+
26
+ ```bash
27
+ npm run watch
28
+ stagepass start
29
+ stagepass link {{NAME}} --origin my-project.webflow.io
30
+ ```
31
+
32
+ Then open `https://my-project.webflow.io/?stagepass={{NAME}}.sp`.
33
+
34
+ ## Types
35
+
36
+ `{{CONFIG_FILE}}` lists `types: {{TYPES_INLINE}}`, generated from `stagepass.json`. Modules that are not declared have no types, so the editor flags `sp.<module>` calls that would fail on the live site. After enabling a module (Webflow script tag + `stagepass.json`), run `stagepass upgrade`.
37
+
38
+ {{STAGEPASS_BLOCK}}
39
+
@@ -0,0 +1,44 @@
1
+ # {{NAME}}
2
+
3
+ Local Stagepass project for Webflow.
4
+
5
+ ## Setup
6
+
7
+ ```bash
8
+ npm install
9
+ npm run build
10
+ stagepass link {{NAME}} --origin my-project.webflow.io
11
+ ```
12
+
13
+ Activate on your live site: `https://my-project.webflow.io/?stagepass={{NAME}}.sp`
14
+
15
+ ## Scripts
16
+
17
+ | Script | Description |
18
+ | :--- | :--- |
19
+ | `npm run build` | Bundle JS/CSS into `dist/` with content hashes + `manifest.json` |
20
+ | `npm run watch` | Rebuild on change |
21
+
22
+ ## Webflow Custom Code
23
+
24
+ Prefer the major CDN pin `@2`. An exact pin is optional (see `data-stagepass-version`).
25
+
26
+ ### Head
27
+
28
+ ```html
29
+ {{HEAD_SNIPPET}}
30
+ ```
31
+
32
+ Optional exact pin (replace `@2` in the URL if you need a locked version): `@{{LOADER_VERSION}}`.
33
+
34
+ ### Footer
35
+
36
+ ```html
37
+ {{FOOTER_SNIPPET}}
38
+ ```
39
+
40
+ After each production upload, set `data-src` / `data-href` to your hosted URLs. For content-hashed uploads, read the filenames from `dist/manifest.json`. Local Stagepass swapping can keep using the stable `dist/main.js` and `dist/styles.css` copies.
41
+
42
+ ## PHP
43
+
44
+ PHP helpers for this scaffolder are planned for a later Stagepass release. Linked `.sp` sites can still use PHP via the CLI when PHP is installed system-wide.