@supacloud/cli 0.123.1 → 0.124.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -9131,6 +9131,26 @@ function inferProjectRefFromSupabaseUrl(value) {
9131
9131
  return "";
9132
9132
  return new URL(value).hostname.match(/^([a-z0-9-]+)\.api\./i)?.[1] ?? "";
9133
9133
  }
9134
+ function inferManagementApiUrlFromSupabaseUrl(value, projectRef = "") {
9135
+ if (!value)
9136
+ return "";
9137
+ const url = new URL(value);
9138
+ const host = url.hostname;
9139
+ if (host.startsWith("api.")) {
9140
+ url.hostname = `studio.${host.slice("api.".length)}`;
9141
+ return url.origin;
9142
+ }
9143
+ const ref = projectRef.trim();
9144
+ if (ref && host.startsWith(`${ref}.api.`)) {
9145
+ url.hostname = `studio-${ref}.${host.slice(`${ref}.api.`.length)}`;
9146
+ return url.origin;
9147
+ }
9148
+ const managedHost = host.match(/^([a-z0-9-]+)\.api\.(.+)$/i);
9149
+ if (!managedHost)
9150
+ return "";
9151
+ url.hostname = `studio-${managedHost[1]}.${managedHost[2]}`;
9152
+ return url.origin;
9153
+ }
9134
9154
  function sourceCredentialScope(values, explicitApiUrl, supabaseUrl) {
9135
9155
  const hasManagementContext = Boolean(explicitApiUrl.trim() || values.SUPACLOUD_API_TOKEN?.trim() || values.SUPACLOUD_HOST?.trim());
9136
9156
  if (hasManagementContext)
@@ -9142,7 +9162,7 @@ function sourceProjectCore(values) {
9142
9162
  const projectRef = (values.SUPACLOUD_PROJECT_REF || "").trim() || inferProjectRefFromSupabaseUrl(supabaseUrl);
9143
9163
  const explicitApiUrl = values.SUPACLOUD_API_URL || "";
9144
9164
  const credentialScope = sourceCredentialScope(values, explicitApiUrl, supabaseUrl);
9145
- const managementUrl = explicitApiUrl || (values.SUPACLOUD_HOST ? `http://${values.SUPACLOUD_HOST}:9090` : "");
9165
+ const managementUrl = explicitApiUrl || (credentialScope === "management" ? inferManagementApiUrlFromSupabaseUrl(supabaseUrl, projectRef) : "") || (values.SUPACLOUD_HOST ? `http://${values.SUPACLOUD_HOST}:9090` : "");
9146
9166
  const apiUrl = credentialScope === "management" ? canonicalApiOrigin(managementUrl) : "";
9147
9167
  const apiToken = credentialScope === "management" ? values.SUPACLOUD_API_TOKEN || "" : "";
9148
9168
  return { apiUrl, apiToken, projectRef, supabaseUrl, credentialScope };
@@ -9402,7 +9422,7 @@ var ACTION_POLICY = {
9402
9422
  edge_functions: {
9403
9423
  read: ["list", "get_config", "source"],
9404
9424
  local: ["check", "scaffold"],
9405
- write: ["deploy", "deploy_bundle", "config", "activate", "delete"]
9425
+ write: ["deploy", "deploy_bundle", "deploy_manifest", "config", "activate", "delete"]
9406
9426
  },
9407
9427
  scheduled_functions: { read: ["list", "get"], write: ["create", "update", "delete"] },
9408
9428
  mutations: { read: ["status"] },
@@ -15578,20 +15598,20 @@ import { createHash as createHash6, timingSafeEqual } from "node:crypto";
15578
15598
  import {
15579
15599
  closeSync,
15580
15600
  constants as fsConstants,
15581
- existsSync as existsSync5,
15601
+ existsSync as existsSync6,
15582
15602
  fstatSync,
15583
15603
  lstatSync,
15584
15604
  mkdirSync,
15585
- mkdtempSync,
15605
+ mkdtempSync as mkdtempSync2,
15586
15606
  openSync,
15587
- readFileSync as readFileSync6,
15607
+ readFileSync as readFileSync7,
15588
15608
  readdirSync as readdirSync3,
15589
- rmSync,
15609
+ rmSync as rmSync2,
15590
15610
  statSync as statSync4,
15591
15611
  writeFileSync
15592
15612
  } from "node:fs";
15593
- import { tmpdir } from "node:os";
15594
- import { basename as basename5, join as join5, relative as relative2, resolve as resolve7, sep as sep2 } from "node:path";
15613
+ import { tmpdir as tmpdir2 } from "node:os";
15614
+ import { basename as basename6, join as join6, relative as relative3, resolve as resolve8, sep as sep3 } from "node:path";
15595
15615
 
15596
15616
  // src/shared/tools/function-aot.ts
15597
15617
  import { execFile } from "node:child_process";
@@ -15910,6 +15930,358 @@ function confirmedFunctionDeletion(payload, expectation) {
15910
15930
  };
15911
15931
  }
15912
15932
 
15933
+ // src/shared/tools/project-function-release.ts
15934
+ import { existsSync as existsSync5, mkdtempSync, readFileSync as readFileSync6, rmSync } from "node:fs";
15935
+ import { tmpdir } from "node:os";
15936
+ import { basename as basename5, join as join5, relative as relative2, resolve as resolve7, sep as sep2 } from "node:path";
15937
+ var SAFE_SLUG_PATTERN2 = /^[A-Za-z0-9_-]{1,128}$/;
15938
+ var RELEASE_ID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
15939
+ var POSITIVE_VERSION_PATTERN = /^[1-9][0-9]*$/;
15940
+ var ARTIFACT_SHA256_PATTERN = /^[a-f0-9]{64}$/;
15941
+ var FRAMEWORKS = ["fetch", "elysia", "hono", "sveltekit-function"];
15942
+ var MAX_MANIFEST_BYTES = 1024 * 1024;
15943
+ var MAX_FUNCTIONS = 128;
15944
+ var RELEASE_OPERATION = "edge_functions.deploy_manifest";
15945
+ function record5(candidate) {
15946
+ return candidate !== null && typeof candidate === "object" && !Array.isArray(candidate) ? candidate : null;
15947
+ }
15948
+ function requiredString(candidate, field) {
15949
+ if (typeof candidate !== "string" || !candidate.trim())
15950
+ throw new Error(`Manifest field '${field}' is required`);
15951
+ return candidate.trim();
15952
+ }
15953
+ function optionalString(candidate, field) {
15954
+ if (candidate === undefined)
15955
+ return;
15956
+ return requiredString(candidate, field);
15957
+ }
15958
+ function validStringArray(candidate, field) {
15959
+ if (candidate === undefined)
15960
+ return;
15961
+ if (!Array.isArray(candidate) || candidate.some((value) => typeof value !== "string" || !value.trim())) {
15962
+ throw new Error(`Manifest field '${field}' must be an array of strings`);
15963
+ }
15964
+ return candidate.map((value) => value.trim());
15965
+ }
15966
+ function validObject(candidate, field) {
15967
+ if (candidate === undefined)
15968
+ return;
15969
+ const value = record5(candidate);
15970
+ if (!value)
15971
+ throw new Error(`Manifest field '${field}' must be an object`);
15972
+ return value;
15973
+ }
15974
+ function functionCapabilities(candidate) {
15975
+ const value = validObject(candidate, "capabilities");
15976
+ if (!value)
15977
+ return;
15978
+ const result = {};
15979
+ for (const field of ["secrets", "outbound_hosts", "bindings"]) {
15980
+ const entries = value[field];
15981
+ if (entries === undefined)
15982
+ continue;
15983
+ if (!Array.isArray(entries) || entries.some((entry) => typeof entry !== "string" || !entry.trim())) {
15984
+ throw new Error(`Manifest field 'capabilities.${field}' must be an array of strings`);
15985
+ }
15986
+ result[field] = entries.map((entry) => entry.trim());
15987
+ }
15988
+ if (value.background !== undefined) {
15989
+ if (typeof value.background !== "boolean")
15990
+ throw new Error("Manifest field 'capabilities.background' must be boolean");
15991
+ result.background = value.background;
15992
+ }
15993
+ return result;
15994
+ }
15995
+ function functionLimits(candidate) {
15996
+ const value = validObject(candidate, "limits");
15997
+ if (!value)
15998
+ return;
15999
+ const result = {};
16000
+ for (const field of ["timeout_ms", "max_request_body_bytes", "max_response_body_bytes", "wait_until_timeout_ms", "max_heap_bytes"]) {
16001
+ const entry = value[field];
16002
+ if (entry === undefined)
16003
+ continue;
16004
+ if (typeof entry !== "number" || !Number.isSafeInteger(entry) || entry < 1) {
16005
+ throw new Error(`Manifest field 'limits.${field}' must be a positive safe integer`);
16006
+ }
16007
+ result[field] = entry;
16008
+ }
16009
+ return result;
16010
+ }
16011
+ function parseManifest(path) {
16012
+ const source = readFileSync6(resolve7(path), "utf8");
16013
+ if (Buffer.byteLength(source) > MAX_MANIFEST_BYTES)
16014
+ throw new Error("Function release manifest exceeds 1 MiB");
16015
+ let parsed;
16016
+ try {
16017
+ parsed = JSON.parse(source);
16018
+ } catch {
16019
+ throw new Error("Function release manifest must be valid JSON");
16020
+ }
16021
+ const root = record5(parsed);
16022
+ const entries = root?.functions;
16023
+ if (!Array.isArray(entries) || entries.length < 1 || entries.length > MAX_FUNCTIONS) {
16024
+ throw new Error("Function release manifest must contain 1-128 functions");
16025
+ }
16026
+ const slugs = new Set;
16027
+ return entries.map((candidate) => {
16028
+ const value = record5(candidate);
16029
+ if (!value)
16030
+ throw new Error("Function release manifest contains an invalid function");
16031
+ const slug = requiredString(value.slug, "slug");
16032
+ if (!SAFE_SLUG_PATTERN2.test(slug) || slug === "_project-release" || slugs.has(slug)) {
16033
+ throw new Error(`Function release manifest contains an invalid or duplicate slug '${slug}'`);
16034
+ }
16035
+ slugs.add(slug);
16036
+ const entrypoint = requiredString(value.entrypoint, "entrypoint");
16037
+ if (entrypoint.startsWith("/") || entrypoint.split(/[\\/]/u).includes("..")) {
16038
+ throw new Error(`Manifest entrypoint must stay within the project: ${entrypoint}`);
16039
+ }
16040
+ const framework = optionalString(value.framework, "framework");
16041
+ if (framework !== undefined && !FRAMEWORKS.includes(framework)) {
16042
+ throw new Error(`Manifest field 'framework' is invalid for '${slug}'`);
16043
+ }
16044
+ const bytecode = optionalString(value.bytecode, "bytecode");
16045
+ if (bytecode !== undefined && !["off", "auto", "required"].includes(bytecode)) {
16046
+ throw new Error(`Manifest field 'bytecode' is invalid for '${slug}'`);
16047
+ }
16048
+ if (value.verify_jwt !== undefined && typeof value.verify_jwt !== "boolean") {
16049
+ throw new Error(`Manifest field 'verify_jwt' must be boolean for '${slug}'`);
16050
+ }
16051
+ const verifyJwt = value.verify_jwt;
16052
+ const backgroundRoutes = validStringArray(value.backgroundRoutes ?? value.background_routes, "background_routes");
16053
+ const capabilities = functionCapabilities(value.capabilities);
16054
+ const limits = functionLimits(value.limits);
16055
+ return {
16056
+ slug,
16057
+ entrypoint,
16058
+ ...verifyJwt === undefined ? {} : { verify_jwt: verifyJwt },
16059
+ ...bytecode === undefined ? {} : { bytecode },
16060
+ ...backgroundRoutes === undefined ? {} : { background_routes: backgroundRoutes },
16061
+ ...framework === undefined ? {} : { framework },
16062
+ ...capabilities === undefined ? {} : { capabilities },
16063
+ ...limits === undefined ? {} : { limits }
16064
+ };
16065
+ });
16066
+ }
16067
+ function projectPath(ref, suffix) {
16068
+ return `/v1/projects/${projectRefPathSegment(ref, "Function release")}${suffix}`;
16069
+ }
16070
+ function validUuid(candidate) {
16071
+ return typeof candidate === "string" && RELEASE_ID_PATTERN.test(candidate);
16072
+ }
16073
+ function positiveVersion(candidate) {
16074
+ return typeof candidate === "string" && POSITIVE_VERSION_PATTERN.test(candidate) && Number.isSafeInteger(Number(candidate));
16075
+ }
16076
+ function parseReleaseStatus(payload, projectRef) {
16077
+ const value = record5(payload);
16078
+ if (!value || value.project_ref !== projectRef || value.active_release_id !== null && !validUuid(value.active_release_id) || !Array.isArray(value.functions))
16079
+ return null;
16080
+ const slugs = new Set;
16081
+ const functions = [];
16082
+ for (const candidate of value.functions) {
16083
+ const entry = record5(candidate);
16084
+ if (!entry || typeof entry.slug !== "string" || !SAFE_SLUG_PATTERN2.test(entry.slug) || slugs.has(entry.slug) || !positiveVersion(entry.version) || !validObservedFunctionActivationId(entry.activation_id))
16085
+ return null;
16086
+ slugs.add(entry.slug);
16087
+ functions.push({
16088
+ slug: entry.slug,
16089
+ version: entry.version,
16090
+ activation_id: entry.activation_id
16091
+ });
16092
+ }
16093
+ return {
16094
+ project_ref: projectRef,
16095
+ active_release_id: value.active_release_id,
16096
+ functions
16097
+ };
16098
+ }
16099
+ function stageCodePath(entrypoint, bundlesDir, slug) {
16100
+ if (bundlesDir) {
16101
+ const bundleRoot = resolve7(bundlesDir);
16102
+ const candidate = join5(bundleRoot, `${slug}.js`);
16103
+ if (!existsSync5(candidate))
16104
+ throw new Error(`Prebuilt Function bundle is missing: ${candidate}`);
16105
+ return candidate;
16106
+ }
16107
+ const projectRoot = process.cwd();
16108
+ const candidate = resolve7(projectRoot, entrypoint);
16109
+ const relativePath = relative2(projectRoot, candidate);
16110
+ if (!relativePath || relativePath.startsWith(`..${sep2}`) || relativePath === "..") {
16111
+ throw new Error(`Manifest entrypoint must stay within the project: ${entrypoint}`);
16112
+ }
16113
+ if (!existsSync5(candidate))
16114
+ throw new Error(`Function entrypoint does not exist: ${candidate}`);
16115
+ return candidate;
16116
+ }
16117
+ async function bundleSource(entrypoint, bundlesDir, slug) {
16118
+ const sourcePath = stageCodePath(entrypoint, bundlesDir, slug);
16119
+ if (bundlesDir)
16120
+ return readFileSync6(sourcePath, "utf8");
16121
+ const directory = mkdtempSync(join5(tmpdir(), "supacloud-function-release-"));
16122
+ const output = join5(directory, `${basename5(sourcePath).replace(/\.[^.]+$/u, "") || "index"}.js`);
16123
+ try {
16124
+ const process2 = Bun.spawn(["bun", "build", sourcePath, "--target", "bun", "--outfile", output], {
16125
+ stdout: "pipe",
16126
+ stderr: "pipe"
16127
+ });
16128
+ const [stdout, stderr, exitCode] = await Promise.all([
16129
+ new Response(process2.stdout).text(),
16130
+ new Response(process2.stderr).text(),
16131
+ process2.exited
16132
+ ]);
16133
+ if (exitCode !== 0)
16134
+ throw new Error(`Failed to bundle '${slug}': ${stderr || stdout}`);
16135
+ return readFileSync6(output, "utf8");
16136
+ } finally {
16137
+ rmSync(directory, { recursive: true, force: true });
16138
+ }
16139
+ }
16140
+ function stageConfig(entry) {
16141
+ return {
16142
+ ...entry.verify_jwt === undefined ? {} : { verify_jwt: entry.verify_jwt },
16143
+ ...entry.bytecode === undefined ? {} : { bytecode: entry.bytecode },
16144
+ ...entry.background_routes === undefined ? {} : { background_routes: entry.background_routes },
16145
+ ...entry.framework === undefined ? {} : { framework: entry.framework },
16146
+ ...entry.capabilities === undefined ? {} : { capabilities: entry.capabilities },
16147
+ ...entry.limits === undefined ? {} : { limits: entry.limits }
16148
+ };
16149
+ }
16150
+ function stagedVersion(payload) {
16151
+ const value = record5(payload);
16152
+ if (!value || !positiveVersion(value.version) || typeof value.artifact_sha256 !== "string" || !ARTIFACT_SHA256_PATTERN.test(value.artifact_sha256))
16153
+ return null;
16154
+ return value.version;
16155
+ }
16156
+ function releaseReceipt(payload, projectRef, mutationId, expectedMembers) {
16157
+ const value = record5(payload);
16158
+ if (!value || value.project_ref !== projectRef || value.active_release_id !== mutationId || typeof value.generation !== "number" || !Number.isSafeInteger(value.generation) || value.generation < 1 || !Array.isArray(value.functions) || value.functions.length !== expectedMembers.length)
16159
+ return null;
16160
+ const observed = new Map;
16161
+ for (const candidate of value.functions) {
16162
+ const entry = record5(candidate);
16163
+ if (!entry || typeof entry.slug !== "string" || !SAFE_SLUG_PATTERN2.test(entry.slug) || observed.has(entry.slug) || !positiveVersion(entry.version) || !validObservedFunctionActivationId(entry.activation_id))
16164
+ return null;
16165
+ observed.set(entry.slug, {
16166
+ slug: entry.slug,
16167
+ version: entry.version,
16168
+ activation_id: entry.activation_id
16169
+ });
16170
+ }
16171
+ for (const expected of expectedMembers) {
16172
+ const actual = observed.get(expected.slug);
16173
+ if (!actual || actual.version !== expected.version)
16174
+ return null;
16175
+ }
16176
+ const mutation = record5(value.mutation);
16177
+ if (!mutation || mutation.mutation_id !== mutationId || mutation.status !== "succeeded")
16178
+ return null;
16179
+ return {
16180
+ project_ref: projectRef,
16181
+ mutation_id: mutationId,
16182
+ active_release_id: mutationId,
16183
+ generation: value.generation,
16184
+ functions: [...observed.values()],
16185
+ mutation: { mutation_id: mutationId, status: "succeeded" }
16186
+ };
16187
+ }
16188
+ function requiredArg(args, name) {
16189
+ const value = args[name];
16190
+ if (typeof value !== "string" || !value.trim())
16191
+ throw new Error(`'--${name}' is required`);
16192
+ return value.trim();
16193
+ }
16194
+ async function deployFunctionManifest(http, args, options = {}) {
16195
+ if (options.readOnly) {
16196
+ return { isError: true, content: [{ type: "text", text: "⚠️ Edge Function release publication blocked in read-only mode." }] };
16197
+ }
16198
+ if (args.atomic !== true)
16199
+ throw new Error("'--atomic' is required for 'deploy_manifest'");
16200
+ const projectRef = requiredArg(args, "ref");
16201
+ const manifestPath = requiredArg(args, "manifest");
16202
+ const bundlesDir = typeof args["bundles-dir"] === "string" ? args["bundles-dir"].trim() : undefined;
16203
+ const mutationId = typeof args["mutation-id"] === "string" && args["mutation-id"].trim() ? args["mutation-id"].trim() : crypto.randomUUID();
16204
+ if (!validUuid(mutationId))
16205
+ throw new Error("'--mutation-id' must be a UUIDv4");
16206
+ const entries = parseManifest(manifestPath);
16207
+ const statusResponse = await http.get(projectPath(projectRef, "/function-releases"), { maxJsonBytes: 256 * 1024 });
16208
+ const status = parseReleaseStatus(statusResponse.data, projectRef);
16209
+ if (!statusResponse.ok || !status) {
16210
+ return releaseControlFailure(RELEASE_OPERATION, "INVALID_RESPONSE", statusResponse.status, { project_ref: projectRef, mutation_id: mutationId });
16211
+ }
16212
+ const requested = new Map(entries.map((entry) => [entry.slug, entry]));
16213
+ const memberVersions = new Map(status.functions.map((entry) => [entry.slug, entry]));
16214
+ const staged = [];
16215
+ for (const entry of entries) {
16216
+ const identityResponse = await http.get(projectPath(projectRef, `/functions/${encodeURIComponent(entry.slug)}/config`), {
16217
+ maxJsonBytes: 128 * 1024
16218
+ });
16219
+ const identity = projectedFunctionIdentity(identityResponse.data, projectRef, entry.slug);
16220
+ if (!identityResponse.ok || !identity) {
16221
+ return releaseControlFailure(RELEASE_OPERATION, "INVALID_RESPONSE", identityResponse.status, {
16222
+ project_ref: projectRef,
16223
+ mutation_id: mutationId,
16224
+ slug: entry.slug
16225
+ });
16226
+ }
16227
+ const code = await bundleSource(entry.entrypoint, bundlesDir, entry.slug);
16228
+ const stageResponse = await http.postReleaseMutation(projectPath(projectRef, `/functions/${encodeURIComponent(entry.slug)}/stage`), { code, config: stageConfig(entry) }, { timeoutMs: 5 * 60000 });
16229
+ const version = stagedVersion(stageResponse.data);
16230
+ if (!stageResponse.ok) {
16231
+ return releaseControlMutationFailure(RELEASE_OPERATION, stageResponse, {
16232
+ project_ref: projectRef,
16233
+ mutation_id: mutationId,
16234
+ slug: entry.slug
16235
+ });
16236
+ }
16237
+ if (!version) {
16238
+ return releaseControlFailure(RELEASE_OPERATION, "OUTCOME_UNKNOWN", stageResponse.status, {
16239
+ project_ref: projectRef,
16240
+ mutation_id: mutationId,
16241
+ slug: entry.slug
16242
+ });
16243
+ }
16244
+ staged.push({ slug: entry.slug, version, expected_activation_id: identity.activation_id });
16245
+ }
16246
+ const members = new Map([...memberVersions.values()].map((member) => [
16247
+ member.slug,
16248
+ { slug: member.slug, version: member.version, expected_activation_id: member.activation_id }
16249
+ ]));
16250
+ for (const member of staged)
16251
+ members.set(member.slug, member);
16252
+ const missing = [...memberVersions.keys()].filter((slug) => !requested.has(slug));
16253
+ const releaseResponse = await http.postReleaseMutation(projectPath(projectRef, "/function-releases"), {
16254
+ mutation_id: mutationId,
16255
+ expected_release_id: status.active_release_id,
16256
+ functions: [...members.values()].sort((left, right) => left.slug.localeCompare(right.slug))
16257
+ }, { timeoutMs: 5 * 60000 });
16258
+ if (!releaseResponse.ok) {
16259
+ return releaseControlMutationFailure(RELEASE_OPERATION, releaseResponse, {
16260
+ project_ref: projectRef,
16261
+ mutation_id: mutationId,
16262
+ expected_release_id: status.active_release_id,
16263
+ staged_functions: staged.map(({ slug, version }) => ({ slug, version })),
16264
+ retained_functions: missing
16265
+ });
16266
+ }
16267
+ const receipt = releaseReceipt(releaseResponse.data, projectRef, mutationId, [...members.values()]);
16268
+ if (!receipt) {
16269
+ return releaseControlFailure(RELEASE_OPERATION, "OUTCOME_UNKNOWN", releaseResponse.status, {
16270
+ project_ref: projectRef,
16271
+ mutation_id: mutationId,
16272
+ expected_release_id: status.active_release_id,
16273
+ staged_functions: staged.map(({ slug, version }) => ({ slug, version })),
16274
+ retained_functions: missing
16275
+ });
16276
+ }
16277
+ return releaseControlSuccess(RELEASE_OPERATION, {
16278
+ ...receipt,
16279
+ expected_release_id: status.active_release_id,
16280
+ staged_functions: staged.map(({ slug, version }) => ({ slug, version })),
16281
+ retained_functions: missing
16282
+ });
16283
+ }
16284
+
15913
16285
  // src/shared/tools/advanced-tools.ts
15914
16286
  var SHA256_HEX_PATTERN = /^[a-f0-9]{64}$/;
15915
16287
  var FORBIDDEN_BUNDLE_SEGMENTS = new Set(["node_modules", ".git"]);
@@ -15987,13 +16359,13 @@ function scaffoldFunction(pathArg, slug, framework) {
15987
16359
  if (typeof framework !== "string" || !FUNCTION_FRAMEWORKS2.includes(framework)) {
15988
16360
  throw new Error("'framework' required for 'scaffold'");
15989
16361
  }
15990
- const target = resolve7(typeof pathArg === "string" ? pathArg : join5("supabase", "functions", slug));
15991
- if (existsSync5(target))
16362
+ const target = resolve8(typeof pathArg === "string" ? pathArg : join6("supabase", "functions", slug));
16363
+ if (existsSync6(target))
15992
16364
  throw new Error(`Scaffold target already exists: ${target}`);
15993
16365
  const files = scaffoldFiles(framework, slug);
15994
16366
  for (const [relativePath, contents] of Object.entries(files)) {
15995
- const destination = join5(target, relativePath);
15996
- mkdirSync(resolve7(destination, ".."), { recursive: true });
16367
+ const destination = join6(target, relativePath);
16368
+ mkdirSync(resolve8(destination, ".."), { recursive: true });
15997
16369
  writeFileSync(destination, contents, { flag: "wx" });
15998
16370
  }
15999
16371
  return JSON.stringify({ success: true, framework, path: target, files: Object.keys(files) }, null, 2);
@@ -16038,10 +16410,10 @@ function assertExpectedSha256(bytes, expectedSha256) {
16038
16410
  }
16039
16411
  }
16040
16412
  function readVerifiedPrebundledCode(pathArg, expectedSha256) {
16041
- const descriptor = openSync(resolve7(pathArg), fsConstants.O_RDONLY | fsConstants.O_NONBLOCK);
16413
+ const descriptor = openSync(resolve8(pathArg), fsConstants.O_RDONLY | fsConstants.O_NONBLOCK);
16042
16414
  try {
16043
16415
  const identityBeforeRead = openFileIdentity(descriptor);
16044
- const bytes = readFileSync6(descriptor);
16416
+ const bytes = readFileSync7(descriptor);
16045
16417
  const identityAfterRead = openFileIdentity(descriptor);
16046
16418
  if (BigInt(bytes.byteLength) !== identityBeforeRead.size || !sameOpenFile(identityBeforeRead, identityAfterRead)) {
16047
16419
  throw new Error("Prebundled file changed while it was being read");
@@ -16053,7 +16425,7 @@ function readVerifiedPrebundledCode(pathArg, expectedSha256) {
16053
16425
  }
16054
16426
  }
16055
16427
  function canonicalBundlePath(root, filePath) {
16056
- const bundlePath = relative2(root, filePath).split(sep2).join("/");
16428
+ const bundlePath = relative3(root, filePath).split(sep3).join("/");
16057
16429
  const segments = bundlePath.split("/");
16058
16430
  if (!bundlePath || bundlePath.startsWith("/") || segments.some((segment) => !segment || segment === "." || segment === ".." || segment.startsWith("._") || FORBIDDEN_BUNDLE_SEGMENTS.has(segment))) {
16059
16431
  throw new Error(`Bundle directory contains a forbidden path: ${bundlePath || filePath}`);
@@ -16064,7 +16436,7 @@ function readBundleDirectory(root, directory = root) {
16064
16436
  const files = {};
16065
16437
  const entries = readdirSync3(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));
16066
16438
  for (const entry of entries) {
16067
- const entryPath = join5(directory, entry.name);
16439
+ const entryPath = join6(directory, entry.name);
16068
16440
  const bundlePath = canonicalBundlePath(root, entryPath);
16069
16441
  const entryState = lstatSync(entryPath);
16070
16442
  if (entryState.isSymbolicLink())
@@ -16075,7 +16447,7 @@ function readBundleDirectory(root, directory = root) {
16075
16447
  }
16076
16448
  if (!entryState.isFile())
16077
16449
  throw new Error(`Bundle directory must contain only regular files: ${bundlePath}`);
16078
- files[bundlePath] = verifiedUtf8Code(readFileSync6(entryPath));
16450
+ files[bundlePath] = verifiedUtf8Code(readFileSync7(entryPath));
16079
16451
  }
16080
16452
  return files;
16081
16453
  }
@@ -16087,7 +16459,7 @@ function preparedBundleFiles(args) {
16087
16459
  }
16088
16460
  if (typeof bundleDirectory !== "string")
16089
16461
  return files;
16090
- const resolvedDirectory = resolve7(bundleDirectory);
16462
+ const resolvedDirectory = resolve8(bundleDirectory);
16091
16463
  const rootState = lstatSync(resolvedDirectory);
16092
16464
  if (rootState.isSymbolicLink() || !rootState.isDirectory()) {
16093
16465
  throw new Error("'--bundle-dir' must be a regular directory and must not be a symlink");
@@ -16125,8 +16497,8 @@ async function runBunBuild(args) {
16125
16497
  }
16126
16498
  async function bundleEdgeFunctionPath(pathArg) {
16127
16499
  const entrypoint = resolveEntrypoint(pathArg);
16128
- const tmpDir = mkdtempSync(join5(tmpdir(), "supacloud-edge-"));
16129
- const outfile = join5(tmpDir, `${basename5(entrypoint).replace(/\.[^.]+$/, "") || "index"}.js`);
16500
+ const tmpDir = mkdtempSync2(join6(tmpdir2(), "supacloud-edge-"));
16501
+ const outfile = join6(tmpDir, `${basename6(entrypoint).replace(/\.[^.]+$/, "") || "index"}.js`);
16130
16502
  try {
16131
16503
  const { stderr } = await runBunBuild([entrypoint, "--target", "bun", "--outfile", outfile]);
16132
16504
  const outFileHandle = Bun.file(outfile);
@@ -16134,7 +16506,7 @@ async function bundleEdgeFunctionPath(pathArg) {
16134
16506
  throw new Error(`Bundle failed: ${stderr}`);
16135
16507
  return await outFileHandle.text();
16136
16508
  } finally {
16137
- rmSync(tmpDir, { recursive: true, force: true });
16509
+ rmSync2(tmpDir, { recursive: true, force: true });
16138
16510
  }
16139
16511
  }
16140
16512
  function prebundledDeployCode(pathArg, expectedSha256, minify) {
@@ -16169,14 +16541,14 @@ async function preparedDeployCode(args) {
16169
16541
  if (typeof pathArg !== "string")
16170
16542
  throw new Error("Function deploy source is invalid");
16171
16543
  if (args.aot === true) {
16172
- const directory = mkdtempSync(join5(tmpdir(), "supacloud-function-aot-"));
16544
+ const directory = mkdtempSync2(join6(tmpdir2(), "supacloud-function-aot-"));
16173
16545
  try {
16174
- return await buildFunctionAot(resolveEntrypoint(pathArg), join5(directory, "index.js"), {
16546
+ return await buildFunctionAot(resolveEntrypoint(pathArg), join6(directory, "index.js"), {
16175
16547
  ...typeof args["aot-entry"] === "string" ? { appEntry: args["aot-entry"] } : {},
16176
16548
  minify: args.minify === true
16177
16549
  });
16178
16550
  } finally {
16179
- rmSync(directory, { recursive: true, force: true });
16551
+ rmSync2(directory, { recursive: true, force: true });
16180
16552
  }
16181
16553
  }
16182
16554
  return bundledDeployCode(pathArg);
@@ -16200,12 +16572,12 @@ function rejectActionSpecificFlags(action, args) {
16200
16572
  }
16201
16573
  }
16202
16574
  function resolveEntrypoint(pathArg) {
16203
- const resolved = resolve7(pathArg);
16575
+ const resolved = resolve8(pathArg);
16204
16576
  const stat = statSync4(resolved);
16205
16577
  if (!stat.isDirectory())
16206
16578
  return resolved;
16207
- const entrypoint = join5(resolved, "index.ts");
16208
- if (!existsSync5(entrypoint)) {
16579
+ const entrypoint = join6(resolved, "index.ts");
16580
+ if (!existsSync6(entrypoint)) {
16209
16581
  throw new Error(`Directory provided but no index.ts found at ${entrypoint}`);
16210
16582
  }
16211
16583
  return entrypoint;
@@ -16513,7 +16885,7 @@ function functionSourceOutput(slug, sourceCode, output) {
16513
16885
  if (!output) {
16514
16886
  return { content: [{ type: "text", text: JSON.stringify({ code: sourceCode }, null, 2) }] };
16515
16887
  }
16516
- const outputPath = resolve7(output);
16888
+ const outputPath = resolve8(output);
16517
16889
  writeFileSync(outputPath, sourceCode, { flag: "wx" });
16518
16890
  return {
16519
16891
  content: [{
@@ -16685,8 +17057,8 @@ async function activateFunctionVersion(http, args, readOnly = false) {
16685
17057
  }
16686
17058
  function registerAdvancedTools(server, http, environment = process.env, options = {}) {
16687
17059
  registerTool(server, "edge_functions", `Edge Function management (Deno/Bun serverless). Source deploys are bundled; verified prebuilt artifacts stay byte-exact.
16688
- Actions: list, get_config, deploy, deploy_bundle, config, source, activate, delete, check, scaffold`, {
16689
- action: withDescription(stringEnum2(["list", "get_config", "deploy", "deploy_bundle", "config", "source", "activate", "delete", "check", "scaffold"]), "Action"),
17060
+ Actions: list, get_config, deploy, deploy_bundle, deploy_manifest, config, source, activate, delete, check, scaffold`, {
17061
+ action: withDescription(stringEnum2(["list", "get_config", "deploy", "deploy_bundle", "deploy_manifest", "config", "source", "activate", "delete", "check", "scaffold"]), "Action"),
16690
17062
  ref: optional(String2(), "Project ref (not used by scaffold)"),
16691
17063
  slug: optional(String2(), "[get_config/deploy/deploy_bundle/config/source/activate/delete/check] Function name"),
16692
17064
  version: withDescription(functionVersionSchema, "[source/activate] Existing immutable Function version; source requires a positive version"),
@@ -16710,7 +17082,11 @@ Actions: list, get_config, deploy, deploy_bundle, config, source, activate, dele
16710
17082
  max_request_body_bytes: optional(Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }), "[deploy/deploy_bundle/config] Max inbound request body size in bytes"),
16711
17083
  max_body_size_mb: optional(Integer({ minimum: 1, maximum: 10240 }), "[deploy/deploy_bundle/config] Max inbound request body size in MiB (convenience shorthand)"),
16712
17084
  "expected-active-version": withDescription(expectedActiveVersionSchema, "[deploy/deploy_bundle/activate] Required current active version, or 'absent' when none exists"),
16713
- "expected-activation-id": withDescription(expectedActivationIdSchema, "[deploy/deploy_bundle/config/activate/delete] Required activation ID from list, or 'legacy' for a new or legacy function")
17085
+ "expected-activation-id": withDescription(expectedActivationIdSchema, "[deploy/deploy_bundle/config/activate/delete] Required activation ID from list, or 'legacy' for a new or legacy function"),
17086
+ manifest: optional(String2(), "[deploy_manifest] JSON release manifest path"),
17087
+ "bundles-dir": optional(String2(), "[deploy_manifest] Directory containing prebuilt <slug>.js files"),
17088
+ atomic: optional(Boolean2(), "[deploy_manifest] Required atomic project release publication"),
17089
+ "mutation-id": optional(String2(), "[deploy_manifest] Release mutation correlation UUIDv4")
16714
17090
  }, async (args) => {
16715
17091
  if (args.aot === true && options.readOnly) {
16716
17092
  return {
@@ -16721,6 +17097,8 @@ Actions: list, get_config, deploy, deploy_bundle, config, source, activate, dele
16721
17097
  validateFunctionAot(args);
16722
17098
  if (args.action === "activate")
16723
17099
  return activateFunctionVersion(http, args, options.readOnly);
17100
+ if (args.action === "deploy_manifest")
17101
+ return deployFunctionManifest(http, args, options);
16724
17102
  if (args.action === "scaffold") {
16725
17103
  return { content: [{ type: "text", text: scaffoldFunction(args.path, args.slug, args.framework) }] };
16726
17104
  }
@@ -16765,8 +17143,8 @@ Actions: list, get_config, deploy, deploy_bundle, config, source, activate, dele
16765
17143
  });
16766
17144
  const hasFunctionConfig = () => Object.keys(functionConfig()).length > 0;
16767
17145
  const checkSyntax = async (sourceCode) => {
16768
- const tmpDir = mkdtempSync(join5(tmpdir(), "supacloud-edge-check-"));
16769
- const tmpFile = join5(tmpDir, "index.ts");
17146
+ const tmpDir = mkdtempSync2(join6(tmpdir2(), "supacloud-edge-check-"));
17147
+ const tmpFile = join6(tmpDir, "index.ts");
16770
17148
  writeFileSync(tmpFile, sourceCode);
16771
17149
  try {
16772
17150
  if (/@ts-(?:ignore|nocheck|expect-error)\b/.test(sourceCode)) {
@@ -16788,7 +17166,7 @@ Actions: list, get_config, deploy, deploy_bundle, config, source, activate, dele
16788
17166
  return { ok: false, err: `${stdout}
16789
17167
  ${stderr || message}` };
16790
17168
  } finally {
16791
- rmSync(tmpDir, { recursive: true, force: true });
17169
+ rmSync2(tmpDir, { recursive: true, force: true });
16792
17170
  }
16793
17171
  };
16794
17172
  if (action === "check" && pathArg && !code) {
@@ -17079,7 +17457,7 @@ ${JSON.stringify(r.data, null, 2)}` : `❌ Failed (${r.status}): ${JSON.stringif
17079
17457
  import { createHash as createHash8 } from "node:crypto";
17080
17458
  import { constants as fsConstants2 } from "node:fs";
17081
17459
  import { open as open2 } from "node:fs/promises";
17082
- import { resolve as resolve8 } from "node:path";
17460
+ import { resolve as resolve9 } from "node:path";
17083
17461
 
17084
17462
  // src/shared/mutation-protocol.ts
17085
17463
  import { createHash as createHash7 } from "node:crypto";
@@ -17321,7 +17699,7 @@ async function fetchMutationStatus(http, ref, mutationId) {
17321
17699
  // src/shared/tools/frontend-release-control.ts
17322
17700
  var PROJECT_REF_PATTERN3 = /^[A-Za-z0-9_-]{1,20}$/u;
17323
17701
  var DEPLOYMENT_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/u;
17324
- var RELEASE_ID_PATTERN = /^[0-9a-f]{64}$/u;
17702
+ var RELEASE_ID_PATTERN2 = /^[0-9a-f]{64}$/u;
17325
17703
  var MUTATION_ID_PATTERN2 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
17326
17704
  var TIMESTAMP_PATTERN2 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u;
17327
17705
  var ARCHIVE_MAX_BYTES = 100 * 1024 * 1024;
@@ -17366,7 +17744,7 @@ function releaseRecord(candidate) {
17366
17744
  "kind",
17367
17745
  "archive_format"
17368
17746
  ];
17369
- if (!exactKeys2(record, keys) || record.schema !== FRONTEND_ARCHIVE_RELEASE_SCHEMA || record.archive_format !== FRONTEND_ARCHIVE_FORMAT || typeof record.project_ref !== "string" || !PROJECT_REF_PATTERN3.test(record.project_ref) || typeof record.deployment_id !== "string" || !DEPLOYMENT_ID_PATTERN.test(record.deployment_id) || typeof record.release_id !== "string" || !RELEASE_ID_PATTERN.test(record.release_id) || record.sha256 !== record.release_id || typeof record.tree_sha256 !== "string" || !RELEASE_ID_PATTERN.test(record.tree_sha256) || !Number.isSafeInteger(record.size_bytes) || Number(record.size_bytes) < 1 || !Number.isSafeInteger(record.file_count) || Number(record.file_count) < 1 || !canonicalTimestamp2(record.created_at) || record.kind !== "prebuilt_static")
17747
+ if (!exactKeys2(record, keys) || record.schema !== FRONTEND_ARCHIVE_RELEASE_SCHEMA || record.archive_format !== FRONTEND_ARCHIVE_FORMAT || typeof record.project_ref !== "string" || !PROJECT_REF_PATTERN3.test(record.project_ref) || typeof record.deployment_id !== "string" || !DEPLOYMENT_ID_PATTERN.test(record.deployment_id) || typeof record.release_id !== "string" || !RELEASE_ID_PATTERN2.test(record.release_id) || record.sha256 !== record.release_id || typeof record.tree_sha256 !== "string" || !RELEASE_ID_PATTERN2.test(record.tree_sha256) || !Number.isSafeInteger(record.size_bytes) || Number(record.size_bytes) < 1 || !Number.isSafeInteger(record.file_count) || Number(record.file_count) < 1 || !canonicalTimestamp2(record.created_at) || record.kind !== "prebuilt_static")
17370
17748
  return null;
17371
17749
  return {
17372
17750
  project_ref: record.project_ref,
@@ -17415,9 +17793,9 @@ function releaseInventory(candidate, expected) {
17415
17793
  ];
17416
17794
  if (!exactKeys2(record, keys) || typeof record.project_ref !== "string" || !PROJECT_REF_PATTERN3.test(record.project_ref) || typeof record.deployment_id !== "string" || !DEPLOYMENT_ID_PATTERN.test(record.deployment_id) || !Array.isArray(record.releases))
17417
17795
  return null;
17418
- const activeReleaseId = nullableIdentity(record.active_release_id, RELEASE_ID_PATTERN);
17796
+ const activeReleaseId = nullableIdentity(record.active_release_id, RELEASE_ID_PATTERN2);
17419
17797
  const activeActivationId = nullableIdentity(record.active_activation_id, MUTATION_ID_PATTERN2);
17420
- const nextCursor = nullableIdentity(record.next_cursor, RELEASE_ID_PATTERN);
17798
+ const nextCursor = nullableIdentity(record.next_cursor, RELEASE_ID_PATTERN2);
17421
17799
  const releases = record.releases.map(releaseRecord);
17422
17800
  if (activeReleaseId === undefined || activeActivationId === undefined || nextCursor === undefined || activeReleaseId === null !== (activeActivationId === null) || releases.some((release) => release === null))
17423
17801
  return null;
@@ -17444,7 +17822,7 @@ function releaseEndpoint(projectRef, deploymentId) {
17444
17822
  return `${deploymentEndpoint(projectRef, deploymentId)}/releases`;
17445
17823
  }
17446
17824
  function releasePath(projectRef, deploymentId, releaseId) {
17447
- if (!RELEASE_ID_PATTERN.test(releaseId))
17825
+ if (!RELEASE_ID_PATTERN2.test(releaseId))
17448
17826
  throw new Error("'release_id' must be a SHA-256 digest");
17449
17827
  return `${releaseEndpoint(projectRef, deploymentId)}/${releaseId}`;
17450
17828
  }
@@ -17465,7 +17843,7 @@ async function archiveSha256(handle, sizeBytes) {
17465
17843
  return hash.digest("hex");
17466
17844
  }
17467
17845
  async function verifiedArchive(path) {
17468
- const archivePath = resolve8(path);
17846
+ const archivePath = resolve9(path);
17469
17847
  const handle = await open2(archivePath, fsConstants2.O_RDONLY | fsConstants2.O_NOFOLLOW);
17470
17848
  try {
17471
17849
  const before = await handle.stat({ bigint: true });
@@ -17509,7 +17887,7 @@ async function listFrontendReleases(http, projectRef, deploymentId, cursor, limi
17509
17887
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > RELEASE_LIST_LIMIT_MAX) {
17510
17888
  throw new Error("'limit' must be 1-100");
17511
17889
  }
17512
- if (cursor !== undefined && !RELEASE_ID_PATTERN.test(cursor))
17890
+ if (cursor !== undefined && !RELEASE_ID_PATTERN2.test(cursor))
17513
17891
  throw new Error("'cursor' is invalid");
17514
17892
  const query = new URLSearchParams({ limit: String(limit) });
17515
17893
  if (cursor)
@@ -17840,7 +18218,7 @@ async function publishFrontendRelease(http, projectRef, deploymentId, archiveSou
17840
18218
  const envelope = value && typeof value === "object" && !Array.isArray(value) ? value : null;
17841
18219
  const candidate = envelope?.release;
17842
18220
  const release = candidate && typeof candidate === "object" && !Array.isArray(candidate) ? candidate : null;
17843
- if (!release || release.tree_sha256 !== expectedTreeSha256 || typeof release.release_id !== "string" || !RELEASE_ID_PATTERN.test(release.release_id)) {
18221
+ if (!release || release.tree_sha256 !== expectedTreeSha256 || typeof release.release_id !== "string" || !RELEASE_ID_PATTERN2.test(release.release_id)) {
17844
18222
  return releaseFailure("frontend.deploy", "INVALID_RESPONSE", 200);
17845
18223
  }
17846
18224
  const mutationId = crypto.randomUUID();
@@ -17905,7 +18283,7 @@ async function rollbackBoundFrontendRelease(http, input) {
17905
18283
  return boundRollbackResponse(await activateFrontendRelease(http, input), input);
17906
18284
  }
17907
18285
  async function rollbackFrontendRelease(http, projectRef, deploymentId, releaseId, options = {}) {
17908
- if (releaseId !== undefined && !RELEASE_ID_PATTERN.test(releaseId)) {
18286
+ if (releaseId !== undefined && !RELEASE_ID_PATTERN2.test(releaseId)) {
17909
18287
  throw new Error("'release_id' must be a SHA-256 digest");
17910
18288
  }
17911
18289
  const bound = options.expectedActiveReleaseId !== undefined || options.expectedActivationId !== undefined || options.mutationId !== undefined;
@@ -17914,7 +18292,7 @@ async function rollbackFrontendRelease(http, projectRef, deploymentId, releaseId
17914
18292
  if (releaseId === undefined || expectedActiveReleaseId === undefined || expectedActivationId === undefined || mutationId === undefined) {
17915
18293
  throw new Error("'release_id', 'expected_active_release_id', 'expected_activation_id', and 'mutation_id' are required together for a bound rollback");
17916
18294
  }
17917
- if (!RELEASE_ID_PATTERN.test(expectedActiveReleaseId)) {
18295
+ if (!RELEASE_ID_PATTERN2.test(expectedActiveReleaseId)) {
17918
18296
  throw new Error("'expected_active_release_id' must be a SHA-256 digest");
17919
18297
  }
17920
18298
  if (!MUTATION_ID_PATTERN2.test(expectedActivationId)) {
@@ -18002,7 +18380,7 @@ async function readPreviousFrontendRelease(http, projectRef, deploymentId) {
18002
18380
  }
18003
18381
  const data = response.data;
18004
18382
  const value = data && typeof data === "object" && !Array.isArray(data) ? data : null;
18005
- const activeReleaseId = value ? nullableIdentity(value.active_release_id, RELEASE_ID_PATTERN) : undefined;
18383
+ const activeReleaseId = value ? nullableIdentity(value.active_release_id, RELEASE_ID_PATTERN2) : undefined;
18006
18384
  const activeActivationId = value ? nullableIdentity(value.active_activation_id, MUTATION_ID_PATTERN2) : undefined;
18007
18385
  const previousActivationId = value ? nullableIdentity(value.previous_activation_id, MUTATION_ID_PATTERN2) : undefined;
18008
18386
  const previous = value?.previous_release === null ? null : releaseRecord(value?.previous_release);
@@ -18036,7 +18414,7 @@ async function activateFrontendReleaseWithReadback(http, input, readActive) {
18036
18414
  const mutationId = input.mutationId;
18037
18415
  if (!MUTATION_ID_PATTERN2.test(mutationId))
18038
18416
  throw new Error("'mutation_id' must be a UUIDv4");
18039
- if (input.expectedActiveReleaseId !== "absent" && !RELEASE_ID_PATTERN.test(input.expectedActiveReleaseId)) {
18417
+ if (input.expectedActiveReleaseId !== "absent" && !RELEASE_ID_PATTERN2.test(input.expectedActiveReleaseId)) {
18040
18418
  throw new Error("'expected_active_release_id' is invalid");
18041
18419
  }
18042
18420
  if (input.expectedActivationId !== "absent" && !MUTATION_ID_PATTERN2.test(input.expectedActivationId)) {
@@ -21086,11 +21464,11 @@ function responseError(result) {
21086
21464
  }
21087
21465
  return `Request failed with HTTP ${result.status}`;
21088
21466
  }
21089
- function projectPath(ref) {
21467
+ function projectPath2(ref) {
21090
21468
  return `/v1/projects/${encodeURIComponent(ref)}/branches`;
21091
21469
  }
21092
21470
  function branchPath(ref, branchRef) {
21093
- return `${projectPath(ref)}/${encodeURIComponent(branchRef)}`;
21471
+ return `${projectPath2(ref)}/${encodeURIComponent(branchRef)}`;
21094
21472
  }
21095
21473
  function formatPromotionPlan(plan) {
21096
21474
  const lines = [
@@ -21165,10 +21543,10 @@ function registerBranchTools(server, http, options = {}) {
21165
21543
  }
21166
21544
  let result;
21167
21545
  if (action === "list") {
21168
- result = await http.get(projectPath(ref));
21546
+ result = await http.get(projectPath2(ref));
21169
21547
  } else if (action === "create") {
21170
21548
  const name = requireString(args.name, "name");
21171
- result = await http.post(projectPath(ref), {
21549
+ result = await http.post(projectPath2(ref), {
21172
21550
  name,
21173
21551
  data_mode: args.data_mode === "full_clone" ? "full_clone" : "schema_only"
21174
21552
  });
@@ -21268,8 +21646,8 @@ function registerBranchTools(server, http, options = {}) {
21268
21646
  }
21269
21647
 
21270
21648
  // src/shared/tools/supabase-cli-tools.ts
21271
- import { chmodSync, existsSync as existsSync6, mkdirSync as mkdirSync2, statSync as statSync5, writeFileSync as writeFileSync2 } from "node:fs";
21272
- import { dirname as dirname4, isAbsolute as isAbsolute2, join as join6, resolve as resolve9 } from "node:path";
21649
+ import { chmodSync, existsSync as existsSync7, mkdirSync as mkdirSync2, statSync as statSync5, writeFileSync as writeFileSync2 } from "node:fs";
21650
+ import { dirname as dirname4, isAbsolute as isAbsolute2, join as join7, resolve as resolve10 } from "node:path";
21273
21651
  var SENSITIVE_ENV_KEY = /(?:^|_)(?: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;
21274
21652
  var VALID_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
21275
21653
  var VALID_MIGRATION_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,100}$/;
@@ -21329,12 +21707,12 @@ function schemaArguments(schema) {
21329
21707
  function workdirArguments(workdir) {
21330
21708
  if (!workdir)
21331
21709
  throw new Error("A workdir is required");
21332
- return ["--workdir", resolve9(workdir)];
21710
+ return ["--workdir", resolve10(workdir)];
21333
21711
  }
21334
21712
  function resolveOutputPath(workdir, file, label) {
21335
21713
  if (!file || /[\r\n\0]/.test(file))
21336
21714
  throw new Error(`${label} file is required`);
21337
- return isAbsolute2(file) ? resolve9(file) : resolve9(workdir, file);
21715
+ return isAbsolute2(file) ? resolve10(file) : resolve10(workdir, file);
21338
21716
  }
21339
21717
  function databaseTargetArguments(databaseUrl) {
21340
21718
  return databaseUrl ? ["--db-url", requirePostgresUrl(databaseUrl)] : ["--local"];
@@ -21509,7 +21887,7 @@ function actionArguments(request, workdir) {
21509
21887
  function buildOfficialSupabaseArgs(request) {
21510
21888
  if (request.action === "version")
21511
21889
  return ["--version"];
21512
- const workdir = request.workdir ? resolve9(request.workdir) : undefined;
21890
+ const workdir = request.workdir ? resolve10(request.workdir) : undefined;
21513
21891
  if (!workdir)
21514
21892
  throw new Error("A workdir is required");
21515
21893
  return [...actionArguments(request, workdir), ...workdirArguments(workdir)];
@@ -21586,14 +21964,14 @@ function resolveOfficialSupabaseCommand(workdir, environment = process.env) {
21586
21964
  }
21587
21965
  return ["npx", "--yes", `supabase@${version}`];
21588
21966
  }
21589
- const localPackageEntry = join6(resolve9(workdir), "node_modules", "supabase", "dist", "supabase.js");
21590
- if (existsSync6(localPackageEntry))
21967
+ const localPackageEntry = join7(resolve10(workdir), "node_modules", "supabase", "dist", "supabase.js");
21968
+ if (existsSync7(localPackageEntry))
21591
21969
  return [process.execPath, localPackageEntry];
21592
21970
  return ["supabase"];
21593
21971
  }
21594
21972
  function resolveExistingWorkdir(workdirInput, fallback) {
21595
- const workdir = resolve9(workdirInput || fallback);
21596
- if (!existsSync6(workdir) || !statSync5(workdir).isDirectory()) {
21973
+ const workdir = resolve10(workdirInput || fallback);
21974
+ if (!existsSync7(workdir) || !statSync5(workdir).isDirectory()) {
21597
21975
  throw new Error(`Supabase workdir not found: ${workdir}`);
21598
21976
  }
21599
21977
  return workdir;
@@ -21693,7 +22071,7 @@ async function executeMigrationPush(request, runtime) {
21693
22071
  if (!projectRef)
21694
22072
  return missingProjectRefResult();
21695
22073
  const workdir = resolveExistingWorkdir(request.workdir, runtime.fallbackWorkdir);
21696
- const migrationDirectory = resolve9(workdir, request.dir || "supabase/migrations");
22074
+ const migrationDirectory = resolve10(workdir, request.dir || "supabase/migrations");
21697
22075
  const migrationResponse = await pushMigrations({
21698
22076
  action: "push_migrations",
21699
22077
  ref: projectRef,
@@ -21736,7 +22114,7 @@ async function executeOfficialAction(request, runtime) {
21736
22114
  if (execution.exitCode === 0 && request.action === "gen_types" && outputPath) {
21737
22115
  return generatedTypesResult(outputPath, execution, secrets);
21738
22116
  }
21739
- if (execution.exitCode === 0 && request.action === "db_dump" && outputPath && existsSync6(outputPath)) {
22117
+ if (execution.exitCode === 0 && request.action === "db_dump" && outputPath && existsSync7(outputPath)) {
21740
22118
  chmodSync(outputPath, 384);
21741
22119
  }
21742
22120
  return {
@@ -21805,12 +22183,12 @@ function registerSupabaseCliTools(server, options = {}) {
21805
22183
  }
21806
22184
 
21807
22185
  // src/shared/tools/lite-cli-tools.ts
21808
- import { existsSync as existsSync8, statSync as statSync7 } from "node:fs";
21809
- import { resolve as resolve11 } from "node:path";
22186
+ import { existsSync as existsSync9, statSync as statSync7 } from "node:fs";
22187
+ import { resolve as resolve12 } from "node:path";
21810
22188
 
21811
22189
  // src/shared/tools/lite-cli-command.ts
21812
- import { existsSync as existsSync7, readFileSync as readFileSync7, statSync as statSync6 } from "node:fs";
21813
- import { isAbsolute as isAbsolute3, join as join7, relative as relative3, resolve as resolve10 } from "node:path";
22190
+ import { existsSync as existsSync8, readFileSync as readFileSync8, statSync as statSync6 } from "node:fs";
22191
+ import { isAbsolute as isAbsolute3, join as join8, relative as relative4, resolve as resolve11 } from "node:path";
21814
22192
  function isRecord5(value) {
21815
22193
  return value !== null && typeof value === "object" && !Array.isArray(value);
21816
22194
  }
@@ -21821,11 +22199,11 @@ function resolveLiteCommand(workdir, environment = process.env) {
21821
22199
  throw new Error("Invalid SUPACLOUD_LITE_CLI_BIN");
21822
22200
  return [explicitBinary];
21823
22201
  }
21824
- const packageRoot = join7(resolve10(workdir), "node_modules", "@supacloud", "lite");
21825
- const manifestPath = join7(packageRoot, "package.json");
21826
- if (!existsSync7(manifestPath))
22202
+ const packageRoot = join8(resolve11(workdir), "node_modules", "@supacloud", "lite");
22203
+ const manifestPath = join8(packageRoot, "package.json");
22204
+ if (!existsSync8(manifestPath))
21827
22205
  return ["supacloud-lite"];
21828
- const manifest = JSON.parse(readFileSync7(manifestPath, "utf8"));
22206
+ const manifest = JSON.parse(readFileSync8(manifestPath, "utf8"));
21829
22207
  if (!isRecord5(manifest) || manifest.name !== "@supacloud/lite" || !isRecord5(manifest.bin)) {
21830
22208
  throw new Error("Invalid installed @supacloud/lite package manifest");
21831
22209
  }
@@ -21833,20 +22211,20 @@ function resolveLiteCommand(workdir, environment = process.env) {
21833
22211
  if (typeof entry !== "string" || !entry.trim() || entry.includes("\x00") || isAbsolute3(entry)) {
21834
22212
  throw new Error("Invalid installed @supacloud/lite bin");
21835
22213
  }
21836
- const executable = resolve10(packageRoot, entry);
21837
- const packageRelative = relative3(packageRoot, executable);
22214
+ const executable = resolve11(packageRoot, entry);
22215
+ const packageRelative = relative4(packageRoot, executable);
21838
22216
  if (!packageRelative || packageRelative === ".." || packageRelative.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute3(packageRelative)) {
21839
22217
  throw new Error("Installed @supacloud/lite bin must stay inside its package");
21840
22218
  }
21841
- if (!existsSync7(executable) || !statSync6(executable).isFile()) {
22219
+ if (!existsSync8(executable) || !statSync6(executable).isFile()) {
21842
22220
  throw new Error("Installed @supacloud/lite bin is missing; reinstall the package");
21843
22221
  }
21844
22222
  return [process.execPath, executable];
21845
22223
  }
21846
22224
  // src/shared/tools/lite-cli-tools.ts
21847
22225
  function requireWorkdir(workdir, fallback) {
21848
- const resolved = resolve11(workdir || fallback);
21849
- if (!existsSync8(resolved) || !statSync7(resolved).isDirectory()) {
22226
+ const resolved = resolve12(workdir || fallback);
22227
+ if (!existsSync9(resolved) || !statSync7(resolved).isDirectory()) {
21850
22228
  throw new Error(`Lite workdir not found: ${resolved}`);
21851
22229
  }
21852
22230
  return resolved;
@@ -22080,40 +22458,40 @@ function registerLiteCliTools(server, options = {}) {
22080
22458
  // src/shared/tools/ai-tools.ts
22081
22459
  import {
22082
22460
  cpSync,
22083
- existsSync as existsSync9,
22461
+ existsSync as existsSync10,
22084
22462
  lstatSync as lstatSync2,
22085
22463
  mkdirSync as mkdirSync3,
22086
- mkdtempSync as mkdtempSync2,
22464
+ mkdtempSync as mkdtempSync3,
22087
22465
  readdirSync as readdirSync4,
22088
- readFileSync as readFileSync8,
22466
+ readFileSync as readFileSync9,
22089
22467
  renameSync,
22090
- rmSync as rmSync2
22468
+ rmSync as rmSync3
22091
22469
  } from "node:fs";
22092
22470
  import { homedir as homedir2 } from "node:os";
22093
- import { dirname as dirname5, join as join8, relative as relative4, resolve as resolve12, sep as sep3 } from "node:path";
22471
+ import { dirname as dirname5, join as join9, relative as relative5, resolve as resolve13, sep as sep4 } from "node:path";
22094
22472
  import { fileURLToPath } from "node:url";
22095
22473
  var SKILL_NAME = "supacloud";
22096
22474
  function regularFiles(rootDirectory, currentDirectory = rootDirectory) {
22097
22475
  const files = [];
22098
22476
  for (const directoryEntry of readdirSync4(currentDirectory, { withFileTypes: true })) {
22099
- const entryPath = join8(currentDirectory, directoryEntry.name);
22477
+ const entryPath = join9(currentDirectory, directoryEntry.name);
22100
22478
  if (directoryEntry.isSymbolicLink())
22101
22479
  throw new Error(`Skill directories cannot contain symlinks: ${entryPath}`);
22102
22480
  if (directoryEntry.isDirectory())
22103
22481
  files.push(...regularFiles(rootDirectory, entryPath));
22104
22482
  if (directoryEntry.isFile())
22105
- files.push(relative4(rootDirectory, entryPath).split(sep3).join("/"));
22483
+ files.push(relative5(rootDirectory, entryPath).split(sep4).join("/"));
22106
22484
  }
22107
22485
  return files.sort();
22108
22486
  }
22109
22487
  function directoriesMatch(sourceDirectory, destinationDirectory) {
22110
- if (!existsSync9(destinationDirectory) || !lstatSync2(destinationDirectory).isDirectory())
22488
+ if (!existsSync10(destinationDirectory) || !lstatSync2(destinationDirectory).isDirectory())
22111
22489
  return false;
22112
22490
  const sourceFiles = regularFiles(sourceDirectory);
22113
22491
  const destinationFiles = regularFiles(destinationDirectory);
22114
22492
  if (sourceFiles.join("\x00") !== destinationFiles.join("\x00"))
22115
22493
  return false;
22116
- return sourceFiles.every((file) => readFileSync8(join8(sourceDirectory, file)).equals(readFileSync8(join8(destinationDirectory, file))));
22494
+ return sourceFiles.every((file) => readFileSync9(join9(sourceDirectory, file)).equals(readFileSync9(join9(destinationDirectory, file))));
22117
22495
  }
22118
22496
  function backupTimestamp(now) {
22119
22497
  return now.toISOString().replace(/[-:.]/g, "");
@@ -22122,7 +22500,7 @@ function availableBackupDirectory(destinationDirectory, now) {
22122
22500
  const baseDirectory = `${destinationDirectory}.backup-${backupTimestamp(now)}`;
22123
22501
  let candidate = baseDirectory;
22124
22502
  let suffix = 2;
22125
- while (existsSync9(candidate)) {
22503
+ while (existsSync10(candidate)) {
22126
22504
  candidate = `${baseDirectory}-${suffix}`;
22127
22505
  suffix += 1;
22128
22506
  }
@@ -22130,12 +22508,12 @@ function availableBackupDirectory(destinationDirectory, now) {
22130
22508
  }
22131
22509
  function stagedSkill(sourceDirectory, targetRoot) {
22132
22510
  mkdirSync3(targetRoot, { recursive: true });
22133
- const stagingRoot = mkdtempSync2(join8(targetRoot, ".supacloud-install-"));
22134
- const stagingSkill = join8(stagingRoot, SKILL_NAME);
22511
+ const stagingRoot = mkdtempSync3(join9(targetRoot, ".supacloud-install-"));
22512
+ const stagingSkill = join9(stagingRoot, SKILL_NAME);
22135
22513
  try {
22136
22514
  cpSync(sourceDirectory, stagingSkill, { recursive: true, errorOnExist: true });
22137
22515
  } catch (error) {
22138
- rmSync2(stagingRoot, { recursive: true, force: true });
22516
+ rmSync3(stagingRoot, { recursive: true, force: true });
22139
22517
  throw error;
22140
22518
  }
22141
22519
  return { root: stagingRoot, skill: stagingSkill };
@@ -22145,7 +22523,7 @@ function createSkill(sourceDirectory, targetRoot, destinationDirectory) {
22145
22523
  try {
22146
22524
  renameSync(staging.skill, destinationDirectory);
22147
22525
  } finally {
22148
- rmSync2(staging.root, { recursive: true, force: true });
22526
+ rmSync3(staging.root, { recursive: true, force: true });
22149
22527
  }
22150
22528
  }
22151
22529
  function replaceSkill(sourceDirectory, targetRoot, destinationDirectory, backupDirectory) {
@@ -22159,17 +22537,17 @@ function replaceSkill(sourceDirectory, targetRoot, destinationDirectory, backupD
22159
22537
  throw error;
22160
22538
  }
22161
22539
  } finally {
22162
- rmSync2(staging.root, { recursive: true, force: true });
22540
+ rmSync3(staging.root, { recursive: true, force: true });
22163
22541
  }
22164
22542
  }
22165
22543
  function skillSummary(request, action, files, backupDirectory) {
22166
- const sourceDirectory = resolve12(request.sourceDirectory);
22167
- const targetRoot = resolve12(request.targetRoot);
22544
+ const sourceDirectory = resolve13(request.sourceDirectory);
22545
+ const targetRoot = resolve13(request.targetRoot);
22168
22546
  return {
22169
22547
  name: SKILL_NAME,
22170
22548
  sourceDirectory,
22171
22549
  targetRoot,
22172
- destinationDirectory: join8(targetRoot, SKILL_NAME),
22550
+ destinationDirectory: join9(targetRoot, SKILL_NAME),
22173
22551
  action,
22174
22552
  mode: request.mode,
22175
22553
  changed: action !== "none",
@@ -22178,14 +22556,14 @@ function skillSummary(request, action, files, backupDirectory) {
22178
22556
  };
22179
22557
  }
22180
22558
  function installSkill(request) {
22181
- const sourceDirectory = resolve12(request.sourceDirectory);
22182
- const targetRoot = resolve12(request.targetRoot);
22183
- const destinationDirectory = join8(targetRoot, SKILL_NAME);
22184
- if (!existsSync9(join8(sourceDirectory, "SKILL.md"))) {
22559
+ const sourceDirectory = resolve13(request.sourceDirectory);
22560
+ const targetRoot = resolve13(request.targetRoot);
22561
+ const destinationDirectory = join9(targetRoot, SKILL_NAME);
22562
+ if (!existsSync10(join9(sourceDirectory, "SKILL.md"))) {
22185
22563
  throw new Error(`Bundled SupaCloud CLI skill not found: ${sourceDirectory}`);
22186
22564
  }
22187
22565
  const files = regularFiles(sourceDirectory);
22188
- if (!existsSync9(destinationDirectory))
22566
+ if (!existsSync10(destinationDirectory))
22189
22567
  return installNewSkill(request, files);
22190
22568
  if (directoriesMatch(sourceDirectory, destinationDirectory)) {
22191
22569
  return skillSummary(request, "none", files, null);
@@ -22196,17 +22574,17 @@ function installSkill(request) {
22196
22574
  return installReplacementSkill(request, files);
22197
22575
  }
22198
22576
  function installNewSkill(request, files) {
22199
- const sourceDirectory = resolve12(request.sourceDirectory);
22200
- const targetRoot = resolve12(request.targetRoot);
22577
+ const sourceDirectory = resolve13(request.sourceDirectory);
22578
+ const targetRoot = resolve13(request.targetRoot);
22201
22579
  if (request.mode === "write") {
22202
- createSkill(sourceDirectory, targetRoot, join8(targetRoot, SKILL_NAME));
22580
+ createSkill(sourceDirectory, targetRoot, join9(targetRoot, SKILL_NAME));
22203
22581
  }
22204
22582
  return skillSummary(request, "create", files, null);
22205
22583
  }
22206
22584
  function installReplacementSkill(request, files) {
22207
- const sourceDirectory = resolve12(request.sourceDirectory);
22208
- const targetRoot = resolve12(request.targetRoot);
22209
- const destinationDirectory = join8(targetRoot, SKILL_NAME);
22585
+ const sourceDirectory = resolve13(request.sourceDirectory);
22586
+ const targetRoot = resolve13(request.targetRoot);
22587
+ const destinationDirectory = join9(targetRoot, SKILL_NAME);
22210
22588
  const backupDirectory = availableBackupDirectory(destinationDirectory, request.now);
22211
22589
  if (request.mode === "write") {
22212
22590
  replaceSkill(sourceDirectory, targetRoot, destinationDirectory, backupDirectory);
@@ -22215,7 +22593,7 @@ function installReplacementSkill(request, files) {
22215
22593
  }
22216
22594
  function resolveDefaultCodexSkillRoot(environment = process.env, homeDirectory = homedir2()) {
22217
22595
  const codexHome = environment.CODEX_HOME?.trim();
22218
- return join8(resolve12(codexHome || join8(homeDirectory, ".codex")), "skills");
22596
+ return join9(resolve13(codexHome || join9(homeDirectory, ".codex")), "skills");
22219
22597
  }
22220
22598
  var SKILL_TARGET_ALIASES = ["codex", "claude", "agents", "project"];
22221
22599
  function resolveSkillTargetRoot(target, options = {}) {
@@ -22227,23 +22605,23 @@ function resolveSkillTargetRoot(target, options = {}) {
22227
22605
  return resolveDefaultCodexSkillRoot(environment, homeDirectory);
22228
22606
  if (normalized === "claude") {
22229
22607
  const config = environment.CLAUDE_CONFIG_DIR?.trim();
22230
- return join8(resolve12(config || join8(homeDirectory, ".claude")), "skills");
22608
+ return join9(resolve13(config || join9(homeDirectory, ".claude")), "skills");
22231
22609
  }
22232
22610
  if (normalized === "agents") {
22233
22611
  const config = environment.AGENTS_HOME?.trim();
22234
- return join8(resolve12(config || join8(homeDirectory, ".agents")), "skills");
22612
+ return join9(resolve13(config || join9(homeDirectory, ".agents")), "skills");
22235
22613
  }
22236
22614
  if (normalized === "project")
22237
- return join8(resolve12(workingDirectory), ".agents", "skills");
22238
- return resolve12(target);
22615
+ return join9(resolve13(workingDirectory), ".agents", "skills");
22616
+ return resolve13(target);
22239
22617
  }
22240
22618
  function resolveBundledSkillDirectory(moduleUrl = import.meta.url) {
22241
22619
  const moduleDirectory = dirname5(fileURLToPath(moduleUrl));
22242
22620
  const candidates = [
22243
- resolve12(moduleDirectory, "../../../skills", SKILL_NAME),
22244
- resolve12(moduleDirectory, "../skills", SKILL_NAME)
22621
+ resolve13(moduleDirectory, "../../../skills", SKILL_NAME),
22622
+ resolve13(moduleDirectory, "../skills", SKILL_NAME)
22245
22623
  ];
22246
- const skillDirectory = candidates.find((candidate) => existsSync9(join8(candidate, "SKILL.md")));
22624
+ const skillDirectory = candidates.find((candidate) => existsSync10(join9(candidate, "SKILL.md")));
22247
22625
  if (!skillDirectory)
22248
22626
  throw new Error("Bundled SupaCloud CLI skill is missing from this installation");
22249
22627
  return skillDirectory;
@@ -22265,7 +22643,7 @@ function registerAiTools(server) {
22265
22643
  name: SKILL_NAME,
22266
22644
  sourceDirectory,
22267
22645
  defaultTargetRoot,
22268
- defaultDestination: join8(defaultTargetRoot, SKILL_NAME),
22646
+ defaultDestination: join9(defaultTargetRoot, SKILL_NAME),
22269
22647
  targetAliases: Object.fromEntries(SKILL_TARGET_ALIASES.map((alias) => [
22270
22648
  alias,
22271
22649
  resolveSkillTargetRoot(alias)
@@ -22331,9 +22709,9 @@ function registerMcpTools(server, context) {
22331
22709
  }
22332
22710
 
22333
22711
  // src/shared/tools/app-tools.ts
22334
- import { existsSync as existsSync12, readFileSync as readFileSync9 } from "node:fs";
22712
+ import { existsSync as existsSync13, readFileSync as readFileSync10 } from "node:fs";
22335
22713
  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";
22714
+ import { basename as basename8, dirname as dirname9, join as join15, relative as relative8, resolve as resolve20 } from "node:path";
22337
22715
  import {
22338
22716
  applyDiagnosticFix,
22339
22717
  buildDeliveryProject,
@@ -22630,7 +23008,7 @@ test("cancelled stream consumers release their subscription", async () => {
22630
23008
 
22631
23009
  // src/shared/tools/app-starter.ts
22632
23010
  import { lstat as lstat2, mkdir as mkdir3, readdir as readdir3, writeFile as writeFile3 } from "node:fs/promises";
22633
- import { basename as basename6, dirname as dirname6, join as join9, resolve as resolve13 } from "node:path";
23011
+ import { basename as basename7, dirname as dirname6, join as join10, resolve as resolve14 } from "node:path";
22634
23012
 
22635
23013
  // src/shared/tools/app-starter-environment.ts
22636
23014
  var STARTER_ENVIRONMENT = String.raw`import { existsSync, readFileSync } from "node:fs";
@@ -27471,8 +27849,8 @@ and governance; TypeScript checks both application and generated source.
27471
27849
  };
27472
27850
  }
27473
27851
  async function initializeAppProject(options) {
27474
- const root = resolve13(options.root ?? process.cwd());
27475
- const name = options.name ?? basename6(root);
27852
+ const root = resolve14(options.root ?? process.cwd());
27853
+ const name = options.name ?? basename7(root);
27476
27854
  if (!/^[a-z][a-z0-9-]*$/.test(name) || name.length > 100) {
27477
27855
  throw new Error("Project name must be lowercase kebab-case (1-100 characters)");
27478
27856
  }
@@ -27504,7 +27882,7 @@ async function initializeAppProject(options) {
27504
27882
  }
27505
27883
  })();
27506
27884
  for (const [relativePath, content] of Object.entries(files)) {
27507
- const path = join9(root, relativePath);
27885
+ const path = join10(root, relativePath);
27508
27886
  await mkdir3(dirname6(path), { recursive: true });
27509
27887
  await writeFile3(path, content, { encoding: "utf8", flag: "wx" });
27510
27888
  }
@@ -27512,8 +27890,8 @@ async function initializeAppProject(options) {
27512
27890
  }
27513
27891
 
27514
27892
  // src/shared/tools/app-database-check.ts
27515
- import { existsSync as existsSync10 } from "node:fs";
27516
- import { join as join10, resolve as resolve14 } from "node:path";
27893
+ import { existsSync as existsSync11 } from "node:fs";
27894
+ import { join as join11, resolve as resolve15 } from "node:path";
27517
27895
  var CHECK_ENTRY = `
27518
27896
  import { createRequire } from "node:module";
27519
27897
  import { join } from "node:path";
@@ -27524,8 +27902,8 @@ process.argv = [process.execPath, cli, "check", "--root", root];
27524
27902
  await import(pathToFileURL(cli).href);
27525
27903
  `;
27526
27904
  function checkAppDatabaseSources(projectRoot) {
27527
- const root = resolve14(projectRoot);
27528
- if (!existsSync10(join10(root, "database.sources.json")))
27905
+ const root = resolve15(projectRoot);
27906
+ if (!existsSync11(join11(root, "database.sources.json")))
27529
27907
  return;
27530
27908
  const name = "database-source-contracts";
27531
27909
  try {
@@ -28718,7 +29096,7 @@ Scenario: Delivery
28718
29096
  // src/shared/tools/app-local-dev.ts
28719
29097
  import { spawn } from "node:child_process";
28720
29098
  import { readFile as readFile2 } from "node:fs/promises";
28721
- import { join as join11, resolve as resolve15 } from "node:path";
29099
+ import { join as join12, resolve as resolve16 } from "node:path";
28722
29100
  function localDatabaseUrl(value) {
28723
29101
  try {
28724
29102
  if (!value || /[\x00-\x20\x7f]/.test(value))
@@ -28765,7 +29143,7 @@ async function probeDatabase(url, signal) {
28765
29143
  }
28766
29144
  }
28767
29145
  async function runLocalDevelopment(options) {
28768
- const root = resolve15(options.root);
29146
+ const root = resolve16(options.root);
28769
29147
  const profile = options.profile ?? "fast";
28770
29148
  if (profile !== "fast" && profile !== "integration")
28771
29149
  throw new Error("Unknown development profile");
@@ -28777,7 +29155,7 @@ async function runLocalDevelopment(options) {
28777
29155
  throw new Error("Inherited remote context must be complete and explicitly tagged with SUPACLOUD_ENV=test");
28778
29156
  }
28779
29157
  const script = profile === "integration" ? "dev:integration" : "dev";
28780
- const manifest = JSON.parse(await readFile2(join11(root, "package.json"), "utf8"));
29158
+ const manifest = JSON.parse(await readFile2(join12(root, "package.json"), "utf8"));
28781
29159
  const scripts = manifest && typeof manifest === "object" && "scripts" in manifest ? manifest.scripts : undefined;
28782
29160
  const command = scripts && typeof scripts === "object" ? Reflect.get(scripts, script) : undefined;
28783
29161
  if (typeof command !== "string" || !command.trim()) {
@@ -28866,9 +29244,9 @@ async function runLocalDevelopment(options) {
28866
29244
 
28867
29245
  // src/shared/tools/app-verification-plan.ts
28868
29246
  import { readdir as readdir4, realpath as realpath3, stat } from "node:fs/promises";
28869
- import { dirname as dirname7, isAbsolute as isAbsolute4, relative as relative5, resolve as resolve16 } from "node:path";
29247
+ import { dirname as dirname7, isAbsolute as isAbsolute4, relative as relative6, resolve as resolve17 } from "node:path";
28870
29248
  function inside2(root, file) {
28871
- const path = relative5(root, file).replaceAll("\\", "/");
29249
+ const path = relative6(root, file).replaceAll("\\", "/");
28872
29250
  return path !== ".." && !path.startsWith("../") && !isAbsolute4(path);
28873
29251
  }
28874
29252
  async function createVerificationPlan(root, graph, target, sourceRoot = root) {
@@ -28878,7 +29256,7 @@ async function createVerificationPlan(root, graph, target, sourceRoot = root) {
28878
29256
  throw new Error("Select one unambiguous module or owned symbol for verification");
28879
29257
  const owner = owners[0];
28880
29258
  const project = await realpath3(root);
28881
- const requestedRoot = resolve16(root);
29259
+ const requestedRoot = resolve17(root);
28882
29260
  const sources = [
28883
29261
  owner.file,
28884
29262
  owner.featureSpec?.file,
@@ -28893,7 +29271,7 @@ async function createVerificationPlan(root, graph, target, sourceRoot = root) {
28893
29271
  const manual = [];
28894
29272
  const validatedSources = [];
28895
29273
  for (const source of new Set(sources)) {
28896
- const requested = resolve16(sourceRoot, source);
29274
+ const requested = resolve17(sourceRoot, source);
28897
29275
  if (!inside2(requestedRoot, requested)) {
28898
29276
  manual.push("A source file is outside the project; select its owning project explicitly");
28899
29277
  continue;
@@ -28904,7 +29282,7 @@ async function createVerificationPlan(root, graph, target, sourceRoot = root) {
28904
29282
  throw error;
28905
29283
  });
28906
29284
  if (actual === null) {
28907
- manual.push(`Source file is missing: ${relative5(requestedRoot, requested).replaceAll("\\", "/")}`);
29285
+ manual.push(`Source file is missing: ${relative6(requestedRoot, requested).replaceAll("\\", "/")}`);
28908
29286
  continue;
28909
29287
  }
28910
29288
  if (!inside2(project, actual)) {
@@ -28912,7 +29290,7 @@ async function createVerificationPlan(root, graph, target, sourceRoot = root) {
28912
29290
  continue;
28913
29291
  }
28914
29292
  if (!(await stat(actual)).isFile()) {
28915
- manual.push(`Source is not a regular file: ${relative5(requestedRoot, requested).replaceAll("\\", "/")}`);
29293
+ manual.push(`Source is not a regular file: ${relative6(requestedRoot, requested).replaceAll("\\", "/")}`);
28916
29294
  continue;
28917
29295
  }
28918
29296
  validatedSources.push(actual);
@@ -28928,12 +29306,12 @@ async function createVerificationPlan(root, graph, target, sourceRoot = root) {
28928
29306
  const local = [];
28929
29307
  for (const entry of await readdir4(directory, { withFileTypes: true })) {
28930
29308
  if (entry.isFile() && /\.(test|spec)\.[cm]?[jt]sx?$/.test(entry.name)) {
28931
- const file = relative5(project, resolve16(directory, entry.name)).replaceAll("\\", "/");
29309
+ const file = relative6(project, resolve17(directory, entry.name)).replaceAll("\\", "/");
28932
29310
  tests.add(file);
28933
29311
  local.push(file);
28934
29312
  }
28935
29313
  }
28936
- const path = relative5(project, directory).replaceAll("\\", "/") || ".";
29314
+ const path = relative6(project, directory).replaceAll("\\", "/") || ".";
28937
29315
  coverage.push({ directory: path, tests: local.sort(), basis: "colocated-not-proven" });
28938
29316
  if (!local.length)
28939
29317
  manual.push(`No colocated tests for source directory: ${path}`);
@@ -28948,7 +29326,7 @@ async function createVerificationPlan(root, graph, target, sourceRoot = root) {
28948
29326
  source: "declaration",
28949
29327
  target: owner.name,
28950
29328
  ready: manual.length === 0,
28951
- files: [...new Set(validatedSources.map((file) => relative5(project, file).replaceAll("\\", "/")))].sort(),
29329
+ files: [...new Set(validatedSources.map((file) => relative6(project, file).replaceAll("\\", "/")))].sort(),
28952
29330
  tests: selected.slice(0, 32),
28953
29331
  commands: selected.length <= 32 ? [
28954
29332
  ...selected.map((file) => ["bun", "test", `./${file}`]),
@@ -28969,7 +29347,7 @@ async function createVerificationPlan(root, graph, target, sourceRoot = root) {
28969
29347
  // src/shared/tools/app-scaffold-writes.ts
28970
29348
  import { randomUUID as randomUUID2 } from "node:crypto";
28971
29349
  import { link, lstat as lstat3, mkdir as mkdir4, open as open3, readFile as readFile3, realpath as realpath4, rename as rename2, rmdir, unlink } from "node:fs/promises";
28972
- import { dirname as dirname8, isAbsolute as isAbsolute5, join as join12, relative as relative6, resolve as resolve17, sep as sep4, win32 } from "node:path";
29350
+ import { dirname as dirname8, isAbsolute as isAbsolute5, join as join13, relative as relative7, resolve as resolve18, sep as sep5, win32 } from "node:path";
28973
29351
 
28974
29352
  class ScaffoldError extends Error {
28975
29353
  code;
@@ -28990,19 +29368,19 @@ function scaffoldPath(root, path) {
28990
29368
  if (parts.some((part) => /[<>:"|?*\u0000-\u001f]/.test(part) || /[ .]$/.test(part) && part !== "." && part !== ".." || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part) || part.toLowerCase() === ".git" || part.toLowerCase() === ".supacloud-generate.lock")) {
28991
29369
  throw new ScaffoldError("SCAFFOLD_PATH_INVALID", "Scaffold path is reserved or not portable");
28992
29370
  }
28993
- const target = resolve17(root, path);
28994
- const local = relative6(root, target);
28995
- if (!local || local === ".." || local.startsWith(`..${sep4}`) || isAbsolute5(local)) {
29371
+ const target = resolve18(root, path);
29372
+ const local = relative7(root, target);
29373
+ if (!local || local === ".." || local.startsWith(`..${sep5}`) || isAbsolute5(local)) {
28996
29374
  throw new ScaffoldError("SCAFFOLD_PATH_INVALID", "Scaffold path is outside the project root");
28997
29375
  }
28998
29376
  return target;
28999
29377
  }
29000
29378
  async function snapshot(root, path) {
29001
29379
  const target = scaffoldPath(root, path);
29002
- const parts = relative6(root, target).split(sep4);
29380
+ const parts = relative7(root, target).split(sep5);
29003
29381
  let current = root;
29004
29382
  for (const [index, part] of parts.entries()) {
29005
- current = join12(current, part);
29383
+ current = join13(current, part);
29006
29384
  let stat;
29007
29385
  try {
29008
29386
  stat = await lstat3(current);
@@ -29029,13 +29407,13 @@ function sameFile(a, b) {
29029
29407
  return a === null ? b === null : b !== null && a.content === b.content && a.dev === b.dev && a.ino === b.ino && a.mode === b.mode;
29030
29408
  }
29031
29409
  async function planScaffoldWrites(root, writes) {
29032
- const canonical = await realpath4(resolve17(root));
29410
+ const canonical = await realpath4(resolve18(root));
29033
29411
  const targets = new Set;
29034
29412
  const planned = [];
29035
29413
  for (const write of writes) {
29036
29414
  const target = scaffoldPath(canonical, write.path);
29037
29415
  const key = target.toLowerCase();
29038
- if (targets.has(key) || [...targets].some((other) => key.startsWith(`${other}${sep4}`) || other.startsWith(`${key}${sep4}`))) {
29416
+ if (targets.has(key) || [...targets].some((other) => key.startsWith(`${other}${sep5}`) || other.startsWith(`${key}${sep5}`))) {
29039
29417
  throw new ScaffoldError("SCAFFOLD_PATH_CONFLICT", `Conflicting scaffold target: ${write.path}`);
29040
29418
  }
29041
29419
  targets.add(key);
@@ -29052,7 +29430,7 @@ async function planScaffoldWrites(root, writes) {
29052
29430
  return Object.freeze({ root: canonical, writes: Object.freeze(planned) });
29053
29431
  }
29054
29432
  async function applyScaffoldWrites(plan) {
29055
- const lockPath = join12(plan.root, ".supacloud-generate.lock");
29433
+ const lockPath = join13(plan.root, ".supacloud-generate.lock");
29056
29434
  const lock = await open3(lockPath, "wx").catch((error) => {
29057
29435
  if (fsCode(error) === "EEXIST")
29058
29436
  throw new ScaffoldError("SCAFFOLD_BUSY", "Another generator owns .supacloud-generate.lock; no files written");
@@ -29072,8 +29450,8 @@ async function applyScaffoldWrites(plan) {
29072
29450
  for (const write of plan.writes) {
29073
29451
  const target = scaffoldPath(plan.root, write.path);
29074
29452
  let current = plan.root;
29075
- for (const part of relative6(plan.root, dirname8(target)).split(sep4).filter(Boolean)) {
29076
- current = join12(current, part);
29453
+ for (const part of relative7(plan.root, dirname8(target)).split(sep5).filter(Boolean)) {
29454
+ current = join13(current, part);
29077
29455
  try {
29078
29456
  await mkdir4(current);
29079
29457
  directories.push(current);
@@ -29152,9 +29530,9 @@ async function applyScaffoldWrites(plan) {
29152
29530
  }
29153
29531
 
29154
29532
  // src/shared/tools/configuration-tools.ts
29155
- import { existsSync as existsSync11 } from "node:fs";
29533
+ import { existsSync as existsSync12 } from "node:fs";
29156
29534
  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";
29535
+ import { join as join14, resolve as resolve19 } from "node:path";
29158
29536
  var onboardToolSchema = {
29159
29537
  root: optional(String2(), "Repository or configuration root (default: current directory)"),
29160
29538
  profile: optional(stringEnum2(["solo", "podman", "pigsty", "cluster"]), "Deployment profile (default: solo)"),
@@ -29185,7 +29563,7 @@ function textResult(text, isError = false) {
29185
29563
  function jsonResult(value, isError = false) {
29186
29564
  return textResult(JSON.stringify(value, null, 2), isError);
29187
29565
  }
29188
- function record5(value) {
29566
+ function record6(value) {
29189
29567
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
29190
29568
  }
29191
29569
  function unquote(value) {
@@ -29208,10 +29586,10 @@ function parseEnvironment(content) {
29208
29586
  return values;
29209
29587
  }
29210
29588
  async function readJsonObject(path) {
29211
- if (!existsSync11(path))
29589
+ if (!existsSync12(path))
29212
29590
  return {};
29213
29591
  const parsed = JSON.parse(await readFile4(path, "utf8"));
29214
- const value = record5(parsed);
29592
+ const value = record6(parsed);
29215
29593
  if (!value)
29216
29594
  throw new Error(`${path} must contain a JSON object`);
29217
29595
  return value;
@@ -29221,28 +29599,28 @@ async function writeJsonObject(path, value) {
29221
29599
  `, { encoding: "utf8", mode: 420 });
29222
29600
  }
29223
29601
  function contextFromConfig(config) {
29224
- const context = record5(config.context);
29602
+ const context = record6(config.context);
29225
29603
  return context ?? {};
29226
29604
  }
29227
29605
  function environmentContext(config, environment) {
29228
29606
  const context = contextFromConfig(config);
29229
- const environments = record5(context.environments);
29230
- const selected = environments ? record5(environments[environment]) : null;
29607
+ const environments = record6(context.environments);
29608
+ const selected = environments ? record6(environments[environment]) : null;
29231
29609
  return selected ?? {};
29232
29610
  }
29233
29611
  async function syncEnvironmentProfile(args, options) {
29234
- const root = resolve18(typeof args.root === "string" ? args.root : options.cwd ?? process.cwd());
29612
+ const root = resolve19(typeof args.root === "string" ? args.root : options.cwd ?? process.cwd());
29235
29613
  const environment = typeof args.environment === "string" && args.environment.trim() ? args.environment.trim() : options.activeContext?.environment;
29236
29614
  if (!environment)
29237
29615
  throw new Error("env sync requires --env <name> or SUPACLOUD_ENV");
29238
- const profilePath = join13(root, `.env.supacloud.${environment}`);
29239
- if (!existsSync11(profilePath))
29616
+ const profilePath = join14(root, `.env.supacloud.${environment}`);
29617
+ if (!existsSync12(profilePath))
29240
29618
  throw new Error(`Environment profile not found: ${profilePath}`);
29241
29619
  const values = parseEnvironment(await readFile4(profilePath, "utf8"));
29242
- const configPath = join13(root, "supacloud.json");
29620
+ const configPath = join14(root, "supacloud.json");
29243
29621
  const config = await readJsonObject(configPath);
29244
29622
  const context = contextFromConfig(config);
29245
- const environments = record5(context.environments) ?? {};
29623
+ const environments = record6(context.environments) ?? {};
29246
29624
  const publicValues = Object.fromEntries(Object.entries(values).filter(([name]) => !SECRET_KEY.test(name) && !PLATFORM_KEY.test(name)));
29247
29625
  const secretNames = Object.keys(values).filter((name) => SECRET_KEY.test(name));
29248
29626
  const nextEnvironment = {
@@ -29273,11 +29651,11 @@ async function syncEnvironmentProfile(args, options) {
29273
29651
  async function readSecretGap(root, environment) {
29274
29652
  if (!environment)
29275
29653
  return { environment, required: [], present: [], missing: [] };
29276
- const config = await readJsonObject(join13(root, "supacloud.json"));
29654
+ const config = await readJsonObject(join14(root, "supacloud.json"));
29277
29655
  const metadata = environmentContext(config, environment);
29278
29656
  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")) : {};
29657
+ const profilePath = join14(root, `.env.supacloud.${environment}`);
29658
+ const values = existsSync12(profilePath) ? parseEnvironment(await readFile4(profilePath, "utf8")) : {};
29281
29659
  const present = required.filter((name) => values[name] !== undefined && values[name] !== "" && !/^<[^>]+>$/.test(values[name]));
29282
29660
  return { environment, required, present, missing: required.filter((name) => !present.includes(name)) };
29283
29661
  }
@@ -29496,7 +29874,7 @@ async function generateScaffold(args) {
29496
29874
  throw new ScaffoldError("SCAFFOLD_OPTION_INVALID", `--${flag.replaceAll("_", "-")} must be boolean`);
29497
29875
  }
29498
29876
  }
29499
- const root = resolve19(args.root || process.cwd());
29877
+ const root = resolve20(args.root || process.cwd());
29500
29878
  const dir = args.dir ?? "src/features";
29501
29879
  if (dir !== ".")
29502
29880
  scaffoldPath(root, dir);
@@ -29525,7 +29903,7 @@ async function generateScaffold(args) {
29525
29903
  let contractName;
29526
29904
  if (kind === "module" || kind === "resource" || kind === "feature") {
29527
29905
  const name = requireIdentifier(args.name, "name");
29528
- modulePath = join14(dir, name, kind === "feature" ? `${name}.feature.ts` : `${name}.module.ts`).replaceAll("\\", "/");
29906
+ modulePath = join15(dir, name, kind === "feature" ? `${name}.feature.ts` : `${name}.module.ts`).replaceAll("\\", "/");
29529
29907
  moduleSymbol = kind === "feature" ? `${pascalName(name)}Feature` : `${pascalName(name)}Module`;
29530
29908
  if (kind === "module")
29531
29909
  writes.push({ path: modulePath, content: moduleScaffold(name), overwrite: args.force === true });
@@ -29533,18 +29911,18 @@ async function generateScaffold(args) {
29533
29911
  for (const [file, content] of Object.entries(kind === "feature" ? featureScaffold(name, pascalName(name), {
29534
29912
  ...featureGovernance,
29535
29913
  databaseImportPath: (() => {
29536
- const source = relative7(join14(root, dir, name), join14(root, featureGovernance.database.source)).replaceAll("\\", "/").replace(/\.(?:[cm]?tsx?|mts|cts)$/, "");
29914
+ const source = relative8(join15(root, dir, name), join15(root, featureGovernance.database.source)).replaceAll("\\", "/").replace(/\.(?:[cm]?tsx?|mts|cts)$/, "");
29537
29915
  return source.startsWith(".") ? source : `./${source}`;
29538
29916
  })()
29539
29917
  }) : resourceScaffold(name, pascalName(name)))) {
29540
- writes.push({ path: join14(dir, name, file).replaceAll("\\", "/"), content });
29918
+ writes.push({ path: join15(dir, name, file).replaceAll("\\", "/"), content });
29541
29919
  }
29542
29920
  } else {
29543
29921
  const moduleName = requireIdentifier(args.module, "module");
29544
29922
  const name = kind === "controller" ? moduleName : requireIdentifier(args.name, "name");
29545
29923
  const subdir = kind === "command" ? "commands" : kind === "query" ? "queries" : kind === "job" ? "jobs" : kind === "contract" ? "contracts" : "";
29546
- const path = join14(dir, moduleName, subdir, `${name}.${kind}.ts`).replaceAll("\\", "/");
29547
- if (kind === "controller" && existsSync12(scaffoldPath(root, path))) {
29924
+ const path = join15(dir, moduleName, subdir, `${name}.${kind}.ts`).replaceAll("\\", "/");
29925
+ if (kind === "controller" && existsSync13(scaffoldPath(root, path))) {
29548
29926
  throw new ScaffoldError("SCAFFOLD_EXISTS", `Controller already exists: ${path}(请手工合并路由到现有 controller)`);
29549
29927
  }
29550
29928
  const content = kind === "command" ? commandScaffold(moduleName, name) : kind === "query" ? queryScaffold(moduleName, name) : kind === "job" ? jobScaffold(moduleName, name) : kind === "contract" ? contractScaffold(moduleName, name) : controllerScaffold(moduleName);
@@ -29562,7 +29940,7 @@ async function generateScaffold(args) {
29562
29940
  if (new RegExp(`\\b${moduleSymbol}\\b`).test(original)) {
29563
29941
  throw new ScaffoldError("SCAFFOLD_REGISTRATION_CONFLICT", `Registration target already references ${moduleSymbol}; review the import manually`);
29564
29942
  }
29565
- let importPath = relative7(dirname9(target), resolve19(root, modulePath)).replaceAll("\\", "/").replace(/\.ts$/, "");
29943
+ let importPath = relative8(dirname9(target), resolve20(root, modulePath)).replaceAll("\\", "/").replace(/\.ts$/, "");
29566
29944
  if (!importPath.startsWith("."))
29567
29945
  importPath = `./${importPath}`;
29568
29946
  const edit = await applyDiagnosticFix({
@@ -29593,7 +29971,7 @@ async function generateScaffold(args) {
29593
29971
  written: !args.dry_run,
29594
29972
  changes
29595
29973
  }, null, 2));
29596
- const lines = changes.map((change) => `${args.dry_run ? "PREVIEW" : "✅"} ${change.action}: ${join14(plan.root, change.path)}`);
29974
+ const lines = changes.map((change) => `${args.dry_run ? "PREVIEW" : "✅"} ${change.action}: ${join15(plan.root, change.path)}`);
29597
29975
  if (args.dry_run)
29598
29976
  lines.push("No files written. Omit --dry-run to apply this generation.");
29599
29977
  if (kind === "resource")
@@ -29631,17 +30009,17 @@ function parseInclude(include) {
29631
30009
  return patterns && patterns.length > 0 ? patterns : undefined;
29632
30010
  }
29633
30011
  function sourceRoot(args, root, configured) {
29634
- const hasConfig = ["ts", "mts", "js", "mjs"].some((extension) => existsSync12(join14(root, `supacloud.config.${extension}`)));
30012
+ const hasConfig = ["ts", "mts", "js", "mjs"].some((extension) => existsSync13(join15(root, `supacloud.config.${extension}`)));
29635
30013
  return args.root && !hasConfig ? "." : configured;
29636
30014
  }
29637
30015
  async function projectCompileConfig(args) {
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;
30016
+ const root = resolve20(args.root || process.cwd());
30017
+ const configFile = ["ts", "mts", "js", "mjs"].map((extension) => join15(root, `supacloud.config.${extension}`)).find((candidate) => existsSync13(candidate)) ?? null;
29640
30018
  const loadedConfig = await loadSupacloudConfig(root);
29641
30019
  const defaults = resolveSupacloudConfig(loadedConfig, root);
29642
30020
  const configuredRoot = sourceRoot(args, root, loadedConfig.root);
29643
30021
  const include = parseInclude(args.include) ?? loadedConfig.include;
29644
- const outDir = args.out_dir ? resolve19(root, args.out_dir) : defaults.outDir;
30022
+ const outDir = args.out_dir ? resolve20(root, args.out_dir) : defaults.outDir;
29645
30023
  const compileOptions = compileOptionsFromConfig({
29646
30024
  ...loadedConfig,
29647
30025
  ...configuredRoot === undefined ? {} : { root: configuredRoot },
@@ -29653,8 +30031,8 @@ async function projectCompileConfig(args) {
29653
30031
  return { root, sourceDir: compileOptions.rootDir, configFile, outDir, result };
29654
30032
  }
29655
30033
  async function readAllowedDependencies(root) {
29656
- const path = join14(root, "package.json");
29657
- if (!existsSync12(path)) {
30034
+ const path = join15(root, "package.json");
30035
+ if (!existsSync13(path)) {
29658
30036
  return { dependencies: [], devDependencies: [], optionalDependencies: [], peerDependencies: [] };
29659
30037
  }
29660
30038
  try {
@@ -29692,7 +30070,7 @@ async function runContext(args) {
29692
30070
  const subject = args.target?.trim();
29693
30071
  if (subject) {
29694
30072
  const pack = createContextPack({ ...result.graph, diagnostics: result.diagnostics }, subject);
29695
- const execution = args.events === undefined ? undefined : createExecutionContextPack({ ...result.graph, diagnostics: result.diagnostics }, subject, await readExecutionMetadata(resolve19(root, args.events)), args.request_id);
30073
+ const execution = args.events === undefined ? undefined : createExecutionContextPack({ ...result.graph, diagnostics: result.diagnostics }, subject, await readExecutionMetadata(resolve20(root, args.events)), args.request_id);
29696
30074
  const verification = await createVerificationPlan(root, result.graph, pack.subject, sourceDir);
29697
30075
  const repairs = createDiagnosticRepairPlan(pack.diagnostics);
29698
30076
  const workflow = {
@@ -29834,7 +30212,7 @@ async function findUnwiredContracts(rootDir) {
29834
30212
  for (const entry of entries) {
29835
30213
  if (skip.has(entry.name))
29836
30214
  continue;
29837
- const path = join14(directory, entry.name);
30215
+ const path = join15(directory, entry.name);
29838
30216
  if (entry.isDirectory())
29839
30217
  await walk(path);
29840
30218
  else if (entry.isFile() && entry.name.endsWith(".ts"))
@@ -29852,10 +30230,10 @@ async function findUnwiredContracts(rootDir) {
29852
30230
  const symbols = [...source.matchAll(/export\s+const\s+([A-Za-z_$][A-Za-z0-9_$]*)/g)].map((match) => match[1]);
29853
30231
  if (symbols.length === 0)
29854
30232
  continue;
29855
- const moduleName = basename7(contract).replace(/\.ts$/, "");
30233
+ const moduleName = basename8(contract).replace(/\.ts$/, "");
29856
30234
  const wired = otherSources.some((text) => text.includes(moduleName) || symbols.some((symbol) => new RegExp(`\\b${symbol}\\b`).test(text)));
29857
30235
  if (!wired)
29858
- unwired.push({ file: relative7(rootDir, contract), symbols });
30236
+ unwired.push({ file: relative8(rootDir, contract), symbols });
29859
30237
  }
29860
30238
  return unwired;
29861
30239
  }
@@ -29937,7 +30315,7 @@ async function runDoctor(args) {
29937
30315
  `), doctor.errors > 0);
29938
30316
  }
29939
30317
  async function runFix(args) {
29940
- const root = resolve19(args.root || process.cwd());
30318
+ const root = resolve20(args.root || process.cwd());
29941
30319
  const fixPath = args.fix?.trim();
29942
30320
  const doctorPath = args.from_doctor?.trim();
29943
30321
  if (fixPath && doctorPath)
@@ -29952,7 +30330,7 @@ async function runFix(args) {
29952
30330
  if (!Number.isSafeInteger(rawIndex) || rawIndex === undefined || rawIndex < 0) {
29953
30331
  throw new Error("app fix --from-doctor requires a non-negative --fix-index <n>");
29954
30332
  }
29955
- const doctor = JSON.parse(await readFile5(resolve19(root, doctorPath), "utf8"));
30333
+ const doctor = JSON.parse(await readFile5(resolve20(root, doctorPath), "utf8"));
29956
30334
  if (!doctor || typeof doctor !== "object" || !Array.isArray(doctor.fixPlan)) {
29957
30335
  throw new Error("Invalid doctor output: expected a fixPlan array");
29958
30336
  }
@@ -29971,7 +30349,7 @@ async function runFix(args) {
29971
30349
  parsed = repairEntry.fix;
29972
30350
  source = "doctor";
29973
30351
  } else {
29974
- parsed = JSON.parse(await readFile5(resolve19(root, fixPath), "utf8"));
30352
+ parsed = JSON.parse(await readFile5(resolve20(root, fixPath), "utf8"));
29975
30353
  }
29976
30354
  const write = args.write === true;
29977
30355
  const applied = await applyDiagnosticFix(parsed, { rootDir: root, dryRun: !write });
@@ -30020,7 +30398,7 @@ function devDatabase(profile, explicit) {
30020
30398
  }
30021
30399
  function readManifestModules(outDir) {
30022
30400
  try {
30023
- const parsed = JSON.parse(readFileSync9(join14(outDir, "app.manifest.json"), "utf8"));
30401
+ const parsed = JSON.parse(readFileSync10(join15(outDir, "app.manifest.json"), "utf8"));
30024
30402
  return Array.isArray(parsed.modules) ? parsed.modules.map((module) => module.name) : [];
30025
30403
  } catch {
30026
30404
  return [];
@@ -30063,12 +30441,12 @@ async function runAppDev(args, options) {
30063
30441
  throw new ScaffoldError("SCAFFOLD_OPTION_INVALID", "app dev --profile must be fast or integration");
30064
30442
  }
30065
30443
  const database = devDatabase(profile, args.database_url);
30066
- const root = resolve19(args.root || process.cwd());
30444
+ const root = resolve20(args.root || process.cwd());
30067
30445
  const loadedConfig = await loadSupacloudConfig(root);
30068
30446
  const defaults = resolveSupacloudConfig(loadedConfig, root);
30069
30447
  const configuredRoot = sourceRoot(args, root, loadedConfig.root);
30070
30448
  const include = parseInclude(args.include) ?? loadedConfig.include;
30071
- const outDir = args.out_dir ? resolve19(root, args.out_dir) : defaults.outDir;
30449
+ const outDir = args.out_dir ? resolve20(root, args.out_dir) : defaults.outDir;
30072
30450
  const watch = args.once !== true && args.watch !== false;
30073
30451
  const compileOptions = compileOptionsFromConfig({
30074
30452
  ...loadedConfig,
@@ -30154,7 +30532,7 @@ async function runAppDev(args, options) {
30154
30532
  return report(lastEvent, "stopped");
30155
30533
  }
30156
30534
  async function runCompile(args) {
30157
- const root = resolve19(args.root || process.cwd());
30535
+ const root = resolve20(args.root || process.cwd());
30158
30536
  const loadedConfig = await loadSupacloudConfig(root);
30159
30537
  const defaults = resolveSupacloudConfig(loadedConfig, root);
30160
30538
  const configuredRoot = sourceRoot(args, root, loadedConfig.root);
@@ -30163,7 +30541,7 @@ async function runCompile(args) {
30163
30541
  ...compileOptionsFromConfig({
30164
30542
  ...loadedConfig,
30165
30543
  ...configuredRoot === undefined ? {} : { root: configuredRoot },
30166
- outDir: args.out_dir ? resolve19(root, args.out_dir) : defaults.outDir,
30544
+ outDir: args.out_dir ? resolve20(root, args.out_dir) : defaults.outDir,
30167
30545
  ...include === undefined ? {} : { include },
30168
30546
  strict: args.strict ?? loadedConfig.strict ?? false
30169
30547
  }, root),
@@ -30187,7 +30565,7 @@ async function runCompile(args) {
30187
30565
  return textResult2(text, hasError);
30188
30566
  }
30189
30567
  async function runCheck(args) {
30190
- const root = resolve19(args.root || process.cwd());
30568
+ const root = resolve20(args.root || process.cwd());
30191
30569
  const database = checkAppDatabaseSources(root);
30192
30570
  const loadedConfig = await loadSupacloudConfig(root);
30193
30571
  const defaults = resolveSupacloudConfig(loadedConfig, root);
@@ -30196,7 +30574,7 @@ async function runCheck(args) {
30196
30574
  const config = compileOptionsFromConfig({
30197
30575
  ...loadedConfig,
30198
30576
  ...configuredRoot === undefined ? {} : { root: configuredRoot },
30199
- outDir: args.out_dir ? resolve19(root, args.out_dir) : defaults.outDir,
30577
+ outDir: args.out_dir ? resolve20(root, args.out_dir) : defaults.outDir,
30200
30578
  ...include === undefined ? {} : { include },
30201
30579
  strict: args.strict ?? loadedConfig.strict ?? false
30202
30580
  }, root);
@@ -30229,9 +30607,9 @@ async function runCheck(args) {
30229
30607
  }
30230
30608
  async function readManifest(root, args) {
30231
30609
  const config = await loadSupacloudConfig(root);
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)) {
30610
+ const outDir = args.out_dir ? resolve20(root, args.out_dir) : resolveSupacloudConfig(config, root).outDir;
30611
+ const manifestPath = join15(outDir, "app.manifest.json");
30612
+ if (!existsSync13(manifestPath)) {
30235
30613
  throw new Error(`Manifest not found: ${manifestPath}(先运行 app compile 生成)`);
30236
30614
  }
30237
30615
  const parsed = JSON.parse(await readFile5(manifestPath, "utf8"));
@@ -30274,7 +30652,7 @@ function formatGraphText(manifest) {
30274
30652
  `);
30275
30653
  }
30276
30654
  async function runGraph(args) {
30277
- const root = resolve19(args.root || process.cwd());
30655
+ const root = resolve20(args.root || process.cwd());
30278
30656
  const manifest = await readManifest(root, args);
30279
30657
  if (args.format === "json")
30280
30658
  return textResult2(JSON.stringify(manifest, null, 2));
@@ -30342,7 +30720,7 @@ async function runExplain(args) {
30342
30720
  const target = args.target?.trim();
30343
30721
  if (!target)
30344
30722
  throw new Error("app explain requires --target(provider 类名 / token 名 / command 名 / job 名)");
30345
- const root = resolve19(args.root || process.cwd());
30723
+ const root = resolve20(args.root || process.cwd());
30346
30724
  const manifest = await readManifest(root, args);
30347
30725
  for (const module of manifest.modules) {
30348
30726
  const job = module.jobs?.find((entry) => entry.name === target || entry.className === target);
@@ -30417,16 +30795,16 @@ async function runExplain(args) {
30417
30795
  return textResult2(`未找到对象: ${target}`, true);
30418
30796
  }
30419
30797
  async function runExportTools(args) {
30420
- const root = resolve19(args.root || process.cwd());
30798
+ const root = resolve20(args.root || process.cwd());
30421
30799
  const manifest = await readManifest(root, { ...args, out_dir: undefined });
30422
30800
  const definitions = buildToolDefinitions(manifest);
30423
- const outDir = resolve19(args.out_dir || join14(root, "generated"));
30801
+ const outDir = resolve20(args.out_dir || join15(root, "generated"));
30424
30802
  if (args.format === "json") {
30425
30803
  return textResult2(JSON.stringify(definitions, null, 2));
30426
30804
  }
30427
30805
  await mkdir6(outDir, { recursive: true });
30428
- const openaiPath = join14(outDir, "tool-definitions.openai.json");
30429
- const mcpPath = join14(outDir, "tool-definitions.mcp.json");
30806
+ const openaiPath = join15(outDir, "tool-definitions.openai.json");
30807
+ const mcpPath = join15(outDir, "tool-definitions.mcp.json");
30430
30808
  await writeFile5(openaiPath, JSON.stringify(definitions.openai, null, 2), "utf8");
30431
30809
  await writeFile5(mcpPath, JSON.stringify(definitions.mcp, null, 2), "utf8");
30432
30810
  const summary = [
@@ -30441,7 +30819,7 @@ async function runExportTools(args) {
30441
30819
  return textResult2(summary);
30442
30820
  }
30443
30821
  async function runDelivery(args) {
30444
- const root = resolve19(args.root || process.cwd());
30822
+ const root = resolve20(args.root || process.cwd());
30445
30823
  if (args.action === "build") {
30446
30824
  const database = checkAppDatabaseSources(root);
30447
30825
  if (database && !database.ok) {
@@ -30451,7 +30829,7 @@ async function runDelivery(args) {
30451
30829
  const loaded = await loadSupacloudConfig(root);
30452
30830
  const options = compileOptionsFromConfig({
30453
30831
  ...loaded,
30454
- ...args.out_dir === undefined ? {} : { outDir: resolve19(root, args.out_dir) },
30832
+ ...args.out_dir === undefined ? {} : { outDir: resolve20(root, args.out_dir) },
30455
30833
  ...args.include === undefined ? {} : { include: parseInclude(args.include) },
30456
30834
  ...args.strict === undefined ? {} : { strict: args.strict }
30457
30835
  }, root);
@@ -30528,7 +30906,7 @@ async function runAppRelease(request, options, delegate) {
30528
30906
  if (request.activation_id !== undefined || request.expected_activation_id !== undefined) {
30529
30907
  throw new Error("app release generates one activation identity; use app deploy for an exact retry");
30530
30908
  }
30531
- const root = resolve19(request.root || process.cwd());
30909
+ const root = resolve20(request.root || process.cwd());
30532
30910
  const completed = {};
30533
30911
  let manifestPath;
30534
30912
  let buildReceipt;
@@ -30536,7 +30914,7 @@ async function runAppRelease(request, options, delegate) {
30536
30914
  if (request.manifest_path === undefined) {
30537
30915
  throw new Error("app release --skip_build requires --manifest_path");
30538
30916
  }
30539
- manifestPath = resolve19(root, request.manifest_path);
30917
+ manifestPath = resolve20(root, request.manifest_path);
30540
30918
  completed.build = { skipped: true, manifest_path: manifestPath };
30541
30919
  } else {
30542
30920
  const built = await runDelivery({ ...request, action: "build", root, format: "json" });
@@ -30546,7 +30924,7 @@ async function runAppRelease(request, options, delegate) {
30546
30924
  }
30547
30925
  const loaded = await loadSupacloudConfig(root);
30548
30926
  const resolved = resolveSupacloudConfig(loaded, root);
30549
- manifestPath = join14(resolved.outDir, "delivery", "delivery.manifest.json");
30927
+ manifestPath = join15(resolved.outDir, "delivery", "delivery.manifest.json");
30550
30928
  completed.build = {
30551
30929
  ok: true,
30552
30930
  manifest_path: manifestPath,
@@ -30573,7 +30951,7 @@ async function runAppRelease(request, options, delegate) {
30573
30951
  let configurationWrite;
30574
30952
  const activationId = crypto.randomUUID();
30575
30953
  if (request.configuration_path !== undefined) {
30576
- const configurationPath = resolve19(root, request.configuration_path);
30954
+ const configurationPath = resolve20(root, request.configuration_path);
30577
30955
  try {
30578
30956
  configurationWrite = parseApplicationConfigurationWrite(await Bun.file(configurationPath).json());
30579
30957
  configurationId = configurationWrite.configuration_id;
@@ -31109,8 +31487,8 @@ function registerAppTools(server, options = {}) {
31109
31487
  }
31110
31488
 
31111
31489
  // src/shared/tools/db-governance-tools.ts
31112
- import { existsSync as existsSync14 } from "node:fs";
31113
- import { join as join17, resolve as resolve22 } from "node:path";
31490
+ import { existsSync as existsSync15 } from "node:fs";
31491
+ import { join as join18, resolve as resolve23 } from "node:path";
31114
31492
  import {
31115
31493
  buildDatabaseManifest,
31116
31494
  explainObject,
@@ -31123,8 +31501,8 @@ import { databaseSources } from "@supacloud/db/source-contracts";
31123
31501
  // src/shared/tools/db-workflow.ts
31124
31502
  import { createHash as createHash9 } from "node:crypto";
31125
31503
  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";
31126
- import { tmpdir as tmpdir2 } from "node:os";
31127
- import { dirname as dirname11, isAbsolute as isAbsolute7, join as join16, relative as relative8, resolve as resolve21 } from "node:path";
31504
+ import { tmpdir as tmpdir3 } from "node:os";
31505
+ import { dirname as dirname11, isAbsolute as isAbsolute7, join as join17, relative as relative9, resolve as resolve22 } from "node:path";
31128
31506
  import {
31129
31507
  assertApplicationRoleRestricted,
31130
31508
  readDatabaseRole,
@@ -31135,8 +31513,8 @@ import {
31135
31513
  import { parseDatabaseSourcesConfig } from "@supacloud/db/source-contracts";
31136
31514
 
31137
31515
  // src/shared/tools/supabase-cli-tools.ts
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";
31516
+ import { chmodSync as chmodSync2, existsSync as existsSync14, mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync3 } from "node:fs";
31517
+ import { dirname as dirname10, isAbsolute as isAbsolute6, join as join16, resolve as resolve21 } from "node:path";
31140
31518
  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;
31141
31519
  var VALID_VERSION2 = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
31142
31520
  var VALID_MIGRATION_NAME2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,100}$/;
@@ -31196,12 +31574,12 @@ function schemaArguments2(schema) {
31196
31574
  function workdirArguments2(workdir) {
31197
31575
  if (!workdir)
31198
31576
  throw new Error("A workdir is required");
31199
- return ["--workdir", resolve20(workdir)];
31577
+ return ["--workdir", resolve21(workdir)];
31200
31578
  }
31201
31579
  function resolveOutputPath2(workdir, file, label) {
31202
31580
  if (!file || /[\r\n\0]/.test(file))
31203
31581
  throw new Error(`${label} file is required`);
31204
- return isAbsolute6(file) ? resolve20(file) : resolve20(workdir, file);
31582
+ return isAbsolute6(file) ? resolve21(file) : resolve21(workdir, file);
31205
31583
  }
31206
31584
  function databaseTargetArguments2(databaseUrl) {
31207
31585
  return databaseUrl ? ["--db-url", requirePostgresUrl2(databaseUrl)] : ["--local"];
@@ -31376,7 +31754,7 @@ function actionArguments2(request, workdir) {
31376
31754
  function buildOfficialSupabaseArgs2(request) {
31377
31755
  if (request.action === "version")
31378
31756
  return ["--version"];
31379
- const workdir = request.workdir ? resolve20(request.workdir) : undefined;
31757
+ const workdir = request.workdir ? resolve21(request.workdir) : undefined;
31380
31758
  if (!workdir)
31381
31759
  throw new Error("A workdir is required");
31382
31760
  return [...actionArguments2(request, workdir), ...workdirArguments2(workdir)];
@@ -31418,8 +31796,8 @@ function resolveOfficialSupabaseCommand2(workdir, environment = process.env) {
31418
31796
  }
31419
31797
  return ["npx", "--yes", `supabase@${version}`];
31420
31798
  }
31421
- const localPackageEntry = join15(resolve20(workdir), "node_modules", "supabase", "dist", "supabase.js");
31422
- if (existsSync13(localPackageEntry))
31799
+ const localPackageEntry = join16(resolve21(workdir), "node_modules", "supabase", "dist", "supabase.js");
31800
+ if (existsSync14(localPackageEntry))
31423
31801
  return [process.execPath, localPackageEntry];
31424
31802
  return ["supabase"];
31425
31803
  }
@@ -31431,13 +31809,13 @@ var result = (value, isError = false) => ({
31431
31809
  content: [{ type: "text", text: JSON.stringify(value, null, 2) }]
31432
31810
  });
31433
31811
  var schemas = (value) => value?.split(",").map((entry) => entry.trim()).filter(Boolean) ?? ["public"];
31434
- async function projectPath2(root, path) {
31812
+ async function projectPath3(root, path) {
31435
31813
  if (!path || isAbsolute7(path) || path.includes("\\") || path.split("/").some((part) => !part || part === "." || part === "..")) {
31436
31814
  throw new Error("Use a normalized project-relative path");
31437
31815
  }
31438
31816
  let current = root;
31439
31817
  for (const part of path.split("/")) {
31440
- current = join16(current, part);
31818
+ current = join17(current, part);
31441
31819
  try {
31442
31820
  if ((await lstat4(current)).isSymbolicLink())
31443
31821
  throw new Error("Symlink workflow paths are forbidden");
@@ -31459,8 +31837,8 @@ async function exists2(path) {
31459
31837
  }
31460
31838
  }
31461
31839
  async function boundary(root) {
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;
31840
+ const config = join17(root, "database.sources.json");
31841
+ return await exists2(config) ? parseDatabaseSourcesConfig(JSON.parse(await readFile6(await projectPath3(root, "database.sources.json"), "utf8"))) : undefined;
31464
31842
  }
31465
31843
  var overlaps = (a, b) => a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
31466
31844
  async function candidatePath(root, path) {
@@ -31476,7 +31854,7 @@ async function candidatePath(root, path) {
31476
31854
  ];
31477
31855
  if (protectedPaths.some((source) => overlaps(source, path)))
31478
31856
  throw new Error("Candidate output overlaps maintained sources or migrations");
31479
- return projectPath2(root, path);
31857
+ return projectPath3(root, path);
31480
31858
  }
31481
31859
  function connect(url) {
31482
31860
  const client = new Bun.SQL(url);
@@ -31553,9 +31931,9 @@ async function runOfficial(root, workdir, args, environment, options) {
31553
31931
  async function initializeCandidate(stage, majorVersion = 18) {
31554
31932
  if (![15, 16, 17, 18].includes(majorVersion))
31555
31933
  throw new Error("Select a supported PostgreSQL major version (15-18)");
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"), [
31934
+ await mkdir7(join17(stage, "supabase/migrations"), { recursive: true });
31935
+ await mkdir7(join17(stage, "supabase/schemas"), { recursive: true });
31936
+ await writeFile6(join17(stage, "supabase/config.toml"), [
31559
31937
  `project_id = "supacloud-candidate-${hash4(stage).slice(0, 12)}"`,
31560
31938
  "[db]",
31561
31939
  `major_version = ${majorVersion}`,
@@ -31566,16 +31944,16 @@ async function initializeCandidate(stage, majorVersion = 18) {
31566
31944
  `));
31567
31945
  }
31568
31946
  async function copySqlSources(root, source, destination) {
31569
- const path = await projectPath2(root, source);
31947
+ const path = await projectPath3(root, source);
31570
31948
  let count = 0;
31571
31949
  await mkdir7(destination, { recursive: true });
31572
31950
  for (const name of (await readdir6(path)).sort()) {
31573
- const file = await projectPath2(root, `${source}/${name}`);
31951
+ const file = await projectPath3(root, `${source}/${name}`);
31574
31952
  const state = await lstat4(file);
31575
31953
  if (state.isDirectory())
31576
- count += await copySqlSources(root, `${source}/${name}`, join16(destination, name));
31954
+ count += await copySqlSources(root, `${source}/${name}`, join17(destination, name));
31577
31955
  else if (state.isFile() && name.endsWith(".sql")) {
31578
- await writeFile6(join16(destination, name), await readFile6(file));
31956
+ await writeFile6(join17(destination, name), await readFile6(file));
31579
31957
  count++;
31580
31958
  }
31581
31959
  }
@@ -31590,7 +31968,7 @@ async function reverse(args, root, options) {
31590
31968
  throw new Error("Select valid PostgreSQL schemas");
31591
31969
  }
31592
31970
  await mkdir7(dirname11(out), { recursive: true });
31593
- const stage = await mkdtemp(join16(dirname11(out), ".reverse-"));
31971
+ const stage = await mkdtemp(join17(dirname11(out), ".reverse-"));
31594
31972
  try {
31595
31973
  const snapshot = await withDatabase(args, options, async (executor, url) => {
31596
31974
  const snapshot = await reverseDatabase(executor, selectedSchemas);
@@ -31606,15 +31984,15 @@ async function reverse(args, root, options) {
31606
31984
  }, options.environment ?? process.env, options);
31607
31985
  return snapshot;
31608
31986
  });
31609
- const generated = await readdir6(join16(stage, "supabase/schemas"), { recursive: true });
31987
+ const generated = await readdir6(join17(stage, "supabase/schemas"), { recursive: true });
31610
31988
  if (!generated.some((file) => file.endsWith(".sql")))
31611
31989
  throw new Error("Official reverse did not produce declarative SQL");
31612
- await writeFile6(join16(stage, "catalog.json"), renderReverseSnapshot(snapshot));
31990
+ await writeFile6(join17(stage, "catalog.json"), renderReverseSnapshot(snapshot));
31613
31991
  await rename3(stage, out);
31614
31992
  return result({
31615
31993
  ok: true,
31616
31994
  scope: "database-reverse-candidate",
31617
- out: relative8(root, out),
31995
+ out: relative9(root, out),
31618
31996
  databaseWritten: false,
31619
31997
  sourceOverwritten: false,
31620
31998
  review: [...snapshot.review, "Declarative generate and catalog use separate snapshots. Freeze DDL and verify parity before adopting both."]
@@ -31625,7 +32003,7 @@ async function reverse(args, root, options) {
31625
32003
  }
31626
32004
  async function diff2(args, root, options) {
31627
32005
  const sourcePath = args.schema_dir ?? "supabase/schemas";
31628
- const source = await projectPath2(root, sourcePath);
32006
+ const source = await projectPath3(root, sourcePath);
31629
32007
  const out = await candidatePath(root, args.out ?? "output/database-audit/diff");
31630
32008
  if (overlaps(source, out))
31631
32009
  throw new Error("Candidate output overlaps the schema");
@@ -31635,13 +32013,13 @@ async function diff2(args, root, options) {
31635
32013
  if (overlaps(input.dir, out))
31636
32014
  throw new Error("Candidate output overlaps reviewed migration history");
31637
32015
  await mkdir7(dirname11(out), { recursive: true });
31638
- const stage = await mkdtemp(join16(dirname11(out), ".diff-"));
32016
+ const stage = await mkdtemp(join17(dirname11(out), ".diff-"));
31639
32017
  try {
31640
32018
  await initializeCandidate(stage, args.db_major_version);
31641
- if (!await copySqlSources(root, sourcePath, join16(stage, "supabase/schemas")))
32019
+ if (!await copySqlSources(root, sourcePath, join17(stage, "supabase/schemas")))
31642
32020
  throw new Error("No declarative SQL sources");
31643
32021
  for (const { file, text } of input.files)
31644
- await writeFile6(join16(stage, "supabase/migrations", file), text);
32022
+ await writeFile6(join17(stage, "supabase/migrations", file), text);
31645
32023
  await runOfficial(root, stage, {
31646
32024
  action: "db_schema_declarative_sync",
31647
32025
  apply: false,
@@ -31651,15 +32029,15 @@ async function diff2(args, root, options) {
31651
32029
  }, options.environment ?? process.env, options);
31652
32030
  const history = new Map(input.files.map((file) => [file.file, file.text]));
31653
32031
  for (const [file, text] of history) {
31654
- if (await readFile6(join16(stage, "supabase/migrations", file), "utf8") !== text) {
32032
+ if (await readFile6(join17(stage, "supabase/migrations", file), "utf8") !== text) {
31655
32033
  throw new Error("Official diff changed reviewed migration history");
31656
32034
  }
31657
32035
  }
31658
- const names = (await readdir6(join16(stage, "supabase/migrations"))).filter((file) => file.endsWith(".sql") && !history.has(file));
31659
- const candidates = join16(stage, "candidates");
32036
+ const names = (await readdir6(join17(stage, "supabase/migrations"))).filter((file) => file.endsWith(".sql") && !history.has(file));
32037
+ const candidates = join17(stage, "candidates");
31660
32038
  await mkdir7(candidates);
31661
32039
  for (const file of names)
31662
- await writeFile6(join16(candidates, file), await readFile6(join16(stage, "supabase/migrations", file)));
32040
+ await writeFile6(join17(candidates, file), await readFile6(join17(stage, "supabase/migrations", file)));
31663
32041
  await rename3(candidates, out);
31664
32042
  } finally {
31665
32043
  await rm2(stage, { force: true, recursive: true });
@@ -31667,7 +32045,7 @@ async function diff2(args, root, options) {
31667
32045
  return result({
31668
32046
  ok: true,
31669
32047
  scope: "database-migration-candidate",
31670
- out: relative8(root, out),
32048
+ out: relative9(root, out),
31671
32049
  databaseWritten: false,
31672
32050
  review: [
31673
32051
  "Declarative sync compares maintained SQL with replayed migration history, not the live database.",
@@ -31677,13 +32055,13 @@ async function diff2(args, root, options) {
31677
32055
  });
31678
32056
  }
31679
32057
  async function migrations(root, path) {
31680
- const dir = await projectPath2(root, path);
32058
+ const dir = await projectPath3(root, path);
31681
32059
  const names = (await readdir6(dir)).filter((name) => name.endsWith(".sql")).sort();
31682
32060
  if (!names.length)
31683
32061
  throw new Error("No forward migration files");
31684
32062
  const files = [];
31685
32063
  for (const file of names) {
31686
- const text = await readFile6(await projectPath2(root, `${path}/${file}`), "utf8");
32064
+ const text = await readFile6(await projectPath3(root, `${path}/${file}`), "utf8");
31687
32065
  files.push({ file, text, sha256: hash4(text) });
31688
32066
  }
31689
32067
  return { dir, files };
@@ -31697,10 +32075,10 @@ async function migrationAction(args, root, options) {
31697
32075
  throw new Error("Select a Management API and project ref");
31698
32076
  const path = args.dir ?? (await boundary(root))?.migrations ?? "supabase/migrations";
31699
32077
  const input = await migrations(root, path);
31700
- const stage = await mkdtemp(join16(tmpdir2(), "supacloud-reviewed-migrations-"));
32078
+ const stage = await mkdtemp(join17(tmpdir3(), "supacloud-reviewed-migrations-"));
31701
32079
  try {
31702
32080
  for (const { file, text } of input.files)
31703
- await writeFile6(join16(stage, file), text);
32081
+ await writeFile6(join17(stage, file), text);
31704
32082
  const preview = await run({ action: "push_migrations", ref, dir: stage, dry_run: true, strict: true });
31705
32083
  const dryRun = {
31706
32084
  isError: preview.isError === true,
@@ -31727,7 +32105,7 @@ async function migrationAction(args, root, options) {
31727
32105
  }
31728
32106
  }
31729
32107
  async function runDbWorkflow(args, projectRoot, options = {}) {
31730
- const root = resolve21(projectRoot);
32108
+ const root = resolve22(projectRoot);
31731
32109
  if ((await lstat4(root)).isSymbolicLink())
31732
32110
  throw new Error("Workflow root must not be a symlink");
31733
32111
  switch (args.action) {
@@ -31788,8 +32166,8 @@ function normalizeModule(candidate, sourcePath) {
31788
32166
  };
31789
32167
  }
31790
32168
  async function loadDatabaseModules(root, moduleFile) {
31791
- const filePath = moduleFile ? resolve22(root, moduleFile) : join17(root, "db", "modules.ts");
31792
- if (!existsSync14(filePath)) {
32169
+ const filePath = moduleFile ? resolve23(root, moduleFile) : join18(root, "db", "modules.ts");
32170
+ if (!existsSync15(filePath)) {
31793
32171
  throw new Error(moduleFile ? `Module file not found: ${filePath}` : `Module file not found: ${filePath}(用 --module_file 指定一个导出 defineDatabaseModule(...) 的文件)`);
31794
32172
  }
31795
32173
  let imported;
@@ -31878,7 +32256,7 @@ function buildDatabaseAiContext(modules, root, moduleName, target) {
31878
32256
  const objects = target ? allObjects.filter((object) => objectMatchesTarget(object, target)) : allObjects;
31879
32257
  if (target && objects.length === 0)
31880
32258
  throw new Error(`未找到数据库对象: ${target}`);
31881
- const sqlFirst = !existsSync14(join17(root, "zenstack/schema.zmodel")) && existsSync14(join17(root, "supabase/schemas"));
32259
+ const sqlFirst = !existsSync15(join18(root, "zenstack/schema.zmodel")) && existsSync15(join18(root, "supabase/schemas"));
31882
32260
  return {
31883
32261
  version: 1,
31884
32262
  scope: "database-ai-context",
@@ -31925,7 +32303,7 @@ async function collectLintIssues(args, root) {
31925
32303
  const issues = [];
31926
32304
  for (const module of selected) {
31927
32305
  const readSqlFile = async (path) => {
31928
- const absolute = resolve22(root, path);
32306
+ const absolute = resolve23(root, path);
31929
32307
  try {
31930
32308
  return await Bun.file(absolute).text();
31931
32309
  } catch (error) {
@@ -31949,7 +32327,7 @@ ${body}`, hasError);
31949
32327
  async function runCheck2(args, root, environment, spawn, liteBinary, options) {
31950
32328
  const checks = [];
31951
32329
  let ok = true;
31952
- if (existsSync14(join17(root, "database.sources.json"))) {
32330
+ if (existsSync15(join18(root, "database.sources.json"))) {
31953
32331
  try {
31954
32332
  const source = await databaseSources(root, "check");
31955
32333
  checks.push({ name: "source-contract", ok: source.ok, findings: source.findings });
@@ -31962,8 +32340,8 @@ async function runCheck2(args, root, environment, spawn, liteBinary, options) {
31962
32340
  } else {
31963
32341
  checks.push({ name: "source-contract", skipped: true, reason: "database.sources.json not found" });
31964
32342
  }
31965
- const modulePath = args.module_file ? resolve22(root, args.module_file) : join17(root, "db/modules.ts");
31966
- if (existsSync14(modulePath)) {
32343
+ const modulePath = args.module_file ? resolve23(root, args.module_file) : join18(root, "db/modules.ts");
32344
+ if (existsSync15(modulePath)) {
31967
32345
  try {
31968
32346
  const { selected, issues } = await collectLintIssues(args, root);
31969
32347
  const lintOk = !issues.some((issue) => issue.severity === "error");
@@ -32032,14 +32410,14 @@ var defaultLiteSpawn = async (command, cwd) => {
32032
32410
  return { exitCode, stdout, stderr };
32033
32411
  };
32034
32412
  async function runModuleCheckLite(args, root, spawn, liteBinary) {
32035
- const projectDir = resolve22(args.project_dir?.trim() || root);
32413
+ const projectDir = resolve23(args.project_dir?.trim() || root);
32036
32414
  const binary = liteBinary === undefined ? Bun.which("supacloud-lite") : liteBinary;
32037
32415
  if (!binary) {
32038
32416
  throw new Error("db module_check --lite 需要本机可用的 supacloud-lite(npm i -g @supacloud/lite,或加入 PATH)");
32039
32417
  }
32040
32418
  const command = [binary, "db", "check", "--project-dir", projectDir];
32041
32419
  if (args.module_file?.trim())
32042
- command.push("--module-file", resolve22(root, args.module_file.trim()));
32420
+ command.push("--module-file", resolve23(root, args.module_file.trim()));
32043
32421
  const result = await spawn(command, projectDir);
32044
32422
  const output = [result.stdout.trim(), result.stderr.trim()].filter(Boolean).join(`
32045
32423
  `);
@@ -32159,7 +32537,7 @@ function registerDbGovernanceTools(server, options = {}) {
32159
32537
  migration_role: optional(String2(), "[role_sql] Privileged migration role"),
32160
32538
  database: optional(String2(), "[role_sql] PostgreSQL database name")
32161
32539
  }, async (request) => {
32162
- const root = resolve22(request.root || fallbackRoot);
32540
+ const root = resolve23(request.root || fallbackRoot);
32163
32541
  switch (request.action) {
32164
32542
  case "context":
32165
32543
  return runContext2(request, root);
@@ -32199,8 +32577,8 @@ function registerDbGovernanceTools(server, options = {}) {
32199
32577
 
32200
32578
  // src/shared/tools/scheduled-function-tools.ts
32201
32579
  import { randomUUID as randomUUID3 } from "node:crypto";
32202
- import { readFileSync as readFileSync10, statSync as statSync9 } from "node:fs";
32203
- import { resolve as resolve23 } from "node:path";
32580
+ import { readFileSync as readFileSync11, statSync as statSync9 } from "node:fs";
32581
+ import { resolve as resolve24 } from "node:path";
32204
32582
  import { isDeepStrictEqual } from "node:util";
32205
32583
  var HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/;
32206
32584
  var ENVIRONMENT_NAME_PATTERN3 = /^[A-Za-z_][A-Za-z0-9_]{0,255}$/;
@@ -32223,7 +32601,7 @@ var FORBIDDEN_HEADER_NAMES = new Set([
32223
32601
  "x-project-ref"
32224
32602
  ]);
32225
32603
  var SCHEDULE_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
32226
- var SAFE_SLUG_PATTERN2 = /^[A-Za-z0-9_-]{1,128}$/;
32604
+ var SAFE_SLUG_PATTERN3 = /^[A-Za-z0-9_-]{1,128}$/;
32227
32605
  var CRON_PART_PATTERN = /^(\*|([0-9]+)(?:-([0-9]+))?)(?:\/([0-9]+))?$/;
32228
32606
  var CRON_FIELD_BOUNDS = [[0, 59], [0, 23], [1, 31], [1, 12], [0, 7]];
32229
32607
  var MAX_CRON_EXPRESSION_LENGTH = 256;
@@ -32284,14 +32662,14 @@ function validScheduledFunctionCron(expression) {
32284
32662
  function readScheduleBodyFile(bodyPathInput) {
32285
32663
  if (!bodyPathInput.trim())
32286
32664
  throw new Error("'body_file' must be a path");
32287
- const bodyPath = resolve23(bodyPathInput);
32665
+ const bodyPath = resolve24(bodyPathInput);
32288
32666
  const bodyStat = statSync9(bodyPath);
32289
32667
  if (!bodyStat.isFile() || bodyStat.size > MAX_BODY_FILE_BYTES) {
32290
32668
  throw new Error("Scheduled Function body file must be a regular file no larger than 1 MiB");
32291
32669
  }
32292
32670
  let payload;
32293
32671
  try {
32294
- payload = JSON.parse(readFileSync10(bodyPath, "utf8"));
32672
+ payload = JSON.parse(readFileSync11(bodyPath, "utf8"));
32295
32673
  } catch (error) {
32296
32674
  if (!(error instanceof SyntaxError))
32297
32675
  throw error;
@@ -32352,7 +32730,7 @@ function validSafeSchedule(schedule) {
32352
32730
  return validScheduleIdentity(schedule) && validScheduleDefinition(schedule) && validScheduleMetadata(schedule);
32353
32731
  }
32354
32732
  function validScheduleIdentity(schedule) {
32355
- return typeof schedule.id === "string" && SCHEDULE_ID_PATTERN.test(schedule.id) && typeof schedule.name === "string" && schedule.name.trim().length > 0 && schedule.name.length <= MAX_SCHEDULE_NAME_LENGTH && typeof schedule.slug === "string" && SAFE_SLUG_PATTERN2.test(schedule.slug);
32733
+ return typeof schedule.id === "string" && SCHEDULE_ID_PATTERN.test(schedule.id) && typeof schedule.name === "string" && schedule.name.trim().length > 0 && schedule.name.length <= MAX_SCHEDULE_NAME_LENGTH && typeof schedule.slug === "string" && SAFE_SLUG_PATTERN3.test(schedule.slug);
32356
32734
  }
32357
32735
  function validScheduleDefinition(schedule) {
32358
32736
  return typeof schedule.cron === "string" && validScheduledFunctionCron(schedule.cron) && (schedule.method === "GET" || schedule.method === "POST") && typeof schedule.enabled === "boolean";
@@ -32535,7 +32913,7 @@ function requiredName(args, action) {
32535
32913
  }
32536
32914
  function requiredSlug(args, action) {
32537
32915
  const slug = requiredText2(args, "slug", action);
32538
- if (!SAFE_SLUG_PATTERN2.test(slug))
32916
+ if (!SAFE_SLUG_PATTERN3.test(slug))
32539
32917
  throw new Error(`'slug' is invalid for '${action}'`);
32540
32918
  return slug;
32541
32919
  }
@@ -32668,8 +33046,8 @@ var MUTATION_TOOL_SCHEMA = {
32668
33046
 
32669
33047
  // src/shared/tools/release-tools.ts
32670
33048
  import { createHash as createHash10 } from "node:crypto";
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";
33049
+ import { existsSync as existsSync16, mkdirSync as mkdirSync5, readdirSync as readdirSync5, readFileSync as readFileSync12, writeFileSync as writeFileSync4 } from "node:fs";
33050
+ import { dirname as dirname12, join as join19, relative as relative10, resolve as resolve25 } from "node:path";
32673
33051
  var SAFE_PROJECT_REF = /^[A-Za-z0-9_-]{1,64}$/;
32674
33052
  var SAFE_ENVIRONMENT_ID = /^[A-Za-z0-9_-]{1,64}$/;
32675
33053
  var BACKUP_ID = /^logical-full_[A-Za-z0-9_-]{1,64}_[a-f0-9]{32}$/;
@@ -32991,15 +33369,15 @@ function collectScopeFiles(cwd, file, files, dir, task) {
32991
33369
  const results = [];
32992
33370
  const resolvePathWithFallbacks = (filePath) => {
32993
33371
  const trimmed = filePath.trim();
32994
- const resolved = resolve24(cwd, trimmed);
32995
- if (existsSync15(resolved))
33372
+ const resolved = resolve25(cwd, trimmed);
33373
+ if (existsSync16(resolved))
32996
33374
  return resolved;
32997
33375
  const candidates = [
32998
- resolve24(cwd, "supacloud/fa/release-scopes", trimmed),
32999
- resolve24(cwd, "release-scopes", trimmed),
33000
- resolve24(cwd, "scopes", trimmed)
33376
+ resolve25(cwd, "supacloud/fa/release-scopes", trimmed),
33377
+ resolve25(cwd, "release-scopes", trimmed),
33378
+ resolve25(cwd, "scopes", trimmed)
33001
33379
  ];
33002
- const found = candidates.find(existsSync15);
33380
+ const found = candidates.find(existsSync16);
33003
33381
  if (found)
33004
33382
  return found;
33005
33383
  throw new Error(`Scope file not found: ${filePath}`);
@@ -33020,25 +33398,25 @@ function collectScopeFiles(cwd, file, files, dir, task) {
33020
33398
  if (!taskFilter && (!dir || typeof dir !== "string" || !dir.trim())) {
33021
33399
  throw new Error("At least one of --file, --files, or --task is required for scope_rebind");
33022
33400
  }
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")
33401
+ const candidates = typeof dir === "string" && dir.trim() ? [resolve25(cwd, dir.trim())] : [
33402
+ resolve25(cwd, "supacloud/fa/release-scopes"),
33403
+ resolve25(cwd, "release-scopes"),
33404
+ resolve25(cwd, "scopes")
33027
33405
  ];
33028
33406
  for (const directory of candidates) {
33029
- if (existsSync15(directory)) {
33407
+ if (existsSync16(directory)) {
33030
33408
  try {
33031
33409
  const entries = readdirSync5(directory, { withFileTypes: true });
33032
33410
  for (const entry of entries) {
33033
33411
  if (entry.isFile() && entry.name.endsWith(".json")) {
33034
- const fullPath = join18(directory, entry.name);
33412
+ const fullPath = join19(directory, entry.name);
33035
33413
  if (!taskFilter) {
33036
33414
  results.push(fullPath);
33037
33415
  } else if (entry.name.toLowerCase().includes(taskFilter)) {
33038
33416
  results.push(fullPath);
33039
33417
  } else {
33040
33418
  try {
33041
- const parsed = JSON.parse(readFileSync11(fullPath, "utf8"));
33419
+ const parsed = JSON.parse(readFileSync12(fullPath, "utf8"));
33042
33420
  if (typeof parsed?.taskId === "string" && parsed.taskId.toLowerCase() === taskFilter) {
33043
33421
  results.push(fullPath);
33044
33422
  }
@@ -33057,7 +33435,7 @@ function collectScopeFiles(cwd, file, files, dir, task) {
33057
33435
  return [...new Set(results)];
33058
33436
  }
33059
33437
  function handleScopeRebind(args) {
33060
- const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve24(args.cwd.trim()) : process.cwd();
33438
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve25(args.cwd.trim()) : process.cwd();
33061
33439
  const targetBaseCommit = resolveGitBaseCommit(cwd, args.base_commit);
33062
33440
  const requestedEnvironmentId = requestedScopeEnvironment(args, "scope_rebind");
33063
33441
  const scopeFiles = collectScopeFiles(cwd, args.file, args.files, args.dir, args.task);
@@ -33065,7 +33443,7 @@ function handleScopeRebind(args) {
33065
33443
  const parsedScopes = scopeFiles.map((filePath) => {
33066
33444
  let content;
33067
33445
  try {
33068
- content = readFileSync11(filePath, "utf8");
33446
+ content = readFileSync12(filePath, "utf8");
33069
33447
  } catch (cause) {
33070
33448
  throw new Error(`Failed to read scope file '${filePath}': ${cause instanceof Error ? cause.message : String(cause)}`);
33071
33449
  }
@@ -33096,7 +33474,7 @@ function handleScopeRebind(args) {
33096
33474
  writeFileSync4(filePath, formatted, "utf8");
33097
33475
  }
33098
33476
  scopes.push({
33099
- file: relative9(cwd, filePath),
33477
+ file: relative10(cwd, filePath),
33100
33478
  task_id: typeof parsed.taskId === "string" ? parsed.taskId : "",
33101
33479
  target_project_ref: typeof parsed.targetProjectRef === "string" ? parsed.targetProjectRef : "",
33102
33480
  previous_base_commit: previousBaseCommit,
@@ -33115,20 +33493,20 @@ function handleScopeRebind(args) {
33115
33493
  });
33116
33494
  }
33117
33495
  function handleScopeInspect(args) {
33118
- const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve24(args.cwd.trim()) : process.cwd();
33496
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve25(args.cwd.trim()) : process.cwd();
33119
33497
  const requestedEnvironmentId = requestedScopeEnvironment(args, "scope_inspect");
33120
33498
  if (typeof args.file !== "string" || !args.file.trim()) {
33121
33499
  throw new Error("'file' is required for scope_inspect");
33122
33500
  }
33123
33501
  const trimmed = args.file.trim();
33124
- let filePath = resolve24(cwd, trimmed);
33125
- if (!existsSync15(filePath)) {
33502
+ let filePath = resolve25(cwd, trimmed);
33503
+ if (!existsSync16(filePath)) {
33126
33504
  const candidates = [
33127
- resolve24(cwd, "supacloud/fa/release-scopes", trimmed),
33128
- resolve24(cwd, "release-scopes", trimmed),
33129
- resolve24(cwd, "scopes", trimmed)
33505
+ resolve25(cwd, "supacloud/fa/release-scopes", trimmed),
33506
+ resolve25(cwd, "release-scopes", trimmed),
33507
+ resolve25(cwd, "scopes", trimmed)
33130
33508
  ];
33131
- const found = candidates.find(existsSync15);
33509
+ const found = candidates.find(existsSync16);
33132
33510
  if (found)
33133
33511
  filePath = found;
33134
33512
  else
@@ -33136,7 +33514,7 @@ function handleScopeInspect(args) {
33136
33514
  }
33137
33515
  let content;
33138
33516
  try {
33139
- content = readFileSync11(filePath, "utf8");
33517
+ content = readFileSync12(filePath, "utf8");
33140
33518
  } catch (cause) {
33141
33519
  throw new Error(`Failed to read scope file '${args.file}': ${cause instanceof Error ? cause.message : String(cause)}`);
33142
33520
  }
@@ -33156,7 +33534,7 @@ function handleScopeInspect(args) {
33156
33534
  const scopeSha256 = genericScopedReleaseScopeSha256(parsed);
33157
33535
  const git = gitCommitInfo(cwd);
33158
33536
  return releaseControlSuccess("release.scope_inspect", {
33159
- file: relative9(cwd, filePath),
33537
+ file: relative10(cwd, filePath),
33160
33538
  scope: {
33161
33539
  task_id: parsed.taskId,
33162
33540
  target_project_ref: parsed.targetProjectRef,
@@ -33188,20 +33566,20 @@ function releaseComponentView(component) {
33188
33566
  return { kind: component.kind, artifact_sha256: component.artifactSha256 };
33189
33567
  }
33190
33568
  function handleContractPlan(args, fallbackRef) {
33191
- const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve24(args.cwd.trim()) : process.cwd();
33569
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve25(args.cwd.trim()) : process.cwd();
33192
33570
  const requestedRef = typeof args.ref === "string" && args.ref.trim() || fallbackRef;
33193
33571
  if (!requestedRef || !validProjectRef(requestedRef)) {
33194
33572
  throw new Error("'ref' is required for contract_plan and must identify one project");
33195
33573
  }
33196
33574
  const requestedEnvironmentId = requestedScopeEnvironment(args, "contract_plan");
33197
33575
  const file = typeof args.file === "string" && args.file.trim() ? args.file.trim() : "supacloud.release.json";
33198
- const filePath = resolve24(cwd, file);
33199
- if (!existsSync15(filePath)) {
33576
+ const filePath = resolve25(cwd, file);
33577
+ if (!existsSync16(filePath)) {
33200
33578
  throw new Error(`Release contract not found: ${file}`);
33201
33579
  }
33202
33580
  let parsedValue;
33203
33581
  try {
33204
- parsedValue = JSON.parse(readFileSync11(filePath, "utf8"));
33582
+ parsedValue = JSON.parse(readFileSync12(filePath, "utf8"));
33205
33583
  } catch {
33206
33584
  throw new Error(`Release contract '${file}' is not valid JSON`);
33207
33585
  }
@@ -33224,7 +33602,7 @@ function handleContractPlan(args, fallbackRef) {
33224
33602
  }, { migration: 0, function: 0, web: 0 });
33225
33603
  return releaseControlSuccess("release.contract_plan", {
33226
33604
  plan_schema: "supacloud.release-plan.v1",
33227
- file: relative9(cwd, filePath),
33605
+ file: relative10(cwd, filePath),
33228
33606
  release_id: scope.releaseId,
33229
33607
  scope_sha256: releaseScopeSha256(scope),
33230
33608
  source_commit: scope.sourceCommit,
@@ -33258,7 +33636,7 @@ function parseCommaList(value) {
33258
33636
  return [];
33259
33637
  }
33260
33638
  function handleScopeCreate(args, fallbackRef) {
33261
- const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve24(args.cwd.trim()) : process.cwd();
33639
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve25(args.cwd.trim()) : process.cwd();
33262
33640
  if (typeof args.file !== "string" || !args.file.trim()) {
33263
33641
  throw new Error("'file' is required for scope_create");
33264
33642
  }
@@ -33274,7 +33652,7 @@ function handleScopeCreate(args, fallbackRef) {
33274
33652
  throw new Error("'ref' is invalid for release controls");
33275
33653
  }
33276
33654
  const targetBaseCommit = resolveGitBaseCommit(cwd, args.base_commit);
33277
- const filePath = resolve24(cwd, args.file.trim());
33655
+ const filePath = resolve25(cwd, args.file.trim());
33278
33656
  mkdirSync5(dirname12(filePath), { recursive: true });
33279
33657
  const scope = {
33280
33658
  baseCommit: targetBaseCommit,
@@ -33291,7 +33669,7 @@ function handleScopeCreate(args, fallbackRef) {
33291
33669
  `;
33292
33670
  writeFileSync4(filePath, formatted, "utf8");
33293
33671
  return releaseControlSuccess("release.scope_create", {
33294
- file: relative9(cwd, filePath),
33672
+ file: relative10(cwd, filePath),
33295
33673
  task_id: scope.taskId,
33296
33674
  target_project_ref: projectRef,
33297
33675
  target_environment_id: targetEnvironmentId,
@@ -33525,8 +33903,8 @@ function registerReleaseTools(server, http, options = {}) {
33525
33903
  import { access, lstat as lstat5, mkdtemp as mkdtemp2, opendir, readFile as readFile8, rm as rm3, writeFile as writeFile8 } from "node:fs/promises";
33526
33904
  import { spawn as spawn2 } from "node:child_process";
33527
33905
  import { createHash as createHash11 } from "node:crypto";
33528
- import { tmpdir as tmpdir3 } from "node:os";
33529
- import { basename as basename8, dirname as dirname14, join as join20, relative as relative10, resolve as resolve27, sep as sep5 } from "node:path";
33906
+ import { tmpdir as tmpdir4 } from "node:os";
33907
+ import { basename as basename9, dirname as dirname14, join as join21, relative as relative11, resolve as resolve28, sep as sep6 } from "node:path";
33530
33908
 
33531
33909
  // src/shared/tools/project-deployment.ts
33532
33910
  async function requireProjectDeploymentProtocol(http, projectRef, environmentId) {
@@ -33602,14 +33980,14 @@ async function readProjectDeploymentStatus(http, projectRef, environmentId, depl
33602
33980
  }
33603
33981
 
33604
33982
  // src/shared/tools/developer-experience-tools.ts
33605
- import { existsSync as existsSync17 } from "node:fs";
33983
+ import { existsSync as existsSync18 } from "node:fs";
33606
33984
  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";
33985
+ import { dirname as dirname13, join as join20, resolve as resolve27 } from "node:path";
33608
33986
 
33609
33987
  // src/shared/context.ts
33610
- import { existsSync as existsSync16, readFileSync as readFileSync12 } from "node:fs";
33988
+ import { existsSync as existsSync17, readFileSync as readFileSync13 } from "node:fs";
33611
33989
  import { homedir as homedir3 } from "node:os";
33612
- import { resolve as resolve25 } from "node:path";
33990
+ import { resolve as resolve26 } from "node:path";
33613
33991
  var CORE_CONTEXT_KEYS2 = [
33614
33992
  "SUPABASE_URL",
33615
33993
  "SUPABASE_SERVICE_ROLE_KEY",
@@ -33642,11 +34020,11 @@ function parseEnvFile2(contents) {
33642
34020
  return values;
33643
34021
  }
33644
34022
  function projectConfigValues2(cwd, environment) {
33645
- const path = resolve25(cwd, "supacloud.json");
33646
- if (!existsSync16(path))
34023
+ const path = resolve26(cwd, "supacloud.json");
34024
+ if (!existsSync17(path))
33647
34025
  return {};
33648
34026
  try {
33649
- const parsed = JSON.parse(readFileSync12(path, "utf8"));
34027
+ const parsed = JSON.parse(readFileSync13(path, "utf8"));
33650
34028
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
33651
34029
  return {};
33652
34030
  const root = parsed;
@@ -33678,13 +34056,13 @@ function projectConfigValues2(cwd, environment) {
33678
34056
  }
33679
34057
  }
33680
34058
  function readEnvFile2(path, required) {
33681
- if (!existsSync16(path)) {
34059
+ if (!existsSync17(path)) {
33682
34060
  if (required)
33683
34061
  throw new Error(`SupaCloud environment file not found: ${path}`);
33684
34062
  return {};
33685
34063
  }
33686
34064
  try {
33687
- return parseEnvFile2(readFileSync12(path, "utf8"));
34065
+ return parseEnvFile2(readFileSync13(path, "utf8"));
33688
34066
  } catch (error) {
33689
34067
  const message = error instanceof Error ? error.message : String(error);
33690
34068
  throw new Error(`Failed to read SupaCloud environment file ${path}: ${message}`);
@@ -33714,6 +34092,26 @@ function inferProjectRefFromSupabaseUrl2(value) {
33714
34092
  return "";
33715
34093
  return new URL(value).hostname.match(/^([a-z0-9-]+)\.api\./i)?.[1] ?? "";
33716
34094
  }
34095
+ function inferManagementApiUrlFromSupabaseUrl2(value, projectRef = "") {
34096
+ if (!value)
34097
+ return "";
34098
+ const url = new URL(value);
34099
+ const host = url.hostname;
34100
+ if (host.startsWith("api.")) {
34101
+ url.hostname = `studio.${host.slice("api.".length)}`;
34102
+ return url.origin;
34103
+ }
34104
+ const ref = projectRef.trim();
34105
+ if (ref && host.startsWith(`${ref}.api.`)) {
34106
+ url.hostname = `studio-${ref}.${host.slice(`${ref}.api.`.length)}`;
34107
+ return url.origin;
34108
+ }
34109
+ const managedHost = host.match(/^([a-z0-9-]+)\.api\.(.+)$/i);
34110
+ if (!managedHost)
34111
+ return "";
34112
+ url.hostname = `studio-${managedHost[1]}.${managedHost[2]}`;
34113
+ return url.origin;
34114
+ }
33717
34115
  function sourceCredentialScope2(values, explicitApiUrl, supabaseUrl) {
33718
34116
  const hasManagementContext = Boolean(explicitApiUrl.trim() || values.SUPACLOUD_API_TOKEN?.trim() || values.SUPACLOUD_HOST?.trim());
33719
34117
  if (hasManagementContext)
@@ -33725,7 +34123,7 @@ function sourceProjectCore2(values) {
33725
34123
  const projectRef = (values.SUPACLOUD_PROJECT_REF || "").trim() || inferProjectRefFromSupabaseUrl2(supabaseUrl);
33726
34124
  const explicitApiUrl = values.SUPACLOUD_API_URL || "";
33727
34125
  const credentialScope = sourceCredentialScope2(values, explicitApiUrl, supabaseUrl);
33728
- const managementUrl = explicitApiUrl || (values.SUPACLOUD_HOST ? `http://${values.SUPACLOUD_HOST}:9090` : "");
34126
+ const managementUrl = explicitApiUrl || (credentialScope === "management" ? inferManagementApiUrlFromSupabaseUrl2(supabaseUrl, projectRef) : "") || (values.SUPACLOUD_HOST ? `http://${values.SUPACLOUD_HOST}:9090` : "");
33729
34127
  const apiUrl = credentialScope === "management" ? canonicalApiOrigin2(managementUrl) : "";
33730
34128
  const apiToken = credentialScope === "management" ? values.SUPACLOUD_API_TOKEN || "" : "";
33731
34129
  return { apiUrl, apiToken, projectRef, supabaseUrl, credentialScope };
@@ -33755,7 +34153,7 @@ function parseInsecureTls2(values) {
33755
34153
  }
33756
34154
  function namedEnvironmentSource2(cwd, selector) {
33757
34155
  const environment = normalizeEnvironmentName(selector);
33758
- const path = resolve25(cwd, `.env.supacloud.${selector}`);
34156
+ const path = resolve26(cwd, `.env.supacloud.${selector}`);
33759
34157
  const values = readEnvFile2(path, true);
33760
34158
  if (values.SUPACLOUD_ENV && normalizeEnvironmentName(values.SUPACLOUD_ENV) !== environment) {
33761
34159
  throw new Error(`SUPACLOUD_ENV in ${path} does not match selector ${selector}`);
@@ -33763,7 +34161,7 @@ function namedEnvironmentSource2(cwd, selector) {
33763
34161
  return { values, kind: "named_env_file", path, environment };
33764
34162
  }
33765
34163
  function explicitEnvironmentSource2(cwd, envFile) {
33766
- const path = resolve25(cwd, envFile);
34164
+ const path = resolve26(cwd, envFile);
33767
34165
  const values = readEnvFile2(path, true);
33768
34166
  if (!values.SUPACLOUD_ENV)
33769
34167
  throw new Error(`SUPACLOUD_ENV is required in ${path}`);
@@ -33806,18 +34204,18 @@ function contextSource2(env, cwd, selection) {
33806
34204
  if (hasProcessContext2(env)) {
33807
34205
  return { values: processValues2(env), kind: "process_env", path: null, environment: "" };
33808
34206
  }
33809
- const path = resolve25(cwd, ".env");
34207
+ const path = resolve26(cwd, ".env");
33810
34208
  const values = readEnvFile2(path, false);
33811
34209
  const environment = values.SUPACLOUD_ENV ? normalizeEnvironmentName(values.SUPACLOUD_ENV) : "";
33812
34210
  if (environment) {
33813
34211
  return {
33814
34212
  values: { ...projectConfigValues2(cwd, environment), ...values },
33815
34213
  kind: "legacy_dotenv",
33816
- path: existsSync16(path) ? path : null,
34214
+ path: existsSync17(path) ? path : null,
33817
34215
  environment
33818
34216
  };
33819
34217
  }
33820
- return { values, kind: Object.keys(values).length ? "legacy_dotenv" : "none", path: existsSync16(path) ? path : null, environment };
34218
+ return { values, kind: Object.keys(values).length ? "legacy_dotenv" : "none", path: existsSync17(path) ? path : null, environment };
33821
34219
  }
33822
34220
  function resolveSupaCloudContext2(env = process.env, cwd = process.cwd(), selection = {}) {
33823
34221
  const source = contextSource2(env, cwd, selection);
@@ -33829,7 +34227,7 @@ function resolveSupaCloudContext2(env = process.env, cwd = process.cwd(), select
33829
34227
  host,
33830
34228
  sshUser: env.SUPACLOUD_SSH_USER ?? "root",
33831
34229
  sshPort: parseInt(env.SUPACLOUD_SSH_PORT ?? "22", 10),
33832
- sshKey: env.SUPACLOUD_SSH_KEY ?? resolve25(homedir3(), ".ssh", "id_rsa"),
34230
+ sshKey: env.SUPACLOUD_SSH_KEY ?? resolve26(homedir3(), ".ssh", "id_rsa"),
33833
34231
  sshPass: env.SUPACLOUD_SSH_PASS ?? "",
33834
34232
  apiUrl: core.apiUrl,
33835
34233
  apiToken: core.apiToken,
@@ -33886,7 +34284,7 @@ function textResult4(text, isError = false) {
33886
34284
  function jsonResult2(value, isError = false) {
33887
34285
  return textResult4(JSON.stringify(value, null, 2), isError);
33888
34286
  }
33889
- function record6(value) {
34287
+ function record7(value) {
33890
34288
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
33891
34289
  }
33892
34290
  function packageDependencies(manifest) {
@@ -33904,17 +34302,17 @@ function outputDirectoryFor(manifest) {
33904
34302
  return "dist";
33905
34303
  }
33906
34304
  async function readPackageManifest(root) {
33907
- const path = join19(root, "package.json");
33908
- if (!existsSync17(path))
34305
+ const path = join20(root, "package.json");
34306
+ if (!existsSync18(path))
33909
34307
  return {};
33910
34308
  try {
33911
34309
  const parsed = JSON.parse(await readFile7(path, "utf8"));
33912
- const value = record6(parsed);
34310
+ const value = record7(parsed);
33913
34311
  if (!value)
33914
34312
  throw new Error("package.json must contain an object");
33915
- const scripts = record6(value.scripts);
33916
- const dependencies = record6(value.dependencies);
33917
- const devDependencies = record6(value.devDependencies);
34313
+ const scripts = record7(value.scripts);
34314
+ const dependencies = record7(value.dependencies);
34315
+ const devDependencies = record7(value.devDependencies);
33918
34316
  return {
33919
34317
  scripts: scripts ?? undefined,
33920
34318
  dependencies: dependencies ?? undefined,
@@ -33935,8 +34333,8 @@ async function writeNewFile(path, content) {
33935
34333
  }
33936
34334
  }
33937
34335
  async function ensureGitignore(root) {
33938
- const path = join19(root, ".gitignore");
33939
- const existing = existsSync17(path) ? await readFile7(path, "utf8") : "";
34336
+ const path = join20(root, ".gitignore");
34337
+ const existing = existsSync18(path) ? await readFile7(path, "utf8") : "";
33940
34338
  const required = [".env.supacloud.*", "!.env.supacloud.*.example"];
33941
34339
  const missing = required.filter((entry) => !existing.split(/\r?\n/).includes(entry));
33942
34340
  if (missing.length === 0)
@@ -33950,10 +34348,10 @@ async function ensureGitignore(root) {
33950
34348
  return true;
33951
34349
  }
33952
34350
  async function initializeProject(request, options = {}) {
33953
- const root = resolve26(request.root || options.cwd || process.cwd());
34351
+ const root = resolve27(request.root || options.cwd || process.cwd());
33954
34352
  await mkdir8(root, { recursive: true });
33955
- const configPath = join19(root, "supacloud.json");
33956
- if (existsSync17(configPath)) {
34353
+ const configPath = join20(root, "supacloud.json");
34354
+ if (existsSync18(configPath)) {
33957
34355
  throw new Error(`supacloud.json already exists in ${root}; init never overwrites project configuration`);
33958
34356
  }
33959
34357
  const manifest = await readPackageManifest(root);
@@ -33980,10 +34378,10 @@ async function initializeProject(request, options = {}) {
33980
34378
  throw error;
33981
34379
  }
33982
34380
  created.push("supacloud.json");
33983
- if (await writeNewFile(join19(root, ".env.supacloud.test.example"), TEST_PROFILE)) {
34381
+ if (await writeNewFile(join20(root, ".env.supacloud.test.example"), TEST_PROFILE)) {
33984
34382
  created.push(".env.supacloud.test.example");
33985
34383
  }
33986
- if (await writeNewFile(join19(root, ".env.supacloud.production.example"), PRODUCTION_PROFILE)) {
34384
+ if (await writeNewFile(join20(root, ".env.supacloud.production.example"), PRODUCTION_PROFILE)) {
33987
34385
  created.push(".env.supacloud.production.example");
33988
34386
  }
33989
34387
  if (await ensureGitignore(root))
@@ -33994,7 +34392,7 @@ async function initializeProject(request, options = {}) {
33994
34392
  root,
33995
34393
  created,
33996
34394
  detected: {
33997
- package_json: existsSync17(join19(root, "package.json")),
34395
+ package_json: existsSync18(join20(root, "package.json")),
33998
34396
  build_script: hasBuildScript,
33999
34397
  output_directory: outputDirectory
34000
34398
  },
@@ -34039,22 +34437,22 @@ var deployToolSchema = {
34039
34437
  status: optional(String2({ format: "uuid" }), "Read a backend deployment status without publishing"),
34040
34438
  format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
34041
34439
  };
34042
- function record7(candidate) {
34440
+ function record8(candidate) {
34043
34441
  return candidate && typeof candidate === "object" && !Array.isArray(candidate) ? candidate : null;
34044
34442
  }
34045
- function requiredString(candidate, field) {
34443
+ function requiredString2(candidate, field) {
34046
34444
  if (typeof candidate !== "string" || !candidate.trim()) {
34047
34445
  throw new Error(`Invalid frontend deployment response: missing ${field}`);
34048
34446
  }
34049
34447
  return candidate.trim();
34050
34448
  }
34051
34449
  function frontendDeployment(candidate) {
34052
- const value = record7(candidate);
34450
+ const value = record8(candidate);
34053
34451
  if (!value)
34054
34452
  throw new Error("Invalid frontend deployment response");
34055
34453
  return {
34056
- id: requiredString(value.id, "id"),
34057
- name: typeof value.name === "string" && value.name.trim() ? value.name.trim() : requiredString(value.id, "id"),
34454
+ id: requiredString2(value.id, "id"),
34455
+ name: typeof value.name === "string" && value.name.trim() ? value.name.trim() : requiredString2(value.id, "id"),
34058
34456
  framework: typeof value.framework === "string" ? value.framework.trim() : "static",
34059
34457
  buildCommand: typeof value.build_command === "string" ? value.build_command.trim() : "",
34060
34458
  outputDirectory: typeof value.output_dir === "string" ? value.output_dir.trim() : "",
@@ -34071,15 +34469,15 @@ async function readJson(path) {
34071
34469
  }
34072
34470
  }
34073
34471
  async function findDeployConfigRoot(startDirectory, environmentName) {
34074
- let directory = resolve27(startDirectory);
34472
+ let directory = resolve28(startDirectory);
34075
34473
  while (true) {
34076
34474
  const environmentFile = environmentName ? `.env.supacloud.${environmentName}` : null;
34077
- if (await pathExists(join20(directory, "supacloud.json")) || await pathExists(join20(directory, "supacloud.config.ts")) || environmentFile !== null && await pathExists(join20(directory, environmentFile))) {
34475
+ if (await pathExists(join21(directory, "supacloud.json")) || await pathExists(join21(directory, "supacloud.config.ts")) || environmentFile !== null && await pathExists(join21(directory, environmentFile))) {
34078
34476
  return directory;
34079
34477
  }
34080
34478
  const parent = dirname14(directory);
34081
34479
  if (parent === directory)
34082
- return resolve27(startDirectory);
34480
+ return resolve28(startDirectory);
34083
34481
  directory = parent;
34084
34482
  }
34085
34483
  }
@@ -34119,7 +34517,7 @@ function optionalStringArray(value, field) {
34119
34517
  });
34120
34518
  }
34121
34519
  function deployTargetConfig(candidate, name) {
34122
- const value = record7(candidate);
34520
+ const value = record8(candidate);
34123
34521
  if (!value || value.type !== "frontend" && value.type !== "edge_function") {
34124
34522
  throw new Error(`supacloud.json targets.${name}.type must be 'frontend' or 'edge_function'`);
34125
34523
  }
@@ -34144,14 +34542,14 @@ function deployTargetConfig(candidate, name) {
34144
34542
  };
34145
34543
  }
34146
34544
  async function readDeployConfig(configRoot) {
34147
- const configPath = join20(configRoot, "supacloud.json");
34545
+ const configPath = join21(configRoot, "supacloud.json");
34148
34546
  const candidate = await readJson(configPath);
34149
34547
  if (candidate === null)
34150
34548
  return {};
34151
- const config = record7(candidate);
34152
- const frontend = record7(config?.frontend);
34153
- const application = record7(config?.application);
34154
- const targetValues = record7(config?.targets);
34549
+ const config = record8(candidate);
34550
+ const frontend = record8(config?.frontend);
34551
+ const application = record8(config?.application);
34552
+ const targetValues = record8(config?.targets);
34155
34553
  if (!config || config.frontend !== undefined && !frontend || config.application !== undefined && !application || config.targets !== undefined && !targetValues) {
34156
34554
  throw new Error("supacloud.json must contain object-valued 'application', 'frontend' or 'targets' configuration");
34157
34555
  }
@@ -34191,16 +34589,16 @@ async function readDeployConfig(configRoot) {
34191
34589
  };
34192
34590
  }
34193
34591
  async function packageName(projectDirectory) {
34194
- const candidate = record7(await readJson(join20(projectDirectory, "package.json")));
34592
+ const candidate = record8(await readJson(join21(projectDirectory, "package.json")));
34195
34593
  return typeof candidate?.name === "string" && candidate.name.trim() ? candidate.name.trim() : null;
34196
34594
  }
34197
34595
  async function pathExists(path) {
34198
34596
  return access(path).then(() => true, () => false);
34199
34597
  }
34200
34598
  async function hasProjectReleaseManifest(root) {
34201
- if (await pathExists(join20(root, "deploy-manifest.json")))
34599
+ if (await pathExists(join21(root, "deploy-manifest.json")))
34202
34600
  return true;
34203
- const directory = await opendir(join20(root, "supacloud")).catch((error) => {
34601
+ const directory = await opendir(join21(root, "supacloud")).catch((error) => {
34204
34602
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
34205
34603
  return null;
34206
34604
  throw error;
@@ -34211,36 +34609,36 @@ async function hasProjectReleaseManifest(root) {
34211
34609
  for await (const entry of directory) {
34212
34610
  if (++entries > 128)
34213
34611
  throw new Error("Too many SupaCloud project roots to resolve a deployment");
34214
- if ((entry.isDirectory() || entry.isSymbolicLink()) && await pathExists(join20(root, "supacloud", entry.name, "deploy-manifest.json")))
34612
+ if ((entry.isDirectory() || entry.isSymbolicLink()) && await pathExists(join21(root, "supacloud", entry.name, "deploy-manifest.json")))
34215
34613
  return true;
34216
34614
  }
34217
34615
  return false;
34218
34616
  }
34219
34617
  async function defaultBuildCommand(projectDirectory, configRoot) {
34220
- const packageJson = record7(await readJson(join20(projectDirectory, "package.json")));
34221
- const scripts = record7(packageJson?.scripts);
34618
+ const packageJson = record8(await readJson(join21(projectDirectory, "package.json")));
34619
+ const scripts = record8(packageJson?.scripts);
34222
34620
  if (typeof scripts?.build !== "string" || !scripts.build.trim()) {
34223
34621
  throw new Error("No build command was configured and package.json has no build script");
34224
34622
  }
34225
34623
  let directory = projectDirectory;
34226
34624
  while (true) {
34227
- if (await pathExists(join20(directory, "bun.lock")) || await pathExists(join20(directory, "bun.lockb")))
34625
+ if (await pathExists(join21(directory, "bun.lock")) || await pathExists(join21(directory, "bun.lockb")))
34228
34626
  return "bun run build";
34229
- if (await pathExists(join20(directory, "pnpm-lock.yaml")))
34627
+ if (await pathExists(join21(directory, "pnpm-lock.yaml")))
34230
34628
  return "pnpm run build";
34231
- if (await pathExists(join20(directory, "yarn.lock")))
34629
+ if (await pathExists(join21(directory, "yarn.lock")))
34232
34630
  return "yarn build";
34233
34631
  if (directory === configRoot)
34234
34632
  break;
34235
34633
  const parent = dirname14(directory);
34236
- if (parent === directory || !directory.startsWith(`${configRoot}${sep5}`))
34634
+ if (parent === directory || !directory.startsWith(`${configRoot}${sep6}`))
34237
34635
  break;
34238
34636
  directory = parent;
34239
34637
  }
34240
34638
  return "npm run build";
34241
34639
  }
34242
34640
  function deploymentList(candidate) {
34243
- const values = Array.isArray(candidate) ? candidate : Array.isArray(record7(candidate)?.deployments) ? record7(candidate)?.deployments : null;
34641
+ const values = Array.isArray(candidate) ? candidate : Array.isArray(record8(candidate)?.deployments) ? record8(candidate)?.deployments : null;
34244
34642
  if (!values)
34245
34643
  throw new Error("Invalid frontend deployment list response");
34246
34644
  return values.map(frontendDeployment);
@@ -34300,9 +34698,9 @@ function selectFrontendTarget(configRoot, config) {
34300
34698
  throw new Error(`Multiple frontend deploy targets found (${targets.map(([name]) => name).sort().join(", ")}). Set defaultTarget to the Web target`);
34301
34699
  }
34302
34700
  function targetRoot(configRoot, target, name) {
34303
- const root = resolve27(configRoot, target.root || (name === "frontend" ? "." : name));
34304
- const prefix = `${resolve27(configRoot)}${sep5}`;
34305
- if (root !== resolve27(configRoot) && !root.startsWith(prefix)) {
34701
+ const root = resolve28(configRoot, target.root || (name === "frontend" ? "." : name));
34702
+ const prefix = `${resolve28(configRoot)}${sep6}`;
34703
+ if (root !== resolve28(configRoot) && !root.startsWith(prefix)) {
34306
34704
  throw new Error(`Deploy target '${name}' root must stay inside the repository root`);
34307
34705
  }
34308
34706
  return root;
@@ -34320,9 +34718,9 @@ function defaultOutputDirectory(framework) {
34320
34718
  }
34321
34719
  }
34322
34720
  function resolveInsideProject(projectDirectory, candidate, allowRoot = false) {
34323
- const resolved = resolve27(projectDirectory, candidate);
34324
- const projectRoot = resolve27(projectDirectory);
34325
- const projectPrefix = `${projectRoot}${sep5}`;
34721
+ const resolved = resolve28(projectDirectory, candidate);
34722
+ const projectRoot = resolve28(projectDirectory);
34723
+ const projectPrefix = `${projectRoot}${sep6}`;
34326
34724
  if (!allowRoot && resolved === projectRoot || resolved !== projectRoot && !resolved.startsWith(projectPrefix)) {
34327
34725
  throw new Error("Frontend output directory must stay inside the project directory");
34328
34726
  }
@@ -34375,7 +34773,7 @@ async function collectArchiveFiles(root) {
34375
34773
  entries.push(entry);
34376
34774
  entries.sort((left, right) => left.name.localeCompare(right.name, "en"));
34377
34775
  for (const entry of entries) {
34378
- const path = join20(directory, entry.name);
34776
+ const path = join21(directory, entry.name);
34379
34777
  const stats = await lstat5(path);
34380
34778
  if (stats.isSymbolicLink())
34381
34779
  throw new Error(`Frontend output cannot contain symbolic links: ${path}`);
@@ -34398,7 +34796,7 @@ async function collectArchiveFiles(root) {
34398
34796
  bytes += data.byteLength;
34399
34797
  if (bytes > MAX_SOURCE_BYTES)
34400
34798
  throw new Error(`Frontend output exceeds ${MAX_SOURCE_BYTES} bytes`);
34401
- const archivePath = relative10(root, path).split(sep5).join("/");
34799
+ const archivePath = relative11(root, path).split(sep6).join("/");
34402
34800
  files.set(archivePath, data);
34403
34801
  digests.push({ path: archivePath, size: data.byteLength, sha256: createHash11("sha256").update(data).digest("hex") });
34404
34802
  }
@@ -34413,8 +34811,8 @@ async function collectArchiveFiles(root) {
34413
34811
  return { files, bytes, count: paths.length, treeSha256: tree.digest("hex") };
34414
34812
  }
34415
34813
  async function createCollectedFrontendArchive(outputDirectory, collected) {
34416
- const temporaryDirectory = await mkdtemp2(join20(tmpdir3(), "supacloud-deploy-"));
34417
- const archivePath = join20(temporaryDirectory, `${basename8(outputDirectory)}.tar.zst`);
34814
+ const temporaryDirectory = await mkdtemp2(join21(tmpdir4(), "supacloud-deploy-"));
34815
+ const archivePath = join21(temporaryDirectory, `${basename9(outputDirectory)}.tar.zst`);
34418
34816
  try {
34419
34817
  const archiveBytes = await createFrontendTarZstd(collected.files);
34420
34818
  await writeFile8(archivePath, archiveBytes);
@@ -34462,7 +34860,7 @@ async function publishConfiguredFrontend(http, projectRef, configRoot, skipBuild
34462
34860
  }
34463
34861
  function registerDeployTools(server, http, options = {}) {
34464
34862
  registerTool(server, "deploy", "Build and publish the linked project with one command", deployToolSchema, async (args) => {
34465
- const invocationDirectory = resolve27(String(args.cwd || options.cwd || process.cwd()));
34863
+ const invocationDirectory = resolve28(String(args.cwd || options.cwd || process.cwd()));
34466
34864
  if (args.action === "init") {
34467
34865
  return initializeProject({
34468
34866
  ...typeof args.root === "string" ? { root: args.root } : {},
@@ -34543,11 +34941,11 @@ function registerDeployTools(server, http, options = {}) {
34543
34941
  }
34544
34942
 
34545
34943
  // src/shared/tools/remote-dev-tools.ts
34546
- import { existsSync as existsSync18 } from "node:fs";
34944
+ import { existsSync as existsSync19 } from "node:fs";
34547
34945
  import { readFile as readFile9 } from "node:fs/promises";
34548
34946
  import { readdir as readdir8 } from "node:fs/promises";
34549
34947
  import { createHash as createHash12 } from "node:crypto";
34550
- import { join as join21, resolve as resolve28 } from "node:path";
34948
+ import { join as join22, resolve as resolve29 } from "node:path";
34551
34949
  import { compileProject as compileProject2 } from "@supacloud/compiler";
34552
34950
  var SAFE_TOKEN = /^[A-Za-z0-9._:@/+,-]+$/;
34553
34951
  var SAFE_REMOTE_ROOT = /^\/(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+\/?$/;
@@ -34575,8 +34973,8 @@ async function runProcess(executable, args, cwd) {
34575
34973
  return { exitCode: exitCode ?? 1, stdout, stderr };
34576
34974
  }
34577
34975
  async function readProjectConfig(root) {
34578
- const file = join21(root, "supacloud.json");
34579
- if (!existsSync18(file))
34976
+ const file = join22(root, "supacloud.json");
34977
+ if (!existsSync19(file))
34580
34978
  return {};
34581
34979
  try {
34582
34980
  const parsed = JSON.parse(await readFile9(file, "utf8"));
@@ -34597,7 +34995,7 @@ async function sourceFingerprint(root) {
34597
34995
  const visit = async (directory) => {
34598
34996
  const entries = await readdir8(directory, { withFileTypes: true });
34599
34997
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
34600
- const path = join21(directory, entry.name);
34998
+ const path = join22(directory, entry.name);
34601
34999
  if (entry.isDirectory() && ![".git", "node_modules", "dist", "generated", ".supacloud"].includes(entry.name))
34602
35000
  await visit(path);
34603
35001
  else if (entry.isFile())
@@ -34625,19 +35023,19 @@ function remoteRoot(value) {
34625
35023
  }
34626
35024
  function targetDirectory(root, target, functionSlug, config = {}) {
34627
35025
  if (target === "db")
34628
- return join21(root, "supabase", "migrations");
35026
+ return join22(root, "supabase", "migrations");
34629
35027
  if (target === "functions") {
34630
35028
  const targets = config["targets"];
34631
35029
  const entries = targets && typeof targets === "object" ? Object.values(targets) : [];
34632
35030
  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));
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;
35031
+ const base = match?.root ? resolve29(root, match.root) : join22(root, "supabase", "functions");
35032
+ return match?.root ? base : functionSlug ? join22(base, safeToken(functionSlug, "function")) : base;
34635
35033
  }
34636
35034
  if (target === "frontend") {
34637
35035
  const targets = config["targets"];
34638
35036
  const entries = targets && typeof targets === "object" ? Object.values(targets) : [];
34639
35037
  const match = entries.find((entry) => entry !== null && typeof entry === "object" && ("type" in entry) && entry.type === "frontend" && (!("root" in entry) || typeof entry.root === "string"));
34640
- return match?.root ? resolve28(root, match.root) : join21(root, "apps", "web");
35038
+ return match?.root ? resolve29(root, match.root) : join22(root, "apps", "web");
34641
35039
  }
34642
35040
  return root;
34643
35041
  }
@@ -34676,10 +35074,10 @@ function reloadCommand(config, target, projectRef, functionSlug) {
34676
35074
  return [...command.split(" "), "--project-ref", safeToken(projectRef || "test", "project_ref"), "--target", targetConfigPath(target), ...functionSlug ? ["--function", safeToken(functionSlug, "function")] : []];
34677
35075
  }
34678
35076
  function sshArgs(connection, remoteCommand) {
34679
- return ["-p", String(connection.port), "-i", resolve28(connection.key), "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", `${connection.user}@${connection.host}`, ...remoteCommand];
35077
+ return ["-p", String(connection.port), "-i", resolve29(connection.key), "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", `${connection.user}@${connection.host}`, ...remoteCommand];
34680
35078
  }
34681
35079
  function rsyncArgs(connection, source, destination, excludes, deleteRemote) {
34682
- const args = ["-az", "--checksum", "--partial", "--protect-args", "-e", `ssh -p ${connection.port} -i ${resolve28(connection.key)} -o BatchMode=yes -o StrictHostKeyChecking=yes`];
35080
+ const args = ["-az", "--checksum", "--partial", "--protect-args", "-e", `ssh -p ${connection.port} -i ${resolve29(connection.key)} -o BatchMode=yes -o StrictHostKeyChecking=yes`];
34683
35081
  if (deleteRemote)
34684
35082
  args.push("--delete-delay");
34685
35083
  for (const exclude of excludes) {
@@ -34691,17 +35089,17 @@ function rsyncArgs(connection, source, destination, excludes, deleteRemote) {
34691
35089
  return args;
34692
35090
  }
34693
35091
  async function syncOnce(args, options) {
34694
- const root = resolve28(String(args.project_dir || options.cwd || process.cwd()));
35092
+ const root = resolve29(String(args.project_dir || options.cwd || process.cwd()));
34695
35093
  const projectConfig = await readProjectConfig(root);
34696
35094
  const config = projectConfig.dev || {};
34697
35095
  const target = String(args.target || "project");
34698
35096
  const source = targetDirectory(root, target, typeof args.function === "string" ? args.function : undefined, projectConfig);
34699
- if (!existsSync18(source))
35097
+ if (!existsSync19(source))
34700
35098
  throw new Error(`Dev source directory not found: ${source}`);
34701
35099
  let compiled = false;
34702
35100
  if (config.compile === true && target !== "db") {
34703
- const compileRoot = resolve28(root, config.compileRoot || ".");
34704
- const compileOutDir = resolve28(root, config.compileOutDir || "generated");
35101
+ const compileRoot = resolve29(root, config.compileRoot || ".");
35102
+ const compileOutDir = resolve29(root, config.compileOutDir || "generated");
34705
35103
  const compilation = await compileProject2({
34706
35104
  rootDir: compileRoot,
34707
35105
  outDir: compileOutDir,
@@ -34739,7 +35137,7 @@ function registerRemoteDevTools(server, options = {}) {
34739
35137
  if (["production", "prod"].includes((options.environment || "").toLowerCase()))
34740
35138
  throw new Error("Remote dev mode is forbidden for production environments");
34741
35139
  if (args.action === "status") {
34742
- const root = resolve28(String(args.project_dir || options.cwd || process.cwd()));
35140
+ const root = resolve29(String(args.project_dir || options.cwd || process.cwd()));
34743
35141
  const config = await readDevConfig(root);
34744
35142
  const connection = connectionArgs(options, config, args);
34745
35143
  const execute = options.execute || ((command, commandArgs, cwd) => runProcess(command, commandArgs, cwd));
@@ -34750,7 +35148,7 @@ function registerRemoteDevTools(server, options = {}) {
34750
35148
  return { content: [{ type: "text", text: JSON.stringify(await syncOnce(args, options), null, 2) }] };
34751
35149
  }
34752
35150
  if (args.action === "watch") {
34753
- const root = resolve28(String(args.project_dir || options.cwd || process.cwd()));
35151
+ const root = resolve29(String(args.project_dir || options.cwd || process.cwd()));
34754
35152
  const interval = Math.max(100, Math.min(1e4, Number(args.interval_ms || 300)));
34755
35153
  let fingerprint = "";
34756
35154
  let lastSync = null;
@@ -34770,9 +35168,9 @@ function registerRemoteDevTools(server, options = {}) {
34770
35168
  }
34771
35169
 
34772
35170
  // src/shared/tools/developer-experience-tools.ts
34773
- import { existsSync as existsSync19 } from "node:fs";
35171
+ import { existsSync as existsSync20 } from "node:fs";
34774
35172
  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";
35173
+ import { dirname as dirname15, join as join23, resolve as resolve30 } from "node:path";
34776
35174
  var initToolSchema2 = {
34777
35175
  root: optional(String2(), "Project directory to initialize (default: current directory)"),
34778
35176
  format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
@@ -34806,7 +35204,7 @@ function textResult5(text, isError = false) {
34806
35204
  function jsonResult3(value, isError = false) {
34807
35205
  return textResult5(JSON.stringify(value, null, 2), isError);
34808
35206
  }
34809
- function record8(value) {
35207
+ function record9(value) {
34810
35208
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
34811
35209
  }
34812
35210
  function packageDependencies2(manifest) {
@@ -34824,17 +35222,17 @@ function outputDirectoryFor2(manifest) {
34824
35222
  return "dist";
34825
35223
  }
34826
35224
  async function readPackageManifest2(root) {
34827
- const path = join22(root, "package.json");
34828
- if (!existsSync19(path))
35225
+ const path = join23(root, "package.json");
35226
+ if (!existsSync20(path))
34829
35227
  return {};
34830
35228
  try {
34831
35229
  const parsed = JSON.parse(await readFile10(path, "utf8"));
34832
- const value = record8(parsed);
35230
+ const value = record9(parsed);
34833
35231
  if (!value)
34834
35232
  throw new Error("package.json must contain an object");
34835
- const scripts = record8(value.scripts);
34836
- const dependencies = record8(value.dependencies);
34837
- const devDependencies = record8(value.devDependencies);
35233
+ const scripts = record9(value.scripts);
35234
+ const dependencies = record9(value.dependencies);
35235
+ const devDependencies = record9(value.devDependencies);
34838
35236
  return {
34839
35237
  scripts: scripts ?? undefined,
34840
35238
  dependencies: dependencies ?? undefined,
@@ -34855,8 +35253,8 @@ async function writeNewFile2(path, content) {
34855
35253
  }
34856
35254
  }
34857
35255
  async function ensureGitignore2(root) {
34858
- const path = join22(root, ".gitignore");
34859
- const existing = existsSync19(path) ? await readFile10(path, "utf8") : "";
35256
+ const path = join23(root, ".gitignore");
35257
+ const existing = existsSync20(path) ? await readFile10(path, "utf8") : "";
34860
35258
  const required = [".env.supacloud.*", "!.env.supacloud.*.example"];
34861
35259
  const missing = required.filter((entry) => !existing.split(/\r?\n/).includes(entry));
34862
35260
  if (missing.length === 0)
@@ -34870,10 +35268,10 @@ async function ensureGitignore2(root) {
34870
35268
  return true;
34871
35269
  }
34872
35270
  async function initializeProject2(request, options = {}) {
34873
- const root = resolve29(request.root || options.cwd || process.cwd());
35271
+ const root = resolve30(request.root || options.cwd || process.cwd());
34874
35272
  await mkdir9(root, { recursive: true });
34875
- const configPath = join22(root, "supacloud.json");
34876
- if (existsSync19(configPath)) {
35273
+ const configPath = join23(root, "supacloud.json");
35274
+ if (existsSync20(configPath)) {
34877
35275
  throw new Error(`supacloud.json already exists in ${root}; init never overwrites project configuration`);
34878
35276
  }
34879
35277
  const manifest = await readPackageManifest2(root);
@@ -34900,10 +35298,10 @@ async function initializeProject2(request, options = {}) {
34900
35298
  throw error;
34901
35299
  }
34902
35300
  created.push("supacloud.json");
34903
- if (await writeNewFile2(join22(root, ".env.supacloud.test.example"), TEST_PROFILE2)) {
35301
+ if (await writeNewFile2(join23(root, ".env.supacloud.test.example"), TEST_PROFILE2)) {
34904
35302
  created.push(".env.supacloud.test.example");
34905
35303
  }
34906
- if (await writeNewFile2(join22(root, ".env.supacloud.production.example"), PRODUCTION_PROFILE2)) {
35304
+ if (await writeNewFile2(join23(root, ".env.supacloud.production.example"), PRODUCTION_PROFILE2)) {
34907
35305
  created.push(".env.supacloud.production.example");
34908
35306
  }
34909
35307
  if (await ensureGitignore2(root))
@@ -34914,7 +35312,7 @@ async function initializeProject2(request, options = {}) {
34914
35312
  root,
34915
35313
  created,
34916
35314
  detected: {
34917
- package_json: existsSync19(join22(root, "package.json")),
35315
+ package_json: existsSync20(join23(root, "package.json")),
34918
35316
  build_script: hasBuildScript,
34919
35317
  output_directory: outputDirectory
34920
35318
  },
@@ -34948,7 +35346,7 @@ async function environmentProfiles(root) {
34948
35346
  });
34949
35347
  return entries.filter((entry) => entry.isFile()).map((entry) => {
34950
35348
  const name = profileNameFromFile(entry.name);
34951
- return name ? { name, path: join22(root, entry.name), exists: true } : null;
35349
+ return name ? { name, path: join23(root, entry.name), exists: true } : null;
34952
35350
  }).filter((profile) => profile !== null).sort((left, right) => left.name.localeCompare(right.name));
34953
35351
  }
34954
35352
  function statusMissing(context) {
@@ -34987,14 +35385,14 @@ async function inspectProfile(profile) {
34987
35385
  environmentName: profile.name
34988
35386
  });
34989
35387
  const status = statusMissing(context);
34990
- const configText = await readFile10(join22(dirname15(profile.path), "supacloud.json"), "utf8").catch((error) => {
35388
+ const configText = await readFile10(join23(dirname15(profile.path), "supacloud.json"), "utf8").catch((error) => {
34991
35389
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
34992
35390
  return "{}";
34993
35391
  throw error;
34994
35392
  });
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);
35393
+ const config = record9(JSON.parse(configText));
35394
+ const hasFrontend = record9(config?.frontend) !== null || Object.values(record9(config?.targets) ?? {}).some((target) => record9(target)?.type === "frontend");
35395
+ const deploy = deployMissing(context, record9(config?.application), hasFrontend);
34998
35396
  return {
34999
35397
  name: profile.name,
35000
35398
  path: profile.path,
@@ -35031,7 +35429,7 @@ async function inspectProfile(profile) {
35031
35429
  }
35032
35430
  }
35033
35431
  async function inspectEnvironment(request, options) {
35034
- const root = resolve29(request.root || options.cwd || process.cwd());
35432
+ const root = resolve30(request.root || options.cwd || process.cwd());
35035
35433
  const profiles = await environmentProfiles(root);
35036
35434
  if (request.action === "list") {
35037
35435
  const active = options.activeContext?.environment || null;
@@ -35093,9 +35491,9 @@ function registerDeveloperExperienceTools(server, options = {}) {
35093
35491
  }
35094
35492
 
35095
35493
  // src/shared/tools/configuration-tools.ts
35096
- import { existsSync as existsSync20 } from "node:fs";
35494
+ import { existsSync as existsSync21 } from "node:fs";
35097
35495
  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";
35496
+ import { join as join24, resolve as resolve31 } from "node:path";
35099
35497
  var MANAGEMENT_CONFIGURATION_KEYS = ["SUPACLOUD_API_URL", "SUPACLOUD_API_TOKEN", "SUPACLOUD_PROJECT_REF"];
35100
35498
  var APPLICATION_CONFIGURATION_KEYS = ["SUPABASE_URL", "SUPABASE_SERVICE_ROLE_KEY", "SUPACLOUD_PROJECT_REF"];
35101
35499
  var onboardToolSchema2 = {
@@ -35128,7 +35526,7 @@ function textResult6(text, isError = false) {
35128
35526
  function jsonResult4(value, isError = false) {
35129
35527
  return textResult6(JSON.stringify(value, null, 2), isError);
35130
35528
  }
35131
- function record9(value) {
35529
+ function record10(value) {
35132
35530
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
35133
35531
  }
35134
35532
  function unquote2(value) {
@@ -35151,10 +35549,10 @@ function parseEnvironment2(content) {
35151
35549
  return values;
35152
35550
  }
35153
35551
  async function readJsonObject2(path) {
35154
- if (!existsSync20(path))
35552
+ if (!existsSync21(path))
35155
35553
  return {};
35156
35554
  const parsed = JSON.parse(await readFile11(path, "utf8"));
35157
- const value = record9(parsed);
35555
+ const value = record10(parsed);
35158
35556
  if (!value)
35159
35557
  throw new Error(`${path} must contain a JSON object`);
35160
35558
  return value;
@@ -35164,13 +35562,13 @@ async function writeJsonObject2(path, value) {
35164
35562
  `, { encoding: "utf8", mode: 420 });
35165
35563
  }
35166
35564
  function contextFromConfig2(config) {
35167
- const context = record9(config.context);
35565
+ const context = record10(config.context);
35168
35566
  return context ?? {};
35169
35567
  }
35170
35568
  function environmentContext2(config, environment) {
35171
35569
  const context = contextFromConfig2(config);
35172
- const environments = record9(context.environments);
35173
- const selected = environments ? record9(environments[environment]) : null;
35570
+ const environments = record10(context.environments);
35571
+ const selected = environments ? record10(environments[environment]) : null;
35174
35572
  return selected ?? {};
35175
35573
  }
35176
35574
  function derivedValues(values) {
@@ -35255,13 +35653,13 @@ function onboardingPlan(args, root) {
35255
35653
  };
35256
35654
  }
35257
35655
  async function runOnboard(args, options) {
35258
- const root = resolve30(typeof args.root === "string" ? args.root : options.cwd ?? process.cwd());
35656
+ const root = resolve31(typeof args.root === "string" ? args.root : options.cwd ?? process.cwd());
35259
35657
  const plan = onboardingPlan(args, root);
35260
35658
  if (args.write === true) {
35261
35659
  await mkdir10(root, { recursive: true });
35262
- const path = join23(root, "supacloud.json");
35660
+ const path = join24(root, "supacloud.json");
35263
35661
  const config = await readJsonObject2(path);
35264
- if (existsSync20(path) && config.context !== undefined) {
35662
+ if (existsSync21(path) && config.context !== undefined) {
35265
35663
  throw new Error("supacloud.json already has context metadata; use env sync to update one environment");
35266
35664
  }
35267
35665
  config.context = {
@@ -35287,10 +35685,10 @@ async function runOnboard(args, options) {
35287
35685
  `));
35288
35686
  }
35289
35687
  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"));
35688
+ const root = resolve31(typeof args.root === "string" ? args.root : options.cwd ?? process.cwd());
35689
+ const config = await readJsonObject2(join24(root, "supacloud.json"));
35292
35690
  const environment = options.activeContext?.environment || "";
35293
- const profileValues = environment && existsSync20(join23(root, `.env.supacloud.${environment}`)) ? parseEnvironment2(await readFile11(join23(root, `.env.supacloud.${environment}`), "utf8")) : {};
35691
+ const profileValues = environment && existsSync21(join24(root, `.env.supacloud.${environment}`)) ? parseEnvironment2(await readFile11(join24(root, `.env.supacloud.${environment}`), "utf8")) : {};
35294
35692
  const metadata = environment ? environmentContext2(config, environment) : {};
35295
35693
  const values = {
35296
35694
  ...Object.fromEntries(Object.entries(metadata).filter(([, value]) => typeof value === "string")),
@@ -35331,9 +35729,9 @@ function registerConfigurationTools(server, options = {}) {
35331
35729
  }
35332
35730
 
35333
35731
  // src/shared/tools/pipeline-tools.ts
35334
- import { existsSync as existsSync21 } from "node:fs";
35732
+ import { existsSync as existsSync22 } from "node:fs";
35335
35733
  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";
35734
+ import { join as join25, resolve as resolve32 } from "node:path";
35337
35735
  var pipelineToolSchema = {
35338
35736
  action: withDescription(stringEnum2(["connect"]), "Pipeline configuration action"),
35339
35737
  provider: optional(stringEnum2(["github", "gitlab"]), "[connect] Git provider (default: github)"),
@@ -35348,14 +35746,14 @@ function textResult7(text, isError = false) {
35348
35746
  function jsonResult5(value, isError = false) {
35349
35747
  return textResult7(JSON.stringify(value, null, 2), isError);
35350
35748
  }
35351
- function record10(value) {
35749
+ function record11(value) {
35352
35750
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
35353
35751
  }
35354
35752
  async function readJson2(path) {
35355
- if (!existsSync21(path))
35753
+ if (!existsSync22(path))
35356
35754
  return {};
35357
35755
  const parsed = JSON.parse(await readFile12(path, "utf8"));
35358
- return record10(parsed) ?? {};
35756
+ return record11(parsed) ?? {};
35359
35757
  }
35360
35758
  function workflow(provider, preview) {
35361
35759
  if (provider !== "github") {
@@ -35420,15 +35818,15 @@ jobs:
35420
35818
  ${previewSteps}`;
35421
35819
  }
35422
35820
  async function connectPipeline(args, options = {}) {
35423
- const root = resolve31(typeof args.root === "string" ? args.root : options.cwd ?? process.cwd());
35821
+ const root = resolve32(typeof args.root === "string" ? args.root : options.cwd ?? process.cwd());
35424
35822
  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);
35823
+ const config = await readJson2(join25(root, "supacloud.json"));
35824
+ const frontend = record11(config.frontend);
35825
+ const packageJson = await readJson2(join25(root, "package.json"));
35826
+ const scripts = record11(packageJson.scripts);
35429
35827
  const buildCommand = typeof frontend?.buildCommand === "string" ? frontend.buildCommand : typeof scripts?.build === "string" ? scripts.build : "(configure package.json build script)";
35430
35828
  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");
35829
+ const workflowPath = provider === "github" ? join25(root, ".github", "workflows", "supacloud-deploy.yml") : join25(root, ".gitlab-ci.yml");
35432
35830
  const result = {
35433
35831
  schema: "supacloud.pipeline-connection.v1",
35434
35832
  provider,
@@ -35449,10 +35847,10 @@ async function connectPipeline(args, options = {}) {
35449
35847
  "No files were changed. Re-run with --write after reviewing the generated workflow."
35450
35848
  ].join(`
35451
35849
  `));
35452
- if (provider === "gitlab" && existsSync21(workflowPath)) {
35850
+ if (provider === "gitlab" && existsSync22(workflowPath)) {
35453
35851
  throw new Error(`Refusing to overwrite existing GitLab workflow: ${workflowPath}`);
35454
35852
  }
35455
- await mkdir11(resolve31(workflowPath, ".."), { recursive: true });
35853
+ await mkdir11(resolve32(workflowPath, ".."), { recursive: true });
35456
35854
  await writeFile11(workflowPath, workflow(provider, args.preview === true), { encoding: "utf8", mode: 420 });
35457
35855
  return jsonResult5({ ...result, written: true });
35458
35856
  }
@@ -35585,7 +35983,7 @@ async function runProjectDeployment(http, args) {
35585
35983
  // package.json
35586
35984
  var package_default = {
35587
35985
  name: "@supacloud/cli",
35588
- version: "0.123.1",
35986
+ version: "0.124.0",
35589
35987
  description: "Project-scoped CLI for SupaCloud users",
35590
35988
  type: "module",
35591
35989
  main: "./dist/index.js",