@scrymore/scry-deployer 0.13.1-nightly.20261104035911 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,6 +33,19 @@ npx skills add epinnock/scry-node --skill ss
33
33
 
34
34
  It needs the Scry MCP connection that `scry-setup` configures.
35
35
 
36
+ ### Use your shared Scry clipboard
37
+
38
+ If you copy with Scry Copy in Scry Sync, install the `sc` skill and type `/sc`
39
+ (or `/sc turn this into a table`) to hand the newest item on your shared
40
+ clipboard (a copy, or your newest snip) to the assistant:
41
+
42
+ ```bash
43
+ npx skills add epinnock/scry-node --skill sc
44
+ ```
45
+
46
+ It also needs the Scry MCP connection. Clipboard content is treated as
47
+ untrusted data.
48
+
36
49
  ## Set up directly with the CLI
37
50
 
38
51
  `init` writes configuration and workflows, configures GitHub secrets, then
@@ -48,7 +61,7 @@ Visit the [Scry Dashboard](https://dashboard.scrymore.com) and:
48
61
  ### 2. Run the setup command
49
62
 
50
63
  ```bash
51
- npx @scrymore/scry-deployer init --projectId YOUR_PROJECT_ID --apiKey YOUR_API_KEY
64
+ npx @scrymore/scry-deployer init --project-id YOUR_PROJECT_ID --api-key YOUR_API_KEY
52
65
  ```
53
66
 
54
67
  **That's it!** 🎉
@@ -112,10 +125,10 @@ Requires Node.js 20.9 or newer (Node 18 is end of life; use `@scrymore/scry-depl
112
125
 
113
126
  ```bash
114
127
  # From npm (recommended)
115
- npx @scrymore/scry-deployer init --projectId xxx --apiKey yyy
128
+ npx @scrymore/scry-deployer init --project-id xxx --api-key yyy
116
129
 
117
130
  # From GitHub (latest from main branch)
118
- npx github:scryorg/scry-node init --projectId xxx --apiKey yyy
131
+ npx github:scryorg/scry-node init --project-id xxx --api-key yyy
119
132
  ```
120
133
 
121
134
  ### Installing as a Dependency
@@ -138,10 +151,10 @@ After installation, you can run commands using:
138
151
 
139
152
  ```bash
140
153
  # Using the scry-deployer binary
141
- npm exec -- scry-deployer init --projectId xxx --apiKey yyy
154
+ npm exec -- scry-deployer init --project-id xxx --api-key yyy
142
155
 
143
156
  # Using the scry alias
144
- npx scry init --projectId xxx --apiKey yyy
157
+ npx scry init --project-id xxx --api-key yyy
145
158
 
146
159
  # Using the storybook-deploy alias (for deploy commands)
147
160
  npx storybook-deploy --dir ./storybook-static
@@ -276,6 +289,77 @@ decorators: [(Story) => <SafeAreaProvider><SafeAreaView edges={['top']}><Story /
276
289
  the table (or to be stricter); it does not move or crop anything. Requires the app's Scry probe, since the
277
290
  frame comes from it.
278
291
 
292
+ ### Capture Command (web, build-free)
293
+
294
+ Capture every story of a web Storybook into an SCF bundle without building Storybook, then
295
+ upload the bundle. It needs `@scrymore/scry-deployer` 0.14.0 or newer.
296
+
297
+ ```bash
298
+ npx @scrymore/scry-deployer capture web # writes .scry/capture and .scry/capture-report.json
299
+ npx @scrymore/scry-deployer upload .scry/capture # validate and upload the bundle
300
+ ```
301
+
302
+ `capture web` starts the project's own Vite dev server, renders each story in headless Chromium
303
+ and writes one image and one structure tree per story. The upload makes the stories searchable
304
+ in Scry. It does not host a browsable Storybook and it does not produce a coverage report; the
305
+ default deploy command still does both.
306
+
307
+ What the project needs:
308
+
309
+ - Storybook 10 on a Vite framework with the React renderer (for example `@storybook/react-vite`).
310
+ Any other Storybook version, builder or renderer stops with a message that says which.
311
+ - `storybook` and `vite` installed in the project. They are resolved from the project.
312
+ - Playwright and its Chromium (`npx playwright install chromium`). A run by hand uses the
313
+ project's Playwright when it has one and otherwise the copy that comes with the deployer's
314
+ dependencies. The generated workflow needs `playwright` (or `@playwright/test`) in the
315
+ project, because it installs Chromium with the project's own Playwright.
316
+ - Node 20.19 or newer.
317
+
318
+ To run it in GitHub Actions, add `--capture web` to `init` (new project) or `update-workflows`
319
+ (project already set up):
320
+
321
+ ```bash
322
+ npx -y @scrymore/scry-deployer@^0.14.0 init --project-id YOUR_PROJECT_ID --api-key YOUR_API_KEY --capture web
323
+ npx -y @scrymore/scry-deployer@^0.14.0 update-workflows --capture web
324
+ ```
325
+
326
+ Keep the `@^0.14.0`. A deployer older than 0.14.0 (for example one npx has cached) does not
327
+ know `--capture`, ignores it without an error and writes the two default workflows only.
328
+
329
+ Run it at the repository root. The option first checks that the project qualifies. The check
330
+ loads the project's Storybook and Vite config, as Storybook itself does; run it only in a
331
+ repository you trust. Scry, GitHub and npm credentials are removed from the environment of
332
+ that check. If the project does not qualify, the command prints the reason, writes nothing
333
+ and exits 1. If it does:
334
+
335
+ - `.github/workflows/scry-capture-web.yml` is written. On a push to `main` or `master` it
336
+ captures every story and uploads the bundle. If the default branch has another name, change
337
+ `branches` in the file, or the workflow never runs on a push. A run started by hand
338
+ (`workflow_dispatch`) on the default branch uploads; on any other branch it is a dry run
339
+ that validates the bundle and sends nothing.
340
+ - `.github/workflows/deploy-storybook.yml` is written with `--no-analysis` in place of
341
+ `--with-analysis`. It still builds and hosts Storybook and reports coverage. It no longer
342
+ takes the screenshots a second time. (Coverage with `--coverage-execute` still renders the
343
+ stories to run them.)
344
+ - `.github/workflows/deploy-pr-preview.yml` is the same as without the option. Pull requests
345
+ keep their preview, their comment and their screenshots.
346
+
347
+ Pass `--config-dir <dir>` when the Storybook config is not in `.storybook`.
348
+
349
+ Limit in this version: the Storybook project must be at the repository root. Run from a
350
+ subfolder of the repository (a monorepo package), the option stops and writes nothing. For
351
+ such a project, copy `templates/workflows/scry-capture-web.yml` by hand and add
352
+ `working-directory`.
353
+
354
+ The workflow installs the project with its own package manager and lockfile (npm, pnpm, yarn
355
+ or bun). For pnpm it uses the version in `packageManager` in `package.json` when there is
356
+ one; otherwise pnpm 10, or pnpm 8 when the lockfile is older than version 9.
357
+
358
+ To go back, run `update-workflows` without the option and delete `scry-capture-web.yml`.
359
+
360
+ Flags, per-story settings, the report, limits and CI details are in
361
+ [docs/capture-web.md](docs/capture-web.md).
362
+
279
363
  ### Options
280
364
 
281
365
  The CLI is configured through a combination of command-line options and environment variables. Command-line options always take precedence.
@@ -1127,7 +1211,7 @@ gh auth login
1127
1211
 
1128
1212
  Or skip GitHub CLI setup and set variables manually:
1129
1213
  ```bash
1130
- npx @scrymore/scry-deployer init --projectId xxx --apiKey yyy --skip-gh-setup
1214
+ npx @scrymore/scry-deployer init --project-id xxx --api-key yyy --skip-gh-setup
1131
1215
  ```
1132
1216
 
1133
1217
  Then manually add variables in GitHub Settings → Secrets and variables → Actions.
@@ -1168,6 +1252,9 @@ It detects your package manager from the lockfile and your Storybook build scrip
1168
1252
  `package.json`, and overwrites `.github/workflows/deploy-storybook.yml` and
1169
1253
  `.github/workflows/deploy-pr-preview.yml`. Review the diff if you customised them.
1170
1254
 
1255
+ With `--capture web` (deployer 0.14.0 or newer) it also writes
1256
+ `.github/workflows/scry-capture-web.yml`; see "Capture Command (web, build-free)" above.
1257
+
1171
1258
  ### Want to customize the generated workflows?
1172
1259
 
1173
1260
  After running `init`, you can edit:
package/bin/cli.js CHANGED
@@ -877,31 +877,66 @@ async function main() {
877
877
  .option('include-source', { describe: "Also upload each capture's component source text (code.componentFile). Off by default: Scry never needs your code", type: 'boolean', default: false })
878
878
  .option('repo-root', { describe: 'Repository root that code.componentFile paths are relative to (default: cwd)', type: 'string' })
879
879
  .option('dry-run', { describe: 'Validate and zip only; print where the ZIP is', type: 'boolean', default: false })
880
+ .option('validate', { describe: 'Always run the full validation, even when capture web already validated this folder', type: 'boolean', default: false })
881
+ .option('allow-partial-bundle', { type: 'boolean', default: false, hidden: true })
880
882
  .option('verbose', { describe: 'Enable verbose logging', type: 'boolean' });
881
883
  }, async (argv) => {
882
884
  const config = loadConfig(argv);
883
- const outcome = await runUploadBundle({ ...config, path: argv.path, includeSource: argv.includeSource, repoRoot: argv.repoRoot, source: argv.source, dryRun: argv.dryRun });
885
+ const outcome = await runUploadBundle({ ...config, validate: argv.validate, path: argv.path, includeSource: argv.includeSource, repoRoot: argv.repoRoot, source: argv.source, dryRun: argv.dryRun, allowPartialBundle: argv.allowPartialBundle });
884
886
  process.exitCode = outcome.exitCode;
885
887
  })
886
- .command('capture <adapter>', 'Capture stories into a Scry Capture Format bundle (adapters: rn)', (yargs) => {
888
+ .command('capture <adapter>', 'Capture stories into a Scry Capture Format bundle (adapters: rn, web)', (yargs) => {
887
889
  return yargs
888
- .positional('adapter', { describe: 'Capture adapter', choices: ['rn'] })
889
- .option('platform', { describe: 'ios (Simulator, macOS) or android (emulator)', choices: ['ios', 'android'], demandOption: true })
890
+ .positional('adapter', { describe: 'Capture adapter', choices: ['rn', 'web'] })
891
+ .option('platform', { describe: 'rn: ios (Simulator, macOS) or android (emulator). Required for rn', choices: ['ios', 'android'] })
890
892
  .option('device', { describe: 'Simulator name (e.g. "iPhone 16") or AVD name / adb serial', type: 'string' })
891
893
  .option('app', { describe: 'Built app to install first (.app for iOS, .apk for Android)', type: 'string' })
892
894
  .option('app-id', { describe: 'Bundle id / package (default: from app.json)', type: 'string' })
893
895
  .option('open-url', { describe: 'Deep link to open after launch, e.g. exp://127.0.0.1:8081 for Expo Go (with --app-id host.exp.Exponent) or a dev client URL', type: 'string' })
894
896
  .option('build', { describe: 'Build and install the app with `expo run:<platform>` when it is not installed', type: 'boolean', default: false })
895
- .option('project-dir', { describe: 'React Native project directory (default: cwd)', type: 'string' })
897
+ .option('project-dir', { describe: 'Project directory (default: cwd)', type: 'string' })
896
898
  .option('out', { describe: 'Bundle output directory (default: <project>/.scry/capture)', type: 'string' })
897
- .option('stories', { describe: 'Comma-separated story ids to capture (default: all)', type: 'string' })
899
+ .option('stories', { describe: 'Comma-separated story ids to capture (default: all). web: writes images and a report, not an upload bundle', type: 'string' })
898
900
  .option('metro', { describe: 'Start Metro with STORYBOOK_ENABLED=true when the Storybook channel is not already up', type: 'boolean', default: true })
899
901
  .option('ws-port', { describe: 'Storybook channel port', type: 'number', default: 7007 })
900
902
  .option('settle-timeout', { describe: 'Per-story budget in ms to render and settle (two identical frames)', type: 'number', default: 10000 })
901
903
  .option('safe-area-inset', { describe: 'iOS: top unsafe-area height in points used to flag captures whose story root starts inside it (default: from the simulator model). Flagged captures get x-scry.captureWarnings ["overlaps_top_unsafe_area"]; wrap your stories in a SafeAreaView decorator', type: 'number' })
902
904
  .option('structure', { describe: 'Write an rn-fiber structure tree per story when the app exposes one', type: 'boolean', default: true })
903
- .option('verbose', { describe: 'Enable verbose logging', type: 'boolean' });
905
+ .option('config-dir', { describe: 'web: Storybook config directory (default: .storybook)', type: 'string' })
906
+ .option('workers', { describe: 'web: browser pages capturing at once (default: the CPU cores this process may use, at most 4)', type: 'number' })
907
+ .option('max-dropped', { describe: 'web: exit 1 when more than this many stories fail to capture', type: 'number', default: 0 })
908
+ .option('retries', { describe: 'web: extra tries, on a fresh page, for a story that fails', type: 'number', default: 1 })
909
+ .option('story-timeout', { describe: 'web: per-story budget in ms to render and finish its play function', type: 'number', default: 15000 })
910
+ .option('scale', { describe: 'web: device scale factor of the images, above 0 and at most 4', type: 'number', default: 1 })
911
+ .option('viewport', { describe: 'web: browser viewport WIDTHxHEIGHT', type: 'string', default: '1280x720' })
912
+ .option('fixed-time', { describe: 'web: the instant the page clock starts at for each story (ISO 8601), or "off" for the real clock (default: 2026-11-14T12:00:00Z)', type: 'string' })
913
+ .option('changed-since', { describe: 'web: capture only the stories affected by changes since this git ref. Writes images and a report, never an upload bundle', type: 'string' })
914
+ .option('list', { describe: 'web: print the story ids (with --changed-since: the affected story files) one per line and capture nothing', type: 'boolean', default: false })
915
+ .option('list-ids', { describe: 'web: with --changed-since, print the affected story ids instead of story files', type: 'boolean', default: false })
916
+ .option('report', { describe: 'web: where to write the run report JSON (default: next to the bundle, capture-report.json)', type: 'string' })
917
+ .option('allow-partial-bundle', { type: 'boolean', default: false, hidden: true })
918
+ .option('verbose', { describe: 'Enable verbose logging', type: 'boolean' })
919
+ .check((argv) => {
920
+ if (argv.adapter === 'rn' && !argv.platform) throw new Error('Missing required argument: platform');
921
+ return true;
922
+ });
904
923
  }, async (argv) => {
924
+ if (argv.adapter === 'web') {
925
+ const { runCaptureWeb } = require('../lib/capture/web/index.js');
926
+ const logger = createLogger(argv);
927
+ let exitCode = 1;
928
+ try {
929
+ const outcome = await runCaptureWeb(argv, { logger, toolVersion: DEPLOYER_VERSION, gitContext: resolveBuildGitContext() });
930
+ exitCode = outcome.exitCode;
931
+ } catch (error) {
932
+ process.stderr.write(`capture web failed: ${error.message}\n`);
933
+ if (argv.verbose && error.stack) process.stderr.write(`${error.stack}\n`);
934
+ }
935
+ // Storybook's presets and the dev server can leave handles open: end the process once the output is flushed.
936
+ process.exitCode = exitCode;
937
+ process.stdout.write('', () => process.stderr.write('', () => process.exit(exitCode)));
938
+ return;
939
+ }
905
940
  const { runCaptureRn } = require('../lib/capture/rn.js');
906
941
  const logger = createLogger(argv);
907
942
  try {
@@ -1027,6 +1062,15 @@ async function main() {
1027
1062
  default: false,
1028
1063
  alias: 'skipGhSetup'
1029
1064
  })
1065
+ .option('capture', {
1066
+ describe: 'web: also write .github/workflows/scry-capture-web.yml (build-free capture: Storybook 10, a Vite framework, React, Playwright in the project) and stop deploy-storybook.yml taking the screenshots a second time. Run it at the repository root. Stops and writes nothing when the project does not qualify. The check loads the project\'s Storybook and Vite config, as Storybook itself does; run it only in a repository you trust',
1067
+ choices: ['web'],
1068
+ })
1069
+ .option('config-dir', {
1070
+ describe: 'With --capture web: the Storybook config directory, relative to the repository root (default: .storybook)',
1071
+ type: 'string',
1072
+ alias: 'configDir',
1073
+ })
1030
1074
  .option('commit-api-key', {
1031
1075
  describe: 'Write the API key into the committed config file (not recommended)',
1032
1076
  type: 'boolean',
@@ -1050,6 +1094,8 @@ async function main() {
1050
1094
  apiUrl: argv.apiUrl,
1051
1095
  skipGhSetup: argv.skipGhSetup,
1052
1096
  commitApiKey: argv.commitApiKey,
1097
+ capture: argv.capture,
1098
+ configDir: argv.configDir,
1053
1099
  verbose: argv.verbose
1054
1100
  };
1055
1101
 
@@ -1062,6 +1108,15 @@ async function main() {
1062
1108
  type: 'boolean',
1063
1109
  default: false,
1064
1110
  })
1111
+ .option('capture', {
1112
+ describe: 'web: also write .github/workflows/scry-capture-web.yml (build-free capture: Storybook 10, a Vite framework, React, Playwright in the project) and stop deploy-storybook.yml taking the screenshots a second time. Run it at the repository root. Stops and writes nothing when the project does not qualify. The check loads the project\'s Storybook and Vite config, as Storybook itself does; run it only in a repository you trust',
1113
+ choices: ['web'],
1114
+ })
1115
+ .option('config-dir', {
1116
+ describe: 'With --capture web: the Storybook config directory, relative to the repository root (default: .storybook)',
1117
+ type: 'string',
1118
+ alias: 'configDir',
1119
+ })
1065
1120
  .option('commit-message', {
1066
1121
  describe: 'Commit message used with --commit',
1067
1122
  type: 'string',
package/lib/bundle.js CHANGED
@@ -19,6 +19,8 @@ const {
19
19
  listFiles,
20
20
  } = require('./scf.js');
21
21
 
22
+ const { checkCaptureRecord, sha256 } = require('./captureRecord.js');
23
+
22
24
  const SOURCE_TEXT_MAX_BYTES = 1024 * 1024;
23
25
  const UNZIP_HELPER = path.join(__dirname, 'scf-unzip.mjs');
24
26
 
@@ -185,6 +187,38 @@ function copySourceFile(file, root, stageDir, skipped) {
185
187
  return bundlePath;
186
188
  }
187
189
 
190
+ /**
191
+ * Validate the staged bundle, unless `capture web` already validated this exact folder: the input
192
+ * is a directory, it matches the record capture left (same files, sizes, times, deployer and
193
+ * validator), and staging left scf.json byte for byte as it was. Anything else, or `--validate`,
194
+ * runs the full validation. Logs which path was taken.
195
+ */
196
+ function skipReason(input, stageDir, opts) {
197
+ if (opts.validate) return { why: 'forced by --validate' };
198
+ if (opts.includeSource) return { why: '--include-source adds files' };
199
+ if (!fs.statSync(input).isDirectory()) return { why: 'input is not a folder' };
200
+ const check = checkCaptureRecord(input);
201
+ if (!check.match) return { why: check.reason };
202
+ let staged = null;
203
+ try {
204
+ staged = sha256(fs.readFileSync(path.join(stageDir, 'scf.json')));
205
+ } catch {
206
+ staged = null;
207
+ }
208
+ return staged === check.manifestSha256 ? { skip: true } : { why: 'staging changed scf.json' };
209
+ }
210
+
211
+ function validateOrSkip(input, stageDir, opts) {
212
+ const { logger } = opts;
213
+ const verdict = skipReason(input, stageDir, opts);
214
+ if (verdict.skip) {
215
+ logger.info('Validation skipped: capture web validated this exact folder and nothing changed (pass --validate to run it again).');
216
+ return { ok: true, errors: [], warnings: [], manifest: null, skipped: true };
217
+ }
218
+ logger.info(`Running the full validation (${verdict.why}).`);
219
+ return validateBundle(stageDir);
220
+ }
221
+
188
222
  /**
189
223
  * Stage, opt-in, validate and zip a bundle. Throws BundleRejectedError (after printing every
190
224
  * problem) when the validator rejects it.
@@ -266,7 +300,7 @@ async function prepareBundle(input, opts) {
266
300
 
267
301
  const { legacy, sourceText, manifest } = stageManifestAndSourceText(stageDir, opts);
268
302
 
269
- const validation = validateBundle(stageDir);
303
+ const validation = validateOrSkip(input, stageDir, opts);
270
304
  if (!validation.ok) {
271
305
  logger.error(`\n❌ The bundle was rejected by the Scry Capture Format validator. Nothing was uploaded.`);
272
306
  printValidation(validation, logger);
@@ -0,0 +1,159 @@
1
+ /**
2
+ * `--changed-since <ref>`: which story files a change can reach.
3
+ *
4
+ * A story file is affected when a changed file is in its static import graph. Some changes reach
5
+ * every story and are not visible in any one story's graph: the Storybook config directory,
6
+ * anything the preview file imports (global styles, providers), and the root config and lock
7
+ * files. Those select everything. When in doubt, more is selected, never less.
8
+ */
9
+ const path = require('path');
10
+ const { execFileSync } = require('child_process');
11
+
12
+ const GLOBAL_FILES = [
13
+ /^package\.json$/, /^package-lock\.json$/, /^npm-shrinkwrap\.json$/, /^pnpm-lock\.yaml$/, /^pnpm-workspace\.yaml$/,
14
+ /^yarn\.lock$/, /^bun\.lockb?$/, /^[tj]sconfig(\.[\w-]+)?\.json$/,
15
+ /^(vite|vitest|next|tailwind|postcss|babel|svelte|astro|nuxt)\.config\.[cm]?[jt]s$/,
16
+ /^\.babelrc(\.\w+)?$/, /^\.browserslistrc$/, /^\.env(\.[\w.-]+)?$/,
17
+ ];
18
+
19
+ const toPosix = (p) => String(p).split(path.sep).join('/');
20
+
21
+ /** A repo-relative path as a project-relative POSIX path (`../` for files outside the project). */
22
+ function toProjectRelative(file, repoRoot, projectDir) {
23
+ return toPosix(path.relative(projectDir, path.resolve(repoRoot, file)));
24
+ }
25
+
26
+ /**
27
+ * @param {string} file project-relative POSIX path
28
+ * @returns {string|null} why the change reaches every story, or null
29
+ */
30
+ function isGlobalChange(file, { configDirRel, previewInputs }) {
31
+ // eslint-disable-next-line sonarjs/super-linear-regex -- a short path from the command line
32
+ const dir = toPosix(configDirRel || '.storybook').replace(/\/+$/, '');
33
+ if (file === dir || file.startsWith(`${dir}/`)) return `Storybook config changed (${file})`;
34
+ if ((previewInputs || []).includes(file)) return `a file the Storybook preview imports changed (${file})`;
35
+ // Root files of the project, or of a directory above it (a monorepo's lock file).
36
+ const atRoot = file.replace(/^(\.\.\/)+/, '');
37
+ if (!atRoot.includes('/') && GLOBAL_FILES.some((re) => re.test(atRoot))) return `${file} changed`;
38
+ return null;
39
+ }
40
+
41
+ /**
42
+ * @param {{graph: Record<string, string[]>, previewInputs?: string[], changedFiles: string[], configDirRel: string}} input
43
+ * graph: story file -> every file in its import graph (project-relative POSIX paths)
44
+ * @returns {{global: boolean, reason: string|null, files: string[]}}
45
+ */
46
+ function selectAffected({ graph, previewInputs = [], changedFiles: changed, configDirRel }) {
47
+ const all = Object.keys(graph).sort();
48
+ for (const file of changed) {
49
+ const reason = isGlobalChange(file, { configDirRel, previewInputs });
50
+ if (reason) return { global: true, reason, files: all };
51
+ }
52
+ const set = new Set(changed);
53
+ const files = all.filter((story) => set.has(story) || graph[story].some((input) => set.has(input)));
54
+ return { global: false, reason: null, files };
55
+ }
56
+
57
+ const splitZ = (out) => String(out || '').split('\0').filter(Boolean);
58
+
59
+ /**
60
+ * Files that differ from `ref` (committed, staged, unstaged and untracked). `A..B` compares two
61
+ * commits instead and ignores the working tree.
62
+ * @returns {{repoRoot: string, files: string[]}} repo-relative POSIX paths
63
+ */
64
+ function changedFiles(ref, { cwd, exec } = {}) {
65
+ if (!ref || String(ref).startsWith('-')) throw new Error(`--changed-since ${ref}: expected a git ref such as origin/main or HEAD~1.`);
66
+ // eslint-disable-next-line sonarjs/no-os-command-from-path -- git is found on PATH, as everywhere else in this CLI
67
+ const git = exec || ((args, opts) => execFileSync('git', args, { cwd: opts.cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] }));
68
+ let repoRoot;
69
+ try {
70
+ repoRoot = String(git(['rev-parse', '--show-toplevel'], { cwd })).trim();
71
+ } catch (error) {
72
+ throw new Error(`--changed-since needs a git repository (${cwd}): ${firstLine(error)}`);
73
+ }
74
+ const files = new Set();
75
+ try {
76
+ for (const f of splitZ(git(['diff', '--no-ext-diff', '--name-only', '-z', ref, '--'], { cwd: repoRoot }))) files.add(toPosix(f));
77
+ } catch (error) {
78
+ throw new Error(`--changed-since ${ref}: git could not compare against that ref (${firstLine(error)}). In CI, fetch it first (a shallow clone does not have it).`);
79
+ }
80
+ if (!ref.includes('..')) {
81
+ for (const f of splitZ(git(['ls-files', '--others', '--exclude-standard', '-z'], { cwd: repoRoot }))) files.add(toPosix(f));
82
+ }
83
+ return { repoRoot, files: [...files].sort() };
84
+ }
85
+
86
+ function firstLine(error) {
87
+ const text = String((error && (error.stderr || error.message)) || error);
88
+ return text.trim().split('\n').pop().trim();
89
+ }
90
+
91
+ const CODE_FILE = /\.([cm]?[jt]sx?|json)$/;
92
+
93
+ function applyAlias(spec, alias) {
94
+ for (const entry of alias || []) {
95
+ const { find, replacement } = entry;
96
+ if (typeof replacement !== 'string') continue;
97
+ if (find instanceof RegExp) {
98
+ if (find.test(spec)) return spec.replace(find, replacement);
99
+ } else if (typeof find === 'string' && (spec === find || spec.startsWith(`${find}/`))) {
100
+ return replacement + spec.slice(find.length);
101
+ }
102
+ }
103
+ return spec;
104
+ }
105
+
106
+ /**
107
+ * The static import graph of every story file (and of the preview file), from esbuild's metafile.
108
+ * Packages are left out: a dependency change shows up as a lock file change. An import that cannot
109
+ * be resolved is skipped; a file that is not code is recorded but not read.
110
+ *
111
+ * @returns {Promise<{graph: Record<string, string[]>, previewInputs: string[]}>}
112
+ */
113
+ async function buildGraph({ projectDir, entries, previewFile, alias, esbuild }) {
114
+ const entryPoints = [...entries, ...(previewFile ? [previewFile] : [])];
115
+ const plugin = {
116
+ name: 'scry-capture-graph',
117
+ setup(build) {
118
+ build.onResolve({ filter: /.*/ }, async (args) => {
119
+ if (args.kind === 'entry-point' || (args.pluginData && args.pluginData.scry)) return null;
120
+ // eslint-disable-next-line sonarjs/super-linear-regex -- runs on the project's own source files, not on untrusted input
121
+ const spec = applyAlias(args.path.replace(/[?#].*$/, ''), alias);
122
+ if (!spec || /^(data|https?|virtual|node):/.test(spec) || spec.startsWith('\0')) return { path: args.path, external: true };
123
+ const resolved = await build.resolve(spec, { resolveDir: args.resolveDir, kind: args.kind, importer: args.importer, pluginData: { scry: true } });
124
+ if (resolved.errors.length) return { path: args.path, external: true };
125
+ if (!resolved.external && /[\\/]node_modules[\\/]/.test(resolved.path)) return { path: args.path, external: true };
126
+ return resolved;
127
+ });
128
+ build.onLoad({ filter: /.*/ }, (args) => (CODE_FILE.test(args.path) ? null : { contents: '', loader: 'js' }));
129
+ },
130
+ };
131
+ const result = await esbuild.build({
132
+ entryPoints,
133
+ absWorkingDir: projectDir,
134
+ bundle: true,
135
+ write: false,
136
+ metafile: true,
137
+ splitting: false,
138
+ format: 'esm',
139
+ platform: 'browser',
140
+ outdir: path.join(projectDir, '.scry-capture-graph-never-written'),
141
+ logLevel: 'silent',
142
+ packages: 'external',
143
+ jsx: 'automatic',
144
+ plugins: [plugin],
145
+ });
146
+ const previewRel = previewFile ? toPosix(path.relative(projectDir, previewFile)) : null;
147
+ const graph = {};
148
+ let previewInputs = [];
149
+ for (const output of Object.values(result.metafile.outputs)) {
150
+ if (!output.entryPoint) continue;
151
+ const entry = toPosix(output.entryPoint);
152
+ const inputs = Object.keys(output.inputs).map(toPosix).sort();
153
+ if (entry === previewRel) previewInputs = inputs;
154
+ else graph[entry] = inputs;
155
+ }
156
+ return { graph, previewInputs };
157
+ }
158
+
159
+ module.exports = { isGlobalChange, selectAffected, changedFiles, toProjectRelative, buildGraph, applyAlias, GLOBAL_FILES };
@@ -0,0 +1,52 @@
1
+ /**
2
+ * How many CPU cores this process may really use, and the worker count that follows.
3
+ *
4
+ * `os.availableParallelism()` honours the affinity mask (taskset, cpuset), but not a CFS quota:
5
+ * a container limited to 2 CPUs on a 64-core host still reports 64. So the cgroup quota is read
6
+ * too and the smaller number wins.
7
+ */
8
+ const fs = require('fs');
9
+ const os = require('os');
10
+
11
+ /** Change here when measured numbers say otherwise. */
12
+ const MAX_DEFAULT_WORKERS = 4;
13
+
14
+ function readQuota(readFile) {
15
+ try {
16
+ const [quota, period] = String(readFile('/sys/fs/cgroup/cpu.max')).trim().split(/\s+/);
17
+ if (quota && quota !== 'max' && Number(quota) > 0 && Number(period) > 0) {
18
+ return { cpus: Number(quota) / Number(period), source: 'cgroup-v2' };
19
+ }
20
+ return null;
21
+ } catch {
22
+ // not cgroup v2
23
+ }
24
+ try {
25
+ const quota = Number(String(readFile('/sys/fs/cgroup/cpu/cpu.cfs_quota_us')).trim());
26
+ const period = Number(String(readFile('/sys/fs/cgroup/cpu/cpu.cfs_period_us')).trim());
27
+ if (quota > 0 && period > 0) return { cpus: quota / period, source: 'cgroup-v1' };
28
+ } catch {
29
+ // no cgroup limit readable
30
+ }
31
+ return null;
32
+ }
33
+
34
+ /**
35
+ * @returns {{cores:number, source:'os'|'cgroup-v1'|'cgroup-v2', os:number, cgroup:number|null}}
36
+ */
37
+ function coresSeen(deps = {}) {
38
+ const availableParallelism = deps.availableParallelism
39
+ || (typeof os.availableParallelism === 'function' ? () => os.availableParallelism() : () => os.cpus().length);
40
+ const readFile = deps.readFile || ((file) => fs.readFileSync(file, 'utf8'));
41
+ const fromOs = Math.max(1, Math.floor(Number(availableParallelism()) || 1));
42
+ const quota = readQuota(readFile);
43
+ const cgroup = quota ? Math.max(1, Math.floor(quota.cpus)) : null;
44
+ if (cgroup !== null && cgroup < fromOs) return { cores: cgroup, source: quota.source, os: fromOs, cgroup };
45
+ return { cores: fromOs, source: cgroup !== null && cgroup === fromOs ? quota.source : 'os', os: fromOs, cgroup };
46
+ }
47
+
48
+ function defaultWorkers(cores) {
49
+ return Math.max(1, Math.min(MAX_DEFAULT_WORKERS, Math.floor(Number(cores) || 1)));
50
+ }
51
+
52
+ module.exports = { coresSeen, defaultWorkers, MAX_DEFAULT_WORKERS };