@supacloud/cli 0.48.0 → 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/README.md +66 -0
- package/dist/index.js +1552 -206
- package/package.json +2 -2
- package/skills/supacloud-cli/references/command-map.md +4 -1
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
|
|
183703
|
-
import { dirname as
|
|
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);
|
|
@@ -183712,14 +183713,18 @@ import { createHash as createHash22 } from "node:crypto";
|
|
|
183712
183713
|
import { existsSync as existsSync8, readFileSync as readFileSync6 } from "node:fs";
|
|
183713
183714
|
import { dirname as dirname3, join as join6, resolve as resolve7 } from "node:path";
|
|
183714
183715
|
import { createHash as createHash4 } from "node:crypto";
|
|
183716
|
+
var ts4 = __toESM(require_typescript(), 1);
|
|
183717
|
+
var ts5 = __toESM(require_typescript(), 1);
|
|
183715
183718
|
import { createHash as createHash42 } from "node:crypto";
|
|
183716
|
-
import { access, mkdir, rename, unlink, writeFile } from "node:fs/promises";
|
|
183719
|
+
import { access, mkdir, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
|
|
183717
183720
|
import { join as join22 } from "node:path";
|
|
183718
|
-
|
|
183721
|
+
import { dirname as dirname32, relative as relative32, sep as sep32 } from "node:path";
|
|
183722
|
+
import { existsSync as existsSync32, readFileSync as readFileSync32 } from "node:fs";
|
|
183723
|
+
import { join as join42 } from "node:path";
|
|
183719
183724
|
import { existsSync as existsSync22, readFileSync as readFileSync22 } from "node:fs";
|
|
183720
|
-
import { dirname as
|
|
183725
|
+
import { dirname as dirname4, join as join32, relative as relative4, resolve as resolve32, sep as sep4 } from "node:path";
|
|
183721
183726
|
import { existsSync as existsSync52 } from "node:fs";
|
|
183722
|
-
import { join as join62, resolve as
|
|
183727
|
+
import { join as join62, resolve as resolve62 } from "node:path";
|
|
183723
183728
|
import { pathToFileURL } from "node:url";
|
|
183724
183729
|
|
|
183725
183730
|
class TraitCompiler {
|
|
@@ -183811,6 +183816,15 @@ function createDefaultTraitHandlers() {
|
|
|
183811
183816
|
return initializer && ts.isCallExpression(initializer) && expressionName(initializer.expression) === "defineModule" ? node.name.text : undefined;
|
|
183812
183817
|
}
|
|
183813
183818
|
},
|
|
183819
|
+
{
|
|
183820
|
+
kind: "defineFeatureSlice",
|
|
183821
|
+
detect: (node) => {
|
|
183822
|
+
if (!ts.isVariableDeclaration(node) || !ts.isIdentifier(node.name))
|
|
183823
|
+
return;
|
|
183824
|
+
const initializer = node.initializer;
|
|
183825
|
+
return initializer && ts.isCallExpression(initializer) && expressionName(initializer.expression) === "defineFeatureSlice" ? node.name.text : undefined;
|
|
183826
|
+
}
|
|
183827
|
+
},
|
|
183814
183828
|
{
|
|
183815
183829
|
kind: "injectionToken",
|
|
183816
183830
|
detect: (node) => {
|
|
@@ -184153,6 +184167,7 @@ async function analyzeProject(rootDir, include, cache, changedPaths) {
|
|
|
184153
184167
|
checker,
|
|
184154
184168
|
tokensByName: new Map,
|
|
184155
184169
|
classesByName: new Map,
|
|
184170
|
+
variablesByName: new Map,
|
|
184156
184171
|
diagnostics: []
|
|
184157
184172
|
};
|
|
184158
184173
|
const nativeTraitFiles = new Map;
|
|
@@ -184187,9 +184202,9 @@ async function analyzeProject(rootDir, include, cache, changedPaths) {
|
|
|
184187
184202
|
});
|
|
184188
184203
|
}
|
|
184189
184204
|
}
|
|
184190
|
-
if (!cache || traits?.has("defineModule")) {
|
|
184205
|
+
if (!cache || traits?.has("defineModule") || traits?.has("defineFeatureSlice")) {
|
|
184191
184206
|
for (const call of descendantsOfKind(sf, ts3.isCallExpression)) {
|
|
184192
|
-
if (nodeText(call.expression)
|
|
184207
|
+
if (!["defineModule", "defineFeatureSlice"].includes(nodeText(call.expression)))
|
|
184193
184208
|
continue;
|
|
184194
184209
|
const parent = call.parent;
|
|
184195
184210
|
if (!parent || !ts3.isVariableDeclaration(parent))
|
|
@@ -184495,6 +184510,9 @@ function indexFile(sf, ctx) {
|
|
|
184495
184510
|
}
|
|
184496
184511
|
for (const statement of sf.statements.filter(ts3.isVariableStatement)) {
|
|
184497
184512
|
for (const decl of statement.declarationList.declarations) {
|
|
184513
|
+
if (ts3.isIdentifier(decl.name) && !ctx.variablesByName.has(decl.name.text)) {
|
|
184514
|
+
ctx.variablesByName.set(decl.name.text, decl);
|
|
184515
|
+
}
|
|
184498
184516
|
const info = parseTokenVariable(decl, sf.fileName);
|
|
184499
184517
|
if (info && !ctx.tokensByName.has(info.name)) {
|
|
184500
184518
|
ctx.tokensByName.set(info.name, info);
|
|
@@ -184522,8 +184540,8 @@ function parseTokenVariable(decl, file) {
|
|
|
184522
184540
|
if (providedIn === "root") {
|
|
184523
184541
|
info.providedIn = "root";
|
|
184524
184542
|
}
|
|
184525
|
-
const
|
|
184526
|
-
if (
|
|
184543
|
+
const factory2 = getProp(optionsArg, "factory");
|
|
184544
|
+
if (factory2) {
|
|
184527
184545
|
info.hasFactory = true;
|
|
184528
184546
|
}
|
|
184529
184547
|
}
|
|
@@ -184532,6 +184550,7 @@ function parseTokenVariable(decl, file) {
|
|
|
184532
184550
|
function parseModule(candidate, nameByNode, ctx) {
|
|
184533
184551
|
const { options, className, file, line } = candidate;
|
|
184534
184552
|
const name = nameByNode.get(candidate.node) ?? className;
|
|
184553
|
+
const featureSpec = parseFeatureSpec(getProp(options, "spec"), ctx);
|
|
184535
184554
|
const tags = arrayProp(options, "tags").map((el) => ts3.isStringLiteral(el) ? el.text : nodeText(el).replace(/['"]/g, "")).filter(Boolean);
|
|
184536
184555
|
const aspects = parseAspectRefs(getProp(options, "aspects"), ctx, `module ${name}`);
|
|
184537
184556
|
const imports = arrayProp(options, "imports").map((el) => {
|
|
@@ -184706,8 +184725,71 @@ function parseModule(candidate, nameByNode, ctx) {
|
|
|
184706
184725
|
jobs,
|
|
184707
184726
|
queries,
|
|
184708
184727
|
...aspects.length > 0 ? { aspects } : {},
|
|
184709
|
-
exports
|
|
184728
|
+
exports,
|
|
184729
|
+
...featureSpec ? { featureSpec } : {}
|
|
184730
|
+
};
|
|
184731
|
+
}
|
|
184732
|
+
function parseFeatureSpec(input, ctx, seen = new Set) {
|
|
184733
|
+
if (!input)
|
|
184734
|
+
return;
|
|
184735
|
+
if (seen.has(input))
|
|
184736
|
+
return;
|
|
184737
|
+
seen.add(input);
|
|
184738
|
+
if (ts3.isIdentifier(input)) {
|
|
184739
|
+
const local = input.getSourceFile().statements.flatMap((statement) => ts3.isVariableStatement(statement) ? [...statement.declarationList.declarations] : []);
|
|
184740
|
+
const resolved = resolveDeclaration(input, ctx)[0];
|
|
184741
|
+
const decl = (resolved && ts3.isVariableDeclaration(resolved) ? resolved : undefined) ?? ctx.variablesByName.get(input.text) ?? local.find((candidate) => ts3.isIdentifier(candidate.name) && candidate.name.text === input.text) ?? descendantsOfKind(input.getSourceFile(), ts3.isVariableDeclaration).find((candidate) => ts3.isIdentifier(candidate.name) && candidate.name.text === input.text);
|
|
184742
|
+
if (decl && ts3.isVariableDeclaration(decl))
|
|
184743
|
+
return parseFeatureSpec(decl.initializer, ctx, seen);
|
|
184744
|
+
}
|
|
184745
|
+
if (ts3.isCallExpression(input) && nodeText(input.expression) === "defineFeatureSpec") {
|
|
184746
|
+
return parseFeatureSpec(input.arguments[0], ctx, seen);
|
|
184747
|
+
}
|
|
184748
|
+
if (ts3.isAsExpression(input) || ts3.isSatisfiesExpression(input) || ts3.isParenthesizedExpression(input)) {
|
|
184749
|
+
return parseFeatureSpec(input.expression, ctx, seen);
|
|
184750
|
+
}
|
|
184751
|
+
const invalid = () => {
|
|
184752
|
+
ctx.diagnostics.push({
|
|
184753
|
+
severity: "error",
|
|
184754
|
+
code: "invalid-feature-spec",
|
|
184755
|
+
message: "Feature spec must use static name, states and transition objects.",
|
|
184756
|
+
file: sourcePath(ctx.rootDir, input.getSourceFile().fileName),
|
|
184757
|
+
line: lineOf(input)
|
|
184758
|
+
});
|
|
184759
|
+
return;
|
|
184710
184760
|
};
|
|
184761
|
+
if (!ts3.isObjectLiteralExpression(input))
|
|
184762
|
+
return invalid();
|
|
184763
|
+
const name = stringLiteralProp(input, "name");
|
|
184764
|
+
const statesExpr = getProp(input, "states");
|
|
184765
|
+
const transitionObject = getProp(input, "transitions");
|
|
184766
|
+
if (!name || !statesExpr || !ts3.isArrayLiteralExpression(statesExpr) || statesExpr.elements.some((state) => !ts3.isStringLiteral(state)) || !transitionObject || !ts3.isObjectLiteralExpression(transitionObject) || input.properties.some((property) => !ts3.isPropertyAssignment(property))) {
|
|
184767
|
+
return invalid();
|
|
184768
|
+
}
|
|
184769
|
+
const states = statesExpr.elements.map((state) => state.text);
|
|
184770
|
+
const transitions = [];
|
|
184771
|
+
for (const property of transitionObject.properties) {
|
|
184772
|
+
if (!ts3.isPropertyAssignment(property) || ts3.isComputedPropertyName(property.name) || !ts3.isObjectLiteralExpression(property.initializer))
|
|
184773
|
+
return invalid();
|
|
184774
|
+
const options = property.initializer;
|
|
184775
|
+
const from = stringLiteralProp(options, "from");
|
|
184776
|
+
const to = stringLiteralProp(options, "to");
|
|
184777
|
+
if (!from || !to || options.properties.some((prop) => !ts3.isPropertyAssignment(prop)) || ["permission", "command", "route", "audit"].some((key) => getProp(options, key) && !stringLiteralProp(options, key)) || ["transaction", "idempotency"].some((key) => getProp(options, key) && !commandModeProp(options, key))) {
|
|
184778
|
+
return invalid();
|
|
184779
|
+
}
|
|
184780
|
+
transitions.push({
|
|
184781
|
+
name: propertyName(property.name),
|
|
184782
|
+
from,
|
|
184783
|
+
to,
|
|
184784
|
+
permission: stringLiteralProp(options, "permission"),
|
|
184785
|
+
command: stringLiteralProp(options, "command"),
|
|
184786
|
+
route: stringLiteralProp(options, "route"),
|
|
184787
|
+
transaction: commandModeProp(options, "transaction"),
|
|
184788
|
+
idempotency: commandModeProp(options, "idempotency"),
|
|
184789
|
+
audit: stringLiteralProp(options, "audit")
|
|
184790
|
+
});
|
|
184791
|
+
}
|
|
184792
|
+
return { name, states, transitions, file: sourcePath(ctx.rootDir, input.getSourceFile().fileName), line: lineOf(input) };
|
|
184711
184793
|
}
|
|
184712
184794
|
function commandModeProp(object, name) {
|
|
184713
184795
|
const value = stringLiteralProp(object, name);
|
|
@@ -185878,9 +185960,57 @@ function sourcePath(rootDir, absFile) {
|
|
|
185878
185960
|
function warn(ctx, code, message, file, line) {
|
|
185879
185961
|
ctx.diagnostics.push({ severity: "warn", code, message, file, line });
|
|
185880
185962
|
}
|
|
185963
|
+
function validateFeatureSpec(spec, module) {
|
|
185964
|
+
const diagnostics = [];
|
|
185965
|
+
const error = (code, message) => {
|
|
185966
|
+
diagnostics.push({ severity: "error", code, message, file: spec.file, line: spec.line });
|
|
185967
|
+
};
|
|
185968
|
+
if (!spec.name.trim() || spec.states.length === 0 || spec.states.some((state) => !state.trim()) || new Set(spec.states).size !== spec.states.length) {
|
|
185969
|
+
error("invalid-feature-states", "Feature name and states must be non-empty; states must be unique.");
|
|
185970
|
+
}
|
|
185971
|
+
const names = new Set;
|
|
185972
|
+
for (const transition of spec.transitions) {
|
|
185973
|
+
if (!transition.name.trim() || names.has(transition.name)) {
|
|
185974
|
+
error("duplicate-feature-transition", `Feature ${spec.name} has duplicate/empty transition '${transition.name}'.`);
|
|
185975
|
+
}
|
|
185976
|
+
names.add(transition.name);
|
|
185977
|
+
if (!spec.states.includes(transition.from) || !spec.states.includes(transition.to)) {
|
|
185978
|
+
error("invalid-feature-transition", `Transition ${transition.name} references an undeclared state.`);
|
|
185979
|
+
}
|
|
185980
|
+
if (transition.permission !== undefined && !transition.permission.trim()) {
|
|
185981
|
+
error("feature-governance-drift", `Transition ${transition.name} declares an empty permission.`);
|
|
185982
|
+
}
|
|
185983
|
+
if (!module)
|
|
185984
|
+
continue;
|
|
185985
|
+
const commands = module.commands.filter((command2) => command2.className === transition.command || command2.name === transition.command);
|
|
185986
|
+
const command = commands[0];
|
|
185987
|
+
if (transition.command && commands.length !== 1) {
|
|
185988
|
+
error("feature-command-unresolved", `Transition ${transition.name} must reference exactly one command in module ${module.name}.`);
|
|
185989
|
+
}
|
|
185990
|
+
if (!transition.command && [transition.permission, transition.transaction, transition.idempotency, transition.audit].some((value) => value !== undefined)) {
|
|
185991
|
+
error("feature-command-unresolved", `Transition ${transition.name} declares governance without a command binding.`);
|
|
185992
|
+
}
|
|
185993
|
+
if (command) {
|
|
185994
|
+
for (const key of ["permission", "transaction", "idempotency", "audit"]) {
|
|
185995
|
+
if (transition[key] !== undefined && transition[key] !== command[key]) {
|
|
185996
|
+
error("feature-governance-drift", `Transition ${transition.name} ${key} differs from command ${command.className}.`);
|
|
185997
|
+
}
|
|
185998
|
+
}
|
|
185999
|
+
}
|
|
186000
|
+
if (transition.route) {
|
|
186001
|
+
const routes = module.controllers.flatMap((controller) => controller.routes.filter((route) => `${route.method} ${joinRoutePaths(controller.path, route.path)}` === transition.route));
|
|
186002
|
+
if (routes.length !== 1) {
|
|
186003
|
+
error("feature-route-unresolved", `Transition ${transition.name} must reference exactly one route '${transition.route}' in module ${module.name}.`);
|
|
186004
|
+
} else if (command && routes[0].command !== command.className) {
|
|
186005
|
+
error("feature-route-drift", `Route ${transition.route} is not bound to ${command.className}.`);
|
|
186006
|
+
}
|
|
186007
|
+
}
|
|
186008
|
+
}
|
|
186009
|
+
return diagnostics;
|
|
186010
|
+
}
|
|
185881
186011
|
var HEADER = "// GENERATED BY @supacloud/compiler — do not edit";
|
|
185882
186012
|
var INTERFACES = `export interface CompiledRoute {
|
|
185883
|
-
method:
|
|
186013
|
+
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
|
|
185884
186014
|
path: string;
|
|
185885
186015
|
handler: string;
|
|
185886
186016
|
body?: unknown;
|
|
@@ -185951,7 +186081,7 @@ export type CompiledAspect = (
|
|
|
185951
186081
|
export interface CompiledController {
|
|
185952
186082
|
path: string;
|
|
185953
186083
|
serviceKey: string;
|
|
185954
|
-
scope:
|
|
186084
|
+
scope: "application" | "request" | "job";
|
|
185955
186085
|
routes: CompiledRoute[];
|
|
185956
186086
|
}
|
|
185957
186087
|
|
|
@@ -186177,10 +186307,10 @@ async function writeFileIfChanged(path, content, hashes) {
|
|
|
186177
186307
|
async function writeFileAtomic(path, content) {
|
|
186178
186308
|
const temporaryPath = `${path}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
|
|
186179
186309
|
try {
|
|
186180
|
-
await
|
|
186181
|
-
await
|
|
186310
|
+
await writeFile2(temporaryPath, content, "utf8");
|
|
186311
|
+
await rename2(temporaryPath, path);
|
|
186182
186312
|
} catch (error) {
|
|
186183
|
-
await
|
|
186313
|
+
await unlink2(temporaryPath).catch(() => {
|
|
186184
186314
|
return;
|
|
186185
186315
|
});
|
|
186186
186316
|
throw error;
|
|
@@ -186565,7 +186695,7 @@ ${indent(item, 2)}`).join(",")}
|
|
|
186565
186695
|
switch (provider.kind) {
|
|
186566
186696
|
case "class": {
|
|
186567
186697
|
const useClass = this.imports.add(provider.useClass ?? provider.token, provider.importPath, provider.importModule);
|
|
186568
|
-
const args = provider.deps.map((dep) => this.
|
|
186698
|
+
const args = provider.deps.map((dep, index) => this.typedDepExpr(dep, kind, this.depOptions(provider, dep), `ConstructorParameters<typeof ${useClass}>[${index}]`)).join(", ");
|
|
186569
186699
|
const local = this.localVar(isMulti ? provider.useClass ?? `${provider.token}Item` : provider.token, kind);
|
|
186570
186700
|
return {
|
|
186571
186701
|
constLine: `const ${local} = ${this.instantiate(useClass, args, kind, provider.functionalInjects)};`,
|
|
@@ -186585,10 +186715,10 @@ ${indent(item, 2)}`).join(",")}
|
|
|
186585
186715
|
const constLine = `const ${local2} = resolveFactoryValue(${tokenIdent});`;
|
|
186586
186716
|
return { constLine, key, expr: local2 };
|
|
186587
186717
|
}
|
|
186588
|
-
const
|
|
186589
|
-
const args = provider.deps.map((dep) => this.
|
|
186718
|
+
const factory2 = this.imports.add(provider.useFactoryName ?? "", provider.importPath, provider.importModule);
|
|
186719
|
+
const args = provider.deps.map((dep, index) => this.typedDepExpr(dep, kind, this.depOptions(provider, dep), `Parameters<typeof ${factory2}>[${index}]`)).join(", ");
|
|
186590
186720
|
const local = this.localVar(isMulti ? provider.useFactoryName ?? `${provider.token}Item` : provider.token, kind);
|
|
186591
|
-
return { constLine: `const ${local} = ${
|
|
186721
|
+
return { constLine: `const ${local} = ${factory2}(${args});`, key, expr: local };
|
|
186592
186722
|
}
|
|
186593
186723
|
case "existing": {
|
|
186594
186724
|
return {
|
|
@@ -186600,7 +186730,7 @@ ${indent(item, 2)}`).join(",")}
|
|
|
186600
186730
|
}
|
|
186601
186731
|
emitController(controller, kind) {
|
|
186602
186732
|
const className = this.imports.add(controller.className, controller.importPath);
|
|
186603
|
-
const args = controller.deps.map((dep) => this.
|
|
186733
|
+
const args = controller.deps.map((dep, index) => this.typedDepExpr(dep, kind, this.depOptions(controller, dep), `ConstructorParameters<typeof ${className}>[${index}]`)).join(", ");
|
|
186604
186734
|
const key = camelName(controller.className);
|
|
186605
186735
|
const local = this.localVar(controller.className, kind);
|
|
186606
186736
|
return {
|
|
@@ -186658,6 +186788,13 @@ ${indent(item, 2)}`).join(",")}
|
|
|
186658
186788
|
host: "hostDeps" in node ? node.hostDeps?.includes(token) ?? false : false
|
|
186659
186789
|
};
|
|
186660
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
|
+
}
|
|
186661
186798
|
depExpr(token, kind, options = {}) {
|
|
186662
186799
|
const isOptional = options.optional ?? false;
|
|
186663
186800
|
const isSelf = options.self ?? false;
|
|
@@ -187165,6 +187302,7 @@ var COMPILER_DIAGNOSTIC_CODES = {
|
|
|
187165
187302
|
"invalid-http-method-body": { code: "SC3004", docsUrl: "https://supacloud.dev/errors/SC3004" },
|
|
187166
187303
|
"unmatched-route-parameter": { code: "SC3005", docsUrl: "https://supacloud.dev/errors/SC3005" },
|
|
187167
187304
|
"missing-route-parameter-binding": { code: "SC3006", docsUrl: "https://supacloud.dev/errors/SC3006" },
|
|
187305
|
+
"missing-path-param": { code: "SC3006", docsUrl: "https://supacloud.dev/errors/SC3006" },
|
|
187168
187306
|
"duplicate-route": { code: "SC3007", docsUrl: "https://supacloud.dev/errors/SC3007" },
|
|
187169
187307
|
"missing-body-schema": { code: "SC3008", docsUrl: "https://supacloud.dev/errors/SC3008" },
|
|
187170
187308
|
"unused-route-schema": { code: "SC3009", docsUrl: "https://supacloud.dev/errors/SC3009" },
|
|
@@ -187175,6 +187313,7 @@ var COMPILER_DIAGNOSTIC_CODES = {
|
|
|
187175
187313
|
"unmatched-path-param-decorator": { code: "SC3014", docsUrl: "https://supacloud.dev/errors/SC3014" },
|
|
187176
187314
|
"invalid-query-default-type": { code: "SC3015", docsUrl: "https://supacloud.dev/errors/SC3015" },
|
|
187177
187315
|
"disallowed-body-on-get-delete": { code: "SC3016", docsUrl: "https://supacloud.dev/errors/SC3016" },
|
|
187316
|
+
"invalid-body-binding": { code: "SC3016", docsUrl: "https://supacloud.dev/errors/SC3016" },
|
|
187178
187317
|
"duplicate-query-param-binding": { code: "SC3017", docsUrl: "https://supacloud.dev/errors/SC3017" },
|
|
187179
187318
|
"conflicting-route-method": { code: "SC3018", docsUrl: "https://supacloud.dev/errors/SC3018" },
|
|
187180
187319
|
"missing-param-colon": { code: "SC3019", docsUrl: "https://supacloud.dev/errors/SC3019" },
|
|
@@ -187190,7 +187329,15 @@ var COMPILER_DIAGNOSTIC_CODES = {
|
|
|
187190
187329
|
"invalid-job-scope": { code: "SC4007", docsUrl: "https://supacloud.dev/errors/SC4007" },
|
|
187191
187330
|
"dynamic-aspect-reference": { code: "SC4010", docsUrl: "https://supacloud.dev/errors/SC4010" },
|
|
187192
187331
|
"invalid-aspect-reference": { code: "SC4011", docsUrl: "https://supacloud.dev/errors/SC4011" },
|
|
187193
|
-
"unused-root-provider": { code: "SC5001", docsUrl: "https://supacloud.dev/errors/SC5001" }
|
|
187332
|
+
"unused-root-provider": { code: "SC5001", docsUrl: "https://supacloud.dev/errors/SC5001" },
|
|
187333
|
+
"invalid-feature-states": { code: "SC6001", docsUrl: "https://supacloud.dev/errors/SC6001" },
|
|
187334
|
+
"duplicate-feature-transition": { code: "SC6002", docsUrl: "https://supacloud.dev/errors/SC6002" },
|
|
187335
|
+
"invalid-feature-transition": { code: "SC6003", docsUrl: "https://supacloud.dev/errors/SC6003" },
|
|
187336
|
+
"feature-command-unresolved": { code: "SC6004", docsUrl: "https://supacloud.dev/errors/SC6004" },
|
|
187337
|
+
"feature-governance-drift": { code: "SC6005", docsUrl: "https://supacloud.dev/errors/SC6005" },
|
|
187338
|
+
"feature-route-unresolved": { code: "SC6006", docsUrl: "https://supacloud.dev/errors/SC6006" },
|
|
187339
|
+
"feature-route-drift": { code: "SC6007", docsUrl: "https://supacloud.dev/errors/SC6007" },
|
|
187340
|
+
"invalid-feature-spec": { code: "SC6008", docsUrl: "https://supacloud.dev/errors/SC6008" }
|
|
187194
187341
|
};
|
|
187195
187342
|
function validateGraph(graph, options = false) {
|
|
187196
187343
|
const strict = typeof options === "boolean" ? options : options.strict ?? false;
|
|
@@ -187246,7 +187393,7 @@ function validateGraph(graph, options = false) {
|
|
|
187246
187393
|
}
|
|
187247
187394
|
return;
|
|
187248
187395
|
}
|
|
187249
|
-
const error = (code, message, file, line, suggestion) => {
|
|
187396
|
+
const error = (code, message, file, line, suggestion, fix) => {
|
|
187250
187397
|
const meta = COMPILER_DIAGNOSTIC_CODES[code];
|
|
187251
187398
|
diagnostics.push({
|
|
187252
187399
|
severity: "error",
|
|
@@ -187256,10 +187403,11 @@ function validateGraph(graph, options = false) {
|
|
|
187256
187403
|
line,
|
|
187257
187404
|
suggestion,
|
|
187258
187405
|
errorCode: meta?.code,
|
|
187259
|
-
docsUrl: meta?.docsUrl
|
|
187406
|
+
docsUrl: meta?.docsUrl,
|
|
187407
|
+
fix
|
|
187260
187408
|
});
|
|
187261
187409
|
};
|
|
187262
|
-
const warn2 = (code, message, file, line, suggestion) => {
|
|
187410
|
+
const warn2 = (code, message, file, line, suggestion, fix) => {
|
|
187263
187411
|
const meta = COMPILER_DIAGNOSTIC_CODES[code];
|
|
187264
187412
|
diagnostics.push({
|
|
187265
187413
|
severity: strict ? "error" : "warn",
|
|
@@ -187269,7 +187417,8 @@ function validateGraph(graph, options = false) {
|
|
|
187269
187417
|
line,
|
|
187270
187418
|
suggestion,
|
|
187271
187419
|
errorCode: meta?.code,
|
|
187272
|
-
docsUrl: meta?.docsUrl
|
|
187420
|
+
docsUrl: meta?.docsUrl,
|
|
187421
|
+
fix
|
|
187273
187422
|
});
|
|
187274
187423
|
};
|
|
187275
187424
|
const modulesByName = new Map;
|
|
@@ -187277,6 +187426,12 @@ function validateGraph(graph, options = false) {
|
|
|
187277
187426
|
const routesByKey = new Map;
|
|
187278
187427
|
const declaredRoutes = [];
|
|
187279
187428
|
for (const module of graph.modules) {
|
|
187429
|
+
if (module.featureSpec) {
|
|
187430
|
+
for (const diagnostic of validateFeatureSpec(module.featureSpec, module)) {
|
|
187431
|
+
const meta = COMPILER_DIAGNOSTIC_CODES[diagnostic.code];
|
|
187432
|
+
diagnostics.push({ ...diagnostic, errorCode: meta?.code, docsUrl: meta?.docsUrl });
|
|
187433
|
+
}
|
|
187434
|
+
}
|
|
187280
187435
|
const previousModule = modulesByName.get(module.name);
|
|
187281
187436
|
if (previousModule) {
|
|
187282
187437
|
error("duplicate-module", `模块名 ${module.name} 重复(首次声明于 ${previousModule.file}:${previousModule.line})`, module.file, module.line);
|
|
@@ -187369,7 +187524,14 @@ function validateGraph(graph, options = false) {
|
|
|
187369
187524
|
if (paramBindings.length > 0) {
|
|
187370
187525
|
for (const param of pathParams) {
|
|
187371
187526
|
if (!paramBindings.includes(param)) {
|
|
187372
|
-
warn2("missing-path-param", `Route path '${route.path}' defines parameter ':${param}', but handler ${controller.className}.${route.handler} does not bind it with @Param('${param}').`, controller.file, undefined, `Add @Param('${param}') to ${route.handler} arguments
|
|
187527
|
+
warn2("missing-path-param", `Route path '${route.path}' defines parameter ':${param}', but handler ${controller.className}.${route.handler} does not bind it with @Param('${param}').`, controller.file, undefined, `Add @Param('${param}') to ${route.handler} arguments.`, {
|
|
187528
|
+
type: "add_route_parameter_binding",
|
|
187529
|
+
targetFile: controller.file,
|
|
187530
|
+
controller: controller.className,
|
|
187531
|
+
route: route.handler,
|
|
187532
|
+
parameter: param,
|
|
187533
|
+
binding: "param"
|
|
187534
|
+
});
|
|
187373
187535
|
}
|
|
187374
187536
|
}
|
|
187375
187537
|
}
|
|
@@ -187396,10 +187558,20 @@ function validateGraph(graph, options = false) {
|
|
|
187396
187558
|
}
|
|
187397
187559
|
}
|
|
187398
187560
|
if ((route.method === "GET" || route.method === "HEAD" || route.method === "OPTIONS" || route.method === "DELETE") && (route.hasBodyBinding || route.body)) {
|
|
187399
|
-
error("disallowed-body-on-get-delete", `Route handler ${controller.className}.${route.handler} binds @Body() or declares body schema on HTTP ${route.method} route '${route.path}'. Request bodies are not supported on ${route.method} requests.`, controller.file, undefined, `Use POST, PUT, or PATCH for routes accepting a request body, or bind parameters via @Query() / @Param()
|
|
187561
|
+
error("disallowed-body-on-get-delete", `Route handler ${controller.className}.${route.handler} binds @Body() or declares body schema on HTTP ${route.method} route '${route.path}'. Request bodies are not supported on ${route.method} requests.`, controller.file, undefined, `Use POST, PUT, or PATCH for routes accepting a request body, or bind parameters via @Query() / @Param().`, {
|
|
187562
|
+
type: "remove_route_body_binding",
|
|
187563
|
+
targetFile: controller.file,
|
|
187564
|
+
controller: controller.className,
|
|
187565
|
+
route: route.handler
|
|
187566
|
+
});
|
|
187400
187567
|
}
|
|
187401
187568
|
if (route.hasBodyBinding && (route.method === "GET" || route.method === "HEAD" || route.method === "OPTIONS")) {
|
|
187402
|
-
error("invalid-body-binding", `Route handler ${controller.className}.${route.handler} binds @Body() on HTTP ${route.method} route '${route.path}'. Request bodies are not supported on ${route.method} requests.`, controller.file, undefined, `Use POST, PUT, or PATCH for routes accepting a request body, or bind parameters via @Query() / @Param()
|
|
187569
|
+
error("invalid-body-binding", `Route handler ${controller.className}.${route.handler} binds @Body() on HTTP ${route.method} route '${route.path}'. Request bodies are not supported on ${route.method} requests.`, controller.file, undefined, `Use POST, PUT, or PATCH for routes accepting a request body, or bind parameters via @Query() / @Param().`, {
|
|
187570
|
+
type: "remove_route_body_binding",
|
|
187571
|
+
targetFile: controller.file,
|
|
187572
|
+
controller: controller.className,
|
|
187573
|
+
route: route.handler
|
|
187574
|
+
});
|
|
187403
187575
|
} else if (route.hasBodyBinding && !route.body) {
|
|
187404
187576
|
warn2("missing-body-schema", `Route handler ${controller.className}.${route.handler} binds @Body() on route '${route.path}', but route definition does not specify a body validation schema.`, controller.file, undefined, `Add schema to route options (e.g. body: Schema) for compile-time and runtime validation.`);
|
|
187405
187577
|
} else if (route.body && !route.hasBodyBinding && !route.command) {
|
|
@@ -187540,23 +187712,51 @@ function validateGraph(graph, options = false) {
|
|
|
187540
187712
|
const owner = globalProviders.get(dep);
|
|
187541
187713
|
if (!owner)
|
|
187542
187714
|
continue;
|
|
187543
|
-
error("module-boundary", `模块 ${module.name} 的 provider ${provider.token} 依赖 ${dep},该 token 由模块 ${owner.module.name} 提供但未被 import`, provider.file, provider.line, `Import module '${owner.module.name}' in '${module.name}', add '${dep}' to '${owner.module.name}' exports, or mark @Injectable({ providedIn: 'root' })
|
|
187715
|
+
error("module-boundary", `模块 ${module.name} 的 provider ${provider.token} 依赖 ${dep},该 token 由模块 ${owner.module.name} 提供但未被 import`, provider.file, provider.line, `Import module '${owner.module.name}' in '${module.name}', add '${dep}' to '${owner.module.name}' exports, or mark @Injectable({ providedIn: 'root' }).`, {
|
|
187716
|
+
type: "add_module_import",
|
|
187717
|
+
targetFile: module.file,
|
|
187718
|
+
module: owner.module.name,
|
|
187719
|
+
provider: dep,
|
|
187720
|
+
symbol: owner.module.className,
|
|
187721
|
+
targetModule: module.name,
|
|
187722
|
+
importPath: (() => {
|
|
187723
|
+
const value = relative32(dirname32(module.file), owner.module.file).replace(/\.(tsx?|mts|cts)$/, "").split(sep32).join("/");
|
|
187724
|
+
return value.startsWith(".") ? value : `./${value}`;
|
|
187725
|
+
})()
|
|
187726
|
+
});
|
|
187544
187727
|
} else if (dep.includes("TOKEN") || dep.endsWith("Token") || dep.length > 2 && dep === dep.toUpperCase()) {
|
|
187545
187728
|
error("missing-token-factory", `InjectionToken '${dep}' referenced by provider '${provider.token}' has no provider in module '${module.name}' and no default factory function.`, provider.file, provider.line, `Provide '${dep}' in @Module({ providers: [...] }) or declare it with new InjectionToken('${dep}', { factory: () => ... }).`);
|
|
187546
187729
|
} else {
|
|
187547
|
-
error("unresolved-token", `模块 ${module.name} 的 provider ${provider.token} 依赖的 token ${dep} 无法解析`, provider.file, provider.line, `Provide '${dep}' in a module, mark constructor parameter @Optional(), or define @Injectable({ providedIn: 'root' })
|
|
187730
|
+
error("unresolved-token", `模块 ${module.name} 的 provider ${provider.token} 依赖的 token ${dep} 无法解析`, provider.file, provider.line, `Provide '${dep}' in a module, mark constructor parameter @Optional(), or define @Injectable({ providedIn: 'root' }).`, {
|
|
187731
|
+
type: "add_provider",
|
|
187732
|
+
targetFile: module.file,
|
|
187733
|
+
token: dep,
|
|
187734
|
+
module: module.name
|
|
187735
|
+
});
|
|
187548
187736
|
}
|
|
187549
187737
|
}
|
|
187550
187738
|
continue;
|
|
187551
187739
|
}
|
|
187552
187740
|
if (SCOPE_LIFETIME_RANK[resolved.provider.scope] > SCOPE_LIFETIME_RANK[provider.scope]) {
|
|
187553
|
-
error("scope-violation", `模块 ${module.name} 的 ${provider.scope} provider ${provider.token} 不能依赖 ${resolved.provider.scope} provider ${dep}`, provider.file, provider.line, `Change provider '${provider.token}' scope to '${resolved.provider.scope}', or inject a factory/context instead
|
|
187741
|
+
error("scope-violation", `模块 ${module.name} 的 ${provider.scope} provider ${provider.token} 不能依赖 ${resolved.provider.scope} provider ${dep}`, provider.file, provider.line, `Change provider '${provider.token}' scope to '${resolved.provider.scope}', or inject a factory/context instead.`, {
|
|
187742
|
+
type: "change_provider_scope",
|
|
187743
|
+
targetFile: provider.file,
|
|
187744
|
+
provider: provider.token,
|
|
187745
|
+
from: provider.scope,
|
|
187746
|
+
to: resolved.provider.scope
|
|
187747
|
+
});
|
|
187554
187748
|
}
|
|
187555
187749
|
}
|
|
187556
187750
|
}
|
|
187557
187751
|
for (const command of module.commands) {
|
|
187558
187752
|
if (!command.permission) {
|
|
187559
|
-
error("command-missing-permission", `模块 ${module.name} 的 command ${command.name} (${command.className}) 未声明 permission`, module.file, module.line, "Add 'permission: string' to @Command({ ... }) or configure command execution capabilities permission=false."
|
|
187753
|
+
error("command-missing-permission", `模块 ${module.name} 的 command ${command.name} (${command.className}) 未声明 permission`, module.file, module.line, "Add 'permission: string' to @Command({ ... }) or configure command execution capabilities permission=false.", {
|
|
187754
|
+
type: "add_command_permission",
|
|
187755
|
+
targetFile: module.providers.find((provider) => provider.useClass === command.className || provider.token === command.className)?.file ?? module.file,
|
|
187756
|
+
command: command.className,
|
|
187757
|
+
module: module.name,
|
|
187758
|
+
permission: `${module.name}.${command.name}`
|
|
187759
|
+
});
|
|
187560
187760
|
}
|
|
187561
187761
|
if (typeof options === "object" && options.commandCapabilities) {
|
|
187562
187762
|
const caps = options.commandCapabilities;
|
|
@@ -187926,7 +188126,7 @@ function scanGeneratedArtifacts(artifacts, strict = true) {
|
|
|
187926
188126
|
for (const [file, content] of Object.entries(artifacts)) {
|
|
187927
188127
|
if (content === undefined)
|
|
187928
188128
|
continue;
|
|
187929
|
-
const sourceFile =
|
|
188129
|
+
const sourceFile = ts5.createSourceFile(file, content, ts5.ScriptTarget.Latest, true, ts5.ScriptKind.TS);
|
|
187930
188130
|
for (const node of descendantsOfKind2(sourceFile, isAnyKeyword)) {
|
|
187931
188131
|
diagnostics.push(makeDiagnostic("generated-any", `生成产物 ${file} 包含 any;严格生成模式要求使用 unknown、具体接口或泛型约束。`, sourceFile, node, strict));
|
|
187932
188132
|
}
|
|
@@ -187934,30 +188134,30 @@ function scanGeneratedArtifacts(artifacts, strict = true) {
|
|
|
187934
188134
|
return diagnostics;
|
|
187935
188135
|
}
|
|
187936
188136
|
function scanProductionSource(options) {
|
|
187937
|
-
const rootDir =
|
|
188137
|
+
const rootDir = resolve32(options.rootDir);
|
|
187938
188138
|
const configPath = join32(rootDir, "tsconfig.json");
|
|
187939
188139
|
const projectConfig = existsSync22(configPath) ? readProjectConfig2(configPath) : {
|
|
187940
188140
|
options: {
|
|
187941
188141
|
strict: true,
|
|
187942
188142
|
skipLibCheck: true,
|
|
187943
|
-
target:
|
|
187944
|
-
module:
|
|
188143
|
+
target: ts5.ScriptTarget.ES2022,
|
|
188144
|
+
module: ts5.ModuleKind.ESNext
|
|
187945
188145
|
},
|
|
187946
188146
|
errors: []
|
|
187947
188147
|
};
|
|
187948
188148
|
const include = options.include ?? ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"];
|
|
187949
|
-
const rootNames =
|
|
188149
|
+
const rootNames = ts5.sys.readDirectory(rootDir, [".ts", ".tsx", ".mts", ".cts"], ["node_modules", "dist"], include).filter((file) => isProductionSourcePath(rootDir, file, [...DEFAULT_EXCLUDES, ...options.exclude ?? []]));
|
|
187950
188150
|
const compilerOptions = { ...projectConfig.options, noEmit: true };
|
|
187951
|
-
const host =
|
|
188151
|
+
const host = ts5.createCompilerHost(compilerOptions);
|
|
187952
188152
|
host.getCurrentDirectory = () => rootDir;
|
|
187953
|
-
const program =
|
|
188153
|
+
const program = ts5.createProgram(rootNames, compilerOptions, host);
|
|
187954
188154
|
const outDir = options.outDir ? normalizeRelative(rootDir, options.outDir) : undefined;
|
|
187955
188155
|
const excludes = [...DEFAULT_EXCLUDES, ...options.exclude ?? []];
|
|
187956
188156
|
const sourceFiles = program.getSourceFiles().filter((sourceFile) => isProductionSource(rootDir, sourceFile, excludes, outDir));
|
|
187957
188157
|
const diagnostics = [...projectConfig.errors, ...program.getOptionsDiagnostics()].map((diagnostic) => ({
|
|
187958
188158
|
severity: "error",
|
|
187959
188159
|
code: "source-config",
|
|
187960
|
-
message:
|
|
188160
|
+
message: ts5.flattenDiagnosticMessageText(diagnostic.messageText, `
|
|
187961
188161
|
`),
|
|
187962
188162
|
file: diagnostic.file ? normalizeRelative(rootDir, diagnostic.file.fileName) : normalizeRelative(rootDir, configPath),
|
|
187963
188163
|
line: diagnostic.file && diagnostic.start !== undefined ? diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start).line + 1 : undefined,
|
|
@@ -187974,22 +188174,22 @@ function scanSourceFile(sourceFile, checker, rootDir, diagnostics, strict) {
|
|
|
187974
188174
|
diagnostics.push(makeDiagnostic("source-any", "生产源码使用了显式 any;请改用 unknown、具体接口或泛型约束。", sourceFile, node, strict, rootDir));
|
|
187975
188175
|
}
|
|
187976
188176
|
for (const node of descendants(sourceFile)) {
|
|
187977
|
-
if (
|
|
187978
|
-
if (
|
|
188177
|
+
if (ts5.isAsExpression(node)) {
|
|
188178
|
+
if (ts5.isAsExpression(node.parent) || ts5.isTypeAssertionExpression(node.parent))
|
|
187979
188179
|
continue;
|
|
187980
188180
|
const assertedType = node.type.getText(sourceFile);
|
|
187981
188181
|
if (assertedType === "const")
|
|
187982
188182
|
continue;
|
|
187983
188183
|
diagnostics.push(makeDiagnostic("source-type-assertion", `生产源码包含类型断言 ${node.getText(sourceFile)};请优先使用类型守卫、satisfies 或显式边界解析。`, sourceFile, node, strict, rootDir));
|
|
187984
|
-
} else if (
|
|
187985
|
-
if (
|
|
188184
|
+
} else if (ts5.isTypeAssertionExpression(node)) {
|
|
188185
|
+
if (ts5.isAsExpression(node.parent) || ts5.isTypeAssertionExpression(node.parent))
|
|
187986
188186
|
continue;
|
|
187987
188187
|
diagnostics.push(makeDiagnostic("source-type-assertion", `生产源码包含类型断言 ${node.getText(sourceFile)};请优先使用类型守卫、satisfies 或显式边界解析。`, sourceFile, node, strict, rootDir));
|
|
187988
|
-
} else if (
|
|
188188
|
+
} else if (ts5.isNonNullExpression(node)) {
|
|
187989
188189
|
diagnostics.push(makeDiagnostic("source-non-null-assertion", `生产源码包含非空断言 ${node.getText(sourceFile)};请显式处理 null/undefined。`, sourceFile, node, strict, rootDir));
|
|
187990
188190
|
}
|
|
187991
188191
|
}
|
|
187992
|
-
for (const declaration of descendantsOfKind2(sourceFile,
|
|
188192
|
+
for (const declaration of descendantsOfKind2(sourceFile, ts5.isVariableDeclaration)) {
|
|
187993
188193
|
const initializer = declaration.initializer;
|
|
187994
188194
|
if (!initializer || declaration.type)
|
|
187995
188195
|
continue;
|
|
@@ -188005,11 +188205,11 @@ function scanSourceFile(sourceFile, checker, rootDir, diagnostics, strict) {
|
|
|
188005
188205
|
if (isLetDeclaration(declaration) && isLiteralSyntax(initializer) && !isLiteralType(declarationType)) {
|
|
188006
188206
|
diagnostics.push(makeDiagnostic("source-implicit-widening", `变量 ${declaration.name.getText(sourceFile)} 的字面量类型从 ${checker.typeToString(initializerType, initializer)} 隐式宽化为 ${checker.typeToString(declarationType, declaration)};请补充类型或使用 const。`, sourceFile, declaration, strict, rootDir));
|
|
188007
188207
|
}
|
|
188008
|
-
if (
|
|
188208
|
+
if (ts5.isObjectLiteralExpression(initializer) && isConstDeclaration(declaration) && initializer.getText(sourceFile).length > 0 && initializer.properties.some((property2) => ts5.isPropertyAssignment(property2) && property2.initializer !== undefined && !ts5.isAsExpression(property2.initializer) && isLiteralExpression(property2.initializer))) {
|
|
188009
188209
|
diagnostics.push(makeDiagnostic("source-implicit-widening", `常量对象 ${declaration.name.getText(sourceFile)} 的字面量属性会隐式宽化;请补充对象类型或使用 as const。`, sourceFile, declaration, strict, rootDir));
|
|
188010
188210
|
}
|
|
188011
188211
|
}
|
|
188012
|
-
for (const parameter of descendantsOfKind2(sourceFile,
|
|
188212
|
+
for (const parameter of descendantsOfKind2(sourceFile, ts5.isParameter)) {
|
|
188013
188213
|
if (parameter.type)
|
|
188014
188214
|
continue;
|
|
188015
188215
|
for (const name of bindingNames(parameter.name)) {
|
|
@@ -188020,10 +188220,10 @@ function scanSourceFile(sourceFile, checker, rootDir, diagnostics, strict) {
|
|
|
188020
188220
|
}
|
|
188021
188221
|
}
|
|
188022
188222
|
function readProjectConfig2(configPath) {
|
|
188023
|
-
const config =
|
|
188223
|
+
const config = ts5.readConfigFile(configPath, (file) => readFileSync22(file, "utf8"));
|
|
188024
188224
|
if (config.error)
|
|
188025
188225
|
return { options: {}, errors: [config.error] };
|
|
188026
|
-
const parsed =
|
|
188226
|
+
const parsed = ts5.parseJsonConfigFileContent(config.config, ts5.sys, dirname4(configPath));
|
|
188027
188227
|
return { options: parsed.options, errors: parsed.errors };
|
|
188028
188228
|
}
|
|
188029
188229
|
function isProductionSource(rootDir, sourceFile, excludes, outDir) {
|
|
@@ -188043,42 +188243,42 @@ function globMatches(value, pattern) {
|
|
|
188043
188243
|
return new RegExp(`^${escaped}$`).test(value);
|
|
188044
188244
|
}
|
|
188045
188245
|
function bindingNames(name) {
|
|
188046
|
-
if (
|
|
188246
|
+
if (ts5.isIdentifier(name))
|
|
188047
188247
|
return [name];
|
|
188048
|
-
return name.elements.flatMap((element) =>
|
|
188248
|
+
return name.elements.flatMap((element) => ts5.isBindingElement(element) ? bindingNames(element.name) : []);
|
|
188049
188249
|
}
|
|
188050
188250
|
function isLiteralExpression(node) {
|
|
188051
188251
|
if (!node)
|
|
188052
188252
|
return false;
|
|
188053
188253
|
return [
|
|
188054
|
-
|
|
188055
|
-
|
|
188056
|
-
|
|
188057
|
-
|
|
188254
|
+
ts5.SyntaxKind.StringLiteral,
|
|
188255
|
+
ts5.SyntaxKind.NumericLiteral,
|
|
188256
|
+
ts5.SyntaxKind.TrueKeyword,
|
|
188257
|
+
ts5.SyntaxKind.FalseKeyword
|
|
188058
188258
|
].includes(node.kind);
|
|
188059
188259
|
}
|
|
188060
188260
|
function isLiteralSyntax(node) {
|
|
188061
|
-
return
|
|
188261
|
+
return ts5.isStringLiteral(node) || ts5.isNumericLiteral(node) || node.kind === ts5.SyntaxKind.TrueKeyword || node.kind === ts5.SyntaxKind.FalseKeyword;
|
|
188062
188262
|
}
|
|
188063
188263
|
function isLiteralType(type) {
|
|
188064
|
-
return (type.flags & (
|
|
188264
|
+
return (type.flags & (ts5.TypeFlags.StringLiteral | ts5.TypeFlags.NumberLiteral | ts5.TypeFlags.BooleanLiteral | ts5.TypeFlags.BigIntLiteral)) !== 0;
|
|
188065
188265
|
}
|
|
188066
188266
|
function isAnyType(type) {
|
|
188067
|
-
return (type.flags &
|
|
188267
|
+
return (type.flags & ts5.TypeFlags.Any) !== 0;
|
|
188068
188268
|
}
|
|
188069
188269
|
function isLetDeclaration(declaration) {
|
|
188070
|
-
return
|
|
188270
|
+
return ts5.isVariableDeclarationList(declaration.parent) && (declaration.parent.flags & ts5.NodeFlags.Let) !== 0;
|
|
188071
188271
|
}
|
|
188072
188272
|
function isConstDeclaration(declaration) {
|
|
188073
|
-
return
|
|
188273
|
+
return ts5.isVariableDeclarationList(declaration.parent) && (declaration.parent.flags & ts5.NodeFlags.Const) !== 0;
|
|
188074
188274
|
}
|
|
188075
188275
|
function descendants(root) {
|
|
188076
188276
|
const result = [];
|
|
188077
188277
|
const visit = (node) => {
|
|
188078
188278
|
result.push(node);
|
|
188079
|
-
|
|
188279
|
+
ts5.forEachChild(node, visit);
|
|
188080
188280
|
};
|
|
188081
|
-
|
|
188281
|
+
ts5.forEachChild(root, visit);
|
|
188082
188282
|
return result;
|
|
188083
188283
|
}
|
|
188084
188284
|
function descendantsOfKind2(root, predicate) {
|
|
@@ -188086,9 +188286,9 @@ function descendantsOfKind2(root, predicate) {
|
|
|
188086
188286
|
const visit = (node) => {
|
|
188087
188287
|
if (predicate(node))
|
|
188088
188288
|
result.push(node);
|
|
188089
|
-
|
|
188289
|
+
ts5.forEachChild(node, visit);
|
|
188090
188290
|
};
|
|
188091
|
-
|
|
188291
|
+
ts5.forEachChild(root, visit);
|
|
188092
188292
|
return result;
|
|
188093
188293
|
}
|
|
188094
188294
|
function makeDiagnostic(code, message, fileOrSourceFile, node, strict, rootDir) {
|
|
@@ -188106,10 +188306,10 @@ function makeDiagnostic(code, message, fileOrSourceFile, node, strict, rootDir)
|
|
|
188106
188306
|
};
|
|
188107
188307
|
}
|
|
188108
188308
|
function normalizeRelative(rootDir, filePath) {
|
|
188109
|
-
return
|
|
188309
|
+
return relative4(rootDir, filePath).split(sep4).join("/").replace(/^\.\//, "");
|
|
188110
188310
|
}
|
|
188111
188311
|
function isAnyKeyword(node) {
|
|
188112
|
-
return node.kind ===
|
|
188312
|
+
return node.kind === ts5.SyntaxKind.AnyKeyword;
|
|
188113
188313
|
}
|
|
188114
188314
|
async function compileProject(options) {
|
|
188115
188315
|
const graph = await analyzeProject(options.rootDir, options.include, options.cache, options.changedPaths);
|
|
@@ -188174,6 +188374,79 @@ async function compileProject(options) {
|
|
|
188174
188374
|
} : undefined;
|
|
188175
188375
|
return { diagnostics, graph, written, stats };
|
|
188176
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
|
+
}
|
|
188177
188450
|
function resolveTypeSafety(options) {
|
|
188178
188451
|
return {
|
|
188179
188452
|
noAnyInGenerated: options.typeSafety?.noAnyInGenerated ?? options.strict ?? false,
|
|
@@ -188201,13 +188474,14 @@ function defineSupacloudConfig(config = {}) {
|
|
|
188201
188474
|
function resolveSupacloudConfig(config = {}, cwd = process.cwd()) {
|
|
188202
188475
|
const resolved = defineSupacloudConfig(config);
|
|
188203
188476
|
return {
|
|
188204
|
-
rootDir:
|
|
188205
|
-
outDir:
|
|
188477
|
+
rootDir: resolve62(cwd, resolved.root ?? DEFAULT_SUPACLOUD_CONFIG.root),
|
|
188478
|
+
outDir: resolve62(cwd, resolved.outDir ?? DEFAULT_SUPACLOUD_CONFIG.outDir),
|
|
188206
188479
|
include: resolved.include ?? [...DEFAULT_SUPACLOUD_CONFIG.include],
|
|
188207
188480
|
strict: resolved.strict ?? DEFAULT_SUPACLOUD_CONFIG.strict,
|
|
188208
188481
|
generateClient: resolved.generateClient ?? DEFAULT_SUPACLOUD_CONFIG.generateClient,
|
|
188209
188482
|
generatePermissions: resolved.generatePermissions ?? DEFAULT_SUPACLOUD_CONFIG.generatePermissions,
|
|
188210
188483
|
moduleBoundaryPreset: resolved.moduleBoundaryPreset ?? DEFAULT_SUPACLOUD_CONFIG.moduleBoundaryPreset,
|
|
188484
|
+
commandCapabilities: resolved.commandCapabilities,
|
|
188211
188485
|
treeShakeUnusedProviders: resolved.treeShakeUnusedProviders ?? DEFAULT_SUPACLOUD_CONFIG.treeShakeUnusedProviders
|
|
188212
188486
|
};
|
|
188213
188487
|
}
|
|
@@ -188234,6 +188508,7 @@ function compileOptionsFromConfig(config, cwd = process.cwd()) {
|
|
|
188234
188508
|
generateClient: resolved.generateClient,
|
|
188235
188509
|
generatePermissions: resolved.generatePermissions,
|
|
188236
188510
|
moduleBoundaryPreset: resolved.moduleBoundaryPreset,
|
|
188511
|
+
commandCapabilities: resolved.commandCapabilities,
|
|
188237
188512
|
treeShakeUnusedProviders: resolved.treeShakeUnusedProviders
|
|
188238
188513
|
};
|
|
188239
188514
|
}
|
|
@@ -188352,7 +188627,728 @@ function buildToolDefinitions(manifest) {
|
|
|
188352
188627
|
return { openai, mcp };
|
|
188353
188628
|
}
|
|
188354
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
|
+
|
|
188355
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
|
+
}
|
|
188356
189352
|
function textResult(text, isError = false) {
|
|
188357
189353
|
return { isError, content: [{ type: "text", text }] };
|
|
188358
189354
|
}
|
|
@@ -188378,11 +189374,11 @@ async function writeScaffold(path, content, force) {
|
|
|
188378
189374
|
if (!force) {
|
|
188379
189375
|
throw new Error(`File already exists: ${path}(使用 --force 覆盖)`);
|
|
188380
189376
|
}
|
|
188381
|
-
await
|
|
189377
|
+
await writeFile3(path, content, "utf8");
|
|
188382
189378
|
return "overwritten";
|
|
188383
189379
|
}
|
|
188384
|
-
await
|
|
188385
|
-
await
|
|
189380
|
+
await mkdir3(dirname7(path), { recursive: true });
|
|
189381
|
+
await writeFile3(path, content, "utf8");
|
|
188386
189382
|
return "created";
|
|
188387
189383
|
}
|
|
188388
189384
|
function moduleScaffold(name) {
|
|
@@ -188426,11 +189422,11 @@ async function generateScaffold(args) {
|
|
|
188426
189422
|
const kind = args.kind;
|
|
188427
189423
|
if (!kind)
|
|
188428
189424
|
throw new Error("app generate requires --kind (module|command|query|controller)");
|
|
188429
|
-
const root =
|
|
189425
|
+
const root = resolve9(args.root || process.cwd());
|
|
188430
189426
|
const dir = args.dir || "src/features";
|
|
188431
189427
|
if (kind === "module") {
|
|
188432
189428
|
const name2 = requireIdentifier(args.name, "name");
|
|
188433
|
-
const path2 =
|
|
189429
|
+
const path2 = join8(root, dir, name2, `${name2}.module.ts`);
|
|
188434
189430
|
const status2 = await writeScaffold(path2, moduleScaffold(name2), args.force === true);
|
|
188435
189431
|
return textResult(`✅ ${status2}: ${path2}`);
|
|
188436
189432
|
}
|
|
@@ -188438,7 +189434,7 @@ async function generateScaffold(args) {
|
|
|
188438
189434
|
const name = kind === "controller" ? moduleName : requireIdentifier(args.name, "name");
|
|
188439
189435
|
const fileName = kind === "controller" ? `${moduleName}.controller.ts` : `${name}.${kind}.ts`;
|
|
188440
189436
|
const subdir = kind === "command" ? "commands" : kind === "query" ? "queries" : "";
|
|
188441
|
-
const path =
|
|
189437
|
+
const path = join8(root, dir, moduleName, subdir, fileName);
|
|
188442
189438
|
if (kind === "controller" && existsSync9(path)) {
|
|
188443
189439
|
throw new Error(`Controller already exists: ${path}(请手工合并路由到现有 controller)`);
|
|
188444
189440
|
}
|
|
@@ -188460,18 +189456,23 @@ function parseInclude(include) {
|
|
|
188460
189456
|
const patterns = include?.split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
188461
189457
|
return patterns && patterns.length > 0 ? patterns : undefined;
|
|
188462
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
|
+
}
|
|
188463
189463
|
async function runCompile(args) {
|
|
188464
|
-
const root =
|
|
189464
|
+
const root = resolve9(args.root || process.cwd());
|
|
188465
189465
|
const loadedConfig = await loadSupacloudConfig(root);
|
|
188466
189466
|
const defaults = resolveSupacloudConfig(loadedConfig, root);
|
|
188467
189467
|
const result = await compileProject({
|
|
188468
189468
|
...compileOptionsFromConfig({
|
|
188469
189469
|
...loadedConfig,
|
|
188470
|
-
root: args
|
|
188471
|
-
outDir: args.out_dir ?
|
|
189470
|
+
root: sourceRoot(args, root, loadedConfig.root),
|
|
189471
|
+
outDir: args.out_dir ? resolve9(root, args.out_dir) : defaults.outDir,
|
|
188472
189472
|
include: parseInclude(args.include) ?? loadedConfig.include,
|
|
188473
189473
|
strict: args.strict ?? loadedConfig.strict ?? false
|
|
188474
|
-
}, root)
|
|
189474
|
+
}, root),
|
|
189475
|
+
writeOnError: false
|
|
188475
189476
|
});
|
|
188476
189477
|
const hasError = result.diagnostics.some((diagnostic) => diagnostic.severity === "error");
|
|
188477
189478
|
const text = [
|
|
@@ -188484,38 +189485,29 @@ async function runCompile(args) {
|
|
|
188484
189485
|
return textResult(text, hasError);
|
|
188485
189486
|
}
|
|
188486
189487
|
async function runCheck(args) {
|
|
188487
|
-
const root =
|
|
189488
|
+
const root = resolve9(args.root || process.cwd());
|
|
188488
189489
|
const loadedConfig = await loadSupacloudConfig(root);
|
|
188489
189490
|
const defaults = resolveSupacloudConfig(loadedConfig, root);
|
|
188490
189491
|
const config = compileOptionsFromConfig({
|
|
188491
189492
|
...loadedConfig,
|
|
188492
|
-
root: args
|
|
188493
|
-
outDir: args.out_dir ?
|
|
189493
|
+
root: sourceRoot(args, root, loadedConfig.root),
|
|
189494
|
+
outDir: args.out_dir ? resolve9(root, args.out_dir) : defaults.outDir,
|
|
188494
189495
|
include: parseInclude(args.include) ?? loadedConfig.include,
|
|
188495
189496
|
strict: args.strict ?? loadedConfig.strict ?? false
|
|
188496
189497
|
}, root);
|
|
188497
|
-
const
|
|
188498
|
-
const
|
|
188499
|
-
|
|
188500
|
-
|
|
188501
|
-
|
|
188502
|
-
|
|
188503
|
-
|
|
188504
|
-
|
|
188505
|
-
|
|
188506
|
-
|
|
188507
|
-
if (diagnostic.severity === "warn")
|
|
188508
|
-
diagnostic.severity = "error";
|
|
188509
|
-
}
|
|
188510
|
-
}
|
|
188511
|
-
const hasError = diagnostics.some((diagnostic) => diagnostic.severity === "error");
|
|
188512
|
-
const summary = `checked ${graph.modules.length} module(s), no files written`;
|
|
188513
|
-
return textResult(`${formatDiagnostics(diagnostics)}
|
|
188514
|
-
|
|
188515
|
-
${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);
|
|
188516
189508
|
}
|
|
188517
189509
|
async function readManifest(root) {
|
|
188518
|
-
const manifestPath =
|
|
189510
|
+
const manifestPath = join8(root, "generated", "app.manifest.json");
|
|
188519
189511
|
if (!existsSync9(manifestPath)) {
|
|
188520
189512
|
throw new Error(`Manifest not found: ${manifestPath}(先运行 app compile 生成)`);
|
|
188521
189513
|
}
|
|
@@ -188556,7 +189548,7 @@ function formatGraphText(manifest) {
|
|
|
188556
189548
|
`);
|
|
188557
189549
|
}
|
|
188558
189550
|
async function runGraph(args) {
|
|
188559
|
-
const root =
|
|
189551
|
+
const root = resolve9(args.root || process.cwd());
|
|
188560
189552
|
const manifest = await readManifest(root);
|
|
188561
189553
|
if (args.format === "json")
|
|
188562
189554
|
return textResult(JSON.stringify(manifest, null, 2));
|
|
@@ -188620,7 +189612,7 @@ async function runExplain(args) {
|
|
|
188620
189612
|
const target = args.target?.trim();
|
|
188621
189613
|
if (!target)
|
|
188622
189614
|
throw new Error("app explain requires --target(provider 类名 / token 名 / command 名)");
|
|
188623
|
-
const root =
|
|
189615
|
+
const root = resolve9(args.root || process.cwd());
|
|
188624
189616
|
const manifest = await readManifest(root);
|
|
188625
189617
|
for (const module of manifest.modules) {
|
|
188626
189618
|
const providerIndex = module.providers.findIndex((provider) => provider.token === target || provider.useClass === target);
|
|
@@ -188673,18 +189665,18 @@ async function runExplain(args) {
|
|
|
188673
189665
|
return textResult(`未找到对象: ${target}`, true);
|
|
188674
189666
|
}
|
|
188675
189667
|
async function runExportTools(args) {
|
|
188676
|
-
const root =
|
|
189668
|
+
const root = resolve9(args.root || process.cwd());
|
|
188677
189669
|
const manifest = await readManifest(root);
|
|
188678
189670
|
const definitions = buildToolDefinitions(manifest);
|
|
188679
|
-
const outDir =
|
|
188680
|
-
await
|
|
189671
|
+
const outDir = resolve9(args.out_dir || join8(root, "generated"));
|
|
189672
|
+
await mkdir3(outDir, { recursive: true });
|
|
188681
189673
|
if (args.format === "json") {
|
|
188682
189674
|
return textResult(JSON.stringify(definitions, null, 2));
|
|
188683
189675
|
}
|
|
188684
|
-
const openaiPath =
|
|
188685
|
-
const mcpPath =
|
|
188686
|
-
await
|
|
188687
|
-
await
|
|
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");
|
|
188688
189680
|
const summary = [
|
|
188689
189681
|
`exported ${definitions.openai.length} tool(s):`,
|
|
188690
189682
|
` openai → ${openaiPath}`,
|
|
@@ -188697,14 +189689,14 @@ async function runExportTools(args) {
|
|
|
188697
189689
|
return textResult(summary);
|
|
188698
189690
|
}
|
|
188699
189691
|
function registerAppTools(server2) {
|
|
188700
|
-
server2.tool("app", "Local @supacloud/app framework commands: scaffold, compile, check, graph, explain and export-tools. Actions: generate, compile, check, graph, explain, export-tools", {
|
|
188701
|
-
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"),
|
|
188702
189694
|
kind: optional(stringEnum(["module", "command", "query", "controller"]), "[generate] Scaffold kind"),
|
|
188703
|
-
name: optional(Type.String(), "[generate]
|
|
189695
|
+
name: optional(Type.String(), "[init/generate] Project or object name"),
|
|
188704
189696
|
module: optional(Type.String(), "[generate] Target feature module (required for command/query/controller)"),
|
|
188705
189697
|
dir: optional(Type.String(), "[generate] Feature root directory (default: src/features)"),
|
|
188706
189698
|
force: optional(Type.Boolean(), "[generate] Overwrite existing files"),
|
|
188707
|
-
root: optional(Type.String(), "
|
|
189699
|
+
root: optional(Type.String(), "Project directory containing supacloud.config.ts (default: current directory)"),
|
|
188708
189700
|
include: optional(Type.String(), "[compile/check] Comma-separated glob patterns for source files"),
|
|
188709
189701
|
out_dir: optional(Type.String(), "[compile/export-tools] Output directory (default: <root>/generated)"),
|
|
188710
189702
|
strict: optional(Type.Boolean(), "[compile/check] Promote warnings to errors"),
|
|
@@ -188712,6 +189704,8 @@ function registerAppTools(server2) {
|
|
|
188712
189704
|
target: optional(Type.String(), "[explain] Provider class name / token name / command name")
|
|
188713
189705
|
}, async (request) => {
|
|
188714
189706
|
switch (request.action) {
|
|
189707
|
+
case "init":
|
|
189708
|
+
return initProject(request);
|
|
188715
189709
|
case "generate":
|
|
188716
189710
|
return generateScaffold(request);
|
|
188717
189711
|
case "compile":
|
|
@@ -188732,7 +189726,7 @@ function registerAppTools(server2) {
|
|
|
188732
189726
|
|
|
188733
189727
|
// src/shared/tools/db-governance-tools.ts
|
|
188734
189728
|
import { existsSync as existsSync10 } from "node:fs";
|
|
188735
|
-
import { join as
|
|
189729
|
+
import { join as join9, resolve as resolve10 } from "node:path";
|
|
188736
189730
|
|
|
188737
189731
|
// node_modules/@supacloud/db/dist/index.js
|
|
188738
189732
|
var TABLES_SQL = `
|
|
@@ -189184,7 +190178,7 @@ function normalizeModule(candidate, sourcePath2) {
|
|
|
189184
190178
|
};
|
|
189185
190179
|
}
|
|
189186
190180
|
async function loadDatabaseModules(root, moduleFile) {
|
|
189187
|
-
const filePath = moduleFile ?
|
|
190181
|
+
const filePath = moduleFile ? resolve10(root, moduleFile) : join9(root, "db", "modules.ts");
|
|
189188
190182
|
if (!existsSync10(filePath)) {
|
|
189189
190183
|
throw new Error(moduleFile ? `Module file not found: ${filePath}` : `Module file not found: ${filePath}(用 --module_file 指定一个导出 defineDatabaseModule(...) 的文件)`);
|
|
189190
190184
|
}
|
|
@@ -189233,7 +190227,7 @@ async function runLint(args, root) {
|
|
|
189233
190227
|
const issues = [];
|
|
189234
190228
|
for (const module of selected) {
|
|
189235
190229
|
const readSqlFile = async (path) => {
|
|
189236
|
-
const absolute =
|
|
190230
|
+
const absolute = resolve10(root, path);
|
|
189237
190231
|
try {
|
|
189238
190232
|
return await Bun.file(absolute).text();
|
|
189239
190233
|
} catch (error) {
|
|
@@ -189269,14 +190263,14 @@ var defaultLiteSpawn = async (command, cwd) => {
|
|
|
189269
190263
|
return { exitCode, stdout, stderr };
|
|
189270
190264
|
};
|
|
189271
190265
|
async function runModuleCheckLite(args, root, spawn3, liteBinary) {
|
|
189272
|
-
const projectDir =
|
|
190266
|
+
const projectDir = resolve10(args.project_dir?.trim() || root);
|
|
189273
190267
|
const binary = liteBinary === undefined ? Bun.which("supacloud-lite") : liteBinary;
|
|
189274
190268
|
if (!binary) {
|
|
189275
190269
|
throw new Error("db module_check --lite 需要本机可用的 supacloud-lite(npm i -g @supacloud/lite,或加入 PATH)");
|
|
189276
190270
|
}
|
|
189277
190271
|
const command = [binary, "db", "check", "--project-dir", projectDir];
|
|
189278
190272
|
if (args.module_file?.trim())
|
|
189279
|
-
command.push("--module-file",
|
|
190273
|
+
command.push("--module-file", resolve10(root, args.module_file.trim()));
|
|
189280
190274
|
const result = await spawn3(command, projectDir);
|
|
189281
190275
|
const output = [result.stdout.trim(), result.stderr.trim()].filter(Boolean).join(`
|
|
189282
190276
|
`);
|
|
@@ -189327,7 +190321,7 @@ function registerDbGovernanceTools(server2, options = {}) {
|
|
|
189327
190321
|
lite: optional(Type.Boolean(), "[module_check] Reconcile against a local SupaCloud Lite project (runs supacloud-lite db check)"),
|
|
189328
190322
|
project_dir: optional(Type.String(), "[module_check] Lite project directory (with --lite; default: --root)")
|
|
189329
190323
|
}, async (request) => {
|
|
189330
|
-
const root =
|
|
190324
|
+
const root = resolve10(request.root || fallbackRoot);
|
|
189331
190325
|
switch (request.action) {
|
|
189332
190326
|
case "lint":
|
|
189333
190327
|
return runLint(request, root);
|
|
@@ -189344,7 +190338,7 @@ function registerDbGovernanceTools(server2, options = {}) {
|
|
|
189344
190338
|
// src/shared/tools/scheduled-function-tools.ts
|
|
189345
190339
|
import { randomUUID } from "node:crypto";
|
|
189346
190340
|
import { readFileSync as readFileSync7, statSync as statSync5 } from "node:fs";
|
|
189347
|
-
import { resolve as
|
|
190341
|
+
import { resolve as resolve11 } from "node:path";
|
|
189348
190342
|
import { isDeepStrictEqual } from "node:util";
|
|
189349
190343
|
var HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/;
|
|
189350
190344
|
var ENVIRONMENT_NAME_PATTERN2 = /^[A-Za-z_][A-Za-z0-9_]{0,255}$/;
|
|
@@ -189428,7 +190422,7 @@ function validScheduledFunctionCron(expression) {
|
|
|
189428
190422
|
function readScheduleBodyFile(bodyPathInput) {
|
|
189429
190423
|
if (!bodyPathInput.trim())
|
|
189430
190424
|
throw new Error("'body_file' must be a path");
|
|
189431
|
-
const bodyPath =
|
|
190425
|
+
const bodyPath = resolve11(bodyPathInput);
|
|
189432
190426
|
const bodyStat = statSync5(bodyPath);
|
|
189433
190427
|
if (!bodyStat.isFile() || bodyStat.size > MAX_BODY_FILE_BYTES) {
|
|
189434
190428
|
throw new Error("Scheduled Function body file must be a regular file no larger than 1 MiB");
|
|
@@ -190009,6 +191003,10 @@ var MUTATION_TOOL_SCHEMA = {
|
|
|
190009
191003
|
};
|
|
190010
191004
|
|
|
190011
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";
|
|
190012
191010
|
var SAFE_PROJECT_REF = /^[A-Za-z0-9_-]{1,64}$/;
|
|
190013
191011
|
var BACKUP_ID = /^logical-full_[A-Za-z0-9_-]{1,64}_[a-f0-9]{32}$/;
|
|
190014
191012
|
var SHA256 = /^[a-f0-9]{64}$/;
|
|
@@ -190225,18 +191223,337 @@ async function applicationOriginMatches(http, projectRef2, applicationOrigin) {
|
|
|
190225
191223
|
const endpointRead = await http.get(`${endpoint(projectRef2)}/endpoint/projection`, { maxJsonBytes: PROJECT_ENDPOINT_RESPONSE_MAX_BYTES, responseTimeoutMs: RELEASE_READ_RESPONSE_TIMEOUT_MS });
|
|
190226
191224
|
return projectApiOrigins(endpointRead, projectRef2)?.includes(applicationOrigin) === true;
|
|
190227
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
|
+
}
|
|
190228
191531
|
function registerReleaseTools(server2, http, options = {}) {
|
|
190229
|
-
|
|
190230
|
-
|
|
190231
|
-
|
|
190232
|
-
|
|
190233
|
-
|
|
190234
|
-
|
|
190235
|
-
|
|
190236
|
-
|
|
190237
|
-
|
|
190238
|
-
|
|
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"),
|
|
190239
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"),
|
|
190240
191557
|
backup_id: optional(Type.String(), "[logical_backup_restore] Exact verified logical-full backup ID from the selected project inventory"),
|
|
190241
191558
|
expected_sha256: optional(Type.String(), "[logical_backup_restore] Exact lowercase SHA-256 from the selected project inventory"),
|
|
190242
191559
|
restore_confirmation: optional(Type.String(), "[logical_backup_restore] Exact RESTORE_PROJECT:<ref>:<backup_id>:<sha256> confirmation"),
|
|
@@ -190245,7 +191562,29 @@ function registerReleaseTools(server2, http, options = {}) {
|
|
|
190245
191562
|
fixture_id: optional(Type.String(), "[release_canary_fixture_disable_replay] Exact staged fixture UUID"),
|
|
190246
191563
|
disable_request_id: optional(Type.String(), "[release_canary_fixture_disable_replay] Exact idempotent disable request UUID"),
|
|
190247
191564
|
issuer: optional(Type.String(), "[release_canary_fixture_disable_replay] Exact HTTP(S) issuer")
|
|
190248
|
-
}, async (
|
|
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;
|
|
190249
191588
|
const projectRef2 = typeof ref === "string" && ref || options.projectRef;
|
|
190250
191589
|
if (!projectRef2)
|
|
190251
191590
|
throw new Error("'ref' is required for release controls");
|
|
@@ -190386,10 +191725,10 @@ function registerReleaseTools(server2, http, options = {}) {
|
|
|
190386
191725
|
}
|
|
190387
191726
|
|
|
190388
191727
|
// src/shared/tools/deploy-tools.ts
|
|
190389
|
-
import { access as access2, lstat, mkdtemp, opendir, readFile as readFile2, rm, writeFile as
|
|
190390
|
-
import { createHash as
|
|
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";
|
|
190391
191730
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
190392
|
-
import { basename as
|
|
191731
|
+
import { basename as basename5, dirname as dirname9, join as join11, relative as relative7, resolve as resolve13, sep as sep5 } from "node:path";
|
|
190393
191732
|
import { spawn as spawn3 } from "node:child_process";
|
|
190394
191733
|
|
|
190395
191734
|
// node_modules/fflate/esm/index.mjs
|
|
@@ -191081,13 +192420,13 @@ async function readJson(path) {
|
|
|
191081
192420
|
}
|
|
191082
192421
|
}
|
|
191083
192422
|
async function findDeployConfigRoot(startDirectory) {
|
|
191084
|
-
let directory =
|
|
192423
|
+
let directory = resolve13(startDirectory);
|
|
191085
192424
|
while (true) {
|
|
191086
|
-
if (await pathExists(
|
|
192425
|
+
if (await pathExists(join11(directory, "supacloud.json")))
|
|
191087
192426
|
return directory;
|
|
191088
|
-
const parent =
|
|
192427
|
+
const parent = dirname9(directory);
|
|
191089
192428
|
if (parent === directory)
|
|
191090
|
-
return
|
|
192429
|
+
return resolve13(startDirectory);
|
|
191091
192430
|
directory = parent;
|
|
191092
192431
|
}
|
|
191093
192432
|
}
|
|
@@ -191130,7 +192469,7 @@ function deployTargetConfig(candidate, name) {
|
|
|
191130
192469
|
};
|
|
191131
192470
|
}
|
|
191132
192471
|
async function readDeployConfig(configRoot) {
|
|
191133
|
-
const configPath =
|
|
192472
|
+
const configPath = join11(configRoot, "supacloud.json");
|
|
191134
192473
|
const candidate = await readJson(configPath);
|
|
191135
192474
|
if (candidate === null)
|
|
191136
192475
|
return {};
|
|
@@ -191152,30 +192491,30 @@ async function readDeployConfig(configRoot) {
|
|
|
191152
192491
|
};
|
|
191153
192492
|
}
|
|
191154
192493
|
async function packageName(projectDirectory) {
|
|
191155
|
-
const candidate = record2(await readJson(
|
|
192494
|
+
const candidate = record2(await readJson(join11(projectDirectory, "package.json")));
|
|
191156
192495
|
return typeof candidate?.name === "string" && candidate.name.trim() ? candidate.name.trim() : null;
|
|
191157
192496
|
}
|
|
191158
192497
|
async function pathExists(path) {
|
|
191159
192498
|
return access2(path).then(() => true, () => false);
|
|
191160
192499
|
}
|
|
191161
192500
|
async function defaultBuildCommand(projectDirectory, configRoot) {
|
|
191162
|
-
const packageJson = record2(await readJson(
|
|
192501
|
+
const packageJson = record2(await readJson(join11(projectDirectory, "package.json")));
|
|
191163
192502
|
const scripts = record2(packageJson?.scripts);
|
|
191164
192503
|
if (typeof scripts?.build !== "string" || !scripts.build.trim()) {
|
|
191165
192504
|
throw new Error("No build command was configured and package.json has no build script");
|
|
191166
192505
|
}
|
|
191167
192506
|
let directory = projectDirectory;
|
|
191168
192507
|
while (true) {
|
|
191169
|
-
if (await pathExists(
|
|
192508
|
+
if (await pathExists(join11(directory, "bun.lock")) || await pathExists(join11(directory, "bun.lockb")))
|
|
191170
192509
|
return "bun run build";
|
|
191171
|
-
if (await pathExists(
|
|
192510
|
+
if (await pathExists(join11(directory, "pnpm-lock.yaml")))
|
|
191172
192511
|
return "pnpm run build";
|
|
191173
|
-
if (await pathExists(
|
|
192512
|
+
if (await pathExists(join11(directory, "yarn.lock")))
|
|
191174
192513
|
return "yarn build";
|
|
191175
192514
|
if (directory === configRoot)
|
|
191176
192515
|
break;
|
|
191177
|
-
const parent =
|
|
191178
|
-
if (parent === directory || !directory.startsWith(`${configRoot}${
|
|
192516
|
+
const parent = dirname9(directory);
|
|
192517
|
+
if (parent === directory || !directory.startsWith(`${configRoot}${sep5}`))
|
|
191179
192518
|
break;
|
|
191180
192519
|
directory = parent;
|
|
191181
192520
|
}
|
|
@@ -191205,9 +192544,9 @@ function selectDeployment(deployments, requestedId, projectName) {
|
|
|
191205
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`);
|
|
191206
192545
|
}
|
|
191207
192546
|
function targetRoot(configRoot, target, name) {
|
|
191208
|
-
const root =
|
|
191209
|
-
const prefix = `${
|
|
191210
|
-
if (root !==
|
|
192547
|
+
const root = resolve13(configRoot, target.root || (name === "frontend" ? "." : name));
|
|
192548
|
+
const prefix = `${resolve13(configRoot)}${sep5}`;
|
|
192549
|
+
if (root !== resolve13(configRoot) && !root.startsWith(prefix)) {
|
|
191211
192550
|
throw new Error(`Deploy target '${name}' root must stay inside the repository root`);
|
|
191212
192551
|
}
|
|
191213
192552
|
return root;
|
|
@@ -191228,7 +192567,7 @@ function selectTarget(configRoot, invocationDirectory, config, requestedName) {
|
|
|
191228
192567
|
throw new Error(`Deploy target '${requestedName}' was not found in supacloud.json`);
|
|
191229
192568
|
return { name: selected[0], config: selected[1], root: targetRoot(configRoot, selected[1], selected[0]) };
|
|
191230
192569
|
}
|
|
191231
|
-
const containing = targets.map(([name, target]) => ({ name, target, root: targetRoot(configRoot, target, name) })).filter((candidate) => invocationDirectory === candidate.root || invocationDirectory.startsWith(`${candidate.root}${
|
|
192570
|
+
const containing = targets.map(([name, target]) => ({ name, target, root: targetRoot(configRoot, target, name) })).filter((candidate) => invocationDirectory === candidate.root || invocationDirectory.startsWith(`${candidate.root}${sep5}`)).sort((left, right) => right.root.length - left.root.length);
|
|
191232
192571
|
if (containing.length === 1 || containing.length > 1 && containing[0].root !== containing[1].root) {
|
|
191233
192572
|
const selected = containing[0];
|
|
191234
192573
|
return { name: selected.name, config: selected.target, root: selected.root };
|
|
@@ -191258,9 +192597,9 @@ function defaultOutputDirectory(framework) {
|
|
|
191258
192597
|
}
|
|
191259
192598
|
}
|
|
191260
192599
|
function resolveInsideProject(projectDirectory, candidate, allowRoot = false) {
|
|
191261
|
-
const resolved =
|
|
191262
|
-
const projectRoot =
|
|
191263
|
-
const projectPrefix = `${projectRoot}${
|
|
192600
|
+
const resolved = resolve13(projectDirectory, candidate);
|
|
192601
|
+
const projectRoot = resolve13(projectDirectory);
|
|
192602
|
+
const projectPrefix = `${projectRoot}${sep5}`;
|
|
191264
192603
|
if (!allowRoot && resolved === projectRoot || resolved !== projectRoot && !resolved.startsWith(projectPrefix)) {
|
|
191265
192604
|
throw new Error("Frontend output directory must stay inside the project directory");
|
|
191266
192605
|
}
|
|
@@ -191279,7 +192618,7 @@ async function runBuild(command, cwd) {
|
|
|
191279
192618
|
});
|
|
191280
192619
|
}
|
|
191281
192620
|
async function collectArchiveFiles(root) {
|
|
191282
|
-
const rootStat = await
|
|
192621
|
+
const rootStat = await lstat2(root).catch(() => null);
|
|
191283
192622
|
if (!rootStat?.isDirectory() || rootStat.isSymbolicLink()) {
|
|
191284
192623
|
throw new Error(`Frontend output directory does not exist or is not a regular directory: ${root}`);
|
|
191285
192624
|
}
|
|
@@ -191290,8 +192629,8 @@ async function collectArchiveFiles(root) {
|
|
|
191290
192629
|
entries.push(entry);
|
|
191291
192630
|
entries.sort((left, right) => left.name.localeCompare(right.name, "en"));
|
|
191292
192631
|
for (const entry of entries) {
|
|
191293
|
-
const path =
|
|
191294
|
-
const stats = await
|
|
192632
|
+
const path = join11(directory, entry.name);
|
|
192633
|
+
const stats = await lstat2(path);
|
|
191295
192634
|
if (stats.isSymbolicLink())
|
|
191296
192635
|
throw new Error(`Frontend output cannot contain symbolic links: ${path}`);
|
|
191297
192636
|
if (stats.isDirectory())
|
|
@@ -191312,19 +192651,19 @@ async function collectArchiveFiles(root) {
|
|
|
191312
192651
|
bytes += data.byteLength;
|
|
191313
192652
|
if (bytes > MAX_SOURCE_BYTES)
|
|
191314
192653
|
throw new Error(`Frontend output exceeds ${MAX_SOURCE_BYTES} bytes`);
|
|
191315
|
-
const archivePath =
|
|
192654
|
+
const archivePath = relative7(root, path).split(sep5).join("/");
|
|
191316
192655
|
files[archivePath] = [data, { mtime: FIXED_ZIP_MTIME }];
|
|
191317
192656
|
}
|
|
191318
192657
|
return { files, bytes, count: paths.length };
|
|
191319
192658
|
}
|
|
191320
192659
|
async function createFrontendArchive(outputDirectory) {
|
|
191321
192660
|
const collected = await collectArchiveFiles(outputDirectory);
|
|
191322
|
-
const temporaryDirectory = await mkdtemp(
|
|
191323
|
-
const archivePath =
|
|
192661
|
+
const temporaryDirectory = await mkdtemp(join11(tmpdir2(), "supacloud-deploy-"));
|
|
192662
|
+
const archivePath = join11(temporaryDirectory, `${basename5(outputDirectory)}.zip`);
|
|
191324
192663
|
try {
|
|
191325
192664
|
const archiveBytes = zipSync(collected.files, { level: 6, mtime: FIXED_ZIP_MTIME });
|
|
191326
|
-
await
|
|
191327
|
-
const sha256 =
|
|
192665
|
+
await writeFile5(archivePath, archiveBytes);
|
|
192666
|
+
const sha256 = createHash6("sha256").update(archiveBytes).digest("hex");
|
|
191328
192667
|
return {
|
|
191329
192668
|
archivePath,
|
|
191330
192669
|
sha256,
|
|
@@ -191346,16 +192685,16 @@ function payload(response) {
|
|
|
191346
192685
|
throw new Error("Deployment operation returned an invalid response");
|
|
191347
192686
|
return parsed;
|
|
191348
192687
|
}
|
|
191349
|
-
function phaseReporter(
|
|
192688
|
+
function phaseReporter(json2) {
|
|
191350
192689
|
const started = performance.now();
|
|
191351
192690
|
return (phase, detail) => {
|
|
191352
|
-
if (!
|
|
192691
|
+
if (!json2)
|
|
191353
192692
|
console.error(` ${phase.padEnd(10)} ${detail}`);
|
|
191354
192693
|
return Math.round(performance.now() - started);
|
|
191355
192694
|
};
|
|
191356
192695
|
}
|
|
191357
|
-
function deployResponse(result,
|
|
191358
|
-
if (
|
|
192696
|
+
function deployResponse(result, json2) {
|
|
192697
|
+
if (json2)
|
|
191359
192698
|
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
191360
192699
|
const lines = [
|
|
191361
192700
|
result.unchanged === true ? "Already up to date." : `Deployed ${String(result.target || result.deployment_id || result.slug)}.`,
|
|
@@ -191370,7 +192709,7 @@ function deployResponse(result, json) {
|
|
|
191370
192709
|
}
|
|
191371
192710
|
function registerDeployTools(server2, http, options = {}) {
|
|
191372
192711
|
server2.tool("deploy", "Build and publish the linked frontend with one command", deployToolSchema, async (args) => {
|
|
191373
|
-
const invocationDirectory =
|
|
192712
|
+
const invocationDirectory = resolve13(String(args.cwd || options.cwd || process.cwd()));
|
|
191374
192713
|
const projectRef2 = String(args.ref || options.projectRef || "").trim();
|
|
191375
192714
|
if (!projectRef2)
|
|
191376
192715
|
throw new Error("A linked project ref is required. Set SUPACLOUD_PROJECT_REF or pass --ref");
|
|
@@ -191378,7 +192717,7 @@ function registerDeployTools(server2, http, options = {}) {
|
|
|
191378
192717
|
const config = await readDeployConfig(configRoot);
|
|
191379
192718
|
const target = selectTarget(configRoot, invocationDirectory, config, String(args.target || "").trim() || undefined);
|
|
191380
192719
|
const projectDirectory = target.root;
|
|
191381
|
-
const targetState = await
|
|
192720
|
+
const targetState = await lstat2(projectDirectory).catch(() => null);
|
|
191382
192721
|
if (!targetState?.isDirectory() || targetState.isSymbolicLink()) {
|
|
191383
192722
|
throw new Error(`Deploy target '${target.name}' root is not a regular directory: ${projectDirectory}`);
|
|
191384
192723
|
}
|
|
@@ -191484,7 +192823,7 @@ function registerDeployTools(server2, http, options = {}) {
|
|
|
191484
192823
|
} else {
|
|
191485
192824
|
report("build", "skipped");
|
|
191486
192825
|
}
|
|
191487
|
-
report("package",
|
|
192826
|
+
report("package", relative7(projectDirectory, outputDirectory) || ".");
|
|
191488
192827
|
const archive = await createFrontendArchive(outputDirectory);
|
|
191489
192828
|
try {
|
|
191490
192829
|
const inventory = payload(await listFrontendReleases(http, projectRef2, selected.id, undefined, 100));
|
|
@@ -191543,11 +192882,11 @@ function registerDeployTools(server2, http, options = {}) {
|
|
|
191543
192882
|
|
|
191544
192883
|
// src/shared/tools/remote-dev-tools.ts
|
|
191545
192884
|
import { spawn as spawn4 } from "node:child_process";
|
|
191546
|
-
import { existsSync as
|
|
192885
|
+
import { existsSync as existsSync12 } from "node:fs";
|
|
191547
192886
|
import { readFile as readFile3 } from "node:fs/promises";
|
|
191548
|
-
import { readdir } from "node:fs/promises";
|
|
191549
|
-
import { createHash as
|
|
191550
|
-
import { join as
|
|
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";
|
|
191551
192890
|
var SAFE_TOKEN = /^[A-Za-z0-9._:@/+,-]+$/;
|
|
191552
192891
|
var SAFE_REMOTE_ROOT = /^\/(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+\/?$/;
|
|
191553
192892
|
var remoteDevToolSchema = {
|
|
@@ -191589,21 +192928,21 @@ function runProcess(executable, args, cwd) {
|
|
|
191589
192928
|
function resolveDrizzleCommand(root, configured) {
|
|
191590
192929
|
if (configured?.trim())
|
|
191591
192930
|
return configured.trim();
|
|
191592
|
-
const local =
|
|
191593
|
-
return
|
|
192931
|
+
const local = join12(root, "node_modules", ".bin", "drizzle-kit");
|
|
192932
|
+
return existsSync12(local) ? local : "drizzle-kit";
|
|
191594
192933
|
}
|
|
191595
192934
|
function toolFailed(value) {
|
|
191596
192935
|
return value?.isError === true || value?.content?.some((chunk) => typeof chunk?.text === "string" && chunk.text.trimStart().startsWith("❌"));
|
|
191597
192936
|
}
|
|
191598
192937
|
async function migrateDatabase(args, options) {
|
|
191599
|
-
const root =
|
|
192938
|
+
const root = resolve14(String(args.project_dir || options.cwd || process.cwd()));
|
|
191600
192939
|
const projectConfig = await readProjectConfig3(root);
|
|
191601
192940
|
const config = projectConfig.dev || {};
|
|
191602
192941
|
const database = config.database || {};
|
|
191603
192942
|
const execute = options.execute || ((command, commandArgs, cwd) => runProcess(command, commandArgs, cwd));
|
|
191604
|
-
const drizzleConfig =
|
|
192943
|
+
const drizzleConfig = resolve14(root, String(args.drizzle_config || database.drizzleConfig || "drizzle.config.ts"));
|
|
191605
192944
|
const migrationsDir = String(args.migrations_dir || database.migrationsDir || "supabase/migrations");
|
|
191606
|
-
if (!
|
|
192945
|
+
if (!existsSync12(drizzleConfig))
|
|
191607
192946
|
throw new Error(`Drizzle config not found: ${drizzleConfig}`);
|
|
191608
192947
|
const generated = await execute(resolveDrizzleCommand(root, typeof args.drizzle_bin === "string" ? args.drizzle_bin : database.drizzleBin), ["generate", "--config", drizzleConfig], root);
|
|
191609
192948
|
if (generated.exitCode !== 0)
|
|
@@ -191621,8 +192960,8 @@ async function migrateDatabase(args, options) {
|
|
|
191621
192960
|
return { ok: true, mode: "dev", action: "migrate", generated: true, applied: true, migrations_dir: migrationsDir, result: applied };
|
|
191622
192961
|
}
|
|
191623
192962
|
async function readProjectConfig3(root) {
|
|
191624
|
-
const file =
|
|
191625
|
-
if (!
|
|
192963
|
+
const file = join12(root, "supacloud.json");
|
|
192964
|
+
if (!existsSync12(file))
|
|
191626
192965
|
return {};
|
|
191627
192966
|
try {
|
|
191628
192967
|
const parsed = JSON.parse(await readFile3(file, "utf8"));
|
|
@@ -191638,9 +192977,9 @@ async function readDevConfig(root) {
|
|
|
191638
192977
|
async function sourceFingerprint(root) {
|
|
191639
192978
|
const files = [];
|
|
191640
192979
|
const visit = async (directory) => {
|
|
191641
|
-
const entries = await
|
|
192980
|
+
const entries = await readdir2(directory, { withFileTypes: true });
|
|
191642
192981
|
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
191643
|
-
const path =
|
|
192982
|
+
const path = join12(directory, entry.name);
|
|
191644
192983
|
if (entry.isDirectory() && ![".git", "node_modules", "dist", "generated", ".supacloud"].includes(entry.name))
|
|
191645
192984
|
await visit(path);
|
|
191646
192985
|
else if (entry.isFile())
|
|
@@ -191648,7 +192987,7 @@ async function sourceFingerprint(root) {
|
|
|
191648
192987
|
}
|
|
191649
192988
|
};
|
|
191650
192989
|
await visit(root);
|
|
191651
|
-
const hash2 =
|
|
192990
|
+
const hash2 = createHash7("sha256");
|
|
191652
192991
|
for (const file of files) {
|
|
191653
192992
|
hash2.update(file.slice(root.length).replace(/\\/g, "/"));
|
|
191654
192993
|
hash2.update(await readFile3(file));
|
|
@@ -191668,17 +193007,17 @@ function remoteRoot(value) {
|
|
|
191668
193007
|
}
|
|
191669
193008
|
function targetDirectory(root, target, functionSlug, config = {}) {
|
|
191670
193009
|
if (target === "db")
|
|
191671
|
-
return
|
|
193010
|
+
return join12(root, "supabase", "migrations");
|
|
191672
193011
|
if (target === "functions") {
|
|
191673
193012
|
const targets = config.targets && typeof config.targets === "object" ? config.targets : {};
|
|
191674
193013
|
const match = Object.values(targets).find((entry) => entry?.type === "edge_function" && (!functionSlug || String(entry.slug || "") === functionSlug));
|
|
191675
|
-
const base = match?.root ?
|
|
191676
|
-
return match?.root ? base : functionSlug ?
|
|
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;
|
|
191677
193016
|
}
|
|
191678
193017
|
if (target === "frontend") {
|
|
191679
193018
|
const targets = config.targets && typeof config.targets === "object" ? config.targets : {};
|
|
191680
193019
|
const match = Object.values(targets).find((entry) => entry?.type === "frontend");
|
|
191681
|
-
return match?.root ?
|
|
193020
|
+
return match?.root ? resolve14(root, String(match.root)) : join12(root, "apps", "web");
|
|
191682
193021
|
}
|
|
191683
193022
|
return root;
|
|
191684
193023
|
}
|
|
@@ -191717,10 +193056,10 @@ function reloadCommand(config, target, projectRef2, functionSlug) {
|
|
|
191717
193056
|
return [...command.split(" "), "--project-ref", safeToken(projectRef2 || "test", "project_ref"), "--target", targetConfigPath(target), ...functionSlug ? ["--function", safeToken(functionSlug, "function")] : []];
|
|
191718
193057
|
}
|
|
191719
193058
|
function sshArgs(connection, remoteCommand) {
|
|
191720
|
-
return ["-p", String(connection.port), "-i",
|
|
193059
|
+
return ["-p", String(connection.port), "-i", resolve14(connection.key), "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", `${connection.user}@${connection.host}`, ...remoteCommand];
|
|
191721
193060
|
}
|
|
191722
193061
|
function rsyncArgs(connection, source, destination, excludes, deleteRemote) {
|
|
191723
|
-
const args = ["-az", "--checksum", "--partial", "--protect-args", "-e", `ssh -p ${connection.port} -i ${
|
|
193062
|
+
const args = ["-az", "--checksum", "--partial", "--protect-args", "-e", `ssh -p ${connection.port} -i ${resolve14(connection.key)} -o BatchMode=yes -o StrictHostKeyChecking=yes`];
|
|
191724
193063
|
if (deleteRemote)
|
|
191725
193064
|
args.push("--delete-delay");
|
|
191726
193065
|
for (const exclude of excludes) {
|
|
@@ -191732,17 +193071,17 @@ function rsyncArgs(connection, source, destination, excludes, deleteRemote) {
|
|
|
191732
193071
|
return args;
|
|
191733
193072
|
}
|
|
191734
193073
|
async function syncOnce(args, options) {
|
|
191735
|
-
const root =
|
|
193074
|
+
const root = resolve14(String(args.project_dir || options.cwd || process.cwd()));
|
|
191736
193075
|
const projectConfig = await readProjectConfig3(root);
|
|
191737
193076
|
const config = projectConfig.dev || {};
|
|
191738
193077
|
const target = String(args.target || "project");
|
|
191739
193078
|
const source = targetDirectory(root, target, typeof args.function === "string" ? args.function : undefined, projectConfig);
|
|
191740
|
-
if (!
|
|
193079
|
+
if (!existsSync12(source))
|
|
191741
193080
|
throw new Error(`Dev source directory not found: ${source}`);
|
|
191742
193081
|
let compiled = false;
|
|
191743
193082
|
if (config.compile === true && target !== "db") {
|
|
191744
|
-
const compileRoot =
|
|
191745
|
-
const compileOutDir =
|
|
193083
|
+
const compileRoot = resolve14(root, config.compileRoot || ".");
|
|
193084
|
+
const compileOutDir = resolve14(root, config.compileOutDir || "generated");
|
|
191746
193085
|
const compilation = await compileProject({
|
|
191747
193086
|
rootDir: compileRoot,
|
|
191748
193087
|
outDir: compileOutDir,
|
|
@@ -191759,9 +193098,9 @@ async function syncOnce(args, options) {
|
|
|
191759
193098
|
const destination = remoteTargetRoot(remoteBase, target, slug);
|
|
191760
193099
|
const connection = connectionArgs(options, config, args);
|
|
191761
193100
|
const execute = options.execute || ((command, commandArgs, cwd) => runProcess(command, commandArgs, cwd));
|
|
191762
|
-
const
|
|
191763
|
-
if (
|
|
191764
|
-
throw new Error(`Remote dev prepare failed: ${
|
|
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}`}`);
|
|
191765
193104
|
const excludes = Array.isArray(config.excludes) ? config.excludes : ["node_modules", ".git", ".env*", "dist", ".supacloud"];
|
|
191766
193105
|
const sync = await execute("rsync", rsyncArgs(connection, source, destination, excludes, args.delete === true), root);
|
|
191767
193106
|
if (sync.exitCode !== 0)
|
|
@@ -191780,7 +193119,7 @@ function registerRemoteDevTools(server2, options = {}) {
|
|
|
191780
193119
|
if (["production", "prod"].includes((options.environment || "").toLowerCase()))
|
|
191781
193120
|
throw new Error("Remote dev mode is forbidden for production environments");
|
|
191782
193121
|
if (args.action === "status") {
|
|
191783
|
-
const root =
|
|
193122
|
+
const root = resolve14(String(args.project_dir || options.cwd || process.cwd()));
|
|
191784
193123
|
const config = await readDevConfig(root);
|
|
191785
193124
|
const connection = connectionArgs(options, config, args);
|
|
191786
193125
|
const execute = options.execute || ((command, commandArgs, cwd) => runProcess(command, commandArgs, cwd));
|
|
@@ -191794,7 +193133,7 @@ function registerRemoteDevTools(server2, options = {}) {
|
|
|
191794
193133
|
return { content: [{ type: "text", text: JSON.stringify(await migrateDatabase(args, options), null, 2) }] };
|
|
191795
193134
|
}
|
|
191796
193135
|
if (args.action === "watch") {
|
|
191797
|
-
const root =
|
|
193136
|
+
const root = resolve14(String(args.project_dir || options.cwd || process.cwd()));
|
|
191798
193137
|
const interval = Math.max(100, Math.min(1e4, Number(args.interval_ms || 300)));
|
|
191799
193138
|
let fingerprint = "";
|
|
191800
193139
|
let lastSync = null;
|
|
@@ -191813,9 +193152,9 @@ function registerRemoteDevTools(server2, options = {}) {
|
|
|
191813
193152
|
});
|
|
191814
193153
|
}
|
|
191815
193154
|
// package.json
|
|
191816
|
-
var
|
|
193155
|
+
var package_default4 = {
|
|
191817
193156
|
name: "@supacloud/cli",
|
|
191818
|
-
version: "0.
|
|
193157
|
+
version: "0.49.0",
|
|
191819
193158
|
description: "Project-scoped CLI for SupaCloud users",
|
|
191820
193159
|
type: "module",
|
|
191821
193160
|
main: "./dist/index.js",
|
|
@@ -191848,7 +193187,7 @@ var package_default = {
|
|
|
191848
193187
|
},
|
|
191849
193188
|
dependencies: {
|
|
191850
193189
|
"@sinclair/typebox": "^0.34.52",
|
|
191851
|
-
"@supacloud/compiler": "^0.
|
|
193190
|
+
"@supacloud/compiler": "^0.10.0",
|
|
191852
193191
|
"@supacloud/db": "^0.2.0",
|
|
191853
193192
|
fflate: "^0.8.3"
|
|
191854
193193
|
},
|
|
@@ -192082,6 +193421,8 @@ EXAMPLES
|
|
|
192082
193421
|
${preferredCommand} release postgrest_restart --ref abc123
|
|
192083
193422
|
${preferredCommand} release release_canary_fixture_stage_replay --ref abc123 --subject <uuid> --request_id <uuid>
|
|
192084
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
|
|
192085
193426
|
${preferredCommand} queue stats --queue emails
|
|
192086
193427
|
${preferredCommand} queue dlq --queue emails --limit 20
|
|
192087
193428
|
${preferredCommand} frontend list --ref abc123
|
|
@@ -192102,6 +193443,7 @@ EXAMPLES
|
|
|
192102
193443
|
${preferredCommand} branch promote --branch_ref preview123 --plan_checksum <sha256>
|
|
192103
193444
|
${preferredCommand} ai show_skill
|
|
192104
193445
|
${preferredCommand} ai install_skill --dry_run
|
|
193446
|
+
${preferredCommand} app init --name my-service
|
|
192105
193447
|
${preferredCommand} app generate --kind module --name billing
|
|
192106
193448
|
${preferredCommand} app generate --kind command --module billing --name issue-invoice
|
|
192107
193449
|
${preferredCommand} app compile --root .
|
|
@@ -192239,6 +193581,10 @@ function createCliTools(context, confirmProduction) {
|
|
|
192239
193581
|
Object.assign(tools, captureTools((server2) => registerDatabaseTools(server2, undefined, {
|
|
192240
193582
|
localOnly: true
|
|
192241
193583
|
})));
|
|
193584
|
+
Object.assign(tools, captureTools((server2) => registerReleaseTools(server2, undefined, {
|
|
193585
|
+
localOnly: true,
|
|
193586
|
+
projectRef: context.projectRef || undefined
|
|
193587
|
+
})));
|
|
192242
193588
|
Object.assign(tools, captureTools((server2) => registerRemoteDevTools(server2, {
|
|
192243
193589
|
cwd: process.cwd(),
|
|
192244
193590
|
host: process.env.SUPACLOUD_DEV_HOST || context.host,
|
|
@@ -192350,7 +193696,7 @@ function createCliTools(context, confirmProduction) {
|
|
|
192350
193696
|
async function main() {
|
|
192351
193697
|
const rawArgs = process.argv.slice(2);
|
|
192352
193698
|
if (rawArgs.length === 1 && rawArgs[0] === "--version") {
|
|
192353
|
-
console.log(
|
|
193699
|
+
console.log(package_default4.version);
|
|
192354
193700
|
return;
|
|
192355
193701
|
}
|
|
192356
193702
|
const globalOptions = parseGlobalOptions(rawArgs);
|