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.
@@ -0,0 +1,475 @@
1
+ #!/usr/bin/env node
2
+ import "node:path";
3
+ import "node:url";
4
+ import.meta.url;
5
+ import { TERRAFORM_REQUIRED_VERSION } from "./terraform-aws.js";
6
+ //#region src/commands/server/terraform-gcp.ts
7
+ function header() {
8
+ return `# Generated by \`storyshelf server init --target gcp\`. Do not edit by hand;\n# re-run the scaffold or edit the generator in @storyshelf/cli.\n\n`;
9
+ }
10
+ function generateGcpVersions() {
11
+ return `${header()}terraform {
12
+ required_version = "${TERRAFORM_REQUIRED_VERSION}"
13
+
14
+ required_providers {
15
+ google = {
16
+ source = "hashicorp/google"
17
+ version = ">= 6.0"
18
+ }
19
+ random = {
20
+ source = "hashicorp/random"
21
+ version = ">= 3.0"
22
+ }
23
+ }
24
+ }
25
+
26
+ provider "google" {
27
+ project = var.gcp_project_id
28
+ region = var.location
29
+ }
30
+ `;
31
+ }
32
+ function generateGcpVariables() {
33
+ return `${header()}variable "project" {
34
+ description = "Project slug, used as a name prefix for all resources."
35
+ type = string
36
+ }
37
+
38
+ variable "gcp_project_id" {
39
+ description = "Existing GCP project ID (APIs, billing, and IAM live here)."
40
+ type = string
41
+ }
42
+
43
+ variable "location" {
44
+ description = "GCP region for all resources."
45
+ type = string
46
+ default = "us-central1"
47
+ }
48
+
49
+ variable "domain_name" {
50
+ description = "Public domain for the app (Cloud DNS + domain mapping). Empty skips DNS."
51
+ type = string
52
+ default = ""
53
+ }
54
+
55
+ variable "identity_tenant" {
56
+ description = "Identity Platform tenant display name. Empty skips identity."
57
+ type = string
58
+ default = ""
59
+ }
60
+ `;
61
+ }
62
+ function generateGcpMain() {
63
+ return `${header()}# Enable every API the stack touches. disable_on_destroy stays
64
+ # default (true) so CI teardown also releases the API bindings.
65
+ locals {
66
+ slug = lower(var.project)
67
+ apis = toset([
68
+ "run.googleapis.com",
69
+ "sqladmin.googleapis.com",
70
+ "pubsub.googleapis.com",
71
+ "storage.googleapis.com",
72
+ "secretmanager.googleapis.com",
73
+ "dns.googleapis.com",
74
+ "identitytoolkit.googleapis.com",
75
+ ])
76
+ }
77
+
78
+ resource "google_project_service" "apis" {
79
+ for_each = local.apis
80
+ project = var.gcp_project_id
81
+ service = each.value
82
+ }
83
+ `;
84
+ }
85
+ function generateGcpApp() {
86
+ return `${header()}# App with public ingress. Image is a placeholder: build and push
87
+ # the scaffolded Dockerfile (Artifact Registry) and update it before apply.
88
+ resource "google_cloud_run_v2_service" "app" {
89
+ name = "\${local.slug}-app"
90
+ location = var.location
91
+
92
+ template {
93
+ containers {
94
+ image = "storyshelf:latest"
95
+
96
+ ports {
97
+ container_port = 3000
98
+ }
99
+
100
+ resources {
101
+ limits = {
102
+ cpu = "1"
103
+ memory = "2Gi"
104
+ }
105
+ }
106
+ }
107
+
108
+ scaling {
109
+ min_instance_count = 1
110
+ max_instance_count = 3
111
+ }
112
+ }
113
+
114
+ ingress = "INGRESS_TRAFFIC_ALL"
115
+ }
116
+ `;
117
+ }
118
+ function generateGcpWorker() {
119
+ return `${header()}# Worker polls the capture queue and renders with Playwright.
120
+ # Internal ingress only: it makes outbound calls (queue, database, storage).
121
+ resource "google_cloud_run_v2_service" "worker" {
122
+ name = "\${local.slug}-worker"
123
+ location = var.location
124
+
125
+ template {
126
+ containers {
127
+ image = "storyshelf-worker:latest"
128
+
129
+ resources {
130
+ limits = {
131
+ cpu = "2"
132
+ memory = "4Gi"
133
+ }
134
+ }
135
+ }
136
+
137
+ scaling {
138
+ min_instance_count = 1
139
+ max_instance_count = 3
140
+ }
141
+ }
142
+
143
+ ingress = "INGRESS_TRAFFIC_INTERNAL_ONLY"
144
+ }
145
+ `;
146
+ }
147
+ function generateGcpDatabase() {
148
+ return `${header()}# Cloud SQL Postgres, smallest shared-core tier (test-profile
149
+ # default — raise tier for production). The server connects with
150
+ # createPostgresDatabase({ url: <database_url output> }).
151
+ resource "random_password" "db" {
152
+ length = 32
153
+ special = true
154
+ }
155
+
156
+ resource "google_sql_database_instance" "main" {
157
+ name = "\${local.slug}-db"
158
+ region = var.location
159
+ database_version = "POSTGRES_16"
160
+
161
+ settings {
162
+ tier = "db-f1-micro"
163
+
164
+ backup_configuration {
165
+ enabled = true
166
+ }
167
+
168
+ ip_configuration {
169
+ ipv4_enabled = true
170
+ require_ssl = true
171
+ }
172
+ }
173
+ }
174
+
175
+ resource "google_sql_database" "shelf" {
176
+ name = "shelf"
177
+ instance = google_sql_database_instance.main.name
178
+ }
179
+
180
+ resource "google_sql_user" "shelf" {
181
+ name = "shelfadmin"
182
+ instance = google_sql_database_instance.main.name
183
+ password = random_password.db.result
184
+ }
185
+ `;
186
+ }
187
+ function generateGcpStorage() {
188
+ return `${header()}# Bucket for storybook bundles. force_destroy keeps the CI
189
+ # teardown working on non-empty buckets; versioning plus a 30-day
190
+ # lifecycle on transient builds mirrors the S3 reference stack.
191
+ resource "google_storage_bucket" "storybook" {
192
+ name = "\${local.slug}-storybook"
193
+ location = var.location
194
+ force_destroy = true
195
+ public_access_prevention = "enforced"
196
+ uniform_bucket_level_access = true
197
+
198
+ versioning {
199
+ enabled = true
200
+ }
201
+
202
+ lifecycle_rule {
203
+ action {
204
+ type = "Delete"
205
+ }
206
+
207
+ condition {
208
+ age = 30
209
+ matches_prefix = ["builds/"]
210
+ }
211
+ }
212
+ }
213
+ `;
214
+ }
215
+ function generateGcpQueue() {
216
+ return `${header()}# Pull subscription with dead-lettering: past max deliveries the
217
+ # message moves to the DLQ topic — the GCP analog of SQS + DLQ. The
218
+ # subscription name matches the scaffolded worker default. Grant the
219
+ # runtime service account Pub/Sub roles post-apply (see README).
220
+ resource "google_pubsub_topic" "capture" {
221
+ name = "\${local.slug}-capture"
222
+ }
223
+
224
+ resource "google_pubsub_topic" "capture_dlq" {
225
+ name = "\${local.slug}-capture-dlq"
226
+ }
227
+
228
+ resource "google_pubsub_subscription" "capture" {
229
+ name = "capture-jobs"
230
+ topic = google_pubsub_topic.capture.id
231
+
232
+ ack_deadline_seconds = 300
233
+ message_retention_duration = "604800s"
234
+
235
+ dead_letter_policy {
236
+ dead_letter_topic = google_pubsub_topic.capture_dlq.id
237
+ max_delivery_attempts = 5
238
+ }
239
+ }
240
+ `;
241
+ }
242
+ function generateGcpIdentity() {
243
+ return `${header()}# Identity Platform tenant for OIDC sign-in. Skipped entirely
244
+ # when var.identity_tenant is empty (use any OIDC provider instead).
245
+ resource "google_identity_platform_tenant" "main" {
246
+ count = var.identity_tenant == "" ? 0 : 1
247
+ display_name = var.identity_tenant
248
+ project = var.gcp_project_id
249
+ allow_password_signup = false
250
+ }
251
+ `;
252
+ }
253
+ function generateGcpSecrets() {
254
+ return `${header()}# Secret Manager: session secret, OIDC secret, break-glass admin
255
+ # token, and the Postgres password. Never check these into env files.
256
+ resource "google_secret_manager_secret" "shelf_secret" {
257
+ secret_id = "\${local.slug}-secret"
258
+
259
+ replication {
260
+ auto {}
261
+ }
262
+ }
263
+
264
+ resource "google_secret_manager_secret_version" "shelf_secret" {
265
+ secret = google_secret_manager_secret.shelf_secret.id
266
+ secret_data = "change-me"
267
+ }
268
+
269
+ resource "google_secret_manager_secret" "oidc_client_secret" {
270
+ secret_id = "\${local.slug}-oidc-client-secret"
271
+
272
+ replication {
273
+ auto {}
274
+ }
275
+ }
276
+
277
+ resource "google_secret_manager_secret_version" "oidc_client_secret" {
278
+ secret = google_secret_manager_secret.oidc_client_secret.id
279
+ secret_data = "change-me"
280
+ }
281
+
282
+ resource "google_secret_manager_secret" "admin_token" {
283
+ secret_id = "\${local.slug}-admin-token"
284
+
285
+ replication {
286
+ auto {}
287
+ }
288
+ }
289
+
290
+ resource "google_secret_manager_secret_version" "admin_token" {
291
+ secret = google_secret_manager_secret.admin_token.id
292
+ secret_data = "change-me"
293
+ }
294
+
295
+ resource "google_secret_manager_secret" "db_password" {
296
+ secret_id = "\${local.slug}-db-password"
297
+
298
+ replication {
299
+ auto {}
300
+ }
301
+ }
302
+
303
+ resource "google_secret_manager_secret_version" "db_password" {
304
+ secret = google_secret_manager_secret.db_password.id
305
+ secret_data = random_password.db.result
306
+ }
307
+ `;
308
+ }
309
+ function generateGcpDns() {
310
+ return `${header()}# Cloud DNS zone + app CNAME + domain mapping. Skipped entirely
311
+ # when var.domain_name is empty. Google issues the managed certificate
312
+ # automatically once the records resolve.
313
+ resource "google_dns_managed_zone" "main" {
314
+ count = var.domain_name == "" ? 0 : 1
315
+ name = "\${local.slug}-zone"
316
+ dns_name = "\${var.domain_name}."
317
+ description = "\${var.project} app zone"
318
+ }
319
+
320
+ resource "google_dns_record_set" "app" {
321
+ count = var.domain_name == "" ? 0 : 1
322
+ name = "app.\${var.domain_name}."
323
+ type = "CNAME"
324
+ ttl = 300
325
+ managed_zone = google_dns_managed_zone.main[0].name
326
+ rrdatas = ["\${trimsuffix(replace(google_cloud_run_v2_service.app.uri, "https://", ""), "/")}."]
327
+ }
328
+
329
+ resource "google_cloud_run_domain_mapping" "app" {
330
+ count = var.domain_name == "" ? 0 : 1
331
+ location = var.location
332
+ name = "app.\${var.domain_name}"
333
+
334
+ metadata {
335
+ namespace = var.gcp_project_id
336
+ }
337
+
338
+ spec {
339
+ route_name = google_cloud_run_v2_service.app.name
340
+ }
341
+ }
342
+ `;
343
+ }
344
+ function generateGcpOutputs() {
345
+ return `${header()}# Outputs feed directly into the scaffolded server's env. Keys are
346
+ # a stable contract parsed by CI — do not rename (tests pin the set).
347
+ # Values are "" when the resource is not provisioned.
348
+ output "run_url" {
349
+ value = google_cloud_run_v2_service.app.uri
350
+ }
351
+
352
+ output "gcs_bucket" {
353
+ value = google_storage_bucket.storybook.name
354
+ }
355
+
356
+ output "pubsub_topic" {
357
+ value = google_pubsub_topic.capture.id
358
+ }
359
+
360
+ output "pubsub_subscription" {
361
+ value = google_pubsub_subscription.capture.id
362
+ }
363
+
364
+ output "database_url" {
365
+ value = "postgresql://shelfadmin:\${random_password.db.result}@\${google_sql_database_instance.main.public_ip_address}:5432/shelf?sslmode=require"
366
+ sensitive = true
367
+ }
368
+
369
+ output "identity_tenant_id" {
370
+ value = var.identity_tenant == "" ? "" : google_identity_platform_tenant.main[0].name
371
+ }
372
+ `;
373
+ }
374
+ function generateGcpTfvarsExample() {
375
+ return `# Copy to terraform.tfvars and fill in per environment.
376
+ # CI test profile: pass a unique project per run instead —
377
+ # terraform plan -var "project=shelf-ci-$GITHUB_RUN_ID"
378
+ project = "my-storyshelf"
379
+ gcp_project_id = "my-gcp-project"
380
+ location = "us-central1"
381
+ domain_name = ""
382
+ identity_tenant = ""
383
+ `;
384
+ }
385
+ function generateGcpEnvTable() {
386
+ return `| Output | Env var | Adapter |
387
+ |---|---|---|
388
+ | \`gcs_bucket\` (+ \`GOOGLE_CLOUD_PROJECT\`) | \`GCS_BUCKET\` | \`storage-gcs\` |
389
+ | \`pubsub_topic\` / \`pubsub_subscription\` | topic \`capture-jobs\` + subscription (baked into scaffold) | \`queue-gcp\` |
390
+ | \`database_url\` | \`DATABASE_URL\` | \`db-postgres\` |
391
+ | \`identity_tenant_id\` | \`OIDC_ISSUER\` (tenant issuer URL) / \`OIDC_CLIENT_ID\` | \`auth\` (keycloak recipe) |
392
+ | Secret Manager | \`SECRET\` / \`OIDC_CLIENT_SECRET\` / \`ADMIN_TOKEN\` | sessions / OIDC / bootstrap |
393
+ `;
394
+ }
395
+ function generateGcpCiProfile() {
396
+ return `## CI test profile
397
+
398
+ Smallest footprint, unique resources per run, documented destroy:
399
+
400
+ \`\`\`sh
401
+ export PROJECT="shelf-ci-$GITHUB_RUN_ID" # unique prefix per run (all names derive from it)
402
+ terraform init
403
+ terraform plan -var "project=$PROJECT" -out=tfplan
404
+ terraform apply tfplan
405
+ terraform output -json # or: npm run infra:outputs
406
+ # ... run live tests against the outputs ...
407
+ terraform destroy -var "project=$PROJECT" -auto-approve
408
+ \`\`\`
409
+
410
+ Cost notes: Cloud SQL runs the shared-core \`db-f1-micro\` tier and the
411
+ worker scales to a single instance; the bucket uses
412
+ \`force_destroy\` so teardown succeeds on non-empty buckets. Prefer a
413
+ fresh unique prefix per run.
414
+ `;
415
+ }
416
+ function generateGcpReadme(project) {
417
+ return `# ${project} on Google Cloud
418
+
419
+ Scaffolded by \`storyshelf server init --target gcp\`.
420
+
421
+ ## Next steps
422
+
423
+ \`\`\`sh
424
+ gcloud auth login
425
+ gcloud config set project <gcp-project-id>
426
+ cd terraform
427
+ terraform init
428
+ terraform plan -out=tfplan # review before applying
429
+ terraform apply tfplan
430
+ \`\`\`
431
+
432
+ Grant the runtime service account Pub/Sub (publisher/subscriber), Cloud
433
+ SQL Client, and Secret Manager accessor roles post-apply — Terraform
434
+ creates the resources, IAM bindings stay with your org policy.
435
+
436
+ ## Wire outputs into env
437
+
438
+ \`\`\`sh
439
+ terraform output -json # or: npm run infra:outputs
440
+ \`\`\`
441
+
442
+ ${generateGcpEnvTable()}
443
+ \`\`\`sh
444
+ npm install
445
+ npm start
446
+ \`\`\`
447
+
448
+ Authenticate with \`gcloud auth login\` (or workload identity / a
449
+ service-account key) — never check credentials into env files.
450
+
451
+ ${generateGcpCiProfile()}`;
452
+ }
453
+ const GCP_FILES = [
454
+ ["terraform/versions.tf", () => generateGcpVersions()],
455
+ ["terraform/variables.tf", () => generateGcpVariables()],
456
+ ["terraform/main.tf", () => generateGcpMain()],
457
+ ["terraform/compute.tf", () => `${generateGcpApp()}${generateGcpWorker()}`],
458
+ ["terraform/database.tf", () => generateGcpDatabase()],
459
+ ["terraform/storage.tf", () => generateGcpStorage()],
460
+ ["terraform/queue.tf", () => generateGcpQueue()],
461
+ ["terraform/identity.tf", () => generateGcpIdentity()],
462
+ ["terraform/secrets.tf", () => generateGcpSecrets()],
463
+ ["terraform/dns.tf", () => generateGcpDns()],
464
+ ["terraform/outputs.tf", () => generateGcpOutputs()],
465
+ ["terraform/terraform.tfvars.example", () => generateGcpTfvarsExample()]
466
+ ];
467
+ /** Generate every Terraform file for the GCP reference stack. */
468
+ function generateGcpTerraformFiles(options) {
469
+ const files = {};
470
+ for (const [path, generate] of GCP_FILES) files[path] = generate(options);
471
+ files["terraform/README.md"] = generateGcpReadme(options.project);
472
+ return files;
473
+ }
474
+ //#endregion
475
+ export { generateGcpApp, generateGcpDatabase, generateGcpDns, generateGcpIdentity, generateGcpMain, generateGcpOutputs, generateGcpQueue, generateGcpReadme, generateGcpSecrets, generateGcpStorage, generateGcpTerraformFiles, generateGcpTfvarsExample, generateGcpVariables, generateGcpVersions, generateGcpWorker };
@@ -0,0 +1,104 @@
1
+ #!/usr/bin/env node
2
+ import "node:path";
3
+ import "node:url";
4
+ import.meta.url;
5
+ import { join } from "node:path";
6
+ import { readFileSync } from "node:fs";
7
+ //#region src/commands/shared/detect-adapters.ts
8
+ /**
9
+ * Detect installed adapter choices from a project's package.json.
10
+ *
11
+ * Reads `dependencies` and `devDependencies` keys and maps them to the prompt
12
+ * choices used by `server init` / `worker init`. Missing or malformed
13
+ * package.json returns an empty object.
14
+ *
15
+ * @param dir - Absolute path to the scaffolded project directory.
16
+ * @returns Detected adapter selections (partial).
17
+ */
18
+ function detectInstalledAdapters(dir) {
19
+ const pkgPath = join(dir, "package.json");
20
+ let raw;
21
+ try {
22
+ raw = readFileSync(pkgPath, "utf8");
23
+ } catch {
24
+ return {};
25
+ }
26
+ let pkg;
27
+ try {
28
+ pkg = JSON.parse(raw);
29
+ } catch {
30
+ return {};
31
+ }
32
+ const deps = /* @__PURE__ */ new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]);
33
+ const result = {};
34
+ if (deps.has("@storyshelf/db-mysql")) result.database = detectMysqlFlavor(dir, deps);
35
+ else if (deps.has("@storyshelf/db-postgres")) result.database = detectPostgresFlavor(dir, deps);
36
+ else if (deps.has("@storyshelf/db-turso")) result.database = "turso";
37
+ else if (deps.has("@storyshelf/db-sqlite")) result.database = detectSqliteFlavor(dir, deps);
38
+ if (deps.has("@storyshelf/storage-azure")) result.storage = "azure";
39
+ else if (deps.has("@storyshelf/storage-gcs")) result.storage = "gcs";
40
+ else if (deps.has("@storyshelf/storage-s3")) result.storage = "s3";
41
+ else if (deps.has("@storyshelf/storage-local")) result.storage = "local";
42
+ if (deps.has("@storyshelf/queue-azure")) result.queue = deps.has("@azure/service-bus") ? "azure-service-bus" : "azure-storage-queues";
43
+ else if (deps.has("@storyshelf/queue-gcp")) result.queue = "gcp-pubsub";
44
+ else if (deps.has("@storyshelf/queue-sqs")) result.queue = "sqs";
45
+ else if (deps.has("@storyshelf/queue-redis")) result.queue = "redis";
46
+ else if (deps.has("@storyshelf/worker")) {}
47
+ if (deps.has("@storyshelf/git-github")) result.git = "github";
48
+ else if (deps.has("@storyshelf/git-gitlab")) result.git = "gitlab";
49
+ return result;
50
+ }
51
+ /**
52
+ * Distinguish the `@storyshelf/db-sqlite` presets. Peer deps disambiguate
53
+ * turso/better-sqlite3; `bun:sqlite` is a builtin and D1 has no marker dep,
54
+ * so fall back to scanning generated sources for subpath imports.
55
+ */
56
+ function detectSqliteFlavor(dir, deps) {
57
+ if (deps.has("better-sqlite3")) return "better-sqlite3";
58
+ if (deps.has("@libsql/client")) return "turso";
59
+ const sources = readGeneratedSources(dir);
60
+ if (sources.includes("@storyshelf/db-sqlite/bun-sqlite")) return "bun-sqlite";
61
+ if (sources.includes("@storyshelf/db-sqlite/d1")) return "d1";
62
+ if (sources.includes("@storyshelf/db-sqlite/better-sqlite3")) return "better-sqlite3";
63
+ if (sources.includes("@storyshelf/db-sqlite/turso")) return "turso";
64
+ return "sqlite";
65
+ }
66
+ function detectPostgresFlavor(dir, deps) {
67
+ if (deps.has("pg")) return "pg";
68
+ if (deps.has("@neondatabase/serverless")) {
69
+ if (readGeneratedSources(dir).includes("@storyshelf/db-postgres/neon-http")) return "neon-http";
70
+ return "neon";
71
+ }
72
+ if (deps.has("@vercel/postgres")) return "vercel";
73
+ if (deps.has("@electric-sql/pglite")) return "pglite";
74
+ const sources = readGeneratedSources(dir);
75
+ if (sources.includes("@storyshelf/db-postgres/pg")) return "pg";
76
+ if (sources.includes("@storyshelf/db-postgres/neon-http")) return "neon-http";
77
+ if (sources.includes("@storyshelf/db-postgres/neon")) return "neon";
78
+ if (sources.includes("@storyshelf/db-postgres/vercel")) return "vercel";
79
+ if (sources.includes("@storyshelf/db-postgres/pglite")) return "pglite";
80
+ return "postgres";
81
+ }
82
+ function detectMysqlFlavor(dir, deps) {
83
+ if (deps.has("@planetscale/database")) return "planetscale";
84
+ if (deps.has("@tidbcloud/serverless")) return "tidb";
85
+ if (deps.has("mysql2")) {
86
+ const sources = readGeneratedSources(dir);
87
+ if (sources.includes("@storyshelf/db-mysql/planetscale")) return "planetscale";
88
+ if (sources.includes("@storyshelf/db-mysql/tidb")) return "tidb";
89
+ return "mysql";
90
+ }
91
+ const sources = readGeneratedSources(dir);
92
+ if (sources.includes("@storyshelf/db-mysql/planetscale")) return "planetscale";
93
+ if (sources.includes("@storyshelf/db-mysql/tidb")) return "tidb";
94
+ return "mysql";
95
+ }
96
+ function readGeneratedSources(dir) {
97
+ let sources = "";
98
+ for (const file of ["server.ts", "worker.ts"]) try {
99
+ sources += readFileSync(join(dir, file), "utf8");
100
+ } catch {}
101
+ return sources;
102
+ }
103
+ //#endregion
104
+ export { detectInstalledAdapters };
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ import "node:path";
3
+ import "node:url";
4
+ import.meta.url;
5
+ import { detectPackageRunner } from "../config.js";
6
+ import { printLine } from "../output.js";
7
+ import { resolve } from "node:path";
8
+ import { execSync } from "node:child_process";
9
+ import { access, readdir } from "node:fs/promises";
10
+ //#region src/commands/storybook-build.ts
11
+ /**
12
+ * Script invocation per runner. npm needs `--` to forward args; pnpm, bun,
13
+ * yarn, deno, and nub append trailing args to the script directly (a literal
14
+ * `--` would be forwarded as a positional and can break the build).
15
+ */
16
+ function scriptCommand(runner, scriptName, buildDir) {
17
+ const args = `--output-dir ${buildDir}`;
18
+ if (runner === "npm") return `npm run ${scriptName} -- ${args}`;
19
+ if (runner === "deno") return `deno task ${scriptName} ${args}`;
20
+ if (runner === "yarn") return `yarn ${scriptName} ${args}`;
21
+ return `${runner} run ${scriptName} ${args}`;
22
+ }
23
+ /** Resolve the shell command that builds the Storybook directory. */
24
+ async function resolveBuildCommand(cwd, buildDir, buildCommand, buildScriptName) {
25
+ if (buildCommand) return buildCommand;
26
+ return scriptCommand(await detectPackageRunner(cwd), buildScriptName ?? "build-storybook", buildDir);
27
+ }
28
+ /** Build the Storybook directory when missing, empty, or forced. */
29
+ async function ensureBuildDir(opts) {
30
+ if (opts.buildCommand && opts.buildScriptName) throw new Error("buildCommand and buildScriptName are mutually exclusive");
31
+ const full = resolve(opts.cwd, opts.buildDir);
32
+ if (!(opts.force ?? await needsBuild(full))) return;
33
+ const command = await resolveBuildCommand(opts.cwd, opts.buildDir, opts.buildCommand, opts.buildScriptName);
34
+ printLine(`Building Storybook: ${command}`);
35
+ execSync(command, {
36
+ stdio: "inherit",
37
+ env: {
38
+ ...process.env,
39
+ STORYBOOK_BUILD_STORIES_JSON: "true"
40
+ }
41
+ });
42
+ }
43
+ /** True when the build directory is missing or empty. */
44
+ async function needsBuild(full) {
45
+ try {
46
+ await access(full);
47
+ return (await readdir(full)).length === 0;
48
+ } catch {
49
+ return true;
50
+ }
51
+ }
52
+ /** Fail fast when the build output lacks the Storybook index. */
53
+ async function assertBuildOutput(cwd, buildDir) {
54
+ const index = resolve(cwd, buildDir, "index.json");
55
+ try {
56
+ await access(index);
57
+ } catch {
58
+ throw new Error(`Build output incomplete: ${index} not found — check --build-dir and the build command output`);
59
+ }
60
+ }
61
+ //#endregion
62
+ export { assertBuildOutput, ensureBuildDir, needsBuild, resolveBuildCommand };