@supacloud/cli 0.121.8 → 0.123.1

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
@@ -9058,6 +9058,42 @@ function parseEnvFile(contents) {
9058
9058
  }
9059
9059
  return values;
9060
9060
  }
9061
+ function projectConfigValues(cwd, environment) {
9062
+ const path = resolve2(cwd, "supacloud.json");
9063
+ if (!existsSync(path))
9064
+ return {};
9065
+ try {
9066
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
9067
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
9068
+ return {};
9069
+ const root = parsed;
9070
+ const context = root.context;
9071
+ if (!context || typeof context !== "object" || Array.isArray(context))
9072
+ return {};
9073
+ const contextRecord = context;
9074
+ const environments = contextRecord.environments;
9075
+ if (!environments || typeof environments !== "object" || Array.isArray(environments))
9076
+ return {};
9077
+ const selected = environments[environment];
9078
+ if (!selected || typeof selected !== "object" || Array.isArray(selected))
9079
+ return {};
9080
+ const values = selected;
9081
+ const output = {};
9082
+ const mappings = {
9083
+ api_url: "SUPACLOUD_API_URL",
9084
+ project_ref: "SUPACLOUD_PROJECT_REF",
9085
+ application_id: "SUPACLOUD_APPLICATION_ID",
9086
+ environment_id: "SUPACLOUD_APPLICATION_ENVIRONMENT_ID"
9087
+ };
9088
+ for (const [source, target] of Object.entries(mappings)) {
9089
+ if (typeof values[source] === "string" && values[source].trim())
9090
+ output[target] = values[source].trim();
9091
+ }
9092
+ return output;
9093
+ } catch {
9094
+ return {};
9095
+ }
9096
+ }
9061
9097
  function readEnvFile(path, required) {
9062
9098
  if (!existsSync(path)) {
9063
9099
  if (required)
@@ -9158,17 +9194,31 @@ function explicitEnvironmentSource(cwd, envFile) {
9158
9194
  function contextSource(env, cwd, selection) {
9159
9195
  if (selection.environmentName && selection.envFile)
9160
9196
  throw new Error("Environment selectors are mutually exclusive");
9161
- if (selection.environmentName)
9162
- return namedEnvironmentSource(cwd, selection.environmentName);
9163
- if (selection.envFile)
9164
- return explicitEnvironmentSource(cwd, selection.envFile);
9197
+ if (selection.environmentName) {
9198
+ const source = namedEnvironmentSource(cwd, selection.environmentName);
9199
+ return {
9200
+ ...source,
9201
+ values: { ...projectConfigValues(cwd, source.environment), ...source.values }
9202
+ };
9203
+ }
9204
+ if (selection.envFile) {
9205
+ const source = explicitEnvironmentSource(cwd, selection.envFile);
9206
+ return {
9207
+ ...source,
9208
+ values: { ...projectConfigValues(cwd, source.environment), ...source.values }
9209
+ };
9210
+ }
9165
9211
  if (env.SUPACLOUD_ENV) {
9166
9212
  const environment = normalizeEnvironmentName(env.SUPACLOUD_ENV);
9167
- const values = processValues(env);
9213
+ const values = { ...projectConfigValues(cwd, environment), ...processValues(env) };
9168
9214
  if (completeProjectContext(values)) {
9169
9215
  return { values, kind: "process_env", path: null, environment };
9170
9216
  }
9171
- return namedEnvironmentSource(cwd, env.SUPACLOUD_ENV);
9217
+ const source = namedEnvironmentSource(cwd, env.SUPACLOUD_ENV);
9218
+ return {
9219
+ ...source,
9220
+ values: { ...projectConfigValues(cwd, source.environment), ...source.values }
9221
+ };
9172
9222
  }
9173
9223
  if (hasProcessContext(env)) {
9174
9224
  return { values: processValues(env), kind: "process_env", path: null, environment: "" };
@@ -9176,6 +9226,14 @@ function contextSource(env, cwd, selection) {
9176
9226
  const path = resolve2(cwd, ".env");
9177
9227
  const values = readEnvFile(path, false);
9178
9228
  const environment = values.SUPACLOUD_ENV ? normalizeEnvironmentName(values.SUPACLOUD_ENV) : "";
9229
+ if (environment) {
9230
+ return {
9231
+ values: { ...projectConfigValues(cwd, environment), ...values },
9232
+ kind: "legacy_dotenv",
9233
+ path: existsSync(path) ? path : null,
9234
+ environment
9235
+ };
9236
+ }
9179
9237
  return { values, kind: Object.keys(values).length ? "legacy_dotenv" : "none", path: existsSync(path) ? path : null, environment };
9180
9238
  }
9181
9239
  function resolveSupaCloudContext(env = process.env, cwd = process.cwd(), selection = {}) {
@@ -9267,10 +9325,16 @@ function parseGlobalOptions(args) {
9267
9325
 
9268
9326
  // src/shared/execution-policy.ts
9269
9327
  var ACTION_POLICY = {
9328
+ config: {
9329
+ read: ["doctor", "explain"]
9330
+ },
9331
+ pipeline: {
9332
+ local: ["connect"]
9333
+ },
9270
9334
  deploy: { local: ["init"], write: ["deploy"] },
9271
9335
  applications: {
9272
9336
  read: ["list_releases", "get_release", "get_runtime", "get_deployment_evidence", "get_configuration", "get_release_transfer_plan", "get_promotion_plan", "get_promotion_status", "get_rollback_snapshot", "get_history", "get_deploy_plan", "logs", "get_preview_plan", "list_previews", "get_preview"],
9273
- write: ["upload_release", "put_configuration", "deploy_application", "transfer_release", "promote_application", "reconcile_promotion", "create_preview", "reconcile_preview", "cleanup_preview", "activate_release", "deploy_release", "rollback_release", "reconcile_activation", "retire_activation"]
9337
+ write: ["upload_release", "put_configuration", "deploy_application", "transfer_release", "promote_application", "reconcile_promotion", "create_preview", "reconcile_preview", "cleanup_preview", "preview_pull_request", "activate_release", "deploy_release", "rollback_release", "reconcile_activation", "retire_activation"]
9274
9338
  },
9275
9339
  project: {
9276
9340
  read: ["get", "endpoints", "health", "logs", "api_keys", "settings", "tasks", "task_detail", "task_stats", "dlq", "background_settings"],
@@ -9366,11 +9430,11 @@ var ACTION_POLICY = {
9366
9430
  ai: { local: ["show_skill", "install_skill"] },
9367
9431
  mcp: { local: ["config"] },
9368
9432
  init: { local: ["init"] },
9369
- env: { local: ["list", "check"] },
9433
+ env: { local: ["list", "check", "sync"] },
9370
9434
  app: {
9371
9435
  local: ["init", "generate", "dev", "watch", "verify-plan", "compile", "check", "graph", "explain", "export-tools", "context", "lens", "doctor", "fix", "plan", "build"],
9372
9436
  read: ["status", "evidence", "logs", "transfer-plan", "promote-plan", "rollback-plan", "history", "deploy-plan", "diff", "promote-status", "preview-plan", "previews", "preview-list", "preview-status"],
9373
- write: ["release", "upload", "configure", "transfer", "promote", "promote-reconcile", "deploy", "rollback", "reconcile", "retire", "preview", "preview-create", "preview-reconcile", "preview-cleanup"]
9437
+ write: ["release", "upload", "configure", "transfer", "promote", "promote-reconcile", "deploy", "rollback", "reconcile", "retire", "preview", "preview-create", "preview-reconcile", "preview-cleanup", "preview-pr"]
9374
9438
  },
9375
9439
  db: {
9376
9440
  local: ["context", "lint", "explain", "diff", "role_sql"],
@@ -15857,7 +15921,7 @@ function scaffoldFiles(framework, slug) {
15857
15921
  "package.json": JSON.stringify({
15858
15922
  private: true,
15859
15923
  type: "module",
15860
- dependencies: { elysia: "2.0.0-rc.3" }
15924
+ dependencies: { elysia: "2.0.0-rc.4" }
15861
15925
  }, null, 2) + `
15862
15926
  `,
15863
15927
  "index.ts": `import { Elysia } from "elysia";
@@ -18032,6 +18096,27 @@ async function activationReadback(http, input, mutationId, activationStatus) {
18032
18096
  }
18033
18097
 
18034
18098
  // src/shared/tools/frontend-tools.ts
18099
+ function parseEnvironmentVariables(value) {
18100
+ if (value === undefined)
18101
+ return;
18102
+ const candidate = typeof value === "string" ? (() => {
18103
+ try {
18104
+ return JSON.parse(value);
18105
+ } catch {
18106
+ throw new Error("'env_vars' must be a valid JSON object");
18107
+ }
18108
+ })() : value;
18109
+ if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) {
18110
+ throw new Error("'env_vars' must be a JSON object");
18111
+ }
18112
+ const environment = {};
18113
+ for (const [name, entry] of Object.entries(candidate)) {
18114
+ if (typeof entry !== "string")
18115
+ throw new Error(`'env_vars.${name}' must be a string`);
18116
+ environment[name] = entry;
18117
+ }
18118
+ return environment;
18119
+ }
18035
18120
  function registerFrontendTools(server, http) {
18036
18121
  registerTool(server, "frontend", `Frontend hosting and immutable prebuilt releases. Supports: static, react, vue, svelte, sveltekit, sveltekit-static, nextjs, nuxt, astro.
18037
18122
  Actions: list, get, create, update, delete, build_logs, add_domain, remove_domain, set_env, list_frameworks, list_records, list_releases, get_active_release, get_release, verify_release, rollback. Publish with supacloud deploy.`, {
@@ -18063,7 +18148,10 @@ Actions: list, get, create, update, delete, build_logs, add_domain, remove_domai
18063
18148
  install_command: optional(String2(), "[create/update] Install command override"),
18064
18149
  node_version: optional(String2(), "[create/update] Node.js version"),
18065
18150
  health_check_path: optional(String2(), "[create/update] SSR readiness path (default: /)"),
18066
- env_vars: optional(Record(String2(), String2()), "[create/update/set_env] Environment variables"),
18151
+ env_vars: optional(Union([
18152
+ Record(String2(), String2()),
18153
+ String2({ minLength: 2, maxLength: 262144 })
18154
+ ]), '[create/update/set_env] JSON object, for example {"VITE_API_URL":"https://..."}'),
18067
18155
  release_id: optional(String2(), "[get_release] SHA-256 release ID; [rollback] optional, defaults to journal-verified previous release"),
18068
18156
  cursor: optional(String2(), "[list_releases] Last release SHA-256 cursor"),
18069
18157
  limit: optional(Number2(), "[list_releases] Page size, 1-100 (default 50)")
@@ -18089,6 +18177,7 @@ Actions: list, get, create, update, delete, build_logs, add_domain, remove_domai
18089
18177
  if (value === undefined || value === null || value === "")
18090
18178
  throw new Error(`'${field}' required for '${action}'`);
18091
18179
  };
18180
+ const environment = parseEnvironmentVariables(env_vars);
18092
18181
  const ok = (res) => res.ok ? JSON.stringify(res.data, null, 2) : `❌ Failed (${res.status}): ${JSON.stringify(res.data)}`;
18093
18182
  let text;
18094
18183
  switch (action) {
@@ -18114,7 +18203,7 @@ Actions: list, get, create, update, delete, build_logs, add_domain, remove_domai
18114
18203
  install_command,
18115
18204
  node_version,
18116
18205
  health_check_path,
18117
- env_vars
18206
+ env_vars: environment
18118
18207
  }));
18119
18208
  break;
18120
18209
  case "update":
@@ -18128,7 +18217,7 @@ Actions: list, get, create, update, delete, build_logs, add_domain, remove_domai
18128
18217
  install_command,
18129
18218
  node_version,
18130
18219
  health_check_path,
18131
- env_vars
18220
+ env_vars: environment
18132
18221
  }));
18133
18222
  break;
18134
18223
  case "delete":
@@ -18157,8 +18246,8 @@ Actions: list, get, create, update, delete, build_logs, add_domain, remove_domai
18157
18246
  case "set_env":
18158
18247
  need("ref", ref);
18159
18248
  need("id", id);
18160
- need("env_vars", env_vars);
18161
- text = (await http.put(`/v1/projects/${ref}/frontend/deployments/${id}/env`, { env_vars })).ok ? `✅ Set ${Object.keys(env_vars).length} env vars` : `❌ Failed`;
18249
+ need("env_vars", environment);
18250
+ text = (await http.put(`/v1/projects/${ref}/frontend/deployments/${id}/env`, { env_vars: environment })).ok ? `✅ Set ${Object.keys(environment).length} env vars` : `❌ Failed`;
18162
18251
  break;
18163
18252
  case "list_frameworks":
18164
18253
  text = ok(await http.get("/v1/projects/_/frontend/frameworks"));
@@ -18411,7 +18500,8 @@ var APPLICATION_PREVIEW_ACTIONS = [
18411
18500
  "list_previews",
18412
18501
  "get_preview",
18413
18502
  "reconcile_preview",
18414
- "cleanup_preview"
18503
+ "cleanup_preview",
18504
+ "preview_pull_request"
18415
18505
  ];
18416
18506
  var previewIdSchema = String2({ pattern: "^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$" });
18417
18507
  var branchRefSchema = String2({ pattern: "^[a-z0-9-]{1,20}$" });
@@ -18428,7 +18518,10 @@ var APPLICATION_PREVIEW_FIELDS = {
18428
18518
  data_mode: optional(stringEnum2(["schema_only", "full_clone"]), "[get_preview_plan/create_preview] Default schema_only; full_clone copies rows"),
18429
18519
  ttl_seconds: optional(ttlSecondsSchema, "[get_preview_plan/create_preview] Lifetime from 300 to 604800 seconds; creation defaults to the platform TTL"),
18430
18520
  wait: optional(Boolean2(), "[create_preview/get_preview] Wait for verified readiness of this preview only"),
18431
- timeout_seconds: optional(waitSecondsSchema, "[create_preview/get_preview] Observation budget with wait, from 1 to 3600 seconds (default 300)")
18521
+ timeout_seconds: optional(waitSecondsSchema, "[create_preview/get_preview] Observation budget with wait, from 1 to 3600 seconds (default 300)"),
18522
+ pull_request_action: optional(stringEnum2(["opened", "closed"]), "[preview_pull_request] Pull request lifecycle action"),
18523
+ repository: optional(String2({ pattern: "^[A-Za-z0-9_.-]{1,100}/[A-Za-z0-9_.-]{1,100}$" }), "[preview_pull_request] Repository owner/name"),
18524
+ pull_request_number: optional(Integer({ minimum: 1, maximum: 1e9 }), "[preview_pull_request] Pull request number")
18432
18525
  };
18433
18526
  var strict = { additionalProperties: false };
18434
18527
  var phase2 = stringEnum2(["pending", "ready", "failed", "cleaned"]);
@@ -18493,7 +18586,8 @@ var actionFields = {
18493
18586
  list_previews: [],
18494
18587
  get_preview: ["preview_id", "wait", "timeout_seconds"],
18495
18588
  reconcile_preview: ["preview_id"],
18496
- cleanup_preview: ["preview_id"]
18589
+ cleanup_preview: ["preview_id"],
18590
+ preview_pull_request: ["pull_request_action", "repository", "pull_request_number", "release_id"]
18497
18591
  };
18498
18592
  function timestamp4(value) {
18499
18593
  return Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
@@ -18638,6 +18732,34 @@ async function applicationPreviewAction(http, args, project) {
18638
18732
  const identity = { project_ref: ref, application_id: id, environment_id: environment };
18639
18733
  const applicationPath = `/v1/projects/${project}/applications/${encodeURIComponent(id)}`;
18640
18734
  const path = `${applicationPath}/environments/${encodeURIComponent(environment)}`;
18735
+ if (action === "preview_pull_request") {
18736
+ const lifecycle = required5(args, "pull_request_action");
18737
+ const repository = required5(args, "repository");
18738
+ const releaseId = required5(args, "release_id");
18739
+ const number = args["pull_request_number"];
18740
+ if (!Check2(ApplicationReleaseIdSchema2, releaseId) || !/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/.test(repository) || (typeof number !== "number" || !Number.isSafeInteger(number) || number < 1 || number > 1e9)) {
18741
+ throw new Error("Invalid pull request preview identity");
18742
+ }
18743
+ const result = await http.post(`${path}/preview-pull-requests`, {
18744
+ action: lifecycle,
18745
+ repository,
18746
+ number,
18747
+ release_id: releaseId
18748
+ }, { timeoutMs: 120000, maxJsonBytes: 1048576, responseTimeoutMs: 30000 });
18749
+ const payload = result.data && typeof result.data === "object" && !Array.isArray(result.data) ? result.data : null;
18750
+ if (!result.ok || !payload || payload["action"] !== lifecycle || typeof payload["preview_id"] !== "string" || typeof payload["status"] !== "string" || !Array.isArray(payload["leftovers"])) {
18751
+ return releaseControlFailure(operation, result.ok ? "INVALID_RESPONSE" : "HTTP_ERROR", result.transportError ? null : result.status, identity);
18752
+ }
18753
+ const preview = payload["receipt"] === null || payload["receipt"] === undefined ? null : receipt(payload["receipt"], { ref, id, environment, previewId: payload["preview_id"] });
18754
+ return releaseControlSuccess(operation, {
18755
+ ...identity,
18756
+ action: lifecycle,
18757
+ preview_id: payload["preview_id"],
18758
+ status: payload["status"],
18759
+ leftovers: payload["leftovers"].filter((value) => typeof value === "string").slice(0, 64),
18760
+ receipt: preview
18761
+ });
18762
+ }
18641
18763
  const previewId = action === "get_preview" || action === "reconcile_preview" || action === "cleanup_preview" ? required5(args, "preview_id") : action === "create_preview" ? typeof args["preview_id"] === "string" ? required5(args, "preview_id") : randomUUID() : action === "get_preview_plan" && typeof args["preview_id"] === "string" ? required5(args, "preview_id") : undefined;
18642
18764
  const mutation = action === "create_preview" || action === "reconcile_preview" || action === "cleanup_preview";
18643
18765
  const requestBudget = startedAt === undefined ? 120000 : Math.min(120000, timeoutSeconds * 1000);
@@ -22209,9 +22331,9 @@ function registerMcpTools(server, context) {
22209
22331
  }
22210
22332
 
22211
22333
  // src/shared/tools/app-tools.ts
22212
- import { existsSync as existsSync11, readFileSync as readFileSync9 } from "node:fs";
22213
- import { mkdir as mkdir5, readFile as readFile4, readdir as readdir5, writeFile as writeFile4 } from "node:fs/promises";
22214
- import { basename as basename7, dirname as dirname9, join as join13, relative as relative7, resolve as resolve18 } from "node:path";
22334
+ import { existsSync as existsSync12, readFileSync as readFileSync9 } from "node:fs";
22335
+ import { mkdir as mkdir6, readFile as readFile5, readdir as readdir5, writeFile as writeFile5 } from "node:fs/promises";
22336
+ import { basename as basename7, dirname as dirname9, join as join14, relative as relative7, resolve as resolve19 } from "node:path";
22215
22337
  import {
22216
22338
  applyDiagnosticFix,
22217
22339
  buildDeliveryProject,
@@ -22356,16 +22478,16 @@ var starter_metadata_default = {
22356
22478
  generatedBy: "supacloud/starter-metadata-v1",
22357
22479
  packages: {
22358
22480
  compiler: {
22359
- version: "0.62.6"
22481
+ version: "0.62.7"
22360
22482
  },
22361
22483
  app: {
22362
- version: "0.39.3",
22484
+ version: "0.39.4",
22363
22485
  dependencies: {
22364
22486
  rxjs: "7.8.2"
22365
22487
  }
22366
22488
  },
22367
22489
  elysia: {
22368
- version: "0.42.4"
22490
+ version: "0.42.5"
22369
22491
  },
22370
22492
  commands: {
22371
22493
  version: "0.12.0"
@@ -22374,15 +22496,15 @@ var starter_metadata_default = {
22374
22496
  version: "0.16.2"
22375
22497
  },
22376
22498
  db: {
22377
- version: "0.24.2",
22499
+ version: "0.25.1",
22378
22500
  dependencies: {},
22379
22501
  devDependencies: {},
22380
22502
  peerDependencies: {
22381
- "@supacloud/db-zenstack": "^0.1.0 || ^0.2.0"
22503
+ "@supacloud/db-zenstack": "^0.1.0 || ^0.2.0 || ^0.3.0"
22382
22504
  }
22383
22505
  },
22384
22506
  dbZenstack: {
22385
- version: "0.2.2",
22507
+ version: "0.3.1",
22386
22508
  dependencies: {
22387
22509
  "@zenstackhq/orm": "3.10.0",
22388
22510
  "@zenstackhq/schema": "3.10.0",
@@ -22390,15 +22512,16 @@ var starter_metadata_default = {
22390
22512
  "@zenstackhq/language": "3.10.0",
22391
22513
  "@zenstackhq/sdk": "3.10.0",
22392
22514
  kysely: "0.29.0"
22393
- },
22394
- devDependencies: {
22395
- "@zenstackhq/cli": "3.10.0",
22396
- prisma: "6.19.3",
22397
- pg: "8.23.1"
22515
+ }
22516
+ },
22517
+ modelTooling: {
22518
+ version: "0.1.1",
22519
+ dependencies: {
22520
+ "@supacloud/db-zenstack": "^0.3.0"
22398
22521
  }
22399
22522
  },
22400
22523
  sdk: {
22401
- version: "0.48.3",
22524
+ version: "0.48.4",
22402
22525
  peerDependencies: {
22403
22526
  "@supabase/supabase-js": "^2.118.0"
22404
22527
  }
@@ -22826,7 +22949,7 @@ function baseTemplateFiles(name, sdkDependencies) {
22826
22949
  "@supacloud/app": `^${appMetadata.version}`,
22827
22950
  "@supacloud/elysia": `^${elysiaMetadata.version}`,
22828
22951
  effect: "4.0.5",
22829
- elysia: "2.0.0-rc.3",
22952
+ elysia: "2.0.0-rc.4",
22830
22953
  ...sdkDependencies
22831
22954
  },
22832
22955
  devDependencies: {
@@ -23570,7 +23693,7 @@ GRANT SELECT, INSERT, UPDATE ON supacloud_commands.execution_receipts TO model_o
23570
23693
  GRANT SELECT, INSERT ON supacloud_commands.execution_audit TO model_orders_app;
23571
23694
  `;
23572
23695
  function modelCommandTemplateFiles(name, sdk) {
23573
- const { app, compiler, elysia, commands, contracts, db, dbZenstack } = starter_metadata_default.packages;
23696
+ const { app, compiler, elysia, commands, contracts, db, dbZenstack, modelTooling } = starter_metadata_default.packages;
23574
23697
  const files = baseTemplateFiles(name, sdk);
23575
23698
  delete files["scripts/dev.ts"];
23576
23699
  delete files["scripts/serve.ts"];
@@ -23593,7 +23716,9 @@ function modelCommandTemplateFiles(name, sdk) {
23593
23716
  scripts: {
23594
23717
  "db:generate": "supacloud-model generate && supacloud-db generate",
23595
23718
  "db:check": "supacloud-model check && supacloud-db check",
23596
- "db:diff": "supacloud-model diff",
23719
+ "db:diff": "supacloud db plan --dir migrations",
23720
+ "db:plan": "supacloud db plan --dir migrations",
23721
+ "db:apply": "supacloud db apply --dir migrations",
23597
23722
  "db:pull": "supacloud-model pull",
23598
23723
  compile: "supacloud-compiler compile",
23599
23724
  "check:generated": "supacloud-compiler check",
@@ -23614,10 +23739,10 @@ function modelCommandTemplateFiles(name, sdk) {
23614
23739
  ...dbZenstack.dependencies,
23615
23740
  typebox: "1.4.3",
23616
23741
  effect: "4.0.5",
23617
- elysia: "2.0.0-rc.3",
23742
+ elysia: "2.0.0-rc.4",
23618
23743
  ...sdk
23619
23744
  },
23620
- devDependencies: { "@supacloud/compiler": "^" + compiler.version, ...db.devDependencies, ...dbZenstack.devDependencies, "@types/bun": "^1.4.4", typescript: "7.1.0-beta" }
23745
+ devDependencies: { "@supacloud/compiler": "^" + compiler.version, "@supacloud/model-tooling": "^" + modelTooling.version, "@types/bun": "^1.4.4", typescript: "7.1.0-beta" }
23621
23746
  }),
23622
23747
  "supacloud.config.ts": `import { defineSupacloudConfig } from "@supacloud/compiler";
23623
23748
  export default defineSupacloudConfig({
@@ -23714,7 +23839,7 @@ The receipt migration uses the same supacloud_commands ledger as the platform. I
23714
23839
 
23715
23840
  The model_orders_app role is a trusted-server capability and does not set request.jwt.claims. Its SQL policy is a host bypass, not the model row projection; do not grant that role to PostgREST. Authenticated SELECT, INSERT and UPDATE policies are emitted from the ZModel @@allow rules and must stay in the migration. They do not grant privileges; add a reviewed GRANT before exposing the table through PostgREST.
23716
23841
 
23717
- To change the schema: bun run db:generate, bun run db:check, then bun run db:diff -- --candidate output/database-audit/change.sql against an explicit shadow database. Review forward SQL before promotion. Stop intake and drain HTTP/worker work before host.dispose(), then close the caller-owned pool.
23842
+ To change the schema: bun run db:generate, bun run db:check, then bun run db:plan. Review the Management API's remote plan and run bun run db:apply -- --approved_digest <digest> after approval. The CLI does not receive a database URL. Stop intake and drain HTTP/worker work before host.dispose(), then close the caller-owned pool.
23718
23843
  `
23719
23844
  };
23720
23845
  }
@@ -24994,20 +25119,24 @@ SQL, not the authenticated row-policy projection. Command writes still use the s
24994
25119
  transaction, receipt and audit boundary, not unrestricted CRUD. SQL constraints, RPCs
24995
25120
  and RLS remain explicit reviewed migrations when the model language cannot express them.
24996
25121
 
24997
- Use \`bun run db:diff -- --candidate output/database-audit/change.sql\` with an
24998
- explicit read-only SUPACLOUD_MODEL_DATABASE_URL. Review the SQL, then promote a new
24999
- forward migration through the existing SupaCloud plan/apply ledger. Never run
25000
- zen migrate deploy or db push against a managed production database.
25001
- \`bun run db:pull -- --candidate output/database-audit/schema.zmodel\` writes a
25002
- review candidate only; it never overwrites the maintained model. Add policies
25003
- before adopting introspection output. Keep one migration history and preserve RLS.
25122
+ Use \`bun run db:plan\` to send the reviewed migration directory to the
25123
+ Management API for a remote, read-only plan. Review the returned digest, then run
25124
+ \`bun run db:apply -- --approved_digest <digest>\` to apply the exact same bytes
25125
+ through the project migration ledger. Neither command needs DATABASE_URL or a
25126
+ public PostgreSQL port. Never run zen migrate deploy or db push against a managed
25127
+ production database.
25128
+ \`bun run db:pull -- --candidate output/database-audit/schema.zmodel\` uses the
25129
+ same Management API binding and writes a review candidate only; it never
25130
+ overwrites the maintained model. Add policies before adopting introspection
25131
+ output. Keep one migration history and preserve RLS.
25004
25132
 
25005
25133
  Adopting a database that has no model yet starts with the same command: pull
25006
- introspects through a temporary datasource-only model, so no hand-written ZModel
25007
- is required. Review the candidate, add the policy plugin and @@allow rules, move
25008
- it to zenstack/schema.zmodel, then run \`bun run db:generate\`. Until that file
25009
- exists, \`db:diff\` and \`db:generate\` fail closed instead of building from an
25010
- unreviewed introspection result. Keep the host wiring unchanged: one
25134
+ introspects through a temporary datasource-only model inside the Management API,
25135
+ so no hand-written ZModel is required. Review the candidate, add the policy
25136
+ plugin and @@allow rules, move it to zenstack/schema.zmodel, then run
25137
+ \`bun run db:generate\`. Until that file exists, \`db:plan\` and
25138
+ \`db:generate\` fail closed instead of building from an unreviewed
25139
+ introspection result. Keep the host wiring unchanged: one
25011
25140
  createZenStackDatabase composition root supplies read-only models and the
25012
25141
  transactional command store.
25013
25142
  `;
@@ -26337,7 +26466,7 @@ export async function createReviewTaskAdapters(options: ReviewTaskOptions): Prom
26337
26466
  `;
26338
26467
 
26339
26468
  // src/shared/tools/app-starter.ts
26340
- var { compiler: compilerMetadata2, app: appMetadata2, elysia: elysiaMetadata2, commands: commandsMetadata, contracts: contractsMetadata, db: dbMetadata, dbZenstack: dbZenstackMetadata, sdk: sdkMetadata } = starter_metadata_default.packages;
26469
+ var { compiler: compilerMetadata2, app: appMetadata2, elysia: elysiaMetadata2, commands: commandsMetadata, contracts: contractsMetadata, db: dbMetadata, dbZenstack: dbZenstackMetadata, modelTooling: modelToolingMetadata, sdk: sdkMetadata } = starter_metadata_default.packages;
26341
26470
  var json3 = (value) => `${JSON.stringify(value, null, 2)}
26342
26471
  `;
26343
26472
  function appStarterFiles(name) {
@@ -26361,7 +26490,9 @@ function appStarterFiles(name) {
26361
26490
  "db:generate": "supacloud-model generate && supacloud-db generate",
26362
26491
  "db:check": "supacloud-model check && supacloud-db check",
26363
26492
  "db:assess": "supacloud-db assess",
26364
- "db:diff": "supacloud-model diff",
26493
+ "db:diff": "supacloud db plan --dir migrations",
26494
+ "db:plan": "supacloud db plan --dir migrations",
26495
+ "db:apply": "supacloud db apply --dir migrations",
26365
26496
  "db:pull": "supacloud-model pull",
26366
26497
  check: "bun run db:check && bun run compile && bun run check:generated && bun run typecheck && bun run test",
26367
26498
  test: "bun run compile && bun --no-env-file scripts/environment.ts test bun test",
@@ -26385,13 +26516,12 @@ function appStarterFiles(name) {
26385
26516
  "@supacloud/js": `^${sdkMetadata.version}`,
26386
26517
  "@supabase/supabase-js": sdkMetadata.peerDependencies["@supabase/supabase-js"],
26387
26518
  effect: "4.0.5",
26388
- elysia: "2.0.0-rc.3",
26519
+ elysia: "2.0.0-rc.4",
26389
26520
  rxjs: appMetadata2.dependencies.rxjs
26390
26521
  },
26391
26522
  devDependencies: {
26392
26523
  "@supacloud/compiler": `^${compilerMetadata2.version}`,
26393
- ...dbMetadata.devDependencies,
26394
- ...dbZenstackMetadata.devDependencies,
26524
+ "@supacloud/model-tooling": `^${modelToolingMetadata.version}`,
26395
26525
  "@types/bun": "^1.4.4",
26396
26526
  typescript: "7.1.0-beta"
26397
26527
  }
@@ -29021,6 +29151,137 @@ async function applyScaffoldWrites(plan) {
29021
29151
  }
29022
29152
  }
29023
29153
 
29154
+ // src/shared/tools/configuration-tools.ts
29155
+ import { existsSync as existsSync11 } from "node:fs";
29156
+ import { mkdir as mkdir5, readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
29157
+ import { join as join13, resolve as resolve18 } from "node:path";
29158
+ var onboardToolSchema = {
29159
+ root: optional(String2(), "Repository or configuration root (default: current directory)"),
29160
+ profile: optional(stringEnum2(["solo", "podman", "pigsty", "cluster"]), "Deployment profile (default: solo)"),
29161
+ domain: optional(String2(), "Public API domain; studio domain is derived from it"),
29162
+ database: optional(stringEnum2(["local", "external"]), "Database provider (default: local)"),
29163
+ storage: optional(stringEnum2(["juicefs", "external"]), "Storage provider (default: juicefs)"),
29164
+ write: optional(Boolean2(), "Write the generated context into supacloud.json"),
29165
+ format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
29166
+ };
29167
+ var configurationToolSchema = {
29168
+ action: withDescription(stringEnum2(["doctor", "explain"]), "Configuration inspection action"),
29169
+ root: optional(String2(), "Repository or configuration root (default: current directory)"),
29170
+ key: optional(String2(), "[explain] Environment variable name"),
29171
+ format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
29172
+ };
29173
+ var environmentSyncSchema = {
29174
+ action: withDescription(stringEnum2(["list", "check", "sync"]), "Environment profile action"),
29175
+ root: optional(String2(), "Project directory containing .env.supacloud.* files"),
29176
+ environment: optional(String2(), "[sync] Profile name; defaults to the selected environment"),
29177
+ write: optional(Boolean2(), "[sync] Persist derived context and the reduced profile example"),
29178
+ format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
29179
+ };
29180
+ var SECRET_KEY = /(?:PASSWORD|PASS|SECRET|TOKEN|PRIVATE|CREDENTIAL|AUTHORIZATION|COOKIE|SESSION|DATABASE_URL|CONNECTION_STRING|DSN)/i;
29181
+ var PLATFORM_KEY = /^(?:SUPACLOUD|SUPABASE)_(?:API|PROJECT|ENV|HOST|SSH|APPLICATION|SERVICE_ROLE|ACCESS|URL|READ_ONLY|TLS|ANON|PUBLISHABLE)/;
29182
+ function textResult(text, isError = false) {
29183
+ return { isError, content: [{ type: "text", text }] };
29184
+ }
29185
+ function jsonResult(value, isError = false) {
29186
+ return textResult(JSON.stringify(value, null, 2), isError);
29187
+ }
29188
+ function record5(value) {
29189
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
29190
+ }
29191
+ function unquote(value) {
29192
+ const trimmed = value.trim();
29193
+ if (trimmed.length >= 2 && (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'"))) {
29194
+ return trimmed.slice(1, -1);
29195
+ }
29196
+ return trimmed;
29197
+ }
29198
+ function parseEnvironment(content) {
29199
+ const values = {};
29200
+ for (const rawLine of content.split(/\r?\n/)) {
29201
+ const line = rawLine.trim();
29202
+ if (!line || line.startsWith("#"))
29203
+ continue;
29204
+ const match = line.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
29205
+ if (match)
29206
+ values[match[1]] = unquote(match[2]);
29207
+ }
29208
+ return values;
29209
+ }
29210
+ async function readJsonObject(path) {
29211
+ if (!existsSync11(path))
29212
+ return {};
29213
+ const parsed = JSON.parse(await readFile4(path, "utf8"));
29214
+ const value = record5(parsed);
29215
+ if (!value)
29216
+ throw new Error(`${path} must contain a JSON object`);
29217
+ return value;
29218
+ }
29219
+ async function writeJsonObject(path, value) {
29220
+ await writeFile4(path, `${JSON.stringify(value, null, 2)}
29221
+ `, { encoding: "utf8", mode: 420 });
29222
+ }
29223
+ function contextFromConfig(config) {
29224
+ const context = record5(config.context);
29225
+ return context ?? {};
29226
+ }
29227
+ function environmentContext(config, environment) {
29228
+ const context = contextFromConfig(config);
29229
+ const environments = record5(context.environments);
29230
+ const selected = environments ? record5(environments[environment]) : null;
29231
+ return selected ?? {};
29232
+ }
29233
+ async function syncEnvironmentProfile(args, options) {
29234
+ const root = resolve18(typeof args.root === "string" ? args.root : options.cwd ?? process.cwd());
29235
+ const environment = typeof args.environment === "string" && args.environment.trim() ? args.environment.trim() : options.activeContext?.environment;
29236
+ if (!environment)
29237
+ throw new Error("env sync requires --env <name> or SUPACLOUD_ENV");
29238
+ const profilePath = join13(root, `.env.supacloud.${environment}`);
29239
+ if (!existsSync11(profilePath))
29240
+ throw new Error(`Environment profile not found: ${profilePath}`);
29241
+ const values = parseEnvironment(await readFile4(profilePath, "utf8"));
29242
+ const configPath = join13(root, "supacloud.json");
29243
+ const config = await readJsonObject(configPath);
29244
+ const context = contextFromConfig(config);
29245
+ const environments = record5(context.environments) ?? {};
29246
+ const publicValues = Object.fromEntries(Object.entries(values).filter(([name]) => !SECRET_KEY.test(name) && !PLATFORM_KEY.test(name)));
29247
+ const secretNames = Object.keys(values).filter((name) => SECRET_KEY.test(name));
29248
+ const nextEnvironment = {
29249
+ api_url: values.SUPACLOUD_API_URL ?? null,
29250
+ project_ref: values.SUPACLOUD_PROJECT_REF ?? null,
29251
+ application_id: values.SUPACLOUD_APPLICATION_ID ?? null,
29252
+ environment_id: values.SUPACLOUD_APPLICATION_ENVIRONMENT_ID ?? environment,
29253
+ public: publicValues,
29254
+ secret_names: secretNames
29255
+ };
29256
+ const result = {
29257
+ schema: "supacloud.environment-sync.v1",
29258
+ environment,
29259
+ profile: profilePath,
29260
+ config: configPath,
29261
+ diff: { changed: nextEnvironment, secret_values_written: false },
29262
+ next: ["Secret values are never copied into supacloud.json", `supacloud --env ${environment} status`]
29263
+ };
29264
+ if (args.write !== true)
29265
+ return jsonResult({ ...result, written: false });
29266
+ config.context = { ...context, environments: { ...environments, [environment]: nextEnvironment } };
29267
+ await writeJsonObject(configPath, config);
29268
+ const reducedExample = [`SUPACLOUD_ENV=${environment}`, "SUPACLOUD_API_TOKEN=<inject-at-runtime>", ""].join(`
29269
+ `);
29270
+ await writeFile4(`${profilePath}.example`, reducedExample, { encoding: "utf8", mode: 384 });
29271
+ return jsonResult({ ...result, written: true, reduced_profile_example: `${profilePath}.example` });
29272
+ }
29273
+ async function readSecretGap(root, environment) {
29274
+ if (!environment)
29275
+ return { environment, required: [], present: [], missing: [] };
29276
+ const config = await readJsonObject(join13(root, "supacloud.json"));
29277
+ const metadata = environmentContext(config, environment);
29278
+ const required = Array.isArray(metadata.secret_names) ? metadata.secret_names.filter((value) => typeof value === "string" && /^[A-Z_][A-Z0-9_]*$/.test(value)).sort() : [];
29279
+ const profilePath = join13(root, `.env.supacloud.${environment}`);
29280
+ const values = existsSync11(profilePath) ? parseEnvironment(await readFile4(profilePath, "utf8")) : {};
29281
+ const present = required.filter((name) => values[name] !== undefined && values[name] !== "" && !/^<[^>]+>$/.test(values[name]));
29282
+ return { environment, required, present, missing: required.filter((name) => !present.includes(name)) };
29283
+ }
29284
+
29024
29285
  // src/shared/tools/app-tools.ts
29025
29286
  var REMOTE_APP_ACTIONS = {
29026
29287
  upload: "upload_release",
@@ -29033,6 +29294,7 @@ var REMOTE_APP_ACTIONS = {
29033
29294
  "preview-create": "create_preview",
29034
29295
  "preview-status": "get_preview",
29035
29296
  "preview-cleanup": "cleanup_preview",
29297
+ "preview-pr": "preview_pull_request",
29036
29298
  transfer: "transfer_release",
29037
29299
  configure: "put_configuration",
29038
29300
  deploy: "deploy_release",
@@ -29101,7 +29363,7 @@ async function initProject(args) {
29101
29363
  ];
29102
29364
  const note = template === "client" ? "Data-plane client only (@supabase/supabase-js). The forced default is app init (minimal compiler/Effect stack)." : template === "model-command" ? "Requires an explicitly selected database, reviewed migrations and trusted HTTP/worker identity authority; see README.md." : "Local demo only. Production requires persistent governance and identity adapters; see README.md.";
29103
29365
  if (args.format === "json")
29104
- return textResult(JSON.stringify({
29366
+ return textResult2(JSON.stringify({
29105
29367
  version: 1,
29106
29368
  ok: true,
29107
29369
  root,
@@ -29111,7 +29373,7 @@ async function initProject(args) {
29111
29373
  next,
29112
29374
  note
29113
29375
  }, null, 2));
29114
- return textResult([
29376
+ return textResult2([
29115
29377
  `Initialized ${name} in ${root} (${files.length} files, template: ${template}).`,
29116
29378
  `cd '${root.replaceAll("'", "'\\''")}'`,
29117
29379
  ...next,
@@ -29119,7 +29381,7 @@ async function initProject(args) {
29119
29381
  ].join(`
29120
29382
  `));
29121
29383
  }
29122
- function textResult(text, isError = false) {
29384
+ function textResult2(text, isError = false) {
29123
29385
  return { isError, content: [{ type: "text", text }] };
29124
29386
  }
29125
29387
  function pascalName(name) {
@@ -29234,7 +29496,7 @@ async function generateScaffold(args) {
29234
29496
  throw new ScaffoldError("SCAFFOLD_OPTION_INVALID", `--${flag.replaceAll("_", "-")} must be boolean`);
29235
29497
  }
29236
29498
  }
29237
- const root = resolve18(args.root || process.cwd());
29499
+ const root = resolve19(args.root || process.cwd());
29238
29500
  const dir = args.dir ?? "src/features";
29239
29501
  if (dir !== ".")
29240
29502
  scaffoldPath(root, dir);
@@ -29263,7 +29525,7 @@ async function generateScaffold(args) {
29263
29525
  let contractName;
29264
29526
  if (kind === "module" || kind === "resource" || kind === "feature") {
29265
29527
  const name = requireIdentifier(args.name, "name");
29266
- modulePath = join13(dir, name, kind === "feature" ? `${name}.feature.ts` : `${name}.module.ts`).replaceAll("\\", "/");
29528
+ modulePath = join14(dir, name, kind === "feature" ? `${name}.feature.ts` : `${name}.module.ts`).replaceAll("\\", "/");
29267
29529
  moduleSymbol = kind === "feature" ? `${pascalName(name)}Feature` : `${pascalName(name)}Module`;
29268
29530
  if (kind === "module")
29269
29531
  writes.push({ path: modulePath, content: moduleScaffold(name), overwrite: args.force === true });
@@ -29271,18 +29533,18 @@ async function generateScaffold(args) {
29271
29533
  for (const [file, content] of Object.entries(kind === "feature" ? featureScaffold(name, pascalName(name), {
29272
29534
  ...featureGovernance,
29273
29535
  databaseImportPath: (() => {
29274
- const source = relative7(join13(root, dir, name), join13(root, featureGovernance.database.source)).replaceAll("\\", "/").replace(/\.(?:[cm]?tsx?|mts|cts)$/, "");
29536
+ const source = relative7(join14(root, dir, name), join14(root, featureGovernance.database.source)).replaceAll("\\", "/").replace(/\.(?:[cm]?tsx?|mts|cts)$/, "");
29275
29537
  return source.startsWith(".") ? source : `./${source}`;
29276
29538
  })()
29277
29539
  }) : resourceScaffold(name, pascalName(name)))) {
29278
- writes.push({ path: join13(dir, name, file).replaceAll("\\", "/"), content });
29540
+ writes.push({ path: join14(dir, name, file).replaceAll("\\", "/"), content });
29279
29541
  }
29280
29542
  } else {
29281
29543
  const moduleName = requireIdentifier(args.module, "module");
29282
29544
  const name = kind === "controller" ? moduleName : requireIdentifier(args.name, "name");
29283
29545
  const subdir = kind === "command" ? "commands" : kind === "query" ? "queries" : kind === "job" ? "jobs" : kind === "contract" ? "contracts" : "";
29284
- const path = join13(dir, moduleName, subdir, `${name}.${kind}.ts`).replaceAll("\\", "/");
29285
- if (kind === "controller" && existsSync11(scaffoldPath(root, path))) {
29546
+ const path = join14(dir, moduleName, subdir, `${name}.${kind}.ts`).replaceAll("\\", "/");
29547
+ if (kind === "controller" && existsSync12(scaffoldPath(root, path))) {
29286
29548
  throw new ScaffoldError("SCAFFOLD_EXISTS", `Controller already exists: ${path}(请手工合并路由到现有 controller)`);
29287
29549
  }
29288
29550
  const content = kind === "command" ? commandScaffold(moduleName, name) : kind === "query" ? queryScaffold(moduleName, name) : kind === "job" ? jobScaffold(moduleName, name) : kind === "contract" ? contractScaffold(moduleName, name) : controllerScaffold(moduleName);
@@ -29300,7 +29562,7 @@ async function generateScaffold(args) {
29300
29562
  if (new RegExp(`\\b${moduleSymbol}\\b`).test(original)) {
29301
29563
  throw new ScaffoldError("SCAFFOLD_REGISTRATION_CONFLICT", `Registration target already references ${moduleSymbol}; review the import manually`);
29302
29564
  }
29303
- let importPath = relative7(dirname9(target), resolve18(root, modulePath)).replaceAll("\\", "/").replace(/\.ts$/, "");
29565
+ let importPath = relative7(dirname9(target), resolve19(root, modulePath)).replaceAll("\\", "/").replace(/\.ts$/, "");
29304
29566
  if (!importPath.startsWith("."))
29305
29567
  importPath = `./${importPath}`;
29306
29568
  const edit = await applyDiagnosticFix({
@@ -29310,7 +29572,7 @@ async function generateScaffold(args) {
29310
29572
  importPath,
29311
29573
  symbol: moduleSymbol
29312
29574
  }, { rootDir: root, dryRun: true });
29313
- if (await readFile4(target, "utf8") !== original)
29575
+ if (await readFile5(target, "utf8") !== original)
29314
29576
  throw new ScaffoldError("SCAFFOLD_CHANGED", "Registration source changed during planning");
29315
29577
  writes.push({ path: args.register_in, content: edit.content, expected: original });
29316
29578
  }
@@ -29323,7 +29585,7 @@ async function generateScaffold(args) {
29323
29585
  ...args.dry_run ? { content: write.content } : {}
29324
29586
  }));
29325
29587
  if (args.format === "json")
29326
- return textResult(JSON.stringify({
29588
+ return textResult2(JSON.stringify({
29327
29589
  version: 1,
29328
29590
  ok: true,
29329
29591
  kind,
@@ -29331,7 +29593,7 @@ async function generateScaffold(args) {
29331
29593
  written: !args.dry_run,
29332
29594
  changes
29333
29595
  }, null, 2));
29334
- const lines = changes.map((change) => `${args.dry_run ? "PREVIEW" : "✅"} ${change.action}: ${join13(plan.root, change.path)}`);
29596
+ const lines = changes.map((change) => `${args.dry_run ? "PREVIEW" : "✅"} ${change.action}: ${join14(plan.root, change.path)}`);
29335
29597
  if (args.dry_run)
29336
29598
  lines.push("No files written. Omit --dry-run to apply this generation.");
29337
29599
  if (kind === "resource")
@@ -29342,7 +29604,7 @@ async function generateScaffold(args) {
29342
29604
  const prefix = pascalName(contractName);
29343
29605
  lines.push("", "Next, bind the contract to a route so the compiler can check route/schema drift:", ` import { ${prefix}Body, ${prefix}Response } from "./contracts/${contractName}.contract";`, ` @Post("/", { body: ${prefix}Body, responses: { 200: ${prefix}Response } })`, "Fill in the schema fields and reuse them in command decoders; never widen them to unknown.");
29344
29606
  }
29345
- return textResult(lines.join(`
29607
+ return textResult2(lines.join(`
29346
29608
  `));
29347
29609
  }
29348
29610
  function formatDiagnostic(diagnostic) {
@@ -29369,17 +29631,17 @@ function parseInclude(include) {
29369
29631
  return patterns && patterns.length > 0 ? patterns : undefined;
29370
29632
  }
29371
29633
  function sourceRoot(args, root, configured) {
29372
- const hasConfig = ["ts", "mts", "js", "mjs"].some((extension) => existsSync11(join13(root, `supacloud.config.${extension}`)));
29634
+ const hasConfig = ["ts", "mts", "js", "mjs"].some((extension) => existsSync12(join14(root, `supacloud.config.${extension}`)));
29373
29635
  return args.root && !hasConfig ? "." : configured;
29374
29636
  }
29375
29637
  async function projectCompileConfig(args) {
29376
- const root = resolve18(args.root || process.cwd());
29377
- const configFile = ["ts", "mts", "js", "mjs"].map((extension) => join13(root, `supacloud.config.${extension}`)).find((candidate) => existsSync11(candidate)) ?? null;
29638
+ const root = resolve19(args.root || process.cwd());
29639
+ const configFile = ["ts", "mts", "js", "mjs"].map((extension) => join14(root, `supacloud.config.${extension}`)).find((candidate) => existsSync12(candidate)) ?? null;
29378
29640
  const loadedConfig = await loadSupacloudConfig(root);
29379
29641
  const defaults = resolveSupacloudConfig(loadedConfig, root);
29380
29642
  const configuredRoot = sourceRoot(args, root, loadedConfig.root);
29381
29643
  const include = parseInclude(args.include) ?? loadedConfig.include;
29382
- const outDir = args.out_dir ? resolve18(root, args.out_dir) : defaults.outDir;
29644
+ const outDir = args.out_dir ? resolve19(root, args.out_dir) : defaults.outDir;
29383
29645
  const compileOptions = compileOptionsFromConfig({
29384
29646
  ...loadedConfig,
29385
29647
  ...configuredRoot === undefined ? {} : { root: configuredRoot },
@@ -29391,12 +29653,12 @@ async function projectCompileConfig(args) {
29391
29653
  return { root, sourceDir: compileOptions.rootDir, configFile, outDir, result };
29392
29654
  }
29393
29655
  async function readAllowedDependencies(root) {
29394
- const path = join13(root, "package.json");
29395
- if (!existsSync11(path)) {
29656
+ const path = join14(root, "package.json");
29657
+ if (!existsSync12(path)) {
29396
29658
  return { dependencies: [], devDependencies: [], optionalDependencies: [], peerDependencies: [] };
29397
29659
  }
29398
29660
  try {
29399
- const parsed = JSON.parse(await readFile4(path, "utf8"));
29661
+ const parsed = JSON.parse(await readFile5(path, "utf8"));
29400
29662
  return {
29401
29663
  dependencies: Object.keys(parsed.dependencies ?? {}).sort(),
29402
29664
  devDependencies: Object.keys(parsed.devDependencies ?? {}).sort(),
@@ -29430,7 +29692,7 @@ async function runContext(args) {
29430
29692
  const subject = args.target?.trim();
29431
29693
  if (subject) {
29432
29694
  const pack = createContextPack({ ...result.graph, diagnostics: result.diagnostics }, subject);
29433
- const execution = args.events === undefined ? undefined : createExecutionContextPack({ ...result.graph, diagnostics: result.diagnostics }, subject, await readExecutionMetadata(resolve18(root, args.events)), args.request_id);
29695
+ const execution = args.events === undefined ? undefined : createExecutionContextPack({ ...result.graph, diagnostics: result.diagnostics }, subject, await readExecutionMetadata(resolve19(root, args.events)), args.request_id);
29434
29696
  const verification = await createVerificationPlan(root, result.graph, pack.subject, sourceDir);
29435
29697
  const repairs = createDiagnosticRepairPlan(pack.diagnostics);
29436
29698
  const workflow = {
@@ -29461,7 +29723,7 @@ async function runContext(args) {
29461
29723
  },
29462
29724
  executed: false
29463
29725
  };
29464
- return textResult(args.format === "json" ? JSON.stringify({ ...pack, ...execution ? { execution } : {}, workflow }, null, 2) : [
29726
+ return textResult2(args.format === "json" ? JSON.stringify({ ...pack, ...execution ? { execution } : {}, workflow }, null, 2) : [
29465
29727
  formatModuleContextPack(pack),
29466
29728
  ` edit files (project-relative): ${workflow.editFiles.join(", ") || "-"}`,
29467
29729
  ` focused tests: ${verification.tests.join(", ") || "-"}`,
@@ -29510,8 +29772,8 @@ async function runContext(args) {
29510
29772
  }
29511
29773
  };
29512
29774
  if (args.format === "json")
29513
- return textResult(JSON.stringify(project, null, 2));
29514
- return textResult([
29775
+ return textResult2(JSON.stringify(project, null, 2));
29776
+ return textResult2([
29515
29777
  `CONTEXT ${root}`,
29516
29778
  ` config: ${configFile ?? "(none)"}`,
29517
29779
  ` generated: ${outDir}`,
@@ -29544,13 +29806,13 @@ async function runLens(args) {
29544
29806
  diagnostics: result.diagnostics
29545
29807
  };
29546
29808
  if (args.format === "json")
29547
- return textResult(JSON.stringify(output, null, 2), lens.conflicts.some((conflict) => conflict.severity === "error"));
29809
+ return textResult2(JSON.stringify(output, null, 2), lens.conflicts.some((conflict) => conflict.severity === "error"));
29548
29810
  const lines = [`LENS ${context?.subject ?? "application"}`, ` semantic hash: ${lens.snapshot.semanticHash}`, ` source hash: ${lens.snapshot.sourceHash}`];
29549
29811
  for (const item of lens.nodes)
29550
29812
  lines.push(` ${item.kind} ${item.id} ${item.hash}`);
29551
29813
  for (const conflict of lens.conflicts)
29552
29814
  lines.push(` ${conflict.severity.toUpperCase()} ${conflict.code}: ${conflict.message}`);
29553
- return textResult(lines.join(`
29815
+ return textResult2(lines.join(`
29554
29816
  `), lens.conflicts.some((conflict) => conflict.severity === "error"));
29555
29817
  }
29556
29818
  function doctorFixPlan(doctor) {
@@ -29572,7 +29834,7 @@ async function findUnwiredContracts(rootDir) {
29572
29834
  for (const entry of entries) {
29573
29835
  if (skip.has(entry.name))
29574
29836
  continue;
29575
- const path = join13(directory, entry.name);
29837
+ const path = join14(directory, entry.name);
29576
29838
  if (entry.isDirectory())
29577
29839
  await walk(path);
29578
29840
  else if (entry.isFile() && entry.name.endsWith(".ts"))
@@ -29583,10 +29845,10 @@ async function findUnwiredContracts(rootDir) {
29583
29845
  const contracts = files.filter((file) => file.endsWith(".contract.ts"));
29584
29846
  if (contracts.length === 0)
29585
29847
  return [];
29586
- const otherSources = await Promise.all(files.filter((file) => !contracts.includes(file)).map(async (file) => await readFile4(file, "utf8").catch(() => "")));
29848
+ const otherSources = await Promise.all(files.filter((file) => !contracts.includes(file)).map(async (file) => await readFile5(file, "utf8").catch(() => "")));
29587
29849
  const unwired = [];
29588
29850
  for (const contract of contracts) {
29589
- const source = await readFile4(contract, "utf8").catch(() => "");
29851
+ const source = await readFile5(contract, "utf8").catch(() => "");
29590
29852
  const symbols = [...source.matchAll(/export\s+const\s+([A-Za-z_$][A-Za-z0-9_$]*)/g)].map((match) => match[1]);
29591
29853
  if (symbols.length === 0)
29592
29854
  continue;
@@ -29602,6 +29864,15 @@ async function runDoctor(args) {
29602
29864
  const target = args.target?.trim();
29603
29865
  const context = target ? createContextPack({ ...result.graph, diagnostics: result.diagnostics }, target) : undefined;
29604
29866
  const doctor = doctorProject(root, outDir, { ...result.graph, ...context ? { modules: context.modules } : {}, diagnostics: [] }, result.upToDate, context?.diagnostics ?? result.diagnostics);
29867
+ const secretGap = await readSecretGap(root, process.env.SUPACLOUD_ENV?.trim() ?? "");
29868
+ if (secretGap.missing.length > 0) {
29869
+ doctor.errors += 1;
29870
+ doctor.diagnostics = [...doctor.diagnostics ?? [], {
29871
+ severity: "error",
29872
+ code: "SUPACLOUD_SECRET_MISSING",
29873
+ message: `Missing environment secrets: ${secretGap.missing.join(", ")}`
29874
+ }];
29875
+ }
29605
29876
  const database = context ? null : checkAppDatabaseSources(root);
29606
29877
  if (database) {
29607
29878
  doctor.checks.push(database);
@@ -29626,7 +29897,7 @@ async function runDoctor(args) {
29626
29897
  generatedArtifactCheck: "project-wide"
29627
29898
  } : undefined;
29628
29899
  if (args.format === "json") {
29629
- return textResult(JSON.stringify({
29900
+ return textResult2(JSON.stringify({
29630
29901
  ok: doctor.errors === 0,
29631
29902
  next,
29632
29903
  autoFixable,
@@ -29634,11 +29905,15 @@ async function runDoctor(args) {
29634
29905
  manualFixes,
29635
29906
  fixPlan,
29636
29907
  unwiredContracts,
29908
+ secretGap,
29637
29909
  ...scope ? { scope } : {},
29638
29910
  ...doctor
29639
29911
  }, null, 2), doctor.errors > 0);
29640
29912
  }
29641
29913
  const lines = doctor.checks.map((check) => formatDoctorCheck(check));
29914
+ if (secretGap.required.length > 0) {
29915
+ lines.push(`Environment secrets (${secretGap.environment}): ${secretGap.missing.length === 0 ? "ready" : `missing ${secretGap.missing.join(", ")}`}`);
29916
+ }
29642
29917
  if (scope)
29643
29918
  lines.unshift(`TARGET ${scope.target}; omitted project diagnostics=${scope.omittedProjectDiagnostics}; generated drift remains project-wide`);
29644
29919
  for (const diagnostic of doctor.diagnostics ?? []) {
@@ -29658,11 +29933,11 @@ async function runDoctor(args) {
29658
29933
  if (unwiredContracts.length > 0) {
29659
29934
  lines.push(`${unwiredContracts.length} unwired contract file(s): ${unwiredContracts.map((contract) => contract.file).join(", ")}. Import their schemas into a controller route or remove them.`);
29660
29935
  }
29661
- return textResult(lines.join(`
29936
+ return textResult2(lines.join(`
29662
29937
  `), doctor.errors > 0);
29663
29938
  }
29664
29939
  async function runFix(args) {
29665
- const root = resolve18(args.root || process.cwd());
29940
+ const root = resolve19(args.root || process.cwd());
29666
29941
  const fixPath = args.fix?.trim();
29667
29942
  const doctorPath = args.from_doctor?.trim();
29668
29943
  if (fixPath && doctorPath)
@@ -29677,7 +29952,7 @@ async function runFix(args) {
29677
29952
  if (!Number.isSafeInteger(rawIndex) || rawIndex === undefined || rawIndex < 0) {
29678
29953
  throw new Error("app fix --from-doctor requires a non-negative --fix-index <n>");
29679
29954
  }
29680
- const doctor = JSON.parse(await readFile4(resolve18(root, doctorPath), "utf8"));
29955
+ const doctor = JSON.parse(await readFile5(resolve19(root, doctorPath), "utf8"));
29681
29956
  if (!doctor || typeof doctor !== "object" || !Array.isArray(doctor.fixPlan)) {
29682
29957
  throw new Error("Invalid doctor output: expected a fixPlan array");
29683
29958
  }
@@ -29696,11 +29971,11 @@ async function runFix(args) {
29696
29971
  parsed = repairEntry.fix;
29697
29972
  source = "doctor";
29698
29973
  } else {
29699
- parsed = JSON.parse(await readFile4(resolve18(root, fixPath), "utf8"));
29974
+ parsed = JSON.parse(await readFile5(resolve19(root, fixPath), "utf8"));
29700
29975
  }
29701
29976
  const write = args.write === true;
29702
29977
  const applied = await applyDiagnosticFix(parsed, { rootDir: root, dryRun: !write });
29703
- return textResult(JSON.stringify({
29978
+ return textResult2(JSON.stringify({
29704
29979
  ok: true,
29705
29980
  source,
29706
29981
  ...source === "doctor" ? {
@@ -29745,7 +30020,7 @@ function devDatabase(profile, explicit) {
29745
30020
  }
29746
30021
  function readManifestModules(outDir) {
29747
30022
  try {
29748
- const parsed = JSON.parse(readFileSync9(join13(outDir, "app.manifest.json"), "utf8"));
30023
+ const parsed = JSON.parse(readFileSync9(join14(outDir, "app.manifest.json"), "utf8"));
29749
30024
  return Array.isArray(parsed.modules) ? parsed.modules.map((module) => module.name) : [];
29750
30025
  } catch {
29751
30026
  return [];
@@ -29779,21 +30054,21 @@ async function runAppDev(args, options) {
29779
30054
  profile: args.profile,
29780
30055
  databaseUrl: args.database_url,
29781
30056
  signal: options.signal,
29782
- onOutput: (text) => options.onDevProgress?.(textResult(args.format === "json" ? JSON.stringify({ version: 1, source: "application", output: text }) : text))
30057
+ onOutput: (text) => options.onDevProgress?.(textResult2(args.format === "json" ? JSON.stringify({ version: 1, source: "application", output: text }) : text))
29783
30058
  });
29784
- return textResult(JSON.stringify({ version: 1, ok: result.exitCode === 0, ...result }), result.exitCode !== 0);
30059
+ return textResult2(JSON.stringify({ version: 1, ok: result.exitCode === 0, ...result }), result.exitCode !== 0);
29785
30060
  }
29786
30061
  const profile = args.profile ?? "fast";
29787
30062
  if (profile !== "fast" && profile !== "integration") {
29788
30063
  throw new ScaffoldError("SCAFFOLD_OPTION_INVALID", "app dev --profile must be fast or integration");
29789
30064
  }
29790
30065
  const database = devDatabase(profile, args.database_url);
29791
- const root = resolve18(args.root || process.cwd());
30066
+ const root = resolve19(args.root || process.cwd());
29792
30067
  const loadedConfig = await loadSupacloudConfig(root);
29793
30068
  const defaults = resolveSupacloudConfig(loadedConfig, root);
29794
30069
  const configuredRoot = sourceRoot(args, root, loadedConfig.root);
29795
30070
  const include = parseInclude(args.include) ?? loadedConfig.include;
29796
- const outDir = args.out_dir ? resolve18(root, args.out_dir) : defaults.outDir;
30071
+ const outDir = args.out_dir ? resolve19(root, args.out_dir) : defaults.outDir;
29797
30072
  const watch = args.once !== true && args.watch !== false;
29798
30073
  const compileOptions = compileOptionsFromConfig({
29799
30074
  ...loadedConfig,
@@ -29808,7 +30083,7 @@ async function runAppDev(args, options) {
29808
30083
  const artifacts = hasError ? "not-current" : "current";
29809
30084
  const notVerified = DEV_NOT_VERIFIED[profile];
29810
30085
  if (args.format === "json") {
29811
- return textResult(JSON.stringify({
30086
+ return textResult2(JSON.stringify({
29812
30087
  version: 1,
29813
30088
  ok: !hasError,
29814
30089
  profile,
@@ -29824,7 +30099,7 @@ async function runAppDev(args, options) {
29824
30099
  notVerified
29825
30100
  }, null, progress ? undefined : 2), hasError);
29826
30101
  }
29827
- return textResult([
30102
+ return textResult2([
29828
30103
  `app watch (compile-only, profile: ${profile}, watch: ${watch ? "on" : "off"}, state: ${state})`,
29829
30104
  ` root: ${root}`,
29830
30105
  ` outDir: ${outDir}`,
@@ -29879,7 +30154,7 @@ async function runAppDev(args, options) {
29879
30154
  return report(lastEvent, "stopped");
29880
30155
  }
29881
30156
  async function runCompile(args) {
29882
- const root = resolve18(args.root || process.cwd());
30157
+ const root = resolve19(args.root || process.cwd());
29883
30158
  const loadedConfig = await loadSupacloudConfig(root);
29884
30159
  const defaults = resolveSupacloudConfig(loadedConfig, root);
29885
30160
  const configuredRoot = sourceRoot(args, root, loadedConfig.root);
@@ -29888,7 +30163,7 @@ async function runCompile(args) {
29888
30163
  ...compileOptionsFromConfig({
29889
30164
  ...loadedConfig,
29890
30165
  ...configuredRoot === undefined ? {} : { root: configuredRoot },
29891
- outDir: args.out_dir ? resolve18(root, args.out_dir) : defaults.outDir,
30166
+ outDir: args.out_dir ? resolve19(root, args.out_dir) : defaults.outDir,
29892
30167
  ...include === undefined ? {} : { include },
29893
30168
  strict: args.strict ?? loadedConfig.strict ?? false
29894
30169
  }, root),
@@ -29896,7 +30171,7 @@ async function runCompile(args) {
29896
30171
  });
29897
30172
  const hasError = result.diagnostics.some((diagnostic) => diagnostic.severity === "error");
29898
30173
  if (args.format === "json")
29899
- return textResult(JSON.stringify({
30174
+ return textResult2(JSON.stringify({
29900
30175
  version: 1,
29901
30176
  ok: !hasError,
29902
30177
  diagnostics: result.diagnostics,
@@ -29909,10 +30184,10 @@ async function runCompile(args) {
29909
30184
  ...result.written.map((path) => ` ${path}`)
29910
30185
  ].join(`
29911
30186
  `);
29912
- return textResult(text, hasError);
30187
+ return textResult2(text, hasError);
29913
30188
  }
29914
30189
  async function runCheck(args) {
29915
- const root = resolve18(args.root || process.cwd());
30190
+ const root = resolve19(args.root || process.cwd());
29916
30191
  const database = checkAppDatabaseSources(root);
29917
30192
  const loadedConfig = await loadSupacloudConfig(root);
29918
30193
  const defaults = resolveSupacloudConfig(loadedConfig, root);
@@ -29921,7 +30196,7 @@ async function runCheck(args) {
29921
30196
  const config = compileOptionsFromConfig({
29922
30197
  ...loadedConfig,
29923
30198
  ...configuredRoot === undefined ? {} : { root: configuredRoot },
29924
- outDir: args.out_dir ? resolve18(root, args.out_dir) : defaults.outDir,
30199
+ outDir: args.out_dir ? resolve19(root, args.out_dir) : defaults.outDir,
29925
30200
  ...include === undefined ? {} : { include },
29926
30201
  strict: args.strict ?? loadedConfig.strict ?? false
29927
30202
  }, root);
@@ -29930,7 +30205,7 @@ async function runCheck(args) {
29930
30205
  const hasError = diagnosticError || result.mismatches.length > 0 || database?.ok === false;
29931
30206
  const next = hasError ? diagnosticError || database?.ok === false ? ["supacloud app doctor --format json"] : ["supacloud app compile", "supacloud app check --format json"] : ["supacloud app verify-plan --target <module>"];
29932
30207
  if (args.format === "json")
29933
- return textResult(JSON.stringify({
30208
+ return textResult2(JSON.stringify({
29934
30209
  version: 1,
29935
30210
  ok: !hasError,
29936
30211
  next,
@@ -29943,7 +30218,7 @@ async function runCheck(args) {
29943
30218
  ...database ? { database } : {}
29944
30219
  }, null, 2), hasError);
29945
30220
  const summary = `checked ${result.graph.modules.length} module(s), no files written`;
29946
- return textResult([
30221
+ return textResult2([
29947
30222
  formatDiagnostics(result.diagnostics),
29948
30223
  ...result.mismatches.map((path) => `generated artifact mismatch: ${path}`),
29949
30224
  ...database ? [formatDoctorCheck(database)] : [],
@@ -29954,12 +30229,12 @@ async function runCheck(args) {
29954
30229
  }
29955
30230
  async function readManifest(root, args) {
29956
30231
  const config = await loadSupacloudConfig(root);
29957
- const outDir = args.out_dir ? resolve18(root, args.out_dir) : resolveSupacloudConfig(config, root).outDir;
29958
- const manifestPath = join13(outDir, "app.manifest.json");
29959
- if (!existsSync11(manifestPath)) {
30232
+ const outDir = args.out_dir ? resolve19(root, args.out_dir) : resolveSupacloudConfig(config, root).outDir;
30233
+ const manifestPath = join14(outDir, "app.manifest.json");
30234
+ if (!existsSync12(manifestPath)) {
29960
30235
  throw new Error(`Manifest not found: ${manifestPath}(先运行 app compile 生成)`);
29961
30236
  }
29962
- const parsed = JSON.parse(await readFile4(manifestPath, "utf8"));
30237
+ const parsed = JSON.parse(await readFile5(manifestPath, "utf8"));
29963
30238
  if (!Array.isArray(parsed.modules)) {
29964
30239
  throw new Error(`Invalid manifest: ${manifestPath}`);
29965
30240
  }
@@ -29999,11 +30274,11 @@ function formatGraphText(manifest) {
29999
30274
  `);
30000
30275
  }
30001
30276
  async function runGraph(args) {
30002
- const root = resolve18(args.root || process.cwd());
30277
+ const root = resolve19(args.root || process.cwd());
30003
30278
  const manifest = await readManifest(root, args);
30004
30279
  if (args.format === "json")
30005
- return textResult(JSON.stringify(manifest, null, 2));
30006
- return textResult(formatGraphText(manifest));
30280
+ return textResult2(JSON.stringify(manifest, null, 2));
30281
+ return textResult2(formatGraphText(manifest));
30007
30282
  }
30008
30283
  function reverseDependencies(manifest, token) {
30009
30284
  const dependents = [];
@@ -30067,7 +30342,7 @@ async function runExplain(args) {
30067
30342
  const target = args.target?.trim();
30068
30343
  if (!target)
30069
30344
  throw new Error("app explain requires --target(provider 类名 / token 名 / command 名 / job 名)");
30070
- const root = resolve18(args.root || process.cwd());
30345
+ const root = resolve19(args.root || process.cwd());
30071
30346
  const manifest = await readManifest(root, args);
30072
30347
  for (const module of manifest.modules) {
30073
30348
  const job = module.jobs?.find((entry) => entry.name === target || entry.className === target);
@@ -30089,15 +30364,15 @@ async function runExplain(args) {
30089
30364
  lines.push(`idempotency: ${job.idempotency}`);
30090
30365
  const dependents = reverseDependencies(manifest, job.className);
30091
30366
  lines.push(`被依赖: ${dependents.length > 0 ? dependents.join(", ") : "(none)"}`);
30092
- return textResult(lines.join(`
30367
+ return textResult2(lines.join(`
30093
30368
  `));
30094
30369
  }
30095
30370
  const providerIndex = module.providers.findIndex((provider) => provider.token === target || provider.useClass === target);
30096
30371
  if (providerIndex >= 0)
30097
- return textResult(explainProvider(manifest, module, providerIndex));
30372
+ return textResult2(explainProvider(manifest, module, providerIndex));
30098
30373
  const controllerIndex = module.controllers.findIndex((controller) => controller.className === target);
30099
30374
  if (controllerIndex >= 0)
30100
- return textResult(explainController(manifest, module, controllerIndex));
30375
+ return textResult2(explainController(manifest, module, controllerIndex));
30101
30376
  const command = module.commands.find((entry) => entry.name === target || entry.className === target);
30102
30377
  if (command) {
30103
30378
  const lines = [
@@ -30116,12 +30391,12 @@ async function runExplain(args) {
30116
30391
  lines.push(`idempotency: ${command.idempotency}`);
30117
30392
  const dependents = reverseDependencies(manifest, command.className);
30118
30393
  lines.push(`被依赖: ${dependents.length > 0 ? dependents.join(", ") : "(none)"}`);
30119
- return textResult(lines.join(`
30394
+ return textResult2(lines.join(`
30120
30395
  `));
30121
30396
  }
30122
30397
  const query = module.queries.find((entry) => entry.name === target || entry.className === target);
30123
30398
  if (query) {
30124
- return textResult([
30399
+ return textResult2([
30125
30400
  `对象: ${query.name}`,
30126
30401
  "类型: query",
30127
30402
  `所属模块: ${module.name}`,
@@ -30132,28 +30407,28 @@ async function runExplain(args) {
30132
30407
  }
30133
30408
  if (manifest.externalTokens.includes(target)) {
30134
30409
  const dependents = reverseDependencies(manifest, target);
30135
- return textResult([
30410
+ return textResult2([
30136
30411
  `对象: ${target}`,
30137
30412
  "类型: externalToken(平台注入,无模块提供)",
30138
30413
  `被依赖: ${dependents.length > 0 ? dependents.join(", ") : "(none)"}`
30139
30414
  ].join(`
30140
30415
  `));
30141
30416
  }
30142
- return textResult(`未找到对象: ${target}`, true);
30417
+ return textResult2(`未找到对象: ${target}`, true);
30143
30418
  }
30144
30419
  async function runExportTools(args) {
30145
- const root = resolve18(args.root || process.cwd());
30420
+ const root = resolve19(args.root || process.cwd());
30146
30421
  const manifest = await readManifest(root, { ...args, out_dir: undefined });
30147
30422
  const definitions = buildToolDefinitions(manifest);
30148
- const outDir = resolve18(args.out_dir || join13(root, "generated"));
30423
+ const outDir = resolve19(args.out_dir || join14(root, "generated"));
30149
30424
  if (args.format === "json") {
30150
- return textResult(JSON.stringify(definitions, null, 2));
30425
+ return textResult2(JSON.stringify(definitions, null, 2));
30151
30426
  }
30152
- await mkdir5(outDir, { recursive: true });
30153
- const openaiPath = join13(outDir, "tool-definitions.openai.json");
30154
- const mcpPath = join13(outDir, "tool-definitions.mcp.json");
30155
- await writeFile4(openaiPath, JSON.stringify(definitions.openai, null, 2), "utf8");
30156
- await writeFile4(mcpPath, JSON.stringify(definitions.mcp, null, 2), "utf8");
30427
+ await mkdir6(outDir, { recursive: true });
30428
+ const openaiPath = join14(outDir, "tool-definitions.openai.json");
30429
+ const mcpPath = join14(outDir, "tool-definitions.mcp.json");
30430
+ await writeFile5(openaiPath, JSON.stringify(definitions.openai, null, 2), "utf8");
30431
+ await writeFile5(mcpPath, JSON.stringify(definitions.mcp, null, 2), "utf8");
30157
30432
  const summary = [
30158
30433
  `exported ${definitions.openai.length} tool(s):`,
30159
30434
  ` openai → ${openaiPath}`,
@@ -30163,29 +30438,29 @@ async function runExportTools(args) {
30163
30438
  `)
30164
30439
  ].join(`
30165
30440
  `);
30166
- return textResult(summary);
30441
+ return textResult2(summary);
30167
30442
  }
30168
30443
  async function runDelivery(args) {
30169
- const root = resolve18(args.root || process.cwd());
30444
+ const root = resolve19(args.root || process.cwd());
30170
30445
  if (args.action === "build") {
30171
30446
  const database = checkAppDatabaseSources(root);
30172
30447
  if (database && !database.ok) {
30173
- return textResult(JSON.stringify({ ok: false, database, written: [] }, null, 2), true);
30448
+ return textResult2(JSON.stringify({ ok: false, database, written: [] }, null, 2), true);
30174
30449
  }
30175
30450
  }
30176
30451
  const loaded = await loadSupacloudConfig(root);
30177
30452
  const options = compileOptionsFromConfig({
30178
30453
  ...loaded,
30179
- ...args.out_dir === undefined ? {} : { outDir: resolve18(root, args.out_dir) },
30454
+ ...args.out_dir === undefined ? {} : { outDir: resolve19(root, args.out_dir) },
30180
30455
  ...args.include === undefined ? {} : { include: parseInclude(args.include) },
30181
30456
  ...args.strict === undefined ? {} : { strict: args.strict }
30182
30457
  }, root);
30183
30458
  if (args.action === "plan") {
30184
30459
  const result = await planDeliveryProject(options, loaded.delivery);
30185
- return textResult(args.format === "json" ? JSON.stringify(result, null, 2) : formatDeliveryPlan(result), !result.ok);
30460
+ return textResult2(args.format === "json" ? JSON.stringify(result, null, 2) : formatDeliveryPlan(result), !result.ok);
30186
30461
  }
30187
30462
  const result = await buildDeliveryProject(options, loaded.delivery);
30188
- return textResult(JSON.stringify(result, null, 2), !result.ok);
30463
+ return textResult2(JSON.stringify(result, null, 2), !result.ok);
30189
30464
  }
30190
30465
  function resultObject(result) {
30191
30466
  try {
@@ -30225,7 +30500,7 @@ function releasePhaseFailure(phase, result, completed) {
30225
30500
  if (phaseResult?.expected_activation_id !== undefined) {
30226
30501
  payload.expected_activation_id = phaseResult.expected_activation_id;
30227
30502
  }
30228
- return textResult(JSON.stringify(payload, null, 2), true);
30503
+ return textResult2(JSON.stringify(payload, null, 2), true);
30229
30504
  }
30230
30505
  function releaseField(payload, container, field) {
30231
30506
  const value = payload?.[container];
@@ -30253,7 +30528,7 @@ async function runAppRelease(request, options, delegate) {
30253
30528
  if (request.activation_id !== undefined || request.expected_activation_id !== undefined) {
30254
30529
  throw new Error("app release generates one activation identity; use app deploy for an exact retry");
30255
30530
  }
30256
- const root = resolve18(request.root || process.cwd());
30531
+ const root = resolve19(request.root || process.cwd());
30257
30532
  const completed = {};
30258
30533
  let manifestPath;
30259
30534
  let buildReceipt;
@@ -30261,7 +30536,7 @@ async function runAppRelease(request, options, delegate) {
30261
30536
  if (request.manifest_path === undefined) {
30262
30537
  throw new Error("app release --skip_build requires --manifest_path");
30263
30538
  }
30264
- manifestPath = resolve18(root, request.manifest_path);
30539
+ manifestPath = resolve19(root, request.manifest_path);
30265
30540
  completed.build = { skipped: true, manifest_path: manifestPath };
30266
30541
  } else {
30267
30542
  const built = await runDelivery({ ...request, action: "build", root, format: "json" });
@@ -30271,7 +30546,7 @@ async function runAppRelease(request, options, delegate) {
30271
30546
  }
30272
30547
  const loaded = await loadSupacloudConfig(root);
30273
30548
  const resolved = resolveSupacloudConfig(loaded, root);
30274
- manifestPath = join13(resolved.outDir, "delivery", "delivery.manifest.json");
30549
+ manifestPath = join14(resolved.outDir, "delivery", "delivery.manifest.json");
30275
30550
  completed.build = {
30276
30551
  ok: true,
30277
30552
  manifest_path: manifestPath,
@@ -30298,7 +30573,7 @@ async function runAppRelease(request, options, delegate) {
30298
30573
  let configurationWrite;
30299
30574
  const activationId = crypto.randomUUID();
30300
30575
  if (request.configuration_path !== undefined) {
30301
- const configurationPath = resolve18(root, request.configuration_path);
30576
+ const configurationPath = resolve19(root, request.configuration_path);
30302
30577
  try {
30303
30578
  configurationWrite = parseApplicationConfigurationWrite(await Bun.file(configurationPath).json());
30304
30579
  configurationId = configurationWrite.configuration_id;
@@ -30359,7 +30634,7 @@ async function runAppRelease(request, options, delegate) {
30359
30634
  ...typeof deployReceipt.activation_id === "string" ? { activation_id: deployReceipt.activation_id } : {},
30360
30635
  ...deployReceipt.web === undefined ? {} : { web: deployReceipt.web }
30361
30636
  };
30362
- return request.format === "json" ? textResult(JSON.stringify(result, null, 2)) : textResult([
30637
+ return request.format === "json" ? textResult2(JSON.stringify(result, null, 2)) : textResult2([
30363
30638
  `${ref}/${id}/${environmentId}: ${deployReceipt.status === "accepted" ? "accepted" : result.no_op ? "no-op" : "released"}`,
30364
30639
  `Release: ${releaseId}`,
30365
30640
  `Configuration: ${configurationId}`,
@@ -30382,7 +30657,7 @@ function formatReleaseTransfer(result) {
30382
30657
  const data = plan ?? receipt;
30383
30658
  if (!data)
30384
30659
  return result;
30385
- return textResult([
30660
+ return textResult2([
30386
30661
  `${data.project_ref}/${data.application_id}: ${plan ? plan.action === "no-op" ? "No changes" : "Transfer required" : "Artifact transferred"}`,
30387
30662
  `Source: ${data.source.project_ref} / ${data.source.release_id}`,
30388
30663
  `Target release: ${data.candidate_release_id}`,
@@ -30429,7 +30704,7 @@ function historyText(result, request, projectRef) {
30429
30704
  }
30430
30705
  if (history.next_cursor)
30431
30706
  lines.push("", `Next cursor: ${history.next_cursor}`);
30432
- return textResult(lines.join(`
30707
+ return textResult2(lines.join(`
30433
30708
  `));
30434
30709
  } catch {
30435
30710
  return releaseControlFailure("applications.get_history", "INVALID_RESPONSE", null);
@@ -30449,7 +30724,7 @@ function formatRemoteDeployPlan(result) {
30449
30724
  ...names(plan.changes.targets.removed, "-"),
30450
30725
  ...names(plan.changes.targets.changed, "~")
30451
30726
  ];
30452
- return textResult([
30727
+ return textResult2([
30453
30728
  `${plan.project_ref}/${plan.application_id} [${plan.environment_id}]: ${plan.action === "no-op" ? "No changes" : "Activation required"}`,
30454
30729
  `Release: ${plan.candidate.release_id} (${plan.changes.release ? "changed" : "unchanged"})`,
30455
30730
  `Configuration: ${plan.candidate.configuration_id} (${plan.changes.configuration ? "changed" : "unchanged"})`,
@@ -30471,7 +30746,7 @@ function formatPromotionPlan2(result) {
30471
30746
  if (!payload || typeof payload !== "object" || !("plan" in payload))
30472
30747
  return result;
30473
30748
  const plan = parseApplicationPromotionPlan(payload.plan);
30474
- return textResult([
30749
+ return textResult2([
30475
30750
  `${plan.project_ref}/${plan.application_id}/${plan.environment_id}: ${plan.action}`,
30476
30751
  `Source: ${plan.source.project_ref}/${plan.source.environment_id}`,
30477
30752
  ...plan.blockers.length ? [`Blocked: ${plan.blockers.join(", ")}`] : [],
@@ -30498,7 +30773,7 @@ function formatPromotionExecution(result) {
30498
30773
  const receipt = payload.result;
30499
30774
  if (receipt.project_ref !== envelope.project_ref || receipt.application_id !== envelope.application_id || receipt.environment_id !== envelope.environment_id || receipt.mutation_id !== envelope.mutation_id || receipt.plan_sha256 !== envelope.plan_sha256)
30500
30775
  return result;
30501
- return textResult([
30776
+ return textResult2([
30502
30777
  `${String(envelope.project_ref)}/${String(envelope.application_id)}/${String(envelope.environment_id)}: promoted`,
30503
30778
  `Mutation: ${String(envelope.mutation_id)}`,
30504
30779
  `Activation: ${String(receipt.activation_id)}`,
@@ -30529,7 +30804,7 @@ function formatWorkflowObservation(result, action) {
30529
30804
  if (!data.mutation || typeof data.mutation !== "object" || !("mutation_id" in data.mutation) || typeof data.mutation.mutation_id !== "string")
30530
30805
  return result;
30531
30806
  const status = parsePromotionStatus({ ...identity, mutation: data.mutation, promotion: data.promotion }, { ...identity, mutation_id: data.mutation.mutation_id });
30532
- return textResult([
30807
+ return textResult2([
30533
30808
  `${label}: ${status.mutation.status}`,
30534
30809
  `Mutation: ${status.mutation.mutation_id}`,
30535
30810
  `Phase: ${status.promotion.phase ?? "not recorded"}`,
@@ -30539,15 +30814,21 @@ function formatWorkflowObservation(result, action) {
30539
30814
  }
30540
30815
  if (action === "preview-list" || action === "previews") {
30541
30816
  const list = parsePreviewList({ ...identity, previews: data.previews }, identity);
30542
- return textResult([
30817
+ return textResult2([
30543
30818
  `${label}: ${list.previews.length} preview(s)`,
30544
30819
  ...list.previews.map((preview) => `${preview.preview_id} ${preview.status} ${preview.resources.database_branch.branch_ref}`)
30545
30820
  ].join(`
30546
30821
  `));
30547
30822
  }
30548
- if (["preview-plan", "preview-create", "preview-status", "preview-reconcile", "preview-cleanup"].includes(action)) {
30823
+ if (action === "preview-pr") {
30824
+ const status = typeof data.status === "string" ? data.status : "unknown";
30825
+ const previewId = typeof data.preview_id === "string" ? data.preview_id : "unknown";
30826
+ return textResult2(`${label}: PR preview ${status}
30827
+ Preview: ${previewId}`);
30828
+ }
30829
+ if (["preview-plan", "preview-create", "preview-status", "preview-reconcile", "preview-cleanup", "preview-pr"].includes(action)) {
30549
30830
  const preview = parsePreviewReceipt(data.preview ?? data, identity);
30550
- return textResult([
30831
+ return textResult2([
30551
30832
  `${label}: ${preview.status}`,
30552
30833
  `Preview: ${preview.preview_id}`,
30553
30834
  `Branch: ${preview.resources.database_branch.branch_ref} (${preview.resources.database_branch.data_mode})`,
@@ -30576,16 +30857,16 @@ async function runPromotion(request, options, delegate) {
30576
30857
  try {
30577
30858
  payload = JSON.parse(planned.content[0]?.text ?? "");
30578
30859
  } catch {
30579
- return textResult("Promotion plan response was not valid JSON.", true);
30860
+ return textResult2("Promotion plan response was not valid JSON.", true);
30580
30861
  }
30581
30862
  if (!payload || typeof payload !== "object" || !("plan" in payload)) {
30582
- return textResult("Promotion plan response was invalid.", true);
30863
+ return textResult2("Promotion plan response was invalid.", true);
30583
30864
  }
30584
30865
  let plan;
30585
30866
  try {
30586
30867
  plan = parseApplicationPromotionPlan(payload.plan);
30587
30868
  } catch {
30588
- return textResult("Promotion plan failed immutable validation.", true);
30869
+ return textResult2("Promotion plan failed immutable validation.", true);
30589
30870
  }
30590
30871
  const identity = { project_ref: ref, application_id: request.id, environment_id: request.environment_id };
30591
30872
  if (plan.project_ref !== ref || plan.application_id !== request.id || plan.environment_id !== request.environment_id || plan.source.project_ref !== request.source_ref || plan.source.environment_id !== request.source_environment_id || plan.source.release_id !== request.source_release_id || request.configuration_id !== undefined && plan.target.configuration_id !== request.configuration_id) {
@@ -30600,14 +30881,14 @@ async function runPromotion(request, options, delegate) {
30600
30881
  no_op: true,
30601
30882
  execution_performed: false
30602
30883
  });
30603
- return format === "json" ? noOp : textResult(`${plan.project_ref}/${plan.application_id}/${plan.environment_id}: no-op
30884
+ return format === "json" ? noOp : textResult2(`${plan.project_ref}/${plan.application_id}/${plan.environment_id}: no-op
30604
30885
  Execution: skipped`);
30605
30886
  }
30606
30887
  if (plan.blockers.some((code) => !["MIGRATION_PENDING", "BACKUP_REQUIRED"].includes(code))) {
30607
30888
  return releaseControlFailure("applications.promote_application", "MUTATION_NOT_SUCCEEDED", null, { ...identity, plan, execution_performed: false });
30608
30889
  }
30609
30890
  if (!plan.target.configuration_id)
30610
- return textResult("Promotion plan has no target configuration revision.", true);
30891
+ return textResult2("Promotion plan has no target configuration revision.", true);
30611
30892
  const mutationId = crypto.randomUUID();
30612
30893
  const executeArgs = {
30613
30894
  ...remoteRequest,
@@ -30639,19 +30920,19 @@ async function runAppTool(request, options = {}) {
30639
30920
  if (request.action === "promote") {
30640
30921
  const delegate = options.getApplications?.();
30641
30922
  if (!delegate)
30642
- return textResult("App remote actions require a Management API context.", true);
30923
+ return textResult2("App remote actions require a Management API context.", true);
30643
30924
  return runPromotion(request, options, delegate);
30644
30925
  }
30645
30926
  if (request.action === "release") {
30646
30927
  const delegate = options.getApplications?.();
30647
30928
  if (!delegate)
30648
- return textResult("App remote actions require a Management API context.", true);
30929
+ return textResult2("App remote actions require a Management API context.", true);
30649
30930
  return runAppRelease(request, options, delegate);
30650
30931
  }
30651
30932
  if (Object.hasOwn(REMOTE_APP_ACTIONS, request.action)) {
30652
30933
  const delegate = options.getApplications?.();
30653
30934
  if (!delegate)
30654
- return textResult("App remote actions require a Management API context.", true);
30935
+ return textResult2("App remote actions require a Management API context.", true);
30655
30936
  const promotionDiff = request.action === "diff" && request.source_ref !== undefined && request.source_environment_id !== undefined && request.source_release_id !== undefined;
30656
30937
  const action = promotionDiff ? "get_promotion_plan" : REMOTE_APP_ACTIONS[request.action];
30657
30938
  const { format, ...remoteRequest } = request;
@@ -30668,13 +30949,13 @@ async function runAppTool(request, options = {}) {
30668
30949
  if (payload === null || typeof payload !== "object" || !("project_ref" in payload) || payload.project_ref !== args.ref || !("application_id" in payload) || payload.application_id !== request.id || !("environment_id" in payload) || payload.environment_id !== request.environment_id || !("evidence" in payload))
30669
30950
  throw new Error;
30670
30951
  if (payload.evidence === null)
30671
- return textResult("DEPLOYMENT incomplete: no recorded evidence. Read runtime status and obtain authenticated smoke and recovery evidence.");
30952
+ return textResult2("DEPLOYMENT incomplete: no recorded evidence. Read runtime status and obtain authenticated smoke and recovery evidence.");
30672
30953
  const evidence = parseDeploymentEvidence(payload.evidence);
30673
30954
  if (evidence.scope.project_ref !== args.ref || evidence.scope.application_id !== request.id || evidence.scope.environment_id !== request.environment_id)
30674
30955
  throw new Error;
30675
- return textResult(formatDeploymentEvidence(evidence));
30956
+ return textResult2(formatDeploymentEvidence(evidence));
30676
30957
  } catch {
30677
- return textResult("DEPLOYMENT unknown: invalid or mismatched evidence; no mutation was attempted.", true);
30958
+ return textResult2("DEPLOYMENT unknown: invalid or mismatched evidence; no mutation was attempted.", true);
30678
30959
  }
30679
30960
  }
30680
30961
  if (request.action === "history" && format !== "json") {
@@ -30696,7 +30977,7 @@ async function runAppTool(request, options = {}) {
30696
30977
  const { root, sourceDir, result } = await projectCompileConfig(request);
30697
30978
  const plan = await createVerificationPlan(root, result.graph, request.target.trim(), sourceDir);
30698
30979
  const ready = plan.ready && !result.diagnostics.some((item) => item.severity === "error");
30699
- return textResult(JSON.stringify({ ...plan, ready, diagnostics: result.diagnostics }, null, 2), !ready);
30980
+ return textResult2(JSON.stringify({ ...plan, ready, diagnostics: result.diagnostics }, null, 2), !ready);
30700
30981
  }
30701
30982
  case "dev":
30702
30983
  case "watch":
@@ -30712,7 +30993,7 @@ async function runAppTool(request, options = {}) {
30712
30993
  } catch (error) {
30713
30994
  if (request.format !== "json")
30714
30995
  throw error;
30715
- return textResult(JSON.stringify({
30996
+ return textResult2(JSON.stringify({
30716
30997
  version: 1,
30717
30998
  ok: false,
30718
30999
  code: error instanceof ScaffoldError ? error.code : "SCAFFOLD_FAILED",
@@ -30739,7 +31020,7 @@ async function runAppTool(request, options = {}) {
30739
31020
  case "fix":
30740
31021
  return runFix(request);
30741
31022
  default:
30742
- return textResult(`Unknown app action: ${String(request.action)}`, true);
31023
+ return textResult2(`Unknown app action: ${String(request.action)}`, true);
30743
31024
  }
30744
31025
  }
30745
31026
  function registerAppTools(server, options = {}) {
@@ -30786,6 +31067,7 @@ function registerAppTools(server, options = {}) {
30786
31067
  "preview-create",
30787
31068
  "preview-status",
30788
31069
  "preview-cleanup",
31070
+ "preview-pr",
30789
31071
  "preview-reconcile",
30790
31072
  "promote",
30791
31073
  "promote-status",
@@ -30827,8 +31109,8 @@ function registerAppTools(server, options = {}) {
30827
31109
  }
30828
31110
 
30829
31111
  // src/shared/tools/db-governance-tools.ts
30830
- import { existsSync as existsSync13 } from "node:fs";
30831
- import { join as join16, resolve as resolve21 } from "node:path";
31112
+ import { existsSync as existsSync14 } from "node:fs";
31113
+ import { join as join17, resolve as resolve22 } from "node:path";
30832
31114
  import {
30833
31115
  buildDatabaseManifest,
30834
31116
  explainObject,
@@ -30840,9 +31122,9 @@ import { databaseSources } from "@supacloud/db/source-contracts";
30840
31122
 
30841
31123
  // src/shared/tools/db-workflow.ts
30842
31124
  import { createHash as createHash9 } from "node:crypto";
30843
- import { lstat as lstat4, mkdir as mkdir6, mkdtemp, readFile as readFile5, readdir as readdir6, rename as rename3, rm as rm2, writeFile as writeFile5 } from "node:fs/promises";
31125
+ import { lstat as lstat4, mkdir as mkdir7, mkdtemp, readFile as readFile6, readdir as readdir6, rename as rename3, rm as rm2, writeFile as writeFile6 } from "node:fs/promises";
30844
31126
  import { tmpdir as tmpdir2 } from "node:os";
30845
- import { dirname as dirname11, isAbsolute as isAbsolute7, join as join15, relative as relative8, resolve as resolve20 } from "node:path";
31127
+ import { dirname as dirname11, isAbsolute as isAbsolute7, join as join16, relative as relative8, resolve as resolve21 } from "node:path";
30846
31128
  import {
30847
31129
  assertApplicationRoleRestricted,
30848
31130
  readDatabaseRole,
@@ -30853,8 +31135,8 @@ import {
30853
31135
  import { parseDatabaseSourcesConfig } from "@supacloud/db/source-contracts";
30854
31136
 
30855
31137
  // src/shared/tools/supabase-cli-tools.ts
30856
- import { chmodSync as chmodSync2, existsSync as existsSync12, mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync3 } from "node:fs";
30857
- import { dirname as dirname10, isAbsolute as isAbsolute6, join as join14, resolve as resolve19 } from "node:path";
31138
+ import { chmodSync as chmodSync2, existsSync as existsSync13, mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync3 } from "node:fs";
31139
+ import { dirname as dirname10, isAbsolute as isAbsolute6, join as join15, resolve as resolve20 } from "node:path";
30858
31140
  var SENSITIVE_ENV_KEY2 = /(?:^|_)(?:PASSWORD|PASS|SECRET|TOKEN|KEY|CREDENTIALS?|AUTHORIZATION|AUTH|SESSION|COOKIE|BEARER|DB_URI|DB_URL|DSN|DATABASE_URL|DATABASE_URI|CONNECTION_STRING|CONNECTION_URI)(?:_|$)/i;
30859
31141
  var VALID_VERSION2 = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
30860
31142
  var VALID_MIGRATION_NAME2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,100}$/;
@@ -30914,12 +31196,12 @@ function schemaArguments2(schema) {
30914
31196
  function workdirArguments2(workdir) {
30915
31197
  if (!workdir)
30916
31198
  throw new Error("A workdir is required");
30917
- return ["--workdir", resolve19(workdir)];
31199
+ return ["--workdir", resolve20(workdir)];
30918
31200
  }
30919
31201
  function resolveOutputPath2(workdir, file, label) {
30920
31202
  if (!file || /[\r\n\0]/.test(file))
30921
31203
  throw new Error(`${label} file is required`);
30922
- return isAbsolute6(file) ? resolve19(file) : resolve19(workdir, file);
31204
+ return isAbsolute6(file) ? resolve20(file) : resolve20(workdir, file);
30923
31205
  }
30924
31206
  function databaseTargetArguments2(databaseUrl) {
30925
31207
  return databaseUrl ? ["--db-url", requirePostgresUrl2(databaseUrl)] : ["--local"];
@@ -31094,7 +31376,7 @@ function actionArguments2(request, workdir) {
31094
31376
  function buildOfficialSupabaseArgs2(request) {
31095
31377
  if (request.action === "version")
31096
31378
  return ["--version"];
31097
- const workdir = request.workdir ? resolve19(request.workdir) : undefined;
31379
+ const workdir = request.workdir ? resolve20(request.workdir) : undefined;
31098
31380
  if (!workdir)
31099
31381
  throw new Error("A workdir is required");
31100
31382
  return [...actionArguments2(request, workdir), ...workdirArguments2(workdir)];
@@ -31136,8 +31418,8 @@ function resolveOfficialSupabaseCommand2(workdir, environment = process.env) {
31136
31418
  }
31137
31419
  return ["npx", "--yes", `supabase@${version}`];
31138
31420
  }
31139
- const localPackageEntry = join14(resolve19(workdir), "node_modules", "supabase", "dist", "supabase.js");
31140
- if (existsSync12(localPackageEntry))
31421
+ const localPackageEntry = join15(resolve20(workdir), "node_modules", "supabase", "dist", "supabase.js");
31422
+ if (existsSync13(localPackageEntry))
31141
31423
  return [process.execPath, localPackageEntry];
31142
31424
  return ["supabase"];
31143
31425
  }
@@ -31155,7 +31437,7 @@ async function projectPath2(root, path) {
31155
31437
  }
31156
31438
  let current = root;
31157
31439
  for (const part of path.split("/")) {
31158
- current = join15(current, part);
31440
+ current = join16(current, part);
31159
31441
  try {
31160
31442
  if ((await lstat4(current)).isSymbolicLink())
31161
31443
  throw new Error("Symlink workflow paths are forbidden");
@@ -31177,8 +31459,8 @@ async function exists2(path) {
31177
31459
  }
31178
31460
  }
31179
31461
  async function boundary(root) {
31180
- const config = join15(root, "database.sources.json");
31181
- return await exists2(config) ? parseDatabaseSourcesConfig(JSON.parse(await readFile5(await projectPath2(root, "database.sources.json"), "utf8"))) : undefined;
31462
+ const config = join16(root, "database.sources.json");
31463
+ return await exists2(config) ? parseDatabaseSourcesConfig(JSON.parse(await readFile6(await projectPath2(root, "database.sources.json"), "utf8"))) : undefined;
31182
31464
  }
31183
31465
  var overlaps = (a, b) => a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
31184
31466
  async function candidatePath(root, path) {
@@ -31271,9 +31553,9 @@ async function runOfficial(root, workdir, args, environment, options) {
31271
31553
  async function initializeCandidate(stage, majorVersion = 18) {
31272
31554
  if (![15, 16, 17, 18].includes(majorVersion))
31273
31555
  throw new Error("Select a supported PostgreSQL major version (15-18)");
31274
- await mkdir6(join15(stage, "supabase/migrations"), { recursive: true });
31275
- await mkdir6(join15(stage, "supabase/schemas"), { recursive: true });
31276
- await writeFile5(join15(stage, "supabase/config.toml"), [
31556
+ await mkdir7(join16(stage, "supabase/migrations"), { recursive: true });
31557
+ await mkdir7(join16(stage, "supabase/schemas"), { recursive: true });
31558
+ await writeFile6(join16(stage, "supabase/config.toml"), [
31277
31559
  `project_id = "supacloud-candidate-${hash4(stage).slice(0, 12)}"`,
31278
31560
  "[db]",
31279
31561
  `major_version = ${majorVersion}`,
@@ -31286,14 +31568,14 @@ async function initializeCandidate(stage, majorVersion = 18) {
31286
31568
  async function copySqlSources(root, source, destination) {
31287
31569
  const path = await projectPath2(root, source);
31288
31570
  let count = 0;
31289
- await mkdir6(destination, { recursive: true });
31571
+ await mkdir7(destination, { recursive: true });
31290
31572
  for (const name of (await readdir6(path)).sort()) {
31291
31573
  const file = await projectPath2(root, `${source}/${name}`);
31292
31574
  const state = await lstat4(file);
31293
31575
  if (state.isDirectory())
31294
- count += await copySqlSources(root, `${source}/${name}`, join15(destination, name));
31576
+ count += await copySqlSources(root, `${source}/${name}`, join16(destination, name));
31295
31577
  else if (state.isFile() && name.endsWith(".sql")) {
31296
- await writeFile5(join15(destination, name), await readFile5(file));
31578
+ await writeFile6(join16(destination, name), await readFile6(file));
31297
31579
  count++;
31298
31580
  }
31299
31581
  }
@@ -31307,8 +31589,8 @@ async function reverse(args, root, options) {
31307
31589
  if (!selectedSchemas.length || selectedSchemas.some((schema) => !/^[a-z_][a-z0-9_$]*$/i.test(schema))) {
31308
31590
  throw new Error("Select valid PostgreSQL schemas");
31309
31591
  }
31310
- await mkdir6(dirname11(out), { recursive: true });
31311
- const stage = await mkdtemp(join15(dirname11(out), ".reverse-"));
31592
+ await mkdir7(dirname11(out), { recursive: true });
31593
+ const stage = await mkdtemp(join16(dirname11(out), ".reverse-"));
31312
31594
  try {
31313
31595
  const snapshot = await withDatabase(args, options, async (executor, url) => {
31314
31596
  const snapshot = await reverseDatabase(executor, selectedSchemas);
@@ -31324,10 +31606,10 @@ async function reverse(args, root, options) {
31324
31606
  }, options.environment ?? process.env, options);
31325
31607
  return snapshot;
31326
31608
  });
31327
- const generated = await readdir6(join15(stage, "supabase/schemas"), { recursive: true });
31609
+ const generated = await readdir6(join16(stage, "supabase/schemas"), { recursive: true });
31328
31610
  if (!generated.some((file) => file.endsWith(".sql")))
31329
31611
  throw new Error("Official reverse did not produce declarative SQL");
31330
- await writeFile5(join15(stage, "catalog.json"), renderReverseSnapshot(snapshot));
31612
+ await writeFile6(join16(stage, "catalog.json"), renderReverseSnapshot(snapshot));
31331
31613
  await rename3(stage, out);
31332
31614
  return result({
31333
31615
  ok: true,
@@ -31352,14 +31634,14 @@ async function diff2(args, root, options) {
31352
31634
  const input = await migrations(root, args.dir ?? (await boundary(root))?.migrations ?? "supabase/migrations");
31353
31635
  if (overlaps(input.dir, out))
31354
31636
  throw new Error("Candidate output overlaps reviewed migration history");
31355
- await mkdir6(dirname11(out), { recursive: true });
31356
- const stage = await mkdtemp(join15(dirname11(out), ".diff-"));
31637
+ await mkdir7(dirname11(out), { recursive: true });
31638
+ const stage = await mkdtemp(join16(dirname11(out), ".diff-"));
31357
31639
  try {
31358
31640
  await initializeCandidate(stage, args.db_major_version);
31359
- if (!await copySqlSources(root, sourcePath, join15(stage, "supabase/schemas")))
31641
+ if (!await copySqlSources(root, sourcePath, join16(stage, "supabase/schemas")))
31360
31642
  throw new Error("No declarative SQL sources");
31361
31643
  for (const { file, text } of input.files)
31362
- await writeFile5(join15(stage, "supabase/migrations", file), text);
31644
+ await writeFile6(join16(stage, "supabase/migrations", file), text);
31363
31645
  await runOfficial(root, stage, {
31364
31646
  action: "db_schema_declarative_sync",
31365
31647
  apply: false,
@@ -31369,15 +31651,15 @@ async function diff2(args, root, options) {
31369
31651
  }, options.environment ?? process.env, options);
31370
31652
  const history = new Map(input.files.map((file) => [file.file, file.text]));
31371
31653
  for (const [file, text] of history) {
31372
- if (await readFile5(join15(stage, "supabase/migrations", file), "utf8") !== text) {
31654
+ if (await readFile6(join16(stage, "supabase/migrations", file), "utf8") !== text) {
31373
31655
  throw new Error("Official diff changed reviewed migration history");
31374
31656
  }
31375
31657
  }
31376
- const names = (await readdir6(join15(stage, "supabase/migrations"))).filter((file) => file.endsWith(".sql") && !history.has(file));
31377
- const candidates = join15(stage, "candidates");
31378
- await mkdir6(candidates);
31658
+ const names = (await readdir6(join16(stage, "supabase/migrations"))).filter((file) => file.endsWith(".sql") && !history.has(file));
31659
+ const candidates = join16(stage, "candidates");
31660
+ await mkdir7(candidates);
31379
31661
  for (const file of names)
31380
- await writeFile5(join15(candidates, file), await readFile5(join15(stage, "supabase/migrations", file)));
31662
+ await writeFile6(join16(candidates, file), await readFile6(join16(stage, "supabase/migrations", file)));
31381
31663
  await rename3(candidates, out);
31382
31664
  } finally {
31383
31665
  await rm2(stage, { force: true, recursive: true });
@@ -31401,7 +31683,7 @@ async function migrations(root, path) {
31401
31683
  throw new Error("No forward migration files");
31402
31684
  const files = [];
31403
31685
  for (const file of names) {
31404
- const text = await readFile5(await projectPath2(root, `${path}/${file}`), "utf8");
31686
+ const text = await readFile6(await projectPath2(root, `${path}/${file}`), "utf8");
31405
31687
  files.push({ file, text, sha256: hash4(text) });
31406
31688
  }
31407
31689
  return { dir, files };
@@ -31415,10 +31697,10 @@ async function migrationAction(args, root, options) {
31415
31697
  throw new Error("Select a Management API and project ref");
31416
31698
  const path = args.dir ?? (await boundary(root))?.migrations ?? "supabase/migrations";
31417
31699
  const input = await migrations(root, path);
31418
- const stage = await mkdtemp(join15(tmpdir2(), "supacloud-reviewed-migrations-"));
31700
+ const stage = await mkdtemp(join16(tmpdir2(), "supacloud-reviewed-migrations-"));
31419
31701
  try {
31420
31702
  for (const { file, text } of input.files)
31421
- await writeFile5(join15(stage, file), text);
31703
+ await writeFile6(join16(stage, file), text);
31422
31704
  const preview = await run({ action: "push_migrations", ref, dir: stage, dry_run: true, strict: true });
31423
31705
  const dryRun = {
31424
31706
  isError: preview.isError === true,
@@ -31445,7 +31727,7 @@ async function migrationAction(args, root, options) {
31445
31727
  }
31446
31728
  }
31447
31729
  async function runDbWorkflow(args, projectRoot, options = {}) {
31448
- const root = resolve20(projectRoot);
31730
+ const root = resolve21(projectRoot);
31449
31731
  if ((await lstat4(root)).isSymbolicLink())
31450
31732
  throw new Error("Workflow root must not be a symlink");
31451
31733
  switch (args.action) {
@@ -31488,7 +31770,7 @@ async function runDbWorkflow(args, projectRoot, options = {}) {
31488
31770
  }
31489
31771
 
31490
31772
  // src/shared/tools/db-governance-tools.ts
31491
- function textResult2(text, isError = false) {
31773
+ function textResult3(text, isError = false) {
31492
31774
  return { isError, content: [{ type: "text", text }] };
31493
31775
  }
31494
31776
  function normalizeModule(candidate, sourcePath) {
@@ -31506,8 +31788,8 @@ function normalizeModule(candidate, sourcePath) {
31506
31788
  };
31507
31789
  }
31508
31790
  async function loadDatabaseModules(root, moduleFile) {
31509
- const filePath = moduleFile ? resolve21(root, moduleFile) : join16(root, "db", "modules.ts");
31510
- if (!existsSync13(filePath)) {
31791
+ const filePath = moduleFile ? resolve22(root, moduleFile) : join17(root, "db", "modules.ts");
31792
+ if (!existsSync14(filePath)) {
31511
31793
  throw new Error(moduleFile ? `Module file not found: ${filePath}` : `Module file not found: ${filePath}(用 --module_file 指定一个导出 defineDatabaseModule(...) 的文件)`);
31512
31794
  }
31513
31795
  let imported;
@@ -31596,7 +31878,7 @@ function buildDatabaseAiContext(modules, root, moduleName, target) {
31596
31878
  const objects = target ? allObjects.filter((object) => objectMatchesTarget(object, target)) : allObjects;
31597
31879
  if (target && objects.length === 0)
31598
31880
  throw new Error(`未找到数据库对象: ${target}`);
31599
- const sqlFirst = !existsSync13(join16(root, "zenstack/schema.zmodel")) && existsSync13(join16(root, "supabase/schemas"));
31881
+ const sqlFirst = !existsSync14(join17(root, "zenstack/schema.zmodel")) && existsSync14(join17(root, "supabase/schemas"));
31600
31882
  return {
31601
31883
  version: 1,
31602
31884
  scope: "database-ai-context",
@@ -31643,7 +31925,7 @@ async function collectLintIssues(args, root) {
31643
31925
  const issues = [];
31644
31926
  for (const module of selected) {
31645
31927
  const readSqlFile = async (path) => {
31646
- const absolute = resolve21(root, path);
31928
+ const absolute = resolve22(root, path);
31647
31929
  try {
31648
31930
  return await Bun.file(absolute).text();
31649
31931
  } catch (error) {
@@ -31661,13 +31943,13 @@ async function runLint(args, root) {
31661
31943
  const header = `linted ${selected.length} module(s): ${selected.map((module) => module.name).join(", ")}`;
31662
31944
  const body = issues.length > 0 ? issues.map(formatLintIssue).join(`
31663
31945
  `) : "no issues";
31664
- return textResult2(`${header}
31946
+ return textResult3(`${header}
31665
31947
  ${body}`, hasError);
31666
31948
  }
31667
31949
  async function runCheck2(args, root, environment, spawn, liteBinary, options) {
31668
31950
  const checks = [];
31669
31951
  let ok = true;
31670
- if (existsSync13(join16(root, "database.sources.json"))) {
31952
+ if (existsSync14(join17(root, "database.sources.json"))) {
31671
31953
  try {
31672
31954
  const source = await databaseSources(root, "check");
31673
31955
  checks.push({ name: "source-contract", ok: source.ok, findings: source.findings });
@@ -31680,8 +31962,8 @@ async function runCheck2(args, root, environment, spawn, liteBinary, options) {
31680
31962
  } else {
31681
31963
  checks.push({ name: "source-contract", skipped: true, reason: "database.sources.json not found" });
31682
31964
  }
31683
- const modulePath = args.module_file ? resolve21(root, args.module_file) : join16(root, "db/modules.ts");
31684
- if (existsSync13(modulePath)) {
31965
+ const modulePath = args.module_file ? resolve22(root, args.module_file) : join17(root, "db/modules.ts");
31966
+ if (existsSync14(modulePath)) {
31685
31967
  try {
31686
31968
  const { selected, issues } = await collectLintIssues(args, root);
31687
31969
  const lintOk = !issues.some((issue) => issue.severity === "error");
@@ -31719,7 +32001,7 @@ async function runCheck2(args, root, environment, spawn, liteBinary, options) {
31719
32001
  } else {
31720
32002
  checks.push({ name: "catalog", skipped: true, reason: "no --database_url, DATABASE_URL, --lite or --remote" });
31721
32003
  }
31722
- return textResult2(JSON.stringify({
32004
+ return textResult3(JSON.stringify({
31723
32005
  version: 1,
31724
32006
  scope: "database-check",
31725
32007
  root,
@@ -31734,11 +32016,11 @@ async function runExplain2(args, root) {
31734
32016
  const modules = await loadDatabaseModules(root, args.module_file);
31735
32017
  const manifest = buildDatabaseManifest(modules);
31736
32018
  const text = explainObject(manifest, target);
31737
- return textResult2(text, text.startsWith("未找到对象"));
32019
+ return textResult3(text, text.startsWith("未找到对象"));
31738
32020
  }
31739
32021
  async function runContext2(args, root) {
31740
32022
  const modules = await loadDatabaseModules(root, args.module_file);
31741
- return textResult2(JSON.stringify(buildDatabaseAiContext(modules, root, args.module, args.target), null, 2));
32023
+ return textResult3(JSON.stringify(buildDatabaseAiContext(modules, root, args.module, args.target), null, 2));
31742
32024
  }
31743
32025
  var defaultLiteSpawn = async (command, cwd) => {
31744
32026
  const proc = Bun.spawn({ cmd: command, cwd, stdout: "pipe", stderr: "pipe" });
@@ -31750,18 +32032,18 @@ var defaultLiteSpawn = async (command, cwd) => {
31750
32032
  return { exitCode, stdout, stderr };
31751
32033
  };
31752
32034
  async function runModuleCheckLite(args, root, spawn, liteBinary) {
31753
- const projectDir = resolve21(args.project_dir?.trim() || root);
32035
+ const projectDir = resolve22(args.project_dir?.trim() || root);
31754
32036
  const binary = liteBinary === undefined ? Bun.which("supacloud-lite") : liteBinary;
31755
32037
  if (!binary) {
31756
32038
  throw new Error("db module_check --lite 需要本机可用的 supacloud-lite(npm i -g @supacloud/lite,或加入 PATH)");
31757
32039
  }
31758
32040
  const command = [binary, "db", "check", "--project-dir", projectDir];
31759
32041
  if (args.module_file?.trim())
31760
- command.push("--module-file", resolve21(root, args.module_file.trim()));
32042
+ command.push("--module-file", resolve22(root, args.module_file.trim()));
31761
32043
  const result = await spawn(command, projectDir);
31762
32044
  const output = [result.stdout.trim(), result.stderr.trim()].filter(Boolean).join(`
31763
32045
  `);
31764
- return textResult2(output || "lite db check 无输出", result.exitCode !== 0);
32046
+ return textResult3(output || "lite db check 无输出", result.exitCode !== 0);
31765
32047
  }
31766
32048
  function remoteModuleManifest(modules) {
31767
32049
  return modules.map((module) => ({
@@ -31843,7 +32125,7 @@ async function runModuleCheckAction(args, root, environment, spawn, liteBinary,
31843
32125
  reports.push(await runModuleCheck(module, executor, schemas));
31844
32126
  }
31845
32127
  const hasError = reports.some((report) => !report.ok);
31846
- return textResult2(reports.map(formatReconcileReport).join(`
32128
+ return textResult3(reports.map(formatReconcileReport).join(`
31847
32129
  `), hasError);
31848
32130
  } catch (error) {
31849
32131
  const message = error instanceof Error ? error.message : String(error);
@@ -31877,7 +32159,7 @@ function registerDbGovernanceTools(server, options = {}) {
31877
32159
  migration_role: optional(String2(), "[role_sql] Privileged migration role"),
31878
32160
  database: optional(String2(), "[role_sql] PostgreSQL database name")
31879
32161
  }, async (request) => {
31880
- const root = resolve21(request.root || fallbackRoot);
32162
+ const root = resolve22(request.root || fallbackRoot);
31881
32163
  switch (request.action) {
31882
32164
  case "context":
31883
32165
  return runContext2(request, root);
@@ -31910,7 +32192,7 @@ function registerDbGovernanceTools(server, options = {}) {
31910
32192
  runDatabase: options.runDatabase
31911
32193
  });
31912
32194
  default:
31913
- return textResult2(`Unknown db action: ${String(request.action)}`, true);
32195
+ return textResult3(`Unknown db action: ${String(request.action)}`, true);
31914
32196
  }
31915
32197
  });
31916
32198
  }
@@ -31918,7 +32200,7 @@ function registerDbGovernanceTools(server, options = {}) {
31918
32200
  // src/shared/tools/scheduled-function-tools.ts
31919
32201
  import { randomUUID as randomUUID3 } from "node:crypto";
31920
32202
  import { readFileSync as readFileSync10, statSync as statSync9 } from "node:fs";
31921
- import { resolve as resolve22 } from "node:path";
32203
+ import { resolve as resolve23 } from "node:path";
31922
32204
  import { isDeepStrictEqual } from "node:util";
31923
32205
  var HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/;
31924
32206
  var ENVIRONMENT_NAME_PATTERN3 = /^[A-Za-z_][A-Za-z0-9_]{0,255}$/;
@@ -32002,7 +32284,7 @@ function validScheduledFunctionCron(expression) {
32002
32284
  function readScheduleBodyFile(bodyPathInput) {
32003
32285
  if (!bodyPathInput.trim())
32004
32286
  throw new Error("'body_file' must be a path");
32005
- const bodyPath = resolve22(bodyPathInput);
32287
+ const bodyPath = resolve23(bodyPathInput);
32006
32288
  const bodyStat = statSync9(bodyPath);
32007
32289
  if (!bodyStat.isFile() || bodyStat.size > MAX_BODY_FILE_BYTES) {
32008
32290
  throw new Error("Scheduled Function body file must be a regular file no larger than 1 MiB");
@@ -32386,8 +32668,8 @@ var MUTATION_TOOL_SCHEMA = {
32386
32668
 
32387
32669
  // src/shared/tools/release-tools.ts
32388
32670
  import { createHash as createHash10 } from "node:crypto";
32389
- import { existsSync as existsSync14, mkdirSync as mkdirSync5, readdirSync as readdirSync5, readFileSync as readFileSync11, writeFileSync as writeFileSync4 } from "node:fs";
32390
- import { dirname as dirname12, join as join17, relative as relative9, resolve as resolve23 } from "node:path";
32671
+ import { existsSync as existsSync15, mkdirSync as mkdirSync5, readdirSync as readdirSync5, readFileSync as readFileSync11, writeFileSync as writeFileSync4 } from "node:fs";
32672
+ import { dirname as dirname12, join as join18, relative as relative9, resolve as resolve24 } from "node:path";
32391
32673
  var SAFE_PROJECT_REF = /^[A-Za-z0-9_-]{1,64}$/;
32392
32674
  var SAFE_ENVIRONMENT_ID = /^[A-Za-z0-9_-]{1,64}$/;
32393
32675
  var BACKUP_ID = /^logical-full_[A-Za-z0-9_-]{1,64}_[a-f0-9]{32}$/;
@@ -32709,15 +32991,15 @@ function collectScopeFiles(cwd, file, files, dir, task) {
32709
32991
  const results = [];
32710
32992
  const resolvePathWithFallbacks = (filePath) => {
32711
32993
  const trimmed = filePath.trim();
32712
- const resolved = resolve23(cwd, trimmed);
32713
- if (existsSync14(resolved))
32994
+ const resolved = resolve24(cwd, trimmed);
32995
+ if (existsSync15(resolved))
32714
32996
  return resolved;
32715
32997
  const candidates = [
32716
- resolve23(cwd, "supacloud/fa/release-scopes", trimmed),
32717
- resolve23(cwd, "release-scopes", trimmed),
32718
- resolve23(cwd, "scopes", trimmed)
32998
+ resolve24(cwd, "supacloud/fa/release-scopes", trimmed),
32999
+ resolve24(cwd, "release-scopes", trimmed),
33000
+ resolve24(cwd, "scopes", trimmed)
32719
33001
  ];
32720
- const found = candidates.find(existsSync14);
33002
+ const found = candidates.find(existsSync15);
32721
33003
  if (found)
32722
33004
  return found;
32723
33005
  throw new Error(`Scope file not found: ${filePath}`);
@@ -32738,18 +33020,18 @@ function collectScopeFiles(cwd, file, files, dir, task) {
32738
33020
  if (!taskFilter && (!dir || typeof dir !== "string" || !dir.trim())) {
32739
33021
  throw new Error("At least one of --file, --files, or --task is required for scope_rebind");
32740
33022
  }
32741
- const candidates = typeof dir === "string" && dir.trim() ? [resolve23(cwd, dir.trim())] : [
32742
- resolve23(cwd, "supacloud/fa/release-scopes"),
32743
- resolve23(cwd, "release-scopes"),
32744
- resolve23(cwd, "scopes")
33023
+ const candidates = typeof dir === "string" && dir.trim() ? [resolve24(cwd, dir.trim())] : [
33024
+ resolve24(cwd, "supacloud/fa/release-scopes"),
33025
+ resolve24(cwd, "release-scopes"),
33026
+ resolve24(cwd, "scopes")
32745
33027
  ];
32746
33028
  for (const directory of candidates) {
32747
- if (existsSync14(directory)) {
33029
+ if (existsSync15(directory)) {
32748
33030
  try {
32749
33031
  const entries = readdirSync5(directory, { withFileTypes: true });
32750
33032
  for (const entry of entries) {
32751
33033
  if (entry.isFile() && entry.name.endsWith(".json")) {
32752
- const fullPath = join17(directory, entry.name);
33034
+ const fullPath = join18(directory, entry.name);
32753
33035
  if (!taskFilter) {
32754
33036
  results.push(fullPath);
32755
33037
  } else if (entry.name.toLowerCase().includes(taskFilter)) {
@@ -32775,7 +33057,7 @@ function collectScopeFiles(cwd, file, files, dir, task) {
32775
33057
  return [...new Set(results)];
32776
33058
  }
32777
33059
  function handleScopeRebind(args) {
32778
- const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve23(args.cwd.trim()) : process.cwd();
33060
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve24(args.cwd.trim()) : process.cwd();
32779
33061
  const targetBaseCommit = resolveGitBaseCommit(cwd, args.base_commit);
32780
33062
  const requestedEnvironmentId = requestedScopeEnvironment(args, "scope_rebind");
32781
33063
  const scopeFiles = collectScopeFiles(cwd, args.file, args.files, args.dir, args.task);
@@ -32833,20 +33115,20 @@ function handleScopeRebind(args) {
32833
33115
  });
32834
33116
  }
32835
33117
  function handleScopeInspect(args) {
32836
- const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve23(args.cwd.trim()) : process.cwd();
33118
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve24(args.cwd.trim()) : process.cwd();
32837
33119
  const requestedEnvironmentId = requestedScopeEnvironment(args, "scope_inspect");
32838
33120
  if (typeof args.file !== "string" || !args.file.trim()) {
32839
33121
  throw new Error("'file' is required for scope_inspect");
32840
33122
  }
32841
33123
  const trimmed = args.file.trim();
32842
- let filePath = resolve23(cwd, trimmed);
32843
- if (!existsSync14(filePath)) {
33124
+ let filePath = resolve24(cwd, trimmed);
33125
+ if (!existsSync15(filePath)) {
32844
33126
  const candidates = [
32845
- resolve23(cwd, "supacloud/fa/release-scopes", trimmed),
32846
- resolve23(cwd, "release-scopes", trimmed),
32847
- resolve23(cwd, "scopes", trimmed)
33127
+ resolve24(cwd, "supacloud/fa/release-scopes", trimmed),
33128
+ resolve24(cwd, "release-scopes", trimmed),
33129
+ resolve24(cwd, "scopes", trimmed)
32848
33130
  ];
32849
- const found = candidates.find(existsSync14);
33131
+ const found = candidates.find(existsSync15);
32850
33132
  if (found)
32851
33133
  filePath = found;
32852
33134
  else
@@ -32906,15 +33188,15 @@ function releaseComponentView(component) {
32906
33188
  return { kind: component.kind, artifact_sha256: component.artifactSha256 };
32907
33189
  }
32908
33190
  function handleContractPlan(args, fallbackRef) {
32909
- const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve23(args.cwd.trim()) : process.cwd();
33191
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve24(args.cwd.trim()) : process.cwd();
32910
33192
  const requestedRef = typeof args.ref === "string" && args.ref.trim() || fallbackRef;
32911
33193
  if (!requestedRef || !validProjectRef(requestedRef)) {
32912
33194
  throw new Error("'ref' is required for contract_plan and must identify one project");
32913
33195
  }
32914
33196
  const requestedEnvironmentId = requestedScopeEnvironment(args, "contract_plan");
32915
33197
  const file = typeof args.file === "string" && args.file.trim() ? args.file.trim() : "supacloud.release.json";
32916
- const filePath = resolve23(cwd, file);
32917
- if (!existsSync14(filePath)) {
33198
+ const filePath = resolve24(cwd, file);
33199
+ if (!existsSync15(filePath)) {
32918
33200
  throw new Error(`Release contract not found: ${file}`);
32919
33201
  }
32920
33202
  let parsedValue;
@@ -32976,7 +33258,7 @@ function parseCommaList(value) {
32976
33258
  return [];
32977
33259
  }
32978
33260
  function handleScopeCreate(args, fallbackRef) {
32979
- const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve23(args.cwd.trim()) : process.cwd();
33261
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve24(args.cwd.trim()) : process.cwd();
32980
33262
  if (typeof args.file !== "string" || !args.file.trim()) {
32981
33263
  throw new Error("'file' is required for scope_create");
32982
33264
  }
@@ -32992,7 +33274,7 @@ function handleScopeCreate(args, fallbackRef) {
32992
33274
  throw new Error("'ref' is invalid for release controls");
32993
33275
  }
32994
33276
  const targetBaseCommit = resolveGitBaseCommit(cwd, args.base_commit);
32995
- const filePath = resolve23(cwd, args.file.trim());
33277
+ const filePath = resolve24(cwd, args.file.trim());
32996
33278
  mkdirSync5(dirname12(filePath), { recursive: true });
32997
33279
  const scope = {
32998
33280
  baseCommit: targetBaseCommit,
@@ -33240,11 +33522,11 @@ function registerReleaseTools(server, http, options = {}) {
33240
33522
  }
33241
33523
 
33242
33524
  // src/shared/tools/deploy-tools.ts
33243
- import { access, lstat as lstat5, mkdtemp as mkdtemp2, opendir, readFile as readFile7, rm as rm3, writeFile as writeFile7 } from "node:fs/promises";
33525
+ import { access, lstat as lstat5, mkdtemp as mkdtemp2, opendir, readFile as readFile8, rm as rm3, writeFile as writeFile8 } from "node:fs/promises";
33244
33526
  import { spawn as spawn2 } from "node:child_process";
33245
33527
  import { createHash as createHash11 } from "node:crypto";
33246
33528
  import { tmpdir as tmpdir3 } from "node:os";
33247
- import { basename as basename8, dirname as dirname14, join as join19, relative as relative10, resolve as resolve26, sep as sep5 } from "node:path";
33529
+ import { basename as basename8, dirname as dirname14, join as join20, relative as relative10, resolve as resolve27, sep as sep5 } from "node:path";
33248
33530
 
33249
33531
  // src/shared/tools/project-deployment.ts
33250
33532
  async function requireProjectDeploymentProtocol(http, projectRef, environmentId) {
@@ -33320,14 +33602,14 @@ async function readProjectDeploymentStatus(http, projectRef, environmentId, depl
33320
33602
  }
33321
33603
 
33322
33604
  // src/shared/tools/developer-experience-tools.ts
33323
- import { existsSync as existsSync16 } from "node:fs";
33324
- import { mkdir as mkdir7, readdir as readdir7, readFile as readFile6, writeFile as writeFile6 } from "node:fs/promises";
33325
- import { dirname as dirname13, join as join18, resolve as resolve25 } from "node:path";
33605
+ import { existsSync as existsSync17 } from "node:fs";
33606
+ import { mkdir as mkdir8, readdir as readdir7, readFile as readFile7, writeFile as writeFile7 } from "node:fs/promises";
33607
+ import { dirname as dirname13, join as join19, resolve as resolve26 } from "node:path";
33326
33608
 
33327
33609
  // src/shared/context.ts
33328
- import { existsSync as existsSync15, readFileSync as readFileSync12 } from "node:fs";
33610
+ import { existsSync as existsSync16, readFileSync as readFileSync12 } from "node:fs";
33329
33611
  import { homedir as homedir3 } from "node:os";
33330
- import { resolve as resolve24 } from "node:path";
33612
+ import { resolve as resolve25 } from "node:path";
33331
33613
  var CORE_CONTEXT_KEYS2 = [
33332
33614
  "SUPABASE_URL",
33333
33615
  "SUPABASE_SERVICE_ROLE_KEY",
@@ -33359,8 +33641,44 @@ function parseEnvFile2(contents) {
33359
33641
  }
33360
33642
  return values;
33361
33643
  }
33644
+ function projectConfigValues2(cwd, environment) {
33645
+ const path = resolve25(cwd, "supacloud.json");
33646
+ if (!existsSync16(path))
33647
+ return {};
33648
+ try {
33649
+ const parsed = JSON.parse(readFileSync12(path, "utf8"));
33650
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
33651
+ return {};
33652
+ const root = parsed;
33653
+ const context = root.context;
33654
+ if (!context || typeof context !== "object" || Array.isArray(context))
33655
+ return {};
33656
+ const contextRecord = context;
33657
+ const environments = contextRecord.environments;
33658
+ if (!environments || typeof environments !== "object" || Array.isArray(environments))
33659
+ return {};
33660
+ const selected = environments[environment];
33661
+ if (!selected || typeof selected !== "object" || Array.isArray(selected))
33662
+ return {};
33663
+ const values = selected;
33664
+ const output = {};
33665
+ const mappings = {
33666
+ api_url: "SUPACLOUD_API_URL",
33667
+ project_ref: "SUPACLOUD_PROJECT_REF",
33668
+ application_id: "SUPACLOUD_APPLICATION_ID",
33669
+ environment_id: "SUPACLOUD_APPLICATION_ENVIRONMENT_ID"
33670
+ };
33671
+ for (const [source, target] of Object.entries(mappings)) {
33672
+ if (typeof values[source] === "string" && values[source].trim())
33673
+ output[target] = values[source].trim();
33674
+ }
33675
+ return output;
33676
+ } catch {
33677
+ return {};
33678
+ }
33679
+ }
33362
33680
  function readEnvFile2(path, required) {
33363
- if (!existsSync15(path)) {
33681
+ if (!existsSync16(path)) {
33364
33682
  if (required)
33365
33683
  throw new Error(`SupaCloud environment file not found: ${path}`);
33366
33684
  return {};
@@ -33437,7 +33755,7 @@ function parseInsecureTls2(values) {
33437
33755
  }
33438
33756
  function namedEnvironmentSource2(cwd, selector) {
33439
33757
  const environment = normalizeEnvironmentName(selector);
33440
- const path = resolve24(cwd, `.env.supacloud.${selector}`);
33758
+ const path = resolve25(cwd, `.env.supacloud.${selector}`);
33441
33759
  const values = readEnvFile2(path, true);
33442
33760
  if (values.SUPACLOUD_ENV && normalizeEnvironmentName(values.SUPACLOUD_ENV) !== environment) {
33443
33761
  throw new Error(`SUPACLOUD_ENV in ${path} does not match selector ${selector}`);
@@ -33445,7 +33763,7 @@ function namedEnvironmentSource2(cwd, selector) {
33445
33763
  return { values, kind: "named_env_file", path, environment };
33446
33764
  }
33447
33765
  function explicitEnvironmentSource2(cwd, envFile) {
33448
- const path = resolve24(cwd, envFile);
33766
+ const path = resolve25(cwd, envFile);
33449
33767
  const values = readEnvFile2(path, true);
33450
33768
  if (!values.SUPACLOUD_ENV)
33451
33769
  throw new Error(`SUPACLOUD_ENV is required in ${path}`);
@@ -33459,25 +33777,47 @@ function explicitEnvironmentSource2(cwd, envFile) {
33459
33777
  function contextSource2(env, cwd, selection) {
33460
33778
  if (selection.environmentName && selection.envFile)
33461
33779
  throw new Error("Environment selectors are mutually exclusive");
33462
- if (selection.environmentName)
33463
- return namedEnvironmentSource2(cwd, selection.environmentName);
33464
- if (selection.envFile)
33465
- return explicitEnvironmentSource2(cwd, selection.envFile);
33780
+ if (selection.environmentName) {
33781
+ const source = namedEnvironmentSource2(cwd, selection.environmentName);
33782
+ return {
33783
+ ...source,
33784
+ values: { ...projectConfigValues2(cwd, source.environment), ...source.values }
33785
+ };
33786
+ }
33787
+ if (selection.envFile) {
33788
+ const source = explicitEnvironmentSource2(cwd, selection.envFile);
33789
+ return {
33790
+ ...source,
33791
+ values: { ...projectConfigValues2(cwd, source.environment), ...source.values }
33792
+ };
33793
+ }
33466
33794
  if (env.SUPACLOUD_ENV) {
33467
33795
  const environment = normalizeEnvironmentName(env.SUPACLOUD_ENV);
33468
- const values = processValues2(env);
33796
+ const values = { ...projectConfigValues2(cwd, environment), ...processValues2(env) };
33469
33797
  if (completeProjectContext2(values)) {
33470
33798
  return { values, kind: "process_env", path: null, environment };
33471
33799
  }
33472
- return namedEnvironmentSource2(cwd, env.SUPACLOUD_ENV);
33800
+ const source = namedEnvironmentSource2(cwd, env.SUPACLOUD_ENV);
33801
+ return {
33802
+ ...source,
33803
+ values: { ...projectConfigValues2(cwd, source.environment), ...source.values }
33804
+ };
33473
33805
  }
33474
33806
  if (hasProcessContext2(env)) {
33475
33807
  return { values: processValues2(env), kind: "process_env", path: null, environment: "" };
33476
33808
  }
33477
- const path = resolve24(cwd, ".env");
33809
+ const path = resolve25(cwd, ".env");
33478
33810
  const values = readEnvFile2(path, false);
33479
33811
  const environment = values.SUPACLOUD_ENV ? normalizeEnvironmentName(values.SUPACLOUD_ENV) : "";
33480
- return { values, kind: Object.keys(values).length ? "legacy_dotenv" : "none", path: existsSync15(path) ? path : null, environment };
33812
+ if (environment) {
33813
+ return {
33814
+ values: { ...projectConfigValues2(cwd, environment), ...values },
33815
+ kind: "legacy_dotenv",
33816
+ path: existsSync16(path) ? path : null,
33817
+ environment
33818
+ };
33819
+ }
33820
+ return { values, kind: Object.keys(values).length ? "legacy_dotenv" : "none", path: existsSync16(path) ? path : null, environment };
33481
33821
  }
33482
33822
  function resolveSupaCloudContext2(env = process.env, cwd = process.cwd(), selection = {}) {
33483
33823
  const source = contextSource2(env, cwd, selection);
@@ -33489,7 +33829,7 @@ function resolveSupaCloudContext2(env = process.env, cwd = process.cwd(), select
33489
33829
  host,
33490
33830
  sshUser: env.SUPACLOUD_SSH_USER ?? "root",
33491
33831
  sshPort: parseInt(env.SUPACLOUD_SSH_PORT ?? "22", 10),
33492
- sshKey: env.SUPACLOUD_SSH_KEY ?? resolve24(homedir3(), ".ssh", "id_rsa"),
33832
+ sshKey: env.SUPACLOUD_SSH_KEY ?? resolve25(homedir3(), ".ssh", "id_rsa"),
33493
33833
  sshPass: env.SUPACLOUD_SSH_PASS ?? "",
33494
33834
  apiUrl: core.apiUrl,
33495
33835
  apiToken: core.apiToken,
@@ -33518,7 +33858,7 @@ var initToolSchema = {
33518
33858
  format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
33519
33859
  };
33520
33860
  var environmentToolSchema = {
33521
- action: withDescription(stringEnum2(["list", "check"]), "Environment profile inspection action"),
33861
+ ...environmentSyncSchema,
33522
33862
  root: optional(String2(), "Project directory containing .env.supacloud.* files"),
33523
33863
  format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
33524
33864
  };
@@ -33540,13 +33880,13 @@ var PRODUCTION_PROFILE = [
33540
33880
  ""
33541
33881
  ].join(`
33542
33882
  `);
33543
- function textResult3(text, isError = false) {
33883
+ function textResult4(text, isError = false) {
33544
33884
  return { isError, content: [{ type: "text", text }] };
33545
33885
  }
33546
- function jsonResult(value, isError = false) {
33547
- return textResult3(JSON.stringify(value, null, 2), isError);
33886
+ function jsonResult2(value, isError = false) {
33887
+ return textResult4(JSON.stringify(value, null, 2), isError);
33548
33888
  }
33549
- function record5(value) {
33889
+ function record6(value) {
33550
33890
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
33551
33891
  }
33552
33892
  function packageDependencies(manifest) {
@@ -33564,17 +33904,17 @@ function outputDirectoryFor(manifest) {
33564
33904
  return "dist";
33565
33905
  }
33566
33906
  async function readPackageManifest(root) {
33567
- const path = join18(root, "package.json");
33568
- if (!existsSync16(path))
33907
+ const path = join19(root, "package.json");
33908
+ if (!existsSync17(path))
33569
33909
  return {};
33570
33910
  try {
33571
- const parsed = JSON.parse(await readFile6(path, "utf8"));
33572
- const value = record5(parsed);
33911
+ const parsed = JSON.parse(await readFile7(path, "utf8"));
33912
+ const value = record6(parsed);
33573
33913
  if (!value)
33574
33914
  throw new Error("package.json must contain an object");
33575
- const scripts = record5(value.scripts);
33576
- const dependencies = record5(value.dependencies);
33577
- const devDependencies = record5(value.devDependencies);
33915
+ const scripts = record6(value.scripts);
33916
+ const dependencies = record6(value.dependencies);
33917
+ const devDependencies = record6(value.devDependencies);
33578
33918
  return {
33579
33919
  scripts: scripts ?? undefined,
33580
33920
  dependencies: dependencies ?? undefined,
@@ -33586,7 +33926,7 @@ async function readPackageManifest(root) {
33586
33926
  }
33587
33927
  async function writeNewFile(path, content) {
33588
33928
  try {
33589
- await writeFile6(path, content, { encoding: "utf8", flag: "wx", mode: 384 });
33929
+ await writeFile7(path, content, { encoding: "utf8", flag: "wx", mode: 384 });
33590
33930
  return true;
33591
33931
  } catch (error) {
33592
33932
  if (error instanceof Error && "code" in error && error.code === "EEXIST")
@@ -33595,8 +33935,8 @@ async function writeNewFile(path, content) {
33595
33935
  }
33596
33936
  }
33597
33937
  async function ensureGitignore(root) {
33598
- const path = join18(root, ".gitignore");
33599
- const existing = existsSync16(path) ? await readFile6(path, "utf8") : "";
33938
+ const path = join19(root, ".gitignore");
33939
+ const existing = existsSync17(path) ? await readFile7(path, "utf8") : "";
33600
33940
  const required = [".env.supacloud.*", "!.env.supacloud.*.example"];
33601
33941
  const missing = required.filter((entry) => !existing.split(/\r?\n/).includes(entry));
33602
33942
  if (missing.length === 0)
@@ -33604,16 +33944,16 @@ async function ensureGitignore(root) {
33604
33944
  const prefix = existing.length > 0 && !existing.endsWith(`
33605
33945
  `) ? `${existing}
33606
33946
  ` : existing;
33607
- await writeFile6(path, `${prefix}${missing.join(`
33947
+ await writeFile7(path, `${prefix}${missing.join(`
33608
33948
  `)}
33609
33949
  `, "utf8");
33610
33950
  return true;
33611
33951
  }
33612
33952
  async function initializeProject(request, options = {}) {
33613
- const root = resolve25(request.root || options.cwd || process.cwd());
33614
- await mkdir7(root, { recursive: true });
33615
- const configPath = join18(root, "supacloud.json");
33616
- if (existsSync16(configPath)) {
33953
+ const root = resolve26(request.root || options.cwd || process.cwd());
33954
+ await mkdir8(root, { recursive: true });
33955
+ const configPath = join19(root, "supacloud.json");
33956
+ if (existsSync17(configPath)) {
33617
33957
  throw new Error(`supacloud.json already exists in ${root}; init never overwrites project configuration`);
33618
33958
  }
33619
33959
  const manifest = await readPackageManifest(root);
@@ -33627,7 +33967,7 @@ async function initializeProject(request, options = {}) {
33627
33967
  };
33628
33968
  const created = [];
33629
33969
  try {
33630
- await writeFile6(configPath, `${JSON.stringify(config, null, 2)}
33970
+ await writeFile7(configPath, `${JSON.stringify(config, null, 2)}
33631
33971
  `, {
33632
33972
  encoding: "utf8",
33633
33973
  flag: "wx",
@@ -33640,10 +33980,10 @@ async function initializeProject(request, options = {}) {
33640
33980
  throw error;
33641
33981
  }
33642
33982
  created.push("supacloud.json");
33643
- if (await writeNewFile(join18(root, ".env.supacloud.test.example"), TEST_PROFILE)) {
33983
+ if (await writeNewFile(join19(root, ".env.supacloud.test.example"), TEST_PROFILE)) {
33644
33984
  created.push(".env.supacloud.test.example");
33645
33985
  }
33646
- if (await writeNewFile(join18(root, ".env.supacloud.production.example"), PRODUCTION_PROFILE)) {
33986
+ if (await writeNewFile(join19(root, ".env.supacloud.production.example"), PRODUCTION_PROFILE)) {
33647
33987
  created.push(".env.supacloud.production.example");
33648
33988
  }
33649
33989
  if (await ensureGitignore(root))
@@ -33654,7 +33994,7 @@ async function initializeProject(request, options = {}) {
33654
33994
  root,
33655
33995
  created,
33656
33996
  detected: {
33657
- package_json: existsSync16(join18(root, "package.json")),
33997
+ package_json: existsSync17(join19(root, "package.json")),
33658
33998
  build_script: hasBuildScript,
33659
33999
  output_directory: outputDirectory
33660
34000
  },
@@ -33666,8 +34006,8 @@ async function initializeProject(request, options = {}) {
33666
34006
  ]
33667
34007
  };
33668
34008
  if (request.format === "json")
33669
- return jsonResult(result);
33670
- return textResult3([
34009
+ return jsonResult2(result);
34010
+ return textResult4([
33671
34011
  `Initialized SupaCloud deployment in ${root}.`,
33672
34012
  `Created: ${created.join(", ")}.`,
33673
34013
  hasBuildScript ? `Detected package.json build script; deploy output defaults to ${outputDirectory}.` : "No package.json build script detected; add one before deploying.",
@@ -33699,7 +34039,7 @@ var deployToolSchema = {
33699
34039
  status: optional(String2({ format: "uuid" }), "Read a backend deployment status without publishing"),
33700
34040
  format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
33701
34041
  };
33702
- function record6(candidate) {
34042
+ function record7(candidate) {
33703
34043
  return candidate && typeof candidate === "object" && !Array.isArray(candidate) ? candidate : null;
33704
34044
  }
33705
34045
  function requiredString(candidate, field) {
@@ -33709,7 +34049,7 @@ function requiredString(candidate, field) {
33709
34049
  return candidate.trim();
33710
34050
  }
33711
34051
  function frontendDeployment(candidate) {
33712
- const value = record6(candidate);
34052
+ const value = record7(candidate);
33713
34053
  if (!value)
33714
34054
  throw new Error("Invalid frontend deployment response");
33715
34055
  return {
@@ -33723,7 +34063,7 @@ function frontendDeployment(candidate) {
33723
34063
  }
33724
34064
  async function readJson(path) {
33725
34065
  try {
33726
- return JSON.parse(await readFile7(path, "utf8"));
34066
+ return JSON.parse(await readFile8(path, "utf8"));
33727
34067
  } catch (error) {
33728
34068
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
33729
34069
  return null;
@@ -33731,15 +34071,15 @@ async function readJson(path) {
33731
34071
  }
33732
34072
  }
33733
34073
  async function findDeployConfigRoot(startDirectory, environmentName) {
33734
- let directory = resolve26(startDirectory);
34074
+ let directory = resolve27(startDirectory);
33735
34075
  while (true) {
33736
34076
  const environmentFile = environmentName ? `.env.supacloud.${environmentName}` : null;
33737
- if (await pathExists(join19(directory, "supacloud.json")) || await pathExists(join19(directory, "supacloud.config.ts")) || environmentFile !== null && await pathExists(join19(directory, environmentFile))) {
34077
+ if (await pathExists(join20(directory, "supacloud.json")) || await pathExists(join20(directory, "supacloud.config.ts")) || environmentFile !== null && await pathExists(join20(directory, environmentFile))) {
33738
34078
  return directory;
33739
34079
  }
33740
34080
  const parent = dirname14(directory);
33741
34081
  if (parent === directory)
33742
- return resolve26(startDirectory);
34082
+ return resolve27(startDirectory);
33743
34083
  directory = parent;
33744
34084
  }
33745
34085
  }
@@ -33779,7 +34119,7 @@ function optionalStringArray(value, field) {
33779
34119
  });
33780
34120
  }
33781
34121
  function deployTargetConfig(candidate, name) {
33782
- const value = record6(candidate);
34122
+ const value = record7(candidate);
33783
34123
  if (!value || value.type !== "frontend" && value.type !== "edge_function") {
33784
34124
  throw new Error(`supacloud.json targets.${name}.type must be 'frontend' or 'edge_function'`);
33785
34125
  }
@@ -33804,14 +34144,14 @@ function deployTargetConfig(candidate, name) {
33804
34144
  };
33805
34145
  }
33806
34146
  async function readDeployConfig(configRoot) {
33807
- const configPath = join19(configRoot, "supacloud.json");
34147
+ const configPath = join20(configRoot, "supacloud.json");
33808
34148
  const candidate = await readJson(configPath);
33809
34149
  if (candidate === null)
33810
34150
  return {};
33811
- const config = record6(candidate);
33812
- const frontend = record6(config?.frontend);
33813
- const application = record6(config?.application);
33814
- const targetValues = record6(config?.targets);
34151
+ const config = record7(candidate);
34152
+ const frontend = record7(config?.frontend);
34153
+ const application = record7(config?.application);
34154
+ const targetValues = record7(config?.targets);
33815
34155
  if (!config || config.frontend !== undefined && !frontend || config.application !== undefined && !application || config.targets !== undefined && !targetValues) {
33816
34156
  throw new Error("supacloud.json must contain object-valued 'application', 'frontend' or 'targets' configuration");
33817
34157
  }
@@ -33851,16 +34191,16 @@ async function readDeployConfig(configRoot) {
33851
34191
  };
33852
34192
  }
33853
34193
  async function packageName(projectDirectory) {
33854
- const candidate = record6(await readJson(join19(projectDirectory, "package.json")));
34194
+ const candidate = record7(await readJson(join20(projectDirectory, "package.json")));
33855
34195
  return typeof candidate?.name === "string" && candidate.name.trim() ? candidate.name.trim() : null;
33856
34196
  }
33857
34197
  async function pathExists(path) {
33858
34198
  return access(path).then(() => true, () => false);
33859
34199
  }
33860
34200
  async function hasProjectReleaseManifest(root) {
33861
- if (await pathExists(join19(root, "deploy-manifest.json")))
34201
+ if (await pathExists(join20(root, "deploy-manifest.json")))
33862
34202
  return true;
33863
- const directory = await opendir(join19(root, "supacloud")).catch((error) => {
34203
+ const directory = await opendir(join20(root, "supacloud")).catch((error) => {
33864
34204
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
33865
34205
  return null;
33866
34206
  throw error;
@@ -33871,24 +34211,24 @@ async function hasProjectReleaseManifest(root) {
33871
34211
  for await (const entry of directory) {
33872
34212
  if (++entries > 128)
33873
34213
  throw new Error("Too many SupaCloud project roots to resolve a deployment");
33874
- if ((entry.isDirectory() || entry.isSymbolicLink()) && await pathExists(join19(root, "supacloud", entry.name, "deploy-manifest.json")))
34214
+ if ((entry.isDirectory() || entry.isSymbolicLink()) && await pathExists(join20(root, "supacloud", entry.name, "deploy-manifest.json")))
33875
34215
  return true;
33876
34216
  }
33877
34217
  return false;
33878
34218
  }
33879
34219
  async function defaultBuildCommand(projectDirectory, configRoot) {
33880
- const packageJson = record6(await readJson(join19(projectDirectory, "package.json")));
33881
- const scripts = record6(packageJson?.scripts);
34220
+ const packageJson = record7(await readJson(join20(projectDirectory, "package.json")));
34221
+ const scripts = record7(packageJson?.scripts);
33882
34222
  if (typeof scripts?.build !== "string" || !scripts.build.trim()) {
33883
34223
  throw new Error("No build command was configured and package.json has no build script");
33884
34224
  }
33885
34225
  let directory = projectDirectory;
33886
34226
  while (true) {
33887
- if (await pathExists(join19(directory, "bun.lock")) || await pathExists(join19(directory, "bun.lockb")))
34227
+ if (await pathExists(join20(directory, "bun.lock")) || await pathExists(join20(directory, "bun.lockb")))
33888
34228
  return "bun run build";
33889
- if (await pathExists(join19(directory, "pnpm-lock.yaml")))
34229
+ if (await pathExists(join20(directory, "pnpm-lock.yaml")))
33890
34230
  return "pnpm run build";
33891
- if (await pathExists(join19(directory, "yarn.lock")))
34231
+ if (await pathExists(join20(directory, "yarn.lock")))
33892
34232
  return "yarn build";
33893
34233
  if (directory === configRoot)
33894
34234
  break;
@@ -33900,7 +34240,7 @@ async function defaultBuildCommand(projectDirectory, configRoot) {
33900
34240
  return "npm run build";
33901
34241
  }
33902
34242
  function deploymentList(candidate) {
33903
- const values = Array.isArray(candidate) ? candidate : Array.isArray(record6(candidate)?.deployments) ? record6(candidate)?.deployments : null;
34243
+ const values = Array.isArray(candidate) ? candidate : Array.isArray(record7(candidate)?.deployments) ? record7(candidate)?.deployments : null;
33904
34244
  if (!values)
33905
34245
  throw new Error("Invalid frontend deployment list response");
33906
34246
  return values.map(frontendDeployment);
@@ -33960,9 +34300,9 @@ function selectFrontendTarget(configRoot, config) {
33960
34300
  throw new Error(`Multiple frontend deploy targets found (${targets.map(([name]) => name).sort().join(", ")}). Set defaultTarget to the Web target`);
33961
34301
  }
33962
34302
  function targetRoot(configRoot, target, name) {
33963
- const root = resolve26(configRoot, target.root || (name === "frontend" ? "." : name));
33964
- const prefix = `${resolve26(configRoot)}${sep5}`;
33965
- if (root !== resolve26(configRoot) && !root.startsWith(prefix)) {
34303
+ const root = resolve27(configRoot, target.root || (name === "frontend" ? "." : name));
34304
+ const prefix = `${resolve27(configRoot)}${sep5}`;
34305
+ if (root !== resolve27(configRoot) && !root.startsWith(prefix)) {
33966
34306
  throw new Error(`Deploy target '${name}' root must stay inside the repository root`);
33967
34307
  }
33968
34308
  return root;
@@ -33980,8 +34320,8 @@ function defaultOutputDirectory(framework) {
33980
34320
  }
33981
34321
  }
33982
34322
  function resolveInsideProject(projectDirectory, candidate, allowRoot = false) {
33983
- const resolved = resolve26(projectDirectory, candidate);
33984
- const projectRoot = resolve26(projectDirectory);
34323
+ const resolved = resolve27(projectDirectory, candidate);
34324
+ const projectRoot = resolve27(projectDirectory);
33985
34325
  const projectPrefix = `${projectRoot}${sep5}`;
33986
34326
  if (!allowRoot && resolved === projectRoot || resolved !== projectRoot && !resolved.startsWith(projectPrefix)) {
33987
34327
  throw new Error("Frontend output directory must stay inside the project directory");
@@ -34035,7 +34375,7 @@ async function collectArchiveFiles(root) {
34035
34375
  entries.push(entry);
34036
34376
  entries.sort((left, right) => left.name.localeCompare(right.name, "en"));
34037
34377
  for (const entry of entries) {
34038
- const path = join19(directory, entry.name);
34378
+ const path = join20(directory, entry.name);
34039
34379
  const stats = await lstat5(path);
34040
34380
  if (stats.isSymbolicLink())
34041
34381
  throw new Error(`Frontend output cannot contain symbolic links: ${path}`);
@@ -34054,7 +34394,7 @@ async function collectArchiveFiles(root) {
34054
34394
  const files = new Map;
34055
34395
  const digests = [];
34056
34396
  for (const path of paths) {
34057
- const data = new Uint8Array(await readFile7(path));
34397
+ const data = new Uint8Array(await readFile8(path));
34058
34398
  bytes += data.byteLength;
34059
34399
  if (bytes > MAX_SOURCE_BYTES)
34060
34400
  throw new Error(`Frontend output exceeds ${MAX_SOURCE_BYTES} bytes`);
@@ -34073,11 +34413,11 @@ async function collectArchiveFiles(root) {
34073
34413
  return { files, bytes, count: paths.length, treeSha256: tree.digest("hex") };
34074
34414
  }
34075
34415
  async function createCollectedFrontendArchive(outputDirectory, collected) {
34076
- const temporaryDirectory = await mkdtemp2(join19(tmpdir3(), "supacloud-deploy-"));
34077
- const archivePath = join19(temporaryDirectory, `${basename8(outputDirectory)}.tar.zst`);
34416
+ const temporaryDirectory = await mkdtemp2(join20(tmpdir3(), "supacloud-deploy-"));
34417
+ const archivePath = join20(temporaryDirectory, `${basename8(outputDirectory)}.tar.zst`);
34078
34418
  try {
34079
34419
  const archiveBytes = await createFrontendTarZstd(collected.files);
34080
- await writeFile7(archivePath, archiveBytes);
34420
+ await writeFile8(archivePath, archiveBytes);
34081
34421
  const sha256 = createHash11("sha256").update(archiveBytes).digest("hex");
34082
34422
  return {
34083
34423
  archivePath,
@@ -34122,7 +34462,7 @@ async function publishConfiguredFrontend(http, projectRef, configRoot, skipBuild
34122
34462
  }
34123
34463
  function registerDeployTools(server, http, options = {}) {
34124
34464
  registerTool(server, "deploy", "Build and publish the linked project with one command", deployToolSchema, async (args) => {
34125
- const invocationDirectory = resolve26(String(args.cwd || options.cwd || process.cwd()));
34465
+ const invocationDirectory = resolve27(String(args.cwd || options.cwd || process.cwd()));
34126
34466
  if (args.action === "init") {
34127
34467
  return initializeProject({
34128
34468
  ...typeof args.root === "string" ? { root: args.root } : {},
@@ -34203,11 +34543,11 @@ function registerDeployTools(server, http, options = {}) {
34203
34543
  }
34204
34544
 
34205
34545
  // src/shared/tools/remote-dev-tools.ts
34206
- import { existsSync as existsSync17 } from "node:fs";
34207
- import { readFile as readFile8 } from "node:fs/promises";
34546
+ import { existsSync as existsSync18 } from "node:fs";
34547
+ import { readFile as readFile9 } from "node:fs/promises";
34208
34548
  import { readdir as readdir8 } from "node:fs/promises";
34209
34549
  import { createHash as createHash12 } from "node:crypto";
34210
- import { join as join20, resolve as resolve27 } from "node:path";
34550
+ import { join as join21, resolve as resolve28 } from "node:path";
34211
34551
  import { compileProject as compileProject2 } from "@supacloud/compiler";
34212
34552
  var SAFE_TOKEN = /^[A-Za-z0-9._:@/+,-]+$/;
34213
34553
  var SAFE_REMOTE_ROOT = /^\/(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+\/?$/;
@@ -34235,13 +34575,13 @@ async function runProcess(executable, args, cwd) {
34235
34575
  return { exitCode: exitCode ?? 1, stdout, stderr };
34236
34576
  }
34237
34577
  async function readProjectConfig(root) {
34238
- const file = join20(root, "supacloud.json");
34239
- if (!existsSync17(file))
34578
+ const file = join21(root, "supacloud.json");
34579
+ if (!existsSync18(file))
34240
34580
  return {};
34241
34581
  try {
34242
- const parsed = JSON.parse(await readFile8(file, "utf8"));
34582
+ const parsed = JSON.parse(await readFile9(file, "utf8"));
34243
34583
  if (parsed && typeof parsed === "object" && "dev" in parsed && parsed.dev && typeof parsed.dev === "object" && "database" in parsed.dev) {
34244
- throw new Error("dev.database was removed; use supacloud-model diff and db plan/apply");
34584
+ throw new Error("dev.database was removed; use db:plan/db:apply through the Management API");
34245
34585
  }
34246
34586
  return parsed && typeof parsed === "object" ? parsed : {};
34247
34587
  } catch (error) {
@@ -34257,7 +34597,7 @@ async function sourceFingerprint(root) {
34257
34597
  const visit = async (directory) => {
34258
34598
  const entries = await readdir8(directory, { withFileTypes: true });
34259
34599
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
34260
- const path = join20(directory, entry.name);
34600
+ const path = join21(directory, entry.name);
34261
34601
  if (entry.isDirectory() && ![".git", "node_modules", "dist", "generated", ".supacloud"].includes(entry.name))
34262
34602
  await visit(path);
34263
34603
  else if (entry.isFile())
@@ -34268,7 +34608,7 @@ async function sourceFingerprint(root) {
34268
34608
  const hash = createHash12("sha256");
34269
34609
  for (const file of files) {
34270
34610
  hash.update(file.slice(root.length).replace(/\\/g, "/"));
34271
- hash.update(await readFile8(file));
34611
+ hash.update(await readFile9(file));
34272
34612
  }
34273
34613
  return hash.digest("hex");
34274
34614
  }
@@ -34285,19 +34625,19 @@ function remoteRoot(value) {
34285
34625
  }
34286
34626
  function targetDirectory(root, target, functionSlug, config = {}) {
34287
34627
  if (target === "db")
34288
- return join20(root, "supabase", "migrations");
34628
+ return join21(root, "supabase", "migrations");
34289
34629
  if (target === "functions") {
34290
34630
  const targets = config["targets"];
34291
34631
  const entries = targets && typeof targets === "object" ? Object.values(targets) : [];
34292
34632
  const match = entries.find((entry) => entry !== null && typeof entry === "object" && ("type" in entry) && entry.type === "edge_function" && (!("root" in entry) || typeof entry.root === "string") && (!("slug" in entry) || typeof entry.slug === "string") && (!functionSlug || ("slug" in entry) && entry.slug === functionSlug));
34293
- const base = match?.root ? resolve27(root, match.root) : join20(root, "supabase", "functions");
34294
- return match?.root ? base : functionSlug ? join20(base, safeToken(functionSlug, "function")) : base;
34633
+ const base = match?.root ? resolve28(root, match.root) : join21(root, "supabase", "functions");
34634
+ return match?.root ? base : functionSlug ? join21(base, safeToken(functionSlug, "function")) : base;
34295
34635
  }
34296
34636
  if (target === "frontend") {
34297
34637
  const targets = config["targets"];
34298
34638
  const entries = targets && typeof targets === "object" ? Object.values(targets) : [];
34299
34639
  const match = entries.find((entry) => entry !== null && typeof entry === "object" && ("type" in entry) && entry.type === "frontend" && (!("root" in entry) || typeof entry.root === "string"));
34300
- return match?.root ? resolve27(root, match.root) : join20(root, "apps", "web");
34640
+ return match?.root ? resolve28(root, match.root) : join21(root, "apps", "web");
34301
34641
  }
34302
34642
  return root;
34303
34643
  }
@@ -34336,10 +34676,10 @@ function reloadCommand(config, target, projectRef, functionSlug) {
34336
34676
  return [...command.split(" "), "--project-ref", safeToken(projectRef || "test", "project_ref"), "--target", targetConfigPath(target), ...functionSlug ? ["--function", safeToken(functionSlug, "function")] : []];
34337
34677
  }
34338
34678
  function sshArgs(connection, remoteCommand) {
34339
- return ["-p", String(connection.port), "-i", resolve27(connection.key), "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", `${connection.user}@${connection.host}`, ...remoteCommand];
34679
+ return ["-p", String(connection.port), "-i", resolve28(connection.key), "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", `${connection.user}@${connection.host}`, ...remoteCommand];
34340
34680
  }
34341
34681
  function rsyncArgs(connection, source, destination, excludes, deleteRemote) {
34342
- const args = ["-az", "--checksum", "--partial", "--protect-args", "-e", `ssh -p ${connection.port} -i ${resolve27(connection.key)} -o BatchMode=yes -o StrictHostKeyChecking=yes`];
34682
+ const args = ["-az", "--checksum", "--partial", "--protect-args", "-e", `ssh -p ${connection.port} -i ${resolve28(connection.key)} -o BatchMode=yes -o StrictHostKeyChecking=yes`];
34343
34683
  if (deleteRemote)
34344
34684
  args.push("--delete-delay");
34345
34685
  for (const exclude of excludes) {
@@ -34351,17 +34691,17 @@ function rsyncArgs(connection, source, destination, excludes, deleteRemote) {
34351
34691
  return args;
34352
34692
  }
34353
34693
  async function syncOnce(args, options) {
34354
- const root = resolve27(String(args.project_dir || options.cwd || process.cwd()));
34694
+ const root = resolve28(String(args.project_dir || options.cwd || process.cwd()));
34355
34695
  const projectConfig = await readProjectConfig(root);
34356
34696
  const config = projectConfig.dev || {};
34357
34697
  const target = String(args.target || "project");
34358
34698
  const source = targetDirectory(root, target, typeof args.function === "string" ? args.function : undefined, projectConfig);
34359
- if (!existsSync17(source))
34699
+ if (!existsSync18(source))
34360
34700
  throw new Error(`Dev source directory not found: ${source}`);
34361
34701
  let compiled = false;
34362
34702
  if (config.compile === true && target !== "db") {
34363
- const compileRoot = resolve27(root, config.compileRoot || ".");
34364
- const compileOutDir = resolve27(root, config.compileOutDir || "generated");
34703
+ const compileRoot = resolve28(root, config.compileRoot || ".");
34704
+ const compileOutDir = resolve28(root, config.compileOutDir || "generated");
34365
34705
  const compilation = await compileProject2({
34366
34706
  rootDir: compileRoot,
34367
34707
  outDir: compileOutDir,
@@ -34399,7 +34739,7 @@ function registerRemoteDevTools(server, options = {}) {
34399
34739
  if (["production", "prod"].includes((options.environment || "").toLowerCase()))
34400
34740
  throw new Error("Remote dev mode is forbidden for production environments");
34401
34741
  if (args.action === "status") {
34402
- const root = resolve27(String(args.project_dir || options.cwd || process.cwd()));
34742
+ const root = resolve28(String(args.project_dir || options.cwd || process.cwd()));
34403
34743
  const config = await readDevConfig(root);
34404
34744
  const connection = connectionArgs(options, config, args);
34405
34745
  const execute = options.execute || ((command, commandArgs, cwd) => runProcess(command, commandArgs, cwd));
@@ -34410,7 +34750,7 @@ function registerRemoteDevTools(server, options = {}) {
34410
34750
  return { content: [{ type: "text", text: JSON.stringify(await syncOnce(args, options), null, 2) }] };
34411
34751
  }
34412
34752
  if (args.action === "watch") {
34413
- const root = resolve27(String(args.project_dir || options.cwd || process.cwd()));
34753
+ const root = resolve28(String(args.project_dir || options.cwd || process.cwd()));
34414
34754
  const interval = Math.max(100, Math.min(1e4, Number(args.interval_ms || 300)));
34415
34755
  let fingerprint = "";
34416
34756
  let lastSync = null;
@@ -34430,15 +34770,15 @@ function registerRemoteDevTools(server, options = {}) {
34430
34770
  }
34431
34771
 
34432
34772
  // src/shared/tools/developer-experience-tools.ts
34433
- import { existsSync as existsSync18 } from "node:fs";
34434
- import { mkdir as mkdir8, readdir as readdir9, readFile as readFile9, writeFile as writeFile8 } from "node:fs/promises";
34435
- import { dirname as dirname15, join as join21, resolve as resolve28 } from "node:path";
34773
+ import { existsSync as existsSync19 } from "node:fs";
34774
+ import { mkdir as mkdir9, readdir as readdir9, readFile as readFile10, writeFile as writeFile9 } from "node:fs/promises";
34775
+ import { dirname as dirname15, join as join22, resolve as resolve29 } from "node:path";
34436
34776
  var initToolSchema2 = {
34437
34777
  root: optional(String2(), "Project directory to initialize (default: current directory)"),
34438
34778
  format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
34439
34779
  };
34440
34780
  var environmentToolSchema2 = {
34441
- action: withDescription(stringEnum2(["list", "check"]), "Environment profile inspection action"),
34781
+ ...environmentSyncSchema,
34442
34782
  root: optional(String2(), "Project directory containing .env.supacloud.* files"),
34443
34783
  format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
34444
34784
  };
@@ -34460,13 +34800,13 @@ var PRODUCTION_PROFILE2 = [
34460
34800
  ""
34461
34801
  ].join(`
34462
34802
  `);
34463
- function textResult4(text, isError = false) {
34803
+ function textResult5(text, isError = false) {
34464
34804
  return { isError, content: [{ type: "text", text }] };
34465
34805
  }
34466
- function jsonResult2(value, isError = false) {
34467
- return textResult4(JSON.stringify(value, null, 2), isError);
34806
+ function jsonResult3(value, isError = false) {
34807
+ return textResult5(JSON.stringify(value, null, 2), isError);
34468
34808
  }
34469
- function record7(value) {
34809
+ function record8(value) {
34470
34810
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
34471
34811
  }
34472
34812
  function packageDependencies2(manifest) {
@@ -34484,17 +34824,17 @@ function outputDirectoryFor2(manifest) {
34484
34824
  return "dist";
34485
34825
  }
34486
34826
  async function readPackageManifest2(root) {
34487
- const path = join21(root, "package.json");
34488
- if (!existsSync18(path))
34827
+ const path = join22(root, "package.json");
34828
+ if (!existsSync19(path))
34489
34829
  return {};
34490
34830
  try {
34491
- const parsed = JSON.parse(await readFile9(path, "utf8"));
34492
- const value = record7(parsed);
34831
+ const parsed = JSON.parse(await readFile10(path, "utf8"));
34832
+ const value = record8(parsed);
34493
34833
  if (!value)
34494
34834
  throw new Error("package.json must contain an object");
34495
- const scripts = record7(value.scripts);
34496
- const dependencies = record7(value.dependencies);
34497
- const devDependencies = record7(value.devDependencies);
34835
+ const scripts = record8(value.scripts);
34836
+ const dependencies = record8(value.dependencies);
34837
+ const devDependencies = record8(value.devDependencies);
34498
34838
  return {
34499
34839
  scripts: scripts ?? undefined,
34500
34840
  dependencies: dependencies ?? undefined,
@@ -34506,7 +34846,7 @@ async function readPackageManifest2(root) {
34506
34846
  }
34507
34847
  async function writeNewFile2(path, content) {
34508
34848
  try {
34509
- await writeFile8(path, content, { encoding: "utf8", flag: "wx", mode: 384 });
34849
+ await writeFile9(path, content, { encoding: "utf8", flag: "wx", mode: 384 });
34510
34850
  return true;
34511
34851
  } catch (error) {
34512
34852
  if (error instanceof Error && "code" in error && error.code === "EEXIST")
@@ -34515,8 +34855,8 @@ async function writeNewFile2(path, content) {
34515
34855
  }
34516
34856
  }
34517
34857
  async function ensureGitignore2(root) {
34518
- const path = join21(root, ".gitignore");
34519
- const existing = existsSync18(path) ? await readFile9(path, "utf8") : "";
34858
+ const path = join22(root, ".gitignore");
34859
+ const existing = existsSync19(path) ? await readFile10(path, "utf8") : "";
34520
34860
  const required = [".env.supacloud.*", "!.env.supacloud.*.example"];
34521
34861
  const missing = required.filter((entry) => !existing.split(/\r?\n/).includes(entry));
34522
34862
  if (missing.length === 0)
@@ -34524,16 +34864,16 @@ async function ensureGitignore2(root) {
34524
34864
  const prefix = existing.length > 0 && !existing.endsWith(`
34525
34865
  `) ? `${existing}
34526
34866
  ` : existing;
34527
- await writeFile8(path, `${prefix}${missing.join(`
34867
+ await writeFile9(path, `${prefix}${missing.join(`
34528
34868
  `)}
34529
34869
  `, "utf8");
34530
34870
  return true;
34531
34871
  }
34532
34872
  async function initializeProject2(request, options = {}) {
34533
- const root = resolve28(request.root || options.cwd || process.cwd());
34534
- await mkdir8(root, { recursive: true });
34535
- const configPath = join21(root, "supacloud.json");
34536
- if (existsSync18(configPath)) {
34873
+ const root = resolve29(request.root || options.cwd || process.cwd());
34874
+ await mkdir9(root, { recursive: true });
34875
+ const configPath = join22(root, "supacloud.json");
34876
+ if (existsSync19(configPath)) {
34537
34877
  throw new Error(`supacloud.json already exists in ${root}; init never overwrites project configuration`);
34538
34878
  }
34539
34879
  const manifest = await readPackageManifest2(root);
@@ -34547,7 +34887,7 @@ async function initializeProject2(request, options = {}) {
34547
34887
  };
34548
34888
  const created = [];
34549
34889
  try {
34550
- await writeFile8(configPath, `${JSON.stringify(config, null, 2)}
34890
+ await writeFile9(configPath, `${JSON.stringify(config, null, 2)}
34551
34891
  `, {
34552
34892
  encoding: "utf8",
34553
34893
  flag: "wx",
@@ -34560,10 +34900,10 @@ async function initializeProject2(request, options = {}) {
34560
34900
  throw error;
34561
34901
  }
34562
34902
  created.push("supacloud.json");
34563
- if (await writeNewFile2(join21(root, ".env.supacloud.test.example"), TEST_PROFILE2)) {
34903
+ if (await writeNewFile2(join22(root, ".env.supacloud.test.example"), TEST_PROFILE2)) {
34564
34904
  created.push(".env.supacloud.test.example");
34565
34905
  }
34566
- if (await writeNewFile2(join21(root, ".env.supacloud.production.example"), PRODUCTION_PROFILE2)) {
34906
+ if (await writeNewFile2(join22(root, ".env.supacloud.production.example"), PRODUCTION_PROFILE2)) {
34567
34907
  created.push(".env.supacloud.production.example");
34568
34908
  }
34569
34909
  if (await ensureGitignore2(root))
@@ -34574,7 +34914,7 @@ async function initializeProject2(request, options = {}) {
34574
34914
  root,
34575
34915
  created,
34576
34916
  detected: {
34577
- package_json: existsSync18(join21(root, "package.json")),
34917
+ package_json: existsSync19(join22(root, "package.json")),
34578
34918
  build_script: hasBuildScript,
34579
34919
  output_directory: outputDirectory
34580
34920
  },
@@ -34586,8 +34926,8 @@ async function initializeProject2(request, options = {}) {
34586
34926
  ]
34587
34927
  };
34588
34928
  if (request.format === "json")
34589
- return jsonResult2(result);
34590
- return textResult4([
34929
+ return jsonResult3(result);
34930
+ return textResult5([
34591
34931
  `Initialized SupaCloud deployment in ${root}.`,
34592
34932
  `Created: ${created.join(", ")}.`,
34593
34933
  hasBuildScript ? `Detected package.json build script; deploy output defaults to ${outputDirectory}.` : "No package.json build script detected; add one before deploying.",
@@ -34608,7 +34948,7 @@ async function environmentProfiles(root) {
34608
34948
  });
34609
34949
  return entries.filter((entry) => entry.isFile()).map((entry) => {
34610
34950
  const name = profileNameFromFile(entry.name);
34611
- return name ? { name, path: join21(root, entry.name), exists: true } : null;
34951
+ return name ? { name, path: join22(root, entry.name), exists: true } : null;
34612
34952
  }).filter((profile) => profile !== null).sort((left, right) => left.name.localeCompare(right.name));
34613
34953
  }
34614
34954
  function statusMissing(context) {
@@ -34647,14 +34987,14 @@ async function inspectProfile(profile) {
34647
34987
  environmentName: profile.name
34648
34988
  });
34649
34989
  const status = statusMissing(context);
34650
- const configText = await readFile9(join21(dirname15(profile.path), "supacloud.json"), "utf8").catch((error) => {
34990
+ const configText = await readFile10(join22(dirname15(profile.path), "supacloud.json"), "utf8").catch((error) => {
34651
34991
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
34652
34992
  return "{}";
34653
34993
  throw error;
34654
34994
  });
34655
- const config = record7(JSON.parse(configText));
34656
- const hasFrontend = record7(config?.frontend) !== null || Object.values(record7(config?.targets) ?? {}).some((target) => record7(target)?.type === "frontend");
34657
- const deploy = deployMissing(context, record7(config?.application), hasFrontend);
34995
+ const config = record8(JSON.parse(configText));
34996
+ const hasFrontend = record8(config?.frontend) !== null || Object.values(record8(config?.targets) ?? {}).some((target) => record8(target)?.type === "frontend");
34997
+ const deploy = deployMissing(context, record8(config?.application), hasFrontend);
34658
34998
  return {
34659
34999
  name: profile.name,
34660
35000
  path: profile.path,
@@ -34691,7 +35031,7 @@ async function inspectProfile(profile) {
34691
35031
  }
34692
35032
  }
34693
35033
  async function inspectEnvironment(request, options) {
34694
- const root = resolve28(request.root || options.cwd || process.cwd());
35034
+ const root = resolve29(request.root || options.cwd || process.cwd());
34695
35035
  const profiles = await environmentProfiles(root);
34696
35036
  if (request.action === "list") {
34697
35037
  const active = options.activeContext?.environment || null;
@@ -34707,12 +35047,12 @@ async function inspectEnvironment(request, options) {
34707
35047
  }))
34708
35048
  };
34709
35049
  if (request.format === "json")
34710
- return jsonResult2(result);
35050
+ return jsonResult3(result);
34711
35051
  if (profiles.length === 0) {
34712
- return textResult4(`No .env.supacloud.<name> profiles found in ${root}.
35052
+ return textResult5(`No .env.supacloud.<name> profiles found in ${root}.
34713
35053
  Run \`supacloud deploy init\` to create safe examples.`);
34714
35054
  }
34715
- return textResult4([
35055
+ return textResult5([
34716
35056
  `Environment profiles in ${root}:`,
34717
35057
  ...result.environments.map((profile) => `${profile.active ? "*" : " "} ${profile.name} ${profile.path}`)
34718
35058
  ].join(`
@@ -34727,9 +35067,9 @@ Run \`supacloud deploy init\` to create safe examples.`);
34727
35067
  environments: reports
34728
35068
  };
34729
35069
  if (request.format === "json")
34730
- return jsonResult2(result, !result.ok);
35070
+ return jsonResult3(result, !result.ok);
34731
35071
  if (reports.length === 0) {
34732
- return textResult4(`No environment profiles found in ${root}.
35072
+ return textResult5(`No environment profiles found in ${root}.
34733
35073
  Run \`supacloud deploy init\` and copy an example profile.`, true);
34734
35074
  }
34735
35075
  const lines = reports.map((report) => {
@@ -34740,11 +35080,384 @@ Run \`supacloud deploy init\` and copy an example profile.`, true);
34740
35080
  const ref = report.projectRef ? `project=${report.projectRef}` : "project=unknown";
34741
35081
  return `${status} ${report.name} ${deploy} ${ref}`;
34742
35082
  });
34743
- return textResult4(lines.join(`
35083
+ return textResult5(lines.join(`
34744
35084
  `), !result.ok);
34745
35085
  }
34746
35086
  function registerDeveloperExperienceTools(server, options = {}) {
34747
- registerTool(server, "env", "List or locally validate named SupaCloud environment profiles without contacting the platform or printing secrets.", environmentToolSchema2, (request) => inspectEnvironment(request, options));
35087
+ registerTool(server, "env", "List or locally validate named SupaCloud environment profiles without contacting the platform or printing secrets.", environmentToolSchema2, (request) => {
35088
+ const input = request;
35089
+ if (input.action === "sync")
35090
+ return syncEnvironmentProfile(input, options);
35091
+ return inspectEnvironment(input, options);
35092
+ });
35093
+ }
35094
+
35095
+ // src/shared/tools/configuration-tools.ts
35096
+ import { existsSync as existsSync20 } from "node:fs";
35097
+ import { mkdir as mkdir10, readFile as readFile11, writeFile as writeFile10 } from "node:fs/promises";
35098
+ import { join as join23, resolve as resolve30 } from "node:path";
35099
+ var MANAGEMENT_CONFIGURATION_KEYS = ["SUPACLOUD_API_URL", "SUPACLOUD_API_TOKEN", "SUPACLOUD_PROJECT_REF"];
35100
+ var APPLICATION_CONFIGURATION_KEYS = ["SUPABASE_URL", "SUPABASE_SERVICE_ROLE_KEY", "SUPACLOUD_PROJECT_REF"];
35101
+ var onboardToolSchema2 = {
35102
+ root: optional(String2(), "Repository or configuration root (default: current directory)"),
35103
+ profile: optional(stringEnum2(["solo", "podman", "pigsty", "cluster"]), "Deployment profile (default: solo)"),
35104
+ domain: optional(String2(), "Public API domain; studio domain is derived from it"),
35105
+ database: optional(stringEnum2(["local", "external"]), "Database provider (default: local)"),
35106
+ storage: optional(stringEnum2(["juicefs", "external"]), "Storage provider (default: juicefs)"),
35107
+ write: optional(Boolean2(), "Write the generated context into supacloud.json"),
35108
+ format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
35109
+ };
35110
+ var configurationToolSchema2 = {
35111
+ action: withDescription(stringEnum2(["doctor", "explain"]), "Configuration inspection action"),
35112
+ root: optional(String2(), "Repository or configuration root (default: current directory)"),
35113
+ key: optional(String2(), "[explain] Environment variable name"),
35114
+ format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
35115
+ };
35116
+ var environmentSyncSchema2 = {
35117
+ action: withDescription(stringEnum2(["list", "check", "sync"]), "Environment profile action"),
35118
+ root: optional(String2(), "Project directory containing .env.supacloud.* files"),
35119
+ environment: optional(String2(), "[sync] Profile name; defaults to the selected environment"),
35120
+ write: optional(Boolean2(), "[sync] Persist derived context and the reduced profile example"),
35121
+ format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
35122
+ };
35123
+ var SECRET_KEY2 = /(?:PASSWORD|PASS|SECRET|TOKEN|PRIVATE|CREDENTIAL|AUTHORIZATION|COOKIE|SESSION|DATABASE_URL|CONNECTION_STRING|DSN)/i;
35124
+ var PLATFORM_KEY2 = /^(?:SUPACLOUD|SUPABASE)_(?:API|PROJECT|ENV|HOST|SSH|APPLICATION|SERVICE_ROLE|ACCESS|URL|READ_ONLY|TLS|ANON|PUBLISHABLE)/;
35125
+ function textResult6(text, isError = false) {
35126
+ return { isError, content: [{ type: "text", text }] };
35127
+ }
35128
+ function jsonResult4(value, isError = false) {
35129
+ return textResult6(JSON.stringify(value, null, 2), isError);
35130
+ }
35131
+ function record9(value) {
35132
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
35133
+ }
35134
+ function unquote2(value) {
35135
+ const trimmed = value.trim();
35136
+ if (trimmed.length >= 2 && (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'"))) {
35137
+ return trimmed.slice(1, -1);
35138
+ }
35139
+ return trimmed;
35140
+ }
35141
+ function parseEnvironment2(content) {
35142
+ const values = {};
35143
+ for (const rawLine of content.split(/\r?\n/)) {
35144
+ const line = rawLine.trim();
35145
+ if (!line || line.startsWith("#"))
35146
+ continue;
35147
+ const match = line.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
35148
+ if (match)
35149
+ values[match[1]] = unquote2(match[2]);
35150
+ }
35151
+ return values;
35152
+ }
35153
+ async function readJsonObject2(path) {
35154
+ if (!existsSync20(path))
35155
+ return {};
35156
+ const parsed = JSON.parse(await readFile11(path, "utf8"));
35157
+ const value = record9(parsed);
35158
+ if (!value)
35159
+ throw new Error(`${path} must contain a JSON object`);
35160
+ return value;
35161
+ }
35162
+ async function writeJsonObject2(path, value) {
35163
+ await writeFile10(path, `${JSON.stringify(value, null, 2)}
35164
+ `, { encoding: "utf8", mode: 420 });
35165
+ }
35166
+ function contextFromConfig2(config) {
35167
+ const context = record9(config.context);
35168
+ return context ?? {};
35169
+ }
35170
+ function environmentContext2(config, environment) {
35171
+ const context = contextFromConfig2(config);
35172
+ const environments = record9(context.environments);
35173
+ const selected = environments ? record9(environments[environment]) : null;
35174
+ return selected ?? {};
35175
+ }
35176
+ function derivedValues(values) {
35177
+ const derived = {};
35178
+ const publicDomain = values.SUPABASE_PUBLIC_DOMAIN?.trim();
35179
+ if (publicDomain && !values.SUPABASE_STUDIO_DOMAIN) {
35180
+ derived.SUPABASE_STUDIO_DOMAIN = `studio.${publicDomain.replace(/^api\./, "")}`;
35181
+ }
35182
+ if (publicDomain && !values.SUPABASE_PUBLIC_URL) {
35183
+ derived.SUPABASE_PUBLIC_URL = `https://${publicDomain}`;
35184
+ }
35185
+ const host = values.SUPACLOUD_HOST?.trim();
35186
+ if (host && !values.SUPACLOUD_API_URL) {
35187
+ derived.SUPACLOUD_API_URL = `http://${host}:9090`;
35188
+ }
35189
+ if (values.SUPACLOUD_DEPLOYMENT_PROFILE === undefined) {
35190
+ derived.SUPACLOUD_DEPLOYMENT_PROFILE = "solo";
35191
+ }
35192
+ if (!values.S3_STORAGE_TYPE)
35193
+ derived.S3_STORAGE_TYPE = "juicefs";
35194
+ return derived;
35195
+ }
35196
+ function classify(name, value) {
35197
+ if (SECRET_KEY2.test(name))
35198
+ return "secret";
35199
+ if (PLATFORM_KEY2.test(name))
35200
+ return "platform";
35201
+ if (value === undefined || value === "")
35202
+ return "default";
35203
+ return "override";
35204
+ }
35205
+ function configurationEntries(values) {
35206
+ const derived = derivedValues(values);
35207
+ const names = [...new Set([...Object.keys(values), ...Object.keys(derived)])].sort();
35208
+ return names.map((name) => {
35209
+ const value = values[name] ?? derived[name];
35210
+ const kind = derived[name] !== undefined && values[name] === undefined ? "derived" : classify(name, values[name]);
35211
+ return {
35212
+ name,
35213
+ kind,
35214
+ source: kind === "derived" ? "platform-default" : values[name] === undefined ? "absent" : "profile",
35215
+ configured: value !== undefined && value !== "",
35216
+ value: kind === "secret" ? value ? "********" : null : value ?? null
35217
+ };
35218
+ });
35219
+ }
35220
+ function requiredConfigurationKeys(activeContext) {
35221
+ return activeContext?.credentialScope === "project_application" ? APPLICATION_CONFIGURATION_KEYS : MANAGEMENT_CONFIGURATION_KEYS;
35222
+ }
35223
+ function onboardingPlan(args, root) {
35224
+ const profile = typeof args.profile === "string" ? args.profile : "solo";
35225
+ const database = typeof args.database === "string" ? args.database : "local";
35226
+ const storage = typeof args.storage === "string" ? args.storage : "juicefs";
35227
+ const domain = typeof args.domain === "string" && args.domain.trim() ? args.domain.trim() : null;
35228
+ const required = ["profile"];
35229
+ if (domain === null)
35230
+ required.push("public_domain_or_explicit_ip");
35231
+ if (database === "external")
35232
+ required.push("database_url");
35233
+ if (storage === "external")
35234
+ required.push("s3_endpoint_and_credentials");
35235
+ return {
35236
+ schema: "supacloud.onboarding-plan.v1",
35237
+ root,
35238
+ profile,
35239
+ domain,
35240
+ database,
35241
+ storage,
35242
+ required_inputs: required,
35243
+ derived: {
35244
+ studio_domain: domain ? `studio.${domain.replace(/^api\./, "")}` : null,
35245
+ storage_backend: storage === "juicefs" ? "postgresql-large-object" : "external-s3",
35246
+ internal_service_urls: "allocated by the selected deployment profile",
35247
+ component_versions: "read from the verified release manifest"
35248
+ },
35249
+ writes: ["supacloud.json context metadata"],
35250
+ safety: [
35251
+ "unknown local PostgreSQL is never adopted automatically",
35252
+ "secret values are generated or injected and never printed",
35253
+ "external providers are requested only when selected"
35254
+ ]
35255
+ };
35256
+ }
35257
+ async function runOnboard(args, options) {
35258
+ const root = resolve30(typeof args.root === "string" ? args.root : options.cwd ?? process.cwd());
35259
+ const plan = onboardingPlan(args, root);
35260
+ if (args.write === true) {
35261
+ await mkdir10(root, { recursive: true });
35262
+ const path = join23(root, "supacloud.json");
35263
+ const config = await readJsonObject2(path);
35264
+ if (existsSync20(path) && config.context !== undefined) {
35265
+ throw new Error("supacloud.json already has context metadata; use env sync to update one environment");
35266
+ }
35267
+ config.context = {
35268
+ default_environment: "test",
35269
+ deployment_profile: plan.profile,
35270
+ public_domain: plan.domain,
35271
+ database: plan.database,
35272
+ storage: plan.storage,
35273
+ environments: {}
35274
+ };
35275
+ await writeJsonObject2(path, config);
35276
+ return jsonResult4({ ...plan, ok: true, written: path });
35277
+ }
35278
+ return args.format === "json" ? jsonResult4({ ...plan, ok: true, written: false }) : textResult6([
35279
+ "SupaCloud onboarding plan",
35280
+ `profile: ${String(plan.profile)}`,
35281
+ `database: ${String(plan.database)}`,
35282
+ `storage: ${String(plan.storage)}`,
35283
+ `domain: ${plan.domain ?? "(required)"}`,
35284
+ "",
35285
+ "No files were changed. Re-run with --write after reviewing the plan."
35286
+ ].join(`
35287
+ `));
35288
+ }
35289
+ async function runConfiguration(args, options) {
35290
+ const root = resolve30(typeof args.root === "string" ? args.root : options.cwd ?? process.cwd());
35291
+ const config = await readJsonObject2(join23(root, "supacloud.json"));
35292
+ const environment = options.activeContext?.environment || "";
35293
+ const profileValues = environment && existsSync20(join23(root, `.env.supacloud.${environment}`)) ? parseEnvironment2(await readFile11(join23(root, `.env.supacloud.${environment}`), "utf8")) : {};
35294
+ const metadata = environment ? environmentContext2(config, environment) : {};
35295
+ const values = {
35296
+ ...Object.fromEntries(Object.entries(metadata).filter(([, value]) => typeof value === "string")),
35297
+ ...profileValues
35298
+ };
35299
+ const entries = configurationEntries(Object.fromEntries([
35300
+ ...Object.entries(values),
35301
+ ...requiredConfigurationKeys(options.activeContext).map((name) => [name, values[name] ?? ""])
35302
+ ]));
35303
+ if (args.action === "explain") {
35304
+ const key = typeof args.key === "string" ? args.key.trim() : "";
35305
+ const selected = key ? entries.filter((entry) => entry.name === key) : entries;
35306
+ return jsonResult4({ schema: "supacloud.configuration.explain.v1", root, environment: environment || null, entries: selected });
35307
+ }
35308
+ const missing = entries.filter((entry) => entry.configured === false).map((entry) => entry.name);
35309
+ const secrets = entries.filter((entry) => entry.kind === "secret").map((entry) => entry.name);
35310
+ const result = {
35311
+ schema: "supacloud.configuration.doctor.v1",
35312
+ root,
35313
+ environment: environment || null,
35314
+ ok: missing.length === 0,
35315
+ missing,
35316
+ secret_names: secrets,
35317
+ entries,
35318
+ next: missing.length ? ["supacloud config explain"] : ["supacloud env sync --env test --write"]
35319
+ };
35320
+ return args.format === "json" ? jsonResult4(result, !result.ok) : textResult6([
35321
+ `Configuration: ${result.ok ? "OK" : "BLOCKED"}`,
35322
+ `environment: ${environment || "(none selected)"}`,
35323
+ missing.length ? `missing: ${missing.join(", ")}` : "missing: none",
35324
+ secrets.length ? `secrets: ${secrets.join(", ")}` : "secrets: none"
35325
+ ].join(`
35326
+ `), !result.ok);
35327
+ }
35328
+ function registerConfigurationTools(server, options = {}) {
35329
+ registerTool(server, "onboard", "Preview or write a minimal SupaCloud onboarding plan.", onboardToolSchema2, (args) => runOnboard(args, options));
35330
+ registerTool(server, "config", "Inspect configuration sources, derived values and missing inputs.", configurationToolSchema2, (args) => runConfiguration(args, options));
35331
+ }
35332
+
35333
+ // src/shared/tools/pipeline-tools.ts
35334
+ import { existsSync as existsSync21 } from "node:fs";
35335
+ import { mkdir as mkdir11, readFile as readFile12, writeFile as writeFile11 } from "node:fs/promises";
35336
+ import { join as join24, resolve as resolve31 } from "node:path";
35337
+ var pipelineToolSchema = {
35338
+ action: withDescription(stringEnum2(["connect"]), "Pipeline configuration action"),
35339
+ provider: optional(stringEnum2(["github", "gitlab"]), "[connect] Git provider (default: github)"),
35340
+ root: optional(String2(), "[connect] Repository root (default: current directory)"),
35341
+ write: optional(Boolean2(), "[connect] Write the generated workflow"),
35342
+ preview: optional(Boolean2(), "[connect] Include pull request Preview lifecycle"),
35343
+ format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
35344
+ };
35345
+ function textResult7(text, isError = false) {
35346
+ return { isError, content: [{ type: "text", text }] };
35347
+ }
35348
+ function jsonResult5(value, isError = false) {
35349
+ return textResult7(JSON.stringify(value, null, 2), isError);
35350
+ }
35351
+ function record10(value) {
35352
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
35353
+ }
35354
+ async function readJson2(path) {
35355
+ if (!existsSync21(path))
35356
+ return {};
35357
+ const parsed = JSON.parse(await readFile12(path, "utf8"));
35358
+ return record10(parsed) ?? {};
35359
+ }
35360
+ function workflow(provider, preview) {
35361
+ if (provider !== "github") {
35362
+ return [
35363
+ "stages:",
35364
+ " - deploy",
35365
+ "",
35366
+ "supacloud_deploy:",
35367
+ " stage: deploy",
35368
+ " image: node:24",
35369
+ " rules:",
35370
+ " - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'",
35371
+ " variables:",
35372
+ " SUPACLOUD_API_URL: $SUPACLOUD_API_URL",
35373
+ " SUPACLOUD_API_TOKEN: $SUPACLOUD_DEPLOY_TOKEN",
35374
+ " SUPACLOUD_PROJECT_REF: $SUPACLOUD_PROJECT_REF",
35375
+ " script:",
35376
+ " - npx @supacloud/cli deploy",
35377
+ ""
35378
+ ].join(`
35379
+ `);
35380
+ }
35381
+ const events = preview ? ` push:
35382
+ branches: [main]
35383
+ pull_request:
35384
+ types: [opened, synchronize, reopened, closed]` : ` push:
35385
+ branches: [main]`;
35386
+ const previewSteps = preview ? [
35387
+ " - name: Provision or reclaim PR Preview",
35388
+ " if: ${{ github.event_name == 'pull_request' }}",
35389
+ " env:",
35390
+ " SUPACLOUD_API_TOKEN: ${{ secrets.SUPACLOUD_DEPLOY_TOKEN }}",
35391
+ " SUPACLOUD_API_URL: ${{ secrets.SUPACLOUD_API_URL }}",
35392
+ " SUPACLOUD_PROJECT_REF: ${{ secrets.SUPACLOUD_PROJECT_REF }}",
35393
+ " run: >-",
35394
+ " npx @supacloud/cli --env test app preview-pr",
35395
+ " --id ${{ vars.SUPACLOUD_APPLICATION_ID }}",
35396
+ " --environment_id ${{ vars.SUPACLOUD_ENVIRONMENT_ID }}",
35397
+ " --pull_request_action ${{ github.event.action == 'closed' && 'closed' || 'opened' }}",
35398
+ " --repository ${{ github.repository }}",
35399
+ " --pull_request_number ${{ github.event.pull_request.number }}",
35400
+ " --release_id ${{ vars.SUPACLOUD_RELEASE_ID }}"
35401
+ ].join(`
35402
+ `) : "";
35403
+ return `name: SupaCloud deploy
35404
+
35405
+ on:
35406
+ ${events}
35407
+
35408
+ jobs:
35409
+ deploy:
35410
+ runs-on: ubuntu-latest
35411
+ steps:
35412
+ - uses: actions/checkout@v4
35413
+ - name: Deploy to SupaCloud
35414
+ if: \${{ github.event_name == 'push' || github.event.action == '' }}
35415
+ env:
35416
+ SUPACLOUD_API_URL: \${{ secrets.SUPACLOUD_API_URL }}
35417
+ SUPACLOUD_API_TOKEN: \${{ secrets.SUPACLOUD_DEPLOY_TOKEN }}
35418
+ SUPACLOUD_PROJECT_REF: \${{ secrets.SUPACLOUD_PROJECT_REF }}
35419
+ run: npx @supacloud/cli deploy
35420
+ ${previewSteps}`;
35421
+ }
35422
+ async function connectPipeline(args, options = {}) {
35423
+ const root = resolve31(typeof args.root === "string" ? args.root : options.cwd ?? process.cwd());
35424
+ const provider = typeof args.provider === "string" ? args.provider : "github";
35425
+ const config = await readJson2(join24(root, "supacloud.json"));
35426
+ const frontend = record10(config.frontend);
35427
+ const packageJson = await readJson2(join24(root, "package.json"));
35428
+ const scripts = record10(packageJson.scripts);
35429
+ const buildCommand = typeof frontend?.buildCommand === "string" ? frontend.buildCommand : typeof scripts?.build === "string" ? scripts.build : "(configure package.json build script)";
35430
+ const outputDirectory = typeof frontend?.outputDirectory === "string" ? frontend.outputDirectory : "dist";
35431
+ const workflowPath = provider === "github" ? join24(root, ".github", "workflows", "supacloud-deploy.yml") : join24(root, ".gitlab-ci.yml");
35432
+ const result = {
35433
+ schema: "supacloud.pipeline-connection.v1",
35434
+ provider,
35435
+ root,
35436
+ detected: { build_command: buildCommand, output_directory: outputDirectory },
35437
+ workflow: workflowPath,
35438
+ secrets: ["SUPACLOUD_DEPLOY_TOKEN", "SUPACLOUD_API_URL", "SUPACLOUD_PROJECT_REF"],
35439
+ variables: args.preview === true ? ["SUPACLOUD_APPLICATION_ID", "SUPACLOUD_ENVIRONMENT_ID", "SUPACLOUD_RELEASE_ID"] : [],
35440
+ preview: args.preview === true,
35441
+ safety: ["workflow contains no secret values", "provider token remains in the provider secret store"]
35442
+ };
35443
+ if (args.write !== true)
35444
+ return args.format === "json" ? jsonResult5({ ...result, written: false }) : textResult7([
35445
+ `Pipeline provider: ${provider}`,
35446
+ `build: ${buildCommand}`,
35447
+ `output: ${outputDirectory}`,
35448
+ `workflow: ${workflowPath}`,
35449
+ "No files were changed. Re-run with --write after reviewing the generated workflow."
35450
+ ].join(`
35451
+ `));
35452
+ if (provider === "gitlab" && existsSync21(workflowPath)) {
35453
+ throw new Error(`Refusing to overwrite existing GitLab workflow: ${workflowPath}`);
35454
+ }
35455
+ await mkdir11(resolve31(workflowPath, ".."), { recursive: true });
35456
+ await writeFile11(workflowPath, workflow(provider, args.preview === true), { encoding: "utf8", mode: 420 });
35457
+ return jsonResult5({ ...result, written: true });
35458
+ }
35459
+ function registerPipelineTools(server, options = {}) {
35460
+ registerTool(server, "pipeline", "Generate a provider workflow for deployment and optional PR Preview lifecycle.", pipelineToolSchema, (args) => connectPipeline(args, options));
34748
35461
  }
34749
35462
 
34750
35463
  // src/shared/tools/project-deployment.ts
@@ -34872,7 +35585,7 @@ async function runProjectDeployment(http, args) {
34872
35585
  // package.json
34873
35586
  var package_default = {
34874
35587
  name: "@supacloud/cli",
34875
- version: "0.121.8",
35588
+ version: "0.123.1",
34876
35589
  description: "Project-scoped CLI for SupaCloud users",
34877
35590
  type: "module",
34878
35591
  main: "./dist/index.js",
@@ -34924,26 +35637,26 @@ var package_default = {
34924
35637
  directory: "packages/cli"
34925
35638
  },
34926
35639
  dependencies: {
34927
- "@supacloud/compiler": "^0.62.6",
35640
+ "@supacloud/compiler": "^0.62.7",
34928
35641
  "@supacloud/delivery": "0.28.0",
34929
- "@supacloud/db": "0.24.2",
35642
+ "@supacloud/db": "0.25.1",
34930
35643
  typebox: "1.4.3"
34931
35644
  },
34932
35645
  overrides: {
34933
35646
  "@supacloud/contracts": "0.16.2",
34934
35647
  "@supacloud/delivery": "0.28.0",
34935
35648
  "@graphql-tools/utils": "^12.0.4",
34936
- "@supacloud/compiler": "^0.62.6",
34937
- "@supacloud/db": "0.24.2",
35649
+ "@supacloud/compiler": "^0.62.7",
35650
+ "@supacloud/db": "0.25.1",
34938
35651
  "deepmerge-ts": "8.0.2",
34939
35652
  prisma: "6.19.3"
34940
35653
  },
34941
35654
  devDependencies: {
34942
35655
  "@supabase/supabase-js": "2.118.0",
34943
- "@supacloud/elysia": "0.42.4",
35656
+ "@supacloud/elysia": "0.42.5",
34944
35657
  "@types/bun": "^1.4.4",
34945
35658
  effect: "4.0.5",
34946
- elysia: "2.0.0-rc.3",
35659
+ elysia: "2.0.0-rc.4",
34947
35660
  typescript: "7.1.0-beta"
34948
35661
  }
34949
35662
  };
@@ -35113,6 +35826,9 @@ USAGE
35113
35826
  ${preferredCommand} [global flags] deploy [--flags]
35114
35827
  ${preferredCommand} [global flags] <module> <action> [--flags]
35115
35828
  ${preferredCommand} deploy init [--root <directory>]
35829
+ ${preferredCommand} onboard [--profile solo] [--domain <domain>] [--write]
35830
+ ${preferredCommand} config <doctor|explain>
35831
+ ${preferredCommand} pipeline connect [--write] [--preview]
35116
35832
  ${preferredCommand} env <list|check> [--root <directory>]
35117
35833
  ${preferredCommand} [global flags] status
35118
35834
  ${preferredCommand} --help
@@ -35147,7 +35863,11 @@ DEFAULT CONTEXT
35147
35863
  EXAMPLES
35148
35864
 
35149
35865
  ${preferredCommand} deploy init
35866
+ ${preferredCommand} onboard
35867
+ ${preferredCommand} config doctor --format json
35868
+ ${preferredCommand} config explain --key SUPACLOUD_API_URL
35150
35869
  ${preferredCommand} env check
35870
+ ${preferredCommand} env sync --env test --write
35151
35871
  ${preferredCommand} env check --format json
35152
35872
  ${preferredCommand} status
35153
35873
  ${preferredCommand} deploy
@@ -35304,6 +36024,13 @@ function createCliTools(context, confirmProduction) {
35304
36024
  cwd: process.cwd(),
35305
36025
  activeContext: context
35306
36026
  })));
36027
+ Object.assign(tools, captureTools((server) => registerConfigurationTools(server, {
36028
+ cwd: process.cwd(),
36029
+ activeContext: context
36030
+ })));
36031
+ Object.assign(tools, captureTools((server) => registerPipelineTools(server, {
36032
+ cwd: process.cwd()
36033
+ })));
35307
36034
  Object.assign(tools, captureTools((server) => registerAppTools(server, { onDevProgress: writeDevProgress })));
35308
36035
  Object.assign(tools, captureTools((server) => registerDbGovernanceTools(server, {
35309
36036
  projectRef: context.projectRef || undefined,