@stagepass/cli 2.4.0 → 2.5.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.
@@ -1,16 +1,18 @@
1
1
  import fs from 'fs-extra';
2
2
  import path from 'node:path';
3
+ import { stagepassPackageUrl } from './cdn-base.js';
3
4
 
4
5
  /**
5
6
  * Canonical CDN embed snippets recommended by Stagepass docs.
6
7
  * Doctor checks these so generated / documented snippets never drift to @latest.
8
+ * Host comes from STAGEPASS_PACKAGE_CDN.
7
9
  */
8
10
  export const RECOMMENDED_CDN_SNIPPETS = Object.freeze([
9
- 'https://cdn.jsdelivr.net/npm/@stagepass/loader@2/dist/loader.min.js',
10
- 'https://cdn.jsdelivr.net/npm/@stagepass/modules@2/dist/inject.min.js',
11
- 'https://cdn.jsdelivr.net/npm/@stagepass/modules@2/dist/cookies.min.js',
12
- 'https://cdn.jsdelivr.net/npm/@stagepass/modules@2/dist/maintenance.min.js',
13
- 'https://cdn.jsdelivr.net/npm/@stagepass/modules@2/dist/all.min.js',
11
+ stagepassPackageUrl('loader', '@2', 'loader.min.js'),
12
+ stagepassPackageUrl('modules', '@2', 'inject.min.js'),
13
+ stagepassPackageUrl('modules', '@2', 'cookies.min.js'),
14
+ stagepassPackageUrl('modules', '@2', 'maintenance.min.js'),
15
+ stagepassPackageUrl('modules', '@2', 'all.min.js'),
14
16
  ]);
15
17
 
16
18
  /**
@@ -9,7 +9,9 @@ import path from 'node:path';
9
9
  import fs from 'fs-extra';
10
10
  import { detectSite, describeDetection } from './site-detect.js';
11
11
  import { formatModules, sameModules } from './project-modules.js';
12
+ import { assessCursorRule, CURSOR_RULE_PATH } from './ai-guide.js';
12
13
  import {
14
+ cursorDirPresent,
13
15
  declaredModules,
14
16
  phpFromStagepassConfig,
15
17
  readStagepassJson,
@@ -50,6 +52,21 @@ export async function runProjectSiteChecks(opts = {}) {
50
52
  checks.push({ id: 'project.modules', status: 'ok', message: `Declared modules: ${formatModules(declared)}` });
51
53
  }
52
54
 
55
+ if (await cursorDirPresent(cwd)) {
56
+ const rulePath = path.join(cwd, CURSOR_RULE_PATH);
57
+ /** @type {string | null} */
58
+ let rule = null;
59
+ if (await fs.pathExists(rulePath)) {
60
+ try {
61
+ rule = await fs.readFile(rulePath, 'utf8');
62
+ } catch {
63
+ rule = null;
64
+ }
65
+ }
66
+ const cursor = assessCursorRule({ cursorDirExists: true, rule });
67
+ if (cursor) checks.push({ id: 'project.cursor', ...cursor });
68
+ }
69
+
53
70
  const php = phpFromStagepassConfig(sp.data);
54
71
  if (php === false) {
55
72
  checks.push({
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Plan a missing PHP `.htaccess` for `stagepass upgrade`.
3
+ * Covered when the file contains the shipped line `RewriteRule "(^|/)\." - [F]`.
4
+ * Symlinks and directories are not followed and are not replaced.
5
+ */
6
+
7
+ import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import fs from 'fs-extra';
10
+
11
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
12
+
13
+ /** Exact deny line from templates/project/htaccess. */
14
+ export const HTACCESS_DENY_LINE = 'RewriteRule "(^|/)\\." - [F]';
15
+
16
+ const HTACCESS_DOCS = 'https://stagepass.one/docs/php/ and api/README.md';
17
+
18
+ export function defaultHtaccessTemplatePath() {
19
+ return path.join(__dirname, '../../templates/project/htaccess');
20
+ }
21
+
22
+ export function htaccessHasDenyRule(source) {
23
+ return String(source).includes(HTACCESS_DENY_LINE);
24
+ }
25
+
26
+ /**
27
+ * Does not write. `php` must be the boolean from stagepass.json.
28
+ *
29
+ * @param {object} options
30
+ * @param {string} options.cwd
31
+ * @param {boolean} [options.php]
32
+ * @param {{ lstat: Function, readFile: Function }} [options.fse]
33
+ * @returns {Promise<{ action: 'skip' | 'create' | 'present' | 'hint' | 'blocked', content?: string, note?: string }>}
34
+ */
35
+ export async function planHtaccessUpgrade(options) {
36
+ if (options.php !== true) return { action: 'skip' };
37
+ const fse = options.fse || fs;
38
+ const abs = path.join(options.cwd, '.htaccess');
39
+ /** @type {import('node:fs').Stats} */
40
+ let st;
41
+ try {
42
+ st = await fse.lstat(abs);
43
+ } catch (err) {
44
+ if (err && /** @type {{ code?: string }} */ (err).code === 'ENOENT') {
45
+ try {
46
+ const content = await fse.readFile(defaultHtaccessTemplatePath(), 'utf8');
47
+ return { action: 'create', content };
48
+ } catch (readErr) {
49
+ const detail = readErr instanceof Error ? readErr.message : String(readErr);
50
+ return {
51
+ action: 'blocked',
52
+ note: `Could not read the .htaccess template (${detail}). Nothing was written.`,
53
+ };
54
+ }
55
+ }
56
+ return { action: 'blocked', note: '.htaccess could not be inspected; left unchanged.' };
57
+ }
58
+ if (st.isSymbolicLink()) {
59
+ return { action: 'blocked', note: '.htaccess is a symlink; left unchanged.' };
60
+ }
61
+ if (st.isDirectory()) {
62
+ return { action: 'blocked', note: '.htaccess is a directory; left unchanged.' };
63
+ }
64
+ if (!st.isFile()) {
65
+ return { action: 'blocked', note: '.htaccess is not a regular file; left unchanged.' };
66
+ }
67
+ /** @type {string} */
68
+ let raw;
69
+ try {
70
+ raw = await fse.readFile(abs, 'utf8');
71
+ } catch {
72
+ return { action: 'blocked', note: '.htaccess could not be read; left unchanged.' };
73
+ }
74
+ if (htaccessHasDenyRule(raw)) return { action: 'present' };
75
+ return {
76
+ action: 'hint',
77
+ note: `.htaccess exists and has no ${HTACCESS_DENY_LINE} line. Left unchanged. See ${HTACCESS_DOCS}.`,
78
+ };
79
+ }
@@ -6,7 +6,8 @@
6
6
  * Change classification is content-based: identical rewrites (same bytes) are
7
7
  * ignored. Only real CSS changes batch as `{type:'css'}`; any other real change
8
8
  * is `{type:'reload'}`. `manifest.json`, dotfiles, `~` backups and `.map` files
9
- * are ignored.
9
+ * are ignored. When `php` is set, `api/` and `.php/` share that debounce and
10
+ * stream. Secrets, rate-limit files, logs, pid files, and editor temps do not.
10
11
  */
11
12
 
12
13
  import http from 'node:http';
@@ -75,6 +76,32 @@ export function isIgnoredWatchBase(base) {
75
76
  );
76
77
  }
77
78
 
79
+ /** Extra project-root directories watched while `stagepass.json` has `"php": true`. */
80
+ export const PHP_WATCH_DIRS = Object.freeze(['api', '.php']);
81
+
82
+ const PHP_SECRET_EXT = /\.(pem|key|p12|pfx|crt|cer|sqlite|db)$/i;
83
+
84
+ /**
85
+ * Project-relative path (slashes) under `api/` or `.php/` that must not reload.
86
+ * Matches the publish skip for secrets, plus editor temp files.
87
+ * @param {string} rel
88
+ * @returns {boolean}
89
+ */
90
+ export function isIgnoredPhpRel(rel) {
91
+ const norm = String(rel || '').split('\\').join('/');
92
+ if (!norm || norm === '..' || norm.startsWith('../') || norm.includes('/../')) return true;
93
+ const parts = norm.split('/').filter((part) => part && part !== '.');
94
+ const base = parts[parts.length - 1] || '';
95
+ if (!base) return true;
96
+ if (base === '.env' || (base.startsWith('.env') && base !== '.env.example')) return true;
97
+ if (base.endsWith('~') || base.endsWith('.swp') || base === '.DS_Store') return true;
98
+ if (base.endsWith('.log') || base.endsWith('.pid')) return true;
99
+ if (PHP_SECRET_EXT.test(base)) return true;
100
+ const phpAt = parts.indexOf('.php');
101
+ if (phpAt !== -1 && parts[phpAt + 1] === 'rate-limit') return true;
102
+ return false;
103
+ }
104
+
78
105
  /**
79
106
  * Turn an absolute file path under outAbs into a site-relative URL path
80
107
  * (project-root relative, with leading slash). Returns null when outside or ignored.
@@ -174,6 +201,7 @@ function walkFiles(dirAbs, visit) {
174
201
  * @typedef {object} LiveServerOptions
175
202
  * @property {string} projectRoot
176
203
  * @property {string} [outDir]
204
+ * @property {boolean} [php] Also watch `api/` and `.php/` (missing dirs are skipped).
177
205
  * @property {number} [debounceMs]
178
206
  * @property {number} [maxConnections]
179
207
  * @property {number} [heartbeatMs]
@@ -211,12 +239,46 @@ export function createLiveServer(options) {
211
239
  const pending = new Set();
212
240
  /** @type {ReturnType<typeof setTimeout>|null} */
213
241
  let debounceTimer = null;
214
- /** @type {import('node:fs').FSWatcher|null} */
215
- let watcher = null;
242
+ /** @type {import('node:fs').FSWatcher[]} */
243
+ const watchers = [];
216
244
  /** @type {ReturnType<typeof setInterval>|null} */
217
245
  let heartbeat = null;
218
246
  /** @type {Map<string, string>} abs path → fingerprint token */
219
247
  const fileHashes = new Map();
248
+ const phpEnabled = options.php === true;
249
+ /** @type {{ rel: string, abs: string }[]} */
250
+ const phpRoots = phpEnabled
251
+ ? PHP_WATCH_DIRS.map((rel) => ({ rel, abs: path.resolve(projectRoot, rel) }))
252
+ : [];
253
+ /** Relative dirs that received a watcher (missing dirs stay off this list). */
254
+ const phpWatched = [];
255
+ let stopped = false;
256
+
257
+ /**
258
+ * Accept a path under the output dir (dist rules) or, when PHP is on, under api/ or .php/.
259
+ * @param {string} fileAbs
260
+ * @returns {{ abs: string, url: string } | null}
261
+ */
262
+ function describeWatched(fileAbs) {
263
+ const underOut = resolveUnderOutDir(fileAbs, outAbs);
264
+ if (underOut) {
265
+ const url = toUrlPath(underOut, projectRoot, outAbs);
266
+ if (!url) return null;
267
+ return { abs: underOut, url };
268
+ }
269
+ if (!phpEnabled) return null;
270
+ const file = path.resolve(fileAbs);
271
+ for (const root of phpRoots) {
272
+ const relRoot = path.relative(root.abs, file);
273
+ if (relRoot.startsWith('..') || path.isAbsolute(relRoot) || relRoot.includes('\0')) continue;
274
+ const relProject = path.relative(projectRoot, file);
275
+ if (relProject.startsWith('..') || path.isAbsolute(relProject)) return null;
276
+ const rel = relProject.split(path.sep).join('/');
277
+ if (!rel || isIgnoredPhpRel(rel)) return null;
278
+ return { abs: file, url: '/' + rel };
279
+ }
280
+ return null;
281
+ }
220
282
 
221
283
  function rememberHash(fileAbs, token) {
222
284
  if (fileHashes.has(fileAbs)) {
@@ -232,14 +294,16 @@ export function createLiveServer(options) {
232
294
 
233
295
  function seedHashes() {
234
296
  fileHashes.clear();
235
- walkFiles(outAbs, (fileAbs) => {
236
- const safe = resolveUnderOutDir(fileAbs, outAbs);
237
- if (!safe) return;
238
- if (isIgnoredWatchBase(path.basename(safe))) return;
239
- const fp = contentFingerprint(safe);
240
- if (fp.kind === 'hash') rememberHash(safe, fp.hash);
241
- else if (fp.kind === 'large') rememberHash(safe, fp.token);
242
- });
297
+ const roots = [outAbs, ...phpRoots.map((root) => root.abs)];
298
+ for (const root of roots) {
299
+ walkFiles(root, (fileAbs) => {
300
+ const described = describeWatched(fileAbs);
301
+ if (!described) return;
302
+ const fp = contentFingerprint(described.abs);
303
+ if (fp.kind === 'hash') rememberHash(described.abs, fp.hash);
304
+ else if (fp.kind === 'large') rememberHash(described.abs, fp.token);
305
+ });
306
+ }
243
307
  }
244
308
 
245
309
  /**
@@ -250,8 +314,16 @@ export function createLiveServer(options) {
250
314
  * @returns {boolean} true when content actually changed (or deleted)
251
315
  */
252
316
  function hasContentChanged(fileAbs) {
253
- const safe = resolveUnderOutDir(fileAbs, outAbs);
254
- if (!safe) return false;
317
+ const described = describeWatched(fileAbs);
318
+ if (!described) return false;
319
+ const safe = described.abs;
320
+ try {
321
+ if (!fs.statSync(safe).isFile()) return false;
322
+ } catch (err) {
323
+ if (!(err && typeof err === 'object' && 'code' in err && err.code === 'ENOENT')) {
324
+ return true;
325
+ }
326
+ }
255
327
 
256
328
  const fp = contentFingerprint(safe);
257
329
  if (fp.kind === 'missing') {
@@ -288,13 +360,16 @@ export function createLiveServer(options) {
288
360
 
289
361
  function flushPending() {
290
362
  debounceTimer = null;
291
- if (pending.size === 0) return;
363
+ if (stopped || pending.size === 0) {
364
+ pending.clear();
365
+ return;
366
+ }
292
367
  /** @type {string[]} */
293
368
  const changed = [];
294
369
  for (const fileAbs of pending) {
295
370
  if (!hasContentChanged(fileAbs)) continue;
296
- const urlPath = toUrlPath(fileAbs, projectRoot, outAbs);
297
- if (urlPath) changed.push(urlPath);
371
+ const described = describeWatched(fileAbs);
372
+ if (described) changed.push(described.url);
298
373
  }
299
374
  pending.clear();
300
375
  if (changed.length === 0) return;
@@ -304,54 +379,84 @@ export function createLiveServer(options) {
304
379
  }
305
380
 
306
381
  function noteChange(fileAbs) {
307
- const safe = resolveUnderOutDir(fileAbs, outAbs);
308
- if (!safe) return;
309
- // Ignore junk / manifest early; defer content compare until debounce flush
310
- // so identical rewrites (and mid-write watch races) do not false-trigger.
311
- if (!toUrlPath(safe, projectRoot, outAbs)) return;
312
- pending.add(safe);
382
+ if (stopped) return;
383
+ const described = describeWatched(fileAbs);
384
+ if (!described) return;
385
+ // Defer content compare until debounce flush so identical rewrites
386
+ // (and mid-write watch races) do not false-trigger.
387
+ pending.add(described.abs);
313
388
  if (debounceTimer) clearTimeout(debounceTimer);
314
389
  debounceTimer = setTimeout(flushPending, debounceMs);
315
390
  }
316
391
 
317
- function startWatch() {
392
+ /**
393
+ * @param {string} abs
394
+ * @param {string} label
395
+ * @returns {boolean}
396
+ */
397
+ function attachWatch(abs, label) {
318
398
  try {
319
- fs.mkdirSync(outAbs, { recursive: true });
320
- } catch {
321
- /* ignore */
399
+ const st = fs.statSync(abs);
400
+ if (!st.isDirectory()) return false;
401
+ } catch (err) {
402
+ const code = err && typeof err === 'object' && 'code' in err ? err.code : '';
403
+ if (code !== 'ENOENT') {
404
+ log(
405
+ `Live reload: could not watch ${label} (${err instanceof Error ? err.message : String(err)})`
406
+ );
407
+ }
408
+ return false;
322
409
  }
323
- seedHashes();
324
410
  try {
325
- watcher = fsWatch(outAbs, { recursive: true }, (_event, filename) => {
326
- if (!filename) return;
411
+ const watcher = fsWatch(abs, { recursive: true }, (_event, filename) => {
412
+ if (!filename || stopped) return;
327
413
  const name = typeof filename === 'string' ? filename : String(filename);
328
- // Join only; resolveUnderOutDir rejects escapes (including .. segments).
329
- noteChange(path.join(outAbs, name));
414
+ // Join only; describeWatched rejects escapes (including .. segments).
415
+ noteChange(path.join(abs, name));
330
416
  });
331
417
  watcher.on('error', () => {
332
418
  /* keep server up; next change may recover */
333
419
  });
420
+ watchers.push(watcher);
421
+ return true;
334
422
  } catch (err) {
335
423
  log(
336
- `Live reload: could not watch ${outAbs} (${err instanceof Error ? err.message : String(err)})`
424
+ `Live reload: could not watch ${label} (${err instanceof Error ? err.message : String(err)})`
337
425
  );
426
+ return false;
427
+ }
428
+ }
429
+
430
+ function startWatch() {
431
+ stopped = false;
432
+ try {
433
+ fs.mkdirSync(outAbs, { recursive: true });
434
+ } catch {
435
+ /* ignore */
436
+ }
437
+ seedHashes();
438
+ attachWatch(outAbs, outAbs);
439
+ phpWatched.length = 0;
440
+ for (const root of phpRoots) {
441
+ if (attachWatch(root.abs, `${root.rel}/`)) phpWatched.push(root.rel);
338
442
  }
339
443
  }
340
444
 
341
445
  function stopWatch() {
446
+ stopped = true;
342
447
  if (debounceTimer) {
343
448
  clearTimeout(debounceTimer);
344
449
  debounceTimer = null;
345
450
  }
346
451
  pending.clear();
347
452
  fileHashes.clear();
348
- if (watcher) {
453
+ while (watchers.length) {
454
+ const watcher = watchers.pop();
349
455
  try {
350
456
  watcher.close();
351
457
  } catch {
352
458
  /* ignore */
353
459
  }
354
- watcher = null;
355
460
  }
356
461
  }
357
462
 
@@ -478,6 +583,8 @@ export function createLiveServer(options) {
478
583
  _fileHashes: fileHashes,
479
584
  _seedHashes: seedHashes,
480
585
  _hasContentChanged: hasContentChanged,
586
+ _watchers: watchers,
587
+ phpWatched,
481
588
  outAbs,
482
589
  outRel: outResolved.rel,
483
590
  };