@bigcommerce/catalyst 1.0.0-alpha.1 → 1.0.0-alpha.2

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.
Files changed (3) hide show
  1. package/dist/cli.js +1130 -662
  2. package/dist/cli.js.map +1 -1
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,15 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // src/cli/program.ts
4
- import { Command as Command8 } from "commander";
5
- import { colorize as colorize2 } from "consola/utils";
6
- import { config } from "dotenv";
7
- import { resolve } from "path";
3
+ // src/cli/lib/logger.ts
4
+ import { createConsola } from "consola";
5
+ var consola = createConsola({
6
+ level: "3" ? parseInt("3", 10) : 3
7
+ });
8
+
9
+ // src/cli/lib/telemetry.ts
10
+ import { Analytics } from "@segment/analytics-node";
11
+ import { randomBytes, randomUUID } from "crypto";
8
12
 
9
13
  // package.json
10
14
  var package_default = {
11
15
  name: "@bigcommerce/catalyst",
12
- version: "0.1.0",
16
+ version: "1.0.0-alpha.1",
13
17
  type: "module",
14
18
  bin: {
15
19
  catalyst: "dist/cli.js"
@@ -18,7 +22,6 @@ var package_default = {
18
22
  "dist",
19
23
  "templates"
20
24
  ],
21
- private: true,
22
25
  scripts: {
23
26
  dev: "tsup --watch",
24
27
  typecheck: "tsc --noEmit",
@@ -39,6 +42,7 @@ var package_default = {
39
42
  consola: "^3.4.2",
40
43
  dotenv: "^16.5.0",
41
44
  execa: "^9.6.0",
45
+ open: "^10.1.0",
42
46
  "yocto-spinner": "^1.0.0",
43
47
  zod: "^4.0.5"
44
48
  },
@@ -58,47 +62,27 @@ var package_default = {
58
62
  vitest: "^3.2.4"
59
63
  },
60
64
  peerDependencies: {
61
- "@opennextjs/cloudflare": "^1.8.0"
65
+ "@opennextjs/cloudflare": "1.17.3"
62
66
  }
63
67
  };
64
68
 
65
- // src/cli/commands/build.ts
66
- import { Command, Option } from "commander";
67
- import { execa } from "execa";
68
- import { existsSync } from "fs";
69
- import { copyFile, cp, writeFile } from "fs/promises";
70
- import { join as join3 } from "path";
71
-
72
- // src/cli/lib/get-module-cli-path.ts
73
- import { dirname, join } from "path";
74
- import { fileURLToPath } from "url";
75
- function getModuleCliPath() {
76
- const __filename = fileURLToPath(import.meta.url);
77
- const __dirname = dirname(__filename);
78
- return join(__dirname, "..");
79
- }
80
-
81
- // src/cli/lib/logger.ts
82
- import { createConsola } from "consola";
83
- var consola = createConsola({
84
- level: "3" ? parseInt("3", 10) : 3
85
- });
86
-
87
69
  // src/cli/lib/project-config.ts
88
70
  import Conf from "conf";
89
- import { join as join2 } from "path";
90
- function getProjectConfig(rootDir = process.cwd()) {
71
+ import { join } from "path";
72
+ function getProjectConfig() {
91
73
  return new Conf({
92
- cwd: join2(rootDir, ".bigcommerce"),
74
+ cwd: join(process.cwd(), ".bigcommerce"),
93
75
  projectSuffix: "",
94
76
  configName: "project",
95
77
  schema: {
96
78
  projectUuid: { type: "string", format: "uuid" },
97
79
  framework: {
98
80
  type: "string",
99
- enum: ["catalyst", "nextjs"],
100
- default: "nextjs"
81
+ enum: ["catalyst"],
82
+ default: "catalyst"
101
83
  },
84
+ storeHash: { type: "string" },
85
+ accessToken: { type: "string" },
102
86
  telemetry: {
103
87
  type: "object",
104
88
  properties: {
@@ -110,177 +94,12 @@ function getProjectConfig(rootDir = process.cwd()) {
110
94
  });
111
95
  }
112
96
 
113
- // src/cli/lib/wrangler-config.ts
114
- function getWranglerConfig(projectUuid, kvNamespaceId) {
115
- return {
116
- $schema: "node_modules/wrangler/config-schema.json",
117
- main: "../.open-next/worker.js",
118
- name: `project-${projectUuid}`,
119
- compatibility_date: "2025-07-15",
120
- compatibility_flags: ["nodejs_compat", "global_fetch_strictly_public"],
121
- observability: {
122
- enabled: true,
123
- head_sampling_rate: 0.05,
124
- logs: {
125
- enabled: true,
126
- head_sampling_rate: 1,
127
- invocation_logs: false
128
- }
129
- },
130
- assets: {
131
- directory: "../.open-next/assets",
132
- binding: "ASSETS"
133
- },
134
- services: [
135
- {
136
- binding: "WORKER_SELF_REFERENCE",
137
- service: `project-${projectUuid}`
138
- }
139
- ],
140
- kv_namespaces: [
141
- {
142
- binding: "NEXT_INC_CACHE_KV",
143
- id: kvNamespaceId
144
- }
145
- ],
146
- durable_objects: {
147
- bindings: [
148
- {
149
- name: "NEXT_CACHE_DO_QUEUE",
150
- class_name: "DOQueueHandler"
151
- },
152
- {
153
- name: "NEXT_TAG_CACHE_DO_SHARDED",
154
- class_name: "DOShardedTagCache"
155
- },
156
- {
157
- name: "NEXT_CACHE_DO_PURGE",
158
- class_name: "BucketCachePurge"
159
- }
160
- ]
161
- },
162
- migrations: [
163
- {
164
- tag: "v1",
165
- new_sqlite_classes: ["DOQueueHandler", "DOShardedTagCache", "BucketCachePurge"]
166
- }
167
- ]
168
- };
169
- }
170
-
171
- // src/cli/commands/build.ts
172
- var WRANGLER_VERSION = "4.24.3";
173
- var build = new Command("build").allowUnknownOption().argument(
174
- "[next-build-options...]",
175
- "Next.js `build` options (see: https://nextjs.org/docs/app/api-reference/cli/next#next-build-options)"
176
- ).addOption(
177
- new Option(
178
- "--project-uuid <uuid>",
179
- "Project UUID to be included in the deployment configuration."
180
- ).env("BIGCOMMERCE_PROJECT_UUID")
181
- ).addOption(
182
- new Option("--framework <framework>", "The framework to use for the build.").choices([
183
- "nextjs",
184
- "catalyst"
185
- ])
186
- ).action(async (nextBuildOptions, options) => {
187
- const coreDir = process.cwd();
188
- try {
189
- const config2 = getProjectConfig();
190
- const framework = options.framework ?? config2.get("framework");
191
- if (framework === "nextjs") {
192
- const nextBin = join3("node_modules", ".bin", "next");
193
- if (!existsSync(nextBin)) {
194
- throw new Error(
195
- `Next.js is not installed in ${coreDir}. Are you in a valid Next.js project?`
196
- );
197
- }
198
- await execa(nextBin, ["build", ...nextBuildOptions], {
199
- stdio: "inherit",
200
- cwd: coreDir
201
- });
202
- }
203
- if (framework === "catalyst") {
204
- const openNextOutDir = join3(coreDir, ".open-next");
205
- const bigcommerceDistDir = join3(coreDir, ".bigcommerce", "dist");
206
- const projectUuid = options.projectUuid ?? config2.get("projectUuid");
207
- if (!projectUuid) {
208
- throw new Error(
209
- "Project UUID is required. Please run `catalyst project create` or `catalyst project link` or this command again with --project-uuid <uuid>."
210
- );
211
- }
212
- const wranglerConfig = getWranglerConfig(projectUuid, "PLACEHOLDER_KV_ID");
213
- consola.start("Copying templates...");
214
- await copyFile(
215
- join3(getModuleCliPath(), "templates", "open-next.config.ts"),
216
- join3(coreDir, ".bigcommerce", "open-next.config.ts")
217
- );
218
- await writeFile(
219
- join3(coreDir, ".bigcommerce", "wrangler.jsonc"),
220
- JSON.stringify(wranglerConfig, null, 2)
221
- );
222
- consola.success("Templates copied");
223
- consola.start("Building project...");
224
- await execa(
225
- "pnpm",
226
- [
227
- "exec",
228
- "opennextjs-cloudflare",
229
- "build",
230
- "--skipWranglerConfigCheck",
231
- "--openNextConfigPath",
232
- join3(coreDir, ".bigcommerce", "open-next.config.ts")
233
- ],
234
- {
235
- stdout: ["pipe", "inherit"],
236
- cwd: coreDir
237
- }
238
- );
239
- await execa(
240
- "pnpm",
241
- [
242
- "dlx",
243
- `wrangler@${WRANGLER_VERSION}`,
244
- "deploy",
245
- "--config",
246
- join3(coreDir, ".bigcommerce", "wrangler.jsonc"),
247
- "--keep-vars",
248
- "--outdir",
249
- bigcommerceDistDir,
250
- "--dry-run"
251
- ],
252
- {
253
- stdout: ["pipe", "inherit"],
254
- cwd: coreDir
255
- }
256
- );
257
- consola.success("Project built");
258
- await cp(join3(openNextOutDir, "assets"), join3(bigcommerceDistDir, "assets"), {
259
- recursive: true,
260
- force: true
261
- });
262
- }
263
- } catch (error) {
264
- consola.error(error);
265
- process.exit(1);
266
- }
267
- });
268
-
269
- // src/cli/commands/deploy.ts
270
- import AdmZip from "adm-zip";
271
- import { Command as Command2, Option as Option2 } from "commander";
272
- import { access, readdir, readFile } from "fs/promises";
273
- import { join as join4 } from "path";
274
- import yoctoSpinner from "yocto-spinner";
275
- import { z } from "zod";
276
-
277
97
  // src/cli/lib/telemetry.ts
278
- import { Analytics } from "@segment/analytics-node";
279
- import { randomBytes } from "crypto";
280
98
  var TELEMETRY_KEY_ENABLED = "telemetry.enabled";
281
99
  var TELEMETRY_KEY_ID = `telemetry.anonymousId`;
282
100
  var Telemetry = class {
283
101
  constructor() {
102
+ this.commandName = "unknown";
284
103
  this.projectName = "catalyst-cli";
285
104
  this.projectVersion = package_default.version;
286
105
  this.setEnabled = (_enabled) => {
@@ -289,11 +108,15 @@ var Telemetry = class {
289
108
  };
290
109
  this.CATALYST_TELEMETRY_DISABLED = process.env.CATALYST_TELEMETRY_DISABLED;
291
110
  this.projectConfig = getProjectConfig();
292
- this.sessionId = randomBytes(32).toString("hex");
111
+ this.sessionId = randomUUID();
112
+ this.startTime = Date.now();
293
113
  this.analytics = new Analytics({
294
- writeKey: "OCkxLj3KTc1N3ebEbnFBqbhxfE3tVb3Z"
114
+ writeKey: "not-a-valid-segment-write-key"
295
115
  });
296
116
  }
117
+ durationMs() {
118
+ return Date.now() - this.startTime;
119
+ }
297
120
  async track(eventName, payload) {
298
121
  if (!this.isEnabled()) {
299
122
  return Promise.resolve(void 0);
@@ -303,7 +126,11 @@ var Telemetry = class {
303
126
  anonymousId: this.getAnonymousId(),
304
127
  properties: {
305
128
  ...payload,
306
- sessionId: this.sessionId
129
+ sessionId: this.sessionId,
130
+ nodeVersion: process.version,
131
+ platform: process.platform,
132
+ arch: process.arch,
133
+ cliVersion: package_default.version
307
134
  },
308
135
  context: {
309
136
  app: {
@@ -344,91 +171,595 @@ var Telemetry = class {
344
171
  return generated;
345
172
  }
346
173
  };
174
+ var telemetryInstance;
175
+ function getTelemetry() {
176
+ telemetryInstance ?? (telemetryInstance = new Telemetry());
177
+ return telemetryInstance;
178
+ }
347
179
 
348
- // src/cli/commands/deploy.ts
349
- var telemetry = new Telemetry();
350
- var stepsEnum = z.enum([
351
- "initializing",
352
- "downloading",
353
- "unzipping",
354
- "processing",
355
- "deploying",
356
- "finalizing",
357
- "complete"
358
- ]);
359
- var STEPS = {
360
- initializing: "Initializing...",
361
- downloading: "Downloading...",
362
- unzipping: "Unzipping...",
363
- processing: "Processing...",
364
- deploying: "Deploying...",
365
- finalizing: "Finalizing...",
366
- complete: "Complete"
367
- };
368
- var UploadSignatureSchema = z.object({
369
- data: z.object({
370
- upload_url: z.url(),
371
- upload_uuid: z.string()
372
- })
180
+ // src/cli/program.ts
181
+ import { Option as Option8 } from "@commander-js/extra-typings";
182
+ import { Command as Command9 } from "commander";
183
+ import { colorize as colorize4 } from "consola/utils";
184
+ import { config } from "dotenv";
185
+ import { resolve } from "path";
186
+
187
+ // src/cli/commands/auth.ts
188
+ import { Command, Option } from "commander";
189
+ import { colorize } from "consola/utils";
190
+ import open from "open";
191
+ import yoctoSpinner from "yocto-spinner";
192
+ import { z as z3 } from "zod";
193
+
194
+ // src/cli/lib/auth.ts
195
+ import { z } from "zod";
196
+ var DEVICE_OAUTH_CLIENT_ID = "s1q4io7mah2lm1i6uwp9yl1eit80n3b";
197
+ var DEVICE_OAUTH_SCOPES = [
198
+ "store_v2_information",
199
+ "store_infrastructure_deployments_manage",
200
+ "store_infrastructure_logs_read_only",
201
+ "store_infrastructure_projects_manage"
202
+ ].join(" ");
203
+ var DEFAULT_LOGIN_URL = "https://login.bigcommerce.com";
204
+ var DeviceCodeResponseSchema = z.object({
205
+ device_code: z.string(),
206
+ user_code: z.string(),
207
+ verification_uri: z.string(),
208
+ expires_in: z.number(),
209
+ interval: z.number()
373
210
  });
374
- var CreateDeploymentSchema = z.object({
375
- data: z.object({
376
- deployment_uuid: z.uuid()
377
- })
211
+ var DeviceCodeSuccessSchema = z.object({
212
+ access_token: z.string(),
213
+ store_hash: z.string(),
214
+ context: z.string(),
215
+ api_uri: z.string()
378
216
  });
379
- var DeploymentStatusSchema = z.object({
380
- deployment_uuid: z.uuid(),
381
- deployment_status: z.enum(["queued", "in_progress", "failed", "completed"]),
382
- event: z.object({
383
- step: stepsEnum,
384
- progress: z.number()
385
- }).nullable(),
386
- error: z.object({
387
- code: z.number()
388
- }).optional()
217
+ async function requestDeviceCode(loginUrl) {
218
+ const response = await fetch(`${loginUrl}/device/token`, {
219
+ method: "POST",
220
+ headers: { "Content-Type": "application/json" },
221
+ body: JSON.stringify({
222
+ client_id: DEVICE_OAUTH_CLIENT_ID,
223
+ scopes: DEVICE_OAUTH_SCOPES
224
+ })
225
+ });
226
+ if (!response.ok) {
227
+ throw new Error(`Failed to request device code: ${response.status} ${response.statusText}`);
228
+ }
229
+ const res = await response.json();
230
+ return DeviceCodeResponseSchema.parse(res);
231
+ }
232
+ async function pollDeviceToken(loginUrl, deviceCode) {
233
+ const response = await fetch(`${loginUrl}/device/token`, {
234
+ method: "POST",
235
+ headers: { "Content-Type": "application/json" },
236
+ body: JSON.stringify({
237
+ device_code: deviceCode,
238
+ client_id: DEVICE_OAUTH_CLIENT_ID
239
+ })
240
+ });
241
+ if (response.status !== 200) {
242
+ return null;
243
+ }
244
+ const res = await response.json();
245
+ return DeviceCodeSuccessSchema.parse(res);
246
+ }
247
+ async function waitForDeviceToken(loginUrl, deviceCode, interval) {
248
+ const credentials = await pollDeviceToken(loginUrl, deviceCode);
249
+ if (credentials) {
250
+ return credentials;
251
+ }
252
+ await new Promise((resolve2) => {
253
+ setTimeout(resolve2, interval * 1e3);
254
+ });
255
+ return waitForDeviceToken(loginUrl, deviceCode, interval);
256
+ }
257
+
258
+ // src/cli/lib/project.ts
259
+ import { z as z2 } from "zod";
260
+ var fetchProjectsSchema = z2.object({
261
+ data: z2.array(
262
+ z2.object({
263
+ uuid: z2.string(),
264
+ name: z2.string()
265
+ })
266
+ )
389
267
  });
390
- var generateBundleZip = async () => {
391
- consola.info("Generating bundle...");
392
- const bigcommerceDir = join4(process.cwd(), ".bigcommerce");
393
- const distDir = join4(process.cwd(), ".bigcommerce", "dist");
394
- try {
395
- await access(distDir);
396
- } catch {
397
- throw new Error(`Dist directory not found: ${distDir}`);
268
+ async function fetchProjects(storeHash, accessToken, apiHost) {
269
+ const response = await fetch(
270
+ `https://${apiHost}/stores/${storeHash}/v3/infrastructure/projects`,
271
+ {
272
+ method: "GET",
273
+ headers: {
274
+ "X-Auth-Token": accessToken,
275
+ "X-Correlation-Id": getTelemetry().sessionId
276
+ }
277
+ }
278
+ );
279
+ if (response.status === 403) {
280
+ throw new Error(
281
+ "Infrastructure Projects API not enabled. If you are part of the alpha, contact support@bigcommerce.com to enable it."
282
+ );
398
283
  }
399
- const buildDirContents = await readdir(distDir);
400
- if (buildDirContents.length === 0) {
401
- throw new Error(`Dist directory is empty: ${distDir}`);
284
+ if (!response.ok) {
285
+ throw new Error(`Failed to fetch projects: ${response.statusText}`);
402
286
  }
403
- const outputZip = join4(bigcommerceDir, "bundle.zip");
404
- const zip = new AdmZip();
405
- zip.addLocalFolder(distDir, "output");
406
- zip.writeZip(outputZip);
407
- consola.success(`Bundle created at: ${outputZip}`);
408
- };
409
- var generateUploadSignature = async (storeHash, accessToken, apiHost) => {
410
- consola.info("Generating upload signature...");
287
+ const res = await response.json();
288
+ const { data } = fetchProjectsSchema.parse(res);
289
+ return data;
290
+ }
291
+ var createProjectSchema = z2.object({
292
+ data: z2.object({
293
+ uuid: z2.string(),
294
+ name: z2.string(),
295
+ date_created: z2.coerce.date(),
296
+ date_modified: z2.coerce.date()
297
+ })
298
+ });
299
+ async function createProject(name, storeHash, accessToken, apiHost) {
411
300
  const response = await fetch(
412
- `https://${apiHost}/stores/${storeHash}/v3/infrastructure/deployments/uploads`,
301
+ `https://${apiHost}/stores/${storeHash}/v3/infrastructure/projects`,
413
302
  {
414
303
  method: "POST",
415
304
  headers: {
416
305
  "X-Auth-Token": accessToken,
306
+ Accept: "application/json",
417
307
  "Content-Type": "application/json",
418
- Accept: "application/json"
308
+ "X-Correlation-Id": getTelemetry().sessionId
419
309
  },
420
- body: JSON.stringify({})
310
+ body: JSON.stringify({ name })
421
311
  }
422
312
  );
313
+ if (response.status === 502) {
314
+ throw new Error("Failed to create project, is the name already in use?");
315
+ }
316
+ if (response.status === 403) {
317
+ throw new Error(
318
+ "Infrastructure Projects API not enabled. If you are part of the alpha, contact support@bigcommerce.com to enable it."
319
+ );
320
+ }
321
+ if (response.status === 422) {
322
+ throw new Error(
323
+ "The project name you entered doesn't meet the requirements. It must be 3\u201332 characters long and use only letters, numbers, hyphens (-), underscores (_), and periods (.)"
324
+ );
325
+ }
423
326
  if (!response.ok) {
424
- throw new Error(`Failed to fetch upload signature: ${response.status} ${response.statusText}`);
327
+ throw new Error(`Failed to create project: ${response.statusText}`);
425
328
  }
426
329
  const res = await response.json();
427
- const { data } = UploadSignatureSchema.parse(res);
428
- consola.success("Upload signature generated.");
330
+ const { data } = createProjectSchema.parse(res);
429
331
  return data;
430
- };
431
- var uploadBundleZip = async (uploadUrl) => {
332
+ }
333
+
334
+ // src/cli/commands/auth.ts
335
+ var StoreProfileSchema = z3.object({
336
+ data: z3.object({
337
+ store_name: z3.string()
338
+ })
339
+ });
340
+ async function fetchStoreProfile(storeHash, accessToken, apiHost) {
341
+ const response = await fetch(`https://${apiHost}/stores/${storeHash}/v3/settings/store/profile`, {
342
+ method: "GET",
343
+ headers: {
344
+ "X-Auth-Token": accessToken,
345
+ Accept: "application/json"
346
+ }
347
+ });
348
+ if (!response.ok) {
349
+ throw new Error(`${response.status} ${response.statusText}`);
350
+ }
351
+ const res = await response.json();
352
+ const result = StoreProfileSchema.safeParse(res);
353
+ if (!result.success) {
354
+ throw new Error("Unexpected response from store profile API");
355
+ }
356
+ return result.data.data;
357
+ }
358
+ var whoami = new Command("whoami").description("Verify stored credentials and display store/project info.").addOption(
359
+ new Option(
360
+ "--store-hash <hash>",
361
+ "BigCommerce store hash. Can be found in the URL of your store Control Panel."
362
+ ).env("CATALYST_STORE_HASH")
363
+ ).addOption(
364
+ new Option(
365
+ "--access-token <token>",
366
+ "BigCommerce access token. Can be found after creating a store-level API account."
367
+ ).env("CATALYST_ACCESS_TOKEN")
368
+ ).addOption(
369
+ new Option("--api-host <host>", "BigCommerce API host. The default is api.bigcommerce.com.").env("BIGCOMMERCE_API_HOST").default("api.bigcommerce.com")
370
+ ).action(async (options) => {
371
+ try {
372
+ const config2 = getProjectConfig();
373
+ const storeHash = options.storeHash ?? config2.get("storeHash");
374
+ const accessToken = options.accessToken ?? config2.get("accessToken");
375
+ if (!storeHash || !accessToken) {
376
+ consola.info("Not logged in: no credentials found.");
377
+ consola.info(
378
+ "Run `catalyst auth login`, or provide --store-hash and --access-token flags (or set CATALYST_STORE_HASH and CATALYST_ACCESS_TOKEN environment variables)."
379
+ );
380
+ process.exit(1);
381
+ return;
382
+ }
383
+ const store = await fetchStoreProfile(storeHash, accessToken, options.apiHost);
384
+ const projectUuid = config2.get("projectUuid");
385
+ if (projectUuid) {
386
+ const projects = await fetchProjects(storeHash, accessToken, options.apiHost);
387
+ const linkedProject = projects.find((p) => p.uuid === projectUuid);
388
+ if (linkedProject) {
389
+ consola.info(
390
+ `Logged in to ${store.store_name} (${storeHash}), connected to project ${linkedProject.name} (${projectUuid})`
391
+ );
392
+ } else {
393
+ consola.info(
394
+ `Logged in to ${store.store_name} (${storeHash}), project ${projectUuid} not found`
395
+ );
396
+ }
397
+ } else {
398
+ consola.info(`Logged in to ${store.store_name} (${storeHash})`);
399
+ }
400
+ process.exit(0);
401
+ } catch (error) {
402
+ const message = error instanceof Error ? error.message : String(error);
403
+ if (message.includes("401") || message.includes("403")) {
404
+ consola.error(`Not logged in: invalid credentials (${message})`);
405
+ } else {
406
+ consola.error(`Failed to verify credentials: ${message}`);
407
+ }
408
+ process.exit(1);
409
+ }
410
+ });
411
+ var login = new Command("login").description("Authenticate via browser using the OAuth device code flow.").addOption(
412
+ new Option(
413
+ "--store-hash <hash>",
414
+ "BigCommerce store hash. Can be found in the URL of your store Control Panel."
415
+ ).env("CATALYST_STORE_HASH")
416
+ ).addOption(
417
+ new Option(
418
+ "--access-token <token>",
419
+ "BigCommerce access token. Can be found after creating a store-level API account."
420
+ ).env("CATALYST_ACCESS_TOKEN")
421
+ ).addOption(
422
+ new Option("--login-url <url>", "BigCommerce login URL.").env("BIGCOMMERCE_LOGIN_URL").default(DEFAULT_LOGIN_URL)
423
+ ).action(async (options) => {
424
+ try {
425
+ const config2 = getProjectConfig();
426
+ const storeHash = options.storeHash ?? config2.get("storeHash");
427
+ const accessToken = options.accessToken ?? config2.get("accessToken");
428
+ if (storeHash && accessToken) {
429
+ consola.info(`Already logged in to store ${storeHash}.`);
430
+ consola.info("Run `catalyst auth logout` first to re-authenticate.");
431
+ process.exit(0);
432
+ return;
433
+ }
434
+ const deviceCode = await requestDeviceCode(options.loginUrl);
435
+ consola.info(
436
+ `${colorize("yellow", "Your one-time code:")} ${colorize("bold", deviceCode.user_code)}`
437
+ );
438
+ try {
439
+ await open(deviceCode.verification_uri);
440
+ consola.info(`Opened ${deviceCode.verification_uri} in your browser.`);
441
+ } catch {
442
+ consola.info(
443
+ `Open ${deviceCode.verification_uri} in your browser and enter the code above.`
444
+ );
445
+ }
446
+ const spinner = yoctoSpinner().start("Waiting for authentication...");
447
+ const credentials = await waitForDeviceToken(
448
+ options.loginUrl,
449
+ deviceCode.device_code,
450
+ deviceCode.interval
451
+ );
452
+ spinner.success("Authentication complete.");
453
+ config2.set("storeHash", credentials.store_hash);
454
+ config2.set("accessToken", credentials.access_token);
455
+ consola.success(`Logged in to store ${credentials.store_hash}.`);
456
+ process.exit(0);
457
+ } catch (error) {
458
+ const message = error instanceof Error ? error.message : String(error);
459
+ consola.error(`Login failed: ${message}`);
460
+ process.exit(1);
461
+ }
462
+ });
463
+ var logout = new Command("logout").description("Remove stored credentials for the current project.").action(() => {
464
+ try {
465
+ const config2 = getProjectConfig();
466
+ const storeHash = config2.get("storeHash");
467
+ const accessToken = config2.get("accessToken");
468
+ if (!storeHash && !accessToken) {
469
+ consola.info("Not logged in: no credentials found.");
470
+ process.exit(0);
471
+ return;
472
+ }
473
+ config2.delete("storeHash");
474
+ config2.delete("accessToken");
475
+ consola.success(`Logged out from store ${storeHash ?? "unknown"}.`);
476
+ process.exit(0);
477
+ } catch (error) {
478
+ const message = error instanceof Error ? error.message : String(error);
479
+ consola.error(`Logout failed: ${message}`);
480
+ process.exit(1);
481
+ }
482
+ });
483
+ var auth = new Command("auth").description("Manage authentication for the BigCommerce CLI.").addCommand(whoami).addCommand(login).addCommand(logout);
484
+
485
+ // src/cli/commands/build.ts
486
+ import { Command as Command2, Option as Option2 } from "commander";
487
+ import { execa } from "execa";
488
+ import { copyFile, cp, writeFile } from "fs/promises";
489
+ import { join as join3 } from "path";
490
+
491
+ // src/cli/lib/get-module-cli-path.ts
492
+ import { dirname, join as join2 } from "path";
493
+ import { fileURLToPath } from "url";
494
+ function getModuleCliPath() {
495
+ const __filename = fileURLToPath(import.meta.url);
496
+ const __dirname = dirname(__filename);
497
+ return join2(__dirname, "..");
498
+ }
499
+
500
+ // src/cli/lib/wrangler-config.ts
501
+ function getWranglerConfig(projectUuid) {
502
+ return {
503
+ $schema: "node_modules/wrangler/config-schema.json",
504
+ main: "../.open-next/worker.js",
505
+ name: `project-${projectUuid}`,
506
+ compatibility_date: "2025-09-15",
507
+ compatibility_flags: ["nodejs_compat", "global_fetch_strictly_public"],
508
+ observability: {
509
+ enabled: true,
510
+ head_sampling_rate: 0.05,
511
+ logs: {
512
+ enabled: true,
513
+ head_sampling_rate: 1,
514
+ invocation_logs: false
515
+ }
516
+ },
517
+ assets: {
518
+ directory: "../.open-next/assets",
519
+ binding: "ASSETS"
520
+ },
521
+ services: [
522
+ {
523
+ binding: "WORKER_SELF_REFERENCE",
524
+ service: `project-${projectUuid}`
525
+ }
526
+ ],
527
+ r2_buckets: [
528
+ {
529
+ binding: "NEXT_INC_CACHE_R2_BUCKET",
530
+ bucket_name: `project-${projectUuid}`
531
+ }
532
+ ],
533
+ durable_objects: {
534
+ bindings: [
535
+ {
536
+ name: "NEXT_CACHE_DO_QUEUE",
537
+ class_name: "DOQueueHandler"
538
+ },
539
+ {
540
+ name: "NEXT_TAG_CACHE_DO_SHARDED",
541
+ class_name: "DOShardedTagCache"
542
+ },
543
+ {
544
+ name: "NEXT_CACHE_DO_PURGE",
545
+ class_name: "BucketCachePurge"
546
+ }
547
+ ]
548
+ },
549
+ migrations: [
550
+ {
551
+ tag: "v1",
552
+ new_sqlite_classes: ["DOQueueHandler", "DOShardedTagCache", "BucketCachePurge"]
553
+ }
554
+ ]
555
+ };
556
+ }
557
+
558
+ // src/cli/commands/build.ts
559
+ var WRANGLER_VERSION = "4.24.3";
560
+ async function buildCatalystProject(projectUuid) {
561
+ const coreDir = process.cwd();
562
+ const openNextOutDir = join3(coreDir, ".open-next");
563
+ const bigcommerceDistDir = join3(coreDir, ".bigcommerce", "dist");
564
+ const wranglerConfig = getWranglerConfig(projectUuid);
565
+ consola.start("Copying templates...");
566
+ await copyFile(
567
+ join3(getModuleCliPath(), "templates", "open-next.config.ts"),
568
+ join3(coreDir, ".bigcommerce", "open-next.config.ts")
569
+ );
570
+ await writeFile(
571
+ join3(coreDir, ".bigcommerce", "wrangler.jsonc"),
572
+ JSON.stringify(wranglerConfig, null, 2)
573
+ );
574
+ consola.success("Templates copied");
575
+ consola.start("Building project...");
576
+ await execa(
577
+ "pnpm",
578
+ [
579
+ "exec",
580
+ "opennextjs-cloudflare",
581
+ "build",
582
+ "--skipWranglerConfigCheck",
583
+ "--openNextConfigPath",
584
+ join3(coreDir, ".bigcommerce", "open-next.config.ts")
585
+ ],
586
+ {
587
+ stdout: ["pipe", "inherit"],
588
+ cwd: coreDir
589
+ }
590
+ );
591
+ await execa(
592
+ "pnpm",
593
+ [
594
+ "dlx",
595
+ `wrangler@${WRANGLER_VERSION}`,
596
+ "deploy",
597
+ "--config",
598
+ join3(coreDir, ".bigcommerce", "wrangler.jsonc"),
599
+ "--keep-vars",
600
+ "--outdir",
601
+ bigcommerceDistDir,
602
+ "--dry-run"
603
+ ],
604
+ {
605
+ stdout: ["pipe", "inherit"],
606
+ cwd: coreDir
607
+ }
608
+ );
609
+ consola.success("Project built");
610
+ await cp(join3(openNextOutDir, "assets"), join3(bigcommerceDistDir, "assets"), {
611
+ recursive: true,
612
+ force: true
613
+ });
614
+ }
615
+ var build = new Command2("build").addOption(
616
+ new Option2(
617
+ "--project-uuid <uuid>",
618
+ "Project UUID to be included in the deployment configuration."
619
+ ).env("CATALYST_PROJECT_UUID")
620
+ ).action(async (options) => {
621
+ const config2 = getProjectConfig();
622
+ const projectUuid = options.projectUuid ?? config2.get("projectUuid");
623
+ if (!projectUuid) {
624
+ throw new Error(
625
+ "Project UUID is required. Please run `catalyst project create` or `catalyst project link` or this command again with --project-uuid <uuid>."
626
+ );
627
+ }
628
+ await buildCatalystProject(projectUuid);
629
+ });
630
+
631
+ // src/cli/commands/deploy.ts
632
+ import AdmZip from "adm-zip";
633
+ import { Command as Command3, Option as Option3 } from "commander";
634
+ import { access, readdir, readFile } from "fs/promises";
635
+ import { join as join4 } from "path";
636
+ import yoctoSpinner2 from "yocto-spinner";
637
+ import { z as z4 } from "zod";
638
+
639
+ // src/cli/lib/deployment-errors.ts
640
+ var ERROR_MESSAGES = {
641
+ 10: "Something went wrong on our end. Please try again. If the issue persists, contact support.",
642
+ 20: "We couldn't retrieve your bundle. This is usually a temporary issue \u2014 please try deploying again. If the problem continues, contact support.",
643
+ 30: "Your bundle could not be extracted. This may mean your build output is too large (max 64 MB compressed / 512 MB uncompressed) or the archive is corrupted. Try reducing your build size or rebuilding your project and deploying again.",
644
+ 40: `There's a problem with your build output. This could be caused by:
645
+ - A worker.js file larger than 40 MB
646
+ - An individual asset file larger than 25 MB
647
+ - More than 1,000 total files in the bundle`,
648
+ 50: "Deployment failed. This is usually a temporary issue \u2014 please try again. If the problem persists, contact support.",
649
+ 60: "Your code was deployed, but we couldn't determine your deployment URL. Please try deploying again. If the issue persists, contact support."
650
+ };
651
+ function getDeploymentErrorMessage(code) {
652
+ return ERROR_MESSAGES[code] ?? `Deployment failed with an unexpected error (code: ${code}). Please try again. If the issue persists, contact support.`;
653
+ }
654
+
655
+ // src/cli/lib/resolve-credentials.ts
656
+ function resolveCredentials(options, config2) {
657
+ const storeHash = options.storeHash ?? config2.get("storeHash");
658
+ const accessToken = options.accessToken ?? config2.get("accessToken");
659
+ if (!storeHash || !accessToken) {
660
+ consola.error("Missing credentials.");
661
+ consola.info(
662
+ "Run `catalyst auth login`, or provide --store-hash and --access-token flags (or set CATALYST_STORE_HASH and CATALYST_ACCESS_TOKEN environment variables)."
663
+ );
664
+ process.exit(1);
665
+ throw new Error("Missing credentials");
666
+ }
667
+ return { storeHash, accessToken };
668
+ }
669
+
670
+ // src/cli/commands/deploy.ts
671
+ var stepsEnum = z4.enum([
672
+ "initializing",
673
+ "downloading",
674
+ "unzipping",
675
+ "processing",
676
+ "deploying",
677
+ "finalizing",
678
+ "complete"
679
+ ]);
680
+ var STEPS = {
681
+ initializing: "Initializing...",
682
+ downloading: "Downloading...",
683
+ unzipping: "Unzipping...",
684
+ processing: "Processing...",
685
+ deploying: "Deploying...",
686
+ finalizing: "Finalizing...",
687
+ complete: "Complete"
688
+ };
689
+ var UploadSignatureSchema = z4.object({
690
+ data: z4.object({
691
+ upload_url: z4.url(),
692
+ upload_uuid: z4.string()
693
+ })
694
+ });
695
+ var CreateDeploymentSchema = z4.object({
696
+ data: z4.object({
697
+ deployment_uuid: z4.uuid()
698
+ })
699
+ });
700
+ var ProjectSchema = z4.object({
701
+ data: z4.array(
702
+ z4.object({
703
+ uuid: z4.uuid(),
704
+ name: z4.string()
705
+ })
706
+ )
707
+ });
708
+ var DeploymentStatusSchema = z4.object({
709
+ deployment_uuid: z4.uuid(),
710
+ deployment_status: z4.enum(["queued", "in_progress", "failed", "completed"]),
711
+ event: z4.object({
712
+ step: stepsEnum,
713
+ progress: z4.number()
714
+ }).nullable(),
715
+ deployment_url: z4.string().nullable(),
716
+ error: z4.object({
717
+ code: z4.number()
718
+ }).optional()
719
+ });
720
+ var generateBundleZip = async () => {
721
+ consola.info("Generating bundle...");
722
+ const bigcommerceDir = join4(process.cwd(), ".bigcommerce");
723
+ const distDir = join4(process.cwd(), ".bigcommerce", "dist");
724
+ try {
725
+ await access(distDir);
726
+ } catch {
727
+ throw new Error(`Dist directory not found: ${distDir}`);
728
+ }
729
+ const buildDirContents = await readdir(distDir);
730
+ if (buildDirContents.length === 0) {
731
+ throw new Error(`Dist directory is empty: ${distDir}`);
732
+ }
733
+ const outputZip = join4(bigcommerceDir, "bundle.zip");
734
+ const zip = new AdmZip();
735
+ zip.addLocalFolder(distDir, "output");
736
+ zip.writeZip(outputZip);
737
+ consola.success(`Bundle created at: ${outputZip}`);
738
+ };
739
+ var generateUploadSignature = async (storeHash, accessToken, apiHost) => {
740
+ consola.info("Generating upload signature...");
741
+ const response = await fetch(
742
+ `https://${apiHost}/stores/${storeHash}/v3/infrastructure/deployments/uploads`,
743
+ {
744
+ method: "POST",
745
+ headers: {
746
+ "X-Auth-Token": accessToken,
747
+ "Content-Type": "application/json",
748
+ Accept: "application/json",
749
+ "X-Correlation-Id": getTelemetry().sessionId
750
+ },
751
+ body: JSON.stringify({})
752
+ }
753
+ );
754
+ if (!response.ok) {
755
+ throw new Error(`Failed to fetch upload signature: ${response.status} ${response.statusText}`);
756
+ }
757
+ const res = await response.json();
758
+ const { data } = UploadSignatureSchema.parse(res);
759
+ consola.success("Upload signature generated.");
760
+ return data;
761
+ };
762
+ var uploadBundleZip = async (uploadUrl) => {
432
763
  consola.info("Uploading bundle...");
433
764
  const zipPath = join4(process.cwd(), ".bigcommerce", "bundle.zip");
434
765
  const fileBuffer = await readFile(zipPath);
@@ -467,7 +798,8 @@ var createDeployment = async (projectUuid, uploadUuid, storeHash, accessToken, a
467
798
  headers: {
468
799
  "X-Auth-Token": accessToken,
469
800
  "Content-Type": "application/json",
470
- Accept: "application/json"
801
+ Accept: "application/json",
802
+ "X-Correlation-Id": getTelemetry().sessionId
471
803
  },
472
804
  body: JSON.stringify({
473
805
  project_uuid: projectUuid,
@@ -486,9 +818,260 @@ var createDeployment = async (projectUuid, uploadUuid, storeHash, accessToken, a
486
818
  };
487
819
  var getDeploymentStatus = async (deploymentUuid, storeHash, accessToken, apiHost) => {
488
820
  consola.info("Fetching deployment status...");
489
- const spinner = yoctoSpinner().start("Fetching...");
821
+ const spinner = yoctoSpinner2().start("Fetching...");
822
+ const response = await fetch(
823
+ `https://${apiHost}/stores/${storeHash}/v3/infrastructure/deployments/${deploymentUuid}/events`,
824
+ {
825
+ method: "GET",
826
+ headers: {
827
+ "X-Auth-Token": accessToken,
828
+ Accept: "text/event-stream",
829
+ Connection: "keep-alive",
830
+ "X-Correlation-Id": getTelemetry().sessionId
831
+ }
832
+ }
833
+ );
834
+ if (!response.ok) {
835
+ throw new Error(`Failed to open event stream: ${response.status} ${response.statusText}`);
836
+ }
837
+ const reader = response.body?.getReader();
838
+ if (!reader) {
839
+ throw new Error("Failed to read event stream.");
840
+ }
841
+ const decoder = new TextDecoder();
842
+ let done = false;
843
+ let deploymentUrl;
844
+ while (!done) {
845
+ const { value, done: streamDone } = await reader.read();
846
+ let json;
847
+ if (value) {
848
+ const chunk = decoder.decode(value, { stream: true }).trim();
849
+ const split = chunk.split("\n\n").map((s) => s.replace("data:", "").trim()).filter(Boolean);
850
+ split.forEach((event) => {
851
+ try {
852
+ json = JSON.parse(event);
853
+ } catch (error) {
854
+ consola.warn(`Failed to parse event, dropping from stream. Event: ${event}`, error);
855
+ return;
856
+ }
857
+ const data = DeploymentStatusSchema.parse(json);
858
+ if (data.error) {
859
+ throw new Error(
860
+ `Deployment failed (error code ${data.error.code}): ${getDeploymentErrorMessage(data.error.code)}`
861
+ );
862
+ }
863
+ if (data.event && STEPS[data.event.step] !== spinner.text) {
864
+ spinner.text = STEPS[data.event.step];
865
+ }
866
+ if (data.deployment_url) {
867
+ console.log(data.deployment_url);
868
+ deploymentUrl = data.deployment_url;
869
+ }
870
+ });
871
+ }
872
+ done = streamDone;
873
+ }
874
+ spinner.success("Deployment completed successfully.\n");
875
+ if (deploymentUrl) {
876
+ consola.success(`View your deployment at: ${deploymentUrl}`);
877
+ }
878
+ };
879
+ var deploy = new Command3("deploy").description("Deploy your application to Cloudflare.").addOption(
880
+ new Option3(
881
+ "--store-hash <hash>",
882
+ "BigCommerce store hash. Can be found in the URL of your store Control Panel. Read from .bigcommerce/project.json when not provided."
883
+ ).env("CATALYST_STORE_HASH")
884
+ ).addOption(
885
+ new Option3(
886
+ "--access-token <token>",
887
+ "BigCommerce access token. Can be found after creating a store-level API account. Read from .bigcommerce/project.json when not provided."
888
+ ).env("CATALYST_ACCESS_TOKEN")
889
+ ).addOption(
890
+ new Option3("--api-host <host>", "BigCommerce API host. The default is api.bigcommerce.com.").env("BIGCOMMERCE_API_HOST").default("api.bigcommerce.com")
891
+ ).addOption(
892
+ new Option3(
893
+ "--project-uuid <uuid>",
894
+ "BigCommerce intrastructure project UUID. Can be found via the BigCommerce API (GET /v3/infrastructure/projects)."
895
+ ).env("CATALYST_PROJECT_UUID")
896
+ ).addOption(
897
+ new Option3(
898
+ "--secret <value>",
899
+ "Secret to set for the deployment (repeatable). Format: --secret KEY=VALUE"
900
+ ).argParser((value, previous = []) => {
901
+ return previous.concat([value]);
902
+ })
903
+ ).option("--dry-run", "Run the command to generate the bundle without uploading or deploying.").option(
904
+ "--prebuilt",
905
+ "Skip the build step. Requires .bigcommerce/dist/ to already contain build output."
906
+ ).action(async (options) => {
907
+ const config2 = getProjectConfig();
908
+ const { storeHash, accessToken } = resolveCredentials(options, config2);
909
+ const telemetry3 = getTelemetry();
910
+ const projectUuid = options.projectUuid ?? config2.get("projectUuid");
911
+ if (!projectUuid) {
912
+ throw new Error(
913
+ "Project UUID is required. Please run either `catalyst project link` or `catalyst project create` or this command again with --project-uuid <uuid>."
914
+ );
915
+ }
916
+ await telemetry3.identify(storeHash);
917
+ if (options.prebuilt) {
918
+ const distDir = join4(process.cwd(), ".bigcommerce", "dist");
919
+ try {
920
+ await access(distDir);
921
+ } catch {
922
+ throw new Error(
923
+ "No build output found at .bigcommerce/dist/. Run `catalyst build` first or remove `--prebuilt` to build automatically."
924
+ );
925
+ }
926
+ const contents = await readdir(distDir);
927
+ if (contents.length === 0) {
928
+ throw new Error(
929
+ "No build output found at .bigcommerce/dist/. Run `catalyst build` first or remove `--prebuilt` to build automatically."
930
+ );
931
+ }
932
+ consola.info("Using existing build output (--prebuilt).");
933
+ } else {
934
+ await buildCatalystProject(projectUuid);
935
+ }
936
+ await generateBundleZip();
937
+ if (options.dryRun) {
938
+ consola.info("Dry run enabled \u2014 skipping upload and deployment steps.");
939
+ consola.info("Next steps (skipped):");
940
+ consola.info("- Generate upload signature");
941
+ consola.info("- Upload bundle.zip");
942
+ consola.info("- Create deployment");
943
+ process.exit(0);
944
+ }
945
+ const uploadSignature = await generateUploadSignature(storeHash, accessToken, options.apiHost);
946
+ await uploadBundleZip(uploadSignature.upload_url);
947
+ const environmentVariables = parseEnvironmentVariables(options.secret);
948
+ const { deployment_uuid: deploymentUuid } = await createDeployment(
949
+ projectUuid,
950
+ uploadSignature.upload_uuid,
951
+ storeHash,
952
+ accessToken,
953
+ options.apiHost,
954
+ environmentVariables
955
+ );
956
+ await getDeploymentStatus(deploymentUuid, storeHash, accessToken, options.apiHost);
957
+ });
958
+
959
+ // src/cli/commands/logs.ts
960
+ import { Command as Command4, Option as Option5 } from "commander";
961
+ import { colorize as colorize2 } from "consola/utils";
962
+ import { z as z5 } from "zod";
963
+
964
+ // src/cli/lib/shared-options.ts
965
+ import { Option as Option4 } from "commander";
966
+ var storeHashOption = () => new Option4(
967
+ "--store-hash <hash>",
968
+ "BigCommerce store hash. Can be found in the URL of your store Control Panel."
969
+ ).env("BIGCOMMERCE_STORE_HASH");
970
+ var accessTokenOption = () => new Option4(
971
+ "--access-token <token>",
972
+ "BigCommerce access token. Can be found after creating a store-level API account."
973
+ ).env("BIGCOMMERCE_ACCESS_TOKEN");
974
+ var apiHostOption = () => new Option4("--api-host <host>", "BigCommerce API host. The default is api.bigcommerce.com.").env("BIGCOMMERCE_API_HOST").default("api.bigcommerce.com");
975
+ var projectUuidOption = () => new Option4(
976
+ "--project-uuid <uuid>",
977
+ "BigCommerce infrastructure project UUID. Can be found via the BigCommerce API (GET /v3/infrastructure/projects)."
978
+ ).env("BIGCOMMERCE_PROJECT_UUID");
979
+ var resolveProjectUuid = (options) => {
980
+ const config2 = getProjectConfig();
981
+ const projectUuid = options.projectUuid ?? config2.get("projectUuid");
982
+ if (!projectUuid) {
983
+ throw new Error(
984
+ "Project UUID is required. Please run either `catalyst project link` or `catalyst project create` or this command again with --project-uuid <uuid>."
985
+ );
986
+ }
987
+ return projectUuid;
988
+ };
989
+
990
+ // src/cli/commands/logs.ts
991
+ var telemetry = new Telemetry();
992
+ var DEFAULT_CONNECTION_TTL_MS = 1 * 60 * 1e3;
993
+ var MAX_RETRIES = 5;
994
+ var isFatalStatusCode = (status) => status >= 400 && status < 500;
995
+ var LEVEL_COLORS = {
996
+ INFO: "green",
997
+ WARN: "yellow",
998
+ ERROR: "red",
999
+ DEBUG: "gray"
1000
+ };
1001
+ var LogEventSchema = z5.object({
1002
+ uuid: z5.string(),
1003
+ project_uuid: z5.string(),
1004
+ request: z5.object({
1005
+ method: z5.string(),
1006
+ url: z5.string(),
1007
+ status_code: z5.number()
1008
+ }),
1009
+ logs: z5.array(
1010
+ z5.object({
1011
+ timestamp: z5.string(),
1012
+ level: z5.string(),
1013
+ messages: z5.array(z5.unknown())
1014
+ })
1015
+ ),
1016
+ exceptions: z5.array(z5.unknown()),
1017
+ timestamp: z5.string()
1018
+ }).loose();
1019
+ var StreamError = class extends Error {
1020
+ constructor(message, fatal) {
1021
+ super(message);
1022
+ this.fatal = fatal;
1023
+ }
1024
+ };
1025
+ var formatMessages = (messages) => messages.map((m) => typeof m === "string" ? m : JSON.stringify(m)).join(" ");
1026
+ var formatLogEvent = (event, format) => {
1027
+ const { request, logs: logEntries, exceptions } = event;
1028
+ logEntries.forEach((entry) => {
1029
+ const msg = formatMessages(entry.messages);
1030
+ const level = entry.level.toUpperCase();
1031
+ const coloredLevel = colorize2(LEVEL_COLORS[level] ?? "white", level);
1032
+ switch (format) {
1033
+ case "short":
1034
+ consola.log(msg);
1035
+ break;
1036
+ case "request":
1037
+ consola.log(
1038
+ `[${entry.timestamp}] [${coloredLevel}] ${request.method} ${request.url} (${request.status_code}) ${msg}`
1039
+ );
1040
+ break;
1041
+ default:
1042
+ consola.log(`[${entry.timestamp}] [${coloredLevel}] ${msg}`);
1043
+ break;
1044
+ }
1045
+ });
1046
+ exceptions.forEach((exception) => {
1047
+ consola.error(`[${event.timestamp}] EXCEPTION`, exception);
1048
+ });
1049
+ };
1050
+ var parseSSEEvent = (raw) => {
1051
+ const joined = raw.split("\n").flatMap((line) => line.startsWith("data:") ? [line.slice(5).trim()] : []).join("\n");
1052
+ return joined.length > 0 ? joined : null;
1053
+ };
1054
+ var processLogEvent = (event, format) => {
1055
+ if (format === "json") {
1056
+ process.stdout.write(`${event}
1057
+ `);
1058
+ return;
1059
+ }
1060
+ try {
1061
+ const parsed = JSON.parse(event);
1062
+ const logEvent = LogEventSchema.parse(parsed);
1063
+ if (format === "pretty") {
1064
+ consola.log(JSON.stringify(logEvent, null, 2));
1065
+ } else {
1066
+ formatLogEvent(logEvent, format);
1067
+ }
1068
+ } catch {
1069
+ consola.warn(`Failed to parse log event: ${event}`);
1070
+ }
1071
+ };
1072
+ var openLogStream = async (projectUuid, storeHash, accessToken, apiHost) => {
490
1073
  const response = await fetch(
491
- `https://${apiHost}/stores/${storeHash}/v3/infrastructure/deployments/${deploymentUuid}/events`,
1074
+ `https://${apiHost}/stores/${storeHash}/v3/infrastructure/logs/${projectUuid}/tail`,
492
1075
  {
493
1076
  method: "GET",
494
1077
  headers: {
@@ -499,443 +1082,263 @@ var getDeploymentStatus = async (deploymentUuid, storeHash, accessToken, apiHost
499
1082
  }
500
1083
  );
501
1084
  if (!response.ok) {
502
- throw new Error(`Failed to open event stream: ${response.status} ${response.statusText}`);
1085
+ throw new StreamError(
1086
+ `Failed to open log stream: ${response.status} ${response.statusText}`,
1087
+ isFatalStatusCode(response.status)
1088
+ );
503
1089
  }
504
1090
  const reader = response.body?.getReader();
505
1091
  if (!reader) {
506
- throw new Error("Failed to read event stream.");
1092
+ throw new StreamError("Failed to read log stream.", true);
507
1093
  }
508
- const decoder = new TextDecoder();
509
- let done = false;
510
- while (!done) {
511
- const { value, done: streamDone } = await reader.read();
512
- let json;
513
- if (value) {
514
- const chunk = decoder.decode(value, { stream: true }).trim();
515
- const split = chunk.split("\n\n").map((s) => s.replace("data:", "").trim()).filter(Boolean);
516
- split.forEach((event) => {
517
- try {
518
- json = JSON.parse(event);
519
- } catch (error) {
520
- consola.warn(`Failed to parse event, dropping from stream. Event: ${event}`, error);
521
- return;
1094
+ return reader;
1095
+ };
1096
+ var tailLogs = async (projectUuid, storeHash, accessToken, apiHost, format, connectionTtlMs = DEFAULT_CONNECTION_TTL_MS) => {
1097
+ consola.info("Tailing logs...");
1098
+ let retries = 0;
1099
+ while (true) {
1100
+ try {
1101
+ const reader = await openLogStream(projectUuid, storeHash, accessToken, apiHost);
1102
+ const decoder = new TextDecoder();
1103
+ const connectTime = Date.now();
1104
+ let buffer = "";
1105
+ retries = 0;
1106
+ while (true) {
1107
+ const { value, done: streamDone } = await reader.read();
1108
+ if (value) {
1109
+ buffer += decoder.decode(value, { stream: true });
1110
+ const parts = buffer.split("\n\n");
1111
+ buffer = parts.pop() ?? "";
1112
+ parts.map((raw) => parseSSEEvent(raw)).filter((event) => event !== null).forEach((event) => processLogEvent(event, format));
522
1113
  }
523
- const data = DeploymentStatusSchema.parse(json);
524
- if (data.error) {
525
- throw new Error(`Deployment failed with error code: ${data.error.code}`);
1114
+ if (streamDone || Date.now() - connectTime >= connectionTtlMs) {
1115
+ void reader.cancel();
1116
+ break;
526
1117
  }
527
- if (data.event && STEPS[data.event.step] !== spinner.text) {
528
- spinner.text = STEPS[data.event.step];
1118
+ }
1119
+ } catch (error) {
1120
+ if (error instanceof StreamError && error.fatal) {
1121
+ throw error;
1122
+ }
1123
+ const isServerDisconnect = error instanceof TypeError && error.message === "terminated";
1124
+ if (isServerDisconnect) {
1125
+ consola.warn("Log stream closed by server, reconnecting...");
1126
+ } else {
1127
+ retries += 1;
1128
+ if (retries >= MAX_RETRIES) {
1129
+ throw new Error(`Failed to connect to log stream after ${MAX_RETRIES} retries.`);
529
1130
  }
530
- });
1131
+ consola.warn(
1132
+ `Log stream disconnected, reconnecting (attempt ${retries}/${MAX_RETRIES})...`,
1133
+ error
1134
+ );
1135
+ }
531
1136
  }
532
- done = streamDone;
533
1137
  }
534
- spinner.success("Deployment completed successfully.");
535
1138
  };
536
- var deploy = new Command2("deploy").description("Deploy your application to Cloudflare.").addOption(
537
- new Option2(
538
- "--store-hash <hash>",
539
- "BigCommerce store hash. Can be found in the URL of your store Control Panel."
540
- ).env("BIGCOMMERCE_STORE_HASH").makeOptionMandatory()
541
- ).addOption(
542
- new Option2(
543
- "--access-token <token>",
544
- "BigCommerce access token. Can be found after creating a store-level API account."
545
- ).env("BIGCOMMERCE_ACCESS_TOKEN").makeOptionMandatory()
546
- ).addOption(
547
- new Option2("--api-host <host>", "BigCommerce API host. The default is api.bigcommerce.com.").env("BIGCOMMERCE_API_HOST").default("api.bigcommerce.com")
548
- ).addOption(
549
- new Option2(
550
- "--project-uuid <uuid>",
551
- "BigCommerce intrastructure project UUID. Can be found via the BigCommerce API (GET /v3/infrastructure/projects)."
552
- ).env("BIGCOMMERCE_PROJECT_UUID")
553
- ).addOption(
554
- new Option2(
555
- "--secret <secrets...>",
556
- "Secrets to set for the deployment. Format: SECRET_1=FOO SECRET_2=BAR"
557
- )
558
- ).option("--dry-run", "Run the command to generate the bundle without uploading or deploying.").action(async (options) => {
1139
+ var tail = new Command4("tail").description("Tail live logs from your deployed application.").addOption(storeHashOption().makeOptionMandatory()).addOption(accessTokenOption().makeOptionMandatory()).addOption(apiHostOption()).addOption(projectUuidOption()).addOption(
1140
+ new Option5("--format <format>", "Output format for log events.").choices(["json", "pretty", "default", "short", "request"]).default("default")
1141
+ ).action(async (options) => {
559
1142
  try {
560
- const config2 = getProjectConfig();
561
1143
  await telemetry.identify(options.storeHash);
562
- const projectUuid = options.projectUuid ?? config2.get("projectUuid");
563
- if (!projectUuid) {
564
- throw new Error(
565
- "Project UUID is required. Please run either `catalyst project link` or `catalyst project create` or this command again with --project-uuid <uuid>."
566
- );
567
- }
568
- await generateBundleZip();
569
- if (options.dryRun) {
570
- consola.info("Dry run enabled \u2014 skipping upload and deployment steps.");
571
- consola.info("Next steps (skipped):");
572
- consola.info("- Generate upload signature");
573
- consola.info("- Upload bundle.zip");
574
- consola.info("- Create deployment");
575
- process.exit(0);
576
- }
577
- const uploadSignature = await generateUploadSignature(
578
- options.storeHash,
579
- options.accessToken,
580
- options.apiHost
581
- );
582
- await uploadBundleZip(uploadSignature.upload_url);
583
- const environmentVariables = parseEnvironmentVariables(options.secret);
584
- const { deployment_uuid: deploymentUuid } = await createDeployment(
1144
+ const projectUuid = resolveProjectUuid(options);
1145
+ await tailLogs(
585
1146
  projectUuid,
586
- uploadSignature.upload_uuid,
587
1147
  options.storeHash,
588
1148
  options.accessToken,
589
1149
  options.apiHost,
590
- environmentVariables
591
- );
592
- await getDeploymentStatus(
593
- deploymentUuid,
594
- options.storeHash,
595
- options.accessToken,
596
- options.apiHost
1150
+ options.format
597
1151
  );
598
1152
  } catch (error) {
599
1153
  consola.error(error);
600
1154
  process.exit(1);
601
1155
  }
602
1156
  });
603
-
604
- // src/cli/commands/dev.ts
605
- import { Command as Command3 } from "commander";
606
- import { execa as execa2 } from "execa";
607
- import { existsSync as existsSync2 } from "fs";
608
- import { join as join5 } from "path";
609
- var dev = new Command3("dev").description("Start the Catalyst development server.").helpOption(false).allowUnknownOption(true).argument(
610
- "[options...]",
611
- "Next.js `dev` options (see: https://nextjs.org/docs/app/api-reference/cli/next#next-dev-options)"
612
- ).action(async (options) => {
613
- try {
614
- const nextBin = join5("node_modules", ".bin", "next");
615
- if (!existsSync2(nextBin)) {
616
- throw new Error(
617
- `Next.js is not installed in ${process.cwd()}. Are you in a valid Next.js project?`
618
- );
619
- }
620
- await execa2(nextBin, ["dev", ...options], {
621
- stdio: "inherit",
622
- cwd: process.cwd()
623
- });
624
- } catch (error) {
625
- consola.error(error instanceof Error ? error.message : error);
626
- process.exit(1);
627
- }
628
- });
629
-
630
- // src/cli/commands/project.ts
631
- import { Command as Command4, Option as Option3 } from "commander";
632
-
633
- // src/cli/lib/project.ts
634
- import { z as z2 } from "zod";
635
- var fetchProjectsSchema = z2.object({
636
- data: z2.array(
637
- z2.object({
638
- uuid: z2.string(),
639
- name: z2.string()
640
- })
641
- )
642
- });
643
- async function fetchProjects(storeHash, accessToken, apiHost) {
644
- const response = await fetch(
645
- `https://${apiHost}/stores/${storeHash}/v3/infrastructure/projects`,
646
- {
647
- method: "GET",
648
- headers: {
649
- "X-Auth-Token": accessToken
650
- }
651
- }
652
- );
653
- if (response.status === 403) {
654
- throw new Error(
655
- "Infrastructure Projects API not enabled. If you are part of the alpha, contact support@bigcommerce.com to enable it."
656
- );
657
- }
658
- if (!response.ok) {
659
- throw new Error(`Failed to fetch projects: ${response.statusText}`);
660
- }
661
- const res = await response.json();
662
- const { data } = fetchProjectsSchema.parse(res);
663
- return data;
664
- }
665
- var createProjectSchema = z2.object({
666
- data: z2.object({
667
- uuid: z2.string(),
668
- name: z2.string(),
669
- date_created: z2.coerce.date(),
670
- date_modified: z2.coerce.date()
671
- })
1157
+ var query = new Command4("query").description("Query historical logs from your deployed application.").addOption(storeHashOption().makeOptionMandatory()).addOption(accessTokenOption().makeOptionMandatory()).addOption(apiHostOption()).addOption(projectUuidOption()).action((_options) => {
1158
+ consola.error("The query command is not yet implemented.");
1159
+ process.exit(1);
672
1160
  });
673
- async function createProject(name, storeHash, accessToken, apiHost) {
674
- const response = await fetch(
675
- `https://${apiHost}/stores/${storeHash}/v3/infrastructure/projects`,
676
- {
677
- method: "POST",
678
- headers: {
679
- "X-Auth-Token": accessToken,
680
- Accept: "application/json",
681
- "Content-Type": "application/json"
682
- },
683
- body: JSON.stringify({ name })
684
- }
685
- );
686
- if (response.status === 502) {
687
- throw new Error("Failed to create project, is the name already in use?");
688
- }
689
- if (response.status === 403) {
690
- throw new Error(
691
- "Infrastructure Projects API not enabled. If you are part of the alpha, contact support@bigcommerce.com to enable it."
692
- );
693
- }
694
- if (!response.ok) {
695
- throw new Error(`Failed to create project: ${response.statusText}`);
696
- }
697
- const res = await response.json();
698
- const { data } = createProjectSchema.parse(res);
699
- return data;
700
- }
1161
+ var logs = new Command4("logs").description("View logs from your deployed application.").addCommand(tail, { isDefault: true }).addCommand(query);
701
1162
 
702
1163
  // src/cli/commands/project.ts
703
- var telemetry2 = new Telemetry();
704
- var list = new Command4("list").description("List BigCommerce infrastructure projects for your store.").addOption(
705
- new Option3(
1164
+ import { Command as Command5, Option as Option6 } from "commander";
1165
+ var list = new Command5("list").description("List BigCommerce infrastructure projects for your store.").addOption(
1166
+ new Option6(
706
1167
  "--store-hash <hash>",
707
1168
  "BigCommerce store hash. Can be found in the URL of your store Control Panel."
708
- ).env("BIGCOMMERCE_STORE_HASH")
1169
+ ).env("CATALYST_STORE_HASH")
709
1170
  ).addOption(
710
- new Option3(
1171
+ new Option6(
711
1172
  "--access-token <token>",
712
1173
  "BigCommerce access token. Can be found after creating a store-level API account."
713
- ).env("BIGCOMMERCE_ACCESS_TOKEN")
1174
+ ).env("CATALYST_ACCESS_TOKEN")
714
1175
  ).addOption(
715
- new Option3("--api-host <host>", "BigCommerce API host. The default is api.bigcommerce.com.").env("BIGCOMMERCE_API_HOST").default("api.bigcommerce.com")
1176
+ new Option6("--api-host <host>", "BigCommerce API host. The default is api.bigcommerce.com.").env("BIGCOMMERCE_API_HOST").default("api.bigcommerce.com")
716
1177
  ).action(async (options) => {
717
- try {
718
- if (!options.storeHash || !options.accessToken) {
719
- consola.error("Insufficient information to list projects.");
720
- consola.info(
721
- "Provide both --store-hash and --access-token (or set BIGCOMMERCE_STORE_HASH and BIGCOMMERCE_ACCESS_TOKEN)."
722
- );
723
- process.exit(1);
724
- return;
725
- }
726
- await telemetry2.identify(options.storeHash);
727
- consola.start("Fetching projects...");
728
- const projects = await fetchProjects(options.storeHash, options.accessToken, options.apiHost);
729
- consola.success("Projects fetched.");
730
- if (projects.length === 0) {
731
- consola.info("No projects found.");
732
- process.exit(0);
733
- return;
734
- }
735
- projects.forEach((p) => {
736
- consola.log(`${p.name} (${p.uuid})`);
737
- });
1178
+ const config2 = getProjectConfig();
1179
+ const { storeHash, accessToken } = resolveCredentials(options, config2);
1180
+ await getTelemetry().identify(storeHash);
1181
+ consola.start("Fetching projects...");
1182
+ const projects = await fetchProjects(storeHash, accessToken, options.apiHost);
1183
+ consola.success("Projects fetched.");
1184
+ if (projects.length === 0) {
1185
+ consola.info("No projects found.");
738
1186
  process.exit(0);
739
- } catch (error) {
740
- consola.error(error instanceof Error ? error.message : error);
741
- process.exit(1);
1187
+ return;
742
1188
  }
1189
+ projects.forEach((p) => {
1190
+ consola.log(`${p.name} (${p.uuid})`);
1191
+ });
1192
+ process.exit(0);
743
1193
  });
744
- var create = new Command4("create").description(
1194
+ var create = new Command5("create").description(
745
1195
  "Create a new BigCommerce infrastructure project and link it to your local Catalyst project."
746
1196
  ).addOption(
747
- new Option3(
1197
+ new Option6(
748
1198
  "--store-hash <hash>",
749
1199
  "BigCommerce store hash. Can be found in the URL of your store Control Panel."
750
- ).env("BIGCOMMERCE_STORE_HASH")
1200
+ ).env("CATALYST_STORE_HASH")
751
1201
  ).addOption(
752
- new Option3(
1202
+ new Option6(
753
1203
  "--access-token <token>",
754
1204
  "BigCommerce access token. Can be found after creating a store-level API account."
755
- ).env("BIGCOMMERCE_ACCESS_TOKEN")
1205
+ ).env("CATALYST_ACCESS_TOKEN")
756
1206
  ).addOption(
757
- new Option3("--api-host <host>", "BigCommerce API host. The default is api.bigcommerce.com.").env("BIGCOMMERCE_API_HOST").default("api.bigcommerce.com")
758
- ).option(
759
- "--root-dir <path>",
760
- "Path to the root directory of your Catalyst project (default: current working directory).",
761
- process.cwd()
1207
+ new Option6("--api-host <host>", "BigCommerce API host. The default is api.bigcommerce.com.").env("BIGCOMMERCE_API_HOST").default("api.bigcommerce.com")
762
1208
  ).action(async (options) => {
763
- try {
764
- if (!options.storeHash || !options.accessToken) {
765
- consola.error("Insufficient information to create a project.");
766
- consola.info(
767
- "Provide both --store-hash and --access-token (or set BIGCOMMERCE_STORE_HASH and BIGCOMMERCE_ACCESS_TOKEN)."
768
- );
769
- process.exit(1);
770
- return;
771
- }
772
- await telemetry2.identify(options.storeHash);
773
- const newProjectName = await consola.prompt("Enter a name for the new project:", {
774
- type: "text"
775
- });
776
- const data = await createProject(
777
- newProjectName,
778
- options.storeHash,
779
- options.accessToken,
780
- options.apiHost
781
- );
782
- consola.success(`Project "${data.name}" created successfully.`);
783
- const config2 = getProjectConfig(options.rootDir);
784
- consola.start("Writing project UUID to .bigcommerce/project.json...");
785
- config2.set("projectUuid", data.uuid);
786
- config2.set("framework", "catalyst");
787
- consola.success("Project UUID written to .bigcommerce/project.json.");
788
- process.exit(0);
789
- } catch (error) {
790
- consola.error(error instanceof Error ? error.message : error);
791
- process.exit(1);
792
- }
1209
+ const config2 = getProjectConfig();
1210
+ const { storeHash, accessToken } = resolveCredentials(options, config2);
1211
+ await getTelemetry().identify(storeHash);
1212
+ const newProjectName = await consola.prompt("Enter a name for the new project:", {
1213
+ type: "text"
1214
+ });
1215
+ const data = await createProject(newProjectName, storeHash, accessToken, options.apiHost);
1216
+ consola.success(`Project "${data.name}" created successfully.`);
1217
+ consola.start("Writing project UUID to .bigcommerce/project.json...");
1218
+ config2.set("projectUuid", data.uuid);
1219
+ config2.set("storeHash", storeHash);
1220
+ config2.set("accessToken", accessToken);
1221
+ consola.success("Project UUID written to .bigcommerce/project.json.");
1222
+ process.exit(0);
793
1223
  });
794
- var link = new Command4("link").description(
1224
+ var link = new Command5("link").description(
795
1225
  "Link your local Catalyst project to a BigCommerce infrastructure project. You can provide a project UUID directly, or fetch and select from available projects using your store credentials."
796
1226
  ).addOption(
797
- new Option3(
1227
+ new Option6(
798
1228
  "--store-hash <hash>",
799
1229
  "BigCommerce store hash. Can be found in the URL of your store Control Panel."
800
- ).env("BIGCOMMERCE_STORE_HASH")
1230
+ ).env("CATALYST_STORE_HASH")
801
1231
  ).addOption(
802
- new Option3(
1232
+ new Option6(
803
1233
  "--access-token <token>",
804
1234
  "BigCommerce access token. Can be found after creating a store-level API account."
805
- ).env("BIGCOMMERCE_ACCESS_TOKEN")
1235
+ ).env("CATALYST_ACCESS_TOKEN")
806
1236
  ).addOption(
807
- new Option3("--api-host <host>", "BigCommerce API host. The default is api.bigcommerce.com.").env("BIGCOMMERCE_API_HOST").default("api.bigcommerce.com")
1237
+ new Option6("--api-host <host>", "BigCommerce API host. The default is api.bigcommerce.com.").env("BIGCOMMERCE_API_HOST").default("api.bigcommerce.com")
808
1238
  ).option(
809
1239
  "--project-uuid <uuid>",
810
1240
  "BigCommerce infrastructure project UUID. Can be found via the BigCommerce API (GET /v3/infrastructure/projects). Use this to link directly without fetching projects."
811
- ).option(
812
- "--root-dir <path>",
813
- "Path to the root directory of your Catalyst project (default: current working directory).",
814
- process.cwd()
815
1241
  ).action(async (options) => {
816
- try {
817
- const config2 = getProjectConfig(options.rootDir);
818
- const writeProjectConfig = (uuid) => {
819
- consola.start("Writing project UUID to .bigcommerce/project.json...");
820
- config2.set("projectUuid", uuid);
821
- config2.set("framework", "catalyst");
822
- consola.success("Project UUID written to .bigcommerce/project.json.");
823
- };
824
- if (options.projectUuid) {
825
- writeProjectConfig(options.projectUuid);
826
- process.exit(0);
1242
+ const config2 = getProjectConfig();
1243
+ const writeProjectConfig = (uuid, credentials) => {
1244
+ consola.start("Writing project UUID to .bigcommerce/project.json...");
1245
+ config2.set("projectUuid", uuid);
1246
+ if (credentials) {
1247
+ config2.set("storeHash", credentials.storeHash);
1248
+ config2.set("accessToken", credentials.accessToken);
827
1249
  }
828
- if (options.storeHash && options.accessToken) {
829
- await telemetry2.identify(options.storeHash);
830
- consola.start("Fetching projects...");
831
- const projects = await fetchProjects(
832
- options.storeHash,
833
- options.accessToken,
834
- options.apiHost
835
- );
836
- consola.success("Projects fetched.");
837
- const promptOptions = [
838
- ...projects.map((proj) => ({
839
- label: proj.name,
840
- value: proj.uuid,
841
- hint: proj.uuid
842
- })),
843
- {
844
- label: "Create a new project",
845
- value: "create",
846
- hint: "Create a new infrastructure project for this BigCommerce store."
847
- }
848
- ];
849
- let projectUuid = await consola.prompt(
850
- "Select a project or create a new project (Press <enter> to select).",
851
- {
852
- type: "select",
853
- options: promptOptions,
854
- cancel: "reject"
855
- }
856
- );
857
- if (projectUuid === "create") {
858
- const newProjectName = await consola.prompt("Enter a name for the new project:", {
859
- type: "text"
860
- });
861
- const data = await createProject(
862
- newProjectName,
863
- options.storeHash,
864
- options.accessToken,
865
- options.apiHost
866
- );
867
- projectUuid = data.uuid;
868
- consola.success(`Project "${data.name}" created successfully.`);
869
- }
870
- writeProjectConfig(projectUuid);
871
- process.exit(0);
1250
+ consola.success("Project UUID written to .bigcommerce/project.json.");
1251
+ };
1252
+ if (options.projectUuid) {
1253
+ writeProjectConfig(options.projectUuid);
1254
+ process.exit(0);
1255
+ return;
1256
+ }
1257
+ const { storeHash, accessToken } = resolveCredentials(options, config2);
1258
+ await getTelemetry().identify(storeHash);
1259
+ consola.start("Fetching projects...");
1260
+ const projects = await fetchProjects(storeHash, accessToken, options.apiHost);
1261
+ consola.success("Projects fetched.");
1262
+ const promptOptions = [
1263
+ ...projects.map((proj) => ({
1264
+ label: proj.name,
1265
+ value: proj.uuid,
1266
+ hint: proj.uuid
1267
+ })),
1268
+ {
1269
+ label: "Create a new project",
1270
+ value: "create",
1271
+ hint: "Create a new infrastructure project for this BigCommerce store."
872
1272
  }
873
- consola.error("Insufficient information to link a project.");
874
- consola.info("Provide a project UUID with --project-uuid, or");
875
- consola.info("Provide both --store-hash and --access-token to fetch and select a project.");
876
- process.exit(1);
877
- } catch (error) {
878
- consola.error(error instanceof Error ? error.message : error);
879
- process.exit(1);
1273
+ ];
1274
+ let projectUuid = await consola.prompt(
1275
+ "Select a project or create a new project (Press <enter> to select).",
1276
+ {
1277
+ type: "select",
1278
+ options: promptOptions,
1279
+ cancel: "reject"
1280
+ }
1281
+ );
1282
+ if (projectUuid === "create") {
1283
+ const newProjectName = await consola.prompt("Enter a name for the new project:", {
1284
+ type: "text"
1285
+ });
1286
+ const data = await createProject(newProjectName, storeHash, accessToken, options.apiHost);
1287
+ projectUuid = data.uuid;
1288
+ consola.success(`Project "${data.name}" created successfully.`);
880
1289
  }
1290
+ writeProjectConfig(projectUuid, { storeHash, accessToken });
1291
+ process.exit(0);
881
1292
  });
882
- var project = new Command4("project").description("Manage your BigCommerce infrastructure project.").addCommand(create).addCommand(list).addCommand(link);
1293
+ var project = new Command5("project").description("Manage your BigCommerce infrastructure project.").addCommand(create).addCommand(list).addCommand(link);
883
1294
 
884
1295
  // src/cli/commands/start.ts
885
- import { Command as Command5, Option as Option4 } from "commander";
886
- import { execa as execa3 } from "execa";
887
- import { existsSync as existsSync3 } from "fs";
888
- import { join as join6 } from "path";
889
- var start = new Command5("start").description("Start your Catalyst storefront in optimized production mode.").allowUnknownOption(true).argument(
890
- "[start-options...]",
891
- "Pass additional options to the start command. If framework is Next.js, see https://nextjs.org/docs/api-reference/cli#start for available options."
892
- ).addOption(
893
- new Option4("--framework <framework>", "The framework to use for the preview").choices([
894
- "catalyst",
895
- "nextjs"
896
- ])
897
- ).action(async (startOptions, options) => {
898
- try {
899
- const config2 = getProjectConfig();
900
- const framework = options.framework ?? config2.get("framework");
901
- if (framework === "nextjs") {
902
- const nextBin = join6("node_modules", ".bin", "next");
903
- if (!existsSync3(nextBin)) {
904
- throw new Error(
905
- `Next.js is not installed in ${process.cwd()}. Are you in a valid Next.js project?`
906
- );
907
- }
908
- await execa3(nextBin, ["start", ...startOptions], {
909
- stdio: "inherit",
910
- cwd: process.cwd()
911
- });
1296
+ import { Command as Command6 } from "commander";
1297
+ import { execa as execa2 } from "execa";
1298
+ import { existsSync, lstatSync, symlinkSync } from "fs";
1299
+ import { join as join5, relative } from "path";
1300
+ var start = new Command6("start").description(
1301
+ "Start a local preview of your Catalyst storefront using the OpenNext Cloudflare adapter."
1302
+ ).action(async () => {
1303
+ const envLocal = join5(process.cwd(), ".env.local");
1304
+ const devVars = join5(process.cwd(), ".bigcommerce", ".dev.vars");
1305
+ if (existsSync(envLocal)) {
1306
+ if (!existsSync(devVars)) {
1307
+ const target = relative(join5(process.cwd(), ".bigcommerce"), envLocal);
1308
+ symlinkSync(target, devVars);
1309
+ consola.success("Symlinked .bigcommerce/.dev.vars \u2192 .env.local");
1310
+ } else if (!lstatSync(devVars).isSymbolicLink()) {
1311
+ consola.warn(
1312
+ ".bigcommerce/.dev.vars already exists and is not a symlink. Wrangler will use it instead of .env.local."
1313
+ );
912
1314
  }
913
- await execa3(
914
- "pnpm",
915
- [
916
- "exec",
917
- "opennextjs-cloudflare",
918
- "preview",
919
- "--config",
920
- join6(".bigcommerce", "wrangler.jsonc"),
921
- ...startOptions
922
- ],
923
- {
924
- stdio: "inherit",
925
- cwd: process.cwd()
926
- }
1315
+ } else {
1316
+ consola.warn(
1317
+ "No .env.local file found. The preview server may fail without environment variables.\nCreate a .env.local file in your project root with the required variables."
927
1318
  );
928
- } catch (error) {
929
- consola.error(error instanceof Error ? error.message : error);
930
1319
  }
1320
+ await execa2(
1321
+ "pnpm",
1322
+ [
1323
+ "exec",
1324
+ "opennextjs-cloudflare",
1325
+ "preview",
1326
+ "--config",
1327
+ join5(".bigcommerce", "wrangler.jsonc")
1328
+ ],
1329
+ {
1330
+ stdio: "inherit",
1331
+ cwd: process.cwd()
1332
+ }
1333
+ );
931
1334
  });
932
1335
 
933
1336
  // src/cli/commands/telemetry.ts
934
- import { Argument, Command as Command6, Option as Option5 } from "commander";
935
- import { colorize } from "consola/utils";
936
- var telemetryService = new Telemetry();
1337
+ import { Argument, Command as Command7, Option as Option7 } from "commander";
1338
+ import { colorize as colorize3 } from "consola/utils";
1339
+ var telemetryService = getTelemetry();
937
1340
  var isEnabled = telemetryService.isEnabled();
938
- var telemetry3 = new Command6("telemetry").addArgument(new Argument("[arg]").choices(["disable", "enable", "status"])).addOption(new Option5("--enable", `Enables CLI telemetry collection.`).conflicts("disable")).option("--disable", `Disables CLI telemetry collection.`).action((arg, options) => {
1341
+ var telemetry2 = new Command7("telemetry").addArgument(new Argument("[arg]").choices(["disable", "enable", "status"])).addOption(new Option7("--enable", `Enables CLI telemetry collection.`).conflicts("disable")).option("--disable", `Disables CLI telemetry collection.`).action((arg, options) => {
939
1342
  if (options.enable || arg === "enable") {
940
1343
  telemetryService.setEnabled(true);
941
1344
  isEnabled = true;
@@ -952,7 +1355,7 @@ var telemetry3 = new Command6("telemetry").addArgument(new Argument("[arg]").cho
952
1355
  consola.info("Catalyst CLI Telemetry\n");
953
1356
  }
954
1357
  consola.info(
955
- `Status: ${colorize("bold", isEnabled ? colorize("green", "Enabled") : colorize("red", "Disabled"))}`
1358
+ `Status: ${colorize3("bold", isEnabled ? colorize3("green", "Enabled") : colorize3("red", "Disabled"))}`
956
1359
  );
957
1360
  if (!isEnabled) {
958
1361
  consola.info(
@@ -962,8 +1365,8 @@ var telemetry3 = new Command6("telemetry").addArgument(new Argument("[arg]").cho
962
1365
  });
963
1366
 
964
1367
  // src/cli/commands/version.ts
965
- import { Command as Command7 } from "commander";
966
- var version = new Command7("version").description("Display detailed version information.").action(() => {
1368
+ import { Command as Command8 } from "commander";
1369
+ var version = new Command8("version").description("Display detailed version information.").action(() => {
967
1370
  consola.log("Version Information:");
968
1371
  consola.log(`CLI Version: ${package_default.version}`);
969
1372
  consola.log(`Node Version: ${process.version}`);
@@ -971,7 +1374,6 @@ var version = new Command7("version").description("Display detailed version info
971
1374
  });
972
1375
 
973
1376
  // src/cli/hooks/telemetry.ts
974
- var telemetry4 = new Telemetry();
975
1377
  var allowlistArguments = ["--keep-temp-dir", "--api-host", "--project-uuid"];
976
1378
  function parseArguments(args) {
977
1379
  return args.reduce((result, arg, index, array) => {
@@ -996,31 +1398,97 @@ function parseArguments(args) {
996
1398
  return result;
997
1399
  }, {});
998
1400
  }
999
- var telemetryPreHook = async (command) => {
1000
- const [commandName, ...args] = command.args;
1001
- return await telemetry4.track(commandName, {
1002
- ...parseArguments(args)
1401
+ function getCommandPath(cmd) {
1402
+ const parts = [];
1403
+ let current = cmd;
1404
+ while (current.parent) {
1405
+ parts.unshift(current.name());
1406
+ current = current.parent;
1407
+ }
1408
+ return parts.join(" ");
1409
+ }
1410
+ var telemetryPreHook = async (thisCommand, actionCommand) => {
1411
+ const telemetry3 = getTelemetry();
1412
+ const commandName = getCommandPath(actionCommand);
1413
+ telemetry3.commandName = commandName;
1414
+ return await telemetry3.track(commandName, {
1415
+ ...parseArguments(thisCommand.args)
1003
1416
  });
1004
1417
  };
1005
1418
  var telemetryPostHook = async () => {
1006
- await telemetry4.analytics.closeAndFlush();
1419
+ const telemetry3 = getTelemetry();
1420
+ await telemetry3.track("command_completed", { durationMs: telemetry3.durationMs() });
1421
+ await telemetry3.analytics.closeAndFlush();
1007
1422
  };
1008
1423
 
1009
1424
  // src/cli/program.ts
1010
- var program = new Command8();
1011
- config({
1012
- path: [
1013
- resolve(process.cwd(), ".env"),
1014
- resolve(process.cwd(), ".env.local"),
1015
- // Assumes the parent directory is the monorepo root:
1016
- resolve(process.cwd(), "..", ".env"),
1017
- resolve(process.cwd(), "..", ".env.local")
1018
- ]
1019
- });
1020
- consola.log(colorize2("cyanBright", `\u25E2 ${package_default.name} v${package_default.version}
1425
+ var program = new Command9();
1426
+ consola.log(colorize4("cyanBright", `\u25E2 ${package_default.name} v${package_default.version}
1427
+ `));
1428
+ program.name(package_default.name).version(package_default.version).description("CLI tool for Catalyst development").addOption(
1429
+ new Option8(
1430
+ "--env-path <path>",
1431
+ "Path to environment file to load (relative to current working directory)"
1432
+ // We are using argParser, because commander loads in environment variables before executing hooks.
1433
+ ).argParser((value) => {
1434
+ if (value) {
1435
+ const envFilePath = resolve(process.cwd(), value);
1436
+ const result = config({
1437
+ path: envFilePath,
1438
+ override: true
1439
+ });
1440
+ if (result.error) {
1441
+ const errCode = "code" in result.error && typeof result.error.code === "string" ? result.error.code : void 0;
1442
+ const message = errCode === "ENOENT" ? `Env file not found: ${envFilePath}` : `Failed to load --env-path ${value}: ${result.error.message}`;
1443
+ throw new Error(message);
1444
+ }
1445
+ consola.log(colorize4("cyanBright", `Loaded environment variables from ${envFilePath}
1021
1446
  `));
1022
- program.name(package_default.name).version(package_default.version).description("CLI tool for Catalyst development").addCommand(version).addCommand(dev).addCommand(start).addCommand(build).addCommand(deploy).addCommand(project).addCommand(telemetry3).hook("preAction", telemetryPreHook).hook("postAction", telemetryPostHook);
1447
+ }
1448
+ return value;
1449
+ })
1450
+ ).addCommand(version).addCommand(start).addCommand(build).addCommand(deploy).addCommand(logs).addCommand(project).addCommand(auth).addCommand(telemetry2).hook("preAction", telemetryPreHook).hook("postAction", telemetryPostHook);
1023
1451
 
1024
1452
  // src/cli/index.ts
1025
- program.parse(process.argv);
1453
+ var handleFatalError = async (error) => {
1454
+ const telemetry3 = getTelemetry();
1455
+ const errorMessage = error instanceof Error ? error.message : String(error);
1456
+ const errorStack = error instanceof Error ? error.stack : void 0;
1457
+ try {
1458
+ await telemetry3.track("error", {
1459
+ commandName: telemetry3.commandName,
1460
+ errorMessage,
1461
+ errorStack,
1462
+ durationMs: telemetry3.durationMs()
1463
+ });
1464
+ await telemetry3.analytics.closeAndFlush();
1465
+ } catch {
1466
+ }
1467
+ consola.error(errorMessage);
1468
+ if (telemetry3.isEnabled()) {
1469
+ consola.info(
1470
+ `
1471
+ Trace ID: ${telemetry3.sessionId}
1472
+ Share this Trace ID with BigCommerce support.`
1473
+ );
1474
+ } else {
1475
+ consola.info(
1476
+ "\nEnable telemetry (`catalyst telemetry enable`) for improved troubleshooting with BigCommerce support."
1477
+ );
1478
+ }
1479
+ process.exit(1);
1480
+ };
1481
+ process.on("uncaughtException", (error) => {
1482
+ void handleFatalError(error);
1483
+ });
1484
+ process.on("unhandledRejection", (reason) => {
1485
+ void handleFatalError(reason);
1486
+ });
1487
+ void (async () => {
1488
+ try {
1489
+ await program.parseAsync(process.argv);
1490
+ } catch (error) {
1491
+ await handleFatalError(error);
1492
+ }
1493
+ })();
1026
1494
  //# sourceMappingURL=cli.js.map