@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,276 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+ import chalk from 'chalk';
4
+ import { defaultExec } from '../lib/exec.js';
5
+ import {
6
+ buildWebflowSnippets,
7
+ printWebflowSnippets,
8
+ } from '../lib/snippets.js';
9
+
10
+ import readline from 'node:readline/promises';
11
+ import { stdin as input, stdout as output } from 'node:process';
12
+ import { STAGEPASS_PACKAGES_VERSION } from '../lib/versions.js';
13
+ import { detectSite } from '../lib/site-detect.js';
14
+ import {
15
+ applyProjectSync,
16
+ planProjectSync,
17
+ readStagepassJson,
18
+ resolveUpgradeModules,
19
+ } from '../lib/project-sync.js';
20
+
21
+ const STAGEPASS_SCOPE = '@stagepass/';
22
+
23
+ /**
24
+ * True when the version looks like an npm dist-tag that needs resolution.
25
+ * @param {string} version
26
+ */
27
+ function needsNpmView(version) {
28
+ if (!version) return false;
29
+ // Semver-ish or range: treat as literal. Dist-tags are bare words.
30
+ if (/^[0-9]/.test(version) || version.startsWith('^') || version.startsWith('~')) {
31
+ return false;
32
+ }
33
+ if (version.includes('.')) return false;
34
+ return /^[a-z][a-z0-9_-]*$/i.test(version);
35
+ }
36
+
37
+ /**
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).
41
+ *
42
+ * @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>}
48
+ */
49
+ export async function resolveUpgradeVersion(requested, deps = {}) {
50
+ const exec = deps.exec || defaultExec;
51
+ const fallback =
52
+ deps.packagesVersion || deps.cliVersion || STAGEPASS_PACKAGES_VERSION;
53
+
54
+ if (!requested || String(requested).trim() === '') {
55
+ return fallback;
56
+ }
57
+
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;
68
+ }
69
+
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}".`);
74
+ }
75
+ if (!/^[~^]?[0-9A-Za-z][0-9A-Za-z._+-]*$/.test(resolved)) {
76
+ throw new Error(`Resolved version looks unsafe: ${resolved}`);
77
+ }
78
+ return resolved;
79
+ }
80
+
81
+ /**
82
+ * Collect @stagepass/* entries from dependencies and devDependencies.
83
+ * @param {object} pkg
84
+ * @returns {{ section: 'dependencies'|'devDependencies', name: string, from: string }[]}
85
+ */
86
+ export function findStagepassDeps(pkg) {
87
+ /** @type {{ section: 'dependencies'|'devDependencies', name: string, from: string }[]} */
88
+ const found = [];
89
+ for (const section of /** @type {const} */ (['dependencies', 'devDependencies'])) {
90
+ const block = pkg[section];
91
+ if (!block || typeof block !== 'object') continue;
92
+ for (const [name, from] of Object.entries(block)) {
93
+ if (name.startsWith(STAGEPASS_SCOPE)) {
94
+ found.push({ section, name, from: String(from) });
95
+ }
96
+ }
97
+ }
98
+ return found;
99
+ }
100
+
101
+ /**
102
+ * Rewrite @stagepass/* versions in a package.json object (mutates a copy).
103
+ * @param {object} pkg
104
+ * @param {string} targetVersion
105
+ * @returns {{ next: object, changes: { name: string, from: string, to: string, section: string }[] }}
106
+ */
107
+ export function applyStagepassVersions(pkg, targetVersion) {
108
+ const next = structuredClone(pkg);
109
+ const changes = [];
110
+ const target = String(targetVersion);
111
+
112
+ for (const { section, name, from } of findStagepassDeps(pkg)) {
113
+ if (!next[section]) continue;
114
+ const to = target;
115
+ if (String(from) !== to) {
116
+ changes.push({ name, from: String(from), to, section });
117
+ }
118
+ next[section][name] = to;
119
+ }
120
+
121
+ return { next, changes };
122
+ }
123
+
124
+ /**
125
+ * Upgrade @stagepass/* deps in the current project's package.json and sync
126
+ * the declared modules into stagepass.json, AGENTS.md, the Cursor rule and
127
+ * tsconfig/jsconfig types.
128
+ *
129
+ * @param {object} [options]
130
+ * @param {boolean} [options.dryRun]
131
+ * @param {string} [options.version]
132
+ * @param {string} [options.site] live Webflow host to detect modules from
133
+ * @param {string} [options.siteModules] none | all | comma list
134
+ * @param {boolean} [options.skipSite]
135
+ * @param {boolean} [options.yes]
136
+ * @param {object} [deps]
137
+ * @param {typeof fs} [deps.fs]
138
+ * @param {string} [deps.cwd]
139
+ * @param {import('../lib/exec.js').ExecFn} [deps.exec]
140
+ * @param {string} [deps.cliVersion]
141
+ * @param {(msg?: string) => void} [deps.log]
142
+ * @returns {Promise<number>} exit code
143
+ */
144
+ export async function upgrade(options = {}, deps = {}) {
145
+ const fse = deps.fs || fs;
146
+ const cwd = deps.cwd || process.cwd();
147
+ const log = deps.log || console.log;
148
+ const pkgPath = path.join(cwd, 'package.json');
149
+
150
+ if (!(await fse.pathExists(pkgPath))) {
151
+ log(chalk.red('No package.json found in the current directory.'));
152
+ return 1;
153
+ }
154
+
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
+ const raw = await fse.readFile(pkgPath, 'utf8');
167
+ let pkg;
168
+ try {
169
+ pkg = JSON.parse(raw);
170
+ } catch {
171
+ log(chalk.red('package.json is not valid JSON.'));
172
+ return 1;
173
+ }
174
+
175
+ const { next, changes } = applyStagepassVersions(pkg, targetVersion);
176
+
177
+ if (changes.length === 0) {
178
+ const existing = findStagepassDeps(pkg);
179
+ if (existing.length === 0) {
180
+ log(chalk.yellow('No @stagepass/* packages found in package.json.'));
181
+ } else {
182
+ log(chalk.green(`@stagepass/* already at ${targetVersion}.`));
183
+ }
184
+ } else {
185
+ log(chalk.bold(`Upgrade @stagepass/* → ${targetVersion}`));
186
+ for (const change of changes) {
187
+ log(` ${change.name}: ${change.from} → ${change.to} (${change.section})`);
188
+ }
189
+ }
190
+
191
+ // Declared modules: live site first, then stagepass.json, then ask.
192
+ const sp = await readStagepassJson(cwd, fse);
193
+ if (sp.error) log(chalk.yellow(sp.error));
194
+ const isTty = deps.isTTY != null ? Boolean(deps.isTTY) : Boolean(input.isTTY && output.isTTY);
195
+ const interactive = isTty && options.yes !== true;
196
+ /** @type {import('node:readline/promises').Interface | null} */
197
+ let rl = null;
198
+ const getRl = () => {
199
+ if (!rl) rl = deps.createReadline?.() || readline.createInterface({ input, output });
200
+ return rl;
201
+ };
202
+ let resolved;
203
+ try {
204
+ resolved = await resolveUpgradeModules(
205
+ { cwd, data: sp.data, pkg: next, options },
206
+ {
207
+ detectSite: deps.detectSite || detectSite,
208
+ loadProjects: deps.loadProjects,
209
+ interactive,
210
+ log,
211
+ ask: async (question, def) => {
212
+ const answer = await getRl().question(`${question} (${def}): `);
213
+ const trimmed = String(answer || '').trim();
214
+ return trimmed === '' ? def : trimmed;
215
+ },
216
+ confirm: async (question, defYes) => {
217
+ const answer = await getRl().question(`${question} (${defYes ? 'Y/n' : 'y/N'}): `);
218
+ const t = String(answer || '').trim().toLowerCase();
219
+ if (t === '') return defYes;
220
+ return ['y', 'yes'].includes(t);
221
+ },
222
+ }
223
+ );
224
+ } finally {
225
+ if (rl) rl.close();
226
+ }
227
+ if (!resolved.ok) {
228
+ log(chalk.red(resolved.error));
229
+ return 1;
230
+ }
231
+
232
+ const plan = await planProjectSync(
233
+ {
234
+ cwd,
235
+ modules: resolved.modules,
236
+ origin: options.site ? resolved.origin : null,
237
+ pkg: next,
238
+ },
239
+ fse
240
+ );
241
+
242
+ log(chalk.bold(`\nProject files for modules: ${resolved.modules.length ? resolved.modules.join(', ') : 'none'}`));
243
+ if (plan.writes.length === 0) {
244
+ log(' Everything is up to date.');
245
+ }
246
+ for (const w of plan.writes) {
247
+ log(` ${w.file}: ${w.action}`);
248
+ }
249
+ for (const note of plan.notes) {
250
+ log(chalk.yellow(` note: ${note}`));
251
+ }
252
+
253
+ if (options.dryRun) {
254
+ log(chalk.dim('\nDry run: no files were modified.'));
255
+ } else {
256
+ if (changes.length > 0) {
257
+ const trailingNewline = raw.endsWith('\n');
258
+ const pkgBody = `${JSON.stringify(next, null, 2)}${trailingNewline ? '\n' : ''}`;
259
+ await fse.writeFile(pkgPath, pkgBody, 'utf8');
260
+ log(chalk.green('\nUpdated package.json.'));
261
+ }
262
+ await applyProjectSync(cwd, plan.writes, fse);
263
+ if (plan.writes.length > 0) log(chalk.green(`Updated ${plan.writes.length} project file(s).`));
264
+ }
265
+
266
+ const snippets = buildWebflowSnippets({
267
+ version: targetVersion,
268
+ moduleList: resolved.modules,
269
+ });
270
+ printWebflowSnippets(snippets, log);
271
+
272
+ log(chalk.bold('\nNext step (not run automatically):'));
273
+ log(' npm install');
274
+
275
+ return 0;
276
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Generated AI guidance (AGENTS.md managed block + Cursor rule).
3
+ *
4
+ * Content depends on the declared modules so agents only see APIs that
5
+ * actually run on the Webflow site.
6
+ */
7
+
8
+ import { MODULE_IDS, expandModules, formatModules } from './project-modules.js';
9
+
10
+ export const BLOCK_BEGIN = '<!-- stagepass:begin -->';
11
+ export const BLOCK_END = '<!-- stagepass:end -->';
12
+ export const CURSOR_RULE_PATH = '.cursor/rules/stagepass.mdc';
13
+
14
+ const LOADER_SECTION = `### Loader API (always available)
15
+
16
+ \`sp\` (same object as \`window.stagepass\`) is created by \`loader.min.js\` in the Webflow head before your bundle runs.
17
+
18
+ | API | Returns | Notes |
19
+ | --- | --- | --- |
20
+ | \`sp.vars\` | frozen object | \`isLocal\`, \`env\`, \`domain\`, \`timestamp\`, \`version\`, \`client\` |
21
+ | \`sp.env()\` | \`'local' \\| 'staging' \\| 'production'\` | \`local\` = active session to a \`.sp\` domain; \`staging\` = \`*.webflow.io\` or \`data-stagepass-staging-hosts\` |
22
+ | \`sp.is(name)\` | \`boolean\` | \`true\` when \`sp.env() === name\` |
23
+ | \`sp.can(cap)\` | \`boolean\` | \`'localStorage' \\| 'sessionStorage' \\| 'cookies' \\| 'serviceWorker'\`; anything else is \`false\` |
24
+ | \`sp.client(key?)\` | \`unknown\` | key of \`sp.vars.client\` (\`theme\`, \`browser\`, \`os\`, \`device\`, \`viewport\`, \`locale\`, \`capabilities\`), or the whole object |
25
+ | \`sp.log(...)\`, \`sp.warn(...)\`, \`sp.error(...)\` | \`void\` | prefixed console output, only while a Stagepass session is active |
26
+ | \`sp.resolveLocalUrl(path)\` | \`string\` | local HTTPS URL during a session, \`''\` otherwise |
27
+ | \`sp.on('theme', fn)\` | unsubscribe \`() => void\` | payload \`{ preferred, current }\` on color scheme changes |
28
+ | \`sp.on('session', fn)\` | unsubscribe \`() => void\` | payload \`{ active, domain, swap, debug }\` |
29
+ | \`sp.use(name, version, factory)\` | \`boolean\` | module registration (used by @stagepass/modules, not needed in app code) |
30
+
31
+ \`\`\`ts
32
+ if (sp.is('local')) sp.log('running against the local dev server');
33
+ const off = sp.on('theme', (payload) => {
34
+ const { current } = payload as { current: string };
35
+ document.documentElement.dataset.theme = current;
36
+ });
37
+ if (sp.can('localStorage')) localStorage.setItem('seen', '1');
38
+ \`\`\``;
39
+
40
+ const MODULE_SECTIONS = {
41
+ inject: `### Module: inject (\`sp.inject\`)
42
+
43
+ Loads extra scripts and stylesheets. Webflow script tag: \`@stagepass/modules@2/dist/inject.min.js\` after \`loader.min.js\`.
44
+
45
+ \`\`\`ts
46
+ if (sp.inject) {
47
+ await sp.inject({ src: 'https://cdn.example.com/lib.js', defer: true, stagepass: false });
48
+ await sp.inject({ src: 'https://cdn.example.com/site/widgets.js', localPath: 'dist/widgets.js' });
49
+ await sp.inject({ scripts: [{ src: 'https://cdn.example.com/a.js' }], styles: [{ src: 'https://cdn.example.com/a.css' }] });
50
+ }
51
+ \`\`\`
52
+
53
+ Argument: one options object, an array of them, or \`{ scripts?, styles? }\`. Returns \`Promise<void>\`.
54
+ Options: \`src\` (required), \`type\` (\`'script' \\| 'style'\`), \`stagepass\` (default true: during a session the file is served from the local project via \`localPath\`/\`path\` or the file name; \`false\` always uses \`src\`), \`localPath\`, \`path\`, \`id\`, \`async\`, \`defer\`, \`version\` (adds \`?v=\` in production), \`attributes\`, \`position\` (\`'head' \\| 'body-start' \\| 'body-end' \\| { target, action: 'before' \\| 'after' }\`), \`integrity\`, \`crossorigin\`, \`nonce\`, \`allowedHosts\`.`,
55
+ cookies: `### Module: cookies (\`sp.cookies\`, alias \`sp.cookie\`, plus \`sp.consent\`)
56
+
57
+ Webflow script tag: \`@stagepass/modules@2/dist/cookies.min.js\` after \`loader.min.js\`.
58
+
59
+ \`\`\`ts
60
+ if (sp.cookies) {
61
+ sp.cookies.bake('visited', '1', { days: 30, sameSite: 'Lax' });
62
+ const prefs = sp.cookies.eat('prefs', { json: true }); // value or null
63
+ if (sp.cookies.has('visited')) sp.cookies.throw('visited');
64
+ sp.cookies.bake('ga', 'x', { category: 'analytics' }); // queued until consent allows it
65
+ }
66
+ if (sp.consent) {
67
+ const accepted = ['necessary', 'analytics']; // from your consent banner
68
+ sp.consent.set((category) => accepted.includes(category));
69
+ sp.consent.update(); // flush queued cookies against the consent function
70
+ }
71
+ \`\`\`
72
+
73
+ Cookies: \`bake(name, value, options?)\`, \`eat(name, { decode?, json? })\` (value or \`null\`), \`throw(name, { path?, domain?, secure?, sameSite? })\`, \`has(name)\`, \`list({ decode?, json? })\`, \`throwAll({ category? })\`, \`jar()\`, \`crumbs(prefix)\`.
74
+ Write options: \`days\`, \`maxAge\`, \`path\`, \`domain\`, \`secure\`, \`sameSite\`, \`encode\`, \`json\`, \`category\`.
75
+ Consent: \`allows(category)\`, \`set(fn)\`, \`update()\`.`,
76
+ maintenance: `### Module: maintenance (\`sp.maintenance\`)
77
+
78
+ Webflow script tag: \`@stagepass/modules@2/dist/maintenance.min.js\` after \`loader.min.js\` (optional attributes \`data-stagepass-maintenance="true"\`, \`data-stagepass-maintenance-title\`, \`data-stagepass-maintenance-text\`).
79
+
80
+ \`\`\`ts
81
+ if (sp.maintenance && !sp.maintenance.isActive()) {
82
+ sp.maintenance.enable({ title: 'Back soon', text: 'We are updating the site.' });
83
+ }
84
+ \`\`\`
85
+
86
+ API: \`enable({ title?, text? })\`, \`disable()\`, \`isActive()\`. Developer sessions see a badge instead of the overlay. This is a visual overlay, not access protection.`,
87
+ };
88
+
89
+ function unavailableLine(id) {
90
+ return `- \`sp.${id}\`: not available; enable by adding the \`${id}.min.js\` script tag after \`loader.min.js\` in Webflow, adding \`"${id}"\` to \`modules\` in stagepass.json, and running \`stagepass upgrade\`.`;
91
+ }
92
+
93
+ /**
94
+ * Inner Markdown for the managed block (without markers).
95
+ * @param {string[]} modules normalized declared list
96
+ */
97
+ export function buildGuideBody(modules) {
98
+ const enabled = expandModules(modules);
99
+ const disabled = MODULE_IDS.filter((id) => !enabled.includes(id));
100
+ const parts = [
101
+ '## Stagepass runtime API',
102
+ '',
103
+ `Generated by \`stagepass upgrade\` from \`stagepass.json\` (modules: ${formatModules(modules)}). Do not edit inside this block; it is replaced on upgrade.`,
104
+ '',
105
+ '**Rule for agents:** only use the `sp.*` APIs listed below. Never call `sp.<module>` APIs that are not listed as available. If a task needs one, tell the user to enable that module first (Webflow script tag, stagepass.json, `stagepass upgrade`). Guard optional modules (`if (sp.cookies) { ... }`).',
106
+ '',
107
+ LOADER_SECTION,
108
+ ];
109
+ for (const id of enabled) {
110
+ parts.push('', MODULE_SECTIONS[id]);
111
+ }
112
+ if (disabled.length > 0) {
113
+ parts.push('', '### Modules not enabled in this project', '');
114
+ for (const id of disabled) parts.push(unavailableLine(id));
115
+ }
116
+ return parts.join('\n');
117
+ }
118
+
119
+ /** Full managed block including markers. */
120
+ export function buildManagedBlock(modules) {
121
+ return `${BLOCK_BEGIN}\n${buildGuideBody(modules)}\n${BLOCK_END}`;
122
+ }
123
+
124
+ /**
125
+ * Insert or replace the managed block in existing content.
126
+ * Content outside the markers is preserved byte for byte.
127
+ *
128
+ * @param {string} content
129
+ * @param {string} block full block incl. markers
130
+ * @returns {{ content: string, action: 'inserted' | 'updated' | 'unchanged' | 'invalid' }}
131
+ */
132
+ export function upsertManagedBlock(content, block) {
133
+ const begin = content.indexOf(BLOCK_BEGIN);
134
+ const end = content.indexOf(BLOCK_END);
135
+ if (begin === -1 && end === -1) {
136
+ const sep = content.length === 0 ? '' : content.endsWith('\n\n') ? '' : content.endsWith('\n') ? '\n' : '\n\n';
137
+ return { content: `${content}${sep}${block}\n`, action: 'inserted' };
138
+ }
139
+ if (begin === -1 || end === -1 || end < begin) {
140
+ return { content, action: 'invalid' };
141
+ }
142
+ const next = content.slice(0, begin) + block + content.slice(end + BLOCK_END.length);
143
+ return { content: next, action: next === content ? 'unchanged' : 'updated' };
144
+ }
145
+
146
+ /**
147
+ * Cursor project rule (.cursor/rules/stagepass.mdc).
148
+ * @param {string[]} modules
149
+ */
150
+ export function buildCursorRule(modules) {
151
+ return [
152
+ '---',
153
+ 'description: Stagepass runtime API (sp) for this Webflow project',
154
+ 'globs: src/**',
155
+ 'alwaysApply: false',
156
+ '---',
157
+ '',
158
+ buildManagedBlock(modules),
159
+ '',
160
+ ].join('\n');
161
+ }