@supacloud/cli 0.48.2 → 0.49.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
@@ -176008,6 +176008,7 @@ var ACTION_POLICY = {
176008
176008
  mutations: { read: ["status"] },
176009
176009
  release: {
176010
176010
  read: ["logical_backup_list", "postgrest_status"],
176011
+ local: ["scope_inspect", "scope_rebind", "scope_create"],
176011
176012
  write: ["logical_backup_create", "logical_backup_restore", "postgrest_restart", "release_canary_fixture_stage_replay", "release_canary_fixture_disable_replay"]
176012
176013
  },
176013
176014
  secrets: { read: ["list"], write: ["upsert", "delete"] },
@@ -176027,7 +176028,7 @@ var ACTION_POLICY = {
176027
176028
  write: ["send", "receive", "ack", "release", "fail", "retry", "delete_message", "update_settings"]
176028
176029
  },
176029
176030
  ai: { local: ["show_skill", "install_skill"] },
176030
- app: { local: ["generate", "compile", "check", "graph", "explain", "export-tools"] },
176031
+ app: { local: ["init", "generate", "compile", "check", "graph", "explain", "export-tools"] },
176031
176032
  db: { local: ["lint", "explain"], read: ["module_check"] },
176032
176033
  dev: { read: ["status"], write: ["sync", "watch", "migrate"] }
176033
176034
  };
@@ -183699,8 +183700,8 @@ function registerAiTools(server2) {
183699
183700
 
183700
183701
  // src/shared/tools/app-tools.ts
183701
183702
  import { existsSync as existsSync9 } from "node:fs";
183702
- import { mkdir as mkdir2, readFile, writeFile } from "node:fs/promises";
183703
- import { dirname as dirname5, join as join7, resolve as resolve8 } from "node:path";
183703
+ import { mkdir as mkdir3, readFile, writeFile as writeFile3 } from "node:fs/promises";
183704
+ import { dirname as dirname7, join as join8, resolve as resolve9 } from "node:path";
183704
183705
 
183705
183706
  // node_modules/@supacloud/compiler/dist/index.js
183706
183707
  var ts3 = __toESM(require_typescript(), 1);
@@ -183713,11 +183714,13 @@ import { existsSync as existsSync8, readFileSync as readFileSync6 } from "node:f
183713
183714
  import { dirname as dirname3, join as join6, resolve as resolve7 } from "node:path";
183714
183715
  import { createHash as createHash4 } from "node:crypto";
183715
183716
  var ts4 = __toESM(require_typescript(), 1);
183717
+ var ts5 = __toESM(require_typescript(), 1);
183716
183718
  import { createHash as createHash42 } from "node:crypto";
183717
183719
  import { access, mkdir, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
183718
183720
  import { join as join22 } from "node:path";
183719
183721
  import { dirname as dirname32, relative as relative32, sep as sep32 } from "node:path";
183720
- var ts5 = __toESM(require_typescript(), 1);
183722
+ import { existsSync as existsSync32, readFileSync as readFileSync32 } from "node:fs";
183723
+ import { join as join42 } from "node:path";
183721
183724
  import { existsSync as existsSync22, readFileSync as readFileSync22 } from "node:fs";
183722
183725
  import { dirname as dirname4, join as join32, relative as relative4, resolve as resolve32, sep as sep4 } from "node:path";
183723
183726
  import { existsSync as existsSync52 } from "node:fs";
@@ -186007,7 +186010,7 @@ function validateFeatureSpec(spec, module) {
186007
186010
  }
186008
186011
  var HEADER = "// GENERATED BY @supacloud/compiler — do not edit";
186009
186012
  var INTERFACES = `export interface CompiledRoute {
186010
- method: string;
186013
+ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
186011
186014
  path: string;
186012
186015
  handler: string;
186013
186016
  body?: unknown;
@@ -186078,7 +186081,7 @@ export type CompiledAspect = (
186078
186081
  export interface CompiledController {
186079
186082
  path: string;
186080
186083
  serviceKey: string;
186081
- scope: string;
186084
+ scope: "application" | "request" | "job";
186082
186085
  routes: CompiledRoute[];
186083
186086
  }
186084
186087
 
@@ -186692,7 +186695,7 @@ ${indent(item, 2)}`).join(",")}
186692
186695
  switch (provider.kind) {
186693
186696
  case "class": {
186694
186697
  const useClass = this.imports.add(provider.useClass ?? provider.token, provider.importPath, provider.importModule);
186695
- const args = provider.deps.map((dep) => this.depExpr(dep, kind, this.depOptions(provider, dep))).join(", ");
186698
+ const args = provider.deps.map((dep, index) => this.typedDepExpr(dep, kind, this.depOptions(provider, dep), `ConstructorParameters<typeof ${useClass}>[${index}]`)).join(", ");
186696
186699
  const local = this.localVar(isMulti ? provider.useClass ?? `${provider.token}Item` : provider.token, kind);
186697
186700
  return {
186698
186701
  constLine: `const ${local} = ${this.instantiate(useClass, args, kind, provider.functionalInjects)};`,
@@ -186713,7 +186716,7 @@ ${indent(item, 2)}`).join(",")}
186713
186716
  return { constLine, key, expr: local2 };
186714
186717
  }
186715
186718
  const factory2 = this.imports.add(provider.useFactoryName ?? "", provider.importPath, provider.importModule);
186716
- const args = provider.deps.map((dep) => this.depExpr(dep, kind, this.depOptions(provider, dep))).join(", ");
186719
+ const args = provider.deps.map((dep, index) => this.typedDepExpr(dep, kind, this.depOptions(provider, dep), `Parameters<typeof ${factory2}>[${index}]`)).join(", ");
186717
186720
  const local = this.localVar(isMulti ? provider.useFactoryName ?? `${provider.token}Item` : provider.token, kind);
186718
186721
  return { constLine: `const ${local} = ${factory2}(${args});`, key, expr: local };
186719
186722
  }
@@ -186727,7 +186730,7 @@ ${indent(item, 2)}`).join(",")}
186727
186730
  }
186728
186731
  emitController(controller, kind) {
186729
186732
  const className = this.imports.add(controller.className, controller.importPath);
186730
- const args = controller.deps.map((dep) => this.depExpr(dep, kind, this.depOptions(controller, dep))).join(", ");
186733
+ const args = controller.deps.map((dep, index) => this.typedDepExpr(dep, kind, this.depOptions(controller, dep), `ConstructorParameters<typeof ${className}>[${index}]`)).join(", ");
186731
186734
  const key = camelName(controller.className);
186732
186735
  const local = this.localVar(controller.className, kind);
186733
186736
  return {
@@ -186785,6 +186788,13 @@ ${indent(item, 2)}`).join(",")}
186785
186788
  host: "hostDeps" in node ? node.hostDeps?.includes(token) ?? false : false
186786
186789
  };
186787
186790
  }
186791
+ typedDepExpr(token, kind, options, type) {
186792
+ const expression = this.depExpr(token, kind, options);
186793
+ const localProvider = this.module.providers.find((provider) => this.locals[kind].get(provider.token) === expression);
186794
+ if (expression === "undefined" || localProvider && !(localProvider.kind === "factory" && !localProvider.useFactoryName))
186795
+ return expression;
186796
+ return `${expression} as ${type}`;
186797
+ }
186788
186798
  depExpr(token, kind, options = {}) {
186789
186799
  const isOptional = options.optional ?? false;
186790
186800
  const isSelf = options.self ?? false;
@@ -188364,6 +188374,79 @@ async function compileProject(options) {
188364
188374
  } : undefined;
188365
188375
  return { diagnostics, graph, written, stats };
188366
188376
  }
188377
+ async function checkProject(options) {
188378
+ const graph = await analyzeProject(options.rootDir, options.include, options.cache, options.changedPaths);
188379
+ const diagnostics = [
188380
+ ...graph.diagnostics ?? [],
188381
+ ...validateGraph(graph, {
188382
+ strict: options.strict,
188383
+ moduleBoundaryPreset: options.moduleBoundaryPreset,
188384
+ moduleBoundaries: options.moduleBoundaries,
188385
+ allowRouteCommandBindings: options.allowRouteCommandBindings,
188386
+ commandCapabilities: options.commandCapabilities,
188387
+ disallowControllerDirectDb: options.disallowControllerDirectDb,
188388
+ detectOrphanModules: options.detectOrphanModules
188389
+ })
188390
+ ];
188391
+ if (options.strict) {
188392
+ for (const diagnostic of diagnostics) {
188393
+ if (diagnostic.severity === "warn")
188394
+ diagnostic.severity = "error";
188395
+ }
188396
+ }
188397
+ const typeSafety = resolveTypeSafety(options);
188398
+ const rendered = renderApplication(graph, {
188399
+ rootDir: options.rootDir,
188400
+ outDir: options.outDir,
188401
+ generateClient: options.generateClient,
188402
+ generatePermissions: options.generatePermissions,
188403
+ treeShakeUnusedProviders: options.treeShakeUnusedProviders
188404
+ });
188405
+ if (typeSafety.scanProductionSource) {
188406
+ diagnostics.push(...scanProductionSource({
188407
+ rootDir: options.rootDir,
188408
+ include: options.include,
188409
+ outDir: options.outDir,
188410
+ strict: options.strict,
188411
+ ...typeSafety
188412
+ }));
188413
+ }
188414
+ if (typeSafety.noAnyInGenerated) {
188415
+ diagnostics.push(...scanGeneratedArtifacts({
188416
+ "application.ts": rendered.applicationCode,
188417
+ "client.ts": rendered.clientCode,
188418
+ "permissions.ts": rendered.permissionsCode
188419
+ }, options.strict ?? false));
188420
+ }
188421
+ const expectedFiles = {
188422
+ "application.ts": rendered.applicationCode,
188423
+ "app.manifest.json": rendered.manifestJson
188424
+ };
188425
+ if (rendered.clientCode) {
188426
+ expectedFiles["client.ts"] = rendered.clientCode;
188427
+ }
188428
+ if (rendered.permissionsCode) {
188429
+ expectedFiles["permissions.ts"] = rendered.permissionsCode;
188430
+ }
188431
+ const mismatches = [];
188432
+ for (const [filename, expectedContent] of Object.entries(expectedFiles)) {
188433
+ const diskPath = join42(options.outDir, filename);
188434
+ if (!existsSync32(diskPath)) {
188435
+ mismatches.push(`${filename}: generated artifact is missing from disk`);
188436
+ continue;
188437
+ }
188438
+ const diskContent = readFileSync32(diskPath, "utf8");
188439
+ if (diskContent !== expectedContent) {
188440
+ mismatches.push(`${filename}: disk artifact differs from current compiler output`);
188441
+ }
188442
+ }
188443
+ return {
188444
+ upToDate: mismatches.length === 0,
188445
+ mismatches,
188446
+ diagnostics,
188447
+ graph
188448
+ };
188449
+ }
188367
188450
  function resolveTypeSafety(options) {
188368
188451
  return {
188369
188452
  noAnyInGenerated: options.typeSafety?.noAnyInGenerated ?? options.strict ?? false,
@@ -188544,7 +188627,728 @@ function buildToolDefinitions(manifest) {
188544
188627
  return { openai, mcp };
188545
188628
  }
188546
188629
 
188630
+ // src/shared/tools/app-starter.ts
188631
+ import { lstat, mkdir as mkdir2, readdir, writeFile } from "node:fs/promises";
188632
+ import { basename as basename4, dirname as dirname5, join as join7, resolve as resolve8 } from "node:path";
188633
+
188634
+ // src/shared/tools/app-starter-environment.ts
188635
+ var STARTER_ENVIRONMENT = String.raw`import { existsSync, readFileSync } from "node:fs";
188636
+ import { dirname, join } from "node:path";
188637
+ import { fileURLToPath } from "node:url";
188638
+ import { parseEnv } from "node:util";
188639
+
188640
+ const targets = ["development", "test", "staging", "production"];
188641
+ const remoteKeys = ["SUPACLOUD_API_URL", "SUPACLOUD_API_TOKEN", "SUPACLOUD_PROJECT_REF"];
188642
+ const projectRoot = dirname(dirname(fileURLToPath(import.meta.url)));
188643
+
188644
+ export function loadEnvironment(
188645
+ target: string,
188646
+ root = projectRoot,
188647
+ inherited: Record<string, string | undefined> = process.env,
188648
+ ): Record<string, string> {
188649
+ if (!targets.includes(target)) throw new Error("Explicit environment required: " + targets.join(", "));
188650
+ const platform = target === "production" ? "production" : "test";
188651
+ const checkSelectors = (source: Record<string, string | undefined>) => {
188652
+ if (source.APP_ENV !== undefined && source.APP_ENV !== target) throw new Error("APP_ENV conflicts with selected target");
188653
+ if (source.SUPACLOUD_ENV !== undefined && source.SUPACLOUD_ENV !== platform) throw new Error("SUPACLOUD_ENV conflicts with selected target");
188654
+ };
188655
+ checkSelectors(inherited);
188656
+ // Untagged or partial process credentials must not be completed from another profile.
188657
+ if (remoteKeys.some((key) => inherited[key] !== undefined)) {
188658
+ if (inherited.SUPACLOUD_ENV !== platform || remoteKeys.some((key) => !inherited[key]?.trim())) {
188659
+ throw new Error("Inherited remote context must be complete and tagged with SUPACLOUD_ENV");
188660
+ }
188661
+ }
188662
+ const localPath = join(root, ".env." + target + ".local");
188663
+ if (target === "production" && existsSync(localPath)) throw new Error("Production local env files are not allowed");
188664
+ const paths = [join(root, ".env." + target)];
188665
+ if (target === "development" || target === "staging") paths.push(localPath);
188666
+ const values: Record<string, string> = {};
188667
+ for (const path of paths) {
188668
+ if (!existsSync(path)) continue;
188669
+ const parsed = parseEnv(readFileSync(path, "utf8"));
188670
+ checkSelectors(parsed);
188671
+ if (remoteKeys.some((key) => parsed[key] !== undefined) && remoteKeys.some((key) => !parsed[key]?.trim())) {
188672
+ throw new Error("Each remote file profile must supply API URL, token and project ref together");
188673
+ }
188674
+ Object.assign(values, parsed);
188675
+ }
188676
+ for (const [key, value] of Object.entries(inherited)) {
188677
+ if (value !== undefined) values[key] = value;
188678
+ }
188679
+ if (remoteKeys.some((key) => values[key] !== undefined) &&
188680
+ remoteKeys.some((key) => !values[key]?.trim())) {
188681
+ throw new Error("Remote context requires API URL, token and project ref together");
188682
+ }
188683
+ // Target selection and runtime optimization are distinct; staging uses production runtime mode.
188684
+ values.APP_ENV = target;
188685
+ values.SUPACLOUD_ENV = platform;
188686
+ values.NODE_ENV = target === "development" ? "development" : target === "test" ? "test" : "production";
188687
+ return values;
188688
+ }
188689
+
188690
+ if (import.meta.main) {
188691
+ const [target, ...command] = process.argv.slice(2);
188692
+ if (!target || !command.length) throw new Error("Usage: environment.ts <target> <command> [args...]");
188693
+ const child = Bun.spawn(command, {
188694
+ cwd: projectRoot,
188695
+ env: loadEnvironment(target),
188696
+ stdin: "inherit", stdout: "inherit", stderr: "inherit",
188697
+ });
188698
+ const stop = (signal: "SIGINT" | "SIGTERM") => child.kill(signal);
188699
+ process.once("SIGINT", () => stop("SIGINT"));
188700
+ process.once("SIGTERM", () => stop("SIGTERM"));
188701
+ process.exitCode = await child.exited;
188702
+ }
188703
+ `;
188704
+ var STARTER_ENVIRONMENT_TEST = String.raw`import { afterEach, expect, test } from "bun:test";
188705
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
188706
+ import { tmpdir } from "node:os";
188707
+ import { join } from "node:path";
188708
+ import { loadEnvironment } from "../scripts/environment";
188709
+
188710
+ const roots: string[] = [];
188711
+ const fixture = () => {
188712
+ const root = mkdtempSync(join(tmpdir(), "app-env-"));
188713
+ roots.push(root);
188714
+ return root;
188715
+ };
188716
+ afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
188717
+
188718
+ test("only selected files are loaded, with process > local > target precedence", () => {
188719
+ const root = fixture();
188720
+ writeFileSync(join(root, ".env"), "LEAK=common\n");
188721
+ writeFileSync(join(root, ".env.local"), "LEAK=common-local\n");
188722
+ writeFileSync(join(root, ".env.production"), "LEAK=production\n");
188723
+ writeFileSync(join(root, ".env.development"), "BASE=base\nVALUE=base\n");
188724
+ writeFileSync(join(root, ".env.development.local"), "VALUE=local\nLOCAL=local\nLITERAL='$untouched'\n");
188725
+ expect(loadEnvironment("development", root, { VALUE: "process" })).toEqual({
188726
+ BASE: "base", VALUE: "process", LOCAL: "local", LITERAL: "$untouched",
188727
+ APP_ENV: "development", SUPACLOUD_ENV: "test", NODE_ENV: "development",
188728
+ });
188729
+ });
188730
+
188731
+ test("test ignores local overrides and staging uses production runtime optimization", () => {
188732
+ const root = fixture();
188733
+ writeFileSync(join(root, ".env.test.local"), "LEAK=local\n");
188734
+ expect(loadEnvironment("test", root, {}).LEAK).toBeUndefined();
188735
+ expect(loadEnvironment("staging", root, {})).toEqual({
188736
+ APP_ENV: "staging", SUPACLOUD_ENV: "test", NODE_ENV: "production",
188737
+ });
188738
+ });
188739
+
188740
+ test("production local files, unknown targets and selector conflicts are rejected", () => {
188741
+ const root = fixture();
188742
+ expect(() => loadEnvironment("", root, {})).toThrow("Explicit environment");
188743
+ expect(() => loadEnvironment("development", root, { APP_ENV: "production" })).toThrow("conflicts");
188744
+ expect(() => loadEnvironment("test", root, { SUPACLOUD_ENV: "production" })).toThrow("conflicts");
188745
+ writeFileSync(join(root, ".env.staging"), "APP_ENV=production\n");
188746
+ expect(() => loadEnvironment("staging", root, {})).toThrow("conflicts");
188747
+ writeFileSync(join(root, ".env.production.local"), "SECRET=synthetic\n");
188748
+ expect(() => loadEnvironment("production", root, {})).toThrow("not allowed");
188749
+ });
188750
+
188751
+ test("partial and untagged inherited remote profiles cannot mix with selected files", () => {
188752
+ const root = fixture();
188753
+ writeFileSync(join(root, ".env.staging"), "SUPACLOUD_API_URL=https://example.invalid\nSUPACLOUD_API_TOKEN=fixture\nSUPACLOUD_PROJECT_REF=fixture\n");
188754
+ expect(() => loadEnvironment("staging", root, { SUPACLOUD_API_TOKEN: "other-fixture" })).toThrow("complete and tagged");
188755
+ expect(() => loadEnvironment("staging", root, { SUPACLOUD_ENV: "test", SUPACLOUD_API_TOKEN: "" })).toThrow("complete and tagged");
188756
+ expect(loadEnvironment("staging", root, {
188757
+ SUPACLOUD_ENV: "test", SUPACLOUD_API_URL: "https://ci.invalid",
188758
+ SUPACLOUD_API_TOKEN: "ci-fixture", SUPACLOUD_PROJECT_REF: "ci-fixture",
188759
+ }).SUPACLOUD_API_URL).toBe("https://ci.invalid");
188760
+ writeFileSync(join(root, ".env.staging.local"), "SUPACLOUD_API_URL=https://other.invalid\n");
188761
+ expect(() => loadEnvironment("staging", root, {})).toThrow("Each remote file profile");
188762
+ });
188763
+ `;
188764
+ // ../compiler/package.json
188765
+ var package_default = {
188766
+ name: "@supacloud/compiler",
188767
+ version: "0.10.0",
188768
+ description: "Static compiler for @supacloud/app metadata: builds the application graph from AST, validates it, and generates reflection-free factory code",
188769
+ type: "module",
188770
+ main: "./dist/index.js",
188771
+ module: "./dist/index.js",
188772
+ types: "./dist/index.d.ts",
188773
+ bin: {
188774
+ "supacloud-compiler": "./dist/cli.js"
188775
+ },
188776
+ exports: {
188777
+ ".": {
188778
+ types: "./dist/index.d.ts",
188779
+ import: "./dist/index.js",
188780
+ default: "./dist/index.js"
188781
+ }
188782
+ },
188783
+ files: [
188784
+ "dist",
188785
+ "README.md"
188786
+ ],
188787
+ scripts: {
188788
+ build: "bun run clean && bun run build:js && bun run build:types",
188789
+ "build:js": "bun build src/index.ts src/cli.ts --outdir dist --target node --external @typescript/typescript6",
188790
+ "build:types": "tsc -p tsconfig.json --emitDeclarationOnly",
188791
+ clean: "rm -rf dist",
188792
+ prepublishOnly: "bun run build",
188793
+ test: "bun test",
188794
+ benchmark: "bun run src/benchmark.ts",
188795
+ typecheck: "tsc -p tsconfig.json --noEmit",
188796
+ "typecheck:test": "tsc -p tsconfig.test.json --noEmit"
188797
+ },
188798
+ keywords: [
188799
+ "supacloud",
188800
+ "compiler",
188801
+ "di",
188802
+ "codegen",
188803
+ "elysia"
188804
+ ],
188805
+ license: "MIT",
188806
+ repository: {
188807
+ type: "git",
188808
+ url: "https://github.com/vibeunion/supacloud.git",
188809
+ directory: "packages/compiler"
188810
+ },
188811
+ dependencies: {
188812
+ "@typescript/typescript6": "^6.0.2"
188813
+ },
188814
+ devDependencies: {
188815
+ "@types/bun": "^1.4.0",
188816
+ typescript: "^7.0.2"
188817
+ }
188818
+ };
188819
+ // ../app/package.json
188820
+ var package_default2 = {
188821
+ name: "@supacloud/app",
188822
+ version: "0.9.0",
188823
+ description: "Angular-style application metadata for SupaCloud: modules, DI tokens, providers, scopes, controllers and commands",
188824
+ type: "module",
188825
+ main: "./dist/index.js",
188826
+ module: "./dist/index.js",
188827
+ types: "./dist/index.d.ts",
188828
+ exports: {
188829
+ ".": {
188830
+ types: "./dist/index.d.ts",
188831
+ import: "./dist/index.js",
188832
+ default: "./dist/index.js"
188833
+ }
188834
+ },
188835
+ files: [
188836
+ "dist",
188837
+ "README.md"
188838
+ ],
188839
+ scripts: {
188840
+ build: "bun run clean && bun run build:js && bun run build:types",
188841
+ "build:js": "bun build src/index.ts --outdir dist --target node",
188842
+ "build:types": "tsc -p tsconfig.json --emitDeclarationOnly",
188843
+ clean: "rm -rf dist",
188844
+ prepublishOnly: "bun run build",
188845
+ test: "bun test",
188846
+ typecheck: "tsc -p tsconfig.json --noEmit",
188847
+ "typecheck:test": "tsc -p tsconfig.test.json --noEmit"
188848
+ },
188849
+ keywords: [
188850
+ "supacloud",
188851
+ "di",
188852
+ "dependency-injection",
188853
+ "module",
188854
+ "elysia"
188855
+ ],
188856
+ license: "MIT",
188857
+ repository: {
188858
+ type: "git",
188859
+ url: "https://github.com/vibeunion/supacloud.git",
188860
+ directory: "packages/app"
188861
+ },
188862
+ dependencies: {
188863
+ "@angular/core": "^22.1.5"
188864
+ },
188865
+ devDependencies: {
188866
+ "@types/bun": "^1.4.0",
188867
+ typescript: "^7.0.2"
188868
+ }
188869
+ };
188870
+ // ../elysia/package.json
188871
+ var package_default3 = {
188872
+ name: "@supacloud/elysia",
188873
+ version: "0.8.0",
188874
+ description: "Elysia runtime adapter for SupaCloud compiled modules: application/request scopes, route registration and validation",
188875
+ type: "module",
188876
+ main: "./dist/index.js",
188877
+ module: "./dist/index.js",
188878
+ types: "./dist/index.d.ts",
188879
+ exports: {
188880
+ ".": {
188881
+ types: "./dist/index.d.ts",
188882
+ import: "./dist/index.js",
188883
+ default: "./dist/index.js"
188884
+ }
188885
+ },
188886
+ files: [
188887
+ "dist",
188888
+ "README.md"
188889
+ ],
188890
+ scripts: {
188891
+ build: "bun run clean && bun run build:js && bun run build:types",
188892
+ "build:js": "bun build src/index.ts --outdir dist --target node --external elysia",
188893
+ "build:types": "tsc -p tsconfig.json --emitDeclarationOnly",
188894
+ clean: "rm -rf dist",
188895
+ prepublishOnly: "bun run build",
188896
+ test: "bun test",
188897
+ typecheck: "tsc -p tsconfig.json --noEmit",
188898
+ "typecheck:test": "tsc -p tsconfig.test.json --noEmit"
188899
+ },
188900
+ keywords: [
188901
+ "supacloud",
188902
+ "elysia",
188903
+ "adapter",
188904
+ "dependency-injection",
188905
+ "module"
188906
+ ],
188907
+ license: "MIT",
188908
+ repository: {
188909
+ type: "git",
188910
+ url: "https://github.com/vibeunion/supacloud.git",
188911
+ directory: "packages/elysia"
188912
+ },
188913
+ peerDependencies: {
188914
+ elysia: "^1.4.30"
188915
+ },
188916
+ devDependencies: {
188917
+ "@types/bun": "^1.4.0",
188918
+ elysia: "^1.4.30",
188919
+ typescript: "^7.0.2"
188920
+ }
188921
+ };
188922
+
188923
+ // src/shared/tools/app-starter.ts
188924
+ var json = (value) => `${JSON.stringify(value, null, 2)}
188925
+ `;
188926
+ function appStarterFiles(name) {
188927
+ return {
188928
+ "package.json": json({
188929
+ name,
188930
+ version: "0.0.0",
188931
+ private: true,
188932
+ type: "module",
188933
+ engines: { bun: ">=1.4.0" },
188934
+ scripts: {
188935
+ compile: "bun --no-env-file node_modules/@supacloud/compiler/dist/cli.js compile",
188936
+ "check:generated": "bun --no-env-file node_modules/@supacloud/compiler/dist/cli.js check",
188937
+ typecheck: "tsc --noEmit",
188938
+ check: "bun run compile && bun run check:generated && bun run typecheck && bun run test",
188939
+ test: "bun run compile && bun --no-env-file scripts/environment.ts test bun test",
188940
+ dev: "bun --no-env-file scripts/environment.ts development bun scripts/dev.ts",
188941
+ build: "bun run compile && bun run typecheck && bun build src/application.ts --target bun --minify --outdir dist",
188942
+ "env:development": "bun --no-env-file scripts/environment.ts development",
188943
+ "env:test": "bun --no-env-file scripts/environment.ts test",
188944
+ "env:staging": "bun --no-env-file scripts/environment.ts staging",
188945
+ "env:production": "bun --no-env-file scripts/environment.ts production"
188946
+ },
188947
+ dependencies: {
188948
+ "@supacloud/app": `^${package_default2.version}`,
188949
+ "@supacloud/elysia": `^${package_default3.version}`,
188950
+ elysia: "^1.4.30"
188951
+ },
188952
+ devDependencies: {
188953
+ "@supacloud/compiler": `^${package_default.version}`,
188954
+ "@types/bun": "^1.4.0",
188955
+ typescript: "^7.0.2"
188956
+ }
188957
+ }),
188958
+ "tsconfig.json": json({
188959
+ compilerOptions: {
188960
+ target: "ES2022",
188961
+ module: "ESNext",
188962
+ moduleResolution: "bundler",
188963
+ strict: true,
188964
+ experimentalDecorators: true,
188965
+ skipLibCheck: true,
188966
+ noEmit: true,
188967
+ types: ["bun"]
188968
+ },
188969
+ include: ["src/**/*.ts", "scripts/**/*.ts", "tests/**/*.ts", "generated/**/*.ts", "supacloud.config.ts"]
188970
+ }),
188971
+ "bunfig.toml": `env = false
188972
+ `,
188973
+ ".gitignore": [
188974
+ "node_modules/",
188975
+ "dist/",
188976
+ ".env",
188977
+ ".env.*",
188978
+ "!.env.*.example",
188979
+ "!.env.test",
188980
+ ""
188981
+ ].join(`
188982
+ `),
188983
+ ".env.development.example": `APP_ENV=development
188984
+ PORT=3000
188985
+ `,
188986
+ ".env.test": `APP_ENV=test
188987
+ `,
188988
+ ".env.staging.example": `APP_ENV=staging
188989
+ # Inject credentials using the deployment platform.
188990
+ `,
188991
+ ".env.production.example": `APP_ENV=production
188992
+ # Inject credentials using the deployment platform.
188993
+ `,
188994
+ "supacloud.config.ts": `import { defineSupacloudConfig } from "@supacloud/compiler";
188995
+
188996
+ export default defineSupacloudConfig({
188997
+ root: "src",
188998
+ outDir: "generated",
188999
+ strict: true,
189000
+ commandCapabilities: { permission: true, transaction: true, idempotency: true, audit: true },
189001
+ });
189002
+ `,
189003
+ "scripts/environment.ts": STARTER_ENVIRONMENT,
189004
+ "tests/environment.test.ts": STARTER_ENVIRONMENT_TEST,
189005
+ "scripts/dev.ts": `import { watchProject, compileOptionsFromConfig, loadSupacloudConfig } from "@supacloud/compiler";
189006
+
189007
+ if (process.env.APP_ENV !== "development") throw new Error("The demo server is development-only");
189008
+ let server: ReturnType<typeof Bun.spawn> | undefined;
189009
+ let restarts = Promise.resolve();
189010
+ let closing = false;
189011
+ const watcher = watchProject({
189012
+ ...compileOptionsFromConfig(await loadSupacloudConfig()),
189013
+ writeOnError: false,
189014
+ onEvent: (event) => {
189015
+ if (event.type === "compile-error") console.error(event.diagnostics);
189016
+ if (event.type !== "compiled") return;
189017
+ restarts = restarts.then(async () => {
189018
+ if (server) { server.kill(); await server.exited; }
189019
+ if (closing) return;
189020
+ server = Bun.spawn([process.execPath, "--no-env-file", "scripts/serve.ts"], {
189021
+ stdin: "inherit", stdout: "inherit", stderr: "inherit", env: process.env,
189022
+ });
189023
+ }).catch((error) => { console.error(error); process.exitCode = 1; });
189024
+ },
189025
+ });
189026
+ const close = async () => {
189027
+ closing = true;
189028
+ await watcher.close();
189029
+ await restarts;
189030
+ if (server) { server.kill(); await server.exited; }
189031
+ process.exit(0);
189032
+ };
189033
+ process.once("SIGINT", close);
189034
+ process.once("SIGTERM", close);
189035
+ await watcher.ready;
189036
+ `,
189037
+ "scripts/serve.ts": `import { createDemo } from "./sandbox";
189038
+
189039
+ if (process.env.APP_ENV !== "development") throw new Error("The demo server is development-only");
189040
+ const port = Number(process.env.PORT ?? "3000");
189041
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error("Invalid PORT");
189042
+ const sandbox = createDemo();
189043
+ const server = Bun.serve({
189044
+ hostname: "127.0.0.1", port,
189045
+ fetch: (request) => sandbox.app.handle(request),
189046
+ });
189047
+ console.log("Local demo: " + server.url);
189048
+ `,
189049
+ "scripts/sandbox.ts": `import { createMemorySandbox } from "@supacloud/elysia";
189050
+ import { createCompiledModules } from "../generated/application";
189051
+
189052
+ export function createDemo() {
189053
+ if (process.env.APP_ENV !== "development" && process.env.APP_ENV !== "test") {
189054
+ throw new Error("Memory adapters are restricted to development and test");
189055
+ }
189056
+ const sandbox = createMemorySandbox({
189057
+ modules: createCompiledModules(),
189058
+ identity: { authenticated: true, subject: "local-demo" },
189059
+ memoryGovernance: true,
189060
+ });
189061
+ sandbox.policy.grant("local-demo", "review.approve");
189062
+ sandbox.db.set("reviews", "demo", { state: "draft", version: 1 });
189063
+ return sandbox;
189064
+ }
189065
+ `,
189066
+ "src/application.ts": `import { createApplication, type ApplicationOptions, type CommandGovernance } from "@supacloud/elysia";
189067
+ import { createCompiledModules } from "../generated/application";
189068
+
189069
+ export interface AppAdapters {
189070
+ deps: NonNullable<ApplicationOptions["deps"]>;
189071
+ requestContext: NonNullable<ApplicationOptions["requestContext"]>;
189072
+ commandGovernance: CommandGovernance;
189073
+ }
189074
+
189075
+ // Supply trusted identity, persistent storage and durable governance in the host.
189076
+ export function createApp(adapters: AppAdapters) {
189077
+ return createApplication({
189078
+ ...adapters,
189079
+ name: ${JSON.stringify(name)},
189080
+ modules: createCompiledModules(),
189081
+ });
189082
+ }
189083
+ `,
189084
+ "src/review/review.ts": `import {
189085
+ Body, Command, Controller, DB_CLIENT, Get, Inject, Param, Post,
189086
+ defineFeatureSlice, defineFeatureSpec, type Aspect,
189087
+ } from "@supacloud/app";
189088
+ import { ApplicationError, assertFeatureTransition } from "@supacloud/elysia";
189089
+ import { t } from "elysia";
189090
+
189091
+ export const reviewSpec = defineFeatureSpec({
189092
+ name: "review",
189093
+ states: ["draft", "approved"],
189094
+ transitions: {
189095
+ approve: {
189096
+ from: "draft", to: "approved", command: "ApproveReview",
189097
+ permission: "review.approve", transaction: "required",
189098
+ idempotency: "required", audit: "review.approved",
189099
+ route: "POST /reviews/:id/approve",
189100
+ },
189101
+ },
189102
+ });
189103
+
189104
+ interface Review { state: string; version: number }
189105
+ // Production implementations must bind both operations to the current transaction.
189106
+ export interface ReviewStore {
189107
+ get(table: string, key: string): unknown;
189108
+ set(table: string, key: string, value: Review): void;
189109
+ }
189110
+
189111
+ export const Params = t.Object({ id: t.String({ minLength: 1 }) });
189112
+ export const ApproveBody = t.Object({ expectedVersion: t.Integer({ minimum: 1 }) });
189113
+ export const ReviewResult = t.Object({
189114
+ state: t.Union([t.Literal("draft"), t.Literal("approved")]),
189115
+ version: t.Integer({ minimum: 1 }),
189116
+ });
189117
+ export const HealthResult = t.Object({ ok: t.Boolean() });
189118
+
189119
+ // Explicit, statically compiled AOP. Do not log identity, request bodies or secrets.
189120
+ export const requireRequest: Aspect = (context, next) => {
189121
+ if (!context.request) throw new ApplicationError("Request context required", { code: "REQUEST_REQUIRED" });
189122
+ return next();
189123
+ };
189124
+
189125
+ function readReview(value: unknown): Review {
189126
+ if (typeof value !== "object" || value === null ||
189127
+ !("state" in value) || typeof value.state !== "string" ||
189128
+ !("version" in value) || typeof value.version !== "number") {
189129
+ throw new ApplicationError("Review not found", { status: 404, code: "REVIEW_NOT_FOUND" });
189130
+ }
189131
+ return { state: value.state, version: value.version };
189132
+ }
189133
+
189134
+ @Command({
189135
+ name: "review.approve", permission: "review.approve", transaction: "required",
189136
+ idempotency: "required", audit: "review.approved", aspects: [requireRequest],
189137
+ })
189138
+ export class ApproveReview {
189139
+ constructor(@Inject(DB_CLIENT) private readonly store: ReviewStore) {}
189140
+
189141
+ execute(id: string, expectedVersion: number): Review {
189142
+ const current = readReview(this.store.get("reviews", id));
189143
+ if (current.version !== expectedVersion) {
189144
+ throw new ApplicationError("Review state or version changed", { status: 409, code: "REVIEW_CONFLICT" });
189145
+ }
189146
+ const next = {
189147
+ state: assertFeatureTransition(reviewSpec, current.state, "approve"),
189148
+ version: current.version + 1,
189149
+ };
189150
+ this.store.set("reviews", id, next);
189151
+ return next;
189152
+ }
189153
+ }
189154
+
189155
+ @Controller("/reviews")
189156
+ export class ReviewController {
189157
+ constructor(@Inject(ApproveReview) private readonly approveReview: ApproveReview) {}
189158
+
189159
+ @Get("/health", { response: HealthResult })
189160
+ health(): { ok: boolean } { return { ok: true }; }
189161
+
189162
+ @Post("/:id/approve", { command: ApproveReview, params: Params, body: ApproveBody, response: ReviewResult })
189163
+ approve(@Param("id") id: string, @Body() body: { expectedVersion: number }): Review {
189164
+ return this.approveReview.execute(id, body.expectedVersion);
189165
+ }
189166
+ }
189167
+
189168
+ export const ReviewFeature = defineFeatureSlice({
189169
+ name: "review", tags: ["type:feature"], spec: reviewSpec,
189170
+ providers: [ApproveReview], controllers: [ReviewController],
189171
+ });
189172
+ `,
189173
+ "tests/review.test.ts": `import { expect, test } from "bun:test";
189174
+ import { createApp } from "../src/application";
189175
+ import { createDemo } from "../scripts/sandbox";
189176
+
189177
+ function approve(sandbox: ReturnType<typeof createDemo>, key: string, expectedVersion = 1) {
189178
+ return sandbox.request("/reviews/demo/approve", {
189179
+ method: "POST", headers: { "content-type": "application/json", "idempotency-key": key },
189180
+ body: JSON.stringify({ expectedVersion }),
189181
+ });
189182
+ }
189183
+
189184
+ test("health and successful transition with an idempotent replay", async () => {
189185
+ const sandbox = createDemo();
189186
+ expect((await sandbox.request("/reviews/health")).status).toBe(200);
189187
+ expect(await (await approve(sandbox, "once")).json()).toEqual({ state: "approved", version: 2 });
189188
+ expect(await (await approve(sandbox, "once")).json()).toEqual({ state: "approved", version: 2 });
189189
+ expect(sandbox.db.get("reviews", "demo")).toEqual({ state: "approved", version: 2 });
189190
+ expect(sandbox.audit).toEqual([{ command: "review.approve", outcome: "succeeded" }]);
189191
+ });
189192
+
189193
+ test("permission denial, stale versions, invalid transitions and conflicting replays fail closed", async () => {
189194
+ const sandbox = createDemo();
189195
+ sandbox.policy.revoke("local-demo", "review.approve");
189196
+ expect((await approve(sandbox, "denied")).status).toBe(403);
189197
+ expect(sandbox.db.get("reviews", "demo")).toEqual({ state: "draft", version: 1 });
189198
+ sandbox.policy.grant("local-demo", "review.approve");
189199
+ expect((await approve(sandbox, "stale", 2)).status).toBe(409);
189200
+ expect(sandbox.db.get("reviews", "demo")).toEqual({ state: "draft", version: 1 });
189201
+ expect((await approve(sandbox, "success")).status).toBe(200);
189202
+ expect((await approve(sandbox, "invalid-transition", 2)).status).toBe(409);
189203
+ expect((await approve(sandbox, "success", 2)).status).toBe(409);
189204
+ });
189205
+
189206
+ test("invalid input and a missing idempotency key never reach the handler", async () => {
189207
+ const sandbox = createDemo();
189208
+ expect((await approve(sandbox, "invalid", 0)).status).toBe(422);
189209
+ expect((await approve(sandbox, "")).status).toBe(400);
189210
+ expect(sandbox.db.get("reviews", "demo")).toEqual({ state: "draft", version: 1 });
189211
+ });
189212
+
189213
+ test("transaction adapter rolls back mutations when work fails", async () => {
189214
+ const sandbox = createDemo();
189215
+ await expect(sandbox.db.transaction(() => {
189216
+ sandbox.db.set("reviews", "demo", { state: "approved", version: 2 });
189217
+ throw new Error("rollback");
189218
+ })).rejects.toThrow("rollback");
189219
+ expect(sandbox.db.get("reviews", "demo")).toEqual({ state: "draft", version: 1 });
189220
+ });
189221
+
189222
+ test("the production composition root rejects missing governance adapters", async () => {
189223
+ const sandbox = createDemo();
189224
+ const app = createApp({
189225
+ deps: { dbClient: sandbox.db },
189226
+ requestContext: () => ({ identity: { authenticated: true, subject: "test" } }),
189227
+ commandGovernance: { authorize: () => {} },
189228
+ });
189229
+ const response = await app.handle(new Request("http://localhost/reviews/demo/approve", {
189230
+ method: "POST", headers: { "content-type": "application/json", "idempotency-key": "production" },
189231
+ body: JSON.stringify({ expectedVersion: 1 }),
189232
+ }));
189233
+ expect(response.status).toBe(501);
189234
+ expect(sandbox.db.get("reviews", "demo")).toEqual({ state: "draft", version: 1 });
189235
+ });
189236
+ `,
189237
+ "README.md": `# ${name}
189238
+
189239
+ ## Local Development
189240
+
189241
+ \`\`\`sh
189242
+ bun install
189243
+ bun run check
189244
+ bun run dev
189245
+ \`\`\`
189246
+
189247
+ Bun 1.4+ is required. No SupaCloud account, token, PostgreSQL or S3 is needed
189248
+ for this local demo. The server binds only to 127.0.0.1:3000. Set PORT in
189249
+ .env.development.local to change it. Source changes trigger semantic compilation
189250
+ and restart the server only after a successful compile. Demo data resets on restart.
189251
+
189252
+ \`\`\`sh
189253
+ curl http://127.0.0.1:3000/reviews/health
189254
+ curl -X POST http://127.0.0.1:3000/reviews/demo/approve \\
189255
+ -H 'Content-Type: application/json' -H 'Idempotency-Key: first-approval' \\
189256
+ -d '{"expectedVersion":1}'
189257
+ \`\`\`
189258
+
189259
+ The included feature demonstrates a declared draft-to-approved transition,
189260
+ compiler-checked command/route/governance bindings, an explicit AOP function,
189261
+ HTTP schemas, permission denial, transaction rollback, idempotency and audit.
189262
+ It is not a complete Maker-Checker workflow or a production authorization policy.
189263
+
189264
+ ## Environments
189265
+
189266
+ Use .env.development.local for private developer values, .env.test for public
189267
+ test fixtures, and platform-injected variables for staging/production.
189268
+ .env.<target> is loaded first, then .env.<target>.local (development/staging only),
189269
+ then process variables. Common .env, .env.local, dev.env, prod.env and parent
189270
+ directories are never read. Test ignores .env.test.local; production rejects
189271
+ .env.production.local. Values use Node parseEnv semantics, without dollar expansion.
189272
+ Templates contain no credentials. Keep generated/ committed for drift checks.
189273
+
189274
+ \`\`\`sh
189275
+ bun run env:staging bun run build
189276
+ bun run env:production bun run build
189277
+ \`\`\`
189278
+
189279
+ APP_ENV selects development/test/staging/production independently of optimization.
189280
+ SUPACLOUD_ENV maps non-production targets to test and production to production.
189281
+ Conflicting inherited environment selectors fail. Remote credentials must be
189282
+ explicitly environment-tagged and complete; no target is inferred from a token.
189283
+ The env wrappers do not deploy or verify credential ownership. Remote deployment
189284
+ must also pin and validate the expected project and API origin.
189285
+
189286
+ ## Production Boundary
189287
+
189288
+ \`bun run build\` creates dist/application.js, an application factory, not a
189289
+ production server. The compiler is a devDependency and is absent from that
189290
+ runtime entry. The memory demo is kept in scripts/ and refuses staging/production.
189291
+
189292
+ Import createApp from dist/application.js in your trusted host and supply:
189293
+
189294
+ - deps.dbClient implementing ReviewStore, with reads/writes bound to a real transaction;
189295
+ - requestContext from verified identity, never a body-supplied actor;
189296
+ - commandGovernance authorization, durable idempotency, transaction and audit adapters.
189297
+
189298
+ The demo store uses synchronous get/set. Replace it and ApproveReview with your
189299
+ async database repository or a transactional RPC before production use. The
189300
+ authoritative database must lock or compare row versions, enforce authorization,
189301
+ and commit transition, idempotency receipt and audit atomically. For distributed
189302
+ side effects use a transactional outbox. Client state machines are projections,
189303
+ not a security boundary. Missing declared runtime adapters return an error.
189304
+
189305
+ ## CI
189306
+
189307
+ After the first compilation, commit generated/. In CI run
189308
+ \`bun run check:generated\` before any command that regenerates files, then
189309
+ \`bun run typecheck\` and \`bun run test\`. \`bun run check\` bootstraps a newly
189310
+ initialized project. The compiler's strict mode checks metadata, type safety
189311
+ and governance; TypeScript checks both application and generated source.
189312
+ `
189313
+ };
189314
+ }
189315
+ async function initializeAppProject(options) {
189316
+ const root = resolve8(options.root ?? process.cwd());
189317
+ const name = options.name ?? basename4(root);
189318
+ if (!/^[a-z][a-z0-9-]*$/.test(name) || name.length > 100) {
189319
+ throw new Error("Project name must be lowercase kebab-case (1-100 characters)");
189320
+ }
189321
+ await mkdir2(root, { recursive: true });
189322
+ const stat = await lstat(root);
189323
+ if (stat.isSymbolicLink() || !stat.isDirectory())
189324
+ throw new Error("Project root must be a real directory");
189325
+ if ((await readdir(root)).some((entry) => entry !== ".git")) {
189326
+ throw new Error("app init requires an empty directory (an existing .git directory is allowed)");
189327
+ }
189328
+ const files = appStarterFiles(name);
189329
+ for (const [relativePath, content] of Object.entries(files)) {
189330
+ const path = join7(root, relativePath);
189331
+ await mkdir2(dirname5(path), { recursive: true });
189332
+ await writeFile(path, content, { encoding: "utf8", flag: "wx" });
189333
+ }
189334
+ return { root, name, files: Object.keys(files) };
189335
+ }
189336
+
188547
189337
  // src/shared/tools/app-tools.ts
189338
+ async function initProject(args) {
189339
+ if (args.force)
189340
+ throw new Error("app init never overwrites files; choose an empty directory");
189341
+ const { root, name, files } = await initializeAppProject(args);
189342
+ return textResult([
189343
+ `Initialized ${name} in ${root} (${files.length} files).`,
189344
+ `cd '${root.replaceAll("'", "'\\''")}'`,
189345
+ "bun install",
189346
+ "bun run check",
189347
+ "bun run dev",
189348
+ "Local demo only. Production requires persistent governance and identity adapters; see README.md."
189349
+ ].join(`
189350
+ `));
189351
+ }
188548
189352
  function textResult(text, isError = false) {
188549
189353
  return { isError, content: [{ type: "text", text }] };
188550
189354
  }
@@ -188570,11 +189374,11 @@ async function writeScaffold(path, content, force) {
188570
189374
  if (!force) {
188571
189375
  throw new Error(`File already exists: ${path}(使用 --force 覆盖)`);
188572
189376
  }
188573
- await writeFile(path, content, "utf8");
189377
+ await writeFile3(path, content, "utf8");
188574
189378
  return "overwritten";
188575
189379
  }
188576
- await mkdir2(dirname5(path), { recursive: true });
188577
- await writeFile(path, content, "utf8");
189380
+ await mkdir3(dirname7(path), { recursive: true });
189381
+ await writeFile3(path, content, "utf8");
188578
189382
  return "created";
188579
189383
  }
188580
189384
  function moduleScaffold(name) {
@@ -188618,11 +189422,11 @@ async function generateScaffold(args) {
188618
189422
  const kind = args.kind;
188619
189423
  if (!kind)
188620
189424
  throw new Error("app generate requires --kind (module|command|query|controller)");
188621
- const root = resolve8(args.root || process.cwd());
189425
+ const root = resolve9(args.root || process.cwd());
188622
189426
  const dir = args.dir || "src/features";
188623
189427
  if (kind === "module") {
188624
189428
  const name2 = requireIdentifier(args.name, "name");
188625
- const path2 = join7(root, dir, name2, `${name2}.module.ts`);
189429
+ const path2 = join8(root, dir, name2, `${name2}.module.ts`);
188626
189430
  const status2 = await writeScaffold(path2, moduleScaffold(name2), args.force === true);
188627
189431
  return textResult(`✅ ${status2}: ${path2}`);
188628
189432
  }
@@ -188630,7 +189434,7 @@ async function generateScaffold(args) {
188630
189434
  const name = kind === "controller" ? moduleName : requireIdentifier(args.name, "name");
188631
189435
  const fileName = kind === "controller" ? `${moduleName}.controller.ts` : `${name}.${kind}.ts`;
188632
189436
  const subdir = kind === "command" ? "commands" : kind === "query" ? "queries" : "";
188633
- const path = join7(root, dir, moduleName, subdir, fileName);
189437
+ const path = join8(root, dir, moduleName, subdir, fileName);
188634
189438
  if (kind === "controller" && existsSync9(path)) {
188635
189439
  throw new Error(`Controller already exists: ${path}(请手工合并路由到现有 controller)`);
188636
189440
  }
@@ -188652,18 +189456,23 @@ function parseInclude(include) {
188652
189456
  const patterns = include?.split(",").map((entry) => entry.trim()).filter(Boolean);
188653
189457
  return patterns && patterns.length > 0 ? patterns : undefined;
188654
189458
  }
189459
+ function sourceRoot(args, root, configured) {
189460
+ const hasConfig = ["ts", "mts", "js", "mjs"].some((extension) => existsSync9(join8(root, `supacloud.config.${extension}`)));
189461
+ return args.root && !hasConfig ? "." : configured;
189462
+ }
188655
189463
  async function runCompile(args) {
188656
- const root = resolve8(args.root || process.cwd());
189464
+ const root = resolve9(args.root || process.cwd());
188657
189465
  const loadedConfig = await loadSupacloudConfig(root);
188658
189466
  const defaults = resolveSupacloudConfig(loadedConfig, root);
188659
189467
  const result = await compileProject({
188660
189468
  ...compileOptionsFromConfig({
188661
189469
  ...loadedConfig,
188662
- root: args.root ? "." : loadedConfig.root,
188663
- outDir: args.out_dir ? resolve8(root, args.out_dir) : defaults.outDir,
189470
+ root: sourceRoot(args, root, loadedConfig.root),
189471
+ outDir: args.out_dir ? resolve9(root, args.out_dir) : defaults.outDir,
188664
189472
  include: parseInclude(args.include) ?? loadedConfig.include,
188665
189473
  strict: args.strict ?? loadedConfig.strict ?? false
188666
- }, root)
189474
+ }, root),
189475
+ writeOnError: false
188667
189476
  });
188668
189477
  const hasError = result.diagnostics.some((diagnostic) => diagnostic.severity === "error");
188669
189478
  const text = [
@@ -188676,38 +189485,29 @@ async function runCompile(args) {
188676
189485
  return textResult(text, hasError);
188677
189486
  }
188678
189487
  async function runCheck(args) {
188679
- const root = resolve8(args.root || process.cwd());
189488
+ const root = resolve9(args.root || process.cwd());
188680
189489
  const loadedConfig = await loadSupacloudConfig(root);
188681
189490
  const defaults = resolveSupacloudConfig(loadedConfig, root);
188682
189491
  const config = compileOptionsFromConfig({
188683
189492
  ...loadedConfig,
188684
- root: args.root ? "." : loadedConfig.root,
188685
- outDir: args.out_dir ? resolve8(root, args.out_dir) : defaults.outDir,
189493
+ root: sourceRoot(args, root, loadedConfig.root),
189494
+ outDir: args.out_dir ? resolve9(root, args.out_dir) : defaults.outDir,
188686
189495
  include: parseInclude(args.include) ?? loadedConfig.include,
188687
189496
  strict: args.strict ?? loadedConfig.strict ?? false
188688
189497
  }, root);
188689
- const graph = await analyzeProject(config.rootDir, config.include);
188690
- const diagnostics = [
188691
- ...graph.diagnostics ?? [],
188692
- ...validateGraph(graph, {
188693
- strict: config.strict,
188694
- moduleBoundaryPreset: config.moduleBoundaryPreset
188695
- })
188696
- ];
188697
- if (config.strict) {
188698
- for (const diagnostic of diagnostics) {
188699
- if (diagnostic.severity === "warn")
188700
- diagnostic.severity = "error";
188701
- }
188702
- }
188703
- const hasError = diagnostics.some((diagnostic) => diagnostic.severity === "error");
188704
- const summary = `checked ${graph.modules.length} module(s), no files written`;
188705
- return textResult(`${formatDiagnostics(diagnostics)}
188706
-
188707
- ${summary}`, hasError);
189498
+ const result = await checkProject(config);
189499
+ const hasError = result.diagnostics.some((diagnostic) => diagnostic.severity === "error") || result.mismatches.length > 0;
189500
+ const summary = `checked ${result.graph.modules.length} module(s), no files written`;
189501
+ return textResult([
189502
+ formatDiagnostics(result.diagnostics),
189503
+ ...result.mismatches.map((path) => `generated artifact mismatch: ${path}`),
189504
+ "",
189505
+ summary
189506
+ ].join(`
189507
+ `), hasError);
188708
189508
  }
188709
189509
  async function readManifest(root) {
188710
- const manifestPath = join7(root, "generated", "app.manifest.json");
189510
+ const manifestPath = join8(root, "generated", "app.manifest.json");
188711
189511
  if (!existsSync9(manifestPath)) {
188712
189512
  throw new Error(`Manifest not found: ${manifestPath}(先运行 app compile 生成)`);
188713
189513
  }
@@ -188748,7 +189548,7 @@ function formatGraphText(manifest) {
188748
189548
  `);
188749
189549
  }
188750
189550
  async function runGraph(args) {
188751
- const root = resolve8(args.root || process.cwd());
189551
+ const root = resolve9(args.root || process.cwd());
188752
189552
  const manifest = await readManifest(root);
188753
189553
  if (args.format === "json")
188754
189554
  return textResult(JSON.stringify(manifest, null, 2));
@@ -188812,7 +189612,7 @@ async function runExplain(args) {
188812
189612
  const target = args.target?.trim();
188813
189613
  if (!target)
188814
189614
  throw new Error("app explain requires --target(provider 类名 / token 名 / command 名)");
188815
- const root = resolve8(args.root || process.cwd());
189615
+ const root = resolve9(args.root || process.cwd());
188816
189616
  const manifest = await readManifest(root);
188817
189617
  for (const module of manifest.modules) {
188818
189618
  const providerIndex = module.providers.findIndex((provider) => provider.token === target || provider.useClass === target);
@@ -188865,18 +189665,18 @@ async function runExplain(args) {
188865
189665
  return textResult(`未找到对象: ${target}`, true);
188866
189666
  }
188867
189667
  async function runExportTools(args) {
188868
- const root = resolve8(args.root || process.cwd());
189668
+ const root = resolve9(args.root || process.cwd());
188869
189669
  const manifest = await readManifest(root);
188870
189670
  const definitions = buildToolDefinitions(manifest);
188871
- const outDir = resolve8(args.out_dir || join7(root, "generated"));
188872
- await mkdir2(outDir, { recursive: true });
189671
+ const outDir = resolve9(args.out_dir || join8(root, "generated"));
189672
+ await mkdir3(outDir, { recursive: true });
188873
189673
  if (args.format === "json") {
188874
189674
  return textResult(JSON.stringify(definitions, null, 2));
188875
189675
  }
188876
- const openaiPath = join7(outDir, "tool-definitions.openai.json");
188877
- const mcpPath = join7(outDir, "tool-definitions.mcp.json");
188878
- await writeFile(openaiPath, JSON.stringify(definitions.openai, null, 2), "utf8");
188879
- await writeFile(mcpPath, JSON.stringify(definitions.mcp, null, 2), "utf8");
189676
+ const openaiPath = join8(outDir, "tool-definitions.openai.json");
189677
+ const mcpPath = join8(outDir, "tool-definitions.mcp.json");
189678
+ await writeFile3(openaiPath, JSON.stringify(definitions.openai, null, 2), "utf8");
189679
+ await writeFile3(mcpPath, JSON.stringify(definitions.mcp, null, 2), "utf8");
188880
189680
  const summary = [
188881
189681
  `exported ${definitions.openai.length} tool(s):`,
188882
189682
  ` openai → ${openaiPath}`,
@@ -188889,14 +189689,14 @@ async function runExportTools(args) {
188889
189689
  return textResult(summary);
188890
189690
  }
188891
189691
  function registerAppTools(server2) {
188892
- server2.tool("app", "Local @supacloud/app framework commands: scaffold, compile, check, graph, explain and export-tools. Actions: generate, compile, check, graph, explain, export-tools", {
188893
- action: withDescription(stringEnum(["generate", "compile", "check", "graph", "explain", "export-tools"]), "App action"),
189692
+ server2.tool("app", "Local @supacloud/app framework commands: init, scaffold, compile, check, graph, explain and export-tools. Actions: init, generate, compile, check, graph, explain, export-tools", {
189693
+ action: withDescription(stringEnum(["init", "generate", "compile", "check", "graph", "explain", "export-tools"]), "App action"),
188894
189694
  kind: optional(stringEnum(["module", "command", "query", "controller"]), "[generate] Scaffold kind"),
188895
- name: optional(Type.String(), "[generate] Object name (module name / command / query name)"),
189695
+ name: optional(Type.String(), "[init/generate] Project or object name"),
188896
189696
  module: optional(Type.String(), "[generate] Target feature module (required for command/query/controller)"),
188897
189697
  dir: optional(Type.String(), "[generate] Feature root directory (default: src/features)"),
188898
189698
  force: optional(Type.Boolean(), "[generate] Overwrite existing files"),
188899
- root: optional(Type.String(), "[generate/compile/check/graph/explain/export-tools] Project root (default: current directory)"),
189699
+ root: optional(Type.String(), "Project directory containing supacloud.config.ts (default: current directory)"),
188900
189700
  include: optional(Type.String(), "[compile/check] Comma-separated glob patterns for source files"),
188901
189701
  out_dir: optional(Type.String(), "[compile/export-tools] Output directory (default: <root>/generated)"),
188902
189702
  strict: optional(Type.Boolean(), "[compile/check] Promote warnings to errors"),
@@ -188904,6 +189704,8 @@ function registerAppTools(server2) {
188904
189704
  target: optional(Type.String(), "[explain] Provider class name / token name / command name")
188905
189705
  }, async (request) => {
188906
189706
  switch (request.action) {
189707
+ case "init":
189708
+ return initProject(request);
188907
189709
  case "generate":
188908
189710
  return generateScaffold(request);
188909
189711
  case "compile":
@@ -188924,7 +189726,7 @@ function registerAppTools(server2) {
188924
189726
 
188925
189727
  // src/shared/tools/db-governance-tools.ts
188926
189728
  import { existsSync as existsSync10 } from "node:fs";
188927
- import { join as join8, resolve as resolve9 } from "node:path";
189729
+ import { join as join9, resolve as resolve10 } from "node:path";
188928
189730
 
188929
189731
  // node_modules/@supacloud/db/dist/index.js
188930
189732
  var TABLES_SQL = `
@@ -189376,7 +190178,7 @@ function normalizeModule(candidate, sourcePath2) {
189376
190178
  };
189377
190179
  }
189378
190180
  async function loadDatabaseModules(root, moduleFile) {
189379
- const filePath = moduleFile ? resolve9(root, moduleFile) : join8(root, "db", "modules.ts");
190181
+ const filePath = moduleFile ? resolve10(root, moduleFile) : join9(root, "db", "modules.ts");
189380
190182
  if (!existsSync10(filePath)) {
189381
190183
  throw new Error(moduleFile ? `Module file not found: ${filePath}` : `Module file not found: ${filePath}(用 --module_file 指定一个导出 defineDatabaseModule(...) 的文件)`);
189382
190184
  }
@@ -189425,7 +190227,7 @@ async function runLint(args, root) {
189425
190227
  const issues = [];
189426
190228
  for (const module of selected) {
189427
190229
  const readSqlFile = async (path) => {
189428
- const absolute = resolve9(root, path);
190230
+ const absolute = resolve10(root, path);
189429
190231
  try {
189430
190232
  return await Bun.file(absolute).text();
189431
190233
  } catch (error) {
@@ -189461,14 +190263,14 @@ var defaultLiteSpawn = async (command, cwd) => {
189461
190263
  return { exitCode, stdout, stderr };
189462
190264
  };
189463
190265
  async function runModuleCheckLite(args, root, spawn3, liteBinary) {
189464
- const projectDir = resolve9(args.project_dir?.trim() || root);
190266
+ const projectDir = resolve10(args.project_dir?.trim() || root);
189465
190267
  const binary = liteBinary === undefined ? Bun.which("supacloud-lite") : liteBinary;
189466
190268
  if (!binary) {
189467
190269
  throw new Error("db module_check --lite 需要本机可用的 supacloud-lite(npm i -g @supacloud/lite,或加入 PATH)");
189468
190270
  }
189469
190271
  const command = [binary, "db", "check", "--project-dir", projectDir];
189470
190272
  if (args.module_file?.trim())
189471
- command.push("--module-file", resolve9(root, args.module_file.trim()));
190273
+ command.push("--module-file", resolve10(root, args.module_file.trim()));
189472
190274
  const result = await spawn3(command, projectDir);
189473
190275
  const output = [result.stdout.trim(), result.stderr.trim()].filter(Boolean).join(`
189474
190276
  `);
@@ -189519,7 +190321,7 @@ function registerDbGovernanceTools(server2, options = {}) {
189519
190321
  lite: optional(Type.Boolean(), "[module_check] Reconcile against a local SupaCloud Lite project (runs supacloud-lite db check)"),
189520
190322
  project_dir: optional(Type.String(), "[module_check] Lite project directory (with --lite; default: --root)")
189521
190323
  }, async (request) => {
189522
- const root = resolve9(request.root || fallbackRoot);
190324
+ const root = resolve10(request.root || fallbackRoot);
189523
190325
  switch (request.action) {
189524
190326
  case "lint":
189525
190327
  return runLint(request, root);
@@ -189536,7 +190338,7 @@ function registerDbGovernanceTools(server2, options = {}) {
189536
190338
  // src/shared/tools/scheduled-function-tools.ts
189537
190339
  import { randomUUID } from "node:crypto";
189538
190340
  import { readFileSync as readFileSync7, statSync as statSync5 } from "node:fs";
189539
- import { resolve as resolve10 } from "node:path";
190341
+ import { resolve as resolve11 } from "node:path";
189540
190342
  import { isDeepStrictEqual } from "node:util";
189541
190343
  var HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/;
189542
190344
  var ENVIRONMENT_NAME_PATTERN2 = /^[A-Za-z_][A-Za-z0-9_]{0,255}$/;
@@ -189620,7 +190422,7 @@ function validScheduledFunctionCron(expression) {
189620
190422
  function readScheduleBodyFile(bodyPathInput) {
189621
190423
  if (!bodyPathInput.trim())
189622
190424
  throw new Error("'body_file' must be a path");
189623
- const bodyPath = resolve10(bodyPathInput);
190425
+ const bodyPath = resolve11(bodyPathInput);
189624
190426
  const bodyStat = statSync5(bodyPath);
189625
190427
  if (!bodyStat.isFile() || bodyStat.size > MAX_BODY_FILE_BYTES) {
189626
190428
  throw new Error("Scheduled Function body file must be a regular file no larger than 1 MiB");
@@ -190201,6 +191003,10 @@ var MUTATION_TOOL_SCHEMA = {
190201
191003
  };
190202
191004
 
190203
191005
  // src/shared/tools/release-tools.ts
191006
+ import { execFileSync } from "node:child_process";
191007
+ import { createHash as createHash5 } from "node:crypto";
191008
+ import { existsSync as existsSync11, mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "node:fs";
191009
+ import { dirname as dirname8, join as join10, relative as relative5, resolve as resolve12 } from "node:path";
190204
191010
  var SAFE_PROJECT_REF = /^[A-Za-z0-9_-]{1,64}$/;
190205
191011
  var BACKUP_ID = /^logical-full_[A-Za-z0-9_-]{1,64}_[a-f0-9]{32}$/;
190206
191012
  var SHA256 = /^[a-f0-9]{64}$/;
@@ -190417,18 +191223,337 @@ async function applicationOriginMatches(http, projectRef2, applicationOrigin) {
190417
191223
  const endpointRead = await http.get(`${endpoint(projectRef2)}/endpoint/projection`, { maxJsonBytes: PROJECT_ENDPOINT_RESPONSE_MAX_BYTES, responseTimeoutMs: RELEASE_READ_RESPONSE_TIMEOUT_MS });
190418
191224
  return projectApiOrigins(endpointRead, projectRef2)?.includes(applicationOrigin) === true;
190419
191225
  }
191226
+ function canonicalValue(value) {
191227
+ if (Array.isArray(value))
191228
+ return value.map(canonicalValue);
191229
+ if (!value || typeof value !== "object")
191230
+ return value;
191231
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, canonicalValue(item)]));
191232
+ }
191233
+ function genericScopedReleaseScopeJson(scope) {
191234
+ return JSON.stringify(canonicalValue(scope));
191235
+ }
191236
+ function genericScopedReleaseScopeSha256(scope) {
191237
+ return createHash5("sha256").update(genericScopedReleaseScopeJson(scope)).digest("hex");
191238
+ }
191239
+ function resolveGitBaseCommit(cwd, explicitRef) {
191240
+ if (typeof explicitRef === "string" && explicitRef.trim()) {
191241
+ const trimmed = explicitRef.trim();
191242
+ if (/^[0-9a-f]{40}$/.test(trimmed)) {
191243
+ try {
191244
+ const verified = execFileSync("git", ["rev-parse", "--verify", `${trimmed}^{commit}`], {
191245
+ cwd,
191246
+ encoding: "utf8",
191247
+ stdio: ["ignore", "pipe", "pipe"]
191248
+ }).trim();
191249
+ if (/^[0-9a-f]{40}$/.test(verified))
191250
+ return verified;
191251
+ } catch {
191252
+ return trimmed;
191253
+ }
191254
+ return trimmed;
191255
+ }
191256
+ try {
191257
+ const sha = execFileSync("git", ["rev-parse", "--verify", `${trimmed}^{commit}`], {
191258
+ cwd,
191259
+ encoding: "utf8",
191260
+ stdio: ["ignore", "pipe", "pipe"]
191261
+ }).trim();
191262
+ if (/^[0-9a-f]{40}$/.test(sha))
191263
+ return sha;
191264
+ } catch {
191265
+ throw new Error(`Unable to resolve base commit from git ref '${trimmed}'`);
191266
+ }
191267
+ }
191268
+ const candidateRefs = ["origin/main", "main", "HEAD^", "HEAD"];
191269
+ for (const candidate of candidateRefs) {
191270
+ try {
191271
+ const sha = execFileSync("git", ["rev-parse", "--verify", `${candidate}^{commit}`], {
191272
+ cwd,
191273
+ encoding: "utf8",
191274
+ stdio: ["ignore", "pipe", "pipe"]
191275
+ }).trim();
191276
+ if (/^[0-9a-f]{40}$/.test(sha))
191277
+ return sha;
191278
+ } catch {
191279
+ continue;
191280
+ }
191281
+ }
191282
+ throw new Error("Unable to resolve git base commit. Pass --base_commit explicitly.");
191283
+ }
191284
+ function gitCommitInfo(cwd) {
191285
+ let head = null;
191286
+ let originMain = null;
191287
+ let parent = null;
191288
+ try {
191289
+ head = execFileSync("git", ["rev-parse", "HEAD"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
191290
+ } catch {}
191291
+ try {
191292
+ originMain = execFileSync("git", ["rev-parse", "--verify", "origin/main^{commit}"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
191293
+ } catch {}
191294
+ try {
191295
+ parent = execFileSync("git", ["rev-parse", "HEAD^"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
191296
+ } catch {}
191297
+ return { head, originMain, parent };
191298
+ }
191299
+ function collectScopeFiles(cwd, file, files, dir, task) {
191300
+ const results = [];
191301
+ const resolvePathWithFallbacks = (filePath) => {
191302
+ const trimmed = filePath.trim();
191303
+ const resolved = resolve12(cwd, trimmed);
191304
+ if (existsSync11(resolved))
191305
+ return resolved;
191306
+ const candidates2 = [
191307
+ resolve12(cwd, "supacloud/fa/release-scopes", trimmed),
191308
+ resolve12(cwd, "release-scopes", trimmed),
191309
+ resolve12(cwd, "scopes", trimmed)
191310
+ ];
191311
+ const found = candidates2.find(existsSync11);
191312
+ if (found)
191313
+ return found;
191314
+ throw new Error(`Scope file not found: ${filePath}`);
191315
+ };
191316
+ if (typeof file === "string" && file.trim()) {
191317
+ results.push(resolvePathWithFallbacks(file));
191318
+ }
191319
+ if (typeof files === "string" && files.trim()) {
191320
+ const parts = files.split(",").map((s) => s.trim()).filter(Boolean);
191321
+ for (const part of parts) {
191322
+ results.push(resolvePathWithFallbacks(part));
191323
+ }
191324
+ }
191325
+ if (results.length > 0) {
191326
+ return [...new Set(results)];
191327
+ }
191328
+ const taskFilter = typeof task === "string" && task.trim() ? task.trim().toLowerCase() : null;
191329
+ if (!taskFilter && (!dir || typeof dir !== "string" || !dir.trim())) {
191330
+ throw new Error("At least one of --file, --files, or --task is required for scope_rebind");
191331
+ }
191332
+ const candidates = typeof dir === "string" && dir.trim() ? [resolve12(cwd, dir.trim())] : [
191333
+ resolve12(cwd, "supacloud/fa/release-scopes"),
191334
+ resolve12(cwd, "release-scopes"),
191335
+ resolve12(cwd, "scopes")
191336
+ ];
191337
+ for (const directory of candidates) {
191338
+ if (existsSync11(directory)) {
191339
+ try {
191340
+ const entries = readdirSync4(directory, { withFileTypes: true });
191341
+ for (const entry of entries) {
191342
+ if (entry.isFile() && entry.name.endsWith(".json")) {
191343
+ const fullPath = join10(directory, entry.name);
191344
+ if (!taskFilter) {
191345
+ results.push(fullPath);
191346
+ } else if (entry.name.toLowerCase().includes(taskFilter)) {
191347
+ results.push(fullPath);
191348
+ } else {
191349
+ try {
191350
+ const parsed = JSON.parse(readFileSync8(fullPath, "utf8"));
191351
+ if (typeof parsed?.taskId === "string" && parsed.taskId.toLowerCase() === taskFilter) {
191352
+ results.push(fullPath);
191353
+ }
191354
+ } catch {}
191355
+ }
191356
+ }
191357
+ }
191358
+ if (results.length > 0)
191359
+ break;
191360
+ } catch {}
191361
+ }
191362
+ }
191363
+ if (results.length === 0) {
191364
+ throw new Error("No release scope files found to rebind");
191365
+ }
191366
+ return [...new Set(results)];
191367
+ }
191368
+ function handleScopeRebind(args) {
191369
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve12(args.cwd.trim()) : process.cwd();
191370
+ const targetBaseCommit = resolveGitBaseCommit(cwd, args.base_commit);
191371
+ const scopeFiles = collectScopeFiles(cwd, args.file, args.files, args.dir, args.task);
191372
+ const dryRun = args.dry_run === true;
191373
+ const scopes = [];
191374
+ for (const filePath of scopeFiles) {
191375
+ let content;
191376
+ try {
191377
+ content = readFileSync8(filePath, "utf8");
191378
+ } catch (cause) {
191379
+ throw new Error(`Failed to read scope file '${filePath}': ${cause instanceof Error ? cause.message : String(cause)}`);
191380
+ }
191381
+ let parsed;
191382
+ try {
191383
+ parsed = JSON.parse(content);
191384
+ } catch {
191385
+ throw new Error(`Scope file '${filePath}' is not valid JSON`);
191386
+ }
191387
+ if (!isRecord3(parsed) || typeof parsed.baseCommit !== "string" || !/^[0-9a-f]{40}$/.test(parsed.baseCommit)) {
191388
+ throw new Error(`Scope file '${filePath}' has missing or invalid baseCommit`);
191389
+ }
191390
+ const previousBaseCommit = parsed.baseCommit;
191391
+ const updated = previousBaseCommit !== targetBaseCommit;
191392
+ if (updated) {
191393
+ parsed.baseCommit = targetBaseCommit;
191394
+ }
191395
+ const canonicalJson = genericScopedReleaseScopeJson(parsed);
191396
+ const scopeSha256 = genericScopedReleaseScopeSha256(parsed);
191397
+ if (updated && !dryRun) {
191398
+ const formatted = JSON.stringify(canonicalValue(parsed), null, 2) + `
191399
+ `;
191400
+ writeFileSync3(filePath, formatted, "utf8");
191401
+ }
191402
+ scopes.push({
191403
+ file: relative5(cwd, filePath),
191404
+ task_id: typeof parsed.taskId === "string" ? parsed.taskId : "",
191405
+ target_project_ref: typeof parsed.targetProjectRef === "string" ? parsed.targetProjectRef : "",
191406
+ previous_base_commit: previousBaseCommit,
191407
+ new_base_commit: targetBaseCommit,
191408
+ scope_sha256: scopeSha256,
191409
+ updated
191410
+ });
191411
+ }
191412
+ return releaseControlSuccess("release.scope_rebind", {
191413
+ base_commit: targetBaseCommit,
191414
+ dry_run: dryRun,
191415
+ count: scopes.length,
191416
+ updated_count: scopes.filter((s) => s.updated).length,
191417
+ scopes
191418
+ });
191419
+ }
191420
+ function handleScopeInspect(args) {
191421
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve12(args.cwd.trim()) : process.cwd();
191422
+ if (typeof args.file !== "string" || !args.file.trim()) {
191423
+ throw new Error("'file' is required for scope_inspect");
191424
+ }
191425
+ const trimmed = args.file.trim();
191426
+ let filePath = resolve12(cwd, trimmed);
191427
+ if (!existsSync11(filePath)) {
191428
+ const candidates = [
191429
+ resolve12(cwd, "supacloud/fa/release-scopes", trimmed),
191430
+ resolve12(cwd, "release-scopes", trimmed),
191431
+ resolve12(cwd, "scopes", trimmed)
191432
+ ];
191433
+ const found = candidates.find(existsSync11);
191434
+ if (found)
191435
+ filePath = found;
191436
+ else
191437
+ throw new Error(`Scope file not found: ${args.file}`);
191438
+ }
191439
+ let content;
191440
+ try {
191441
+ content = readFileSync8(filePath, "utf8");
191442
+ } catch (cause) {
191443
+ throw new Error(`Failed to read scope file '${args.file}': ${cause instanceof Error ? cause.message : String(cause)}`);
191444
+ }
191445
+ let parsed;
191446
+ try {
191447
+ parsed = JSON.parse(content);
191448
+ } catch {
191449
+ throw new Error(`Scope file '${args.file}' is not valid JSON`);
191450
+ }
191451
+ if (!isRecord3(parsed) || typeof parsed.baseCommit !== "string" || !/^[0-9a-f]{40}$/.test(parsed.baseCommit)) {
191452
+ throw new Error(`Scope file '${args.file}' has missing or invalid baseCommit`);
191453
+ }
191454
+ const scopeSha256 = genericScopedReleaseScopeSha256(parsed);
191455
+ const git = gitCommitInfo(cwd);
191456
+ return releaseControlSuccess("release.scope_inspect", {
191457
+ file: relative5(cwd, filePath),
191458
+ scope: {
191459
+ task_id: parsed.taskId,
191460
+ target_project_ref: parsed.targetProjectRef,
191461
+ base_commit: parsed.baseCommit,
191462
+ functions: parsed.functions,
191463
+ excluded_functions: parsed.excludedFunctions,
191464
+ migrations: parsed.migrations,
191465
+ deferred_migrations: parsed.deferredMigrations,
191466
+ baseline_migrations: parsed.baselineMigrations,
191467
+ web: parsed.web,
191468
+ scope_sha256: scopeSha256
191469
+ },
191470
+ git: {
191471
+ matches_head: git.head !== null && parsed.baseCommit === git.head,
191472
+ matches_origin_main: git.originMain !== null && parsed.baseCommit === git.originMain,
191473
+ matches_parent: git.parent !== null && parsed.baseCommit === git.parent,
191474
+ current_head: git.head,
191475
+ origin_main: git.originMain
191476
+ }
191477
+ });
191478
+ }
191479
+ function parseCommaList(value) {
191480
+ if (!value)
191481
+ return [];
191482
+ if (Array.isArray(value)) {
191483
+ return [...new Set(value.map(String).map((s) => s.trim()).filter(Boolean))].sort();
191484
+ }
191485
+ if (typeof value === "string") {
191486
+ return [...new Set(value.split(",").map((s) => s.trim()).filter(Boolean))].sort();
191487
+ }
191488
+ return [];
191489
+ }
191490
+ function handleScopeCreate(args, fallbackRef) {
191491
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve12(args.cwd.trim()) : process.cwd();
191492
+ if (typeof args.file !== "string" || !args.file.trim()) {
191493
+ throw new Error("'file' is required for scope_create");
191494
+ }
191495
+ if (typeof args.task !== "string" || !args.task.trim()) {
191496
+ throw new Error("'task' is required for scope_create");
191497
+ }
191498
+ const projectRef2 = typeof args.ref === "string" && args.ref.trim() || fallbackRef;
191499
+ if (!projectRef2) {
191500
+ throw new Error("'ref' is required for scope_create");
191501
+ }
191502
+ if (!validProjectRef(projectRef2)) {
191503
+ throw new Error("'ref' is invalid for release controls");
191504
+ }
191505
+ const targetBaseCommit = resolveGitBaseCommit(cwd, args.base_commit);
191506
+ const filePath = resolve12(cwd, args.file.trim());
191507
+ mkdirSync4(dirname8(filePath), { recursive: true });
191508
+ const scope = {
191509
+ baseCommit: targetBaseCommit,
191510
+ excludedFunctions: parseCommaList(args.excluded_functions),
191511
+ functions: parseCommaList(args.functions),
191512
+ migrations: parseCommaList(args.migrations),
191513
+ targetProjectRef: projectRef2,
191514
+ taskId: String(args.task).trim(),
191515
+ web: Boolean(args.web)
191516
+ };
191517
+ const canonicalJson = genericScopedReleaseScopeJson(scope);
191518
+ const scopeSha256 = genericScopedReleaseScopeSha256(scope);
191519
+ const formatted = JSON.stringify(canonicalValue(scope), null, 2) + `
191520
+ `;
191521
+ writeFileSync3(filePath, formatted, "utf8");
191522
+ return releaseControlSuccess("release.scope_create", {
191523
+ file: relative5(cwd, filePath),
191524
+ task_id: scope.taskId,
191525
+ target_project_ref: projectRef2,
191526
+ base_commit: targetBaseCommit,
191527
+ scope_sha256: scopeSha256,
191528
+ scope
191529
+ });
191530
+ }
190420
191531
  function registerReleaseTools(server2, http, options = {}) {
190421
- server2.tool("release", "Verified release controls. Management actions use the Management API; release canary stage/disable replay additionally require the selected project's SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY.", {
190422
- action: withDescription(stringEnum([
190423
- "logical_backup_list",
190424
- "logical_backup_create",
190425
- "logical_backup_restore",
190426
- "postgrest_status",
190427
- "postgrest_restart",
190428
- "release_canary_fixture_stage_replay",
190429
- "release_canary_fixture_disable_replay"
190430
- ]), "Release control action"),
191532
+ const localActions = ["scope_inspect", "scope_rebind", "scope_create"];
191533
+ const remoteActions = [
191534
+ "logical_backup_list",
191535
+ "logical_backup_create",
191536
+ "logical_backup_restore",
191537
+ "postgrest_status",
191538
+ "postgrest_restart",
191539
+ "release_canary_fixture_stage_replay",
191540
+ "release_canary_fixture_disable_replay"
191541
+ ];
191542
+ const allActions = [...remoteActions, ...localActions];
191543
+ server2.tool("release", "Verified release controls. Scope management actions operate locally; management actions use the Management API; release canary stage/disable replay additionally require the selected project's SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY.", {
191544
+ action: withDescription(stringEnum(allActions), "Release control action"),
190431
191545
  ref: optional(Type.String(), options.projectRef ? "Optional override when not auto-linked" : "Project ref"),
191546
+ file: optional(Type.String(), "[scope_inspect/scope_rebind/scope_create] Path to release scope JSON file"),
191547
+ files: optional(Type.String(), "[scope_rebind] Comma-separated list of release scope JSON files"),
191548
+ dir: optional(Type.String(), "[scope_rebind] Directory containing release scope JSON files (defaults to supacloud/fa/release-scopes, release-scopes, or scopes)"),
191549
+ task: optional(Type.String(), "[scope_rebind/scope_create] Task ID or prefix filter for scope files"),
191550
+ base_commit: optional(Type.String(), "[scope_rebind/scope_create] Target 40-character base commit SHA or git ref (defaults to origin/main -> main -> HEAD^ -> HEAD)"),
191551
+ functions: optional(Type.String(), "[scope_create] Comma-separated list of functions to deploy"),
191552
+ excluded_functions: optional(Type.String(), "[scope_create] Comma-separated list of functions to exclude"),
191553
+ migrations: optional(Type.String(), "[scope_create] Comma-separated list of migrations to apply"),
191554
+ web: optional(Type.Boolean(), "[scope_create] Whether web assets are included in release scope"),
191555
+ dry_run: optional(Type.Boolean(), "[scope_rebind] Perform calculation and validation without writing files"),
191556
+ cwd: optional(Type.String(), "[scope_inspect/scope_rebind/scope_create] Base directory for relative file and git resolution"),
190432
191557
  backup_id: optional(Type.String(), "[logical_backup_restore] Exact verified logical-full backup ID from the selected project inventory"),
190433
191558
  expected_sha256: optional(Type.String(), "[logical_backup_restore] Exact lowercase SHA-256 from the selected project inventory"),
190434
191559
  restore_confirmation: optional(Type.String(), "[logical_backup_restore] Exact RESTORE_PROJECT:<ref>:<backup_id>:<sha256> confirmation"),
@@ -190437,7 +191562,29 @@ function registerReleaseTools(server2, http, options = {}) {
190437
191562
  fixture_id: optional(Type.String(), "[release_canary_fixture_disable_replay] Exact staged fixture UUID"),
190438
191563
  disable_request_id: optional(Type.String(), "[release_canary_fixture_disable_replay] Exact idempotent disable request UUID"),
190439
191564
  issuer: optional(Type.String(), "[release_canary_fixture_disable_replay] Exact HTTP(S) issuer")
190440
- }, async ({ action, ref, backup_id, expected_sha256, restore_confirmation, subject, request_id, fixture_id, disable_request_id, issuer }) => {
191565
+ }, async (args) => {
191566
+ const { action } = args;
191567
+ if (action === "scope_rebind") {
191568
+ return handleScopeRebind(args);
191569
+ }
191570
+ if (action === "scope_inspect") {
191571
+ return handleScopeInspect(args);
191572
+ }
191573
+ if (action === "scope_create") {
191574
+ return handleScopeCreate(args, options.projectRef);
191575
+ }
191576
+ if (options.localOnly || !http) {
191577
+ return {
191578
+ isError: true,
191579
+ content: [
191580
+ {
191581
+ type: "text",
191582
+ text: "⚠️ This command requires Management API context. Run `supacloud-cli status` to inspect current detection."
191583
+ }
191584
+ ]
191585
+ };
191586
+ }
191587
+ const { ref, backup_id, expected_sha256, restore_confirmation, subject, request_id, fixture_id, disable_request_id, issuer } = args;
190441
191588
  const projectRef2 = typeof ref === "string" && ref || options.projectRef;
190442
191589
  if (!projectRef2)
190443
191590
  throw new Error("'ref' is required for release controls");
@@ -190578,10 +191725,10 @@ function registerReleaseTools(server2, http, options = {}) {
190578
191725
  }
190579
191726
 
190580
191727
  // src/shared/tools/deploy-tools.ts
190581
- import { access as access2, lstat, mkdtemp, opendir, readFile as readFile2, rm, writeFile as writeFile3 } from "node:fs/promises";
190582
- import { createHash as createHash5 } from "node:crypto";
191728
+ import { access as access2, lstat as lstat2, mkdtemp, opendir, readFile as readFile2, rm, writeFile as writeFile5 } from "node:fs/promises";
191729
+ import { createHash as createHash6 } from "node:crypto";
190583
191730
  import { tmpdir as tmpdir2 } from "node:os";
190584
- import { basename as basename4, dirname as dirname7, join as join9, relative as relative5, resolve as resolve11, sep as sep5 } from "node:path";
191731
+ import { basename as basename5, dirname as dirname9, join as join11, relative as relative7, resolve as resolve13, sep as sep5 } from "node:path";
190585
191732
  import { spawn as spawn3 } from "node:child_process";
190586
191733
 
190587
191734
  // node_modules/fflate/esm/index.mjs
@@ -191273,13 +192420,13 @@ async function readJson(path) {
191273
192420
  }
191274
192421
  }
191275
192422
  async function findDeployConfigRoot(startDirectory) {
191276
- let directory = resolve11(startDirectory);
192423
+ let directory = resolve13(startDirectory);
191277
192424
  while (true) {
191278
- if (await pathExists(join9(directory, "supacloud.json")))
192425
+ if (await pathExists(join11(directory, "supacloud.json")))
191279
192426
  return directory;
191280
- const parent = dirname7(directory);
192427
+ const parent = dirname9(directory);
191281
192428
  if (parent === directory)
191282
- return resolve11(startDirectory);
192429
+ return resolve13(startDirectory);
191283
192430
  directory = parent;
191284
192431
  }
191285
192432
  }
@@ -191322,7 +192469,7 @@ function deployTargetConfig(candidate, name) {
191322
192469
  };
191323
192470
  }
191324
192471
  async function readDeployConfig(configRoot) {
191325
- const configPath = join9(configRoot, "supacloud.json");
192472
+ const configPath = join11(configRoot, "supacloud.json");
191326
192473
  const candidate = await readJson(configPath);
191327
192474
  if (candidate === null)
191328
192475
  return {};
@@ -191344,29 +192491,29 @@ async function readDeployConfig(configRoot) {
191344
192491
  };
191345
192492
  }
191346
192493
  async function packageName(projectDirectory) {
191347
- const candidate = record2(await readJson(join9(projectDirectory, "package.json")));
192494
+ const candidate = record2(await readJson(join11(projectDirectory, "package.json")));
191348
192495
  return typeof candidate?.name === "string" && candidate.name.trim() ? candidate.name.trim() : null;
191349
192496
  }
191350
192497
  async function pathExists(path) {
191351
192498
  return access2(path).then(() => true, () => false);
191352
192499
  }
191353
192500
  async function defaultBuildCommand(projectDirectory, configRoot) {
191354
- const packageJson = record2(await readJson(join9(projectDirectory, "package.json")));
192501
+ const packageJson = record2(await readJson(join11(projectDirectory, "package.json")));
191355
192502
  const scripts = record2(packageJson?.scripts);
191356
192503
  if (typeof scripts?.build !== "string" || !scripts.build.trim()) {
191357
192504
  throw new Error("No build command was configured and package.json has no build script");
191358
192505
  }
191359
192506
  let directory = projectDirectory;
191360
192507
  while (true) {
191361
- if (await pathExists(join9(directory, "bun.lock")) || await pathExists(join9(directory, "bun.lockb")))
192508
+ if (await pathExists(join11(directory, "bun.lock")) || await pathExists(join11(directory, "bun.lockb")))
191362
192509
  return "bun run build";
191363
- if (await pathExists(join9(directory, "pnpm-lock.yaml")))
192510
+ if (await pathExists(join11(directory, "pnpm-lock.yaml")))
191364
192511
  return "pnpm run build";
191365
- if (await pathExists(join9(directory, "yarn.lock")))
192512
+ if (await pathExists(join11(directory, "yarn.lock")))
191366
192513
  return "yarn build";
191367
192514
  if (directory === configRoot)
191368
192515
  break;
191369
- const parent = dirname7(directory);
192516
+ const parent = dirname9(directory);
191370
192517
  if (parent === directory || !directory.startsWith(`${configRoot}${sep5}`))
191371
192518
  break;
191372
192519
  directory = parent;
@@ -191397,9 +192544,9 @@ function selectDeployment(deployments, requestedId, projectName) {
191397
192544
  throw new Error(deployments.length === 0 ? "No frontend deployments exist for this project" : `Multiple frontend deployments found (${ids}). Set frontend.id in supacloud.json or pass --id`);
191398
192545
  }
191399
192546
  function targetRoot(configRoot, target, name) {
191400
- const root = resolve11(configRoot, target.root || (name === "frontend" ? "." : name));
191401
- const prefix = `${resolve11(configRoot)}${sep5}`;
191402
- if (root !== resolve11(configRoot) && !root.startsWith(prefix)) {
192547
+ const root = resolve13(configRoot, target.root || (name === "frontend" ? "." : name));
192548
+ const prefix = `${resolve13(configRoot)}${sep5}`;
192549
+ if (root !== resolve13(configRoot) && !root.startsWith(prefix)) {
191403
192550
  throw new Error(`Deploy target '${name}' root must stay inside the repository root`);
191404
192551
  }
191405
192552
  return root;
@@ -191450,8 +192597,8 @@ function defaultOutputDirectory(framework) {
191450
192597
  }
191451
192598
  }
191452
192599
  function resolveInsideProject(projectDirectory, candidate, allowRoot = false) {
191453
- const resolved = resolve11(projectDirectory, candidate);
191454
- const projectRoot = resolve11(projectDirectory);
192600
+ const resolved = resolve13(projectDirectory, candidate);
192601
+ const projectRoot = resolve13(projectDirectory);
191455
192602
  const projectPrefix = `${projectRoot}${sep5}`;
191456
192603
  if (!allowRoot && resolved === projectRoot || resolved !== projectRoot && !resolved.startsWith(projectPrefix)) {
191457
192604
  throw new Error("Frontend output directory must stay inside the project directory");
@@ -191471,7 +192618,7 @@ async function runBuild(command, cwd) {
191471
192618
  });
191472
192619
  }
191473
192620
  async function collectArchiveFiles(root) {
191474
- const rootStat = await lstat(root).catch(() => null);
192621
+ const rootStat = await lstat2(root).catch(() => null);
191475
192622
  if (!rootStat?.isDirectory() || rootStat.isSymbolicLink()) {
191476
192623
  throw new Error(`Frontend output directory does not exist or is not a regular directory: ${root}`);
191477
192624
  }
@@ -191482,8 +192629,8 @@ async function collectArchiveFiles(root) {
191482
192629
  entries.push(entry);
191483
192630
  entries.sort((left, right) => left.name.localeCompare(right.name, "en"));
191484
192631
  for (const entry of entries) {
191485
- const path = join9(directory, entry.name);
191486
- const stats = await lstat(path);
192632
+ const path = join11(directory, entry.name);
192633
+ const stats = await lstat2(path);
191487
192634
  if (stats.isSymbolicLink())
191488
192635
  throw new Error(`Frontend output cannot contain symbolic links: ${path}`);
191489
192636
  if (stats.isDirectory())
@@ -191504,19 +192651,19 @@ async function collectArchiveFiles(root) {
191504
192651
  bytes += data.byteLength;
191505
192652
  if (bytes > MAX_SOURCE_BYTES)
191506
192653
  throw new Error(`Frontend output exceeds ${MAX_SOURCE_BYTES} bytes`);
191507
- const archivePath = relative5(root, path).split(sep5).join("/");
192654
+ const archivePath = relative7(root, path).split(sep5).join("/");
191508
192655
  files[archivePath] = [data, { mtime: FIXED_ZIP_MTIME }];
191509
192656
  }
191510
192657
  return { files, bytes, count: paths.length };
191511
192658
  }
191512
192659
  async function createFrontendArchive(outputDirectory) {
191513
192660
  const collected = await collectArchiveFiles(outputDirectory);
191514
- const temporaryDirectory = await mkdtemp(join9(tmpdir2(), "supacloud-deploy-"));
191515
- const archivePath = join9(temporaryDirectory, `${basename4(outputDirectory)}.zip`);
192661
+ const temporaryDirectory = await mkdtemp(join11(tmpdir2(), "supacloud-deploy-"));
192662
+ const archivePath = join11(temporaryDirectory, `${basename5(outputDirectory)}.zip`);
191516
192663
  try {
191517
192664
  const archiveBytes = zipSync(collected.files, { level: 6, mtime: FIXED_ZIP_MTIME });
191518
- await writeFile3(archivePath, archiveBytes);
191519
- const sha256 = createHash5("sha256").update(archiveBytes).digest("hex");
192665
+ await writeFile5(archivePath, archiveBytes);
192666
+ const sha256 = createHash6("sha256").update(archiveBytes).digest("hex");
191520
192667
  return {
191521
192668
  archivePath,
191522
192669
  sha256,
@@ -191538,16 +192685,16 @@ function payload(response) {
191538
192685
  throw new Error("Deployment operation returned an invalid response");
191539
192686
  return parsed;
191540
192687
  }
191541
- function phaseReporter(json) {
192688
+ function phaseReporter(json2) {
191542
192689
  const started = performance.now();
191543
192690
  return (phase, detail) => {
191544
- if (!json)
192691
+ if (!json2)
191545
192692
  console.error(` ${phase.padEnd(10)} ${detail}`);
191546
192693
  return Math.round(performance.now() - started);
191547
192694
  };
191548
192695
  }
191549
- function deployResponse(result, json) {
191550
- if (json)
192696
+ function deployResponse(result, json2) {
192697
+ if (json2)
191551
192698
  return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
191552
192699
  const lines = [
191553
192700
  result.unchanged === true ? "Already up to date." : `Deployed ${String(result.target || result.deployment_id || result.slug)}.`,
@@ -191562,7 +192709,7 @@ function deployResponse(result, json) {
191562
192709
  }
191563
192710
  function registerDeployTools(server2, http, options = {}) {
191564
192711
  server2.tool("deploy", "Build and publish the linked frontend with one command", deployToolSchema, async (args) => {
191565
- const invocationDirectory = resolve11(String(args.cwd || options.cwd || process.cwd()));
192712
+ const invocationDirectory = resolve13(String(args.cwd || options.cwd || process.cwd()));
191566
192713
  const projectRef2 = String(args.ref || options.projectRef || "").trim();
191567
192714
  if (!projectRef2)
191568
192715
  throw new Error("A linked project ref is required. Set SUPACLOUD_PROJECT_REF or pass --ref");
@@ -191570,7 +192717,7 @@ function registerDeployTools(server2, http, options = {}) {
191570
192717
  const config = await readDeployConfig(configRoot);
191571
192718
  const target = selectTarget(configRoot, invocationDirectory, config, String(args.target || "").trim() || undefined);
191572
192719
  const projectDirectory = target.root;
191573
- const targetState = await lstat(projectDirectory).catch(() => null);
192720
+ const targetState = await lstat2(projectDirectory).catch(() => null);
191574
192721
  if (!targetState?.isDirectory() || targetState.isSymbolicLink()) {
191575
192722
  throw new Error(`Deploy target '${target.name}' root is not a regular directory: ${projectDirectory}`);
191576
192723
  }
@@ -191676,7 +192823,7 @@ function registerDeployTools(server2, http, options = {}) {
191676
192823
  } else {
191677
192824
  report("build", "skipped");
191678
192825
  }
191679
- report("package", relative5(projectDirectory, outputDirectory) || ".");
192826
+ report("package", relative7(projectDirectory, outputDirectory) || ".");
191680
192827
  const archive = await createFrontendArchive(outputDirectory);
191681
192828
  try {
191682
192829
  const inventory = payload(await listFrontendReleases(http, projectRef2, selected.id, undefined, 100));
@@ -191735,11 +192882,11 @@ function registerDeployTools(server2, http, options = {}) {
191735
192882
 
191736
192883
  // src/shared/tools/remote-dev-tools.ts
191737
192884
  import { spawn as spawn4 } from "node:child_process";
191738
- import { existsSync as existsSync11 } from "node:fs";
192885
+ import { existsSync as existsSync12 } from "node:fs";
191739
192886
  import { readFile as readFile3 } from "node:fs/promises";
191740
- import { readdir } from "node:fs/promises";
191741
- import { createHash as createHash6 } from "node:crypto";
191742
- import { join as join10, resolve as resolve12 } from "node:path";
192887
+ import { readdir as readdir2 } from "node:fs/promises";
192888
+ import { createHash as createHash7 } from "node:crypto";
192889
+ import { join as join12, resolve as resolve14 } from "node:path";
191743
192890
  var SAFE_TOKEN = /^[A-Za-z0-9._:@/+,-]+$/;
191744
192891
  var SAFE_REMOTE_ROOT = /^\/(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+\/?$/;
191745
192892
  var remoteDevToolSchema = {
@@ -191781,21 +192928,21 @@ function runProcess(executable, args, cwd) {
191781
192928
  function resolveDrizzleCommand(root, configured) {
191782
192929
  if (configured?.trim())
191783
192930
  return configured.trim();
191784
- const local = join10(root, "node_modules", ".bin", "drizzle-kit");
191785
- return existsSync11(local) ? local : "drizzle-kit";
192931
+ const local = join12(root, "node_modules", ".bin", "drizzle-kit");
192932
+ return existsSync12(local) ? local : "drizzle-kit";
191786
192933
  }
191787
192934
  function toolFailed(value) {
191788
192935
  return value?.isError === true || value?.content?.some((chunk) => typeof chunk?.text === "string" && chunk.text.trimStart().startsWith("❌"));
191789
192936
  }
191790
192937
  async function migrateDatabase(args, options) {
191791
- const root = resolve12(String(args.project_dir || options.cwd || process.cwd()));
192938
+ const root = resolve14(String(args.project_dir || options.cwd || process.cwd()));
191792
192939
  const projectConfig = await readProjectConfig3(root);
191793
192940
  const config = projectConfig.dev || {};
191794
192941
  const database = config.database || {};
191795
192942
  const execute = options.execute || ((command, commandArgs, cwd) => runProcess(command, commandArgs, cwd));
191796
- const drizzleConfig = resolve12(root, String(args.drizzle_config || database.drizzleConfig || "drizzle.config.ts"));
192943
+ const drizzleConfig = resolve14(root, String(args.drizzle_config || database.drizzleConfig || "drizzle.config.ts"));
191797
192944
  const migrationsDir = String(args.migrations_dir || database.migrationsDir || "supabase/migrations");
191798
- if (!existsSync11(drizzleConfig))
192945
+ if (!existsSync12(drizzleConfig))
191799
192946
  throw new Error(`Drizzle config not found: ${drizzleConfig}`);
191800
192947
  const generated = await execute(resolveDrizzleCommand(root, typeof args.drizzle_bin === "string" ? args.drizzle_bin : database.drizzleBin), ["generate", "--config", drizzleConfig], root);
191801
192948
  if (generated.exitCode !== 0)
@@ -191813,8 +192960,8 @@ async function migrateDatabase(args, options) {
191813
192960
  return { ok: true, mode: "dev", action: "migrate", generated: true, applied: true, migrations_dir: migrationsDir, result: applied };
191814
192961
  }
191815
192962
  async function readProjectConfig3(root) {
191816
- const file = join10(root, "supacloud.json");
191817
- if (!existsSync11(file))
192963
+ const file = join12(root, "supacloud.json");
192964
+ if (!existsSync12(file))
191818
192965
  return {};
191819
192966
  try {
191820
192967
  const parsed = JSON.parse(await readFile3(file, "utf8"));
@@ -191830,9 +192977,9 @@ async function readDevConfig(root) {
191830
192977
  async function sourceFingerprint(root) {
191831
192978
  const files = [];
191832
192979
  const visit = async (directory) => {
191833
- const entries = await readdir(directory, { withFileTypes: true });
192980
+ const entries = await readdir2(directory, { withFileTypes: true });
191834
192981
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
191835
- const path = join10(directory, entry.name);
192982
+ const path = join12(directory, entry.name);
191836
192983
  if (entry.isDirectory() && ![".git", "node_modules", "dist", "generated", ".supacloud"].includes(entry.name))
191837
192984
  await visit(path);
191838
192985
  else if (entry.isFile())
@@ -191840,7 +192987,7 @@ async function sourceFingerprint(root) {
191840
192987
  }
191841
192988
  };
191842
192989
  await visit(root);
191843
- const hash2 = createHash6("sha256");
192990
+ const hash2 = createHash7("sha256");
191844
192991
  for (const file of files) {
191845
192992
  hash2.update(file.slice(root.length).replace(/\\/g, "/"));
191846
192993
  hash2.update(await readFile3(file));
@@ -191860,17 +193007,17 @@ function remoteRoot(value) {
191860
193007
  }
191861
193008
  function targetDirectory(root, target, functionSlug, config = {}) {
191862
193009
  if (target === "db")
191863
- return join10(root, "supabase", "migrations");
193010
+ return join12(root, "supabase", "migrations");
191864
193011
  if (target === "functions") {
191865
193012
  const targets = config.targets && typeof config.targets === "object" ? config.targets : {};
191866
193013
  const match = Object.values(targets).find((entry) => entry?.type === "edge_function" && (!functionSlug || String(entry.slug || "") === functionSlug));
191867
- const base = match?.root ? resolve12(root, String(match.root)) : join10(root, "supabase", "functions");
191868
- return match?.root ? base : functionSlug ? join10(base, safeToken(functionSlug, "function")) : base;
193014
+ const base = match?.root ? resolve14(root, String(match.root)) : join12(root, "supabase", "functions");
193015
+ return match?.root ? base : functionSlug ? join12(base, safeToken(functionSlug, "function")) : base;
191869
193016
  }
191870
193017
  if (target === "frontend") {
191871
193018
  const targets = config.targets && typeof config.targets === "object" ? config.targets : {};
191872
193019
  const match = Object.values(targets).find((entry) => entry?.type === "frontend");
191873
- return match?.root ? resolve12(root, String(match.root)) : join10(root, "apps", "web");
193020
+ return match?.root ? resolve14(root, String(match.root)) : join12(root, "apps", "web");
191874
193021
  }
191875
193022
  return root;
191876
193023
  }
@@ -191909,10 +193056,10 @@ function reloadCommand(config, target, projectRef2, functionSlug) {
191909
193056
  return [...command.split(" "), "--project-ref", safeToken(projectRef2 || "test", "project_ref"), "--target", targetConfigPath(target), ...functionSlug ? ["--function", safeToken(functionSlug, "function")] : []];
191910
193057
  }
191911
193058
  function sshArgs(connection, remoteCommand) {
191912
- return ["-p", String(connection.port), "-i", resolve12(connection.key), "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", `${connection.user}@${connection.host}`, ...remoteCommand];
193059
+ return ["-p", String(connection.port), "-i", resolve14(connection.key), "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", `${connection.user}@${connection.host}`, ...remoteCommand];
191913
193060
  }
191914
193061
  function rsyncArgs(connection, source, destination, excludes, deleteRemote) {
191915
- const args = ["-az", "--checksum", "--partial", "--protect-args", "-e", `ssh -p ${connection.port} -i ${resolve12(connection.key)} -o BatchMode=yes -o StrictHostKeyChecking=yes`];
193062
+ const args = ["-az", "--checksum", "--partial", "--protect-args", "-e", `ssh -p ${connection.port} -i ${resolve14(connection.key)} -o BatchMode=yes -o StrictHostKeyChecking=yes`];
191916
193063
  if (deleteRemote)
191917
193064
  args.push("--delete-delay");
191918
193065
  for (const exclude of excludes) {
@@ -191924,17 +193071,17 @@ function rsyncArgs(connection, source, destination, excludes, deleteRemote) {
191924
193071
  return args;
191925
193072
  }
191926
193073
  async function syncOnce(args, options) {
191927
- const root = resolve12(String(args.project_dir || options.cwd || process.cwd()));
193074
+ const root = resolve14(String(args.project_dir || options.cwd || process.cwd()));
191928
193075
  const projectConfig = await readProjectConfig3(root);
191929
193076
  const config = projectConfig.dev || {};
191930
193077
  const target = String(args.target || "project");
191931
193078
  const source = targetDirectory(root, target, typeof args.function === "string" ? args.function : undefined, projectConfig);
191932
- if (!existsSync11(source))
193079
+ if (!existsSync12(source))
191933
193080
  throw new Error(`Dev source directory not found: ${source}`);
191934
193081
  let compiled = false;
191935
193082
  if (config.compile === true && target !== "db") {
191936
- const compileRoot = resolve12(root, config.compileRoot || ".");
191937
- const compileOutDir = resolve12(root, config.compileOutDir || "generated");
193083
+ const compileRoot = resolve14(root, config.compileRoot || ".");
193084
+ const compileOutDir = resolve14(root, config.compileOutDir || "generated");
191938
193085
  const compilation = await compileProject({
191939
193086
  rootDir: compileRoot,
191940
193087
  outDir: compileOutDir,
@@ -191951,9 +193098,9 @@ async function syncOnce(args, options) {
191951
193098
  const destination = remoteTargetRoot(remoteBase, target, slug);
191952
193099
  const connection = connectionArgs(options, config, args);
191953
193100
  const execute = options.execute || ((command, commandArgs, cwd) => runProcess(command, commandArgs, cwd));
191954
- const mkdir3 = await execute("ssh", sshArgs(connection, ["mkdir", "-p", destination]), root);
191955
- if (mkdir3.exitCode !== 0)
191956
- throw new Error(`Remote dev prepare failed: ${mkdir3.stderr.trim() || `exit ${mkdir3.exitCode}`}`);
193101
+ const mkdir4 = await execute("ssh", sshArgs(connection, ["mkdir", "-p", destination]), root);
193102
+ if (mkdir4.exitCode !== 0)
193103
+ throw new Error(`Remote dev prepare failed: ${mkdir4.stderr.trim() || `exit ${mkdir4.exitCode}`}`);
191957
193104
  const excludes = Array.isArray(config.excludes) ? config.excludes : ["node_modules", ".git", ".env*", "dist", ".supacloud"];
191958
193105
  const sync = await execute("rsync", rsyncArgs(connection, source, destination, excludes, args.delete === true), root);
191959
193106
  if (sync.exitCode !== 0)
@@ -191972,7 +193119,7 @@ function registerRemoteDevTools(server2, options = {}) {
191972
193119
  if (["production", "prod"].includes((options.environment || "").toLowerCase()))
191973
193120
  throw new Error("Remote dev mode is forbidden for production environments");
191974
193121
  if (args.action === "status") {
191975
- const root = resolve12(String(args.project_dir || options.cwd || process.cwd()));
193122
+ const root = resolve14(String(args.project_dir || options.cwd || process.cwd()));
191976
193123
  const config = await readDevConfig(root);
191977
193124
  const connection = connectionArgs(options, config, args);
191978
193125
  const execute = options.execute || ((command, commandArgs, cwd) => runProcess(command, commandArgs, cwd));
@@ -191986,7 +193133,7 @@ function registerRemoteDevTools(server2, options = {}) {
191986
193133
  return { content: [{ type: "text", text: JSON.stringify(await migrateDatabase(args, options), null, 2) }] };
191987
193134
  }
191988
193135
  if (args.action === "watch") {
191989
- const root = resolve12(String(args.project_dir || options.cwd || process.cwd()));
193136
+ const root = resolve14(String(args.project_dir || options.cwd || process.cwd()));
191990
193137
  const interval = Math.max(100, Math.min(1e4, Number(args.interval_ms || 300)));
191991
193138
  let fingerprint = "";
191992
193139
  let lastSync = null;
@@ -192005,9 +193152,9 @@ function registerRemoteDevTools(server2, options = {}) {
192005
193152
  });
192006
193153
  }
192007
193154
  // package.json
192008
- var package_default = {
193155
+ var package_default4 = {
192009
193156
  name: "@supacloud/cli",
192010
- version: "0.48.2",
193157
+ version: "0.49.0",
192011
193158
  description: "Project-scoped CLI for SupaCloud users",
192012
193159
  type: "module",
192013
193160
  main: "./dist/index.js",
@@ -192040,7 +193187,7 @@ var package_default = {
192040
193187
  },
192041
193188
  dependencies: {
192042
193189
  "@sinclair/typebox": "^0.34.52",
192043
- "@supacloud/compiler": "^0.9.0",
193190
+ "@supacloud/compiler": "^0.10.0",
192044
193191
  "@supacloud/db": "^0.2.0",
192045
193192
  fflate: "^0.8.3"
192046
193193
  },
@@ -192274,6 +193421,8 @@ EXAMPLES
192274
193421
  ${preferredCommand} release postgrest_restart --ref abc123
192275
193422
  ${preferredCommand} release release_canary_fixture_stage_replay --ref abc123 --subject <uuid> --request_id <uuid>
192276
193423
  ${preferredCommand} release release_canary_fixture_disable_replay --ref abc123 --fixture_id <uuid> --disable_request_id <uuid> --issuer <issuer-url> --subject <uuid>
193424
+ ${preferredCommand} release scope_rebind --file supacloud/fa/release-scopes/20260907-intake-p1-production.json
193425
+ ${preferredCommand} release scope_inspect --file supacloud/fa/release-scopes/20260907-intake-p1-production.json
192277
193426
  ${preferredCommand} queue stats --queue emails
192278
193427
  ${preferredCommand} queue dlq --queue emails --limit 20
192279
193428
  ${preferredCommand} frontend list --ref abc123
@@ -192294,6 +193443,7 @@ EXAMPLES
192294
193443
  ${preferredCommand} branch promote --branch_ref preview123 --plan_checksum <sha256>
192295
193444
  ${preferredCommand} ai show_skill
192296
193445
  ${preferredCommand} ai install_skill --dry_run
193446
+ ${preferredCommand} app init --name my-service
192297
193447
  ${preferredCommand} app generate --kind module --name billing
192298
193448
  ${preferredCommand} app generate --kind command --module billing --name issue-invoice
192299
193449
  ${preferredCommand} app compile --root .
@@ -192431,6 +193581,10 @@ function createCliTools(context, confirmProduction) {
192431
193581
  Object.assign(tools, captureTools((server2) => registerDatabaseTools(server2, undefined, {
192432
193582
  localOnly: true
192433
193583
  })));
193584
+ Object.assign(tools, captureTools((server2) => registerReleaseTools(server2, undefined, {
193585
+ localOnly: true,
193586
+ projectRef: context.projectRef || undefined
193587
+ })));
192434
193588
  Object.assign(tools, captureTools((server2) => registerRemoteDevTools(server2, {
192435
193589
  cwd: process.cwd(),
192436
193590
  host: process.env.SUPACLOUD_DEV_HOST || context.host,
@@ -192542,7 +193696,7 @@ function createCliTools(context, confirmProduction) {
192542
193696
  async function main() {
192543
193697
  const rawArgs = process.argv.slice(2);
192544
193698
  if (rawArgs.length === 1 && rawArgs[0] === "--version") {
192545
- console.log(package_default.version);
193699
+ console.log(package_default4.version);
192546
193700
  return;
192547
193701
  }
192548
193702
  const globalOptions = parseGlobalOptions(rawArgs);