@omnibase/cli 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/commands/auth.js +1 -1
  2. package/dist/commands/auth.js.map +1 -1
  3. package/dist/commands/cloud.d.ts +42 -0
  4. package/dist/commands/cloud.d.ts.map +1 -1
  5. package/dist/commands/cloud.js +488 -80
  6. package/dist/commands/cloud.js.map +1 -1
  7. package/dist/commands/docs.d.ts +3 -0
  8. package/dist/commands/docs.d.ts.map +1 -0
  9. package/dist/commands/docs.js +105 -0
  10. package/dist/commands/docs.js.map +1 -0
  11. package/dist/commands/permissions.d.ts.map +1 -1
  12. package/dist/commands/permissions.js +51 -7
  13. package/dist/commands/permissions.js.map +1 -1
  14. package/dist/commands/restart.d.ts.map +1 -1
  15. package/dist/commands/restart.js +7 -3
  16. package/dist/commands/restart.js.map +1 -1
  17. package/dist/commands/stripe.d.ts.map +1 -1
  18. package/dist/commands/stripe.js +148 -26
  19. package/dist/commands/stripe.js.map +1 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +235 -34
  22. package/dist/index.js.map +1 -1
  23. package/dist/lib/omnibase.js +1 -1
  24. package/dist/lib/omnibase.js.map +1 -1
  25. package/dist/services/db/generate/policies.d.ts +1 -1
  26. package/dist/services/db/generate/policies.d.ts.map +1 -1
  27. package/dist/services/db/generate/policies.js +3 -3
  28. package/dist/services/db/generate/policies.js.map +1 -1
  29. package/dist/services/db/generate/rls/diff.d.ts.map +1 -1
  30. package/dist/services/db/generate/rls/diff.js +60 -4
  31. package/dist/services/db/generate/rls/diff.js.map +1 -1
  32. package/dist/services/db/generate/rls/emit.d.ts +1 -0
  33. package/dist/services/db/generate/rls/emit.d.ts.map +1 -1
  34. package/dist/services/db/generate/rls/emit.js +29 -4
  35. package/dist/services/db/generate/rls/emit.js.map +1 -1
  36. package/dist/services/db/migrate.d.ts.map +1 -1
  37. package/dist/services/db/migrate.js +8 -4
  38. package/dist/services/db/migrate.js.map +1 -1
  39. package/dist/services/docs/client.d.ts +28 -0
  40. package/dist/services/docs/client.d.ts.map +1 -0
  41. package/dist/services/docs/client.js +140 -0
  42. package/dist/services/docs/client.js.map +1 -0
  43. package/dist/utils/agent-files.d.ts +2 -0
  44. package/dist/utils/agent-files.d.ts.map +1 -0
  45. package/dist/utils/agent-files.js +70 -0
  46. package/dist/utils/agent-files.js.map +1 -0
  47. package/dist/utils/api-client.d.ts.map +1 -1
  48. package/dist/utils/api-client.js +3 -1
  49. package/dist/utils/api-client.js.map +1 -1
  50. package/dist/utils/docker.d.ts +7 -1
  51. package/dist/utils/docker.d.ts.map +1 -1
  52. package/dist/utils/docker.js +45 -22
  53. package/dist/utils/docker.js.map +1 -1
  54. package/dist/utils/environment.d.ts +3 -0
  55. package/dist/utils/environment.d.ts.map +1 -1
  56. package/dist/utils/environment.js +24 -0
  57. package/dist/utils/environment.js.map +1 -1
  58. package/dist/utils/permission-namespaces.d.ts +33 -0
  59. package/dist/utils/permission-namespaces.d.ts.map +1 -0
  60. package/dist/utils/permission-namespaces.js +326 -0
  61. package/dist/utils/permission-namespaces.js.map +1 -0
  62. package/dist/utils/start-summary.d.ts +21 -0
  63. package/dist/utils/start-summary.d.ts.map +1 -0
  64. package/dist/utils/start-summary.js +55 -0
  65. package/dist/utils/start-summary.js.map +1 -0
  66. package/dist/utils/versions.d.ts +7 -0
  67. package/dist/utils/versions.d.ts.map +1 -0
  68. package/dist/utils/versions.js +64 -0
  69. package/dist/utils/versions.js.map +1 -0
  70. package/docker/db/000019_rls_helpers_security_definer.down.sql +75 -0
  71. package/docker/db/000019_rls_helpers_security_definer.up.sql +84 -0
  72. package/docker/db/000020_narrow_anon_user_grants.down.sql +10 -0
  73. package/docker/db/000020_narrow_anon_user_grants.up.sql +64 -0
  74. package/docker/db/000021_pg_trgm_schema.down.sql +6 -0
  75. package/docker/db/000021_pg_trgm_schema.up.sql +8 -0
  76. package/docker/db/000022_drop_stripe_id_mappings.down.sql +18 -0
  77. package/docker/db/000022_drop_stripe_id_mappings.up.sql +1 -0
  78. package/docker/db/000023_email_tenant_templates.down.sql +30 -0
  79. package/docker/db/000023_email_tenant_templates.up.sql +48 -0
  80. package/docker/db/000024_email_history.down.sql +1 -0
  81. package/docker/db/000024_email_history.up.sql +15 -0
  82. package/docker/db/000025_manage_billing.down.sql +4 -0
  83. package/docker/db/000025_manage_billing.up.sql +5 -0
  84. package/docker/db/000026_authenticated_role.down.sql +2 -0
  85. package/docker/db/000026_authenticated_role.up.sql +21 -0
  86. package/docker/db/000027_unique_active_tenant.down.sql +1 -0
  87. package/docker/db/000027_unique_active_tenant.up.sql +13 -0
  88. package/docker/db/000028_drop_enterprise_pricing.down.sql +7 -0
  89. package/docker/db/000028_drop_enterprise_pricing.up.sql +8 -0
  90. package/docker/docker-compose.base.yml +11 -10
  91. package/docker/docker-compose.dev.yml +4 -4
  92. package/package.json +5 -5
  93. package/templates/.env.example +36 -0
  94. package/templates/AGENTS.md +40 -0
  95. package/templates/CLAUDE.md +1 -0
  96. package/templates/omnibase.toml +1 -0
  97. package/templates/stripe/example.config.json +7 -1
  98. package/templates/permissions/storage.ts +0 -50
  99. package/templates/permissions/tenants.ts +0 -120
  100. package/templates/permissions/types.ts +0 -16
@@ -36,9 +36,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.unwrapManagedHostingData = unwrapManagedHostingData;
39
40
  exports.packageWorkerBundle = packageWorkerBundle;
40
41
  exports.resolveBundleEntry = resolveBundleEntry;
42
+ exports.isGoneBranchStatus = isGoneBranchStatus;
43
+ exports.findLiveBranchByName = findLiveBranchByName;
44
+ exports.pickLiveBranch = pickLiveBranch;
45
+ exports.buildBranchEnv = buildBranchEnv;
46
+ exports.stripUnresolvedOidcProviders = stripUnresolvedOidcProviders;
41
47
  exports.pushEnvConfig = pushEnvConfig;
48
+ exports.findPlanById = findPlanById;
49
+ exports.findPostgresById = findPostgresById;
42
50
  exports.addCloudCommands = addCloudCommands;
43
51
  const child_process_1 = require("child_process");
44
52
  const promises_1 = require("fs/promises");
@@ -55,6 +63,9 @@ const logger_1 = require("../utils/logger");
55
63
  const errors_1 = require("../utils/errors");
56
64
  const api_client_1 = require("../utils/api-client");
57
65
  const config_1 = require("../utils/config");
66
+ function unwrapManagedHostingData(body) {
67
+ return (body?.data ?? body);
68
+ }
58
69
  /**
59
70
  * Login to OmniBase Cloud
60
71
  */
@@ -67,7 +78,7 @@ async function login(apiKey, options) {
67
78
  Authorization: `Bearer ${apiKey}`,
68
79
  },
69
80
  });
70
- const data = response.data;
81
+ const data = unwrapManagedHostingData(response.data);
71
82
  if (!data?.tenant_id) {
72
83
  throw new Error("Invalid API key");
73
84
  }
@@ -214,25 +225,20 @@ async function listProfiles() {
214
225
  });
215
226
  }
216
227
  /**
217
- * Get deployments from config or fall back to legacy single-worker dir
228
+ * Get deployments from config
218
229
  */
219
230
  function getDeployments(root) {
220
231
  const config = (0, config_1.loadConfig)(root);
221
232
  if (config.deployments.length > 0)
222
233
  return config.deployments;
223
- const legacyWorkersDir = path.join(root, "omnibase", "workers");
224
- if (fs.existsSync(legacyWorkersDir)) {
225
- return [{ name: "default", path: "workers" }];
226
- }
227
- throw new Error("No deployments found. Add [[deployments]] to omnibase/omnibase.toml\n" +
228
- " or create omnibase/workers/ for the default deployment.");
234
+ throw new Error("No deployments found. Add [[deployments]] to omnibase/omnibase.toml.");
229
235
  }
230
236
  /**
231
237
  * Deploy workers to Cloudflare via managed hosting
232
238
  */
233
239
  async function deployWorkers(envFlag, nameFlag, allFlag) {
234
240
  const root = (0, environment_1.findOmnibaseRoot)();
235
- const env = await (0, environment_1.selectEnvironment)(envFlag);
241
+ const env = await (0, environment_1.resolveEnvironment)(envFlag);
236
242
  if (env.name === "local") {
237
243
  logger_1.logger.warn("Workers deployment is not available for local environment.");
238
244
  logger_1.logger.log("Use --env flag to specify a cloud environment:");
@@ -274,10 +280,12 @@ async function deployWorkers(envFlag, nameFlag, allFlag) {
274
280
  });
275
281
  targets = [selected];
276
282
  }
283
+ const failures = [];
277
284
  for (const dep of targets) {
278
285
  const workersDir = path.join(root, "omnibase", dep.path ?? dep.name);
279
286
  if (!fs.existsSync(workersDir)) {
280
287
  logger_1.logger.fail(`Deployment '${dep.name}' directory not found: ${workersDir}`);
288
+ failures.push(dep.name);
281
289
  continue;
282
290
  }
283
291
  logger_1.logger.start(`Building '${dep.name}' for ${env.name}...`);
@@ -290,6 +298,7 @@ async function deployWorkers(envFlag, nameFlag, allFlag) {
290
298
  }
291
299
  catch (error) {
292
300
  logger_1.logger.fail(`Build failed for '${dep.name}'. Check the output above.`);
301
+ failures.push(dep.name);
293
302
  continue;
294
303
  }
295
304
  const bundle = await packageWorkerBundle(workersDir, secrets);
@@ -297,13 +306,18 @@ async function deployWorkers(envFlag, nameFlag, allFlag) {
297
306
  logger_1.logger.start(`Deploying '${dep.name}'...`);
298
307
  try {
299
308
  const result = await uploadToManagedHosting(env, bundle, dep.name);
309
+ const deployed = unwrapManagedHostingData(result);
300
310
  logger_1.logger.succeed(`${dep.name} deployed`);
301
- logger_1.logger.log(` URL: ${result.data?.url}`);
311
+ logger_1.logger.log(` URL: ${deployed?.url}`);
302
312
  }
303
313
  catch (error) {
304
314
  logger_1.logger.fail(`${dep.name} deploy failed: ${(0, errors_1.formatHttpError)(error)}`);
315
+ failures.push(dep.name);
305
316
  }
306
317
  }
318
+ if (failures.length > 0) {
319
+ throw new Error(`Failed to deploy: ${failures.join(", ")}`);
320
+ }
307
321
  }
308
322
  /**
309
323
  * Turn a `wrangler deploy --dry-run --outdir .bundle` output into a
@@ -386,7 +400,7 @@ async function addDirToZip(folder, dir, skip) {
386
400
  }
387
401
  }
388
402
  }
389
- async function uploadToManagedHosting(env, bundle, deploymentName = "default") {
403
+ async function uploadToManagedHosting(env, bundle, deploymentName) {
390
404
  const api = (0, api_client_1.createManagedHostingClient)(env);
391
405
  const form = new form_data_1.default();
392
406
  form.append("bundle", bundle, {
@@ -407,6 +421,146 @@ async function uploadToManagedHosting(env, bundle, deploymentName = "default") {
407
421
  throw new Error((0, errors_1.formatHttpError)(error));
408
422
  }
409
423
  }
424
+ const GONE_BRANCH_STATUSES = new Set(["deleted", "deleting"]);
425
+ const FAILED_BRANCH_STATUSES = new Set([
426
+ "failed",
427
+ "failed_deletion",
428
+ "suspended",
429
+ "deleted",
430
+ ]);
431
+ function isGoneBranchStatus(status) {
432
+ return GONE_BRANCH_STATUSES.has(status);
433
+ }
434
+ function findLiveBranchByName(branches, name) {
435
+ return branches.find((branch) => branch.name === name && !isGoneBranchStatus(branch.status));
436
+ }
437
+ function pickLiveBranch(branches, ref) {
438
+ const matches = branches.filter((branch) => branch.id === ref || branch.name === ref || branch.slug === ref);
439
+ return (matches.find((branch) => !isGoneBranchStatus(branch.status)) ?? matches[0]);
440
+ }
441
+ function resolveProjectId(projectIdFlag) {
442
+ const root = (0, environment_1.findOmnibaseRoot)();
443
+ const config = (0, config_1.loadConfig)(root);
444
+ const projectId = projectIdFlag ?? config.project_id;
445
+ if (!projectId) {
446
+ throw new Error("project_id is required. Provide --project-id or set it in omnibase.toml");
447
+ }
448
+ return projectId;
449
+ }
450
+ async function listProjectBranches(api, projectId) {
451
+ const response = await api.get(`/api/v1/projects/${projectId}/branches`);
452
+ return Array.isArray(response.data) ? response.data : [];
453
+ }
454
+ async function getBranchDetail(api, branchId) {
455
+ const response = await api.get(`/api/v1/project_branches/${branchId}`);
456
+ return response.data;
457
+ }
458
+ function isNotFound(error) {
459
+ return axios_1.default.isAxiosError(error) && error.response?.status === 404;
460
+ }
461
+ function sleep(ms) {
462
+ return new Promise((resolve) => setTimeout(resolve, ms));
463
+ }
464
+ function parseSeconds(value, fallback) {
465
+ if (value === undefined)
466
+ return fallback;
467
+ const seconds = Number(value);
468
+ if (!Number.isFinite(seconds) || seconds <= 0) {
469
+ throw new Error(`Invalid timeout: ${value}`);
470
+ }
471
+ return seconds;
472
+ }
473
+ async function checkBranchHealth(apiUrl) {
474
+ try {
475
+ const response = await axios_1.default.get(`${apiUrl.replace(/\/+$/, "")}/health/ready`, { timeout: 10000, validateStatus: (status) => status === 200 });
476
+ return response.status === 200;
477
+ }
478
+ catch {
479
+ return false;
480
+ }
481
+ }
482
+ async function waitForBranchActive(api, branchId, timeoutMs, quiet) {
483
+ const deadline = Date.now() + timeoutMs;
484
+ let lastStatus = "";
485
+ while (Date.now() < deadline) {
486
+ let detail;
487
+ try {
488
+ detail = await getBranchDetail(api, branchId);
489
+ }
490
+ catch (error) {
491
+ if (!isNotFound(error))
492
+ throw error;
493
+ }
494
+ if (detail) {
495
+ if (detail.status !== lastStatus) {
496
+ lastStatus = detail.status;
497
+ if (!quiet)
498
+ logger_1.logger.info(`Branch status: ${detail.status}`);
499
+ }
500
+ if (detail.status === "active")
501
+ return detail;
502
+ if (FAILED_BRANCH_STATUSES.has(detail.status)) {
503
+ const message = detail.error_message
504
+ ? `${detail.status}: ${detail.error_message}`
505
+ : detail.status;
506
+ throw new Error(`Branch ${detail.name} is ${message}`);
507
+ }
508
+ }
509
+ await sleep(5000);
510
+ }
511
+ throw new Error(`Timed out after ${Math.round(timeoutMs / 1000)}s waiting for branch ${branchId} to become active`);
512
+ }
513
+ async function waitForBranchHealthy(apiUrl, timeoutMs, quiet) {
514
+ const deadline = Date.now() + timeoutMs;
515
+ while (Date.now() < deadline) {
516
+ if (await checkBranchHealth(apiUrl)) {
517
+ if (!quiet)
518
+ logger_1.logger.succeed(`Branch is healthy at ${apiUrl}`);
519
+ return;
520
+ }
521
+ await sleep(5000);
522
+ }
523
+ throw new Error(`Timed out after ${Math.round(timeoutMs / 1000)}s waiting for ${apiUrl}/health/ready`);
524
+ }
525
+ async function getApiServiceKey(api, branchId) {
526
+ try {
527
+ const response = await api.get(`/api/v1/project_branches/${branchId}/api-service-key`);
528
+ const keyData = response.data?.data ?? response.data;
529
+ const serviceKey = keyData?.api_service_key ?? keyData?.service_key;
530
+ if (!serviceKey) {
531
+ throw new Error("API service key missing from response");
532
+ }
533
+ return serviceKey;
534
+ }
535
+ catch (error) {
536
+ throw new Error(`Failed to load branch API service key: ${(0, errors_1.formatHttpError)(error)}`);
537
+ }
538
+ }
539
+ function buildBranchEnv(input) {
540
+ const apiUrl = input.apiUrl.replace(/\/+$/, "");
541
+ const hostname = new URL(apiUrl).hostname;
542
+ const composedSlug = hostname.split(".")[0];
543
+ if (!composedSlug) {
544
+ throw new Error(`Could not derive a branch slug from ${input.apiUrl}`);
545
+ }
546
+ const workerDomain = (input.workerDomain ?? "omnibase-workers.app").replace(/^\.+/, "");
547
+ const cookieDomain = input.cookieDomain ?? `.${workerDomain}`;
548
+ const dashboardUrl = (input.dashboardUrl ?? `https://${composedSlug}-dashboard.${workerDomain}`).replace(/\/+$/, "");
549
+ const postgrestUrl = (input.postgrestUrl ?? `${apiUrl}/api/v1/rest`).replace(/\/+$/, "");
550
+ return {
551
+ NEXT_PUBLIC_WEBSITE_URL: dashboardUrl,
552
+ WEBSITE_URL: dashboardUrl,
553
+ ALLOWED_RETURN_URLS: dashboardUrl,
554
+ NEXT_PUBLIC_OMNIBASE_WORKER_URL: dashboardUrl,
555
+ OMNIBASE_API_URL: apiUrl,
556
+ NEXT_PUBLIC_OMNIBASE_API_URL: apiUrl,
557
+ OMNIBASE_POSTGREST_URL: postgrestUrl,
558
+ OMNIBASE_SERVICE_KEY: input.serviceKey,
559
+ MANAGED_HOSTING_API_URL: input.managedHostingUrl,
560
+ NEXT_PUBLIC_MANAGED_HOSTING_API_URL: input.managedHostingUrl,
561
+ OMNIBASE_COOKIE_DOMAIN: cookieDomain,
562
+ };
563
+ }
410
564
  /**
411
565
  * Resolve a branch for the project from managed hosting. A `--env` value
412
566
  * matches by name, slug, or id; otherwise a single branch is auto-selected or
@@ -452,9 +606,31 @@ async function resolveBranch(managedHostingUrl, projectId, branchFlag) {
452
606
  *
453
607
  * {VAR} secrets resolve from process.env → omnibase/.env.<branch>.
454
608
  */
609
+ function stripUnresolvedOidcProviders(payload) {
610
+ const auth = payload.auth;
611
+ const providers = auth?.oidc;
612
+ if (!Array.isArray(providers))
613
+ return [];
614
+ const dropped = [];
615
+ auth.oidc = providers.filter((provider) => {
616
+ const unresolved = ["client_id", "client_secret"].some((key) => {
617
+ const value = provider[key];
618
+ return typeof value === "string" && /\{[A-Za-z_][A-Za-z0-9_]*\}/.test(value);
619
+ });
620
+ if (unresolved) {
621
+ dropped.push(String(provider.provider ?? "unknown"));
622
+ return false;
623
+ }
624
+ return true;
625
+ });
626
+ if (auth.oidc.length === 0) {
627
+ delete auth.oidc;
628
+ }
629
+ return dropped;
630
+ }
455
631
  async function pushEnvConfig(envFlag) {
456
632
  const root = (0, environment_1.findOmnibaseRoot)();
457
- const env = await (0, environment_1.selectEnvironment)(envFlag);
633
+ const env = await (0, environment_1.resolveEnvironment)(envFlag);
458
634
  if (env.name === "local") {
459
635
  logger_1.logger.warn("Environment push is not available for the local environment.");
460
636
  logger_1.logger.log(" omnibase cloud env push --env <branch>");
@@ -478,6 +654,10 @@ async function pushEnvConfig(envFlag) {
478
654
  (0, config_1.assertValidVersions)(resolved.versions);
479
655
  }
480
656
  const payload = (0, config_1.cloudConfigOf)(resolved);
657
+ const droppedOidc = stripUnresolvedOidcProviders(payload);
658
+ if (droppedOidc.length > 0) {
659
+ logger_1.logger.warn(`Skipping OIDC provider(s) with unresolved credentials: ${droppedOidc.join(", ")}`);
660
+ }
481
661
  const sections = Object.keys(payload);
482
662
  if (sections.length === 0) {
483
663
  logger_1.logger.info("Nothing to push: omnibase.toml has no cloud config sections.");
@@ -509,50 +689,104 @@ async function pushEnvConfig(envFlag) {
509
689
  throw new Error((0, errors_1.formatHttpError)(error));
510
690
  }
511
691
  }
512
- /**
513
- * Create a new branch
514
- */
692
+ function findPlanById(plans, planId) {
693
+ return plans.find((plan) => plan.id === planId);
694
+ }
695
+ function findPostgresById(plan, postgresId) {
696
+ return (plan.postgres ?? []).find((postgres) => postgres.id === postgresId);
697
+ }
698
+ async function fetchManagedPlans(api) {
699
+ const response = await api.get("/api/v1/projects/plans");
700
+ return response.data?.tiers ?? [];
701
+ }
702
+ async function resolveBranchTarget(api, options) {
703
+ const needsPlans = !options.plan || !options.postgres || !options.region;
704
+ let plans = [];
705
+ if (needsPlans) {
706
+ try {
707
+ plans = await fetchManagedPlans(api);
708
+ }
709
+ catch {
710
+ plans = [];
711
+ }
712
+ }
713
+ let plan;
714
+ if (options.plan && plans.length > 0) {
715
+ plan = findPlanById(plans, options.plan);
716
+ if (!plan) {
717
+ throw new Error(`Unknown plan '${options.plan}'. Available plans: ${plans.map((p) => p.id).join(", ")}`);
718
+ }
719
+ }
720
+ else if (options.plan) {
721
+ plan = { id: options.plan };
722
+ }
723
+ else if (plans.length > 0) {
724
+ plan = await (0, prompts_1.select)({
725
+ message: "Plan:",
726
+ choices: plans.map((p) => ({
727
+ name: `${p.display_name ?? p.name ?? p.id} (${p.id})`,
728
+ value: p,
729
+ })),
730
+ });
731
+ }
732
+ else {
733
+ return {
734
+ planId: await (0, prompts_1.input)({ message: "Plan ID:", default: "shared_tier" }),
735
+ postgresId: options.postgres ?? (await (0, prompts_1.input)({ message: "Postgres ID:", default: "postgres_shared" })),
736
+ region: options.region ?? (await (0, prompts_1.input)({ message: "Region:", default: "eu" })),
737
+ };
738
+ }
739
+ let postgresId = options.postgres;
740
+ if (postgresId) {
741
+ if ((plan.postgres ?? []).length > 0 && !findPostgresById(plan, postgresId)) {
742
+ throw new Error(`Postgres '${postgresId}' is not available for plan '${plan.id}'. Available: ${(plan.postgres ?? []).map((p) => p.id).join(", ")}`);
743
+ }
744
+ }
745
+ else if ((plan.postgres ?? []).length > 0) {
746
+ const postgres = await (0, prompts_1.select)({
747
+ message: "Postgres:",
748
+ choices: (plan.postgres ?? []).map((p) => ({
749
+ name: `${p.name} (${p.id})`,
750
+ value: p.id,
751
+ })),
752
+ });
753
+ postgresId = postgres;
754
+ }
755
+ else {
756
+ postgresId = await (0, prompts_1.input)({ message: "Postgres ID:", default: "postgres_shared" });
757
+ }
758
+ let region = options.region;
759
+ if (region) {
760
+ if ((plan.regions ?? []).length > 0 && !plan.regions.some((r) => r.id === region)) {
761
+ throw new Error(`Region '${region}' is not available for plan '${plan.id}'. Available: ${plan.regions.map((r) => r.id).join(", ")}`);
762
+ }
763
+ }
764
+ else if ((plan.regions ?? []).length > 0) {
765
+ region = await (0, prompts_1.select)({
766
+ message: "Region:",
767
+ choices: plan.regions.map((r) => ({ name: `${r.name} (${r.id})`, value: r.id })),
768
+ });
769
+ }
770
+ else {
771
+ region = await (0, prompts_1.input)({ message: "Region:", default: "eu" });
772
+ }
773
+ return { planId: plan.id, postgresId, region };
774
+ }
515
775
  async function branchNew(options) {
516
776
  const root = (0, environment_1.findOmnibaseRoot)();
517
777
  const config = (0, config_1.loadConfig)(root);
518
778
  const api = (0, api_client_1.createProfileClient)();
519
779
  const projectId = options.projectId ?? config.project_id ?? (await (0, prompts_1.input)({ message: "Project ID:" }));
520
780
  const branchName = options.name ?? (await (0, prompts_1.input)({ message: "Branch name:", default: "dev" }));
521
- const email = options.email ?? (await (0, prompts_1.input)({ message: "Billing email:" }));
522
- let region = options.region;
523
- let tier = options.tier;
524
- if (!region || !tier) {
525
- try {
526
- const optsRes = await api.get("/api/v1/options");
527
- const opts = optsRes.data;
528
- if (!region && opts.regions?.length) {
529
- region = await (0, prompts_1.select)({
530
- message: "Region:",
531
- choices: opts.regions.map((r) => ({ name: `${r.name} (${r.id})`, value: r.id })),
532
- });
533
- }
534
- if (!tier && opts.tiers?.length) {
535
- tier = await (0, prompts_1.select)({
536
- message: "Deployment tier:",
537
- choices: opts.tiers.map((t) => ({ name: `${t.name}`, value: t.id })),
538
- });
539
- }
540
- }
541
- catch {
542
- if (!region)
543
- region = await (0, prompts_1.input)({ message: "Region:", default: "syd" });
544
- if (!tier)
545
- tier = await (0, prompts_1.input)({ message: "Deployment tier:", default: "shared" });
546
- }
547
- }
781
+ const target = await resolveBranchTarget(api, options);
548
782
  logger_1.logger.start(`Creating branch '${branchName}'...`);
549
783
  try {
550
784
  const response = await api.post("/api/v1/project_branches", {
551
785
  project_id: projectId,
552
786
  branch_name: branchName,
553
- region,
554
- deployment_tier: tier,
555
- billing_email: email,
787
+ region: target.region,
788
+ plan_id: target.planId,
789
+ postgres_id: target.postgresId,
556
790
  });
557
791
  const data = response.data;
558
792
  logger_1.logger.succeed(`Branch '${branchName}' provisioning started`);
@@ -598,25 +832,142 @@ async function branchList(projectIdFlag) {
598
832
  throw new Error((0, errors_1.formatHttpError)(error));
599
833
  }
600
834
  }
835
+ async function branchEnsure(branchName, options) {
836
+ const api = (0, api_client_1.createProfileClient)();
837
+ const projectId = resolveProjectId(options.projectId);
838
+ const quiet = Boolean(options.json);
839
+ if (!quiet)
840
+ logger_1.logger.start(`Resolving branch '${branchName}'...`);
841
+ const branches = await listProjectBranches(api, projectId);
842
+ let branch = findLiveBranchByName(branches, branchName);
843
+ if (branch) {
844
+ if (!quiet)
845
+ logger_1.logger.succeed(`Reusing branch '${branch.name}' (${branch.id})`);
846
+ }
847
+ else {
848
+ if (!options.region || !options.plan || !options.postgres) {
849
+ throw new Error("--region, --plan, and --postgres are required when creating a branch");
850
+ }
851
+ if (!quiet)
852
+ logger_1.logger.start(`Creating branch '${branchName}'...`);
853
+ const response = await api.post("/api/v1/project_branches", {
854
+ project_id: projectId,
855
+ branch_name: branchName,
856
+ region: options.region,
857
+ plan_id: options.plan,
858
+ postgres_id: options.postgres,
859
+ });
860
+ branch = {
861
+ id: response.data.branch_id,
862
+ name: branchName,
863
+ slug: "",
864
+ status: response.data.status ?? "provisioning",
865
+ };
866
+ if (!quiet)
867
+ logger_1.logger.succeed(`Branch '${branchName}' provisioning started`);
868
+ }
869
+ let detail = {
870
+ ...branch,
871
+ project_id: projectId,
872
+ };
873
+ if (options.wait !== false) {
874
+ const timeoutMs = parseSeconds(options.timeout, 1800) * 1000;
875
+ const healthTimeoutMs = parseSeconds(options.healthTimeout, 600) * 1000;
876
+ detail = await waitForBranchActive(api, branch.id, timeoutMs, quiet);
877
+ if (!detail.api_url) {
878
+ throw new Error(`Branch ${detail.name} is active but has no API URL`);
879
+ }
880
+ await waitForBranchHealthy(detail.api_url, healthTimeoutMs, quiet);
881
+ }
882
+ if (options.json) {
883
+ logger_1.logger.log(JSON.stringify({
884
+ id: detail.id,
885
+ name: detail.name,
886
+ slug: detail.slug,
887
+ status: detail.status,
888
+ project_id: detail.project_id,
889
+ api_url: detail.api_url ?? null,
890
+ postgrest_url: detail.postgrest_url ?? null,
891
+ }));
892
+ return;
893
+ }
894
+ logger_1.logger.log("");
895
+ logger_1.logger.log(`Branch: ${detail.name} (${detail.id})`);
896
+ logger_1.logger.log(`Status: ${detail.status}`);
897
+ if (detail.api_url)
898
+ logger_1.logger.log(`API URL: ${detail.api_url}`);
899
+ logger_1.logger.log("");
900
+ logger_1.logger.log(`Next steps:`);
901
+ logger_1.logger.log(` omnibase cloud branch env ${detail.name} --output omnibase/.env.${detail.name}`);
902
+ logger_1.logger.log(` omnibase sync all --env ${detail.name}`);
903
+ logger_1.logger.log(` omnibase cloud workers deploy --all --env ${detail.name}`);
904
+ }
905
+ async function branchEnv(branchRef, options) {
906
+ const api = (0, api_client_1.createProfileClient)();
907
+ const projectId = resolveProjectId(options.projectId);
908
+ logger_1.logger.start(`Resolving branch '${branchRef}'...`);
909
+ const branches = await listProjectBranches(api, projectId);
910
+ const branch = pickLiveBranch(branches, branchRef);
911
+ if (!branch || isGoneBranchStatus(branch.status)) {
912
+ throw new Error(`Branch '${branchRef}' not found in project ${projectId}`);
913
+ }
914
+ const detail = await getBranchDetail(api, branch.id);
915
+ if (!detail.api_url) {
916
+ throw new Error(`Branch '${branchRef}' has no API URL yet`);
917
+ }
918
+ const serviceKey = await getApiServiceKey(api, branch.id);
919
+ const profile = (0, credentials_1.getActiveProfile)();
920
+ const managedHostingUrl = profile?.managed_hosting_url ?? process.env.MANAGED_HOSTING_API_URL;
921
+ if (!managedHostingUrl) {
922
+ throw new Error("No managed hosting URL configured. Run 'omnibase cloud login' or set MANAGED_HOSTING_API_URL.");
923
+ }
924
+ const env = buildBranchEnv({
925
+ apiUrl: detail.api_url,
926
+ postgrestUrl: detail.postgrest_url,
927
+ serviceKey,
928
+ managedHostingUrl,
929
+ workerDomain: options.workerDomain ?? process.env.OMNIBASE_WORKER_DOMAIN,
930
+ cookieDomain: options.cookieDomain ?? process.env.OMNIBASE_COOKIE_DOMAIN,
931
+ dashboardUrl: options.dashboardUrl,
932
+ });
933
+ const content = Object.entries(env)
934
+ .map(([key, value]) => `${key}=${value}`)
935
+ .join("\n") + "\n";
936
+ if (options.output) {
937
+ const target = path.resolve(options.output);
938
+ fs.mkdirSync(path.dirname(target), { recursive: true });
939
+ fs.writeFileSync(target, content, { mode: 0o600 });
940
+ logger_1.logger.succeed(`Wrote branch environment to ${target}`);
941
+ return;
942
+ }
943
+ logger_1.logger.succeed(`Resolved to ${detail.name} (${detail.id})`);
944
+ logger_1.logger.log(content.trimEnd());
945
+ }
601
946
  /**
602
947
  * Delete a branch by name or ID
603
948
  */
604
- async function branchDelete(branchRef, projectIdFlag) {
605
- const root = (0, environment_1.findOmnibaseRoot)();
949
+ async function branchDelete(branchRef, projectIdFlag, options = {}) {
606
950
  const api = (0, api_client_1.createProfileClient)();
607
- const config = (0, config_1.loadConfig)(root);
608
- const projectId = projectIdFlag ?? config.project_id;
609
- if (!projectId) {
610
- throw new Error("project_id is required. Provide --project-id or set it in omnibase.toml");
611
- }
951
+ const projectId = resolveProjectId(projectIdFlag);
612
952
  logger_1.logger.start(`Resolving branch '${branchRef}'...`);
613
- const response = await api.get(`/api/v1/projects/${projectId}/branches`);
614
- const branches = response.data;
615
- const match = branches.find((b) => b.id === branchRef || b.name === branchRef || b.slug === branchRef);
953
+ const branches = await listProjectBranches(api, projectId);
954
+ const match = pickLiveBranch(branches, branchRef);
616
955
  if (!match) {
956
+ if (options.ifExists) {
957
+ logger_1.logger.succeed(`Branch '${branchRef}' does not exist`);
958
+ return;
959
+ }
617
960
  logger_1.logger.fail(`Branch '${branchRef}' not found`);
618
961
  throw new Error(`Branch '${branchRef}' not found in project ${projectId}`);
619
962
  }
963
+ if (isGoneBranchStatus(match.status)) {
964
+ if (options.ifExists) {
965
+ logger_1.logger.succeed(`Branch '${branchRef}' is already ${match.status}`);
966
+ return;
967
+ }
968
+ logger_1.logger.fail(`Branch '${branchRef}' is already ${match.status}`);
969
+ throw new Error(`Branch '${branchRef}' is already ${match.status}`);
970
+ }
620
971
  logger_1.logger.succeed(`Resolved to ${match.name} (${match.id})`);
621
972
  logger_1.logger.start(`Deprovisioning branch '${branchRef}'...`);
622
973
  try {
@@ -632,7 +983,7 @@ async function branchDelete(branchRef, projectIdFlag) {
632
983
  * List workers for a branch
633
984
  */
634
985
  async function listWorkers(envFlag) {
635
- const env = await (0, environment_1.selectEnvironment)(envFlag);
986
+ const env = await (0, environment_1.resolveEnvironment)(envFlag);
636
987
  const api = (0, api_client_1.createManagedHostingClient)(env);
637
988
  const branchId = env.branchId;
638
989
  if (!branchId) {
@@ -658,7 +1009,7 @@ async function listWorkers(envFlag) {
658
1009
  * Add an account-level custom domain (e.g. example.com or *.example.com)
659
1010
  */
660
1011
  async function domainAdd(envFlag, domain) {
661
- const env = await (0, environment_1.selectEnvironment)(envFlag);
1012
+ const env = await (0, environment_1.resolveEnvironment)(envFlag);
662
1013
  const api = (0, api_client_1.createManagedHostingClient)(env);
663
1014
  logger_1.logger.start(`Adding domain ${domain}...`);
664
1015
  try {
@@ -684,7 +1035,7 @@ async function domainAdd(envFlag, domain) {
684
1035
  * List account-level domains
685
1036
  */
686
1037
  async function domainList(envFlag) {
687
- const env = await (0, environment_1.selectEnvironment)(envFlag);
1038
+ const env = await (0, environment_1.resolveEnvironment)(envFlag);
688
1039
  const api = (0, api_client_1.createManagedHostingClient)(env);
689
1040
  logger_1.logger.start("Fetching domains...");
690
1041
  try {
@@ -706,7 +1057,7 @@ async function domainList(envFlag) {
706
1057
  * Remove an account-level domain
707
1058
  */
708
1059
  async function domainRemove(envFlag, domainId) {
709
- const env = await (0, environment_1.selectEnvironment)(envFlag);
1060
+ const env = await (0, environment_1.resolveEnvironment)(envFlag);
710
1061
  const api = (0, api_client_1.createManagedHostingClient)(env);
711
1062
  logger_1.logger.start("Removing domain...");
712
1063
  try {
@@ -722,7 +1073,7 @@ async function domainRemove(envFlag, domainId) {
722
1073
  * Poll the status of an account-level domain until it activates or times out
723
1074
  */
724
1075
  async function domainStatus(envFlag, domainId, pollSeconds) {
725
- const env = await (0, environment_1.selectEnvironment)(envFlag);
1076
+ const env = await (0, environment_1.resolveEnvironment)(envFlag);
726
1077
  const api = (0, api_client_1.createManagedHostingClient)(env);
727
1078
  const deadline = Date.now() + pollSeconds * 1000;
728
1079
  try {
@@ -753,7 +1104,7 @@ async function domainStatus(envFlag, domainId, pollSeconds) {
753
1104
  * Attach a validated account domain to a worker
754
1105
  */
755
1106
  async function domainAttach(envFlag, domainId, workerName, hostname) {
756
- const env = await (0, environment_1.selectEnvironment)(envFlag);
1107
+ const env = await (0, environment_1.resolveEnvironment)(envFlag);
757
1108
  const api = (0, api_client_1.createManagedHostingClient)(env);
758
1109
  const branchId = env.branchId;
759
1110
  if (!branchId) {
@@ -777,7 +1128,7 @@ async function domainAttach(envFlag, domainId, workerName, hostname) {
777
1128
  * Detach a domain from a worker
778
1129
  */
779
1130
  async function domainDetach(envFlag, domainId) {
780
- const env = await (0, environment_1.selectEnvironment)(envFlag);
1131
+ const env = await (0, environment_1.resolveEnvironment)(envFlag);
781
1132
  const api = (0, api_client_1.createManagedHostingClient)(env);
782
1133
  const branchId = env.branchId;
783
1134
  if (!branchId) {
@@ -896,10 +1247,9 @@ function addCloudCommands(program) {
896
1247
  const workers = cloud
897
1248
  .command("workers")
898
1249
  .summary("Manage Cloudflare Workers deployments")
899
- .description("Deploy and inspect the Workers deployments defined in omnibase.toml " +
900
- "or `omnibase/workers/`.\n\n" +
901
- "Each deployment maps to a directory (default `omnibase/workers/`) " +
902
- "containing a `wrangler.toml`, `wrangler.jsonc`, or `wrangler.json`. " +
1250
+ .description("Deploy and inspect the Workers deployments defined in omnibase.toml.\n\n" +
1251
+ "Each deployment maps to a directory containing a `wrangler.toml`, " +
1252
+ "`wrangler.jsonc`, or `wrangler.json`. " +
903
1253
  "`deploy` ships a deployment to the managed hosting cloud; `list` shows " +
904
1254
  "what is currently deployed for a branch.");
905
1255
  workers
@@ -919,16 +1269,16 @@ function addCloudCommands(program) {
919
1269
  " package time.\n" +
920
1270
  "5. Upload the bundle to managed hosting, which runs " +
921
1271
  " `wrangler deploy --dispatch-namespace` and returns the live URL.\n\n" +
922
- "By default a single-deployment project deploys it directly; with " +
1272
+ "When a project has a single deployment it deploys directly; with " +
923
1273
  "multiple deployments you are prompted to select one. `--name` picks a " +
924
1274
  "specific deployment by name and `--all` deploys every deployment.\n\n" +
925
1275
  "Before: the branch must be provisioned (has a branch ID) and a profile " +
926
1276
  "must be configured (`omnibase cloud login`). Deployments must exist in " +
927
- "omnibase.toml or `omnibase/workers/`. Cloud environments are required — " +
1277
+ "omnibase.toml. Cloud environments are required — " +
928
1278
  "deploying to `local` is not supported.\n\n" +
929
1279
  "Environment variables: `{VAR}` references in the wrangler `[vars]` " +
930
1280
  "resolve from the branch env file. See the env resolution model on the " +
931
- "[`cloud env`](/reference/cli/cloud/env) page.\n\n" +
1281
+ "[`cloud env`](/cli/cloud/env) page.\n\n" +
932
1282
  "Caveats: values in `[vars]` are visible in the deployed worker — put " +
933
1283
  "secrets in `wrangler secret` or the managed-hosting secrets API, not in " +
934
1284
  "`[vars]`. Unresolved `{VAR}` values are left literal and the CLI warns.\n\n" +
@@ -1106,21 +1456,20 @@ function addCloudCommands(program) {
1106
1456
  .summary("Create a new project branch")
1107
1457
  .description("Provision a new branch (environment) for the project.\n\n" +
1108
1458
  "The project ID comes from `--project-id` or the `project_id` in " +
1109
- "omnibase.toml, and is prompted for if neither is set. Region and tier " +
1110
- "default to a picker fed by the managed hosting options endpoint " +
1111
- "(falling back to `syd` / `shared` prompts). A billing email is " +
1112
- "required.\n\n" +
1459
+ "omnibase.toml, and is prompted for if neither is set. Plan, Postgres, " +
1460
+ "and region default to pickers fed by the managed hosting plans " +
1461
+ "endpoint.\n\n" +
1113
1462
  "After: provisioning starts asynchronously. Once complete, use the " +
1114
1463
  "branch with `--env <branch>` on other commands.\n\n" +
1115
1464
  "```bash\n" +
1116
1465
  "omnibase cloud branch new --name staging\n" +
1117
- "omnibase cloud branch new --project-id proj_123 --name dev --region syd --tier shared\n" +
1466
+ "omnibase cloud branch new --project-id proj_123 --name dev --region eu --plan shared_tier --postgres postgres_shared\n" +
1118
1467
  "```")
1119
1468
  .option("--project-id <id>", "Project ID")
1120
1469
  .option("--name <name>", "Branch name")
1121
- .option("--region <region>", "Region (e.g. syd)")
1122
- .option("--tier <tier>", "Deployment tier (e.g. shared)")
1123
- .option("--email <email>", "Billing email")
1470
+ .option("--region <region>", "Region ID (e.g. eu, syd)")
1471
+ .option("--plan <id>", "Plan ID (e.g. shared_tier)")
1472
+ .option("--postgres <id>", "Postgres ID (e.g. postgres_shared)")
1124
1473
  .action(async (cmdOptions) => {
1125
1474
  try {
1126
1475
  await branchNew(cmdOptions);
@@ -1129,6 +1478,60 @@ function addCloudCommands(program) {
1129
1478
  await (0, errors_1.handleCommandError)(error);
1130
1479
  }
1131
1480
  });
1481
+ branch
1482
+ .command("ensure <branch>")
1483
+ .summary("Provision a branch if it does not exist and wait for it")
1484
+ .description("Idempotently provision a branch and wait until it is active and its " +
1485
+ "API reports ready.\n\n" +
1486
+ "An existing live branch with the same name is reused, so this is safe " +
1487
+ "to run on every CI job. When no branch exists, `--region`, `--plan`, " +
1488
+ "and `--postgres` are required.\n\n" +
1489
+ "With `--json`, prints a single JSON object instead of log output. Use " +
1490
+ "`--no-wait` to return as soon as provisioning starts.\n\n" +
1491
+ "```bash\n" +
1492
+ "omnibase cloud branch ensure pr-123 --region eu --plan shared_tier --postgres postgres_shared\n" +
1493
+ "omnibase cloud branch ensure pr-123 --region eu --plan shared_tier --postgres postgres_shared --json\n" +
1494
+ "```")
1495
+ .option("--project-id <id>", "Project ID")
1496
+ .option("--region <region>", "Region ID (e.g. eu, syd)")
1497
+ .option("--plan <id>", "Plan ID (e.g. shared_tier)")
1498
+ .option("--postgres <id>", "Postgres ID (e.g. postgres_shared)")
1499
+ .option("--no-wait", "Return immediately after provisioning starts")
1500
+ .option("--timeout <seconds>", "Provisioning timeout in seconds", "1800")
1501
+ .option("--health-timeout <seconds>", "Health check timeout in seconds", "600")
1502
+ .option("--json", "Print the resolved branch as JSON")
1503
+ .action(async (branchName, cmdOptions) => {
1504
+ try {
1505
+ await branchEnsure(branchName, cmdOptions);
1506
+ }
1507
+ catch (error) {
1508
+ await (0, errors_1.handleCommandError)(error);
1509
+ }
1510
+ });
1511
+ branch
1512
+ .command("env <branch>")
1513
+ .summary("Export branch URLs and keys as environment variables")
1514
+ .description("Resolve a branch's API URL, PostgREST URL, service key, and dashboard " +
1515
+ "worker URL, then write them as dotenv content.\n\n" +
1516
+ "Use `--output` to write a gitignored `omnibase/.env.<branch>` file " +
1517
+ "before `omnibase sync` or `omnibase cloud workers deploy`.\n\n" +
1518
+ "```bash\n" +
1519
+ "omnibase cloud branch env pr-123 --output omnibase/.env.pr-123\n" +
1520
+ "omnibase cloud branch env pr-123\n" +
1521
+ "```")
1522
+ .option("--project-id <id>", "Project ID")
1523
+ .option("--worker-domain <domain>", "Workers domain", "omnibase-workers.app")
1524
+ .option("--cookie-domain <domain>", "Cookie domain")
1525
+ .option("--dashboard-url <url>", "Override the dashboard URL")
1526
+ .option("--output <path>", "Write dotenv output to a file")
1527
+ .action(async (branchRef, cmdOptions) => {
1528
+ try {
1529
+ await branchEnv(branchRef, cmdOptions);
1530
+ }
1531
+ catch (error) {
1532
+ await (0, errors_1.handleCommandError)(error);
1533
+ }
1534
+ });
1132
1535
  branch
1133
1536
  .command("list")
1134
1537
  .summary("List project branches")
@@ -1154,15 +1557,20 @@ function addCloudCommands(program) {
1154
1557
  .description("Delete a branch by name, slug, or ID. The branch is resolved against " +
1155
1558
  "the project's branch list, then deprovisioning is started.\n\n" +
1156
1559
  "This is destructive — the branch's database, workers, and services are " +
1157
- "deprovisioned.\n\n" +
1560
+ "deprovisioned. `--if-exists` makes a missing or already deleted branch " +
1561
+ "a no-op, which is useful in cleanup jobs.\n\n" +
1158
1562
  "```bash\n" +
1159
1563
  "omnibase cloud branch rm staging\n" +
1564
+ "omnibase cloud branch rm pr-123 --if-exists\n" +
1160
1565
  "omnibase cloud branch rm br_123 --project-id proj_123\n" +
1161
1566
  "```")
1162
1567
  .option("--project-id <id>", "Project ID")
1568
+ .option("--if-exists", "Do not fail if the branch is missing or deleted")
1163
1569
  .action(async (branchRef, cmdOptions) => {
1164
1570
  try {
1165
- await branchDelete(branchRef, cmdOptions.projectId);
1571
+ await branchDelete(branchRef, cmdOptions.projectId, {
1572
+ ifExists: cmdOptions.ifExists,
1573
+ });
1166
1574
  }
1167
1575
  catch (error) {
1168
1576
  await (0, errors_1.handleCommandError)(error);
@@ -1206,7 +1614,7 @@ function addCloudCommands(program) {
1206
1614
  "not supported.\n\n" +
1207
1615
  "After: the branch reports which sections were applied and which were " +
1208
1616
  "ignored. Unresolved `{VAR}` values are warned about and left literal.\n\n" +
1209
- "See the env resolution model on the [`cloud env`](/reference/cli/cloud/env) page.\n\n" +
1617
+ "See the env resolution model on the [`cloud env`](/cli/cloud/env) page.\n\n" +
1210
1618
  "```bash\n" +
1211
1619
  "omnibase cloud env push --env dev\n" +
1212
1620
  "omnibase cloud env push --env staging\n" +