@stagepass/cli 2.4.1 → 2.6.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.
- package/README.md +37 -21
- package/package.json +1 -1
- package/src/cli.js +4 -1
- package/src/commands/dev.js +11 -2
- package/src/commands/new.js +53 -3
- package/src/commands/start.js +23 -1
- package/src/commands/upgrade.js +172 -54
- package/src/lib/ai-guide.js +526 -23
- package/src/lib/build-script-upgrade.js +24 -10
- package/src/lib/cdn-base.js +72 -0
- package/src/lib/cdn-snippets.js +12 -8
- package/src/lib/doctor-site.js +17 -0
- package/src/lib/doctor.js +3 -3
- package/src/lib/live-server.js +141 -34
- package/src/lib/package-versions.js +1 -1
- package/src/lib/project-sync.js +543 -32
- package/src/lib/registry.js +9 -7
- package/src/lib/scaffold.js +45 -5
- package/src/lib/site-detect.js +13 -1
- package/src/lib/snippets.js +267 -35
- package/src/lib/versions.js +9 -8
- package/templates/project/AGENTS.md.tmpl +2 -35
- package/templates/project/README.md.tmpl +4 -2
- package/templates/project/api/README.md.tmpl +16 -195
- package/templates/project/api/action.php +11 -2
- package/templates/project/api/env.example +11 -1
- package/templates/project/api/lib/config.php +5 -1
- package/templates/project/api/lib/request.php +366 -3
- package/templates/project/api/lib/security.php +116 -34
- package/templates/project/php-private/config.php +2 -0
package/src/lib/ai-guide.js
CHANGED
|
@@ -1,15 +1,66 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Generated AI guidance
|
|
2
|
+
* Generated AI guidance.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* `AGENTS.stagepass.md` is owned by the CLI (feature set, workflow, runtime
|
|
5
|
+
* API, declared modules, PHP). `AGENTS.md` is the tool-neutral pointer.
|
|
6
|
+
* The Cursor rule is written only when `.cursor/` already exists, the rule
|
|
7
|
+
* file already exists, or the user passed `--cursor-rule`.
|
|
6
8
|
*/
|
|
7
9
|
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import { createRequire } from 'node:module';
|
|
8
12
|
import { MODULE_IDS, expandModules, formatModules } from './project-modules.js';
|
|
13
|
+
import { LOADER_VERSION, MODULES_VERSION } from './versions.js';
|
|
14
|
+
import {
|
|
15
|
+
SNIPPET_LOADER_VERSION,
|
|
16
|
+
SNIPPET_MODULES_VERSION,
|
|
17
|
+
normalizeCdnChoice,
|
|
18
|
+
stagepassPackageUrl,
|
|
19
|
+
} from './cdn-base.js';
|
|
20
|
+
|
|
21
|
+
const require = createRequire(import.meta.url);
|
|
22
|
+
export const CLI_VERSION = require('../../package.json').version;
|
|
9
23
|
|
|
10
24
|
export const BLOCK_BEGIN = '<!-- stagepass:begin -->';
|
|
11
25
|
export const BLOCK_END = '<!-- stagepass:end -->';
|
|
12
26
|
export const CURSOR_RULE_PATH = '.cursor/rules/stagepass.mdc';
|
|
27
|
+
export const STAGEPASS_AGENTS_REL = 'AGENTS.stagepass.md';
|
|
28
|
+
|
|
29
|
+
export const STAGEPASS_AGENTS_NOTICE =
|
|
30
|
+
'Generated by @stagepass/cli. Do not edit this file by hand. `stagepass upgrade` rewrites it. Put your own notes in AGENTS.md.';
|
|
31
|
+
|
|
32
|
+
export const AGENTS_POINTER_TEXT =
|
|
33
|
+
'This is a Stagepass project. Before any work on `src/`, `api/`, or Webflow code, read `AGENTS.stagepass.md` (project root). It is authoritative and is kept current by the CLI.';
|
|
34
|
+
|
|
35
|
+
export const CURSOR_POINTER_TEXT =
|
|
36
|
+
'This is a Stagepass project. Before any work on `src/`, `api/`, or Webflow code, read @AGENTS.stagepass.md. It is authoritative and is kept current by the CLI.';
|
|
37
|
+
|
|
38
|
+
export const STAGEPASS_AGENTS_HINT =
|
|
39
|
+
'AGENTS.stagepass.md was edited by hand, or it has no stagepass:managed header, so it was left unchanged. Run stagepass upgrade --yes to replace it.';
|
|
40
|
+
|
|
41
|
+
export const STAGEPASS_AGENTS_DECLINED = 'AGENTS.stagepass.md left unchanged.';
|
|
42
|
+
|
|
43
|
+
export const STAGEPASS_AGENTS_CONFIRM =
|
|
44
|
+
'Replace AGENTS.stagepass.md with the generated Stagepass guide? It was edited by hand, or it has no managed header.';
|
|
45
|
+
|
|
46
|
+
export const PHP_LIB_MISSING_NOTE =
|
|
47
|
+
'stagepass.json has "php": true but api/lib/ is missing. The guide tells agents not to rebuild the boilerplate. Copy api/ and .php/ from `stagepass new --php` yourself. stagepass upgrade does not add those files.';
|
|
48
|
+
|
|
49
|
+
export const LEGACY_AGENTS_NOTE =
|
|
50
|
+
'AGENTS.md still has older generated Stagepass sections outside the markers (for example "Stagepass feature set"). Those sections now live in AGENTS.stagepass.md. You can delete them. Text outside the markers was left unchanged.';
|
|
51
|
+
|
|
52
|
+
const OLD_CURSOR_FRONT = [
|
|
53
|
+
'description: Stagepass runtime API (sp) for this Webflow project',
|
|
54
|
+
'globs: src/**',
|
|
55
|
+
'alwaysApply: false',
|
|
56
|
+
].join('\n');
|
|
57
|
+
|
|
58
|
+
const NEW_CURSOR_FRONT = [
|
|
59
|
+
'description: Stagepass project guide (AGENTS.stagepass.md)',
|
|
60
|
+
'alwaysApply: true',
|
|
61
|
+
].join('\n');
|
|
62
|
+
|
|
63
|
+
const HEADER_RE = /^<!-- stagepass:managed cli=(\S+) sha256=([a-f0-9]{64}) -->\n/;
|
|
13
64
|
|
|
14
65
|
const LOADER_SECTION = `### Loader API (always available)
|
|
15
66
|
|
|
@@ -40,7 +91,7 @@ if (sp.can('localStorage')) localStorage.setItem('seen', '1');
|
|
|
40
91
|
const MODULE_SECTIONS = {
|
|
41
92
|
inject: `### Module: inject (\`sp.inject\`)
|
|
42
93
|
|
|
43
|
-
Loads extra scripts and stylesheets. Webflow script tag:
|
|
94
|
+
Loads extra scripts and stylesheets. Webflow script tag: \`https://cdn.stagepass.one/modules@${SNIPPET_MODULES_VERSION}/inject.min.js\` after \`loader.min.js\`.
|
|
44
95
|
|
|
45
96
|
\`\`\`ts
|
|
46
97
|
if (sp.inject) {
|
|
@@ -54,7 +105,7 @@ Argument: one options object, an array of them, or \`{ scripts?, styles? }\`. Re
|
|
|
54
105
|
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
106
|
cookies: `### Module: cookies (\`sp.cookies\`, alias \`sp.cookie\`, plus \`sp.consent\`)
|
|
56
107
|
|
|
57
|
-
Webflow script tag:
|
|
108
|
+
Webflow script tag: \`https://cdn.stagepass.one/modules@${SNIPPET_MODULES_VERSION}/cookies.min.js\` after \`loader.min.js\`.
|
|
58
109
|
|
|
59
110
|
\`\`\`ts
|
|
60
111
|
if (sp.cookies) {
|
|
@@ -75,7 +126,7 @@ Write options: \`days\`, \`maxAge\`, \`path\`, \`domain\`, \`secure\`, \`sameSit
|
|
|
75
126
|
Consent: \`allows(category)\`, \`set(fn)\`, \`update()\`.`,
|
|
76
127
|
maintenance: `### Module: maintenance (\`sp.maintenance\`)
|
|
77
128
|
|
|
78
|
-
Webflow script tag:
|
|
129
|
+
Webflow script tag: \`https://cdn.stagepass.one/modules@${SNIPPET_MODULES_VERSION}/maintenance.min.js\` after \`loader.min.js\` (optional attributes \`data-stagepass-maintenance="true"\`, \`data-stagepass-maintenance-title\`, \`data-stagepass-maintenance-text\`).
|
|
79
130
|
|
|
80
131
|
\`\`\`ts
|
|
81
132
|
if (sp.maintenance && !sp.maintenance.isActive()) {
|
|
@@ -90,19 +141,25 @@ function unavailableLine(id) {
|
|
|
90
141
|
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
142
|
}
|
|
92
143
|
|
|
144
|
+
function sha256(text) {
|
|
145
|
+
return createHash('sha256').update(text, 'utf8').digest('hex');
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function normalizeNewlines(source) {
|
|
149
|
+
return String(source).replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
|
150
|
+
}
|
|
151
|
+
|
|
93
152
|
/**
|
|
94
|
-
*
|
|
153
|
+
* Runtime API section (declared modules only).
|
|
95
154
|
* @param {string[]} modules normalized declared list
|
|
96
155
|
*/
|
|
97
156
|
export function buildGuideBody(modules) {
|
|
98
157
|
const enabled = expandModules(modules);
|
|
99
158
|
const disabled = MODULE_IDS.filter((id) => !enabled.includes(id));
|
|
100
159
|
const parts = [
|
|
101
|
-
'##
|
|
102
|
-
'',
|
|
103
|
-
`Generated by \`stagepass upgrade\` from \`stagepass.json\` (modules: ${formatModules(modules)}). Do not edit inside this block; it is replaced on upgrade.`,
|
|
160
|
+
'## Runtime API',
|
|
104
161
|
'',
|
|
105
|
-
|
|
162
|
+
`Declared modules: ${formatModules(modules)}. 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
163
|
'',
|
|
107
164
|
LOADER_SECTION,
|
|
108
165
|
];
|
|
@@ -116,9 +173,18 @@ export function buildGuideBody(modules) {
|
|
|
116
173
|
return parts.join('\n');
|
|
117
174
|
}
|
|
118
175
|
|
|
119
|
-
/**
|
|
120
|
-
export function
|
|
121
|
-
return `${BLOCK_BEGIN}\n${
|
|
176
|
+
/** Short managed block for the user-owned AGENTS.md. */
|
|
177
|
+
export function buildAgentsPointerBlock() {
|
|
178
|
+
return `${BLOCK_BEGIN}\n${AGENTS_POINTER_TEXT}\n${BLOCK_END}`;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** @deprecated Use buildAgentsPointerBlock. Kept so older call sites keep working. */
|
|
182
|
+
export function buildManagedBlock() {
|
|
183
|
+
return buildAgentsPointerBlock();
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function buildCursorPointerBlock() {
|
|
187
|
+
return `${BLOCK_BEGIN}\n${CURSOR_POINTER_TEXT}\n${BLOCK_END}`;
|
|
122
188
|
}
|
|
123
189
|
|
|
124
190
|
/**
|
|
@@ -144,18 +210,455 @@ export function upsertManagedBlock(content, block) {
|
|
|
144
210
|
}
|
|
145
211
|
|
|
146
212
|
/**
|
|
147
|
-
*
|
|
148
|
-
*
|
|
213
|
+
* True when older scaffold prose sits outside the markers.
|
|
214
|
+
* Incomplete markers return false (that case has its own skip note).
|
|
215
|
+
* @param {string} content
|
|
149
216
|
*/
|
|
150
|
-
export function
|
|
217
|
+
export function hasLegacyAgentsProse(content) {
|
|
218
|
+
const begin = content.indexOf(BLOCK_BEGIN);
|
|
219
|
+
const end = content.indexOf(BLOCK_END);
|
|
220
|
+
let outside = content;
|
|
221
|
+
if (begin !== -1 && end !== -1 && end >= begin) {
|
|
222
|
+
outside = content.slice(0, begin) + content.slice(end + BLOCK_END.length);
|
|
223
|
+
} else if (begin !== -1 || end !== -1) {
|
|
224
|
+
return false;
|
|
225
|
+
}
|
|
226
|
+
return (
|
|
227
|
+
outside.includes('## Stagepass feature set') || outside.includes('## Safe development rules (beginners)')
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Cursor project rule. alwaysApply so api/ and Webflow snippets are covered.
|
|
233
|
+
*/
|
|
234
|
+
export function buildCursorRule() {
|
|
235
|
+
return ['---', NEW_CURSOR_FRONT, '---', '', buildCursorPointerBlock(), ''].join('\n');
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Create or refresh the Cursor rule only for a Cursor project, an existing
|
|
240
|
+
* rule file, or an explicit `--cursor-rule`.
|
|
241
|
+
* @param {{ cursorDirExists?: boolean, cursorRule?: boolean, ruleExists?: boolean }} [opts]
|
|
242
|
+
* @returns {boolean}
|
|
243
|
+
*/
|
|
244
|
+
export function shouldWriteCursorRule(opts = {}) {
|
|
245
|
+
return opts.ruleExists === true || opts.cursorDirExists === true || opts.cursorRule === true;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Doctor check. No result when the project has no `.cursor/` directory.
|
|
250
|
+
* @param {{ cursorDirExists?: boolean, rule?: string | null }} input
|
|
251
|
+
* @returns {{ status: 'ok'|'warn', message: string, detail?: string } | null}
|
|
252
|
+
*/
|
|
253
|
+
export function assessCursorRule(input) {
|
|
254
|
+
if (input.cursorDirExists !== true) return null;
|
|
255
|
+
if (input.rule == null) {
|
|
256
|
+
return {
|
|
257
|
+
status: 'warn',
|
|
258
|
+
message: '.cursor/rules/stagepass.mdc is missing',
|
|
259
|
+
detail: 'Run stagepass upgrade to add the pointer to AGENTS.stagepass.md',
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
const block = buildCursorPointerBlock();
|
|
263
|
+
const hasMarkers = input.rule.includes(BLOCK_BEGIN) && input.rule.includes(BLOCK_END);
|
|
264
|
+
if (!hasMarkers) {
|
|
265
|
+
return {
|
|
266
|
+
status: 'warn',
|
|
267
|
+
message: '.cursor/rules/stagepass.mdc has no Stagepass markers',
|
|
268
|
+
detail: 'Left unchanged. Add the markers or replace the file, then run stagepass upgrade.',
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
if (!input.rule.includes(block) || input.rule.includes(OLD_CURSOR_FRONT)) {
|
|
272
|
+
return {
|
|
273
|
+
status: 'warn',
|
|
274
|
+
message: '.cursor/rules/stagepass.mdc is out of date',
|
|
275
|
+
detail: 'Run stagepass upgrade to refresh the managed block',
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
return {
|
|
279
|
+
status: 'ok',
|
|
280
|
+
message: 'Cursor rule points at AGENTS.stagepass.md',
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Replace the previous generated frontmatter when it is still byte-identical.
|
|
286
|
+
* Any other frontmatter is left alone.
|
|
287
|
+
* @param {string} content
|
|
288
|
+
*/
|
|
289
|
+
export function migrateCursorRuleContent(content) {
|
|
290
|
+
if (!content.includes(OLD_CURSOR_FRONT)) return content;
|
|
291
|
+
return content.replace(OLD_CURSOR_FRONT, NEW_CURSOR_FRONT);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* @param {string} markdown guide body, without the managed header
|
|
296
|
+
* @param {string} [cliVersion]
|
|
297
|
+
*/
|
|
298
|
+
export function renderStagepassAgentsFile(markdown, cliVersion = CLI_VERSION) {
|
|
299
|
+
const md = markdown.endsWith('\n') ? markdown : `${markdown}\n`;
|
|
300
|
+
const body = `${STAGEPASS_AGENTS_NOTICE}\n\n${md}`;
|
|
301
|
+
const header = `<!-- stagepass:managed cli=${cliVersion} sha256=${sha256(body)} -->`;
|
|
302
|
+
return `${header}\n${body}`;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* @param {string} raw
|
|
307
|
+
* @returns {{ status: 'managed', cli: string, body: string } | { status: 'edited', cli: string } | { status: 'unmanaged' }}
|
|
308
|
+
*/
|
|
309
|
+
export function inspectStagepassAgents(raw) {
|
|
310
|
+
const text = normalizeNewlines(raw);
|
|
311
|
+
const match = HEADER_RE.exec(text);
|
|
312
|
+
if (!match) return { status: 'unmanaged' };
|
|
313
|
+
const body = text.slice(match[0].length);
|
|
314
|
+
if (sha256(body) !== match[2]) return { status: 'edited', cli: match[1] };
|
|
315
|
+
return { status: 'managed', cli: match[1], body };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* @param {object} input
|
|
320
|
+
* @param {string | null} input.existing null when the file is missing
|
|
321
|
+
* @param {string} input.desired
|
|
322
|
+
* @param {boolean} input.assumeYes
|
|
323
|
+
* @param {boolean} input.interactive
|
|
324
|
+
* @returns {{ action: 'create' | 'update' | 'current' | 'ask' | 'hint', reason?: 'edited' | 'unmanaged' }}
|
|
325
|
+
*/
|
|
326
|
+
export function decideStagepassAgentsUpdate({ existing, desired, assumeYes, interactive }) {
|
|
327
|
+
if (existing == null) return { action: 'create' };
|
|
328
|
+
const found = inspectStagepassAgents(existing);
|
|
329
|
+
if (normalizeNewlines(existing) === normalizeNewlines(desired)) return { action: 'current' };
|
|
330
|
+
if (found.status === 'managed') return { action: 'update' };
|
|
331
|
+
if (assumeYes) return { action: 'update', reason: found.status };
|
|
332
|
+
if (interactive) return { action: 'ask', reason: found.status };
|
|
333
|
+
return { action: 'hint', reason: found.status };
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function langLabel(lang) {
|
|
337
|
+
if (lang === 'ts') return 'TypeScript';
|
|
338
|
+
if (lang === 'js') return 'JavaScript';
|
|
339
|
+
return 'not set';
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function phpLabel(ctx) {
|
|
343
|
+
if (!ctx.php) return 'off';
|
|
344
|
+
if (ctx.phpBoilerplate) return 'on (`api/lib/` is present)';
|
|
345
|
+
return 'on, but `api/lib/` is missing';
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* @param {object} ctx
|
|
350
|
+
* @param {string} ctx.name
|
|
351
|
+
* @param {string | null} ctx.domain
|
|
352
|
+
* @param {string[]} ctx.modules
|
|
353
|
+
* @param {boolean} ctx.php
|
|
354
|
+
* @param {boolean} ctx.phpBoilerplate
|
|
355
|
+
* @param {'ts' | 'js' | null} ctx.lang
|
|
356
|
+
* @param {string | null} ctx.origin
|
|
357
|
+
* @param {string | null} ctx.production
|
|
358
|
+
* @param {string | null} ctx.configFile
|
|
359
|
+
* @param {string[]} ctx.types
|
|
360
|
+
* @param {boolean} ctx.modulesDependency
|
|
361
|
+
* @param {string} [ctx.cdn] `stagepass` (default) or `jsdelivr`
|
|
362
|
+
* @param {string} [ctx.loaderVersion] Resolved loader pin used in official snippets
|
|
363
|
+
*/
|
|
364
|
+
export function buildStagepassGuide(ctx) {
|
|
365
|
+
const name = ctx.name || 'project';
|
|
366
|
+
const domain = ctx.domain || `${name}.sp`;
|
|
367
|
+
const linkName = domain.endsWith('.sp') ? domain.slice(0, -3) : name;
|
|
368
|
+
const origin = ctx.origin || null;
|
|
369
|
+
const openHost = origin || `${linkName}.webflow.io`;
|
|
370
|
+
const configFile = ctx.configFile;
|
|
371
|
+
const types = Array.isArray(ctx.types) ? ctx.types : ['@stagepass/loader'];
|
|
372
|
+
const loaderVersion = ctx.loaderVersion || SNIPPET_LOADER_VERSION;
|
|
373
|
+
const cdnChoice = normalizeCdnChoice(ctx.cdn) || 'stagepass';
|
|
374
|
+
const officialLoaderUrl = stagepassPackageUrl(
|
|
375
|
+
'loader',
|
|
376
|
+
`@${loaderVersion}`,
|
|
377
|
+
'loader.min.js',
|
|
378
|
+
{ cdn: 'stagepass' }
|
|
379
|
+
);
|
|
380
|
+
const jsdelivrLoaderUrl = stagepassPackageUrl(
|
|
381
|
+
'loader',
|
|
382
|
+
'@2',
|
|
383
|
+
'loader.min.js',
|
|
384
|
+
{ cdn: 'jsdelivr' }
|
|
385
|
+
);
|
|
386
|
+
const cdnLine =
|
|
387
|
+
cdnChoice === 'jsdelivr'
|
|
388
|
+
? `- **CDN:** This project uses jsDelivr (major pin \`@2\`), for example \`${jsdelivrLoaderUrl}\`. The Stagepass CDN exact pin is the alternative (\`${officialLoaderUrl}\`).`
|
|
389
|
+
: `- **CDN:** Stagepass CDN first, exact pin, full file path, no \`/dist/\` segment, for example \`${officialLoaderUrl}\`. jsDelivr is the alternative (\`${jsdelivrLoaderUrl}\`).`;
|
|
390
|
+
const parts = [
|
|
391
|
+
`# Stagepass (${name})`,
|
|
392
|
+
'',
|
|
393
|
+
'Authoritative Stagepass guide for this project. Follow it for `src/`, `api/`, and Webflow custom code.',
|
|
394
|
+
'',
|
|
395
|
+
'## This project',
|
|
396
|
+
'',
|
|
397
|
+
`- Name: \`${name}\``,
|
|
398
|
+
`- Local domain: \`${domain}\``,
|
|
399
|
+
`- Language: ${langLabel(ctx.lang)}${configFile ? ` (\`${configFile}\`)` : ''}`,
|
|
400
|
+
`- Staging origin: ${origin ? `\`${origin}\`` : 'not set in stagepass.json'}`,
|
|
401
|
+
`- Production: ${ctx.production ? `\`${ctx.production}\`` : 'not set in stagepass.json'}`,
|
|
402
|
+
`- Modules: ${formatModules(ctx.modules)}`,
|
|
403
|
+
`- PHP: ${phpLabel(ctx)}`,
|
|
404
|
+
`- Guide written for \`@stagepass/cli\` ${CLI_VERSION}, \`@stagepass/loader\` ${LOADER_VERSION}, \`@stagepass/modules\` ${MODULES_VERSION}.`,
|
|
405
|
+
'',
|
|
406
|
+
'## Feature set',
|
|
407
|
+
'',
|
|
408
|
+
'- **CLI:** local `.sp` HTTPS domains (Caddy), DNS, optional PHP. Day to day: `stagepass start`, `stagepass link`, `stagepass build`, `stagepass watch`, `stagepass dev`. Also `doctor`, `certs`, `autostart`, `daemon`, `new`, `upgrade`.',
|
|
409
|
+
'- **Loader:** swaps tagged production assets for local URLs while a session is active (`?stagepass=' +
|
|
410
|
+
domain +
|
|
411
|
+
'`).',
|
|
412
|
+
'- **Session:** `localStorage` key `stagepass_domain`, JSON `{ domain, expires }` (default 12 h).',
|
|
413
|
+
'- **Modules:** separate script tags after `loader.min.js`. This file documents only the modules declared in `stagepass.json`.',
|
|
414
|
+
'- **Runtime:** call `sp` (same object as `window.stagepass`).',
|
|
415
|
+
cdnLine,
|
|
416
|
+
'',
|
|
417
|
+
'## Safe rules',
|
|
418
|
+
'',
|
|
419
|
+
'1. **No secrets in frontend code.** API keys, tokens, and passwords must never ship in JS or CSS served to the browser.',
|
|
420
|
+
'2. **No `innerHTML` with untrusted data.** Prefer `textContent`, `createElement`, or trusted, sanitized markup.',
|
|
421
|
+
'3. **No `eval` or string-built scripts** with user or CMS input.',
|
|
422
|
+
'4. **Pin versions** for production embeds (exact pin on the Stagepass CDN, or jsDelivr major pin `@2`).',
|
|
423
|
+
'5. **Review before publishing.** Read the diff for asset tags, CORS origins, and Webflow Custom Code.',
|
|
424
|
+
'6. **Keep Stagepass tags intact.** Use `data-src` / `data-href` plus `data-stagepass` (and optional `data-stagepass-path`) so production visitors keep production URLs.',
|
|
425
|
+
'7. **Do not commit secrets.** Keep `.env*` out of git.',
|
|
426
|
+
ctx.php
|
|
427
|
+
? '8. **PHP is on.** Follow the PHP section below. Use the shipped helpers and `action_catalog()`. Do not add a second request stack.'
|
|
428
|
+
: '8. **PHP is off** in `stagepass.json`. Do not add PHP endpoints until the user enables PHP with the CLI.',
|
|
429
|
+
'',
|
|
430
|
+
'## Local workflow',
|
|
431
|
+
'',
|
|
432
|
+
'Prefer the Stagepass commands. npm scripts are only a fallback.',
|
|
433
|
+
'',
|
|
434
|
+
'```bash',
|
|
435
|
+
'stagepass start',
|
|
436
|
+
`stagepass link ${linkName}`,
|
|
437
|
+
'stagepass dev',
|
|
438
|
+
'```',
|
|
439
|
+
'',
|
|
440
|
+
'- `stagepass start` starts Caddy and PHP.',
|
|
441
|
+
'- `stagepass link` binds this directory to the `.sp` domain. Without `--origin` it uses `origin` and `production` from `stagepass.json`.',
|
|
442
|
+
ctx.php
|
|
443
|
+
? '- `stagepass dev` rebuilds the stable `dist/main.js` and `dist/styles.css` and serves live reload on the linked domain. With PHP on, a change under `api/` or `.php/` reloads the page too (same debounce). It ignores `.env`, `.php/.env`, `.php/rate-limit/`, logs, pid files, key and certificate files, and editor temp files.'
|
|
444
|
+
: '- `stagepass dev` rebuilds the stable `dist/main.js` and `dist/styles.css` and serves live reload on the linked domain.',
|
|
445
|
+
'- `stagepass watch` is that rebuild without live reload.',
|
|
446
|
+
'- `stagepass build` writes content hashes, SRI, and `dist/manifest.json`. Watch and dev leave the manifest as the last build wrote it.',
|
|
447
|
+
'',
|
|
448
|
+
`Then open \`https://${openHost}/?stagepass=${domain}\`.`,
|
|
449
|
+
'',
|
|
450
|
+
'Fallback (no Stagepass live reload):',
|
|
451
|
+
'',
|
|
452
|
+
'```bash',
|
|
453
|
+
'npm run build',
|
|
454
|
+
'npm run watch',
|
|
455
|
+
'npm run dev',
|
|
456
|
+
'```',
|
|
457
|
+
'',
|
|
458
|
+
'`npm run dev` runs `npm run watch`. It does not start live reload. Prefer `stagepass dev`.',
|
|
459
|
+
'',
|
|
460
|
+
'## Types',
|
|
461
|
+
'',
|
|
462
|
+
];
|
|
463
|
+
|
|
464
|
+
if (configFile) {
|
|
465
|
+
parts.push(
|
|
466
|
+
`\`${configFile}\` lists \`compilerOptions.types\`: \`${JSON.stringify(types)}\`. The list follows \`modules\` in \`stagepass.json\`. A module that is not declared has no types, so the editor flags \`sp.<module>\` calls that would fail on the live site.`
|
|
467
|
+
);
|
|
468
|
+
} else {
|
|
469
|
+
parts.push(
|
|
470
|
+
`Editor types for the declared modules: \`${JSON.stringify(types)}\`. \`stagepass upgrade\` writes them to \`stagepass.d.ts\` when it cannot edit a \`compilerOptions.types\` array. A module that is not declared has no types.`
|
|
471
|
+
);
|
|
472
|
+
}
|
|
473
|
+
if (ctx.modulesDependency === false && ctx.modules.length > 0) {
|
|
474
|
+
parts.push(
|
|
475
|
+
'',
|
|
476
|
+
'`@stagepass/modules` is not in `package.json` yet, so types stay on `@stagepass/loader` until that dependency is added. `stagepass upgrade` adds it when modules are declared. It does not run `npm install`.'
|
|
477
|
+
);
|
|
478
|
+
} else {
|
|
479
|
+
parts.push(
|
|
480
|
+
'',
|
|
481
|
+
'After enabling a module (Webflow script tag plus `stagepass.json`), run `stagepass upgrade`.'
|
|
482
|
+
);
|
|
483
|
+
}
|
|
484
|
+
parts.push('', buildGuideBody(ctx.modules));
|
|
485
|
+
if (ctx.php) {
|
|
486
|
+
parts.push('', ctx.phpBoilerplate ? buildPhpSection() : buildPhpMissingSection());
|
|
487
|
+
}
|
|
488
|
+
return parts.join('\n');
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function buildPhpMissingSection() {
|
|
151
492
|
return [
|
|
152
|
-
'
|
|
153
|
-
'
|
|
154
|
-
'
|
|
155
|
-
'
|
|
156
|
-
'
|
|
493
|
+
'## PHP',
|
|
494
|
+
'',
|
|
495
|
+
'`stagepass.json` has `"php": true`, but `api/lib/` is not in this project. The Stagepass PHP boilerplate is missing.',
|
|
496
|
+
'',
|
|
497
|
+
'Ask the user to add it with the CLI. Do not rebuild `api/action.php`, `api/lib/`, `api/actions.php`, or `.php/config.php` yourself. `stagepass upgrade` does not copy those files. Scaffold a throwaway project with `stagepass new <name> --php --yes --no-link` and copy `api/` and `.php/` across, without overwriting files the user already edited.',
|
|
498
|
+
].join('\n');
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function buildPhpSection() {
|
|
502
|
+
return [
|
|
503
|
+
'## PHP',
|
|
504
|
+
'',
|
|
505
|
+
'Plain PHP 8.2 or newer. No framework, no Composer, no mail. `api/action.php` is the only public PHP file.',
|
|
506
|
+
'',
|
|
507
|
+
'### Layout',
|
|
508
|
+
'',
|
|
509
|
+
'- `api/action.php` routes the request. Leave it alone.',
|
|
510
|
+
'- `api/actions.php` defines `action_catalog()`. This is the allowlist.',
|
|
511
|
+
'- `api/actions/<name>.php` is one handler. The file returns a callable.',
|
|
512
|
+
'- `api/lib/*` holds the helpers below. Use them. Do not copy them into an action.',
|
|
513
|
+
'- `.php/` is config and secrets (`private_dir()`). The scaffold template calls this folder `php-private/`.',
|
|
514
|
+
'- `api/.env.example` is the env template. Copy it to `.env` in the project root (the folder that contains `api/`). `load_config()` also reads `.php/.env`. It does not read `api/.env`.',
|
|
515
|
+
'',
|
|
516
|
+
'### Request flow',
|
|
517
|
+
'',
|
|
518
|
+
'1. `api/action.php` defines `STAGEPASS_PHP_ENTRY`, loads `api/lib/bootstrap.php` and `api/actions.php`, installs the error handlers, and calls `load_config()`.',
|
|
519
|
+
'2. `apply_cors_headers()` runs for the request `Origin`. An `OPTIONS` preflight is `204` when the origin is allowed, and `respond_fail` `403` when it is not.',
|
|
520
|
+
'3. `parse_input()` reads the query, then a JSON or form body. The `action` field selects an entry from `action_catalog()`. An unknown name is `respond_fail` `404`.',
|
|
521
|
+
'4. The method must be in the entry `methods`, or the response is `405`. `origin: "required"` rejects an empty `Origin` and an empty allowlist (`403`). A present `Origin` must be on `ALLOWED_ORIGINS`.',
|
|
522
|
+
'5. When the entry sets `rate_limit`, the router checks `rate_limit_storage_available()` and `rate_limit_allows()` with `client_ip()`. A hit is `429`.',
|
|
523
|
+
'6. A filled honeypot returns `respond_success` and does not run the handler.',
|
|
524
|
+
'7. `load_handler()` loads `api/actions/<file>` and the router calls that callable with `($input, $config)`. The return value is sent with `respond_success`.',
|
|
525
|
+
'',
|
|
526
|
+
'Uncaught exceptions: `ValidationException` becomes HTTP 422, status `fail`. Anything else is logged with `error_log` and returned as a generic HTTP 500, status `error`. `display_errors` stays off.',
|
|
527
|
+
'',
|
|
528
|
+
'### Helpers',
|
|
529
|
+
'',
|
|
530
|
+
'Signatures match the files in `api/lib/`, `api/lib/bootstrap.php`, and `api/actions.php`.',
|
|
531
|
+
'',
|
|
532
|
+
'Config (`api/lib/config.php`):',
|
|
533
|
+
'',
|
|
534
|
+
'- `project_root(): string`. Parent of `api/`.',
|
|
535
|
+
'- `private_dir(): string`. Returns `project_root() . \'/.php\'` for config and rate-limit files.',
|
|
536
|
+
'- `load_dotenv(string $path): void`. Loads `KEY=value` lines. Skips keys that are already set in the environment.',
|
|
537
|
+
'- `env_string(string $key, string $default = \'\'): string`. Returns the env value, or `$default` when unset.',
|
|
538
|
+
'- `env_int(string $key, int $default): int`. Integer env value, or `$default` when unset or not an integer.',
|
|
539
|
+
'- `env_list(string $key): array`. Comma-separated env value as a list of trimmed, unique strings.',
|
|
540
|
+
'- `load_config(): array`. Reads the project-root `.env`, then `.php/.env`, then optional `.php/config.php` (or a project-root `config.php`). File values override the env defaults.',
|
|
541
|
+
'- `is_local_env(array $config): bool`. True only when `APP_ENV` is `local`. That is what registers the `boom` action.',
|
|
542
|
+
'',
|
|
543
|
+
'Request (`api/lib/request.php`):',
|
|
544
|
+
'',
|
|
545
|
+
'- `request_method(): string`. Uppercase `REQUEST_METHOD`.',
|
|
546
|
+
'- `request_origin(): string`. Trimmed `HTTP_ORIGIN`, or empty.',
|
|
547
|
+
'- `client_ip(?array $config = null): string`. Uses `REMOTE_ADDR` unless that address is listed in `TRUSTED_PROXIES`. Only then it reads `TRUSTED_PROXY_HEADER` (`x-forwarded-for` by default, or `forwarded`). Hops are walked from the right. Trusted proxies are skipped. An invalid hop in that suffix falls back to `REMOTE_ADDR`.',
|
|
548
|
+
'- `parse_input(int $maxBodyBytes): array`. Query parameters, with JSON or form body fields winning on `POST`, `PUT`, and `PATCH`.',
|
|
549
|
+
'- `input_string(array $input, string $key): string`. One trimmed string field, or empty.',
|
|
550
|
+
'',
|
|
551
|
+
'Response (`api/lib/response.php`). JSend object `{ status, data, message }`.',
|
|
552
|
+
'',
|
|
553
|
+
'- `respond_success($data = null, ?string $message = null, int $http = 200): never`. Status `success`.',
|
|
554
|
+
'- `respond_fail($data, ?string $message = null, int $http = 400): never`. Status `fail`: a client error (4xx) with `data`.',
|
|
555
|
+
'- `respond_error(string $message, int $http = 500, $data = null): never`. Status `error`: a server error (5xx) with `message`.',
|
|
556
|
+
'',
|
|
557
|
+
'Security (`api/lib/security.php`):',
|
|
558
|
+
'',
|
|
559
|
+
'- `origin_is_allowed(string $origin, array $allowed): bool`. Exact string match. Empty origin or empty allowlist is false.',
|
|
560
|
+
'- `apply_cors_headers(string $origin, array $allowed): void`. Sends CORS headers only for an allowed origin. Methods are `GET`, `POST`, `OPTIONS`.',
|
|
561
|
+
'- `honeypot_is_filled(array $input, string $field): bool`. True when that field is non-empty.',
|
|
562
|
+
'- `rate_limit_allows(string $ip, string $action, int $max, int $window, ?string $env = null): bool`. True when the request may proceed. A storage fault logs and, unless `APP_ENV` is `local`, `development`, or `dev`, ends the request with HTTP 503.',
|
|
563
|
+
'- `rate_limit_storage_available(string $env): bool`. False when the rate-limit directory cannot be used. The other `rate_limit_*` functions in this file are internal. Do not call them from an action.',
|
|
564
|
+
'',
|
|
565
|
+
'Validate (`api/lib/validate.php`):',
|
|
566
|
+
'',
|
|
567
|
+
'- `validate_required(array $input, string $key, array &$errors): void`. Sets a field error when the string is empty.',
|
|
568
|
+
'- `validate_email(array $input, string $key, array &$errors): void`. Checks a non-empty value with `FILTER_VALIDATE_EMAIL`.',
|
|
569
|
+
'- `validate_max_length(array $input, string $key, int $max, array &$errors): void`. Checks string length.',
|
|
570
|
+
'- `ValidationException`. Throw it with the field-error array. The router turns it into HTTP 422, status `fail`.',
|
|
571
|
+
'',
|
|
572
|
+
'Bootstrap (`api/lib/bootstrap.php`) and catalog (`api/actions.php`):',
|
|
573
|
+
'',
|
|
574
|
+
'- `load_handler(string $file): callable`. The name must match `^[a-z0-9_-]+\\.php$` and the file must live in `api/actions/`. The file returns a callable.',
|
|
575
|
+
'- `action_catalog(array $config): array`. Map of action name to `{ file, methods, honeypot, rate_limit, origin }`. `origin` is `required` or `optional`. The `boom` entry exists only when `is_local_env($config)` is true.',
|
|
576
|
+
'',
|
|
577
|
+
'### New action',
|
|
578
|
+
'',
|
|
579
|
+
'Three steps. Do not add another `.php` file next to `action.php`.',
|
|
580
|
+
'',
|
|
581
|
+
'1. Create `api/actions/newsletter.php`. Return a callable. Validate with the helpers. Read secrets with `env_string` and no secret default. Call other services with curl and a timeout. Log upstream failures with `error_log`. Send the client only a generic `respond_error`.',
|
|
582
|
+
'',
|
|
583
|
+
'```php',
|
|
584
|
+
'<?php',
|
|
585
|
+
'declare(strict_types=1);',
|
|
586
|
+
'',
|
|
587
|
+
"if (!defined('STAGEPASS_PHP_ENTRY')) {",
|
|
588
|
+
' http_response_code(404);',
|
|
589
|
+
' exit;',
|
|
590
|
+
'}',
|
|
591
|
+
'',
|
|
592
|
+
'return static function (array $input, array $config): array {',
|
|
593
|
+
' $errors = [];',
|
|
594
|
+
" validate_required($input, 'email', $errors);",
|
|
595
|
+
" validate_email($input, 'email', $errors);",
|
|
596
|
+
' if ($errors !== []) {',
|
|
597
|
+
' throw new ValidationException($errors);',
|
|
598
|
+
' }',
|
|
599
|
+
'',
|
|
600
|
+
" $token = env_string('CRM_TOKEN');",
|
|
601
|
+
" if ($token === '') {",
|
|
602
|
+
" respond_error('The service is not configured.', 500);",
|
|
603
|
+
' }',
|
|
604
|
+
'',
|
|
605
|
+
" $ch = curl_init('https://crm.example.com/v1/contacts');",
|
|
606
|
+
' curl_setopt_array($ch, [',
|
|
607
|
+
' CURLOPT_POST => true,',
|
|
608
|
+
" CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $token, 'Content-Type: application/json'],",
|
|
609
|
+
" CURLOPT_POSTFIELDS => json_encode(['email' => input_string($input, 'email')], JSON_THROW_ON_ERROR),",
|
|
610
|
+
' CURLOPT_RETURNTRANSFER => true,',
|
|
611
|
+
' CURLOPT_TIMEOUT => 8,',
|
|
612
|
+
' CURLOPT_CONNECTTIMEOUT => 3,',
|
|
613
|
+
' ]);',
|
|
614
|
+
' $raw = curl_exec($ch);',
|
|
615
|
+
' $errno = curl_errno($ch);',
|
|
616
|
+
' $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);',
|
|
617
|
+
' curl_close($ch);',
|
|
618
|
+
'',
|
|
619
|
+
' if ($raw === false || $errno !== 0 || $status < 200 || $status >= 300) {',
|
|
620
|
+
" error_log('stagepass-php: crm request failed, status ' . $status);",
|
|
621
|
+
" respond_error('The request could not be completed. Try again later.', 502);",
|
|
622
|
+
' }',
|
|
623
|
+
'',
|
|
624
|
+
" return ['subscribed' => true];",
|
|
625
|
+
'};',
|
|
626
|
+
'```',
|
|
627
|
+
'',
|
|
628
|
+
'2. Register the name in `action_catalog()`:',
|
|
629
|
+
'',
|
|
630
|
+
'```php',
|
|
631
|
+
"'newsletter' => [",
|
|
632
|
+
" 'file' => 'newsletter.php',",
|
|
633
|
+
" 'methods' => ['POST'],",
|
|
634
|
+
" 'honeypot' => true,",
|
|
635
|
+
" 'rate_limit' => true,",
|
|
636
|
+
" 'origin' => 'required',",
|
|
637
|
+
'],',
|
|
638
|
+
'```',
|
|
639
|
+
'',
|
|
640
|
+
'3. Call `POST /api/action.php` with JSON `{ "action": "newsletter", "email": "...", "website": "" }`. `website` is the honeypot (`HONEYPOT_FIELD`, default `website`). Leave it empty.',
|
|
641
|
+
'',
|
|
642
|
+
'The handler returns an array. The router sends `respond_success`. Call `respond_error` only to stop on a server-side failure. Throw `ValidationException` for bad input.',
|
|
643
|
+
'',
|
|
644
|
+
'### Rules for agents',
|
|
645
|
+
'',
|
|
646
|
+
'**MUST**',
|
|
647
|
+
'',
|
|
648
|
+
'- Use `action_catalog()`, `load_handler()`, and the helpers in `api/lib/`.',
|
|
649
|
+
'- Read secrets with `env_string()` or `load_config()`. A missing required secret calls `respond_error` (or fails before any I/O). No default token, key, or remote id.',
|
|
650
|
+
'- Log upstream failures with `error_log`. The client gets a generic `respond_error` message.',
|
|
651
|
+
'- Keep personal data out of the web root. If a file is unavoidable, put it under `private_dir()` and still deny hidden paths.',
|
|
652
|
+
'- Gate debug behavior with `APP_ENV` and `is_local_env()`. The `boom` action is the pattern.',
|
|
157
653
|
'',
|
|
158
|
-
|
|
654
|
+
'**NEVER**',
|
|
159
655
|
'',
|
|
656
|
+
'- Write another dotenv loader, JSON responder, CORS layer, method check, or origin check.',
|
|
657
|
+
'- Put secrets, CRM ids, or a debug token in a default argument or a fallback string.',
|
|
658
|
+
'- Turn on debug with a query parameter. There is no debug token.',
|
|
659
|
+
'- Set `display_errors` to on.',
|
|
660
|
+
'- Store personal data in a web-visible file.',
|
|
661
|
+
'- Return an upstream body, status payload, or error string to the client.',
|
|
662
|
+
'- Add a new public endpoint as its own `.php` file next to `action.php`.',
|
|
160
663
|
].join('\n');
|
|
161
664
|
}
|