@scrymore/scry-deployer 0.14.0 → 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/bin/cli.js CHANGED
@@ -877,11 +877,12 @@ 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 })
880
881
  .option('allow-partial-bundle', { type: 'boolean', default: false, hidden: true })
881
882
  .option('verbose', { describe: 'Enable verbose logging', type: 'boolean' });
882
883
  }, async (argv) => {
883
884
  const config = loadConfig(argv);
884
- const outcome = await runUploadBundle({ ...config, path: argv.path, includeSource: argv.includeSource, repoRoot: argv.repoRoot, source: argv.source, dryRun: argv.dryRun, allowPartialBundle: argv.allowPartialBundle });
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 });
885
886
  process.exitCode = outcome.exitCode;
886
887
  })
887
888
  .command('capture <adapter>', 'Capture stories into a Scry Capture Format bundle (adapters: rn, web)', (yargs) => {
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);
@@ -18,6 +18,7 @@ const { changedFiles, selectAffected, buildGraph, toProjectRelative } = require(
18
18
  const { captureEntry, buildManifest, writeManifest, resetOutDir, sealOutDir, assertOutDirUsable, fileStem, skippedEntry } = require('./scf-writer.js');
19
19
  const { onSignals } = require('./signals.js');
20
20
  const { validateBundle, printValidation } = require('../../scf.js');
21
+ const { writeCaptureRecord } = require('../../captureRecord.js');
21
22
 
22
23
  const toPosix = (p) => p.split(path.sep).join('/');
23
24
 
@@ -171,6 +172,9 @@ function finishRun({ run, selected, options, deps, sb, baseReport, timingsMs, st
171
172
  logger.error(`The bundle at ${options.outDir} did not pass SCF validation:`);
172
173
  printValidation(validation, logger);
173
174
  exitCode = 1;
175
+ } else {
176
+ // Lets `upload <dir>` skip its own second validation while the folder is untouched.
177
+ writeCaptureRecord(options.outDir);
174
178
  }
175
179
  }
176
180
  timingsMs.write = Date.now() - writeStarted;
@@ -9,6 +9,7 @@
9
9
  const fs = require('fs');
10
10
  const path = require('path');
11
11
  const { SCF_SCHEMA_URL } = require('../../scf.js');
12
+ const { recordPathFor } = require('../../captureRecord.js');
12
13
  const { CaptureWebError } = require('./storybook-config.js');
13
14
 
14
15
  const TOOL_NAME = 'scry-deployer capture web';
@@ -273,6 +274,8 @@ function resetOutDir(outDir) {
273
274
  removeFiles(path.join(outDir, 'images'), '.png');
274
275
  removeFiles(path.join(outDir, 'structure'), '.json');
275
276
  fs.rmSync(path.join(outDir, 'scf.json'), { force: true });
277
+ // An old record must not outlive a re-capture that then fails validation.
278
+ fs.rmSync(recordPathFor(outDir), { force: true });
276
279
  fs.mkdirSync(path.join(outDir, 'images'), { recursive: true });
277
280
  fs.mkdirSync(path.join(outDir, 'structure'), { recursive: true });
278
281
  }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * The record `capture web` leaves next to its bundle once the validator has passed it, and the
3
+ * check `upload DIR` makes before it decides to skip a second validation.
4
+ *
5
+ * The record lives OUTSIDE the bundle (a sibling file, `<dir>.scry-validated.json`), so the bundle
6
+ * format, the zip and the service's own validation never see it. It holds a fingerprint of the
7
+ * folder: every file's relative path, size and modification time (sorted), the SHA-256 of
8
+ * scf.json, plus the deployer version and the vendored validator version. `upload` recomputes the
9
+ * fingerprint and skips validation only on an exact match. No record, any difference (a file
10
+ * added, removed, resized, touched, a different deployer or validator) means the full validation
11
+ * runs as before. The fingerprint is a stat walk plus one small file read, a fraction of a second.
12
+ */
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+ const crypto = require('crypto');
16
+ const { listFiles, vendoredScfVersion } = require('./scf.js');
17
+
18
+ const RECORD_VERSION = 1;
19
+
20
+ function deployerVersion() {
21
+ try {
22
+ return require('../package.json').version;
23
+ } catch {
24
+ return 'unknown';
25
+ }
26
+ }
27
+
28
+ /** `<dir>.scry-validated.json`, next to (never inside) the bundle folder. */
29
+ function recordPathFor(dir) {
30
+ return `${path.resolve(dir)}.scry-validated.json`;
31
+ }
32
+
33
+ function sha256(buf) {
34
+ return crypto.createHash('sha256').update(buf).digest('hex');
35
+ }
36
+
37
+ /**
38
+ * Fingerprint a bundle folder.
39
+ * @returns {{digest:string, files:number, manifestSha256:string|null}}
40
+ */
41
+ function fingerprintDir(dir) {
42
+ const files = listFiles(dir);
43
+ const hash = crypto.createHash('sha256');
44
+ for (const rel of files) {
45
+ const st = fs.statSync(path.join(dir, ...rel.split('/')));
46
+ hash.update(`${rel}\0${st.size}\0${Math.floor(st.mtimeMs)}\n`);
47
+ }
48
+ let manifestSha256 = null;
49
+ try {
50
+ manifestSha256 = sha256(fs.readFileSync(path.join(dir, 'scf.json')));
51
+ } catch {
52
+ manifestSha256 = null;
53
+ }
54
+ return { digest: hash.digest('hex'), files: files.length, manifestSha256 };
55
+ }
56
+
57
+ function expectedStamp() {
58
+ return { version: RECORD_VERSION, deployer: deployerVersion(), validator: vendoredScfVersion() };
59
+ }
60
+
61
+ /** Write the record after the validator passed `dir`. Never throws: a failed write only costs a later validation. */
62
+ function writeCaptureRecord(dir) {
63
+ try {
64
+ const record = { ...expectedStamp(), ...fingerprintDir(dir) };
65
+ fs.writeFileSync(recordPathFor(dir), `${JSON.stringify(record, null, 2)}\n`);
66
+ return true;
67
+ } catch {
68
+ return false;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Does `dir` match the record capture left for it?
74
+ * @returns {{match:boolean, reason:string, manifestSha256?:string}}
75
+ */
76
+ function checkCaptureRecord(dir) {
77
+ let record;
78
+ try {
79
+ record = JSON.parse(fs.readFileSync(recordPathFor(dir), 'utf8'));
80
+ } catch {
81
+ return { match: false, reason: 'no capture record' };
82
+ }
83
+ const stamp = expectedStamp();
84
+ if (!record || record.version !== stamp.version || record.deployer !== stamp.deployer || record.validator !== stamp.validator) {
85
+ return { match: false, reason: 'record is from another deployer or validator version' };
86
+ }
87
+ let now;
88
+ try {
89
+ now = fingerprintDir(dir);
90
+ } catch {
91
+ return { match: false, reason: 'folder could not be read' };
92
+ }
93
+ if (!record.manifestSha256 || record.digest !== now.digest || record.files !== now.files || record.manifestSha256 !== now.manifestSha256) {
94
+ return { match: false, reason: 'folder changed since capture validated it' };
95
+ }
96
+ return { match: true, reason: 'matches the capture record', manifestSha256: now.manifestSha256 };
97
+ }
98
+
99
+ module.exports = { recordPathFor, fingerprintDir, writeCaptureRecord, checkCaptureRecord, sha256 };
package/lib/scf.js CHANGED
@@ -141,7 +141,9 @@ function zipBundleDir(dir, outPath) {
141
141
  output.on('close', () => resolve({ bytes: fs.statSync(outPath).size, members }));
142
142
  archive.pipe(output);
143
143
  for (const rel of members) {
144
- archive.file(path.join(dir, ...rel.split('/')), { name: rel });
144
+ // PNG data is already compressed: deflate level 9 costs seconds and saves almost nothing, so
145
+ // store those members (zip method 0, which the upload service reads). Text and JSON are deflated.
146
+ archive.file(path.join(dir, ...rel.split('/')), { name: rel, store: /\.png$/i.test(rel) });
145
147
  }
146
148
  archive.finalize().catch(reject);
147
149
  });
@@ -30,6 +30,7 @@ async function prepareOrFail(input, argv, logger) {
30
30
  try {
31
31
  return await prepareBundle(input, {
32
32
  includeSource: Boolean(argv.includeSource),
33
+ validate: Boolean(argv.validate),
33
34
  repoRoot: argv.repoRoot,
34
35
  logger,
35
36
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scrymore/scry-deployer",
3
- "version": "0.14.0",
3
+ "version": "0.14.1",
4
4
  "description": "A CLI to automate the deployment of Storybook static builds.",
5
5
  "main": "index.js",
6
6
  "bin": {