@donotdev/cli 0.0.33 → 0.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8733,7 +8733,7 @@ var init_cli_input = __esm({
8733
8733
  });
8734
8734
 
8735
8735
  // packages/tooling/src/utils/cli-tools.ts
8736
- import { spawnSync as spawnSync5 } from "node:child_process";
8736
+ import { spawnSync } from "node:child_process";
8737
8737
  function checkCLI(command, args = ["--version"], useCache = true) {
8738
8738
  const cacheKey = `${command}:${args.join(",")}`;
8739
8739
  if (useCache && cliCache.has(cacheKey)) {
@@ -8757,7 +8757,7 @@ function checkCLI(command, args = ["--version"], useCache = true) {
8757
8757
  ].filter(Boolean);
8758
8758
  for (const fullPath of commonPaths) {
8759
8759
  try {
8760
- const testResult = spawnSync5(
8760
+ const testResult = spawnSync(
8761
8761
  "powershell.exe",
8762
8762
  [
8763
8763
  "-NoProfile",
@@ -8779,7 +8779,7 @@ function checkCLI(command, args = ["--version"], useCache = true) {
8779
8779
  continue;
8780
8780
  }
8781
8781
  }
8782
- result = spawnSync5(
8782
+ result = spawnSync(
8783
8783
  "powershell.exe",
8784
8784
  [
8785
8785
  "-NoProfile",
@@ -8794,7 +8794,7 @@ function checkCLI(command, args = ["--version"], useCache = true) {
8794
8794
  }
8795
8795
  );
8796
8796
  } else {
8797
- result = spawnSync5(`${command} ${args.join(" ")}`, {
8797
+ result = spawnSync(`${command} ${args.join(" ")}`, {
8798
8798
  stdio: "pipe",
8799
8799
  shell: true
8800
8800
  });
@@ -9022,6 +9022,29 @@ var init_cli_tools = __esm({
9022
9022
  }
9023
9023
  });
9024
9024
 
9025
+ // packages/tooling/src/utils/error-handling.ts
9026
+ function isError(error2) {
9027
+ return error2 instanceof Error;
9028
+ }
9029
+ function getErrorMessage(error2) {
9030
+ if (isError(error2)) {
9031
+ return error2.message;
9032
+ }
9033
+ if (typeof error2 === "string") {
9034
+ return error2;
9035
+ }
9036
+ if (error2 && typeof error2 === "object" && "message" in error2) {
9037
+ return String(error2.message);
9038
+ }
9039
+ return String(error2);
9040
+ }
9041
+ var init_error_handling = __esm({
9042
+ "packages/tooling/src/utils/error-handling.ts"() {
9043
+ "use strict";
9044
+ init_utils();
9045
+ }
9046
+ });
9047
+
9025
9048
  // node_modules/.bun/yaml@2.8.2/node_modules/yaml/dist/nodes/identity.js
9026
9049
  var require_identity = __commonJS({
9027
9050
  "node_modules/.bun/yaml@2.8.2/node_modules/yaml/dist/nodes/identity.js"(exports) {
@@ -16383,29 +16406,6 @@ var require_dist = __commonJS({
16383
16406
  }
16384
16407
  });
16385
16408
 
16386
- // packages/tooling/src/utils/error-handling.ts
16387
- function isError(error2) {
16388
- return error2 instanceof Error;
16389
- }
16390
- function getErrorMessage(error2) {
16391
- if (isError(error2)) {
16392
- return error2.message;
16393
- }
16394
- if (typeof error2 === "string") {
16395
- return error2;
16396
- }
16397
- if (error2 && typeof error2 === "object" && "message" in error2) {
16398
- return String(error2.message);
16399
- }
16400
- return String(error2);
16401
- }
16402
- var init_error_handling = __esm({
16403
- "packages/tooling/src/utils/error-handling.ts"() {
16404
- "use strict";
16405
- init_utils();
16406
- }
16407
- });
16408
-
16409
16409
  // packages/tooling/src/apps/vercel-api.ts
16410
16410
  function formatVercelError(status, body, context) {
16411
16411
  let vercelCode;
@@ -17317,237 +17317,553 @@ init_cli_output();
17317
17317
  init_errors();
17318
17318
  init_pathResolver();
17319
17319
  init_typed_file_operations();
17320
- import { spawnSync, execSync } from "node:child_process";
17321
- function validateFirebaseJson(appDir) {
17322
- const firebaseJsonPath = joinPath(appDir, "firebase.json");
17323
- if (!pathExists(firebaseJsonPath)) {
17324
- return {
17325
- valid: false,
17326
- hasHosting: false,
17327
- hasFunctions: false
17328
- };
17320
+ import { spawnSync as spawnSync4, execSync as execSync2 } from "node:child_process";
17321
+
17322
+ // packages/tooling/src/apps/deploy-utils.ts
17323
+ init_utils();
17324
+ import { spawnSync as spawnSync3 } from "node:child_process";
17325
+
17326
+ // packages/tooling/src/utils/create-utils.ts
17327
+ init_utils();
17328
+ init_cli_output();
17329
+ init_pathResolver();
17330
+ init_typed_file_operations();
17331
+ async function copyTemplateFiles(sourceDir, destDir, replacements) {
17332
+ if (!pathExists(sourceDir)) {
17333
+ log.warn(`Warning: Template directory does not exist: ${sourceDir}`);
17334
+ return;
17335
+ }
17336
+ const files = await glob("**/*", {
17337
+ cwd: sourceDir,
17338
+ dot: true,
17339
+ onlyFiles: true
17340
+ });
17341
+ for (const file of files) {
17342
+ const sourcePath = joinPath(sourceDir, file);
17343
+ let destFileName = file;
17344
+ if (destFileName.endsWith(".example")) {
17345
+ destFileName = destFileName.slice(0, -8);
17346
+ }
17347
+ const destPath = joinPath(destDir, destFileName);
17348
+ await ensureDir(getDirname(destPath));
17349
+ await copy(sourcePath, destPath);
17350
+ if (await isTextFile(destPath)) {
17351
+ await replacePlaceholders(destPath, replacements);
17352
+ }
17329
17353
  }
17354
+ }
17355
+ async function isTextFile(filePath) {
17356
+ const binaryExtensions = [
17357
+ ".png",
17358
+ ".jpg",
17359
+ ".jpeg",
17360
+ ".gif",
17361
+ ".ico",
17362
+ ".woff",
17363
+ ".woff2",
17364
+ ".eot",
17365
+ ".ttf",
17366
+ ".otf",
17367
+ ".zip",
17368
+ ".pdf",
17369
+ ".exe",
17370
+ ".dll",
17371
+ ".so",
17372
+ ".bin",
17373
+ ".dat",
17374
+ ".class"
17375
+ ];
17376
+ if (binaryExtensions.some((ext) => filePath.toLowerCase().endsWith(ext)))
17377
+ return false;
17378
+ const textExtensions = [
17379
+ ".json",
17380
+ ".js",
17381
+ ".ts",
17382
+ ".tsx",
17383
+ ".jsx",
17384
+ ".md",
17385
+ ".yml",
17386
+ ".yaml",
17387
+ ".html",
17388
+ ".css",
17389
+ ".scss",
17390
+ ".env",
17391
+ ".gitignore",
17392
+ ".npmrc",
17393
+ ".eslintrc",
17394
+ ".prettierrc",
17395
+ ".firebase",
17396
+ ".txt"
17397
+ ];
17398
+ if (textExtensions.some((ext) => filePath.toLowerCase().endsWith(ext)))
17399
+ return true;
17330
17400
  try {
17331
- const config = readFirebaseJson(firebaseJsonPath);
17332
- if (!config.projectId) {
17333
- return {
17334
- valid: false,
17335
- hasHosting: false,
17336
- hasFunctions: false
17337
- };
17401
+ const buffer = await read(filePath, { format: "buffer" });
17402
+ if (buffer.length === 0) return true;
17403
+ for (let i = 0; i < Math.min(buffer.length, 1e3); i++) {
17404
+ if (buffer[i] === 0) return false;
17338
17405
  }
17339
- return {
17340
- valid: true,
17341
- hasHosting: !!config.hosting,
17342
- hasFunctions: !!config.functions && Array.isArray(config.functions)
17343
- };
17406
+ return true;
17344
17407
  } catch {
17345
- return {
17346
- valid: false,
17347
- hasHosting: false,
17348
- hasFunctions: false
17349
- };
17408
+ return false;
17350
17409
  }
17351
17410
  }
17352
- function parseBuildArgs(args) {
17353
- const result = {};
17354
- for (const arg of args) {
17355
- if (arg === ":front" || arg === ":frontend" || arg === "front" || arg === "frontend") {
17356
- result.buildType = "frontend";
17357
- } else if (arg === ":func" || arg === ":functions" || arg === "func" || arg === "functions") {
17358
- result.buildType = "functions";
17359
- } else if (arg === ":both" || arg === "both") {
17360
- result.buildType = "both";
17361
- } else if (arg.includes(":")) {
17362
- const parts = arg.split(":");
17363
- result.appName = parts[0];
17364
- const typePart = parts[1];
17365
- if (typePart === "front" || typePart === "frontend") {
17366
- result.buildType = "frontend";
17367
- } else if (typePart === "func" || typePart === "functions") {
17368
- result.buildType = "functions";
17369
- } else if (typePart === "both") {
17370
- result.buildType = "both";
17411
+ async function replacePlaceholders(filePath, replacements) {
17412
+ try {
17413
+ let content = await read(filePath, { format: "text" });
17414
+ if (typeof content !== "string") {
17415
+ content = typeof content === "object" ? JSON.stringify(content, null, 2) : String(content);
17416
+ }
17417
+ content = processConditionalSections(content, replacements);
17418
+ content = processArrayIterations(content, replacements);
17419
+ for (const [key, value] of Object.entries(replacements)) {
17420
+ if (value !== void 0) {
17421
+ const regex = new RegExp(`{{${key}}}`, "g");
17422
+ if (typeof value === "string") {
17423
+ content = content.replace(regex, value);
17424
+ }
17371
17425
  }
17372
- } else if (!arg.startsWith(":") && arg !== "build") {
17373
- result.appName = arg;
17374
17426
  }
17375
- }
17376
- return result;
17377
- }
17378
- async function main() {
17379
- const args = process.argv.slice(2);
17380
- const { appName: parsedAppName, buildType: parsedBuildType } = parseBuildArgs(args);
17381
- const debugMode = process.env.DEBUG === "true" || process.env.DEBUG === "1" || args.includes("--debug") || args.includes("-d");
17382
- if (debugMode) {
17383
- log.debug(` Args: ${args.join(" ")}`);
17384
- log.debug(
17385
- ` Parsed app: ${parsedAppName || "none"}, build type: ${parsedBuildType || "none"}
17386
- `
17427
+ await write(filePath, content, { overwrite: true });
17428
+ } catch (error2) {
17429
+ log.warn(
17430
+ `Warning: Could not process file ${filePath}: ${error2.message || "Unknown error"}`
17387
17431
  );
17388
17432
  }
17389
- const projectRoot = getRepoRoot();
17390
- if (!projectRoot) {
17391
- throw new DoNotDevError(
17392
- "Could not determine repository root",
17393
- "path-resolution-error"
17433
+ }
17434
+ function processConditionalSections(content, replacements) {
17435
+ Object.keys(replacements).forEach((key) => {
17436
+ const value = replacements[key];
17437
+ const isTruthy = value === true || value === "true";
17438
+ const positivePattern = new RegExp(
17439
+ `{{#${key}}}([\\s\\S]*?){{/${key}}}`,
17440
+ "g"
17394
17441
  );
17395
- }
17396
- const app = await selectApp(projectRoot, parsedAppName);
17397
- if (!app) {
17398
- return 1;
17399
- }
17400
- const appDir = app.path;
17401
- const firebaseConfig = validateFirebaseJson(appDir);
17402
- const hasFunctions = app.hasFunctions || firebaseConfig.hasFunctions;
17403
- const hasFrontend = app.framework !== "unknown";
17404
- let buildType = parsedBuildType;
17405
- if (!buildType) {
17406
- const choices = [];
17407
- if (hasFrontend) {
17408
- choices.push({
17409
- title: "Frontend only",
17410
- value: "frontend",
17411
- hint: "Build app bundle"
17412
- });
17442
+ if (isTruthy) {
17443
+ content = content.replace(positivePattern, (match, inner) => inner);
17444
+ } else {
17445
+ content = content.replace(positivePattern, "");
17413
17446
  }
17414
- if (hasFunctions) {
17415
- choices.push({
17416
- title: "Functions only",
17417
- value: "functions",
17418
- hint: "Build cloud functions"
17419
- });
17447
+ const negativePattern = new RegExp(
17448
+ `{{\\^${key}}}([\\s\\S]*?){{/${key}}}`,
17449
+ "g"
17450
+ );
17451
+ if (!isTruthy) {
17452
+ content = content.replace(negativePattern, (match, inner) => inner);
17453
+ } else {
17454
+ content = content.replace(negativePattern, "");
17420
17455
  }
17421
- if (hasFrontend && hasFunctions) {
17422
- choices.push({
17423
- title: "Both frontend and functions",
17424
- value: "both",
17425
- hint: "Build everything"
17426
- });
17456
+ });
17457
+ return content;
17458
+ }
17459
+ function processArrayIterations(content, replacements) {
17460
+ const appNamesPattern = /{{#appNames}}([\s\S]*?){{\/appNames}}/g;
17461
+ if (replacements.appNames && Array.isArray(replacements.appNames)) {
17462
+ const appNames = replacements.appNames;
17463
+ content = content.replace(appNamesPattern, (match, templateContent) => {
17464
+ return appNames.map((appName) => templateContent.replace(/{{\.}}/g, appName)).join("");
17465
+ });
17466
+ } else {
17467
+ content = content.replace(appNamesPattern, "");
17468
+ }
17469
+ return content;
17470
+ }
17471
+ function isValidFileName(name) {
17472
+ return typeof name === "string" && /^[a-zA-Z0-9_-]+$/.test(name);
17473
+ }
17474
+ var RESERVED_APP_NAMES = ["demo", "dndev"];
17475
+ function isReservedAppName(name) {
17476
+ return RESERVED_APP_NAMES.includes(
17477
+ name.toLowerCase()
17478
+ );
17479
+ }
17480
+ async function updateRootPackageJson(rootDir, appNames) {
17481
+ const packageJsonPath = joinPath(rootDir, "package.json");
17482
+ if (!pathExists(packageJsonPath)) {
17483
+ log.warn("Root package.json not found, skipping script updates");
17484
+ return;
17485
+ }
17486
+ try {
17487
+ const packageJson = await read(packageJsonPath, { format: "json" });
17488
+ packageJson.scripts = packageJson.scripts || {};
17489
+ } catch (error2) {
17490
+ log.warn(
17491
+ `Warning: Could not update root package.json: ${error2.message || "Unknown error"}`
17492
+ );
17493
+ }
17494
+ }
17495
+ async function mergeRootPackageJson(rootDir, allAppNames, options = {}) {
17496
+ const packageJsonPath = joinPath(rootDir, "package.json");
17497
+ if (!pathExists(packageJsonPath)) {
17498
+ log.warn("Root package.json not found, skipping merge");
17499
+ return;
17500
+ }
17501
+ try {
17502
+ const packageJson = await read(packageJsonPath, { format: "json" });
17503
+ packageJson.scripts = packageJson.scripts || {};
17504
+ } catch (error2) {
17505
+ log.warn(
17506
+ `Warning: Could not merge root package.json: ${error2.message || "Unknown error"}`
17507
+ );
17508
+ }
17509
+ }
17510
+ async function mergeRootTsConfig(rootDir, allAppNames, includeFunctions = false) {
17511
+ const tsconfigPath = joinPath(rootDir, "tsconfig.json");
17512
+ if (!pathExists(tsconfigPath)) {
17513
+ log.warn("Root tsconfig.json not found, skipping merge");
17514
+ return;
17515
+ }
17516
+ try {
17517
+ const tsconfig = readTsConfigJson(tsconfigPath);
17518
+ tsconfig.references = tsconfig.references || [];
17519
+ const existingPaths = new Set(
17520
+ tsconfig.references.map((ref) => ref.path)
17521
+ );
17522
+ let updated = false;
17523
+ for (const appName of allAppNames) {
17524
+ const appPath = `${appName}-app`;
17525
+ if (!existingPaths.has(appPath)) {
17526
+ tsconfig.references.push({ path: appPath });
17527
+ updated = true;
17528
+ }
17427
17529
  }
17428
- if (choices.length === 0) {
17429
- log.error("No build targets found. App must have frontend or functions.");
17430
- throw new DoNotDevError("No build targets found", "validation-error");
17530
+ if (includeFunctions && !existingPaths.has("functions")) {
17531
+ tsconfig.references.push({ path: "functions" });
17532
+ updated = true;
17431
17533
  }
17432
- if (choices.length === 1) {
17433
- buildType = choices[0].value;
17434
- Me(`Building: ${choices[0].title}`, "Auto-selected");
17435
- } else {
17436
- buildType = await askForSelection(
17437
- "What would you like to build?",
17438
- choices
17439
- );
17534
+ if (updated) {
17535
+ await write(tsconfigPath, tsconfig, { format: "json", overwrite: true });
17536
+ log.info("Merged root tsconfig.json");
17440
17537
  }
17538
+ } catch (error2) {
17539
+ log.warn(
17540
+ `Warning: Could not merge root tsconfig.json: ${error2.message || "Unknown error"}`
17541
+ );
17441
17542
  }
17442
- if (buildType === "frontend" || buildType === "both") {
17443
- if (!hasFrontend) {
17444
- log.error(
17445
- "Frontend build requested but app has no frontend configuration."
17446
- );
17447
- throw new DoNotDevError(
17448
- "Frontend build requested but app has no frontend configuration",
17449
- "validation-error"
17543
+ }
17544
+ async function mergeRootTurboJson(rootDir) {
17545
+ const turboJsonPath = joinPath(rootDir, "turbo.json");
17546
+ if (!pathExists(turboJsonPath)) {
17547
+ log.warn("Root turbo.json not found, skipping merge");
17548
+ return;
17549
+ }
17550
+ try {
17551
+ const turboJson = readTurboJson(turboJsonPath);
17552
+ if (!turboJson) {
17553
+ throw new Error(
17554
+ `turbo.json is empty or invalid JSON at ${turboJsonPath}`
17450
17555
  );
17451
17556
  }
17452
- log.info(`Building ${app.name} frontend...
17453
- `);
17454
- const turboArgs = ["build", "--filter", app.packageName];
17455
- const env = {
17456
- ...process.env,
17457
- DNDEV_APP_ROOT: app.path
17557
+ turboJson.tasks = turboJson.tasks || {};
17558
+ const defaultTasks = {
17559
+ build: {
17560
+ dependsOn: ["^build"],
17561
+ outputs: ["*/dist/**", "!**/node_modules/**"]
17562
+ },
17563
+ preview: {
17564
+ dependsOn: ["build"],
17565
+ cache: false,
17566
+ persistent: true
17567
+ },
17568
+ test: {
17569
+ dependsOn: ["^build"],
17570
+ outputs: ["coverage/**"]
17571
+ },
17572
+ lint: {
17573
+ outputs: []
17574
+ },
17575
+ dev: {
17576
+ cache: false,
17577
+ persistent: true
17578
+ },
17579
+ clean: {
17580
+ cache: false
17581
+ }
17458
17582
  };
17459
- const result = spawnSync("bunx", ["turbo", ...turboArgs], {
17460
- stdio: "inherit",
17461
- env,
17462
- cwd: projectRoot
17463
- });
17464
- if (result.status !== 0) {
17465
- return result.status || 1;
17466
- }
17467
- }
17468
- if (buildType === "functions" || buildType === "both") {
17469
- if (!hasFunctions) {
17470
- log.error(
17471
- "Functions build requested but app has no functions directory."
17472
- );
17473
- throw new DoNotDevError(
17474
- "Functions build requested but app has no functions directory",
17475
- "validation-error"
17476
- );
17583
+ let updated = false;
17584
+ for (const [taskName, taskConfig] of Object.entries(defaultTasks)) {
17585
+ if (!turboJson.tasks[taskName]) {
17586
+ turboJson.tasks[taskName] = taskConfig;
17587
+ updated = true;
17588
+ }
17477
17589
  }
17478
- const functionsDir = joinPath(appDir, "functions");
17479
- if (!pathExists(functionsDir)) {
17480
- log.error(`Functions directory not found: ${functionsDir}`);
17481
- throw new DoNotDevError(
17482
- `Functions directory not found: ${functionsDir}`,
17483
- "file-not-found"
17484
- );
17590
+ if (!turboJson.globalDependencies) {
17591
+ turboJson.globalDependencies = ["**/.env.*local"];
17592
+ updated = true;
17485
17593
  }
17486
- log.info(`Building ${app.name} functions...
17487
- `);
17488
- const s = Y2();
17489
- s.start("Building functions...");
17490
- try {
17491
- execSync("bun run build", {
17492
- cwd: functionsDir,
17493
- stdio: "inherit"
17594
+ if (updated) {
17595
+ await write(turboJsonPath, turboJson, {
17596
+ format: "json",
17597
+ overwrite: true
17494
17598
  });
17495
- s.stop("Functions built");
17496
- } catch (error2) {
17497
- s.stop("\u274C Functions build failed");
17498
- throw DoNotDevError.from(
17499
- error2,
17500
- "Functions build failed",
17501
- "cli-execution-error"
17502
- );
17599
+ log.info("Merged root turbo.json");
17503
17600
  }
17601
+ } catch (error2) {
17602
+ log.warn(
17603
+ `Warning: Could not merge root turbo.json: ${error2 instanceof Error ? error2.message : String(error2)}`
17604
+ );
17504
17605
  }
17505
- log.success(`Build complete for ${app.name}`);
17506
- return 0;
17507
17606
  }
17508
17607
 
17509
- // packages/tooling/src/apps/dev.ts
17510
- init_utils();
17511
- init_app_selector();
17512
- init_cli_output();
17513
- init_errors();
17514
- init_pathResolver();
17515
- import { execSync as execSync3 } from "node:child_process";
17516
- import { platform as platform2 } from "node:os";
17517
-
17518
- // packages/tooling/src/utils/spawn-utils.ts
17608
+ // packages/tooling/src/utils/matrix.ts
17519
17609
  init_utils();
17520
- init_cli_output();
17521
- init_errors();
17522
17610
  init_pathResolver();
17523
- import {
17524
- spawn,
17525
- spawnSync as spawnSync2,
17526
- execSync as execSync2
17527
- } from "node:child_process";
17528
- import { platform } from "node:os";
17529
- function createAppEnv(appPath) {
17530
- return {
17531
- ...process.env,
17532
- DNDEV_APP_ROOT: appPath
17533
- };
17534
- }
17535
- function spawnCrossPlatform(command, args, options) {
17536
- const isWindows = platform() === "win32";
17537
- const useShell = options.shell ?? isWindows;
17538
- if (useShell) {
17539
- const fullCommand = `${command} ${args.join(" ")}`;
17540
- const { shell: _4, ...rest2 } = options;
17541
- return spawn(fullCommand, [], { ...rest2, shell: true });
17611
+ import { createRequire as createRequire4 } from "node:module";
17612
+ var cachedMatrix = null;
17613
+ function getMatrixPath(mode) {
17614
+ try {
17615
+ const require3 = createRequire4(import.meta.url);
17616
+ const resolved = require3.resolve("@donotdev/cli/dependencies-matrix.json");
17617
+ if (pathExists(resolved)) {
17618
+ return resolved;
17619
+ }
17620
+ } catch {
17542
17621
  }
17543
- const { shell: _3, ...rest } = options;
17544
- return spawn(command, args, rest);
17545
- }
17546
- function createEmulatorEnv(appPath, framework = "vite", options) {
17547
- const baseEnv = createAppEnv(appPath);
17548
- const prefix = framework === "nextjs" ? "NEXT_PUBLIC_" : "VITE_";
17549
- const useEmulatorAuth = options?.useEmulatorAuth ?? false;
17550
- const useEmulatorFirestore = options?.useEmulatorFirestore ?? true;
17622
+ const executionMode = mode || detectExecutionMode();
17623
+ if (executionMode === "development") {
17624
+ const templatesRoot = getTemplatesRoot();
17625
+ const devPath = normalizePath(
17626
+ templatesRoot,
17627
+ "..",
17628
+ "dependencies-matrix.json"
17629
+ );
17630
+ if (pathExists(devPath)) {
17631
+ return devPath;
17632
+ }
17633
+ }
17634
+ return null;
17635
+ }
17636
+ function getCliVersion(mode) {
17637
+ try {
17638
+ const require3 = createRequire4(import.meta.url);
17639
+ const packageJsonPath = require3.resolve("@donotdev/cli/package.json");
17640
+ const pkg = readSync(packageJsonPath, { format: "json" });
17641
+ return String(pkg?.version || "0.0.0");
17642
+ } catch {
17643
+ }
17644
+ const executionMode = mode || detectExecutionMode();
17645
+ if (executionMode === "development") {
17646
+ const templatesRoot = getTemplatesRoot();
17647
+ const cliPackageJson = normalizePath(templatesRoot, "..", "package.json");
17648
+ if (pathExists(cliPackageJson)) {
17649
+ const pkg = readSync(cliPackageJson, { format: "json" });
17650
+ return String(pkg?.version || "0.0.0");
17651
+ }
17652
+ }
17653
+ return "0.0.0";
17654
+ }
17655
+ function loadMatrix(mode) {
17656
+ if (cachedMatrix) return cachedMatrix;
17657
+ const matrixPath = getMatrixPath(mode);
17658
+ if (!matrixPath) {
17659
+ return null;
17660
+ }
17661
+ const content = readSync(matrixPath, { format: "json" });
17662
+ if (!content) {
17663
+ return null;
17664
+ }
17665
+ cachedMatrix = {
17666
+ matrix: content,
17667
+ cliVersion: getCliVersion(mode)
17668
+ };
17669
+ return cachedMatrix;
17670
+ }
17671
+ function resolveGroup(groupName, matrix) {
17672
+ return matrix.groups[groupName]?.packages || {};
17673
+ }
17674
+ function resolveGroups(groupNames, matrix) {
17675
+ const result = {};
17676
+ for (const groupName of groupNames) {
17677
+ Object.assign(result, resolveGroup(groupName, matrix));
17678
+ }
17679
+ return result;
17680
+ }
17681
+
17682
+ // packages/tooling/src/utils/scaffolding-questionnaire.ts
17683
+ init_utils();
17684
+ var APP_QUESTIONNAIRE = [
17685
+ {
17686
+ id: "framework",
17687
+ question: "Which framework?",
17688
+ type: "select",
17689
+ defaultValue: "vite",
17690
+ choices: [
17691
+ {
17692
+ title: "Vite \u2014 SPA/SaaS (client-side rendering, fast dev)",
17693
+ value: "vite"
17694
+ },
17695
+ {
17696
+ title: "Next.js \u2014 Static content/SEO (SSR, SSG) \u2014 BETA",
17697
+ value: "nextjs"
17698
+ },
17699
+ {
17700
+ title: "Expo \u2014 Mobile app (iOS + Android)",
17701
+ value: "expo"
17702
+ }
17703
+ ]
17704
+ },
17705
+ {
17706
+ id: "host",
17707
+ question: "Where will you host?",
17708
+ type: "select",
17709
+ condition: (answers) => answers.framework !== "expo",
17710
+ defaultValue: (answers) => {
17711
+ return answers.framework === "nextjs" ? "vercel" : "none";
17712
+ },
17713
+ choices: [
17714
+ { title: "None \u2014 no hosting config", value: "none" },
17715
+ { title: "Vercel \u2014 edge CDN + serverless", value: "vercel" },
17716
+ { title: "Firebase Hosting \u2014 Google CDN", value: "firebase" }
17717
+ ]
17718
+ },
17719
+ {
17720
+ id: "functions",
17721
+ question: "Serverless functions?",
17722
+ type: "select",
17723
+ defaultValue: "none",
17724
+ // Choices filtered dynamically based on host
17725
+ choices: [
17726
+ { title: "None", value: "none" },
17727
+ { title: "Vercel Functions \u2014 edge + node.js", value: "vercel" },
17728
+ { title: "Firebase Functions \u2014 Google Cloud", value: "firebase" },
17729
+ { title: "Supabase Edge Functions \u2014 Deno", value: "supabase" }
17730
+ ],
17731
+ choicesFilter: (answers) => {
17732
+ const host = answers.host ?? "none";
17733
+ const framework = answers.framework;
17734
+ if (framework === "expo") return ["none", "firebase", "supabase"];
17735
+ if (host === "firebase") return ["none", "firebase"];
17736
+ if (host === "vercel") return ["none", "vercel", "supabase"];
17737
+ return ["none", "vercel", "firebase", "supabase"];
17738
+ }
17739
+ },
17740
+ {
17741
+ id: "backend",
17742
+ question: "Backend / BaaS provider?",
17743
+ type: "select",
17744
+ defaultValue: (answers) => {
17745
+ if (answers.functions === "firebase") return "firebase";
17746
+ if (answers.functions === "supabase") return "supabase";
17747
+ return "none";
17748
+ },
17749
+ choices: [
17750
+ { title: "None \u2014 frontend only", value: "none" },
17751
+ {
17752
+ title: "Firebase \u2014 Auth + Firestore + Storage",
17753
+ value: "firebase"
17754
+ },
17755
+ {
17756
+ title: "Supabase \u2014 Postgres + Auth + Storage",
17757
+ value: "supabase"
17758
+ }
17759
+ ],
17760
+ choicesFilter: (answers) => {
17761
+ const functions = answers.functions ?? "none";
17762
+ if (functions === "firebase") return ["none", "firebase"];
17763
+ if (functions === "supabase") return ["none", "supabase"];
17764
+ if (functions === "vercel") return ["none"];
17765
+ return ["none", "firebase", "supabase"];
17766
+ }
17767
+ }
17768
+ ];
17769
+ var PROJECT_QUESTIONNAIRE = [
17770
+ {
17771
+ id: "projectName",
17772
+ question: "Project name",
17773
+ type: "input",
17774
+ defaultValue: "my-project"
17775
+ },
17776
+ {
17777
+ id: "appNames",
17778
+ question: `App name(s) (comma-separated for multiple, e.g., web, admin) - '${RESERVED_APP_NAMES.join("', '")}' reserved`,
17779
+ type: "input",
17780
+ defaultValue: "web"
17781
+ }
17782
+ ];
17783
+ function aggregateRequirements(answers) {
17784
+ const hasBackend = answers.backend && answers.backend !== "none" || answers.functions && answers.functions !== "none";
17785
+ const requirements = {
17786
+ entities: [],
17787
+ // Entities created in apps/<app>/entities/ (v1), root entities/ for v2
17788
+ billing: true,
17789
+ // Always on (useStripeBillingSafe handles missing package)
17790
+ backend: hasBackend,
17791
+ features: [],
17792
+ template: "vite",
17793
+ // Only Vite for now
17794
+ userAuth: "social"
17795
+ // Always on (useAuthSafe handles missing package)
17796
+ };
17797
+ return requirements;
17798
+ }
17799
+ async function runQuestionnaire(questions, initialAnswers, showWIP, askFor) {
17800
+ const answers = { ...initialAnswers };
17801
+ for (const question of questions) {
17802
+ if (answers[question.id] !== void 0) continue;
17803
+ if (question.condition && !question.condition(answers)) continue;
17804
+ if (question.dependsOn && !answers[question.dependsOn]) continue;
17805
+ let answer;
17806
+ const resolvedDefault = typeof question.defaultValue === "function" ? question.defaultValue(answers) : question.defaultValue;
17807
+ switch (question.type) {
17808
+ case "select":
17809
+ case "multi-select": {
17810
+ let choices = question.choices || [];
17811
+ if (!showWIP) {
17812
+ choices = choices.filter((choice) => !choice.wip);
17813
+ }
17814
+ if (question.choicesFilter) {
17815
+ const allowed = question.choicesFilter(answers);
17816
+ choices = choices.filter((c) => allowed.includes(c.value));
17817
+ }
17818
+ if (choices.length === 0) continue;
17819
+ answer = await askFor.selection(question.question, choices);
17820
+ break;
17821
+ }
17822
+ case "confirm":
17823
+ answer = await askFor.confirmation(question.question, resolvedDefault);
17824
+ break;
17825
+ case "input":
17826
+ answer = await askFor.input(question.question, resolvedDefault);
17827
+ break;
17828
+ }
17829
+ answers[question.id] = answer;
17830
+ }
17831
+ return answers;
17832
+ }
17833
+
17834
+ // packages/tooling/src/utils/spawn-utils.ts
17835
+ init_utils();
17836
+ init_cli_output();
17837
+ init_errors();
17838
+ init_pathResolver();
17839
+ import {
17840
+ spawn,
17841
+ spawnSync as spawnSync2,
17842
+ execSync
17843
+ } from "node:child_process";
17844
+ import { platform } from "node:os";
17845
+ function createAppEnv(appPath) {
17846
+ return {
17847
+ ...process.env,
17848
+ DNDEV_APP_ROOT: appPath
17849
+ };
17850
+ }
17851
+ function spawnCrossPlatform(command, args, options) {
17852
+ const isWindows = platform() === "win32";
17853
+ const useShell = options.shell ?? isWindows;
17854
+ if (useShell) {
17855
+ const fullCommand = `${command} ${args.join(" ")}`;
17856
+ const { shell: _4, ...rest2 } = options;
17857
+ return spawn(fullCommand, [], { ...rest2, shell: true });
17858
+ }
17859
+ const { shell: _3, ...rest } = options;
17860
+ return spawn(command, args, rest);
17861
+ }
17862
+ function createEmulatorEnv(appPath, framework = "vite", options) {
17863
+ const baseEnv = createAppEnv(appPath);
17864
+ const prefix = framework === "nextjs" ? "NEXT_PUBLIC_" : "VITE_";
17865
+ const useEmulatorAuth = options?.useEmulatorAuth ?? false;
17866
+ const useEmulatorFirestore = options?.useEmulatorFirestore ?? true;
17551
17867
  const env = {
17552
17868
  ...baseEnv,
17553
17869
  [`${prefix}USE_FIREBASE_EMULATOR`]: "true",
@@ -17691,1772 +18007,1220 @@ function safeRemove(path, options = {}) {
17691
18007
  }
17692
18008
  }
17693
18009
 
17694
- // packages/tooling/src/apps/dev.ts
17695
- var SIGNAL_EXIT_CODES = {
17696
- SIGINT: 130,
17697
- // 128 + 2
17698
- SIGTERM: 143
17699
- // 128 + 15
17700
- };
17701
- async function main2() {
17702
- const args = process.argv.slice(2);
17703
- const appName = args[0] && args[0] !== "dev" ? args[0] : void 0;
17704
- const projectRoot = getRepoRoot();
17705
- if (!projectRoot) {
17706
- throw new DoNotDevError(
17707
- "Could not determine repository root",
17708
- "path-resolution-error"
17709
- );
17710
- }
17711
- const app = await selectApp(projectRoot, appName);
17712
- if (!app) {
17713
- return 1;
17714
- }
17715
- log.info(`Starting dev server for ${app.name}...
17716
- `);
17717
- const turboArgs = ["dev", "--filter", app.packageName];
17718
- const isWindows = platform2() === "win32";
17719
- const childProcess = spawnCrossPlatform(
17720
- "bunx",
17721
- ["turbo", ...turboArgs],
17722
- {
17723
- stdio: "inherit",
17724
- env: createAppEnv(app.path),
17725
- cwd: projectRoot
17726
- }
17727
- );
17728
- const cleanup = (signal) => {
17729
- if (!childProcess.pid) return;
17730
- log.debug(`Received ${signal}, cleaning up processes...`);
17731
- if (isWindows) {
17732
- try {
17733
- execSync3(`taskkill /F /T /PID ${childProcess.pid}`, {
17734
- stdio: "ignore",
17735
- timeout: 2e3
17736
- });
17737
- } catch {
17738
- }
17739
- } else {
17740
- try {
17741
- process.kill(childProcess.pid, signal);
17742
- } catch {
17743
- }
17744
- try {
17745
- execSync3(`pkill -P ${childProcess.pid}`, {
17746
- stdio: "ignore",
17747
- timeout: 1e3
17748
- });
17749
- } catch {
17750
- }
17751
- }
17752
- };
17753
- const signals = ["SIGINT", "SIGTERM"];
17754
- const handlers = [];
17755
- for (const signal of signals) {
17756
- const handler = () => {
17757
- cleanup(signal);
17758
- handlers.forEach((h2) => h2());
17759
- process.exit(SIGNAL_EXIT_CODES[signal] ?? 130);
17760
- };
17761
- process.on(signal, handler);
17762
- handlers.push(() => process.removeListener(signal, handler));
17763
- }
17764
- return new Promise((resolve4) => {
17765
- childProcess.on("exit", (code, signal) => {
17766
- handlers.forEach((h2) => h2());
17767
- if (signal) {
17768
- log.debug(`Process killed by signal: ${signal}`);
17769
- resolve4(SIGNAL_EXIT_CODES[signal] ?? 130);
17770
- } else {
17771
- resolve4(code ?? 0);
17772
- }
17773
- });
17774
- childProcess.on("error", (error2) => {
17775
- handlers.forEach((h2) => h2());
17776
- log.error(`Failed to start dev server: ${error2.message}`);
17777
- resolve4(1);
17778
- });
17779
- });
17780
- }
17781
-
17782
- // packages/tooling/src/apps/emu.ts
17783
- init_utils();
17784
-
17785
- // packages/tooling/src/apps/emu-firebase.ts
17786
- init_utils();
17787
- init_cli_input();
17788
- init_cli_output();
17789
- init_pathResolver();
17790
- import { spawnSync as spawnSync3, execSync as execSync4 } from "node:child_process";
17791
- import { platform as platform3 } from "node:os";
17792
- init_typed_file_operations();
17793
- function discoverFirebaseProjectId(appPath) {
17794
- const firebasercPath = joinPath(appPath, ".firebaserc");
17795
- if (pathExists(firebasercPath)) {
17796
- try {
17797
- const firebasercRaw = readSync(firebasercPath, { format: "json" });
17798
- const firebaserc = firebasercRaw && typeof firebasercRaw === "object" ? firebasercRaw : null;
17799
- if (firebaserc?.projects?.default) {
17800
- return firebaserc.projects.default;
17801
- }
17802
- } catch {
17803
- }
17804
- }
17805
- return process.env.FIREBASE_PROJECT_ID || null;
17806
- }
17807
- function killPorts(ports) {
17808
- if (ports.length === 0) return;
17809
- const isWindows = process.platform === "win32";
17810
- for (const port of ports) {
17811
- try {
17812
- if (isWindows) {
17813
- const findPort = execSync4(`netstat -ano | findstr :${port}`, {
17814
- encoding: "utf-8"
17815
- });
17816
- const lines = findPort.trim().split("\n");
17817
- const pids = /* @__PURE__ */ new Set();
17818
- for (const line of lines) {
17819
- const match = line.match(/\s+(\d+)\s*$/);
17820
- if (match && match[1]) {
17821
- pids.add(match[1]);
17822
- }
17823
- }
17824
- for (const pid of Array.from(pids)) {
17825
- try {
17826
- execSync4(`taskkill /F /PID ${pid}`, { stdio: "ignore" });
17827
- log.debug(`Killed process ${pid} on port ${port}`);
17828
- } catch {
17829
- }
17830
- }
17831
- } else {
17832
- try {
17833
- const output = execSync4(`lsof -ti:${port}`, {
17834
- encoding: "utf-8"
17835
- }).trim();
17836
- if (output) {
17837
- const pids = output.split("\n").filter(Boolean);
17838
- for (const pid of pids) {
17839
- try {
17840
- execSync4(`kill -9 ${pid}`, { stdio: "ignore" });
17841
- log.debug(`Killed process ${pid} on port ${port}`);
17842
- } catch {
17843
- }
17844
- }
17845
- }
17846
- } catch {
17847
- }
17848
- }
17849
- } catch {
17850
- }
17851
- }
17852
- }
17853
- function getEmulatorPorts(emulatorConfig) {
17854
- const ports = [];
17855
- if (emulatorConfig?.auth?.port) ports.push(emulatorConfig.auth.port);
17856
- if (emulatorConfig?.functions?.port)
17857
- ports.push(emulatorConfig.functions.port);
17858
- if (emulatorConfig?.firestore?.port)
17859
- ports.push(emulatorConfig.firestore.port);
17860
- if (emulatorConfig?.hosting?.port) ports.push(emulatorConfig.hosting.port);
17861
- if (emulatorConfig?.ui?.port) ports.push(emulatorConfig.ui.port);
17862
- if (!emulatorConfig) {
17863
- ports.push(4e3, 5001, 8080, 9099, 5e3);
17864
- }
17865
- return ports;
17866
- }
17867
- function loadEnvFile(filePath) {
17868
- if (!pathExists(filePath)) return;
17869
- try {
17870
- const content = readSync(filePath, { format: "text" });
17871
- if (!content) return;
17872
- content.split("\n").forEach((line) => {
17873
- const trimmed = line.trim();
17874
- if (!trimmed || trimmed.startsWith("#")) return;
17875
- const equalIndex = trimmed.indexOf("=");
17876
- if (equalIndex === -1) return;
17877
- const key = trimmed.substring(0, equalIndex).trim();
17878
- const value = trimmed.substring(equalIndex + 1).trim().replace(/^["']|["']$/g, "");
17879
- if (key && value) {
17880
- process.env[key] = value;
17881
- }
17882
- });
17883
- } catch {
17884
- }
17885
- }
17886
- async function startFirebase(app, projectRoot, options = {}) {
17887
- const debug = options.debug ?? false;
17888
- let selectedServices = options.selectedServices ?? [];
17889
- const serviceChoices = [
17890
- {
17891
- title: "Auth",
17892
- value: "auth",
17893
- hint: "Firebase Auth emulator (for user authentication)"
17894
- },
17895
- {
17896
- title: "Functions",
17897
- value: "functions",
17898
- hint: "Firebase Functions emulator (required for backend)"
17899
- },
17900
- {
17901
- title: "Firestore",
17902
- value: "firestore",
17903
- hint: "Firestore emulator (for database)"
17904
- },
17905
- {
17906
- title: "Stripe",
17907
- value: "stripe",
17908
- hint: "Stripe webhook forwarding (for payment testing)"
17909
- }
17910
- ];
17911
- log.info(`Starting Firebase emulators + dev server for ${app.name}...
17912
- `);
17913
- if (selectedServices.length === 0) {
17914
- selectedServices = await askForMultiSelection(
17915
- "Which services do you want to run?",
17916
- serviceChoices,
17917
- [1, 2]
17918
- // Default: Functions and Firestore
17919
- );
17920
- } else {
17921
- log.info(`Selected services: ${selectedServices.join(", ")}
17922
- `);
17923
- }
17924
- const useAuth = selectedServices.includes("auth");
17925
- const useFunctions = selectedServices.includes("functions");
17926
- const useFirestore = selectedServices.includes("firestore");
17927
- const useStripe = selectedServices.includes("stripe");
17928
- if (!useFunctions) {
17929
- log.error("Functions emulator is required for Firebase apps.");
17930
- return 1;
17931
- }
17932
- const functionsDir = app.functionsPath;
17933
- const envLocalPath = joinPath(functionsDir, ".env.local");
17934
- if (pathExists(envLocalPath)) {
17935
- loadEnvFile(envLocalPath);
17936
- log.debug("Loaded functions/.env.local for emulator context");
17937
- } else {
17938
- log.warn(
17939
- "No .env.local found in functions directory. Emulator may lack required secrets."
17940
- );
17941
- }
17942
- if (useFunctions) {
17943
- const existingContent = pathExists(envLocalPath) ? readSync(envLocalPath, { format: "text" }) || "" : "";
17944
- const hasAuthEmulatorHost = existingContent.includes(
17945
- "FIREBASE_AUTH_EMULATOR_HOST"
17946
- );
17947
- if (useAuth && !hasAuthEmulatorHost) {
17948
- const authEmulatorHost = "localhost:9099";
17949
- const newContent = existingContent ? `${existingContent}
17950
- FIREBASE_AUTH_EMULATOR_HOST=${authEmulatorHost}
17951
- ` : `FIREBASE_AUTH_EMULATOR_HOST=${authEmulatorHost}
17952
- `;
17953
- writeSync(envLocalPath, newContent);
17954
- log.debug("Set FIREBASE_AUTH_EMULATOR_HOST in functions/.env.local");
17955
- } else if (!useAuth && hasAuthEmulatorHost) {
17956
- const lines = existingContent.split("\n");
17957
- const filteredLines = lines.filter(
17958
- (line) => !line.trim().startsWith("FIREBASE_AUTH_EMULATOR_HOST=")
17959
- );
17960
- const newContent = filteredLines.join("\n");
17961
- writeSync(envLocalPath, newContent);
17962
- log.debug(
17963
- "Removed FIREBASE_AUTH_EMULATOR_HOST from functions/.env.local"
17964
- );
17965
- }
17966
- }
17967
- log.info("Building functions...");
17968
- const buildResult = spawnSync3("bun", ["run", "build"], {
17969
- cwd: functionsDir,
17970
- stdio: "pipe",
17971
- env: createEmulatorEnv(app.path, app.framework, {
17972
- useEmulatorAuth: useAuth,
17973
- useEmulatorFirestore: useFirestore
17974
- })
17975
- });
17976
- if (buildResult.status !== 0) {
17977
- if (buildResult.stdout) {
17978
- process.stdout.write(buildResult.stdout);
17979
- }
17980
- if (buildResult.stderr) {
17981
- process.stderr.write(buildResult.stderr);
17982
- }
17983
- log.error("Functions build failed. Fix errors and try again.");
17984
- return 1;
17985
- }
17986
- const appFirebaseJson = joinPath(app.path, "firebase.json");
17987
- let emulatorConfig = null;
17988
- if (pathExists(appFirebaseJson)) {
17989
- try {
17990
- const firebaseConfig = readFirebaseJson(appFirebaseJson);
17991
- if (firebaseConfig.emulators) {
17992
- emulatorConfig = firebaseConfig.emulators;
17993
- }
17994
- } catch {
17995
- }
17996
- }
17997
- const ports = getEmulatorPorts(emulatorConfig);
17998
- if (ports.length > 0) {
17999
- log.info("Clearing ports...");
18000
- killPorts(ports);
18001
- }
18002
- const emulatorsToStart = [];
18003
- if (useFunctions) emulatorsToStart.push("functions");
18004
- if (useAuth) emulatorsToStart.push("auth");
18005
- if (useFirestore) emulatorsToStart.push("firestore");
18006
- if (emulatorConfig?.hosting) {
18007
- emulatorsToStart.push("hosting");
18008
- }
18009
- const emulatorArgs = ["emulators:start"];
18010
- if (emulatorsToStart.length > 0) {
18011
- emulatorArgs.push("--only", emulatorsToStart.join(","));
18012
- }
18013
- if (debug) {
18014
- emulatorArgs.push("--debug");
18015
- }
18016
- const firebaseToolsPath = joinPath(
18017
- projectRoot,
18018
- "node_modules",
18019
- "firebase-tools",
18020
- "lib",
18021
- "bin",
18022
- "firebase.js"
18023
- );
18024
- const emulatorCmd = `node "${firebaseToolsPath}" ${emulatorArgs.join(" ")}`;
18025
- const projectId = discoverFirebaseProjectId(app.path);
18026
- const region = process.env.FIREBASE_REGION || "europe-west1";
18027
- const concurrentlyArgs = [
18028
- "--kill-others-on-fail",
18029
- "--prefix-colors",
18030
- useStripe ? "cyan,green,yellow" : "cyan,green",
18031
- "--prefix",
18032
- "[{name}]",
18033
- "--names",
18034
- useStripe ? "emulators,dev,stripe" : "emulators,dev",
18035
- emulatorCmd,
18036
- `bunx turbo dev --filter=${app.packageName}`
18037
- ];
18038
- if (useStripe && projectId) {
18039
- const stripeWebhookUrl = `http://localhost:5001/${projectId}/${region}/stripeWebhook`;
18040
- concurrentlyArgs.push(`stripe listen --forward-to ${stripeWebhookUrl}`);
18041
- log.info("");
18042
- log.info("Stripe webhook forwarding will start automatically");
18043
- log.info(` Webhook URL: ${stripeWebhookUrl}`);
18044
- log.info(" To trigger test events, run in another terminal:");
18045
- log.info(" stripe trigger checkout.session.completed");
18046
- log.info("");
18047
- }
18048
- const isWindows = platform3() === "win32";
18049
- const childProcess = spawnCrossPlatform(
18050
- "bunx",
18051
- ["concurrently", ...concurrentlyArgs],
18052
- {
18053
- stdio: "inherit",
18054
- env: createEmulatorEnv(app.path, app.framework, {
18055
- useEmulatorAuth: useAuth,
18056
- useEmulatorFirestore: useFirestore
18057
- }),
18058
- cwd: app.path
18059
- }
18060
- );
18061
- const SIGNAL_EXIT_CODES3 = {
18062
- SIGINT: 130,
18063
- SIGTERM: 143
18064
- };
18065
- const cleanup = (signal) => {
18066
- if (!childProcess.pid) return;
18067
- log.debug(`Received ${signal}, cleaning up processes...`);
18068
- if (isWindows) {
18069
- try {
18070
- execSync4(`taskkill /F /T /PID ${childProcess.pid}`, {
18071
- stdio: "ignore",
18072
- timeout: 2e3
18073
- });
18074
- } catch {
18075
- }
18076
- } else {
18077
- try {
18078
- process.kill(childProcess.pid, signal);
18079
- } catch {
18080
- }
18081
- try {
18082
- execSync4(`pkill -P ${childProcess.pid}`, {
18083
- stdio: "ignore",
18084
- timeout: 1e3
18085
- });
18086
- } catch {
18087
- }
18088
- }
18089
- };
18090
- const signals = ["SIGINT", "SIGTERM"];
18091
- const handlers = [];
18092
- for (const signal of signals) {
18093
- const handler = () => {
18094
- cleanup(signal);
18095
- handlers.forEach((h2) => h2());
18096
- process.exit(SIGNAL_EXIT_CODES3[signal] ?? 130);
18097
- };
18098
- process.on(signal, handler);
18099
- handlers.push(() => process.removeListener(signal, handler));
18100
- }
18101
- return new Promise((resolve4) => {
18102
- childProcess.on("exit", (code, signal) => {
18103
- handlers.forEach((h2) => h2());
18104
- if (signal) {
18105
- log.debug(`Process killed by signal: ${signal}`);
18106
- resolve4(SIGNAL_EXIT_CODES3[signal] ?? 130);
18107
- } else {
18108
- resolve4(code ?? 0);
18109
- }
18110
- });
18111
- childProcess.on("error", (error2) => {
18112
- handlers.forEach((h2) => h2());
18113
- log.error(`Failed to start Firebase emulators: ${error2.message}`);
18114
- resolve4(1);
18115
- });
18116
- });
18117
- }
18118
-
18119
- // packages/tooling/src/apps/emu-supabase.ts
18120
- init_utils();
18121
- init_cli_output();
18122
- import { execSync as execSync5 } from "node:child_process";
18123
- import { platform as platform4 } from "node:os";
18124
- function isDockerRunning() {
18125
- try {
18126
- execSync5("docker info", { stdio: "pipe", timeout: 5e3 });
18127
- return true;
18128
- } catch {
18129
- return false;
18130
- }
18131
- }
18132
- async function startSupabase(app, _projectRoot) {
18133
- log.info(`Starting Supabase local stack + dev server for ${app.name}...
18134
- `);
18135
- if (!isDockerRunning()) {
18136
- log.error("Docker is not running. Supabase local dev requires Docker.");
18137
- log.error("Start Docker Desktop and try again.\n");
18138
- return 1;
18139
- }
18140
- try {
18141
- execSync5("supabase --version", { stdio: "pipe" });
18142
- } catch {
18143
- log.error("Supabase CLI not found. Install it:");
18144
- log.error(" bun install -g supabase\n");
18145
- return 1;
18146
- }
18147
- const isWindows = platform4() === "win32";
18148
- const concurrentlyArgs = [
18149
- "--kill-others-on-fail",
18150
- "--prefix-colors",
18151
- "cyan,green",
18152
- "--prefix",
18153
- "[{name}]",
18154
- "--names",
18155
- "supabase,dev",
18156
- "supabase start",
18157
- `bunx turbo dev --filter=${app.packageName}`
18158
- ];
18159
- const childProcess = spawnCrossPlatform(
18160
- "bunx",
18161
- ["concurrently", ...concurrentlyArgs],
18162
- {
18163
- stdio: "inherit",
18164
- cwd: app.path
18165
- }
18166
- );
18167
- const cleanup = () => {
18168
- if (!childProcess.pid) return;
18169
- if (isWindows) {
18170
- try {
18171
- execSync5(`taskkill /F /T /PID ${childProcess.pid}`, {
18172
- stdio: "ignore",
18173
- timeout: 2e3
18174
- });
18175
- } catch {
18176
- }
18177
- } else {
18178
- try {
18179
- process.kill(childProcess.pid, "SIGTERM");
18180
- } catch {
18181
- }
18182
- }
18183
- };
18184
- process.on("SIGINT", () => {
18185
- cleanup();
18186
- process.exit(130);
18187
- });
18188
- process.on("SIGTERM", () => {
18189
- cleanup();
18190
- process.exit(143);
18191
- });
18192
- return new Promise((resolve4) => {
18193
- childProcess.on("exit", (code) => resolve4(code ?? 0));
18194
- childProcess.on("error", (error2) => {
18195
- log.error(`Failed to start Supabase local dev: ${error2.message}`);
18196
- resolve4(1);
18197
- });
18198
- });
18199
- }
18200
-
18201
- // packages/tooling/src/apps/emu-vercel.ts
18202
- init_utils();
18203
- init_cli_output();
18204
- import { execSync as execSync6 } from "node:child_process";
18205
- import { platform as platform5 } from "node:os";
18206
- async function startVercel(app, _projectRoot) {
18207
- log.info(`Starting Vercel dev server for ${app.name}...
18208
- `);
18209
- try {
18210
- execSync6("vercel --version", { stdio: "pipe" });
18211
- } catch {
18212
- log.error("Vercel CLI not found. Install it:");
18213
- log.error(" bun install -g vercel\n");
18214
- return 1;
18215
- }
18216
- const isWindows = platform5() === "win32";
18217
- const childProcess = spawnCrossPlatform("vercel", ["dev"], {
18218
- stdio: "inherit",
18219
- cwd: app.path
18220
- });
18221
- const cleanup = () => {
18222
- if (!childProcess.pid) return;
18223
- if (isWindows) {
18224
- try {
18225
- execSync6(`taskkill /F /T /PID ${childProcess.pid}`, {
18226
- stdio: "ignore",
18227
- timeout: 2e3
18228
- });
18229
- } catch {
18230
- }
18231
- } else {
18232
- try {
18233
- process.kill(childProcess.pid, "SIGTERM");
18234
- } catch {
18235
- }
18236
- }
18237
- };
18238
- process.on("SIGINT", () => {
18239
- cleanup();
18240
- process.exit(130);
18241
- });
18242
- process.on("SIGTERM", () => {
18243
- cleanup();
18244
- process.exit(143);
18245
- });
18246
- return new Promise((resolve4) => {
18247
- childProcess.on("exit", (code) => resolve4(code ?? 0));
18248
- childProcess.on("error", (error2) => {
18249
- log.error(`Failed to start Vercel dev: ${error2.message}`);
18250
- resolve4(1);
18251
- });
18252
- });
18253
- }
18254
-
18255
- // packages/tooling/src/apps/emu.ts
18256
- init_app_selector();
18257
- init_cli_output();
18258
- init_errors();
18010
+ // packages/tooling/src/apps/deploy-utils.ts
18011
+ init_error_handling();
18259
18012
  init_pathResolver();
18260
- async function main3(options) {
18261
- const args = process.argv.slice(2);
18262
- const projectRoot = getRepoRoot();
18263
- if (!projectRoot) {
18264
- throw new DoNotDevError(
18265
- "Could not determine repository root",
18266
- "path-resolution-error"
18267
- );
18268
- }
18269
- const appName = args.find(
18270
- (arg) => arg !== "emu" && arg !== "--debug" && !arg.startsWith("--")
18271
- );
18272
- const app = await selectApp(projectRoot, appName);
18273
- if (!app) {
18274
- return 1;
18275
- }
18276
- switch (app.platform) {
18277
- case "firebase": {
18278
- if (!app.hasFunctions) {
18279
- log.error(
18280
- `App "${app.name}" has Firebase config but no functions directory.`
18281
- );
18282
- log.error('Use "dndev dev" for apps without backend functions.\n');
18283
- return 1;
18284
- }
18285
- const selectedServices = parseFirebaseServices(args, options);
18286
- return startFirebase(app, projectRoot, {
18287
- debug: options?.debug ?? false,
18288
- selectedServices
18289
- });
18290
- }
18291
- case "supabase":
18292
- return startSupabase(app, projectRoot);
18293
- case "vercel":
18294
- return startVercel(app, projectRoot);
18295
- default:
18296
- log.error(`App "${app.name}" does not have a detected backend platform.`);
18297
- log.error(
18298
- "Expected: firebase.json (Firebase), supabase/config.toml or @donotdev/supabase (Supabase), or vercel.json (Vercel)."
18299
- );
18300
- log.error('Use "dndev dev" for apps without a backend.\n');
18301
- return 1;
18302
- }
18303
- }
18304
- function parseFirebaseServices(args, options) {
18305
- const validServices = ["auth", "functions", "firestore", "stripe"];
18306
- let selectedServices = [];
18307
- if (options?.services) {
18308
- selectedServices = options.services.split(",").map((s) => s.trim());
18309
- } else {
18310
- const servicesArg = args.find((arg) => arg.startsWith("--services="));
18311
- if (servicesArg) {
18312
- const servicesList = servicesArg.split("=")[1];
18313
- if (servicesList) {
18314
- selectedServices = servicesList.split(",").map((s) => s.trim());
18315
- }
18316
- } else {
18317
- if (options?.auth || args.includes("--auth"))
18318
- selectedServices.push("auth");
18319
- if (args.includes("--functions")) selectedServices.push("functions");
18320
- if (options?.firestore || args.includes("--firestore"))
18321
- selectedServices.push("firestore");
18322
- if (options?.stripe || args.includes("--stripe"))
18323
- selectedServices.push("stripe");
18324
- }
18013
+ init_typed_file_operations();
18014
+ function detectAvailableApps() {
18015
+ const currentDir = process.cwd();
18016
+ const appsDir = joinPath(currentDir, "apps");
18017
+ if (!pathExists(appsDir)) {
18018
+ return [];
18325
18019
  }
18326
- return selectedServices.filter((s) => validServices.includes(s));
18020
+ return readdirSync2(appsDir).filter((item) => {
18021
+ const itemPath = joinPath(appsDir, item);
18022
+ const stat2 = statSync2(itemPath);
18023
+ return stat2?.isDirectory() === true;
18024
+ }).filter((app) => {
18025
+ const appDir = joinPath(appsDir, app);
18026
+ const firebaseJsonPath = joinPath(appDir, "firebase.json");
18027
+ const supabaseDir = joinPath(appDir, "supabase");
18028
+ const vercelJsonPath = joinPath(appDir, "vercel.json");
18029
+ return pathExists(firebaseJsonPath) || pathExists(supabaseDir) || pathExists(vercelJsonPath);
18030
+ }).sort();
18327
18031
  }
18328
-
18329
- // packages/tooling/src/apps/preview.ts
18330
- init_utils();
18331
- init_app_selector();
18332
- init_cli_output();
18333
- init_errors();
18334
- init_pathResolver();
18335
- import {
18336
- spawnSync as spawnSync4,
18337
- execSync as execSync7
18338
- } from "node:child_process";
18339
- import { platform as platform6 } from "node:os";
18340
- var SIGNAL_EXIT_CODES2 = {
18341
- SIGINT: 130,
18342
- // 128 + 2
18343
- SIGTERM: 143
18344
- // 128 + 15
18345
- };
18346
- async function main4() {
18347
- const args = process.argv.slice(2);
18348
- const appName = args[0] && args[0] !== "preview" ? args[0] : void 0;
18349
- const projectRoot = getRepoRoot();
18350
- if (!projectRoot) {
18032
+ function detectAppDir(appName) {
18033
+ const currentDir = process.cwd();
18034
+ const appDir = joinPath(currentDir, "apps", appName);
18035
+ if (!pathExists(appDir)) {
18351
18036
  throw new DoNotDevError(
18352
- "Could not determine repository root",
18353
- "path-resolution-error"
18354
- );
18355
- }
18356
- const app = await selectApp(projectRoot, appName);
18357
- if (!app) {
18358
- return 1;
18359
- }
18360
- const distPath = joinPath(app.path, "dist");
18361
- const nextPath = joinPath(app.path, ".next");
18362
- const hasBuild = pathExists(distPath) || pathExists(nextPath);
18363
- if (!hasBuild) {
18364
- log.info(`Build not found. Building ${app.name} first...
18365
- `);
18366
- const buildResult = spawnSync4(
18367
- "bunx",
18368
- ["turbo", "build", "--filter", app.packageName],
18369
- {
18370
- stdio: "inherit",
18371
- env: createAppEnv(app.path),
18372
- cwd: projectRoot
18373
- }
18037
+ `App directory not found: ${appDir}`,
18038
+ "file-not-found",
18039
+ { context: { appName, expectedPath: appDir } }
18374
18040
  );
18375
- if (buildResult.status !== 0) {
18376
- return buildResult.status || 1;
18377
- }
18378
18041
  }
18379
- log.info(`Previewing ${app.name}...
18380
- `);
18381
- const turboArgs = ["preview", "--filter", app.packageName];
18382
- const isWindows = platform6() === "win32";
18383
- const childProcess = spawnCrossPlatform(
18384
- "bunx",
18385
- ["turbo", ...turboArgs],
18386
- {
18387
- stdio: "inherit",
18388
- env: createAppEnv(app.path),
18389
- cwd: projectRoot
18390
- }
18391
- );
18392
- const cleanup = (signal) => {
18393
- if (!childProcess.pid) return;
18394
- log.debug(`Received ${signal}, cleaning up processes...`);
18395
- if (isWindows) {
18396
- try {
18397
- execSync7(`taskkill /F /T /PID ${childProcess.pid}`, {
18398
- stdio: "ignore",
18399
- timeout: 2e3
18400
- });
18401
- } catch {
18402
- }
18403
- } else {
18404
- try {
18405
- process.kill(childProcess.pid, signal);
18406
- } catch {
18407
- }
18408
- try {
18409
- execSync7(`pkill -P ${childProcess.pid}`, {
18410
- stdio: "ignore",
18411
- timeout: 1e3
18412
- });
18413
- } catch {
18042
+ return appDir;
18043
+ }
18044
+ function validateServiceAccount(appDir, options) {
18045
+ const keyFileName = options?.staging ? "service-account-key.staging.json" : "service-account-key.json";
18046
+ const rootKeyPath = joinPath(appDir, keyFileName);
18047
+ const functionsDir = joinPath(appDir, "functions");
18048
+ const functionsKeyPath = joinPath(functionsDir, keyFileName);
18049
+ const keyPath = pathExists(rootKeyPath) ? rootKeyPath : functionsKeyPath;
18050
+ const errors = [];
18051
+ if (!pathExists(keyPath)) {
18052
+ return {
18053
+ valid: false,
18054
+ info: {
18055
+ path: keyPath,
18056
+ projectId: "",
18057
+ clientEmail: "",
18058
+ valid: false,
18059
+ errors: [
18060
+ `Service account key file not found. Checked:`,
18061
+ ` - ${rootKeyPath}`,
18062
+ ` - ${functionsKeyPath}`
18063
+ ]
18414
18064
  }
18415
- }
18416
- };
18417
- const signals = ["SIGINT", "SIGTERM"];
18418
- const handlers = [];
18419
- for (const signal of signals) {
18420
- const handler = () => {
18421
- cleanup(signal);
18422
- handlers.forEach((h2) => h2());
18423
- process.exit(SIGNAL_EXIT_CODES2[signal] ?? 130);
18424
18065
  };
18425
- process.on(signal, handler);
18426
- handlers.push(() => process.removeListener(signal, handler));
18427
18066
  }
18428
- return new Promise((resolve4) => {
18429
- childProcess.on("exit", (code, signal) => {
18430
- handlers.forEach((h2) => h2());
18431
- if (signal) {
18432
- log.debug(`Process killed by signal: ${signal}`);
18433
- resolve4(SIGNAL_EXIT_CODES2[signal] ?? 130);
18434
- } else {
18435
- resolve4(code ?? 0);
18067
+ try {
18068
+ const keyData = readServiceAccountKey(keyPath);
18069
+ return {
18070
+ valid: true,
18071
+ info: {
18072
+ path: keyPath,
18073
+ projectId: keyData.project_id,
18074
+ clientEmail: keyData.client_email,
18075
+ valid: true,
18076
+ errors: []
18436
18077
  }
18437
- });
18438
- childProcess.on("error", (error2) => {
18439
- handlers.forEach((h2) => h2());
18440
- log.error(`Failed to start preview server: ${error2.message}`);
18441
- resolve4(1);
18442
- });
18443
- });
18078
+ };
18079
+ } catch (error2) {
18080
+ return {
18081
+ valid: false,
18082
+ info: {
18083
+ path: keyPath,
18084
+ projectId: "",
18085
+ clientEmail: "",
18086
+ valid: false,
18087
+ errors: [`Invalid service account key: ${getErrorMessage(error2)}`]
18088
+ }
18089
+ };
18090
+ }
18444
18091
  }
18445
-
18446
- // packages/tooling/src/apps/deploy.ts
18447
- init_utils();
18448
- import { execSync as execSync9 } from "node:child_process";
18449
-
18450
- // packages/tooling/src/apps/deploy-frontend.ts
18451
- init_utils();
18452
-
18453
- // packages/tooling/src/utils/create-utils.ts
18454
- init_utils();
18455
- init_cli_output();
18456
- init_pathResolver();
18457
- init_typed_file_operations();
18458
- async function copyTemplateFiles(sourceDir, destDir, replacements) {
18459
- if (!pathExists(sourceDir)) {
18460
- log.warn(`Warning: Template directory does not exist: ${sourceDir}`);
18461
- return;
18092
+ function validateFirebaseJson(appDir) {
18093
+ const firebaseJsonPath = joinPath(appDir, "firebase.json");
18094
+ if (!pathExists(firebaseJsonPath)) {
18095
+ return {
18096
+ valid: false,
18097
+ hasHosting: false,
18098
+ hasFunctions: false,
18099
+ hasFirestoreRules: false,
18100
+ hasFirestoreIndexes: false,
18101
+ hasStorageRules: false,
18102
+ errors: [`firebase.json not found at: ${firebaseJsonPath}`]
18103
+ };
18462
18104
  }
18463
- const files = await glob("**/*", {
18464
- cwd: sourceDir,
18465
- dot: true,
18466
- onlyFiles: true
18467
- });
18468
- for (const file of files) {
18469
- const sourcePath = joinPath(sourceDir, file);
18470
- let destFileName = file;
18471
- if (destFileName.endsWith(".example")) {
18472
- destFileName = destFileName.slice(0, -8);
18473
- }
18474
- const destPath = joinPath(destDir, destFileName);
18475
- await ensureDir(getDirname(destPath));
18476
- await copy(sourcePath, destPath);
18477
- if (await isTextFile(destPath)) {
18478
- await replacePlaceholders(destPath, replacements);
18479
- }
18105
+ try {
18106
+ const config = readFirebaseJson(firebaseJsonPath);
18107
+ const hasHosting = !!config.hosting;
18108
+ const hasFunctions = !!config.functions && Array.isArray(config.functions);
18109
+ const hasFirestoreRules = !!config.firestore?.rules && pathExists(joinPath(appDir, config.firestore.rules));
18110
+ const hasFirestoreIndexes = !!config.firestore?.indexes && pathExists(joinPath(appDir, config.firestore.indexes));
18111
+ const hasStorageRules = !!config.storage?.rules && pathExists(joinPath(appDir, config.storage.rules));
18112
+ return {
18113
+ valid: true,
18114
+ projectId: config.projectId,
18115
+ hasHosting,
18116
+ hasFunctions,
18117
+ hasFirestoreRules,
18118
+ hasFirestoreIndexes,
18119
+ hasStorageRules,
18120
+ errors: []
18121
+ };
18122
+ } catch (error2) {
18123
+ return {
18124
+ valid: false,
18125
+ hasHosting: false,
18126
+ hasFunctions: false,
18127
+ hasFirestoreRules: false,
18128
+ hasFirestoreIndexes: false,
18129
+ hasStorageRules: false,
18130
+ errors: [`Invalid firebase.json: ${getErrorMessage(error2)}`]
18131
+ };
18480
18132
  }
18481
18133
  }
18482
- async function isTextFile(filePath) {
18483
- const binaryExtensions = [
18484
- ".png",
18485
- ".jpg",
18486
- ".jpeg",
18487
- ".gif",
18488
- ".ico",
18489
- ".woff",
18490
- ".woff2",
18491
- ".eot",
18492
- ".ttf",
18493
- ".otf",
18494
- ".zip",
18495
- ".pdf",
18496
- ".exe",
18497
- ".dll",
18498
- ".so",
18499
- ".bin",
18500
- ".dat",
18501
- ".class"
18502
- ];
18503
- if (binaryExtensions.some((ext) => filePath.toLowerCase().endsWith(ext)))
18504
- return false;
18505
- const textExtensions = [
18506
- ".json",
18507
- ".js",
18508
- ".ts",
18509
- ".tsx",
18510
- ".jsx",
18511
- ".md",
18512
- ".yml",
18513
- ".yaml",
18514
- ".html",
18515
- ".css",
18516
- ".scss",
18517
- ".env",
18518
- ".gitignore",
18519
- ".npmrc",
18520
- ".eslintrc",
18521
- ".prettierrc",
18522
- ".firebase",
18523
- ".txt"
18524
- ];
18525
- if (textExtensions.some((ext) => filePath.toLowerCase().endsWith(ext)))
18526
- return true;
18134
+ function validateBuild(appDir) {
18135
+ const distPath = joinPath(appDir, "dist");
18136
+ if (!pathExists(distPath)) {
18137
+ return { exists: false, isEmpty: true, path: distPath };
18138
+ }
18527
18139
  try {
18528
- const buffer = await read(filePath, { format: "buffer" });
18529
- if (buffer.length === 0) return true;
18530
- for (let i = 0; i < Math.min(buffer.length, 1e3); i++) {
18531
- if (buffer[i] === 0) return false;
18532
- }
18533
- return true;
18140
+ const files = readdirSync2(distPath);
18141
+ return {
18142
+ exists: true,
18143
+ isEmpty: files.length === 0,
18144
+ path: distPath
18145
+ };
18534
18146
  } catch {
18535
- return false;
18147
+ return { exists: true, isEmpty: true, path: distPath };
18536
18148
  }
18537
18149
  }
18538
- async function replacePlaceholders(filePath, replacements) {
18539
- try {
18540
- let content = await read(filePath, { format: "text" });
18541
- if (typeof content !== "string") {
18542
- content = typeof content === "object" ? JSON.stringify(content, null, 2) : String(content);
18543
- }
18544
- content = processConditionalSections(content, replacements);
18545
- content = processArrayIterations(content, replacements);
18546
- for (const [key, value] of Object.entries(replacements)) {
18547
- if (value !== void 0) {
18548
- const regex = new RegExp(`{{${key}}}`, "g");
18549
- if (typeof value === "string") {
18550
- content = content.replace(regex, value);
18150
+ function readStagingProject(startDir) {
18151
+ let current = startDir;
18152
+ for (let i = 0; i < 10; i++) {
18153
+ const firebasercPath = joinPath(current, ".firebaserc");
18154
+ if (pathExists(firebasercPath)) {
18155
+ try {
18156
+ const firebaserc = readFirebaserc(firebasercPath);
18157
+ if (firebaserc?.projects?.staging) {
18158
+ return firebaserc.projects.staging;
18551
18159
  }
18160
+ } catch (error2) {
18552
18161
  }
18553
18162
  }
18554
- await write(filePath, content, { overwrite: true });
18555
- } catch (error2) {
18556
- log.warn(
18557
- `Warning: Could not process file ${filePath}: ${error2.message || "Unknown error"}`
18558
- );
18163
+ const parent = joinPath(current, "..");
18164
+ if (parent === current) break;
18165
+ current = parent;
18559
18166
  }
18167
+ return null;
18560
18168
  }
18561
- function processConditionalSections(content, replacements) {
18562
- Object.keys(replacements).forEach((key) => {
18563
- const value = replacements[key];
18564
- const isTruthy = value === true || value === "true";
18565
- const positivePattern = new RegExp(
18566
- `{{#${key}}}([\\s\\S]*?){{/${key}}}`,
18567
- "g"
18568
- );
18569
- if (isTruthy) {
18570
- content = content.replace(positivePattern, (match, inner) => inner);
18571
- } else {
18572
- content = content.replace(positivePattern, "");
18169
+ function checkConfigPlaceholders(appDir) {
18170
+ const CONFIG_FILES = ["vercel.json", "firebase.json", ".firebaserc"];
18171
+ const bad = [];
18172
+ for (const file of CONFIG_FILES) {
18173
+ const filePath = joinPath(appDir, file);
18174
+ if (!pathExists(filePath)) continue;
18175
+ const content = readSync(filePath, { format: "text" });
18176
+ if (typeof content === "string" && (content.includes("{{") || content.includes("}}"))) {
18177
+ bad.push(file);
18573
18178
  }
18574
- const negativePattern = new RegExp(
18575
- `{{\\^${key}}}([\\s\\S]*?){{/${key}}}`,
18576
- "g"
18179
+ }
18180
+ if (bad.length > 0) {
18181
+ log.warn(`Unreplaced template placeholders found in: ${bad.join(", ")}`);
18182
+ log.warn(` Fix manually or re-run "dndev init" to regenerate.
18183
+ `);
18184
+ }
18185
+ return bad.length > 0;
18186
+ }
18187
+ async function showServiceAccountError(info2, projectId) {
18188
+ const consoleUrl = projectId ? `https://console.firebase.google.com/project/${projectId}/settings/serviceaccounts/adminsdk` : "https://console.firebase.google.com/project/YOUR_PROJECT/settings/serviceaccounts/adminsdk";
18189
+ const errorList = info2.errors.map((e2) => `\u2022 ${e2}`).join("\n");
18190
+ Me(
18191
+ `${errorList}
18192
+
18193
+ Why it matters:
18194
+ Firebase CLI needs service account credentials to deploy.
18195
+ Without valid credentials, deployment will fail.
18196
+
18197
+ How to fix:
18198
+ 1. Go to Firebase Console:
18199
+ ${consoleUrl}
18200
+ 2. Click "Generate New Private Key"
18201
+ 3. Save the JSON file as: ${info2.path}
18202
+ 4. Required IAM roles:
18203
+ \u2022 Firebase Hosting Admin (for frontend)
18204
+ \u2022 Cloud Functions Admin (for functions)
18205
+ \u2022 Or Firebase Admin (covers both)`,
18206
+ "Service Account Error"
18207
+ );
18208
+ if (projectId) {
18209
+ const shouldOpen = await askForConfirmation(
18210
+ "Open Firebase Console now?",
18211
+ true
18577
18212
  );
18578
- if (!isTruthy) {
18579
- content = content.replace(negativePattern, (match, inner) => inner);
18213
+ if (shouldOpen) {
18214
+ try {
18215
+ const openCommand = process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open";
18216
+ spawnSync3(`${openCommand} ${consoleUrl}`, { shell: true });
18217
+ log.success("Opening Firebase Console...");
18218
+ } catch {
18219
+ log.warn("Could not open browser. Please open the URL manually.");
18220
+ }
18221
+ }
18222
+ }
18223
+ }
18224
+ function showFirebaseJsonError(errors, appDir, deploymentType) {
18225
+ const errorList = errors.map((e2) => `\u2022 ${e2}`).join("\n");
18226
+ const firebaseJsonPath = joinPath(appDir, "firebase.json");
18227
+ let configExample = "";
18228
+ if (deploymentType === "frontend" || deploymentType === "both") {
18229
+ configExample += `
18230
+ Hosting config:
18231
+ { "hosting": { "public": "dist", ... } }`;
18232
+ }
18233
+ if (deploymentType === "functions" || deploymentType === "both") {
18234
+ configExample += `
18235
+ Functions config:
18236
+ { "functions": [{ "source": "functions", ... }] }`;
18237
+ }
18238
+ Me(
18239
+ `${errorList}
18240
+
18241
+ Why it matters:
18242
+ firebase.json defines your deployment configuration.
18243
+ Without it, Firebase CLI doesn't know what to deploy.
18244
+
18245
+ How to fix:
18246
+ 1. Ensure firebase.json exists at: ${firebaseJsonPath}
18247
+ 2. Add required configuration:${configExample}`,
18248
+ "Firebase Configuration Error"
18249
+ );
18250
+ }
18251
+ function clearFirebaseCache(appDir) {
18252
+ const firebaseCacheDir = joinPath(appDir, ".firebase");
18253
+ if (pathExists(firebaseCacheDir)) {
18254
+ log.info("Clearing Firebase cache...");
18255
+ const removed = safeRemove(firebaseCacheDir, { silent: true });
18256
+ if (removed) {
18257
+ log.success("Firebase cache cleared");
18580
18258
  } else {
18581
- content = content.replace(negativePattern, "");
18259
+ log.warn("Could not clear Firebase cache (non-critical)");
18582
18260
  }
18583
- });
18584
- return content;
18585
- }
18586
- function processArrayIterations(content, replacements) {
18587
- const appNamesPattern = /{{#appNames}}([\s\S]*?){{\/appNames}}/g;
18588
- if (replacements.appNames && Array.isArray(replacements.appNames)) {
18589
- const appNames = replacements.appNames;
18590
- content = content.replace(appNamesPattern, (match, templateContent) => {
18591
- return appNames.map((appName) => templateContent.replace(/{{\.}}/g, appName)).join("");
18592
- });
18593
- } else {
18594
- content = content.replace(appNamesPattern, "");
18595
18261
  }
18596
- return content;
18597
- }
18598
- function isValidFileName(name) {
18599
- return typeof name === "string" && /^[a-zA-Z0-9_-]+$/.test(name);
18600
- }
18601
- var RESERVED_APP_NAMES = ["demo", "dndev"];
18602
- function isReservedAppName(name) {
18603
- return RESERVED_APP_NAMES.includes(
18604
- name.toLowerCase()
18605
- );
18606
18262
  }
18607
- async function updateRootPackageJson(rootDir, appNames) {
18608
- const packageJsonPath = joinPath(rootDir, "package.json");
18609
- if (!pathExists(packageJsonPath)) {
18610
- log.warn("Root package.json not found, skipping script updates");
18611
- return;
18263
+
18264
+ // packages/tooling/src/apps/build.ts
18265
+ function validateFirebaseJson2(appDir) {
18266
+ const firebaseJsonPath = joinPath(appDir, "firebase.json");
18267
+ if (!pathExists(firebaseJsonPath)) {
18268
+ return {
18269
+ valid: false,
18270
+ hasHosting: false,
18271
+ hasFunctions: false
18272
+ };
18612
18273
  }
18613
18274
  try {
18614
- const packageJson = await read(packageJsonPath, { format: "json" });
18615
- packageJson.scripts = packageJson.scripts || {};
18616
- } catch (error2) {
18617
- log.warn(
18618
- `Warning: Could not update root package.json: ${error2.message || "Unknown error"}`
18619
- );
18275
+ const config = readFirebaseJson(firebaseJsonPath);
18276
+ if (!config.projectId) {
18277
+ return {
18278
+ valid: false,
18279
+ hasHosting: false,
18280
+ hasFunctions: false
18281
+ };
18282
+ }
18283
+ return {
18284
+ valid: true,
18285
+ hasHosting: !!config.hosting,
18286
+ hasFunctions: !!config.functions && Array.isArray(config.functions)
18287
+ };
18288
+ } catch {
18289
+ return {
18290
+ valid: false,
18291
+ hasHosting: false,
18292
+ hasFunctions: false
18293
+ };
18620
18294
  }
18621
18295
  }
18622
- async function mergeRootPackageJson(rootDir, allAppNames, options = {}) {
18623
- const packageJsonPath = joinPath(rootDir, "package.json");
18624
- if (!pathExists(packageJsonPath)) {
18625
- log.warn("Root package.json not found, skipping merge");
18626
- return;
18627
- }
18628
- try {
18629
- const packageJson = await read(packageJsonPath, { format: "json" });
18630
- packageJson.scripts = packageJson.scripts || {};
18631
- } catch (error2) {
18632
- log.warn(
18633
- `Warning: Could not merge root package.json: ${error2.message || "Unknown error"}`
18634
- );
18296
+ function parseBuildArgs(args) {
18297
+ const result = {};
18298
+ for (const arg of args) {
18299
+ if (arg === ":front" || arg === ":frontend" || arg === "front" || arg === "frontend") {
18300
+ result.buildType = "frontend";
18301
+ } else if (arg === ":func" || arg === ":functions" || arg === "func" || arg === "functions") {
18302
+ result.buildType = "functions";
18303
+ } else if (arg === ":both" || arg === "both") {
18304
+ result.buildType = "both";
18305
+ } else if (arg.includes(":")) {
18306
+ const parts = arg.split(":");
18307
+ result.appName = parts[0];
18308
+ const typePart = parts[1];
18309
+ if (typePart === "front" || typePart === "frontend") {
18310
+ result.buildType = "frontend";
18311
+ } else if (typePart === "func" || typePart === "functions") {
18312
+ result.buildType = "functions";
18313
+ } else if (typePart === "both") {
18314
+ result.buildType = "both";
18315
+ }
18316
+ } else if (!arg.startsWith(":") && arg !== "build") {
18317
+ result.appName = arg;
18318
+ }
18635
18319
  }
18320
+ return result;
18636
18321
  }
18637
- async function mergeRootTsConfig(rootDir, allAppNames, includeFunctions = false) {
18638
- const tsconfigPath = joinPath(rootDir, "tsconfig.json");
18639
- if (!pathExists(tsconfigPath)) {
18640
- log.warn("Root tsconfig.json not found, skipping merge");
18641
- return;
18322
+ async function main() {
18323
+ const args = process.argv.slice(2);
18324
+ const { appName: parsedAppName, buildType: parsedBuildType } = parseBuildArgs(args);
18325
+ const debugMode = process.env.DEBUG === "true" || process.env.DEBUG === "1" || args.includes("--debug") || args.includes("-d");
18326
+ if (debugMode) {
18327
+ log.debug(` Args: ${args.join(" ")}`);
18328
+ log.debug(
18329
+ ` Parsed app: ${parsedAppName || "none"}, build type: ${parsedBuildType || "none"}
18330
+ `
18331
+ );
18642
18332
  }
18643
- try {
18644
- const tsconfig = readTsConfigJson(tsconfigPath);
18645
- tsconfig.references = tsconfig.references || [];
18646
- const existingPaths = new Set(
18647
- tsconfig.references.map((ref) => ref.path)
18333
+ const projectRoot = getRepoRoot();
18334
+ if (!projectRoot) {
18335
+ throw new DoNotDevError(
18336
+ "Could not determine repository root",
18337
+ "path-resolution-error"
18648
18338
  );
18649
- let updated = false;
18650
- for (const appName of allAppNames) {
18651
- const appPath = `${appName}-app`;
18652
- if (!existingPaths.has(appPath)) {
18653
- tsconfig.references.push({ path: appPath });
18654
- updated = true;
18655
- }
18339
+ }
18340
+ const app = await selectApp(projectRoot, parsedAppName);
18341
+ if (!app) {
18342
+ return 1;
18343
+ }
18344
+ const appDir = app.path;
18345
+ checkConfigPlaceholders(appDir);
18346
+ const firebaseConfig = validateFirebaseJson2(appDir);
18347
+ const hasFunctions = app.hasFunctions || firebaseConfig.hasFunctions;
18348
+ const hasFrontend = app.framework !== "unknown";
18349
+ let buildType = parsedBuildType;
18350
+ if (!buildType) {
18351
+ const choices = [];
18352
+ if (hasFrontend) {
18353
+ choices.push({
18354
+ title: "Frontend only",
18355
+ value: "frontend",
18356
+ hint: "Build app bundle"
18357
+ });
18656
18358
  }
18657
- if (includeFunctions && !existingPaths.has("functions")) {
18658
- tsconfig.references.push({ path: "functions" });
18659
- updated = true;
18359
+ if (hasFunctions) {
18360
+ choices.push({
18361
+ title: "Functions only",
18362
+ value: "functions",
18363
+ hint: "Build cloud functions"
18364
+ });
18660
18365
  }
18661
- if (updated) {
18662
- await write(tsconfigPath, tsconfig, { format: "json", overwrite: true });
18663
- log.info("Merged root tsconfig.json");
18366
+ if (hasFrontend && hasFunctions) {
18367
+ choices.push({
18368
+ title: "Both frontend and functions",
18369
+ value: "both",
18370
+ hint: "Build everything"
18371
+ });
18372
+ }
18373
+ if (choices.length === 0) {
18374
+ log.error("No build targets found. App must have frontend or functions.");
18375
+ throw new DoNotDevError("No build targets found", "validation-error");
18376
+ }
18377
+ if (choices.length === 1) {
18378
+ buildType = choices[0].value;
18379
+ Me(`Building: ${choices[0].title}`, "Auto-selected");
18380
+ } else {
18381
+ buildType = await askForSelection(
18382
+ "What would you like to build?",
18383
+ choices
18384
+ );
18664
18385
  }
18665
- } catch (error2) {
18666
- log.warn(
18667
- `Warning: Could not merge root tsconfig.json: ${error2.message || "Unknown error"}`
18668
- );
18669
- }
18670
- }
18671
- async function mergeRootTurboJson(rootDir) {
18672
- const turboJsonPath = joinPath(rootDir, "turbo.json");
18673
- if (!pathExists(turboJsonPath)) {
18674
- log.warn("Root turbo.json not found, skipping merge");
18675
- return;
18676
18386
  }
18677
- try {
18678
- const turboJson = readTurboJson(turboJsonPath);
18679
- if (!turboJson) {
18680
- throw new Error(
18681
- `turbo.json is empty or invalid JSON at ${turboJsonPath}`
18387
+ if (buildType === "frontend" || buildType === "both") {
18388
+ if (!hasFrontend) {
18389
+ log.error(
18390
+ "Frontend build requested but app has no frontend configuration."
18391
+ );
18392
+ throw new DoNotDevError(
18393
+ "Frontend build requested but app has no frontend configuration",
18394
+ "validation-error"
18682
18395
  );
18683
18396
  }
18684
- turboJson.tasks = turboJson.tasks || {};
18685
- const defaultTasks = {
18686
- build: {
18687
- dependsOn: ["^build"],
18688
- outputs: ["*/dist/**", "!**/node_modules/**"]
18689
- },
18690
- preview: {
18691
- dependsOn: ["build"],
18692
- cache: false,
18693
- persistent: true
18694
- },
18695
- test: {
18696
- dependsOn: ["^build"],
18697
- outputs: ["coverage/**"]
18698
- },
18699
- lint: {
18700
- outputs: []
18701
- },
18702
- dev: {
18703
- cache: false,
18704
- persistent: true
18705
- },
18706
- clean: {
18707
- cache: false
18708
- }
18397
+ log.info(`Building ${app.name} frontend...
18398
+ `);
18399
+ const turboArgs = ["build", "--filter", app.packageName];
18400
+ const env = {
18401
+ ...process.env,
18402
+ DNDEV_APP_ROOT: app.path
18709
18403
  };
18710
- let updated = false;
18711
- for (const [taskName, taskConfig] of Object.entries(defaultTasks)) {
18712
- if (!turboJson.tasks[taskName]) {
18713
- turboJson.tasks[taskName] = taskConfig;
18714
- updated = true;
18715
- }
18404
+ const result = spawnSync4("bunx", ["turbo", ...turboArgs], {
18405
+ stdio: "inherit",
18406
+ env,
18407
+ cwd: projectRoot
18408
+ });
18409
+ if (result.status !== 0) {
18410
+ return result.status || 1;
18716
18411
  }
18717
- if (!turboJson.globalDependencies) {
18718
- turboJson.globalDependencies = ["**/.env.*local"];
18719
- updated = true;
18412
+ }
18413
+ if (buildType === "functions" || buildType === "both") {
18414
+ if (!hasFunctions) {
18415
+ log.error(
18416
+ "Functions build requested but app has no functions directory."
18417
+ );
18418
+ throw new DoNotDevError(
18419
+ "Functions build requested but app has no functions directory",
18420
+ "validation-error"
18421
+ );
18720
18422
  }
18721
- if (updated) {
18722
- await write(turboJsonPath, turboJson, {
18723
- format: "json",
18724
- overwrite: true
18423
+ const functionsDir = joinPath(appDir, "functions");
18424
+ if (!pathExists(functionsDir)) {
18425
+ log.error(`Functions directory not found: ${functionsDir}`);
18426
+ throw new DoNotDevError(
18427
+ `Functions directory not found: ${functionsDir}`,
18428
+ "file-not-found"
18429
+ );
18430
+ }
18431
+ log.info(`Building ${app.name} functions...
18432
+ `);
18433
+ const s = Y2();
18434
+ s.start("Building functions...");
18435
+ try {
18436
+ execSync2("bun run build", {
18437
+ cwd: functionsDir,
18438
+ stdio: "inherit"
18725
18439
  });
18726
- log.info("Merged root turbo.json");
18440
+ s.stop("Functions built");
18441
+ } catch (error2) {
18442
+ s.stop("\u274C Functions build failed");
18443
+ throw DoNotDevError.from(
18444
+ error2,
18445
+ "Functions build failed",
18446
+ "cli-execution-error"
18447
+ );
18727
18448
  }
18728
- } catch (error2) {
18729
- log.warn(
18730
- `Warning: Could not merge root turbo.json: ${error2 instanceof Error ? error2.message : String(error2)}`
18731
- );
18732
18449
  }
18450
+ log.success(`Build complete for ${app.name}`);
18451
+ return 0;
18733
18452
  }
18734
18453
 
18735
- // packages/tooling/src/utils/matrix.ts
18454
+ // packages/tooling/src/apps/dev.ts
18736
18455
  init_utils();
18456
+ init_app_selector();
18457
+ init_cli_output();
18458
+ init_errors();
18737
18459
  init_pathResolver();
18738
- import { createRequire as createRequire4 } from "node:module";
18739
- var cachedMatrix = null;
18740
- function getMatrixPath(mode) {
18741
- try {
18742
- const require3 = createRequire4(import.meta.url);
18743
- const resolved = require3.resolve("@donotdev/cli/dependencies-matrix.json");
18744
- if (pathExists(resolved)) {
18745
- return resolved;
18746
- }
18747
- } catch {
18748
- }
18749
- const executionMode = mode || detectExecutionMode();
18750
- if (executionMode === "development") {
18751
- const templatesRoot = getTemplatesRoot();
18752
- const devPath = normalizePath(
18753
- templatesRoot,
18754
- "..",
18755
- "dependencies-matrix.json"
18460
+ import { execSync as execSync3 } from "node:child_process";
18461
+ import { platform as platform2 } from "node:os";
18462
+ var SIGNAL_EXIT_CODES = {
18463
+ SIGINT: 130,
18464
+ // 128 + 2
18465
+ SIGTERM: 143
18466
+ // 128 + 15
18467
+ };
18468
+ async function main2() {
18469
+ const args = process.argv.slice(2);
18470
+ const appName = args[0] && args[0] !== "dev" ? args[0] : void 0;
18471
+ const projectRoot = getRepoRoot();
18472
+ if (!projectRoot) {
18473
+ throw new DoNotDevError(
18474
+ "Could not determine repository root",
18475
+ "path-resolution-error"
18756
18476
  );
18757
- if (pathExists(devPath)) {
18758
- return devPath;
18759
- }
18760
18477
  }
18761
- return null;
18762
- }
18763
- function getCliVersion(mode) {
18764
- try {
18765
- const require3 = createRequire4(import.meta.url);
18766
- const packageJsonPath = require3.resolve("@donotdev/cli/package.json");
18767
- const pkg = readSync(packageJsonPath, { format: "json" });
18768
- return String(pkg?.version || "0.0.0");
18769
- } catch {
18478
+ const app = await selectApp(projectRoot, appName);
18479
+ if (!app) {
18480
+ return 1;
18770
18481
  }
18771
- const executionMode = mode || detectExecutionMode();
18772
- if (executionMode === "development") {
18773
- const templatesRoot = getTemplatesRoot();
18774
- const cliPackageJson = normalizePath(templatesRoot, "..", "package.json");
18775
- if (pathExists(cliPackageJson)) {
18776
- const pkg = readSync(cliPackageJson, { format: "json" });
18777
- return String(pkg?.version || "0.0.0");
18482
+ log.info(`Starting dev server for ${app.name}...
18483
+ `);
18484
+ const turboArgs = ["dev", "--filter", app.packageName];
18485
+ const isWindows = platform2() === "win32";
18486
+ const childProcess = spawnCrossPlatform(
18487
+ "bunx",
18488
+ ["turbo", ...turboArgs],
18489
+ {
18490
+ stdio: "inherit",
18491
+ env: createAppEnv(app.path),
18492
+ cwd: projectRoot
18778
18493
  }
18779
- }
18780
- return "0.0.0";
18781
- }
18782
- function loadMatrix(mode) {
18783
- if (cachedMatrix) return cachedMatrix;
18784
- const matrixPath = getMatrixPath(mode);
18785
- if (!matrixPath) {
18786
- return null;
18787
- }
18788
- const content = readSync(matrixPath, { format: "json" });
18789
- if (!content) {
18790
- return null;
18791
- }
18792
- cachedMatrix = {
18793
- matrix: content,
18794
- cliVersion: getCliVersion(mode)
18795
- };
18796
- return cachedMatrix;
18797
- }
18798
- function resolveGroup(groupName, matrix) {
18799
- return matrix.groups[groupName]?.packages || {};
18800
- }
18801
- function resolveGroups(groupNames, matrix) {
18802
- const result = {};
18803
- for (const groupName of groupNames) {
18804
- Object.assign(result, resolveGroup(groupName, matrix));
18805
- }
18806
- return result;
18807
- }
18808
-
18809
- // packages/tooling/src/utils/scaffolding-questionnaire.ts
18810
- init_utils();
18811
- var APP_QUESTIONNAIRE = [
18812
- {
18813
- id: "framework",
18814
- question: "Which framework?",
18815
- type: "select",
18816
- defaultValue: "vite",
18817
- choices: [
18818
- {
18819
- title: "Vite \u2014 SPA/SaaS (client-side rendering, fast dev)",
18820
- value: "vite"
18821
- },
18822
- {
18823
- title: "Next.js \u2014 Static content/SEO (SSR, SSG) \u2014 BETA",
18824
- value: "nextjs"
18825
- },
18826
- {
18827
- title: "Expo \u2014 Mobile app (iOS + Android)",
18828
- value: "expo"
18494
+ );
18495
+ const cleanup = (signal) => {
18496
+ if (!childProcess.pid) return;
18497
+ log.debug(`Received ${signal}, cleaning up processes...`);
18498
+ if (isWindows) {
18499
+ try {
18500
+ execSync3(`taskkill /F /T /PID ${childProcess.pid}`, {
18501
+ stdio: "ignore",
18502
+ timeout: 2e3
18503
+ });
18504
+ } catch {
18505
+ }
18506
+ } else {
18507
+ try {
18508
+ process.kill(childProcess.pid, signal);
18509
+ } catch {
18510
+ }
18511
+ try {
18512
+ execSync3(`pkill -P ${childProcess.pid}`, {
18513
+ stdio: "ignore",
18514
+ timeout: 1e3
18515
+ });
18516
+ } catch {
18829
18517
  }
18830
- ]
18831
- },
18832
- {
18833
- id: "host",
18834
- question: "Where will you host?",
18835
- type: "select",
18836
- condition: (answers) => answers.framework !== "expo",
18837
- defaultValue: (answers) => {
18838
- return answers.framework === "nextjs" ? "vercel" : "none";
18839
- },
18840
- choices: [
18841
- { title: "None \u2014 no hosting config", value: "none" },
18842
- { title: "Vercel \u2014 edge CDN + serverless", value: "vercel" },
18843
- { title: "Firebase Hosting \u2014 Google CDN", value: "firebase" }
18844
- ]
18845
- },
18846
- {
18847
- id: "functions",
18848
- question: "Serverless functions?",
18849
- type: "select",
18850
- defaultValue: "none",
18851
- // Choices filtered dynamically based on host
18852
- choices: [
18853
- { title: "None", value: "none" },
18854
- { title: "Vercel Functions \u2014 edge + node.js", value: "vercel" },
18855
- { title: "Firebase Functions \u2014 Google Cloud", value: "firebase" },
18856
- { title: "Supabase Edge Functions \u2014 Deno", value: "supabase" }
18857
- ],
18858
- choicesFilter: (answers) => {
18859
- const host = answers.host ?? "none";
18860
- const framework = answers.framework;
18861
- if (framework === "expo") return ["none", "firebase", "supabase"];
18862
- if (host === "firebase") return ["none", "firebase"];
18863
- if (host === "vercel") return ["none", "vercel", "supabase"];
18864
- return ["none", "vercel", "firebase", "supabase"];
18865
18518
  }
18866
- },
18867
- {
18868
- id: "backend",
18869
- question: "Backend / BaaS provider?",
18870
- type: "select",
18871
- defaultValue: (answers) => {
18872
- if (answers.functions === "firebase") return "firebase";
18873
- if (answers.functions === "supabase") return "supabase";
18874
- return "none";
18875
- },
18876
- choices: [
18877
- { title: "None \u2014 frontend only", value: "none" },
18878
- {
18879
- title: "Firebase \u2014 Auth + Firestore + Storage",
18880
- value: "firebase"
18881
- },
18882
- {
18883
- title: "Supabase \u2014 Postgres + Auth + Storage",
18884
- value: "supabase"
18519
+ };
18520
+ const signals = ["SIGINT", "SIGTERM"];
18521
+ const handlers = [];
18522
+ for (const signal of signals) {
18523
+ const handler = () => {
18524
+ cleanup(signal);
18525
+ handlers.forEach((h2) => h2());
18526
+ process.exit(SIGNAL_EXIT_CODES[signal] ?? 130);
18527
+ };
18528
+ process.on(signal, handler);
18529
+ handlers.push(() => process.removeListener(signal, handler));
18530
+ }
18531
+ return new Promise((resolve4) => {
18532
+ childProcess.on("exit", (code, signal) => {
18533
+ handlers.forEach((h2) => h2());
18534
+ if (signal) {
18535
+ log.debug(`Process killed by signal: ${signal}`);
18536
+ resolve4(SIGNAL_EXIT_CODES[signal] ?? 130);
18537
+ } else {
18538
+ resolve4(code ?? 0);
18885
18539
  }
18886
- ],
18887
- choicesFilter: (answers) => {
18888
- const functions = answers.functions ?? "none";
18889
- if (functions === "firebase") return ["none", "firebase"];
18890
- if (functions === "supabase") return ["none", "supabase"];
18891
- if (functions === "vercel") return ["none"];
18892
- return ["none", "firebase", "supabase"];
18540
+ });
18541
+ childProcess.on("error", (error2) => {
18542
+ handlers.forEach((h2) => h2());
18543
+ log.error(`Failed to start dev server: ${error2.message}`);
18544
+ resolve4(1);
18545
+ });
18546
+ });
18547
+ }
18548
+
18549
+ // packages/tooling/src/apps/emu.ts
18550
+ init_utils();
18551
+
18552
+ // packages/tooling/src/apps/emu-firebase.ts
18553
+ init_utils();
18554
+ init_cli_input();
18555
+ init_cli_output();
18556
+ init_pathResolver();
18557
+ import { spawnSync as spawnSync5, execSync as execSync4 } from "node:child_process";
18558
+ import { platform as platform3 } from "node:os";
18559
+ init_typed_file_operations();
18560
+ function discoverFirebaseProjectId(appPath) {
18561
+ const firebasercPath = joinPath(appPath, ".firebaserc");
18562
+ if (pathExists(firebasercPath)) {
18563
+ try {
18564
+ const firebasercRaw = readSync(firebasercPath, { format: "json" });
18565
+ const firebaserc = firebasercRaw && typeof firebasercRaw === "object" ? firebasercRaw : null;
18566
+ if (firebaserc?.projects?.default) {
18567
+ return firebaserc.projects.default;
18568
+ }
18569
+ } catch {
18893
18570
  }
18894
18571
  }
18895
- ];
18896
- var PROJECT_QUESTIONNAIRE = [
18897
- {
18898
- id: "projectName",
18899
- question: "Project name",
18900
- type: "input",
18901
- defaultValue: "my-project"
18902
- },
18903
- {
18904
- id: "appNames",
18905
- question: `App name(s) (comma-separated for multiple, e.g., web, admin) - '${RESERVED_APP_NAMES.join("', '")}' reserved`,
18906
- type: "input",
18907
- defaultValue: "web"
18908
- }
18909
- ];
18910
- function aggregateRequirements(answers) {
18911
- const hasBackend = answers.backend && answers.backend !== "none" || answers.functions && answers.functions !== "none";
18912
- const requirements = {
18913
- entities: [],
18914
- // Entities created in apps/<app>/entities/ (v1), root entities/ for v2
18915
- billing: true,
18916
- // Always on (useStripeBillingSafe handles missing package)
18917
- backend: hasBackend,
18918
- features: [],
18919
- template: "vite",
18920
- // Only Vite for now
18921
- userAuth: "social"
18922
- // Always on (useAuthSafe handles missing package)
18923
- };
18924
- return requirements;
18572
+ return process.env.FIREBASE_PROJECT_ID || null;
18925
18573
  }
18926
- async function runQuestionnaire(questions, initialAnswers, showWIP, askFor) {
18927
- const answers = { ...initialAnswers };
18928
- for (const question of questions) {
18929
- if (answers[question.id] !== void 0) continue;
18930
- if (question.condition && !question.condition(answers)) continue;
18931
- if (question.dependsOn && !answers[question.dependsOn]) continue;
18932
- let answer;
18933
- const resolvedDefault = typeof question.defaultValue === "function" ? question.defaultValue(answers) : question.defaultValue;
18934
- switch (question.type) {
18935
- case "select":
18936
- case "multi-select": {
18937
- let choices = question.choices || [];
18938
- if (!showWIP) {
18939
- choices = choices.filter((choice) => !choice.wip);
18574
+ function killPorts(ports) {
18575
+ if (ports.length === 0) return;
18576
+ const isWindows = process.platform === "win32";
18577
+ for (const port of ports) {
18578
+ try {
18579
+ if (isWindows) {
18580
+ const findPort = execSync4(`netstat -ano | findstr :${port}`, {
18581
+ encoding: "utf-8"
18582
+ });
18583
+ const lines = findPort.trim().split("\n");
18584
+ const pids = /* @__PURE__ */ new Set();
18585
+ for (const line of lines) {
18586
+ const match = line.match(/\s+(\d+)\s*$/);
18587
+ if (match && match[1]) {
18588
+ pids.add(match[1]);
18589
+ }
18940
18590
  }
18941
- if (question.choicesFilter) {
18942
- const allowed = question.choicesFilter(answers);
18943
- choices = choices.filter((c) => allowed.includes(c.value));
18591
+ for (const pid of Array.from(pids)) {
18592
+ try {
18593
+ execSync4(`taskkill /F /PID ${pid}`, { stdio: "ignore" });
18594
+ log.debug(`Killed process ${pid} on port ${port}`);
18595
+ } catch {
18596
+ }
18597
+ }
18598
+ } else {
18599
+ try {
18600
+ const output = execSync4(`lsof -ti:${port}`, {
18601
+ encoding: "utf-8"
18602
+ }).trim();
18603
+ if (output) {
18604
+ const pids = output.split("\n").filter(Boolean);
18605
+ for (const pid of pids) {
18606
+ try {
18607
+ execSync4(`kill -9 ${pid}`, { stdio: "ignore" });
18608
+ log.debug(`Killed process ${pid} on port ${port}`);
18609
+ } catch {
18610
+ }
18611
+ }
18612
+ }
18613
+ } catch {
18944
18614
  }
18945
- if (choices.length === 0) continue;
18946
- answer = await askFor.selection(question.question, choices);
18947
- break;
18948
18615
  }
18949
- case "confirm":
18950
- answer = await askFor.confirmation(question.question, resolvedDefault);
18951
- break;
18952
- case "input":
18953
- answer = await askFor.input(question.question, resolvedDefault);
18954
- break;
18616
+ } catch {
18955
18617
  }
18956
- answers[question.id] = answer;
18957
18618
  }
18958
- return answers;
18959
18619
  }
18960
-
18961
- // packages/tooling/src/apps/deploy-frontend.ts
18962
- async function deployFrontend(appDir, serviceAccountPath, projectId, config) {
18963
- const s = Y2();
18964
- s.start("Deploying frontend to Firebase Hosting...");
18965
- const args = buildFirebaseDeployArgs(
18966
- "hosting",
18967
- projectId,
18968
- config.debug,
18969
- config.force ?? true
18970
- );
18971
- const result = executeFirebaseCommand(args, {
18972
- cwd: appDir,
18973
- serviceAccountPath,
18974
- projectId,
18975
- debug: config.debug
18976
- });
18977
- if (result.error) {
18978
- s.stop("Deployment failed");
18979
- throw result.error;
18980
- }
18981
- if (!result.success) {
18982
- s.stop("Deployment failed");
18983
- handleDeploymentFailure(
18984
- result,
18985
- `firebase ${args.join(" ")}`,
18986
- serviceAccountPath
18987
- );
18620
+ function getEmulatorPorts(emulatorConfig) {
18621
+ const ports = [];
18622
+ if (emulatorConfig?.auth?.port) ports.push(emulatorConfig.auth.port);
18623
+ if (emulatorConfig?.functions?.port)
18624
+ ports.push(emulatorConfig.functions.port);
18625
+ if (emulatorConfig?.firestore?.port)
18626
+ ports.push(emulatorConfig.firestore.port);
18627
+ if (emulatorConfig?.hosting?.port) ports.push(emulatorConfig.hosting.port);
18628
+ if (emulatorConfig?.ui?.port) ports.push(emulatorConfig.ui.port);
18629
+ if (!emulatorConfig) {
18630
+ ports.push(4e3, 5001, 8080, 9099, 5e3);
18988
18631
  }
18989
- s.stop("Frontend deployed successfully");
18632
+ return ports;
18990
18633
  }
18991
-
18992
- // packages/tooling/src/apps/deploy-functions.ts
18993
- init_utils();
18994
- var import_yaml = __toESM(require_dist(), 1);
18995
- import { execSync as execSync8, spawnSync as spawnSync6 } from "node:child_process";
18996
- init_cli_tools();
18997
- init_pathResolver();
18998
- init_typed_file_operations();
18999
- function backupFiles(functionsDir) {
19000
- const backupDir = joinPath(functionsDir, ".deploy-backup");
19001
- const packageJsonPath = joinPath(functionsDir, "package.json");
19002
- const packageLockJsonPath = joinPath(functionsDir, "package-lock.json");
18634
+ function loadEnvFile(filePath) {
18635
+ if (!pathExists(filePath)) return;
19003
18636
  try {
19004
- ensureDirSync(backupDir);
19005
- const backupPackageJson = joinPath(backupDir, "package.json");
19006
- const backupPackageLockJson = joinPath(backupDir, "package-lock.json");
19007
- if (pathExists(packageJsonPath)) {
19008
- const contentRaw = readSync(packageJsonPath, { format: "text" });
19009
- const content = typeof contentRaw === "string" ? contentRaw : null;
19010
- if (!content) {
19011
- throw new Error(`Failed to read package.json: ${packageJsonPath}`);
19012
- }
19013
- writeSync(backupPackageJson, content, { overwrite: true });
19014
- }
19015
- if (pathExists(packageLockJsonPath)) {
19016
- const contentRaw = readSync(packageLockJsonPath, { format: "text" });
19017
- const content = typeof contentRaw === "string" ? contentRaw : null;
19018
- if (!content) {
19019
- throw new Error(
19020
- `Failed to read package-lock.json: ${packageLockJsonPath}`
19021
- );
18637
+ const content = readSync(filePath, { format: "text" });
18638
+ if (!content) return;
18639
+ content.split("\n").forEach((line) => {
18640
+ const trimmed = line.trim();
18641
+ if (!trimmed || trimmed.startsWith("#")) return;
18642
+ const equalIndex = trimmed.indexOf("=");
18643
+ if (equalIndex === -1) return;
18644
+ const key = trimmed.substring(0, equalIndex).trim();
18645
+ const value = trimmed.substring(equalIndex + 1).trim().replace(/^["']|["']$/g, "");
18646
+ if (key && value) {
18647
+ process.env[key] = value;
19022
18648
  }
19023
- writeSync(backupPackageLockJson, content, { overwrite: true });
18649
+ });
18650
+ } catch {
18651
+ }
18652
+ }
18653
+ async function startFirebase(app, projectRoot, options = {}) {
18654
+ const debug = options.debug ?? false;
18655
+ let selectedServices = options.selectedServices ?? [];
18656
+ const serviceChoices = [
18657
+ {
18658
+ title: "Auth",
18659
+ value: "auth",
18660
+ hint: "Firebase Auth emulator (for user authentication)"
18661
+ },
18662
+ {
18663
+ title: "Functions",
18664
+ value: "functions",
18665
+ hint: "Firebase Functions emulator (required for backend)"
18666
+ },
18667
+ {
18668
+ title: "Firestore",
18669
+ value: "firestore",
18670
+ hint: "Firestore emulator (for database)"
18671
+ },
18672
+ {
18673
+ title: "Stripe",
18674
+ value: "stripe",
18675
+ hint: "Stripe webhook forwarding (for payment testing)"
19024
18676
  }
19025
- return {
19026
- packageJson: backupPackageJson,
19027
- packageLockJson: backupPackageLockJson
19028
- };
19029
- } catch (error2) {
19030
- log.warn(
19031
- `Failed to backup files: ${error2 instanceof Error ? error2.message : String(error2)}`
18677
+ ];
18678
+ log.info(`Starting Firebase emulators + dev server for ${app.name}...
18679
+ `);
18680
+ if (selectedServices.length === 0) {
18681
+ selectedServices = await askForMultiSelection(
18682
+ "Which services do you want to run?",
18683
+ serviceChoices,
18684
+ [1, 2]
18685
+ // Default: Functions and Firestore
19032
18686
  );
19033
- return null;
18687
+ } else {
18688
+ log.info(`Selected services: ${selectedServices.join(", ")}
18689
+ `);
19034
18690
  }
19035
- }
19036
- function generateCleanPackageJson(functionsDir) {
19037
- const packageJsonPath = joinPath(functionsDir, "package.json");
19038
- if (!pathExists(packageJsonPath)) {
19039
- throw new DoNotDevError(
19040
- `package.json not found: ${packageJsonPath}`,
19041
- "file-not-found"
19042
- );
18691
+ const useAuth = selectedServices.includes("auth");
18692
+ const useFunctions = selectedServices.includes("functions");
18693
+ const useFirestore = selectedServices.includes("firestore");
18694
+ const useStripe = selectedServices.includes("stripe");
18695
+ if (!useFunctions) {
18696
+ log.error("Functions emulator is required for Firebase apps.");
18697
+ return 1;
19043
18698
  }
19044
- const packageJson = readPackageJson(packageJsonPath);
19045
- if (!packageJson.name) {
19046
- throw new Error(
19047
- `package.json is empty or invalid JSON at ${packageJsonPath}`
18699
+ const functionsDir = app.functionsPath;
18700
+ const envLocalPath = joinPath(functionsDir, ".env.local");
18701
+ if (pathExists(envLocalPath)) {
18702
+ loadEnvFile(envLocalPath);
18703
+ log.debug("Loaded functions/.env.local for emulator context");
18704
+ } else {
18705
+ log.warn(
18706
+ "No .env.local found in functions directory. Emulator may lack required secrets."
19048
18707
  );
19049
18708
  }
19050
- const cleanPackageJson = { ...packageJson };
19051
- if (cleanPackageJson.dependencies) {
19052
- const removedDeps = Object.entries(cleanPackageJson.dependencies).filter(
19053
- ([, version]) => String(version).startsWith("file:") || String(version).startsWith("workspace:")
18709
+ if (useFunctions) {
18710
+ const existingContent = pathExists(envLocalPath) ? readSync(envLocalPath, { format: "text" }) || "" : "";
18711
+ const hasAuthEmulatorHost = existingContent.includes(
18712
+ "FIREBASE_AUTH_EMULATOR_HOST"
19054
18713
  );
19055
- if (removedDeps.length > 0) {
19056
- log.warn(
19057
- `Filtering out ${removedDeps.length} workspace/file dep(s) from dependencies: ${removedDeps.map(([name]) => name).join(", ")}`
18714
+ if (useAuth && !hasAuthEmulatorHost) {
18715
+ const authEmulatorHost = "localhost:9099";
18716
+ const newContent = existingContent ? `${existingContent}
18717
+ FIREBASE_AUTH_EMULATOR_HOST=${authEmulatorHost}
18718
+ ` : `FIREBASE_AUTH_EMULATOR_HOST=${authEmulatorHost}
18719
+ `;
18720
+ writeSync(envLocalPath, newContent);
18721
+ log.debug("Set FIREBASE_AUTH_EMULATOR_HOST in functions/.env.local");
18722
+ } else if (!useAuth && hasAuthEmulatorHost) {
18723
+ const lines = existingContent.split("\n");
18724
+ const filteredLines = lines.filter(
18725
+ (line) => !line.trim().startsWith("FIREBASE_AUTH_EMULATOR_HOST=")
18726
+ );
18727
+ const newContent = filteredLines.join("\n");
18728
+ writeSync(envLocalPath, newContent);
18729
+ log.debug(
18730
+ "Removed FIREBASE_AUTH_EMULATOR_HOST from functions/.env.local"
19058
18731
  );
19059
18732
  }
19060
- cleanPackageJson.dependencies = Object.fromEntries(
19061
- Object.entries(cleanPackageJson.dependencies).filter(
19062
- ([, version]) => !String(version).startsWith("file:") && !String(version).startsWith("workspace:")
19063
- )
19064
- );
19065
18733
  }
19066
- if (cleanPackageJson.devDependencies) {
19067
- const removedDevDeps = Object.entries(
19068
- cleanPackageJson.devDependencies
19069
- ).filter(
19070
- ([, version]) => String(version).startsWith("file:") || String(version).startsWith("workspace:")
19071
- );
19072
- if (removedDevDeps.length > 0) {
19073
- log.warn(
19074
- `Filtering out ${removedDevDeps.length} workspace/file dep(s) from devDependencies: ${removedDevDeps.map(([name]) => name).join(", ")}`
19075
- );
18734
+ log.info("Building functions...");
18735
+ const buildResult = spawnSync5("bun", ["run", "build"], {
18736
+ cwd: functionsDir,
18737
+ stdio: "pipe",
18738
+ env: createEmulatorEnv(app.path, app.framework, {
18739
+ useEmulatorAuth: useAuth,
18740
+ useEmulatorFirestore: useFirestore
18741
+ })
18742
+ });
18743
+ if (buildResult.status !== 0) {
18744
+ if (buildResult.stdout) {
18745
+ process.stdout.write(buildResult.stdout);
19076
18746
  }
19077
- cleanPackageJson.devDependencies = Object.fromEntries(
19078
- Object.entries(cleanPackageJson.devDependencies).filter(
19079
- ([, version]) => !String(version).startsWith("file:") && !String(version).startsWith("workspace:")
19080
- )
19081
- );
18747
+ if (buildResult.stderr) {
18748
+ process.stderr.write(buildResult.stderr);
18749
+ }
18750
+ log.error("Functions build failed. Fix errors and try again.");
18751
+ return 1;
19082
18752
  }
19083
- if (cleanPackageJson.scripts?.preinstall) {
19084
- delete cleanPackageJson.scripts.preinstall;
18753
+ const appFirebaseJson = joinPath(app.path, "firebase.json");
18754
+ let emulatorConfig = null;
18755
+ if (pathExists(appFirebaseJson)) {
18756
+ try {
18757
+ const firebaseConfig = readFirebaseJson(appFirebaseJson);
18758
+ if (firebaseConfig.emulators) {
18759
+ emulatorConfig = firebaseConfig.emulators;
18760
+ }
18761
+ } catch {
18762
+ }
19085
18763
  }
19086
- const content = JSON.stringify(cleanPackageJson, null, 2) + "\n";
19087
- writeSync(packageJsonPath, content, { overwrite: true });
19088
- }
19089
- function prepareFunctionsForDeployment(functionsDir, verbose = false) {
19090
- const s = Y2();
19091
- s.start("Preparing functions for deployment...");
19092
- try {
19093
- backupFiles(functionsDir);
19094
- generateCleanPackageJson(functionsDir);
19095
- safeRemove(joinPath(functionsDir, "package-lock.json"), {
19096
- logSuccess: true,
19097
- successMessage: "Removed package-lock.json - Firebase Cloud Build will generate its own"
19098
- });
19099
- s.stop("Functions prepared for deployment");
19100
- } catch (error2) {
19101
- s.stop("Preparation failed");
19102
- throw error2;
18764
+ const ports = getEmulatorPorts(emulatorConfig);
18765
+ if (ports.length > 0) {
18766
+ log.info("Clearing ports...");
18767
+ killPorts(ports);
19103
18768
  }
19104
- }
19105
- function restoreFunctionsAfterDeployment(functionsDir) {
19106
- const backupDir = joinPath(functionsDir, ".deploy-backup");
19107
- const backupPackageJson = joinPath(backupDir, "package.json");
19108
- const backupPackageLockJson = joinPath(backupDir, "package-lock.json");
19109
- const packageJsonPath = joinPath(functionsDir, "package.json");
19110
- const packageLockJsonPath = joinPath(functionsDir, "package-lock.json");
19111
- try {
19112
- if (pathExists(backupPackageJson)) {
19113
- const content = readSync(backupPackageJson, { format: "text" });
19114
- if (!content) {
19115
- throw new Error(
19116
- `Failed to read backup package.json: ${backupPackageJson}`
19117
- );
19118
- }
19119
- writeSync(packageJsonPath, content, { overwrite: true });
18769
+ const emulatorsToStart = [];
18770
+ if (useFunctions) emulatorsToStart.push("functions");
18771
+ if (useAuth) emulatorsToStart.push("auth");
18772
+ if (useFirestore) emulatorsToStart.push("firestore");
18773
+ if (emulatorConfig?.hosting) {
18774
+ emulatorsToStart.push("hosting");
18775
+ }
18776
+ const emulatorArgs = ["emulators:start"];
18777
+ if (emulatorsToStart.length > 0) {
18778
+ emulatorArgs.push("--only", emulatorsToStart.join(","));
18779
+ }
18780
+ if (debug) {
18781
+ emulatorArgs.push("--debug");
18782
+ }
18783
+ const firebaseToolsPath = joinPath(
18784
+ projectRoot,
18785
+ "node_modules",
18786
+ "firebase-tools",
18787
+ "lib",
18788
+ "bin",
18789
+ "firebase.js"
18790
+ );
18791
+ const emulatorCmd = `node "${firebaseToolsPath}" ${emulatorArgs.join(" ")}`;
18792
+ const projectId = discoverFirebaseProjectId(app.path);
18793
+ const region = process.env.FIREBASE_REGION || "europe-west1";
18794
+ const concurrentlyArgs = [
18795
+ "--kill-others-on-fail",
18796
+ "--prefix-colors",
18797
+ useStripe ? "cyan,green,yellow" : "cyan,green",
18798
+ "--prefix",
18799
+ "[{name}]",
18800
+ "--names",
18801
+ useStripe ? "emulators,dev,stripe" : "emulators,dev",
18802
+ emulatorCmd,
18803
+ `bunx turbo dev --filter=${app.packageName}`
18804
+ ];
18805
+ if (useStripe && projectId) {
18806
+ const stripeWebhookUrl = `http://localhost:5001/${projectId}/${region}/stripeWebhook`;
18807
+ concurrentlyArgs.push(`stripe listen --forward-to ${stripeWebhookUrl}`);
18808
+ log.info("");
18809
+ log.info("Stripe webhook forwarding will start automatically");
18810
+ log.info(` Webhook URL: ${stripeWebhookUrl}`);
18811
+ log.info(" To trigger test events, run in another terminal:");
18812
+ log.info(" stripe trigger checkout.session.completed");
18813
+ log.info("");
18814
+ }
18815
+ const isWindows = platform3() === "win32";
18816
+ const childProcess = spawnCrossPlatform(
18817
+ "bunx",
18818
+ ["concurrently", ...concurrentlyArgs],
18819
+ {
18820
+ stdio: "inherit",
18821
+ env: createEmulatorEnv(app.path, app.framework, {
18822
+ useEmulatorAuth: useAuth,
18823
+ useEmulatorFirestore: useFirestore
18824
+ }),
18825
+ cwd: app.path
19120
18826
  }
19121
- if (pathExists(backupPackageLockJson)) {
19122
- const content = readSync(backupPackageLockJson, { format: "text" });
19123
- if (!content) {
19124
- throw new Error(
19125
- `Failed to read backup package-lock.json: ${backupPackageLockJson}`
19126
- );
18827
+ );
18828
+ const SIGNAL_EXIT_CODES3 = {
18829
+ SIGINT: 130,
18830
+ SIGTERM: 143
18831
+ };
18832
+ const cleanup = (signal) => {
18833
+ if (!childProcess.pid) return;
18834
+ log.debug(`Received ${signal}, cleaning up processes...`);
18835
+ if (isWindows) {
18836
+ try {
18837
+ execSync4(`taskkill /F /T /PID ${childProcess.pid}`, {
18838
+ stdio: "ignore",
18839
+ timeout: 2e3
18840
+ });
18841
+ } catch {
19127
18842
  }
19128
- writeSync(packageLockJsonPath, content, { overwrite: true });
19129
- }
19130
- safeRemove(backupDir, { silent: true });
19131
- } catch (error2) {
19132
- log.warn(
19133
- `Failed to restore files: ${error2 instanceof Error ? error2.message : String(error2)}`
19134
- );
19135
- log.warn(` Backup directory: ${backupDir}`);
18843
+ } else {
18844
+ try {
18845
+ process.kill(childProcess.pid, signal);
18846
+ } catch {
18847
+ }
18848
+ try {
18849
+ execSync4(`pkill -P ${childProcess.pid}`, {
18850
+ stdio: "ignore",
18851
+ timeout: 1e3
18852
+ });
18853
+ } catch {
18854
+ }
18855
+ }
18856
+ };
18857
+ const signals = ["SIGINT", "SIGTERM"];
18858
+ const handlers = [];
18859
+ for (const signal of signals) {
18860
+ const handler = () => {
18861
+ cleanup(signal);
18862
+ handlers.forEach((h2) => h2());
18863
+ process.exit(SIGNAL_EXIT_CODES3[signal] ?? 130);
18864
+ };
18865
+ process.on(signal, handler);
18866
+ handlers.push(() => process.removeListener(signal, handler));
19136
18867
  }
18868
+ return new Promise((resolve4) => {
18869
+ childProcess.on("exit", (code, signal) => {
18870
+ handlers.forEach((h2) => h2());
18871
+ if (signal) {
18872
+ log.debug(`Process killed by signal: ${signal}`);
18873
+ resolve4(SIGNAL_EXIT_CODES3[signal] ?? 130);
18874
+ } else {
18875
+ resolve4(code ?? 0);
18876
+ }
18877
+ });
18878
+ childProcess.on("error", (error2) => {
18879
+ handlers.forEach((h2) => h2());
18880
+ log.error(`Failed to start Firebase emulators: ${error2.message}`);
18881
+ resolve4(1);
18882
+ });
18883
+ });
19137
18884
  }
19138
- function getDeployedFunctionNames(functionsDir) {
19139
- const yamlPath = joinPath(functionsDir, "functions.yaml");
19140
- if (!pathExists(yamlPath)) {
19141
- log.debug("functions.yaml not found, skipping Cloud Run IAM update");
19142
- return [];
19143
- }
18885
+
18886
+ // packages/tooling/src/apps/emu-supabase.ts
18887
+ init_utils();
18888
+ init_cli_output();
18889
+ import { execSync as execSync5 } from "node:child_process";
18890
+ import { platform as platform4 } from "node:os";
18891
+ function isDockerRunning() {
19144
18892
  try {
19145
- const yamlContent = readSync(yamlPath, { format: "text" });
19146
- if (!yamlContent) {
19147
- return [];
19148
- }
19149
- const parsed = (0, import_yaml.parse)(yamlContent);
19150
- if (!parsed?.endpoints) {
19151
- return [];
19152
- }
19153
- return Object.keys(parsed.endpoints);
19154
- } catch (error2) {
19155
- log.warn(
19156
- `Failed to parse functions.yaml: ${error2 instanceof Error ? error2.message : String(error2)}`
19157
- );
19158
- return [];
18893
+ execSync5("docker info", { stdio: "pipe", timeout: 5e3 });
18894
+ return true;
18895
+ } catch {
18896
+ return false;
19159
18897
  }
19160
18898
  }
19161
- function updateCloudRunIAM(functionNames, projectId, region, serviceAccountPath, verbose) {
19162
- if (functionNames.length === 0) {
19163
- return;
18899
+ async function startSupabase(app, _projectRoot) {
18900
+ log.info(`Starting Supabase local stack + dev server for ${app.name}...
18901
+ `);
18902
+ if (!isDockerRunning()) {
18903
+ log.error("Docker is not running. Supabase local dev requires Docker.");
18904
+ log.error("Start Docker Desktop and try again.\n");
18905
+ return 1;
19164
18906
  }
19165
- if (!checkCLI("gcloud", ["--version"])) {
19166
- log.warn("gcloud CLI not found. Skipping Cloud Run IAM updates.");
19167
- log.warn(
19168
- "Functions may require manual IAM configuration for CORS preflight."
19169
- );
19170
- log.warn("Install gcloud: https://cloud.google.com/sdk/docs/install");
19171
- return;
18907
+ try {
18908
+ execSync5("supabase --version", { stdio: "pipe" });
18909
+ } catch {
18910
+ log.error("Supabase CLI not found. Install it:");
18911
+ log.error(" bun install -g supabase\n");
18912
+ return 1;
19172
18913
  }
19173
- const s = Y2();
19174
- s.start(
19175
- `Updating Cloud Run IAM for ${functionNames.length} functions (CORS preflight)...`
18914
+ const isWindows = platform4() === "win32";
18915
+ const concurrentlyArgs = [
18916
+ "--kill-others-on-fail",
18917
+ "--prefix-colors",
18918
+ "cyan,green",
18919
+ "--prefix",
18920
+ "[{name}]",
18921
+ "--names",
18922
+ "supabase,dev",
18923
+ "supabase start",
18924
+ `bunx turbo dev --filter=${app.packageName}`
18925
+ ];
18926
+ const childProcess = spawnCrossPlatform(
18927
+ "bunx",
18928
+ ["concurrently", ...concurrentlyArgs],
18929
+ {
18930
+ stdio: "inherit",
18931
+ cwd: app.path
18932
+ }
19176
18933
  );
19177
- const deployEnv = createDeployEnv(serviceAccountPath);
19178
- let successCount = 0;
19179
- let failCount = 0;
19180
- for (const funcName of functionNames) {
19181
- try {
19182
- const result = spawnSync6(
19183
- "gcloud",
19184
- [
19185
- "run",
19186
- "services",
19187
- "update",
19188
- funcName,
19189
- "--region",
19190
- region,
19191
- "--no-invoker-iam-check",
19192
- "--project",
19193
- projectId,
19194
- "--quiet"
19195
- ],
19196
- {
19197
- env: deployEnv,
19198
- stdio: verbose ? "inherit" : "pipe"
19199
- }
19200
- );
19201
- if (result.status === 0) {
19202
- successCount++;
19203
- if (verbose) {
19204
- log.debug(`\u2713 Updated IAM for ${funcName}`);
19205
- }
19206
- } else {
19207
- failCount++;
19208
- const errorOutput = result.stderr?.toString() || result.stdout?.toString() || "";
19209
- if (verbose || errorOutput.includes("ERROR")) {
19210
- log.warn(`Failed to update IAM for ${funcName}: ${errorOutput}`);
19211
- }
18934
+ const cleanup = () => {
18935
+ if (!childProcess.pid) return;
18936
+ if (isWindows) {
18937
+ try {
18938
+ execSync5(`taskkill /F /T /PID ${childProcess.pid}`, {
18939
+ stdio: "ignore",
18940
+ timeout: 2e3
18941
+ });
18942
+ } catch {
18943
+ }
18944
+ } else {
18945
+ try {
18946
+ process.kill(childProcess.pid, "SIGTERM");
18947
+ } catch {
19212
18948
  }
19213
- } catch (error2) {
19214
- failCount++;
19215
- log.warn(
19216
- `Error updating IAM for ${funcName}: ${error2 instanceof Error ? error2.message : String(error2)}`
19217
- );
19218
18949
  }
19219
- }
19220
- if (successCount > 0) {
19221
- s.stop(`Cloud Run IAM updated for ${successCount} function(s)`);
19222
- } else {
19223
- s.stop("Cloud Run IAM update completed with errors");
19224
- }
19225
- if (failCount > 0) {
19226
- log.warn(
19227
- `${failCount} function(s) failed IAM update. They may require manual configuration.`
19228
- );
19229
- }
18950
+ };
18951
+ process.on("SIGINT", () => {
18952
+ cleanup();
18953
+ process.exit(130);
18954
+ });
18955
+ process.on("SIGTERM", () => {
18956
+ cleanup();
18957
+ process.exit(143);
18958
+ });
18959
+ return new Promise((resolve4) => {
18960
+ childProcess.on("exit", (code) => resolve4(code ?? 0));
18961
+ childProcess.on("error", (error2) => {
18962
+ log.error(`Failed to start Supabase local dev: ${error2.message}`);
18963
+ resolve4(1);
18964
+ });
18965
+ });
19230
18966
  }
19231
- function getFirebaseRegion(functionsDir) {
19232
- const yamlPath = joinPath(functionsDir, "functions.yaml");
19233
- if (!pathExists(yamlPath)) {
19234
- return process.env.FIREBASE_REGION || "europe-west1";
19235
- }
18967
+
18968
+ // packages/tooling/src/apps/emu-vercel.ts
18969
+ init_utils();
18970
+ init_cli_output();
18971
+ import { execSync as execSync6 } from "node:child_process";
18972
+ import { platform as platform5 } from "node:os";
18973
+ async function startVercel(app, _projectRoot) {
18974
+ log.info(`Starting Vercel dev server for ${app.name}...
18975
+ `);
19236
18976
  try {
19237
- const yamlContent = readSync(yamlPath, { format: "text" });
19238
- if (!yamlContent) {
19239
- return process.env.FIREBASE_REGION || "europe-west1";
19240
- }
19241
- const parsed = (0, import_yaml.parse)(yamlContent);
19242
- if (parsed?.endpoints) {
19243
- const firstFunction = Object.values(parsed.endpoints)[0];
19244
- if (firstFunction?.region) {
19245
- const region = Array.isArray(firstFunction.region) ? firstFunction.region[0] : firstFunction.region;
19246
- if (region && typeof region === "string") {
19247
- return region;
19248
- }
19249
- }
19250
- }
18977
+ execSync6("vercel --version", { stdio: "pipe" });
19251
18978
  } catch {
18979
+ log.error("Vercel CLI not found. Install it:");
18980
+ log.error(" bun install -g vercel\n");
18981
+ return 1;
19252
18982
  }
19253
- return process.env.FIREBASE_REGION || "europe-west1";
18983
+ const isWindows = platform5() === "win32";
18984
+ const childProcess = spawnCrossPlatform("vercel", ["dev"], {
18985
+ stdio: "inherit",
18986
+ cwd: app.path
18987
+ });
18988
+ const cleanup = () => {
18989
+ if (!childProcess.pid) return;
18990
+ if (isWindows) {
18991
+ try {
18992
+ execSync6(`taskkill /F /T /PID ${childProcess.pid}`, {
18993
+ stdio: "ignore",
18994
+ timeout: 2e3
18995
+ });
18996
+ } catch {
18997
+ }
18998
+ } else {
18999
+ try {
19000
+ process.kill(childProcess.pid, "SIGTERM");
19001
+ } catch {
19002
+ }
19003
+ }
19004
+ };
19005
+ process.on("SIGINT", () => {
19006
+ cleanup();
19007
+ process.exit(130);
19008
+ });
19009
+ process.on("SIGTERM", () => {
19010
+ cleanup();
19011
+ process.exit(143);
19012
+ });
19013
+ return new Promise((resolve4) => {
19014
+ childProcess.on("exit", (code) => resolve4(code ?? 0));
19015
+ childProcess.on("error", (error2) => {
19016
+ log.error(`Failed to start Vercel dev: ${error2.message}`);
19017
+ resolve4(1);
19018
+ });
19019
+ });
19254
19020
  }
19255
- async function autoSyncSecrets(functionsDir, projectId, config) {
19256
- const envPath = joinPath(functionsDir, ".env");
19257
- if (!pathExists(envPath)) {
19258
- log.debug("No .env file found, skipping secrets sync");
19259
- return;
19021
+
19022
+ // packages/tooling/src/apps/emu.ts
19023
+ init_app_selector();
19024
+ init_cli_output();
19025
+ init_errors();
19026
+ init_pathResolver();
19027
+ async function main3(options) {
19028
+ const args = process.argv.slice(2);
19029
+ const projectRoot = getRepoRoot();
19030
+ if (!projectRoot) {
19031
+ throw new DoNotDevError(
19032
+ "Could not determine repository root",
19033
+ "path-resolution-error"
19034
+ );
19260
19035
  }
19261
- if (config.syncSecrets === false) {
19262
- log.debug("Secrets sync disabled via config");
19263
- return;
19036
+ const appName = args.find(
19037
+ (arg) => arg !== "emu" && arg !== "--debug" && !arg.startsWith("--")
19038
+ );
19039
+ const app = await selectApp(projectRoot, appName);
19040
+ if (!app) {
19041
+ return 1;
19264
19042
  }
19265
- try {
19266
- const envContent = readSync(envPath, { format: "text" });
19267
- if (!envContent) return;
19268
- const reservedPrefixes = ["X_GOOGLE_", "FIREBASE_", "EXT_", "GCLOUD_"];
19269
- const configOnlyKeys = [
19270
- "FIREBASE_REGION",
19271
- "FIREBASE_PROJECT_ID",
19272
- "FIREBASE_AUTH_DOMAIN"
19273
- ];
19274
- const secrets = [];
19275
- for (const line of envContent.split("\n")) {
19276
- const trimmed = line.trim();
19277
- if (!trimmed || trimmed.startsWith("#")) continue;
19278
- const eqIndex = trimmed.indexOf("=");
19279
- if (eqIndex <= 0) continue;
19280
- const key = trimmed.substring(0, eqIndex).trim();
19281
- const value = trimmed.substring(eqIndex + 1).trim().replace(/^["']|["']$/g, "");
19282
- if (configOnlyKeys.includes(key)) continue;
19283
- if (reservedPrefixes.some((p2) => key.startsWith(p2))) continue;
19284
- if (!value) continue;
19285
- secrets.push({ key, value });
19286
- }
19287
- if (secrets.length === 0) {
19288
- log.debug("No secrets found in .env, skipping sync");
19289
- return;
19290
- }
19291
- const s = Y2();
19292
- s.start(
19293
- `Syncing ${secrets.length} secret(s) to Firebase Secret Manager...`
19294
- );
19295
- const firebaseCmd = process.platform === "win32" ? "firebase.cmd" : "firebase";
19296
- let successCount = 0;
19297
- let failCount = 0;
19298
- for (const { key, value } of secrets) {
19299
- try {
19300
- const result = spawnSync6(
19301
- firebaseCmd,
19302
- ["functions:secrets:set", key, "--project", projectId],
19303
- {
19304
- input: value,
19305
- encoding: "utf8",
19306
- stdio: ["pipe", "pipe", "pipe"],
19307
- env: { ...process.env, NODE_OPTIONS: "" },
19308
- cwd: functionsDir,
19309
- shell: false
19310
- }
19043
+ switch (app.platform) {
19044
+ case "firebase": {
19045
+ if (!app.hasFunctions) {
19046
+ log.error(
19047
+ `App "${app.name}" has Firebase config but no functions directory.`
19311
19048
  );
19312
- if (result.status === 0) {
19313
- successCount++;
19314
- } else {
19315
- failCount++;
19316
- const errorOutput = result.stderr?.toString() || "";
19317
- if (config.verbose) {
19318
- log.warn(`Failed to sync secret ${key}: ${errorOutput}`);
19319
- }
19320
- }
19321
- } catch {
19322
- failCount++;
19049
+ log.error('Use "dndev dev" for apps without backend functions.\n');
19050
+ return 1;
19323
19051
  }
19052
+ const selectedServices = parseFirebaseServices(args, options);
19053
+ return startFirebase(app, projectRoot, {
19054
+ debug: options?.debug ?? false,
19055
+ selectedServices
19056
+ });
19324
19057
  }
19325
- if (successCount > 0 && failCount === 0) {
19326
- s.stop(`Synced ${successCount} secret(s) to Firebase Secret Manager`);
19327
- } else if (successCount > 0) {
19328
- s.stop(`Synced ${successCount} secret(s), ${failCount} failed`);
19058
+ case "supabase":
19059
+ return startSupabase(app, projectRoot);
19060
+ case "vercel":
19061
+ return startVercel(app, projectRoot);
19062
+ default:
19063
+ log.error(`App "${app.name}" does not have a detected backend platform.`);
19064
+ log.error(
19065
+ "Expected: firebase.json (Firebase), supabase/config.toml or @donotdev/supabase (Supabase), or vercel.json (Vercel)."
19066
+ );
19067
+ log.error('Use "dndev dev" for apps without a backend.\n');
19068
+ return 1;
19069
+ }
19070
+ }
19071
+ function parseFirebaseServices(args, options) {
19072
+ const validServices = ["auth", "functions", "firestore", "stripe"];
19073
+ let selectedServices = [];
19074
+ if (options?.services) {
19075
+ selectedServices = options.services.split(",").map((s) => s.trim());
19076
+ } else {
19077
+ const servicesArg = args.find((arg) => arg.startsWith("--services="));
19078
+ if (servicesArg) {
19079
+ const servicesList = servicesArg.split("=")[1];
19080
+ if (servicesList) {
19081
+ selectedServices = servicesList.split(",").map((s) => s.trim());
19082
+ }
19329
19083
  } else {
19330
- s.stop("Secrets sync failed");
19331
- log.warn('Could not sync secrets. Run "dn sync-secrets" manually.');
19084
+ if (options?.auth || args.includes("--auth"))
19085
+ selectedServices.push("auth");
19086
+ if (args.includes("--functions")) selectedServices.push("functions");
19087
+ if (options?.firestore || args.includes("--firestore"))
19088
+ selectedServices.push("firestore");
19089
+ if (options?.stripe || args.includes("--stripe"))
19090
+ selectedServices.push("stripe");
19332
19091
  }
19333
- } catch (error2) {
19334
- log.debug(
19335
- `Could not sync secrets: ${error2 instanceof Error ? error2.message : String(error2)}`
19336
- );
19337
- log.info(
19338
- 'Run "dn sync-secrets" manually to sync secrets to Firebase Secret Manager.'
19339
- );
19340
19092
  }
19093
+ return selectedServices.filter((s) => validServices.includes(s));
19341
19094
  }
19342
- async function deployFunctions(appDir, serviceAccountPath, projectId, config) {
19343
- const functionsDir = joinPath(appDir, "functions");
19344
- if (!pathExists(functionsDir)) {
19095
+
19096
+ // packages/tooling/src/apps/preview.ts
19097
+ init_utils();
19098
+ init_app_selector();
19099
+ init_cli_output();
19100
+ init_errors();
19101
+ init_pathResolver();
19102
+ import {
19103
+ spawnSync as spawnSync6,
19104
+ execSync as execSync7
19105
+ } from "node:child_process";
19106
+ import { platform as platform6 } from "node:os";
19107
+ var SIGNAL_EXIT_CODES2 = {
19108
+ SIGINT: 130,
19109
+ // 128 + 2
19110
+ SIGTERM: 143
19111
+ // 128 + 15
19112
+ };
19113
+ async function main4() {
19114
+ const args = process.argv.slice(2);
19115
+ const appName = args[0] && args[0] !== "preview" ? args[0] : void 0;
19116
+ const projectRoot = getRepoRoot();
19117
+ if (!projectRoot) {
19345
19118
  throw new DoNotDevError(
19346
- `Functions directory not found: ${functionsDir}`,
19347
- "file-not-found"
19119
+ "Could not determine repository root",
19120
+ "path-resolution-error"
19348
19121
  );
19349
19122
  }
19350
- const s = Y2();
19351
- s.start("Validating function dependencies...");
19352
- const requiredPackages = ["firebase-functions", "firebase-admin"];
19353
- const missingPackages = requiredPackages.filter((pkg) => {
19354
- try {
19355
- resolvePackage(pkg, functionsDir);
19356
- return false;
19357
- } catch {
19358
- return true;
19359
- }
19360
- });
19361
- if (missingPackages.length > 0) {
19362
- s.stop("Missing dependencies");
19363
- throw new DoNotDevError(
19364
- `Missing required dependencies: ${missingPackages.join(", ")}
19365
-
19366
- To fix this, run:
19367
- cd ${functionsDir}
19368
- bun install --production`,
19369
- "file-not-found",
19370
- { context: { missingPackages, functionsDir } }
19371
- );
19123
+ const app = await selectApp(projectRoot, appName);
19124
+ if (!app) {
19125
+ return 1;
19372
19126
  }
19373
- s.stop("Dependencies validated");
19374
- prepareFunctionsForDeployment(functionsDir, config.verbose);
19375
- log.debug("Waiting for file system sync...");
19376
- await new Promise((resolve4) => setTimeout(resolve4, 1e3));
19377
- try {
19378
- if (!config.skipBuild) {
19379
- const s2 = Y2();
19380
- s2.start("Building functions...");
19381
- try {
19382
- execSync8("bun run build", {
19383
- cwd: functionsDir,
19384
- stdio: config.verbose ? "inherit" : "pipe"
19385
- });
19386
- s2.stop("Functions built");
19387
- } catch (error2) {
19388
- s2.stop("Build failed");
19389
- throw error2;
19127
+ const distPath = joinPath(app.path, "dist");
19128
+ const nextPath = joinPath(app.path, ".next");
19129
+ const hasBuild = pathExists(distPath) || pathExists(nextPath);
19130
+ if (!hasBuild) {
19131
+ log.info(`Build not found. Building ${app.name} first...
19132
+ `);
19133
+ const buildResult = spawnSync6(
19134
+ "bunx",
19135
+ ["turbo", "build", "--filter", app.packageName],
19136
+ {
19137
+ stdio: "inherit",
19138
+ env: createAppEnv(app.path),
19139
+ cwd: projectRoot
19390
19140
  }
19391
- }
19392
- s.start("Deploying functions to Firebase...");
19393
- const firebaseProjectDir = pathExists(joinPath(appDir, "firebase.json")) ? appDir : functionsDir;
19394
- log.debug(`Using service account: ${serviceAccountPath}`);
19395
- log.debug(`Firebase project directory: ${firebaseProjectDir}`);
19396
- const args = buildFirebaseDeployArgs(
19397
- "functions",
19398
- projectId,
19399
- config.debug,
19400
- config.force ?? true
19401
- // Default --force for functions (auto-sets artifact cleanup policy)
19402
19141
  );
19403
- const result = executeFirebaseCommand(args, {
19404
- cwd: firebaseProjectDir,
19405
- serviceAccountPath,
19406
- projectId,
19407
- debug: config.debug
19408
- });
19409
- if (result.error) {
19410
- s.stop("Deployment failed");
19411
- throw result.error;
19142
+ if (buildResult.status !== 0) {
19143
+ return buildResult.status || 1;
19412
19144
  }
19413
- if (!result.success) {
19414
- s.stop("Deployment failed");
19415
- handleDeploymentFailure(
19416
- result,
19417
- `firebase ${args.join(" ")}`,
19418
- serviceAccountPath
19419
- );
19145
+ }
19146
+ log.info(`Previewing ${app.name}...
19147
+ `);
19148
+ const turboArgs = ["preview", "--filter", app.packageName];
19149
+ const isWindows = platform6() === "win32";
19150
+ const childProcess = spawnCrossPlatform(
19151
+ "bunx",
19152
+ ["turbo", ...turboArgs],
19153
+ {
19154
+ stdio: "inherit",
19155
+ env: createAppEnv(app.path),
19156
+ cwd: projectRoot
19420
19157
  }
19421
- s.stop("Functions deployed successfully");
19422
- const functionNames = getDeployedFunctionNames(functionsDir);
19423
- if (functionNames.length > 0) {
19424
- const region = getFirebaseRegion(functionsDir);
19425
- updateCloudRunIAM(
19426
- functionNames,
19427
- projectId,
19428
- region,
19429
- serviceAccountPath,
19430
- config.verbose ?? false
19431
- );
19158
+ );
19159
+ const cleanup = (signal) => {
19160
+ if (!childProcess.pid) return;
19161
+ log.debug(`Received ${signal}, cleaning up processes...`);
19162
+ if (isWindows) {
19163
+ try {
19164
+ execSync7(`taskkill /F /T /PID ${childProcess.pid}`, {
19165
+ stdio: "ignore",
19166
+ timeout: 2e3
19167
+ });
19168
+ } catch {
19169
+ }
19170
+ } else {
19171
+ try {
19172
+ process.kill(childProcess.pid, signal);
19173
+ } catch {
19174
+ }
19175
+ try {
19176
+ execSync7(`pkill -P ${childProcess.pid}`, {
19177
+ stdio: "ignore",
19178
+ timeout: 1e3
19179
+ });
19180
+ } catch {
19181
+ }
19432
19182
  }
19433
- await autoSyncSecrets(functionsDir, projectId, config);
19434
- } finally {
19435
- restoreFunctionsAfterDeployment(functionsDir);
19183
+ };
19184
+ const signals = ["SIGINT", "SIGTERM"];
19185
+ const handlers = [];
19186
+ for (const signal of signals) {
19187
+ const handler = () => {
19188
+ cleanup(signal);
19189
+ handlers.forEach((h2) => h2());
19190
+ process.exit(SIGNAL_EXIT_CODES2[signal] ?? 130);
19191
+ };
19192
+ process.on(signal, handler);
19193
+ handlers.push(() => process.removeListener(signal, handler));
19436
19194
  }
19195
+ return new Promise((resolve4) => {
19196
+ childProcess.on("exit", (code, signal) => {
19197
+ handlers.forEach((h2) => h2());
19198
+ if (signal) {
19199
+ log.debug(`Process killed by signal: ${signal}`);
19200
+ resolve4(SIGNAL_EXIT_CODES2[signal] ?? 130);
19201
+ } else {
19202
+ resolve4(code ?? 0);
19203
+ }
19204
+ });
19205
+ childProcess.on("error", (error2) => {
19206
+ handlers.forEach((h2) => h2());
19207
+ log.error(`Failed to start preview server: ${error2.message}`);
19208
+ resolve4(1);
19209
+ });
19210
+ });
19437
19211
  }
19438
19212
 
19439
- // packages/tooling/src/apps/deploy-rules.ts
19213
+ // packages/tooling/src/apps/deploy.ts
19440
19214
  init_utils();
19441
- async function deployRules(appDir, serviceAccountPath, projectId, config, options) {
19442
- const targets = [];
19443
- if (options.firestore) {
19444
- targets.push("firestore:rules");
19445
- }
19446
- if (options.firestoreIndexes) {
19447
- targets.push("firestore:indexes");
19448
- }
19449
- if (options.storage) {
19450
- targets.push("storage");
19451
- }
19452
- if (targets.length === 0) {
19453
- return;
19454
- }
19455
- const targetNames = targets.join(", ");
19215
+ import { execSync as execSync9 } from "node:child_process";
19216
+
19217
+ // packages/tooling/src/apps/deploy-frontend.ts
19218
+ init_utils();
19219
+ async function deployFrontend(appDir, serviceAccountPath, projectId, config) {
19456
19220
  const s = Y2();
19457
- s.start(`Deploying ${targetNames}...`);
19221
+ s.start("Deploying frontend to Firebase Hosting...");
19458
19222
  const args = buildFirebaseDeployArgs(
19459
- targets,
19223
+ "hosting",
19460
19224
  projectId,
19461
19225
  config.debug,
19462
19226
  config.force ?? true
@@ -19468,256 +19232,511 @@ async function deployRules(appDir, serviceAccountPath, projectId, config, option
19468
19232
  debug: config.debug
19469
19233
  });
19470
19234
  if (result.error) {
19471
- s.stop("Rules deployment failed");
19235
+ s.stop("Deployment failed");
19472
19236
  throw result.error;
19473
19237
  }
19474
19238
  if (!result.success) {
19475
- s.stop("Rules deployment failed");
19239
+ s.stop("Deployment failed");
19476
19240
  handleDeploymentFailure(
19477
19241
  result,
19478
19242
  `firebase ${args.join(" ")}`,
19479
19243
  serviceAccountPath
19480
19244
  );
19481
19245
  }
19482
- s.stop(`${targetNames} deployed successfully`);
19246
+ s.stop("Frontend deployed successfully");
19483
19247
  }
19484
19248
 
19485
- // packages/tooling/src/apps/deploy-utils.ts
19249
+ // packages/tooling/src/apps/deploy-functions.ts
19486
19250
  init_utils();
19487
- import { spawnSync as spawnSync7 } from "node:child_process";
19488
- init_error_handling();
19251
+ var import_yaml = __toESM(require_dist(), 1);
19252
+ import { execSync as execSync8, spawnSync as spawnSync7 } from "node:child_process";
19253
+ init_cli_tools();
19489
19254
  init_pathResolver();
19490
19255
  init_typed_file_operations();
19491
- function detectAvailableApps() {
19492
- const currentDir = process.cwd();
19493
- const appsDir = joinPath(currentDir, "apps");
19494
- if (!pathExists(appsDir)) {
19495
- return [];
19256
+ function backupFiles(functionsDir) {
19257
+ const backupDir = joinPath(functionsDir, ".deploy-backup");
19258
+ const packageJsonPath = joinPath(functionsDir, "package.json");
19259
+ const packageLockJsonPath = joinPath(functionsDir, "package-lock.json");
19260
+ try {
19261
+ ensureDirSync(backupDir);
19262
+ const backupPackageJson = joinPath(backupDir, "package.json");
19263
+ const backupPackageLockJson = joinPath(backupDir, "package-lock.json");
19264
+ if (pathExists(packageJsonPath)) {
19265
+ const contentRaw = readSync(packageJsonPath, { format: "text" });
19266
+ const content = typeof contentRaw === "string" ? contentRaw : null;
19267
+ if (!content) {
19268
+ throw new Error(`Failed to read package.json: ${packageJsonPath}`);
19269
+ }
19270
+ writeSync(backupPackageJson, content, { overwrite: true });
19271
+ }
19272
+ if (pathExists(packageLockJsonPath)) {
19273
+ const contentRaw = readSync(packageLockJsonPath, { format: "text" });
19274
+ const content = typeof contentRaw === "string" ? contentRaw : null;
19275
+ if (!content) {
19276
+ throw new Error(
19277
+ `Failed to read package-lock.json: ${packageLockJsonPath}`
19278
+ );
19279
+ }
19280
+ writeSync(backupPackageLockJson, content, { overwrite: true });
19281
+ }
19282
+ return {
19283
+ packageJson: backupPackageJson,
19284
+ packageLockJson: backupPackageLockJson
19285
+ };
19286
+ } catch (error2) {
19287
+ log.warn(
19288
+ `Failed to backup files: ${error2 instanceof Error ? error2.message : String(error2)}`
19289
+ );
19290
+ return null;
19496
19291
  }
19497
- return readdirSync2(appsDir).filter((item) => {
19498
- const itemPath = joinPath(appsDir, item);
19499
- const stat2 = statSync2(itemPath);
19500
- return stat2?.isDirectory() === true;
19501
- }).filter((app) => {
19502
- const appDir = joinPath(appsDir, app);
19503
- const firebaseJsonPath = joinPath(appDir, "firebase.json");
19504
- const supabaseDir = joinPath(appDir, "supabase");
19505
- const vercelJsonPath = joinPath(appDir, "vercel.json");
19506
- return pathExists(firebaseJsonPath) || pathExists(supabaseDir) || pathExists(vercelJsonPath);
19507
- }).sort();
19508
19292
  }
19509
- function detectAppDir(appName) {
19510
- const currentDir = process.cwd();
19511
- const appDir = joinPath(currentDir, "apps", appName);
19512
- if (!pathExists(appDir)) {
19293
+ function generateCleanPackageJson(functionsDir) {
19294
+ const packageJsonPath = joinPath(functionsDir, "package.json");
19295
+ if (!pathExists(packageJsonPath)) {
19513
19296
  throw new DoNotDevError(
19514
- `App directory not found: ${appDir}`,
19515
- "file-not-found",
19516
- { context: { appName, expectedPath: appDir } }
19297
+ `package.json not found: ${packageJsonPath}`,
19298
+ "file-not-found"
19517
19299
  );
19518
19300
  }
19519
- return appDir;
19301
+ const packageJson = readPackageJson(packageJsonPath);
19302
+ if (!packageJson.name) {
19303
+ throw new Error(
19304
+ `package.json is empty or invalid JSON at ${packageJsonPath}`
19305
+ );
19306
+ }
19307
+ const cleanPackageJson = { ...packageJson };
19308
+ if (cleanPackageJson.dependencies) {
19309
+ const removedDeps = Object.entries(cleanPackageJson.dependencies).filter(
19310
+ ([, version]) => String(version).startsWith("file:") || String(version).startsWith("workspace:")
19311
+ );
19312
+ if (removedDeps.length > 0) {
19313
+ log.warn(
19314
+ `Filtering out ${removedDeps.length} workspace/file dep(s) from dependencies: ${removedDeps.map(([name]) => name).join(", ")}`
19315
+ );
19316
+ }
19317
+ cleanPackageJson.dependencies = Object.fromEntries(
19318
+ Object.entries(cleanPackageJson.dependencies).filter(
19319
+ ([, version]) => !String(version).startsWith("file:") && !String(version).startsWith("workspace:")
19320
+ )
19321
+ );
19322
+ }
19323
+ if (cleanPackageJson.devDependencies) {
19324
+ const removedDevDeps = Object.entries(
19325
+ cleanPackageJson.devDependencies
19326
+ ).filter(
19327
+ ([, version]) => String(version).startsWith("file:") || String(version).startsWith("workspace:")
19328
+ );
19329
+ if (removedDevDeps.length > 0) {
19330
+ log.warn(
19331
+ `Filtering out ${removedDevDeps.length} workspace/file dep(s) from devDependencies: ${removedDevDeps.map(([name]) => name).join(", ")}`
19332
+ );
19333
+ }
19334
+ cleanPackageJson.devDependencies = Object.fromEntries(
19335
+ Object.entries(cleanPackageJson.devDependencies).filter(
19336
+ ([, version]) => !String(version).startsWith("file:") && !String(version).startsWith("workspace:")
19337
+ )
19338
+ );
19339
+ }
19340
+ if (cleanPackageJson.scripts?.preinstall) {
19341
+ delete cleanPackageJson.scripts.preinstall;
19342
+ }
19343
+ const content = JSON.stringify(cleanPackageJson, null, 2) + "\n";
19344
+ writeSync(packageJsonPath, content, { overwrite: true });
19520
19345
  }
19521
- function validateServiceAccount(appDir, options) {
19522
- const keyFileName = options?.staging ? "service-account-key.staging.json" : "service-account-key.json";
19523
- const rootKeyPath = joinPath(appDir, keyFileName);
19524
- const functionsDir = joinPath(appDir, "functions");
19525
- const functionsKeyPath = joinPath(functionsDir, keyFileName);
19526
- const keyPath = pathExists(rootKeyPath) ? rootKeyPath : functionsKeyPath;
19527
- const errors = [];
19528
- if (!pathExists(keyPath)) {
19529
- return {
19530
- valid: false,
19531
- info: {
19532
- path: keyPath,
19533
- projectId: "",
19534
- clientEmail: "",
19535
- valid: false,
19536
- errors: [
19537
- `Service account key file not found. Checked:`,
19538
- ` - ${rootKeyPath}`,
19539
- ` - ${functionsKeyPath}`
19540
- ]
19541
- }
19542
- };
19346
+ function prepareFunctionsForDeployment(functionsDir, verbose = false) {
19347
+ const s = Y2();
19348
+ s.start("Preparing functions for deployment...");
19349
+ try {
19350
+ backupFiles(functionsDir);
19351
+ generateCleanPackageJson(functionsDir);
19352
+ safeRemove(joinPath(functionsDir, "package-lock.json"), {
19353
+ logSuccess: true,
19354
+ successMessage: "Removed package-lock.json - Firebase Cloud Build will generate its own"
19355
+ });
19356
+ s.stop("Functions prepared for deployment");
19357
+ } catch (error2) {
19358
+ s.stop("Preparation failed");
19359
+ throw error2;
19543
19360
  }
19361
+ }
19362
+ function restoreFunctionsAfterDeployment(functionsDir) {
19363
+ const backupDir = joinPath(functionsDir, ".deploy-backup");
19364
+ const backupPackageJson = joinPath(backupDir, "package.json");
19365
+ const backupPackageLockJson = joinPath(backupDir, "package-lock.json");
19366
+ const packageJsonPath = joinPath(functionsDir, "package.json");
19367
+ const packageLockJsonPath = joinPath(functionsDir, "package-lock.json");
19544
19368
  try {
19545
- const keyData = readServiceAccountKey(keyPath);
19546
- return {
19547
- valid: true,
19548
- info: {
19549
- path: keyPath,
19550
- projectId: keyData.project_id,
19551
- clientEmail: keyData.client_email,
19552
- valid: true,
19553
- errors: []
19369
+ if (pathExists(backupPackageJson)) {
19370
+ const content = readSync(backupPackageJson, { format: "text" });
19371
+ if (!content) {
19372
+ throw new Error(
19373
+ `Failed to read backup package.json: ${backupPackageJson}`
19374
+ );
19554
19375
  }
19555
- };
19556
- } catch (error2) {
19557
- return {
19558
- valid: false,
19559
- info: {
19560
- path: keyPath,
19561
- projectId: "",
19562
- clientEmail: "",
19563
- valid: false,
19564
- errors: [`Invalid service account key: ${getErrorMessage(error2)}`]
19376
+ writeSync(packageJsonPath, content, { overwrite: true });
19377
+ }
19378
+ if (pathExists(backupPackageLockJson)) {
19379
+ const content = readSync(backupPackageLockJson, { format: "text" });
19380
+ if (!content) {
19381
+ throw new Error(
19382
+ `Failed to read backup package-lock.json: ${backupPackageLockJson}`
19383
+ );
19565
19384
  }
19566
- };
19385
+ writeSync(packageLockJsonPath, content, { overwrite: true });
19386
+ }
19387
+ safeRemove(backupDir, { silent: true });
19388
+ } catch (error2) {
19389
+ log.warn(
19390
+ `Failed to restore files: ${error2 instanceof Error ? error2.message : String(error2)}`
19391
+ );
19392
+ log.warn(` Backup directory: ${backupDir}`);
19567
19393
  }
19568
19394
  }
19569
- function validateFirebaseJson2(appDir) {
19570
- const firebaseJsonPath = joinPath(appDir, "firebase.json");
19571
- if (!pathExists(firebaseJsonPath)) {
19572
- return {
19573
- valid: false,
19574
- hasHosting: false,
19575
- hasFunctions: false,
19576
- hasFirestoreRules: false,
19577
- hasFirestoreIndexes: false,
19578
- hasStorageRules: false,
19579
- errors: [`firebase.json not found at: ${firebaseJsonPath}`]
19580
- };
19395
+ function getDeployedFunctionNames(functionsDir) {
19396
+ const yamlPath = joinPath(functionsDir, "functions.yaml");
19397
+ if (!pathExists(yamlPath)) {
19398
+ log.debug("functions.yaml not found, skipping Cloud Run IAM update");
19399
+ return [];
19581
19400
  }
19582
19401
  try {
19583
- const config = readFirebaseJson(firebaseJsonPath);
19584
- const hasHosting = !!config.hosting;
19585
- const hasFunctions = !!config.functions && Array.isArray(config.functions);
19586
- const hasFirestoreRules = !!config.firestore?.rules && pathExists(joinPath(appDir, config.firestore.rules));
19587
- const hasFirestoreIndexes = !!config.firestore?.indexes && pathExists(joinPath(appDir, config.firestore.indexes));
19588
- const hasStorageRules = !!config.storage?.rules && pathExists(joinPath(appDir, config.storage.rules));
19589
- return {
19590
- valid: true,
19591
- projectId: config.projectId,
19592
- hasHosting,
19593
- hasFunctions,
19594
- hasFirestoreRules,
19595
- hasFirestoreIndexes,
19596
- hasStorageRules,
19597
- errors: []
19598
- };
19402
+ const yamlContent = readSync(yamlPath, { format: "text" });
19403
+ if (!yamlContent) {
19404
+ return [];
19405
+ }
19406
+ const parsed = (0, import_yaml.parse)(yamlContent);
19407
+ if (!parsed?.endpoints) {
19408
+ return [];
19409
+ }
19410
+ return Object.keys(parsed.endpoints);
19599
19411
  } catch (error2) {
19600
- return {
19601
- valid: false,
19602
- hasHosting: false,
19603
- hasFunctions: false,
19604
- hasFirestoreRules: false,
19605
- hasFirestoreIndexes: false,
19606
- hasStorageRules: false,
19607
- errors: [`Invalid firebase.json: ${getErrorMessage(error2)}`]
19608
- };
19412
+ log.warn(
19413
+ `Failed to parse functions.yaml: ${error2 instanceof Error ? error2.message : String(error2)}`
19414
+ );
19415
+ return [];
19609
19416
  }
19610
19417
  }
19611
- function validateBuild(appDir) {
19612
- const distPath = joinPath(appDir, "dist");
19613
- if (!pathExists(distPath)) {
19614
- return { exists: false, isEmpty: true, path: distPath };
19418
+ function updateCloudRunIAM(functionNames, projectId, region, serviceAccountPath, verbose) {
19419
+ if (functionNames.length === 0) {
19420
+ return;
19421
+ }
19422
+ if (!checkCLI("gcloud", ["--version"])) {
19423
+ log.warn("gcloud CLI not found. Skipping Cloud Run IAM updates.");
19424
+ log.warn(
19425
+ "Functions may require manual IAM configuration for CORS preflight."
19426
+ );
19427
+ log.warn("Install gcloud: https://cloud.google.com/sdk/docs/install");
19428
+ return;
19429
+ }
19430
+ const s = Y2();
19431
+ s.start(
19432
+ `Updating Cloud Run IAM for ${functionNames.length} functions (CORS preflight)...`
19433
+ );
19434
+ const deployEnv = createDeployEnv(serviceAccountPath);
19435
+ let successCount = 0;
19436
+ let failCount = 0;
19437
+ for (const funcName of functionNames) {
19438
+ try {
19439
+ const result = spawnSync7(
19440
+ "gcloud",
19441
+ [
19442
+ "run",
19443
+ "services",
19444
+ "update",
19445
+ funcName,
19446
+ "--region",
19447
+ region,
19448
+ "--no-invoker-iam-check",
19449
+ "--project",
19450
+ projectId,
19451
+ "--quiet"
19452
+ ],
19453
+ {
19454
+ env: deployEnv,
19455
+ stdio: verbose ? "inherit" : "pipe"
19456
+ }
19457
+ );
19458
+ if (result.status === 0) {
19459
+ successCount++;
19460
+ if (verbose) {
19461
+ log.debug(`\u2713 Updated IAM for ${funcName}`);
19462
+ }
19463
+ } else {
19464
+ failCount++;
19465
+ const errorOutput = result.stderr?.toString() || result.stdout?.toString() || "";
19466
+ if (verbose || errorOutput.includes("ERROR")) {
19467
+ log.warn(`Failed to update IAM for ${funcName}: ${errorOutput}`);
19468
+ }
19469
+ }
19470
+ } catch (error2) {
19471
+ failCount++;
19472
+ log.warn(
19473
+ `Error updating IAM for ${funcName}: ${error2 instanceof Error ? error2.message : String(error2)}`
19474
+ );
19475
+ }
19476
+ }
19477
+ if (successCount > 0) {
19478
+ s.stop(`Cloud Run IAM updated for ${successCount} function(s)`);
19479
+ } else {
19480
+ s.stop("Cloud Run IAM update completed with errors");
19481
+ }
19482
+ if (failCount > 0) {
19483
+ log.warn(
19484
+ `${failCount} function(s) failed IAM update. They may require manual configuration.`
19485
+ );
19486
+ }
19487
+ }
19488
+ function getFirebaseRegion(functionsDir) {
19489
+ const yamlPath = joinPath(functionsDir, "functions.yaml");
19490
+ if (!pathExists(yamlPath)) {
19491
+ return process.env.FIREBASE_REGION || "europe-west1";
19615
19492
  }
19616
19493
  try {
19617
- const files = readdirSync2(distPath);
19618
- return {
19619
- exists: true,
19620
- isEmpty: files.length === 0,
19621
- path: distPath
19622
- };
19494
+ const yamlContent = readSync(yamlPath, { format: "text" });
19495
+ if (!yamlContent) {
19496
+ return process.env.FIREBASE_REGION || "europe-west1";
19497
+ }
19498
+ const parsed = (0, import_yaml.parse)(yamlContent);
19499
+ if (parsed?.endpoints) {
19500
+ const firstFunction = Object.values(parsed.endpoints)[0];
19501
+ if (firstFunction?.region) {
19502
+ const region = Array.isArray(firstFunction.region) ? firstFunction.region[0] : firstFunction.region;
19503
+ if (region && typeof region === "string") {
19504
+ return region;
19505
+ }
19506
+ }
19507
+ }
19623
19508
  } catch {
19624
- return { exists: true, isEmpty: true, path: distPath };
19625
19509
  }
19510
+ return process.env.FIREBASE_REGION || "europe-west1";
19626
19511
  }
19627
- function readStagingProject(startDir) {
19628
- let current = startDir;
19629
- for (let i = 0; i < 10; i++) {
19630
- const firebasercPath = joinPath(current, ".firebaserc");
19631
- if (pathExists(firebasercPath)) {
19512
+ async function autoSyncSecrets(functionsDir, projectId, config) {
19513
+ const envPath = joinPath(functionsDir, ".env");
19514
+ if (!pathExists(envPath)) {
19515
+ log.debug("No .env file found, skipping secrets sync");
19516
+ return;
19517
+ }
19518
+ if (config.syncSecrets === false) {
19519
+ log.debug("Secrets sync disabled via config");
19520
+ return;
19521
+ }
19522
+ try {
19523
+ const envContent = readSync(envPath, { format: "text" });
19524
+ if (!envContent) return;
19525
+ const reservedPrefixes = ["X_GOOGLE_", "FIREBASE_", "EXT_", "GCLOUD_"];
19526
+ const configOnlyKeys = [
19527
+ "FIREBASE_REGION",
19528
+ "FIREBASE_PROJECT_ID",
19529
+ "FIREBASE_AUTH_DOMAIN"
19530
+ ];
19531
+ const secrets = [];
19532
+ for (const line of envContent.split("\n")) {
19533
+ const trimmed = line.trim();
19534
+ if (!trimmed || trimmed.startsWith("#")) continue;
19535
+ const eqIndex = trimmed.indexOf("=");
19536
+ if (eqIndex <= 0) continue;
19537
+ const key = trimmed.substring(0, eqIndex).trim();
19538
+ const value = trimmed.substring(eqIndex + 1).trim().replace(/^["']|["']$/g, "");
19539
+ if (configOnlyKeys.includes(key)) continue;
19540
+ if (reservedPrefixes.some((p2) => key.startsWith(p2))) continue;
19541
+ if (!value) continue;
19542
+ secrets.push({ key, value });
19543
+ }
19544
+ if (secrets.length === 0) {
19545
+ log.debug("No secrets found in .env, skipping sync");
19546
+ return;
19547
+ }
19548
+ const s = Y2();
19549
+ s.start(
19550
+ `Syncing ${secrets.length} secret(s) to Firebase Secret Manager...`
19551
+ );
19552
+ const firebaseCmd = process.platform === "win32" ? "firebase.cmd" : "firebase";
19553
+ let successCount = 0;
19554
+ let failCount = 0;
19555
+ for (const { key, value } of secrets) {
19632
19556
  try {
19633
- const firebaserc = readFirebaserc(firebasercPath);
19634
- if (firebaserc?.projects?.staging) {
19635
- return firebaserc.projects.staging;
19557
+ const result = spawnSync7(
19558
+ firebaseCmd,
19559
+ ["functions:secrets:set", key, "--project", projectId],
19560
+ {
19561
+ input: value,
19562
+ encoding: "utf8",
19563
+ stdio: ["pipe", "pipe", "pipe"],
19564
+ env: { ...process.env, NODE_OPTIONS: "" },
19565
+ cwd: functionsDir,
19566
+ shell: false
19567
+ }
19568
+ );
19569
+ if (result.status === 0) {
19570
+ successCount++;
19571
+ } else {
19572
+ failCount++;
19573
+ const errorOutput = result.stderr?.toString() || "";
19574
+ if (config.verbose) {
19575
+ log.warn(`Failed to sync secret ${key}: ${errorOutput}`);
19576
+ }
19636
19577
  }
19637
- } catch (error2) {
19578
+ } catch {
19579
+ failCount++;
19638
19580
  }
19639
19581
  }
19640
- const parent = joinPath(current, "..");
19641
- if (parent === current) break;
19642
- current = parent;
19582
+ if (successCount > 0 && failCount === 0) {
19583
+ s.stop(`Synced ${successCount} secret(s) to Firebase Secret Manager`);
19584
+ } else if (successCount > 0) {
19585
+ s.stop(`Synced ${successCount} secret(s), ${failCount} failed`);
19586
+ } else {
19587
+ s.stop("Secrets sync failed");
19588
+ log.warn('Could not sync secrets. Run "dn sync-secrets" manually.');
19589
+ }
19590
+ } catch (error2) {
19591
+ log.debug(
19592
+ `Could not sync secrets: ${error2 instanceof Error ? error2.message : String(error2)}`
19593
+ );
19594
+ log.info(
19595
+ 'Run "dn sync-secrets" manually to sync secrets to Firebase Secret Manager.'
19596
+ );
19643
19597
  }
19644
- return null;
19645
19598
  }
19646
- async function showServiceAccountError(info2, projectId) {
19647
- const consoleUrl = projectId ? `https://console.firebase.google.com/project/${projectId}/settings/serviceaccounts/adminsdk` : "https://console.firebase.google.com/project/YOUR_PROJECT/settings/serviceaccounts/adminsdk";
19648
- const errorList = info2.errors.map((e2) => `\u2022 ${e2}`).join("\n");
19649
- Me(
19650
- `${errorList}
19651
-
19652
- Why it matters:
19653
- Firebase CLI needs service account credentials to deploy.
19654
- Without valid credentials, deployment will fail.
19599
+ async function deployFunctions(appDir, serviceAccountPath, projectId, config) {
19600
+ const functionsDir = joinPath(appDir, "functions");
19601
+ if (!pathExists(functionsDir)) {
19602
+ throw new DoNotDevError(
19603
+ `Functions directory not found: ${functionsDir}`,
19604
+ "file-not-found"
19605
+ );
19606
+ }
19607
+ const s = Y2();
19608
+ s.start("Validating function dependencies...");
19609
+ const requiredPackages = ["firebase-functions", "firebase-admin"];
19610
+ const missingPackages = requiredPackages.filter((pkg) => {
19611
+ try {
19612
+ resolvePackage(pkg, functionsDir);
19613
+ return false;
19614
+ } catch {
19615
+ return true;
19616
+ }
19617
+ });
19618
+ if (missingPackages.length > 0) {
19619
+ s.stop("Missing dependencies");
19620
+ throw new DoNotDevError(
19621
+ `Missing required dependencies: ${missingPackages.join(", ")}
19655
19622
 
19656
- How to fix:
19657
- 1. Go to Firebase Console:
19658
- ${consoleUrl}
19659
- 2. Click "Generate New Private Key"
19660
- 3. Save the JSON file as: ${info2.path}
19661
- 4. Required IAM roles:
19662
- \u2022 Firebase Hosting Admin (for frontend)
19663
- \u2022 Cloud Functions Admin (for functions)
19664
- \u2022 Or Firebase Admin (covers both)`,
19665
- "Service Account Error"
19666
- );
19667
- if (projectId) {
19668
- const shouldOpen = await askForConfirmation(
19669
- "Open Firebase Console now?",
19670
- true
19623
+ To fix this, run:
19624
+ cd ${functionsDir}
19625
+ bun install --production`,
19626
+ "file-not-found",
19627
+ { context: { missingPackages, functionsDir } }
19671
19628
  );
19672
- if (shouldOpen) {
19629
+ }
19630
+ s.stop("Dependencies validated");
19631
+ prepareFunctionsForDeployment(functionsDir, config.verbose);
19632
+ log.debug("Waiting for file system sync...");
19633
+ await new Promise((resolve4) => setTimeout(resolve4, 1e3));
19634
+ try {
19635
+ if (!config.skipBuild) {
19636
+ const s2 = Y2();
19637
+ s2.start("Building functions...");
19673
19638
  try {
19674
- const openCommand = process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open";
19675
- spawnSync7(`${openCommand} ${consoleUrl}`, { shell: true });
19676
- log.success("Opening Firebase Console...");
19677
- } catch {
19678
- log.warn("Could not open browser. Please open the URL manually.");
19639
+ execSync8("bun run build", {
19640
+ cwd: functionsDir,
19641
+ stdio: config.verbose ? "inherit" : "pipe"
19642
+ });
19643
+ s2.stop("Functions built");
19644
+ } catch (error2) {
19645
+ s2.stop("Build failed");
19646
+ throw error2;
19679
19647
  }
19680
19648
  }
19649
+ s.start("Deploying functions to Firebase...");
19650
+ const firebaseProjectDir = pathExists(joinPath(appDir, "firebase.json")) ? appDir : functionsDir;
19651
+ log.debug(`Using service account: ${serviceAccountPath}`);
19652
+ log.debug(`Firebase project directory: ${firebaseProjectDir}`);
19653
+ const args = buildFirebaseDeployArgs(
19654
+ "functions",
19655
+ projectId,
19656
+ config.debug,
19657
+ config.force ?? true
19658
+ // Default --force for functions (auto-sets artifact cleanup policy)
19659
+ );
19660
+ const result = executeFirebaseCommand(args, {
19661
+ cwd: firebaseProjectDir,
19662
+ serviceAccountPath,
19663
+ projectId,
19664
+ debug: config.debug
19665
+ });
19666
+ if (result.error) {
19667
+ s.stop("Deployment failed");
19668
+ throw result.error;
19669
+ }
19670
+ if (!result.success) {
19671
+ s.stop("Deployment failed");
19672
+ handleDeploymentFailure(
19673
+ result,
19674
+ `firebase ${args.join(" ")}`,
19675
+ serviceAccountPath
19676
+ );
19677
+ }
19678
+ s.stop("Functions deployed successfully");
19679
+ const functionNames = getDeployedFunctionNames(functionsDir);
19680
+ if (functionNames.length > 0) {
19681
+ const region = getFirebaseRegion(functionsDir);
19682
+ updateCloudRunIAM(
19683
+ functionNames,
19684
+ projectId,
19685
+ region,
19686
+ serviceAccountPath,
19687
+ config.verbose ?? false
19688
+ );
19689
+ }
19690
+ await autoSyncSecrets(functionsDir, projectId, config);
19691
+ } finally {
19692
+ restoreFunctionsAfterDeployment(functionsDir);
19681
19693
  }
19682
19694
  }
19683
- function showFirebaseJsonError(errors, appDir, deploymentType) {
19684
- const errorList = errors.map((e2) => `\u2022 ${e2}`).join("\n");
19685
- const firebaseJsonPath = joinPath(appDir, "firebase.json");
19686
- let configExample = "";
19687
- if (deploymentType === "frontend" || deploymentType === "both") {
19688
- configExample += `
19689
- Hosting config:
19690
- { "hosting": { "public": "dist", ... } }`;
19695
+
19696
+ // packages/tooling/src/apps/deploy-rules.ts
19697
+ init_utils();
19698
+ async function deployRules(appDir, serviceAccountPath, projectId, config, options) {
19699
+ const targets = [];
19700
+ if (options.firestore) {
19701
+ targets.push("firestore:rules");
19691
19702
  }
19692
- if (deploymentType === "functions" || deploymentType === "both") {
19693
- configExample += `
19694
- Functions config:
19695
- { "functions": [{ "source": "functions", ... }] }`;
19703
+ if (options.firestoreIndexes) {
19704
+ targets.push("firestore:indexes");
19696
19705
  }
19697
- Me(
19698
- `${errorList}
19699
-
19700
- Why it matters:
19701
- firebase.json defines your deployment configuration.
19702
- Without it, Firebase CLI doesn't know what to deploy.
19703
-
19704
- How to fix:
19705
- 1. Ensure firebase.json exists at: ${firebaseJsonPath}
19706
- 2. Add required configuration:${configExample}`,
19707
- "Firebase Configuration Error"
19706
+ if (options.storage) {
19707
+ targets.push("storage");
19708
+ }
19709
+ if (targets.length === 0) {
19710
+ return;
19711
+ }
19712
+ const targetNames = targets.join(", ");
19713
+ const s = Y2();
19714
+ s.start(`Deploying ${targetNames}...`);
19715
+ const args = buildFirebaseDeployArgs(
19716
+ targets,
19717
+ projectId,
19718
+ config.debug,
19719
+ config.force ?? true
19708
19720
  );
19709
- }
19710
- function clearFirebaseCache(appDir) {
19711
- const firebaseCacheDir = joinPath(appDir, ".firebase");
19712
- if (pathExists(firebaseCacheDir)) {
19713
- log.info("Clearing Firebase cache...");
19714
- const removed = safeRemove(firebaseCacheDir, { silent: true });
19715
- if (removed) {
19716
- log.success("Firebase cache cleared");
19717
- } else {
19718
- log.warn("Could not clear Firebase cache (non-critical)");
19719
- }
19721
+ const result = executeFirebaseCommand(args, {
19722
+ cwd: appDir,
19723
+ serviceAccountPath,
19724
+ projectId,
19725
+ debug: config.debug
19726
+ });
19727
+ if (result.error) {
19728
+ s.stop("Rules deployment failed");
19729
+ throw result.error;
19720
19730
  }
19731
+ if (!result.success) {
19732
+ s.stop("Rules deployment failed");
19733
+ handleDeploymentFailure(
19734
+ result,
19735
+ `firebase ${args.join(" ")}`,
19736
+ serviceAccountPath
19737
+ );
19738
+ }
19739
+ s.stop(`${targetNames} deployed successfully`);
19721
19740
  }
19722
19741
 
19723
19742
  // packages/tooling/src/apps/deploy-vercel-frontend.ts
@@ -19791,8 +19810,26 @@ async function uploadFiles(files, token, orgId) {
19791
19810
  );
19792
19811
  }
19793
19812
  }
19794
- async function createDeployment(files, token, orgId, projectId, projectName) {
19813
+ function loadVercelConfig(appDir) {
19814
+ const configPath = joinPath(appDir, "vercel.json");
19815
+ if (!pathExists(configPath)) return {};
19816
+ try {
19817
+ const raw = readSync(configPath);
19818
+ const config = JSON.parse(raw);
19819
+ const result = {};
19820
+ if (config.rewrites) result.rewrites = config.rewrites;
19821
+ if (config.redirects) result.redirects = config.redirects;
19822
+ if (config.headers) result.headers = config.headers;
19823
+ if (config.cleanUrls != null) result.cleanUrls = config.cleanUrls;
19824
+ if (config.trailingSlash != null) result.trailingSlash = config.trailingSlash;
19825
+ return result;
19826
+ } catch {
19827
+ return {};
19828
+ }
19829
+ }
19830
+ async function createDeployment(files, token, orgId, projectId, projectName, appDir) {
19795
19831
  const q2 = teamQuery(orgId);
19832
+ const vercelConfig = loadVercelConfig(appDir);
19796
19833
  const body = {
19797
19834
  name: projectName,
19798
19835
  project: projectId,
@@ -19806,7 +19843,8 @@ async function createDeployment(files, token, orgId, projectId, projectName) {
19806
19843
  buildCommand: "",
19807
19844
  installCommand: "",
19808
19845
  outputDirectory: "."
19809
- }
19846
+ },
19847
+ ...vercelConfig
19810
19848
  };
19811
19849
  const res = await fetch(`${VERCEL_API2}/v13/deployments${q2}`, {
19812
19850
  method: "POST",
@@ -19890,7 +19928,8 @@ async function deployVercelFrontend(appDir, _config) {
19890
19928
  token,
19891
19929
  orgId,
19892
19930
  projectId,
19893
- project.projectName
19931
+ project.projectName,
19932
+ appDir
19894
19933
  );
19895
19934
  log.info(`Deployment ${deployment.id} created, waiting...`);
19896
19935
  const ready = await waitForReady(deployment.id, token, orgId);
@@ -20058,6 +20097,12 @@ async function main6(options = {}) {
20058
20097
  process.exit(1);
20059
20098
  }
20060
20099
  const appDir = appName ? detectAppDir(appName) : projectRoot;
20100
+ if (checkConfigPlaceholders(appDir)) {
20101
+ throw new DoNotDevError(
20102
+ "Config files contain unreplaced template placeholders. Fix before deploying.",
20103
+ "configuration-error"
20104
+ );
20105
+ }
20061
20106
  const appProviderInfo = detectProvider(appDir);
20062
20107
  const hasVercelConfig = pathExists(joinPath(appDir, "vercel.json"));
20063
20108
  let deploymentType = config.deploymentType;
@@ -20164,7 +20209,7 @@ async function main6(options = {}) {
20164
20209
  staging: isStaging
20165
20210
  });
20166
20211
  if (!serviceAccountResult.valid) {
20167
- const firebaseConfig2 = validateFirebaseJson2(appDir);
20212
+ const firebaseConfig2 = validateFirebaseJson(appDir);
20168
20213
  await showServiceAccountError(
20169
20214
  serviceAccountResult.info,
20170
20215
  firebaseConfig2.projectId
@@ -20183,7 +20228,7 @@ async function main6(options = {}) {
20183
20228
  }
20184
20229
  }
20185
20230
  if (!projectId) {
20186
- const fallbackConfig = validateFirebaseJson2(appDir);
20231
+ const fallbackConfig = validateFirebaseJson(appDir);
20187
20232
  projectId = serviceAccountResult.info.projectId || fallbackConfig.projectId;
20188
20233
  }
20189
20234
  if (!projectId) {
@@ -20198,7 +20243,7 @@ async function main6(options = {}) {
20198
20243
  } else {
20199
20244
  config.project = projectId;
20200
20245
  }
20201
- const firebaseConfig = await validateFirebaseJson2(appDir);
20246
+ const firebaseConfig = await validateFirebaseJson(appDir);
20202
20247
  if (!firebaseConfig.valid) {
20203
20248
  showFirebaseJsonError(firebaseConfig.errors, appDir, deploymentType);
20204
20249
  process.exit(1);
@@ -20679,7 +20724,10 @@ async function createApp(appName, appConfig, workspaceRoot, templatesRoot) {
20679
20724
  backendPlatform,
20680
20725
  isFirebase: backendPlatform === "firebase",
20681
20726
  isSupabase: backendPlatform === "supabase",
20682
- isVercel: backendPlatform === "vercel"
20727
+ isVercel: backendPlatform === "vercel",
20728
+ needsAuth: appConfig.userAuth !== "none",
20729
+ needsBilling: appConfig.billing,
20730
+ needsOAuth: appConfig.userAuth === "social" || appConfig.userAuth === "full-social"
20683
20731
  };
20684
20732
  const templateSourceDir = joinPath(templatesRoot, templateDir);
20685
20733
  const templateFiles = await glob("**/*", {
@@ -20710,8 +20758,6 @@ async function createApp(appName, appConfig, workspaceRoot, templatesRoot) {
20710
20758
  });
20711
20759
  for (const file of overlayFiles) {
20712
20760
  if (file.startsWith("env.fragment")) continue;
20713
- if (file === "vercel.headers.example") continue;
20714
- if (file === "vercel.json.example") continue;
20715
20761
  if (file === "src/config/providers.ts.example") {
20716
20762
  const variantFile = `src/config/providers.${appTemplate}.ts.example`;
20717
20763
  if (overlayFiles.includes(variantFile)) continue;
@@ -20748,32 +20794,6 @@ async function createApp(appName, appConfig, workspaceRoot, templatesRoot) {
20748
20794
  const fragment = readSync(fragmentPath);
20749
20795
  await write(envPath, baseEnv + "\n" + fragment, { overwrite: true });
20750
20796
  }
20751
- if (deployConfig === "vercel-supabase") {
20752
- const vercelPath = joinPath(appDir, "vercel.json");
20753
- const headersFragmentPath = joinPath(
20754
- overlayDir,
20755
- "vercel.headers.example"
20756
- );
20757
- const fullVercelPath = joinPath(overlayDir, "vercel.json.example");
20758
- if (pathExists(vercelPath) && pathExists(headersFragmentPath)) {
20759
- const vercelJson = readSync(vercelPath, { format: "json" });
20760
- const headersFragment = readSync(headersFragmentPath, {
20761
- format: "json"
20762
- });
20763
- vercelJson.headers = [
20764
- ...vercelJson.headers ?? [],
20765
- ...headersFragment
20766
- ];
20767
- await write(vercelPath, vercelJson, {
20768
- format: "json",
20769
- overwrite: true
20770
- });
20771
- } else if (pathExists(fullVercelPath)) {
20772
- await copy(fullVercelPath, vercelPath);
20773
- if (await isTextFile(vercelPath))
20774
- await replacePlaceholders(vercelPath, replacements);
20775
- }
20776
- }
20777
20797
  }
20778
20798
  }
20779
20799
  const executionMode = detectExecutionMode();
@@ -20843,7 +20863,7 @@ async function createApp(appName, appConfig, workspaceRoot, templatesRoot) {
20843
20863
  }
20844
20864
  }
20845
20865
  }
20846
- const deploymentTemplateDir = joinPath(templatesRoot, "root-consumer");
20866
+ const deploymentTemplateDir = joinPath(templatesRoot, "deploy-config");
20847
20867
  if (deployConfig === "firebase") {
20848
20868
  const firebaseJsonSource = joinPath(
20849
20869
  deploymentTemplateDir,
@@ -20955,7 +20975,7 @@ async function createApp(appName, appConfig, workspaceRoot, templatesRoot) {
20955
20975
  }
20956
20976
  }
20957
20977
  }
20958
- if (deployConfig === "vercel-vercel") {
20978
+ if (deployConfig === "vercel-supabase" || deployConfig === "vercel-vercel") {
20959
20979
  const vercelJsonSource = joinPath(
20960
20980
  deploymentTemplateDir,
20961
20981
  "vercel.json.example"
@@ -21097,7 +21117,7 @@ function detectExecutionMode2() {
21097
21117
  }
21098
21118
  return "published";
21099
21119
  }
21100
- async function main9(options) {
21120
+ async function main9(_options, name) {
21101
21121
  try {
21102
21122
  Ie("\u{1F680} DoNotDev Project Creator");
21103
21123
  try {
@@ -21117,7 +21137,7 @@ async function main9(options) {
21117
21137
  const executionMode = detectExecutionMode2();
21118
21138
  const monorepoRoot = process.cwd();
21119
21139
  const templatesRoot = getTemplatesRoot();
21120
- let projectName = options?.projectName || "";
21140
+ let projectName = name || "";
21121
21141
  while (!projectName) {
21122
21142
  const projectNameInput = await askForInput("Project name", "my-project");
21123
21143
  if (!isValidFileName(projectNameInput)) {
@@ -21381,13 +21401,6 @@ async function main9(options) {
21381
21401
  supabase: hasSupabase,
21382
21402
  stripe: hasBilling
21383
21403
  };
21384
- const firebaseRootFiles = /* @__PURE__ */ new Set([
21385
- "firebase.json.example",
21386
- ".firebaserc.example",
21387
- "firestore.rules.example",
21388
- "firestore.indexes.json.example",
21389
- "storage.rules.example"
21390
- ]);
21391
21404
  const files = await glob("**/*", {
21392
21405
  cwd: rootTemplateDir,
21393
21406
  dot: true,
@@ -21395,7 +21408,6 @@ async function main9(options) {
21395
21408
  });
21396
21409
  for (const file of files) {
21397
21410
  if (file === "package.json.example") continue;
21398
- if (firebaseRootFiles.has(file)) continue;
21399
21411
  const sourcePath = joinPath(rootTemplateDir, file);
21400
21412
  let destFileName = file;
21401
21413
  if (destFileName.endsWith(".example")) {
@@ -22222,13 +22234,16 @@ async function findCacheItems(targetDir, verbose) {
22222
22234
  check(joinPath(targetDir, "node_modules", ".vite"));
22223
22235
  check(joinPath(targetDir, "tsconfig.tsbuildinfo"));
22224
22236
  check(joinPath(targetDir, "tsconfig.build.tsbuildinfo"));
22225
- const generatedLogs = await glob(["**/*.generated.log"], {
22226
- cwd: targetDir,
22227
- absolute: true,
22228
- onlyFiles: true,
22229
- ignore: ["**/.git/**", "**/node_modules/**"]
22230
- });
22231
- for (const file of generatedLogs) {
22237
+ const generatedFiles = await glob(
22238
+ ["**/*.generated.log", "**/*.generated.ts"],
22239
+ {
22240
+ cwd: targetDir,
22241
+ absolute: true,
22242
+ onlyFiles: true,
22243
+ ignore: ["**/.git/**", "**/node_modules/**"]
22244
+ }
22245
+ );
22246
+ for (const file of generatedFiles) {
22232
22247
  if (!matches.has(file)) {
22233
22248
  matches.add(file);
22234
22249
  if (verbose) {