storyshelf 0.3.2 → 0.5.3

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/dist/config.js CHANGED
@@ -2,22 +2,169 @@
2
2
  import "node:path";
3
3
  import "node:url";
4
4
  import.meta.url;
5
+ import { fileURLToPath } from "node:url";
6
+ import { dirname, join, relative, resolve, sep } from "node:path";
5
7
  import { execSync } from "node:child_process";
8
+ import { existsSync } from "node:fs";
6
9
  import { access, mkdir, readFile, writeFile } from "node:fs/promises";
7
- import { dirname, join, relative, resolve } from "node:path";
8
- import { z } from "zod";
9
10
  //#region src/config.ts
10
- const storybookConfigSchema = z.object({
11
- slug: z.string().min(1, "slug is required"),
12
- url: z.string().url().optional(),
13
- buildDir: z.string().min(1).optional(),
14
- buildCommand: z.string().min(1).optional(),
15
- buildScriptName: z.string().min(1).optional(),
16
- skip: z.string().min(1).optional()
17
- }).refine((data) => !(data.buildCommand && data.buildScriptName), {
18
- message: "buildCommand and buildScriptName are mutually exclusive",
19
- path: ["buildCommand"]
20
- });
11
+ /** Parse an unknown value into a `StorybookConfig`, or return the reason it is invalid. */
12
+ function parseStorybookConfig(value) {
13
+ if (typeof value !== "object" || value === null) return {
14
+ ok: false,
15
+ error: "expected an object"
16
+ };
17
+ const record = value;
18
+ const slug = readSlug(record);
19
+ if (!slug.ok) return slug;
20
+ const parts = readConfigParts(record);
21
+ if (!parts.ok) return parts;
22
+ return checkCrossFieldRules(slug.slug, parts);
23
+ }
24
+ /** Read the optional string, boolean, and string-list config sections. */
25
+ function readConfigParts(record) {
26
+ const optional = readOptionalStrings(record, OPTIONAL_CONFIG_KEYS);
27
+ if (!optional.ok) return optional;
28
+ const flags = readOptionalBooleans(record, BOOLEAN_CONFIG_KEYS);
29
+ if (!flags.ok) return flags;
30
+ const lists = readOptionalStringArrays(record, STRING_ARRAY_CONFIG_KEYS);
31
+ if (!lists.ok) return lists;
32
+ return {
33
+ ok: true,
34
+ values: optional.values,
35
+ flags: flags.values,
36
+ lists: lists.values
37
+ };
38
+ }
39
+ /** Read the required slug field. */
40
+ function readSlug(record) {
41
+ const slug = record["slug"];
42
+ if (typeof slug !== "string" || slug.length === 0) return {
43
+ ok: false,
44
+ error: "slug is required"
45
+ };
46
+ return {
47
+ ok: true,
48
+ slug
49
+ };
50
+ }
51
+ /** Optional config keys with plain string values. */
52
+ const OPTIONAL_CONFIG_KEYS = [
53
+ "url",
54
+ "buildDir",
55
+ "buildCommand",
56
+ "buildScriptName",
57
+ "skip"
58
+ ];
59
+ /** Optional config keys with boolean values. */
60
+ const BOOLEAN_CONFIG_KEYS = ["affectedOnly"];
61
+ /** Optional config keys with string-array values. */
62
+ const STRING_ARRAY_CONFIG_KEYS = ["untraced"];
63
+ /** Read optional non-empty string fields; any present-but-invalid field is an error. */
64
+ function readOptionalStrings(record, keys) {
65
+ const values = {};
66
+ for (const key of keys) {
67
+ const raw = record[key];
68
+ if (raw === void 0) continue;
69
+ if (typeof raw !== "string" || raw.length === 0) return {
70
+ ok: false,
71
+ error: `${key} must be a non-empty string`
72
+ };
73
+ values[key] = raw;
74
+ }
75
+ return {
76
+ ok: true,
77
+ values
78
+ };
79
+ }
80
+ /** Read optional boolean fields; any present-but-invalid field is an error. */
81
+ function readOptionalBooleans(record, keys) {
82
+ const values = {};
83
+ for (const key of keys) {
84
+ const raw = record[key];
85
+ if (raw === void 0) continue;
86
+ if (typeof raw !== "boolean") return {
87
+ ok: false,
88
+ error: `${key} must be a boolean`
89
+ };
90
+ values[key] = raw;
91
+ }
92
+ return {
93
+ ok: true,
94
+ values
95
+ };
96
+ }
97
+ /** Read optional string-array fields; any present-but-invalid field is an error. */
98
+ function readOptionalStringArrays(record, keys) {
99
+ const values = {};
100
+ for (const key of keys) {
101
+ const raw = record[key];
102
+ if (raw === void 0) continue;
103
+ const collected = collectStringArray(key, raw);
104
+ if (!collected.ok) return collected;
105
+ values[key] = collected.values;
106
+ }
107
+ return {
108
+ ok: true,
109
+ values
110
+ };
111
+ }
112
+ /** Collect validated string entries, or the reason the list is invalid. */
113
+ function collectStringArray(key, raw) {
114
+ if (!Array.isArray(raw)) return {
115
+ ok: false,
116
+ error: `${key} must be an array of non-empty strings`
117
+ };
118
+ const values = [];
119
+ for (const entry of raw) {
120
+ if (typeof entry !== "string" || entry.length === 0) return {
121
+ ok: false,
122
+ error: `${key} must be an array of non-empty strings`
123
+ };
124
+ values.push(entry);
125
+ }
126
+ return {
127
+ ok: true,
128
+ values
129
+ };
130
+ }
131
+ /** Enforce url shape and the buildCommand/buildScriptName exclusion. */
132
+ function checkCrossFieldRules(slug, parts) {
133
+ const url = parts.values["url"];
134
+ if (url !== void 0 && !isHttpUrl(url)) return {
135
+ ok: false,
136
+ error: "url must be a valid http(s) URL"
137
+ };
138
+ if (parts.values["buildCommand"] && parts.values["buildScriptName"]) return {
139
+ ok: false,
140
+ error: "buildCommand and buildScriptName are mutually exclusive"
141
+ };
142
+ const { buildDir, buildCommand, buildScriptName, skip } = parts.values;
143
+ const affectedOnly = parts.flags["affectedOnly"];
144
+ const untraced = parts.lists["untraced"];
145
+ return {
146
+ ok: true,
147
+ config: {
148
+ slug,
149
+ ...url === void 0 ? {} : { url },
150
+ ...buildDir === void 0 ? {} : { buildDir },
151
+ ...buildCommand === void 0 ? {} : { buildCommand },
152
+ ...buildScriptName === void 0 ? {} : { buildScriptName },
153
+ ...skip === void 0 ? {} : { skip },
154
+ ...affectedOnly === void 0 ? {} : { affectedOnly },
155
+ ...untraced === void 0 ? {} : { untraced }
156
+ }
157
+ };
158
+ }
159
+ /** True for http(s) URLs. */
160
+ function isHttpUrl(value) {
161
+ try {
162
+ const protocol = new URL(value).protocol;
163
+ return protocol === "http:" || protocol === "https:";
164
+ } catch {
165
+ return false;
166
+ }
167
+ }
21
168
  const CONFIG_RELATIVE = join(".storybook", "storyshelf.json");
22
169
  const MAIN_CANDIDATES = [
23
170
  ".storybook/main.js",
@@ -29,6 +176,13 @@ const MAIN_CANDIDATES = [
29
176
  ".storybook/main.jsx",
30
177
  ".storybook/main.tsx"
31
178
  ];
179
+ /**
180
+ * Locate the Storybook config file (`.storybook/main.*`) in the project.
181
+ * Probes `.js`, `.ts`, `.mjs`, `.cjs`, `.mts`, `.cts`, `.jsx`, `.tsx` in order.
182
+ *
183
+ * @param cwd - Project root to search from; defaults to `process.cwd()`
184
+ * @returns Absolute path to the first candidate that exists, or `null` if none found
185
+ */
32
186
  async function findStorybookMain(cwd = process.cwd()) {
33
187
  for (const candidate of MAIN_CANDIDATES) {
34
188
  const full = resolve(cwd, candidate);
@@ -39,17 +193,29 @@ async function findStorybookMain(cwd = process.cwd()) {
39
193
  }
40
194
  return null;
41
195
  }
196
+ /**
197
+ * Ensure a Storybook config exists, throwing a human-readable error otherwise.
198
+ *
199
+ * @param cwd - Project root to search from
200
+ * @throws If `.storybook/main.*` cannot be found
201
+ */
42
202
  async function assertStorybookMain(cwd = process.cwd()) {
43
203
  if (!await findStorybookMain(cwd)) throw new Error(".storybook/main.* not found — ensure Storybook is set up in this project");
44
204
  }
205
+ /**
206
+ * Load and validate `.storybook/storyshelf.json` if it exists.
207
+ *
208
+ * @param cwd - Project root
209
+ * @param customPath - Optional explicit config path (overrides the conventional location)
210
+ * @returns Validated config or `null` when the file is missing or invalid
211
+ */
45
212
  async function loadStorybookConfig(cwd = process.cwd(), customPath) {
46
213
  const full = customPath ? resolve(cwd, customPath) : resolve(cwd, CONFIG_RELATIVE);
47
214
  try {
48
215
  const raw = await readFile(full, "utf8");
49
- const parsed = JSON.parse(raw);
50
- const result = storybookConfigSchema.safeParse(parsed);
51
- if (!result.success) return null;
52
- return result.data;
216
+ const result = parseStorybookConfig(JSON.parse(raw));
217
+ if (!result.ok) return null;
218
+ return result.config;
53
219
  } catch {
54
220
  return null;
55
221
  }
@@ -61,16 +227,96 @@ function mergeConfigs(existing, config) {
61
227
  ...config
62
228
  } : { ...config };
63
229
  }
64
- async function writeStorybookConfig(config, cwd = process.cwd(), customPath) {
230
+ /** Base URL for version-pinned config schemas published with the CLI. */
231
+ const SCHEMA_BASE_URL = "https://unpkg.com/storyshelf";
232
+ /** Schema path within the published CLI package. */
233
+ const SCHEMA_PACKAGE_PATH = "schema/storyshelf-config.json";
234
+ /** Running CLI version, or undefined in dev/test without the build define. */
235
+ function cliVersion() {
236
+ return "0.5.3";
237
+ }
238
+ /**
239
+ * Resolve the `$schema` value for a config file: a path relative to the
240
+ * config directory when the schema ships alongside this CLI on disk, else a
241
+ * versioned unpkg URL. Never throws — falls back to the unversioned URL.
242
+ *
243
+ * @param configDir - Directory that will contain the config file.
244
+ * @param options - Module URL and version overrides (test seams).
245
+ */
246
+ function schemaReference(configDir, options = {}) {
247
+ const local = resolveLocalSchema(configDir, options.moduleUrl ?? import.meta.url);
248
+ if (local !== null) return local;
249
+ const version = options.version ?? cliVersion();
250
+ return version === void 0 ? `${SCHEMA_BASE_URL}/${SCHEMA_PACKAGE_PATH}` : `${SCHEMA_BASE_URL}@${version}/${SCHEMA_PACKAGE_PATH}`;
251
+ }
252
+ /** Repo-relative path to the bundled schema, or null when not on disk. */
253
+ function resolveLocalSchema(configDir, moduleUrl) {
254
+ let schemaPath;
255
+ try {
256
+ schemaPath = fileURLToPath(new URL(`../${SCHEMA_PACKAGE_PATH}`, moduleUrl));
257
+ } catch {
258
+ return null;
259
+ }
260
+ if (!existsSync(schemaPath)) return null;
261
+ const rel = relative(configDir, schemaPath).split(sep).join("/");
262
+ return rel.startsWith(".") ? rel : `./${rel}`;
263
+ }
264
+ /**
265
+ * Persist a `StorybookConfig` to `.storybook/storyshelf.json`, merging with any
266
+ * existing file so unrelated keys are preserved.
267
+ *
268
+ * @param config - Partial config to write (merged with existing)
269
+ * @param cwd - Project root
270
+ * @param customPath - Optional explicit path
271
+ * @param options - Set `stampSchema` to write a fresh `$schema` reference;
272
+ * otherwise a pre-existing `$schema` is preserved as-is
273
+ * @returns Absolute path to the written file
274
+ * @throws If the merged result fails validation
275
+ */
276
+ async function writeStorybookConfig(config, cwd = process.cwd(), customPath, options = {}) {
65
277
  const full = customPath ? resolve(cwd, customPath) : resolve(cwd, CONFIG_RELATIVE);
66
278
  const dir = dirname(full);
67
279
  await mkdir(dir, { recursive: true });
68
- const merged = mergeConfigs(await loadStorybookConfig(cwd, customPath), config);
69
- const result = storybookConfigSchema.safeParse(merged);
70
- if (!result.success) throw new Error(`Invalid storybook config: ${result.error.message}`);
71
- await writeFile(full, `${JSON.stringify(result.data, null, 2)}\n`, "utf8");
280
+ const result = parseStorybookConfig(mergeConfigs(await loadStorybookConfig(cwd, customPath), config));
281
+ if (!result.ok) throw new Error(`Invalid storybook config: ${result.error}`);
282
+ await writeConfigFile(full, result.config, await resolveWriteSchema(full, dir, options));
72
283
  return full;
73
284
  }
285
+ /** Resolve the `$schema` to write: fresh stamp or the existing value. */
286
+ async function resolveWriteSchema(full, dir, options) {
287
+ if (options.stampSchema) return schemaReference(dir);
288
+ return await readExistingSchema(full);
289
+ }
290
+ /** Write a validated config with an optional leading `$schema`. */
291
+ function writeConfigFile(full, config, schema) {
292
+ return writeFile(full, `${JSON.stringify(withSchema(config, schema), null, 2)}\n`, "utf8");
293
+ }
294
+ /** `$schema` carried from the existing file, if any. */
295
+ async function readExistingSchema(configPath) {
296
+ try {
297
+ const raw = JSON.parse(await readFile(configPath, "utf8"));
298
+ if (typeof raw === "object" && raw !== null) {
299
+ const schema = raw["$schema"];
300
+ return typeof schema === "string" && schema.length > 0 ? schema : void 0;
301
+ }
302
+ return;
303
+ } catch {
304
+ return;
305
+ }
306
+ }
307
+ /** Prepend `$schema` to a validated config for writing. */
308
+ function withSchema(config, schema) {
309
+ return schema === void 0 ? { ...config } : {
310
+ $schema: schema,
311
+ ...config
312
+ };
313
+ }
314
+ /**
315
+ * Extract framework, addons, and globs from `.storybook/main.*` for `storyshelf init`.
316
+ *
317
+ * @param cwd - Project root
318
+ * @returns Metadata with framework name, addons, and story globs when discoverable
319
+ */
74
320
  async function detectStorybookMeta(cwd = process.cwd()) {
75
321
  const mainPath = await findStorybookMain(cwd);
76
322
  if (!mainPath) return { packagePath: "." };
@@ -109,6 +355,12 @@ function parseMetaLists(raw) {
109
355
  }
110
356
  return lists;
111
357
  }
358
+ /**
359
+ * Read the package name from `package.json` if present.
360
+ *
361
+ * @param cwd - Project root
362
+ * @returns Package name or `null` when unreadable or missing
363
+ */
112
364
  async function detectPackageName(cwd = process.cwd()) {
113
365
  try {
114
366
  const raw = await readFile(resolve(cwd, "package.json"), "utf8");
@@ -119,6 +371,13 @@ async function detectPackageName(cwd = process.cwd()) {
119
371
  return null;
120
372
  }
121
373
  }
374
+ /**
375
+ * Detect the git repository slug (`owner/repo`) from `remote.origin.url`.
376
+ * Handles `git@`, `https://`, and `ssh://` forms and strips `.git`.
377
+ *
378
+ * @param cwd - Project root (used as `git -C` cwd)
379
+ * @returns Normalized `owner/repo` or `null` when not a git repo
380
+ */
122
381
  function detectGitRepository(cwd = process.cwd()) {
123
382
  try {
124
383
  const url = execSync("git config --get remote.origin.url", {
@@ -131,6 +390,12 @@ function detectGitRepository(cwd = process.cwd()) {
131
390
  return null;
132
391
  }
133
392
  }
393
+ /**
394
+ * Detect the default branch, preferring `origin/HEAD` then `HEAD`.
395
+ *
396
+ * @param cwd - Project root
397
+ * @returns Branch name (e.g. `main`) or `null` when not determinable
398
+ */
134
399
  function detectGitDefaultBranch(cwd = process.cwd()) {
135
400
  try {
136
401
  const ref = execSync("git symbolic-ref refs/remotes/origin/HEAD", {
@@ -149,5 +414,113 @@ function detectGitDefaultBranch(cwd = process.cwd()) {
149
414
  } catch {}
150
415
  return null;
151
416
  }
417
+ /** Install/start commands per runner (host-side instructions and scaffolds). */
418
+ const RUNNER_COMMANDS = {
419
+ npm: {
420
+ install: "npm install",
421
+ start: "npm start"
422
+ },
423
+ pnpm: {
424
+ install: "pnpm install",
425
+ start: "pnpm start"
426
+ },
427
+ yarn: {
428
+ install: "yarn install",
429
+ start: "yarn start"
430
+ },
431
+ bun: {
432
+ install: "bun install",
433
+ start: "bun run start"
434
+ },
435
+ deno: {
436
+ install: "deno install",
437
+ start: "deno task start"
438
+ },
439
+ nub: {
440
+ install: "nub install",
441
+ start: "nub run start"
442
+ }
443
+ };
444
+ /** Install command for a runner (e.g. `pnpm install`). */
445
+ function installCommand(runner) {
446
+ return RUNNER_COMMANDS[runner].install;
447
+ }
448
+ /** Start command for a runner (e.g. `pnpm start`). */
449
+ function startCommand(runner) {
450
+ return RUNNER_COMMANDS[runner].start;
451
+ }
452
+ const KNOWN_RUNNERS = /* @__PURE__ */ new Set([
453
+ "npm",
454
+ "pnpm",
455
+ "yarn",
456
+ "bun",
457
+ "deno",
458
+ "nub"
459
+ ]);
460
+ /** Normalize a runner name from a `a/b` value (`npm_config_user_agent`, `packageManager` field). */
461
+ function asRunner(value) {
462
+ const name = value?.split(/[/@]/u)[0]?.trim().toLowerCase();
463
+ return name !== void 0 && KNOWN_RUNNERS.has(name) ? name : void 0;
464
+ }
465
+ /** Lockfiles evidencing a package runner, in check order. */
466
+ const RUNNER_LOCKFILES = [
467
+ {
468
+ file: "nub.lock",
469
+ runner: "nub"
470
+ },
471
+ {
472
+ file: "bun.lockb",
473
+ runner: "bun"
474
+ },
475
+ {
476
+ file: "bun.lock",
477
+ runner: "bun"
478
+ },
479
+ {
480
+ file: "pnpm-lock.yaml",
481
+ runner: "pnpm"
482
+ },
483
+ {
484
+ file: "yarn.lock",
485
+ runner: "yarn"
486
+ },
487
+ {
488
+ file: "package-lock.json",
489
+ runner: "npm"
490
+ },
491
+ {
492
+ file: "deno.lock",
493
+ runner: "deno"
494
+ }
495
+ ];
496
+ async function readPackageManagerField(cwd) {
497
+ try {
498
+ const raw = await readFile(resolve(cwd, "package.json"), "utf8");
499
+ return JSON.parse(raw).packageManager;
500
+ } catch {
501
+ return;
502
+ }
503
+ }
504
+ /**
505
+ * Detect the project's package runner: invoking agent env, then the
506
+ * `packageManager` field, then lockfiles, defaulting to npm.
507
+ */
508
+ async function detectPackageRunner(cwd = process.cwd()) {
509
+ const fromAgent = asRunner(process.env["npm_config_user_agent"]);
510
+ if (fromAgent) return fromAgent;
511
+ const field = await readPackageManagerField(cwd);
512
+ const declared = typeof field === "string" ? asRunner(field) : void 0;
513
+ if (declared) return declared;
514
+ return await runnerFromLockfiles(cwd) ?? "npm";
515
+ }
516
+ /** First runner evidenced by a lockfile, or undefined when none match. */
517
+ async function runnerFromLockfiles(cwd) {
518
+ for (const { file, runner } of RUNNER_LOCKFILES) try {
519
+ await access(resolve(cwd, file));
520
+ return runner;
521
+ } catch {
522
+ continue;
523
+ }
524
+ }
152
525
  //#endregion
153
- export { assertStorybookMain, detectGitDefaultBranch, detectGitRepository, detectPackageName, detectStorybookMeta, findStorybookMain, loadStorybookConfig, storybookConfigSchema, writeStorybookConfig };
526
+ export { assertStorybookMain, detectGitDefaultBranch, detectGitRepository, detectPackageName, detectPackageRunner, detectStorybookMeta, findStorybookMain, installCommand, loadStorybookConfig, schemaReference, startCommand, writeStorybookConfig };
package/dist/index.js CHANGED
@@ -2,16 +2,45 @@
2
2
  import "node:path";
3
3
  import "node:url";
4
4
  import.meta.url;
5
+ import { runBuild } from "./commands/build.js";
5
6
  import { runCreate } from "./commands/create.js";
6
7
  import { runUpload } from "./commands/upload.js";
7
8
  import { handleError, runDefaultCommand } from "./commands/default.js";
9
+ import { runDoctor } from "./commands/doctor.js";
8
10
  import { runInit } from "./commands/init.js";
9
11
  import { runPurge } from "./commands/purge.js";
10
12
  import { runRetry } from "./commands/retry.js";
11
13
  import { runServerInit } from "./commands/server/init.js";
14
+ import { runServerServe } from "./commands/server/serve.js";
15
+ import { runWhoami } from "./commands/whoami.js";
16
+ import { runWorkerInit } from "./commands/worker/init.js";
17
+ import { runWorkerServe } from "./commands/worker/serve.js";
12
18
  import { Command } from "commander";
13
19
  import { pathToFileURL } from "node:url";
14
20
  //#region src/index.ts
21
+ /**
22
+ * Build the StoryShelf CLI program with all subcommands registered.
23
+ *
24
+ * @returns The configured commander Command instance.
25
+ */
26
+ function createProgram() {
27
+ const program = new Command();
28
+ program.name("storyshelf").description("Self-hosted visual testing for Storybook.").version("0.2.0");
29
+ const commands = [
30
+ buildInitCommand(),
31
+ buildCreateCommand(),
32
+ buildServerCommand(),
33
+ buildWorkerCommand(),
34
+ buildPurgeCommand(),
35
+ buildUploadCommand(),
36
+ buildBuildCommand(),
37
+ buildDoctorCommand(),
38
+ buildWhoamiCommand(),
39
+ buildRetryCommand()
40
+ ];
41
+ for (const command of commands) program.addCommand(command);
42
+ return program;
43
+ }
15
44
  function run(fn) {
16
45
  return async (args) => {
17
46
  await fn(args).catch(handleError);
@@ -26,33 +55,36 @@ function buildCreateCommand() {
26
55
  function buildServerCommand() {
27
56
  const server = new Command("server").description("Server operations");
28
57
  server.command("init").description("Scaffold a new StoryShelf server project").option("--dir <dir>", "output directory").action(run(runServerInit));
58
+ const serve = new Command("serve").description("Run a scaffolded StoryShelf server project").option("--dir <dir>", "server project directory (default cwd)").option("--port <port>", "port override (sets PORT)").action(run(runServerServe));
59
+ server.addCommand(serve, { isDefault: true });
29
60
  return server;
30
61
  }
62
+ function buildWorkerCommand() {
63
+ const worker = new Command("worker").description("Worker operations");
64
+ worker.command("init").description("Scaffold a new StoryShelf worker project").option("--dir <dir>", "output directory").action(run(runWorkerInit));
65
+ worker.command("serve").description("Run a scaffolded StoryShelf worker project").option("--dir <dir>", "worker project directory (default cwd)").option("--queue-url <url>", "SQS queue URL override (sets QUEUE_URL)").option("--concurrency <n>", "concurrency override (sets WORKER_CONCURRENCY)").action(run(runWorkerServe));
66
+ const runCmd = new Command("run").description("Run a scaffolded worker (alias for worker serve)").option("--dir <dir>", "worker project directory (default cwd)").option("--queue-url <url>", "SQS queue URL override").option("--concurrency <n>", "concurrency override").action(run(runWorkerServe));
67
+ worker.addCommand(runCmd);
68
+ return worker;
69
+ }
31
70
  function buildPurgeCommand() {
32
71
  return new Command("purge").description("Purge expired builds on a StoryShelf server").requiredOption("--url <url>", "server base URL").option("--token <token>", "admin token (or STORYSHELF_ADMIN_TOKEN env)").action(run(runPurge));
33
72
  }
34
73
  function buildUploadCommand() {
35
- return new Command("upload").description("Create a build record for a StoryShelf project").option("--url <url>", "server base URL (or .storybook/storyshelf.json)").option("--slug <slug>", "project slug (or .storybook/storyshelf.json)").option("--token <token>", "CI token (or STORYSHELF_TOKEN env)").option("--sha <sha>", "git sha (or GITHUB_SHA env)").option("--branch <branch>", "git branch (or GITHUB_REF_NAME env)").option("--build-dir <dir>", "built Storybook directory (default storybook-static)").option("-c, --config <path>", "config file path (default .storybook/storyshelf.json)").option("--build-command <cmd>", "build command to run if buildDir missing/empty").option("--build-script-name <name>", "npm script to build Storybook (default build-storybook)").option("--force-build", "force rebuild even if buildDir exists").option("--skip <glob>", "skip upload for matching branch (glob)").option("--message <message>", "commit message").option("--author-email <email>", "author email").option("--author-name <name>", "author name").option("--label <key=value>", "build label (repeatable: --label pr=123)", (value, previous) => [...previous, value], []).action(run(runUpload));
74
+ return new Command("upload").description("Create a build record for a StoryShelf project").option("--url <url>", "server base URL (or .storybook/storyshelf.json)").option("--slug <slug>", "project slug (or .storybook/storyshelf.json)").option("--token <token>", "CI token (or STORYSHELF_TOKEN env)").option("--sha <sha>", "revision SHA (flag, CI env, local git HEAD, or synthesized local-*)").option("--branch <branch>", "baseline namespace (flag, CI env, local git branch, or local)").option("--build-dir <dir>", "built Storybook directory (default storybook-static)").option("-c, --config <path>", "config file path (default .storybook/storyshelf.json)").option("--build-command <cmd>", "build command to run if buildDir missing/empty").option("--build-script-name <name>", "npm script to build Storybook (default build-storybook)").option("--force-build", "force rebuild even if buildDir exists").option("--dry-run", "validate and build without sending any requests").option("--skip <glob>", "skip upload for matching branch (glob)").option("--message <message>", "build message").option("--author-email <email>", "author email").option("--author-name <name>", "author name").option("--full", "disable affected capture (render every story)").option("--untraced <glob>", "exclude matching files from affected tracing (repeatable)", (value, previous) => [...previous, value], []).option("--stats-file <path>", "bundler stats file (default <buildDir>/preview-stats.json)").option("--label <key=value>", "build label (repeatable: --label pr=123)", (value, previous) => [...previous, value], []).action(run(runUpload));
75
+ }
76
+ function buildBuildCommand() {
77
+ return new Command("build").description("Build Storybook for upload (no server contact)").option("--build-dir <dir>", "built Storybook directory (default storybook-static)").option("-c, --config <path>", "config file path (default .storybook/storyshelf.json)").option("--build-command <cmd>", "build command to run if buildDir missing/empty").option("--build-script-name <name>", "npm script to build Storybook (default build-storybook)").option("--force-build", "force rebuild even if buildDir exists").action(run(runBuild));
78
+ }
79
+ function buildDoctorCommand() {
80
+ return new Command("doctor").description("Diagnose whether an upload would succeed (no side effects)").option("--url <url>", "server base URL (or .storybook/storyshelf.json)").option("--slug <slug>", "project slug (or .storybook/storyshelf.json)").option("--token <token>", "CI token (or STORYSHELF_TOKEN env)").option("--build-dir <dir>", "built Storybook directory (default storybook-static)").option("-c, --config <path>", "config file path (default .storybook/storyshelf.json)").option("--build-command <cmd>", "build command to run if buildDir missing/empty").option("--build-script-name <name>", "npm script to build Storybook (default build-storybook)").action(run(runDoctor));
81
+ }
82
+ function buildWhoamiCommand() {
83
+ return new Command("whoami").description("Verify the token against the server and print the project").option("--url <url>", "server base URL (or .storybook/storyshelf.json)").option("--slug <slug>", "project slug (or .storybook/storyshelf.json)").option("--token <token>", "CI token (or STORYSHELF_TOKEN env)").option("-c, --config <path>", "config file path (default .storybook/storyshelf.json)").action(run(runWhoami));
36
84
  }
37
85
  function buildRetryCommand() {
38
86
  return new Command("retry").description("Retry a failed StoryShelf build").requiredOption("--url <url>", "server base URL").requiredOption("--slug <slug>", "project slug").requiredOption("--build-id <id>", "build id").option("--token <token>", "CI token (or STORYSHELF_TOKEN env)").action(run(runRetry));
39
87
  }
40
- /**
41
- * Build the StoryShelf CLI program with all subcommands registered.
42
- *
43
- * @returns The configured commander Command instance.
44
- */
45
- function createProgram() {
46
- const program = new Command();
47
- program.name("storyshelf").description("Self-hosted visual testing for Storybook.").version("0.2.0");
48
- program.addCommand(buildInitCommand());
49
- program.addCommand(buildCreateCommand());
50
- program.addCommand(buildServerCommand());
51
- program.addCommand(buildPurgeCommand());
52
- program.addCommand(buildUploadCommand());
53
- program.addCommand(buildRetryCommand());
54
- return program;
55
- }
56
88
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
57
89
  const program = createProgram();
58
90
  if (process.argv.length <= 2) await runDefaultCommand(program);
package/dist/output.js CHANGED
@@ -3,12 +3,15 @@ import "node:path";
3
3
  import "node:url";
4
4
  import.meta.url;
5
5
  //#region src/output.ts
6
+ /** Print a line to stdout with a trailing newline. */
6
7
  function printLine(message) {
7
8
  process.stdout.write(`${message}\n`);
8
9
  }
10
+ /** Print a line to stderr (used for errors and warnings). */
9
11
  function printError(message) {
10
12
  process.stderr.write(`${message}\n`);
11
13
  }
14
+ /** Braille spinner frames used by {@link createSpinner} for upload progress. */
12
15
  const spinnerFrames = [
13
16
  "⠋",
14
17
  "⠙",
@@ -21,6 +24,13 @@ const spinnerFrames = [
21
24
  "⠇",
22
25
  "⠏"
23
26
  ];
27
+ /**
28
+ * Create an inline spinner that animates while a long operation runs.
29
+ *
30
+ * @param message - Message shown next to the spinning frame
31
+ * @param frames - Frame sequence; defaults to {@link spinnerFrames}
32
+ * @returns Handle with `stop(finalMessage?)` to clear the line and optionally print a result
33
+ */
24
34
  function createSpinner(message, frames = spinnerFrames) {
25
35
  let frame = 0;
26
36
  const interval = setInterval(() => {
package/package.json CHANGED
@@ -1,7 +1,14 @@
1
1
  {
2
2
  "name": "storyshelf",
3
- "version": "0.3.2",
3
+ "version": "0.5.3",
4
4
  "description": "StoryShelf CLI: create projects, upload builds, purge, and retry from CI.",
5
+ "keywords": [
6
+ "ci",
7
+ "cli",
8
+ "self-hosted",
9
+ "storybook",
10
+ "visual-testing"
11
+ ],
5
12
  "homepage": "https://github.com/GuptaSiddhant/StoryShelf#readme",
6
13
  "bugs": {
7
14
  "url": "https://github.com/GuptaSiddhant/StoryShelf/issues"
@@ -20,7 +27,8 @@
20
27
  "storyshelf": "dist/index.js"
21
28
  },
22
29
  "files": [
23
- "dist"
30
+ "dist",
31
+ "schema"
24
32
  ],
25
33
  "type": "module",
26
34
  "sideEffects": false,
@@ -42,26 +50,26 @@
42
50
  "prepublishOnly": "nub run build"
43
51
  },
44
52
  "dependencies": {
53
+ "@storyshelf/affected": "0.5.3",
45
54
  "archiver": "8.0.0",
46
55
  "commander": "^13.0.0",
47
56
  "hono": "^4.11.0",
48
57
  "picomatch": "^4.0.2",
49
- "prompts": "^2.4.2",
50
- "zod": "^4.2.0"
58
+ "prompts": "^2.4.2"
51
59
  },
52
60
  "devDependencies": {
53
- "@storyshelf/core": "workspace:*",
54
- "@types/node": "catalog:",
61
+ "@storyshelf/core": "0.5.3",
62
+ "@types/node": "^26.0.0",
55
63
  "@types/picomatch": "^4.0.1",
56
64
  "@types/prompts": "^2.4.9",
57
- "@vitest/coverage-v8": "catalog:",
65
+ "@vitest/coverage-v8": "^4.0.0",
58
66
  "adm-zip": "0.6.0",
59
- "oxfmt": "catalog:",
60
- "oxlint": "catalog:",
61
- "oxlint-tsgolint": "catalog:",
62
- "tsdown": "catalog:",
63
- "typescript": "catalog:",
64
- "vitest": "catalog:"
67
+ "oxfmt": "^0.65.0",
68
+ "oxlint": "^1.80.0",
69
+ "oxlint-tsgolint": "^7.0.2001",
70
+ "tsdown": "^0.22.14",
71
+ "typescript": "^7.0.2",
72
+ "vitest": "^5.0.0"
65
73
  },
66
74
  "jsr": false
67
75
  }