@supacloud/cli 0.116.0 → 0.117.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +672 -222
- package/dist/shared/tools/app-model-command-starter.d.ts +3 -0
- package/dist/shared/tools/app-model-command-starter.test.d.ts +1 -0
- package/dist/shared/tools/app-starter-database.d.ts +5 -3
- package/dist/shared/tools/app-starter-query.d.ts +1 -1
- package/dist/shared/tools/app-starter-tasks.d.ts +1 -1
- package/dist/shared/tools/app-starter-templates.d.ts +2 -1
- package/dist/shared/tools/app-tools.d.ts +1 -1
- package/dist/shared/tools/command-receipts.d.ts +1 -0
- package/dist/shared/tools/db-governance-tools.d.ts +1 -1
- package/dist/shared/tools/remote-dev-tools.d.ts +1 -7
- package/package.json +14 -10
- package/skills/supacloud/references/command-map.md +1 -1
- package/skills/supacloud/references/database-workflow.md +1 -1
package/dist/index.js
CHANGED
|
@@ -16560,7 +16560,7 @@ Actions: list, get_config, deploy, deploy_bundle, config, source, activate, dele
|
|
|
16560
16560
|
try {
|
|
16561
16561
|
if (/@ts-(?:ignore|nocheck|expect-error)\b/.test(sourceCode)) {
|
|
16562
16562
|
const { scanProductionSource } = await import("@supacloud/compiler");
|
|
16563
|
-
const suppression = scanProductionSource({ rootDir: tmpDir, include: ["index.ts"] }).find((diagnostic) => diagnostic.code === "source-type-suppression");
|
|
16563
|
+
const suppression = (await scanProductionSource({ rootDir: tmpDir, include: ["index.ts"] })).find((diagnostic) => diagnostic.code === "source-type-suppression");
|
|
16564
16564
|
if (suppression) {
|
|
16565
16565
|
return {
|
|
16566
16566
|
ok: false,
|
|
@@ -22198,34 +22198,38 @@ var starter_metadata_default = {
|
|
|
22198
22198
|
generatedBy: "supacloud/starter-metadata-v1",
|
|
22199
22199
|
packages: {
|
|
22200
22200
|
compiler: {
|
|
22201
|
-
version: "0.
|
|
22201
|
+
version: "0.57.0"
|
|
22202
22202
|
},
|
|
22203
22203
|
app: {
|
|
22204
|
-
version: "0.
|
|
22204
|
+
version: "0.38.0",
|
|
22205
22205
|
dependencies: {
|
|
22206
22206
|
rxjs: "7.8.2"
|
|
22207
22207
|
}
|
|
22208
22208
|
},
|
|
22209
22209
|
elysia: {
|
|
22210
|
-
version: "0.
|
|
22210
|
+
version: "0.40.0"
|
|
22211
22211
|
},
|
|
22212
22212
|
commands: {
|
|
22213
|
-
version: "0.
|
|
22213
|
+
version: "0.12.0"
|
|
22214
22214
|
},
|
|
22215
22215
|
contracts: {
|
|
22216
|
-
version: "0.
|
|
22216
|
+
version: "0.16.0"
|
|
22217
22217
|
},
|
|
22218
22218
|
db: {
|
|
22219
|
-
version: "0.
|
|
22220
|
-
|
|
22221
|
-
"
|
|
22219
|
+
version: "0.21.0",
|
|
22220
|
+
dependencies: {
|
|
22221
|
+
"@zenstackhq/orm": "3.10.0",
|
|
22222
|
+
"@zenstackhq/schema": "3.10.0",
|
|
22223
|
+
"@zenstackhq/plugin-policy": "3.10.0"
|
|
22222
22224
|
},
|
|
22223
22225
|
devDependencies: {
|
|
22224
|
-
"
|
|
22226
|
+
"@zenstackhq/cli": "3.10.0",
|
|
22227
|
+
prisma: "6.19.3",
|
|
22228
|
+
pg: "8.23.1"
|
|
22225
22229
|
}
|
|
22226
22230
|
},
|
|
22227
22231
|
sdk: {
|
|
22228
|
-
version: "0.
|
|
22232
|
+
version: "0.47.0",
|
|
22229
22233
|
peerDependencies: {
|
|
22230
22234
|
"@supabase/supabase-js": "^2.118.0"
|
|
22231
22235
|
}
|
|
@@ -22545,7 +22549,7 @@ export function createCompiledModules(): never {
|
|
|
22545
22549
|
throw new Error("Run bun run compile before starting the application");
|
|
22546
22550
|
}
|
|
22547
22551
|
`;
|
|
22548
|
-
function
|
|
22552
|
+
function baseTemplateFiles(name, sdkDependencies) {
|
|
22549
22553
|
return {
|
|
22550
22554
|
"package.json": json({
|
|
22551
22555
|
name,
|
|
@@ -22577,7 +22581,7 @@ function baseFiles(name, sdkDependencies) {
|
|
|
22577
22581
|
devDependencies: {
|
|
22578
22582
|
"@supacloud/compiler": `^${compilerMetadata.version}`,
|
|
22579
22583
|
"@types/bun": "^1.4.4",
|
|
22580
|
-
typescript: "
|
|
22584
|
+
typescript: "7.1.0-beta"
|
|
22581
22585
|
}
|
|
22582
22586
|
}),
|
|
22583
22587
|
"tsconfig.json": json({
|
|
@@ -22629,7 +22633,7 @@ export default defineSupacloudConfig();
|
|
|
22629
22633
|
}
|
|
22630
22634
|
function minimalTemplate(name, sdkDependencies) {
|
|
22631
22635
|
return {
|
|
22632
|
-
...
|
|
22636
|
+
...baseTemplateFiles(name, sdkDependencies),
|
|
22633
22637
|
"src/features/health/contracts.ts": `import { t } from "elysia";
|
|
22634
22638
|
export const HealthResult = t.Object({ ok: t.Boolean() });
|
|
22635
22639
|
`,
|
|
@@ -22743,6 +22747,516 @@ function appTemplateFiles(name, template, sdkDependencies) {
|
|
|
22743
22747
|
return minimalTemplate(name, sdkDependencies);
|
|
22744
22748
|
}
|
|
22745
22749
|
|
|
22750
|
+
// src/shared/tools/command-receipts.ts
|
|
22751
|
+
var COMMAND_RECEIPT_SQL = `CREATE SCHEMA IF NOT EXISTS supacloud_commands;
|
|
22752
|
+
REVOKE ALL ON SCHEMA supacloud_commands FROM PUBLIC;
|
|
22753
|
+
CREATE TABLE IF NOT EXISTS supacloud_commands.execution_receipts (
|
|
22754
|
+
tenant_id text NOT NULL,
|
|
22755
|
+
actor_id text NOT NULL,
|
|
22756
|
+
command text NOT NULL,
|
|
22757
|
+
operation_key text NOT NULL,
|
|
22758
|
+
kind text NOT NULL CHECK (kind IN ('transactional', 'external')),
|
|
22759
|
+
input_fingerprint text NOT NULL CHECK (input_fingerprint ~ '^[a-f0-9]{64}$'),
|
|
22760
|
+
input_payload text,
|
|
22761
|
+
dispatch_key uuid NOT NULL DEFAULT gen_random_uuid() UNIQUE,
|
|
22762
|
+
status text NOT NULL CHECK (status IN ('pending', 'unknown', 'confirmed', 'rejected')),
|
|
22763
|
+
audit_state text NOT NULL CHECK (audit_state IN ('pending', 'complete')),
|
|
22764
|
+
result jsonb,
|
|
22765
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
22766
|
+
updated_at timestamptz NOT NULL DEFAULT now(),
|
|
22767
|
+
PRIMARY KEY (tenant_id, actor_id, command, operation_key),
|
|
22768
|
+
CHECK ((status = 'confirmed') = (result IS NOT NULL)),
|
|
22769
|
+
CONSTRAINT execution_receipts_audit_terminal_check CHECK (
|
|
22770
|
+
(audit_state <> 'complete' OR status IN ('confirmed', 'rejected'))
|
|
22771
|
+
AND (status <> 'rejected' OR audit_state = 'complete')),
|
|
22772
|
+
CONSTRAINT execution_receipts_transactional_check CHECK (
|
|
22773
|
+
kind <> 'transactional' OR (status = 'confirmed' AND audit_state = 'complete'))
|
|
22774
|
+
);
|
|
22775
|
+
CREATE TABLE IF NOT EXISTS supacloud_commands.execution_audit (
|
|
22776
|
+
tenant_id text NOT NULL,
|
|
22777
|
+
actor_id text NOT NULL,
|
|
22778
|
+
command text NOT NULL,
|
|
22779
|
+
operation_key text NOT NULL,
|
|
22780
|
+
event text NOT NULL,
|
|
22781
|
+
details jsonb NOT NULL,
|
|
22782
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
22783
|
+
PRIMARY KEY (tenant_id, actor_id, command, operation_key),
|
|
22784
|
+
FOREIGN KEY (tenant_id, actor_id, command, operation_key)
|
|
22785
|
+
REFERENCES supacloud_commands.execution_receipts (tenant_id, actor_id, command, operation_key)
|
|
22786
|
+
);
|
|
22787
|
+
REVOKE ALL ON supacloud_commands.execution_receipts, supacloud_commands.execution_audit FROM PUBLIC;
|
|
22788
|
+
CREATE OR REPLACE FUNCTION supacloud_commands.protect_terminal_execution()
|
|
22789
|
+
RETURNS trigger LANGUAGE plpgsql SET search_path = '' AS $terminal$
|
|
22790
|
+
BEGIN
|
|
22791
|
+
IF OLD.status IN ('confirmed','rejected') AND (
|
|
22792
|
+
NEW.status IS DISTINCT FROM OLD.status OR NEW.result IS DISTINCT FROM OLD.result
|
|
22793
|
+
OR (OLD.audit_state = 'complete' AND NEW.audit_state IS DISTINCT FROM OLD.audit_state)) THEN
|
|
22794
|
+
RAISE EXCEPTION 'SUPACLOUD_COMMAND_TERMINAL_RECEIPT';
|
|
22795
|
+
END IF;
|
|
22796
|
+
RETURN NEW;
|
|
22797
|
+
END
|
|
22798
|
+
$terminal$;
|
|
22799
|
+
CREATE OR REPLACE TRIGGER execution_terminal_guard
|
|
22800
|
+
BEFORE UPDATE ON supacloud_commands.execution_receipts
|
|
22801
|
+
FOR EACH ROW EXECUTE FUNCTION supacloud_commands.protect_terminal_execution();
|
|
22802
|
+
|
|
22803
|
+
CREATE OR REPLACE FUNCTION supacloud_commands.require_rejection_audit()
|
|
22804
|
+
RETURNS trigger LANGUAGE plpgsql SET search_path = '' AS $rejection$
|
|
22805
|
+
BEGIN
|
|
22806
|
+
IF NEW.status = 'rejected' AND NOT EXISTS (
|
|
22807
|
+
SELECT FROM supacloud_commands.execution_audit a
|
|
22808
|
+
WHERE a.tenant_id=NEW.tenant_id AND a.actor_id=NEW.actor_id
|
|
22809
|
+
AND a.command=NEW.command AND a.operation_key=NEW.operation_key
|
|
22810
|
+
) THEN
|
|
22811
|
+
RAISE EXCEPTION 'SUPACLOUD_COMMAND_REJECTION_AUDIT_REQUIRED';
|
|
22812
|
+
END IF;
|
|
22813
|
+
RETURN NEW;
|
|
22814
|
+
END
|
|
22815
|
+
$rejection$;
|
|
22816
|
+
DROP TRIGGER IF EXISTS execution_rejection_audit ON supacloud_commands.execution_receipts;
|
|
22817
|
+
CREATE CONSTRAINT TRIGGER execution_rejection_audit
|
|
22818
|
+
AFTER INSERT OR UPDATE ON supacloud_commands.execution_receipts
|
|
22819
|
+
DEFERRABLE INITIALLY DEFERRED
|
|
22820
|
+
FOR EACH ROW WHEN (NEW.status = 'rejected')
|
|
22821
|
+
EXECUTE FUNCTION supacloud_commands.require_rejection_audit();
|
|
22822
|
+
`;
|
|
22823
|
+
|
|
22824
|
+
// src/shared/tools/app-model-command-starter.ts
|
|
22825
|
+
var json2 = (value) => JSON.stringify(value, null, 2) + `
|
|
22826
|
+
`;
|
|
22827
|
+
var MODEL = `datasource db {
|
|
22828
|
+
provider = "postgresql"
|
|
22829
|
+
url = env("DATABASE_URL")
|
|
22830
|
+
}
|
|
22831
|
+
plugin policy {
|
|
22832
|
+
provider = "@zenstackhq/plugin-policy"
|
|
22833
|
+
}
|
|
22834
|
+
type Principal {
|
|
22835
|
+
id String
|
|
22836
|
+
tenantId String
|
|
22837
|
+
canCreate Boolean
|
|
22838
|
+
canApprove Boolean
|
|
22839
|
+
@@auth()
|
|
22840
|
+
}
|
|
22841
|
+
enum OrderState {
|
|
22842
|
+
draft
|
|
22843
|
+
approved
|
|
22844
|
+
}
|
|
22845
|
+
model Order {
|
|
22846
|
+
tenantId String @map("tenant_id") @deny("update", true)
|
|
22847
|
+
id String @deny("update", true)
|
|
22848
|
+
ownerId String @map("owner_id") @deny("update", true)
|
|
22849
|
+
title String
|
|
22850
|
+
state OrderState @default(draft)
|
|
22851
|
+
version Int @default(1)
|
|
22852
|
+
@@id([tenantId, id])
|
|
22853
|
+
@@map("model_orders")
|
|
22854
|
+
@@allow("read", auth() != null && tenantId == auth().tenantId && (ownerId == auth().id || auth().canApprove))
|
|
22855
|
+
@@allow("create", auth() != null && auth().canCreate && tenantId == auth().tenantId && ownerId == auth().id && state == "draft" && version == 1)
|
|
22856
|
+
@@allow("update", auth() != null && auth().canApprove && tenantId == auth().tenantId)
|
|
22857
|
+
}
|
|
22858
|
+
`;
|
|
22859
|
+
var CONTRACTS = `import { Type, type Static, type TSchema } from "typebox";
|
|
22860
|
+
import { Compile } from "typebox/compile";
|
|
22861
|
+
|
|
22862
|
+
const Id = Type.String({ minLength: 1, maxLength: 100 });
|
|
22863
|
+
export const CreateInput = Type.Object({ id: Id, title: Type.String({ minLength: 1, maxLength: 200 }) }, { additionalProperties: false });
|
|
22864
|
+
export const ApproveInput = Type.Object({ id: Id, expectedVersion: Type.Integer({ minimum: 1 }) }, { additionalProperties: false });
|
|
22865
|
+
export const ApproveBody = Type.Object({ expectedVersion: Type.Integer({ minimum: 1 }) }, { additionalProperties: false });
|
|
22866
|
+
export const Params = Type.Object({ id: Id }, { additionalProperties: false });
|
|
22867
|
+
export const KeyHeaders = Type.Object({ "idempotency-key": Id });
|
|
22868
|
+
export const OrderResult = Type.Object({ id: Id, title: Type.String(), state: Type.Union([Type.Literal("draft"), Type.Literal("approved")]), version: Type.Integer() }, { additionalProperties: false });
|
|
22869
|
+
export const Decision = Type.Union([
|
|
22870
|
+
Type.Object({ outcome: Type.Literal("applied"), order: OrderResult }, { additionalProperties: false }),
|
|
22871
|
+
Type.Object({ outcome: Type.Literal("conflict"), order: Type.Null() }, { additionalProperties: false }),
|
|
22872
|
+
]);
|
|
22873
|
+
export const ReceiptResult = Type.Object({ tenantId: Type.String(), actorId: Type.String(), command: Type.String(), operationId: Type.String(), dispatchKey: Type.String(), status: Type.Literal("confirmed"), audit: Type.Literal("complete"), result: Decision }, { additionalProperties: false });
|
|
22874
|
+
export const ReadResult = Type.Object({ order: Type.Union([OrderResult, Type.Null()]) }, { additionalProperties: false });
|
|
22875
|
+
export type CreateInput = Static<typeof CreateInput>;
|
|
22876
|
+
export type ApproveInput = Static<typeof ApproveInput>;
|
|
22877
|
+
export type Decision = Static<typeof Decision>;
|
|
22878
|
+
export type OrderResult = Static<typeof OrderResult>;
|
|
22879
|
+
export type Principal = { readonly id: string; readonly tenantId: string; readonly canCreate: boolean; readonly canApprove: boolean };
|
|
22880
|
+
export type OrderReceipt = Static<typeof ReceiptResult>;
|
|
22881
|
+
|
|
22882
|
+
export function decoder<S extends TSchema>(schema: S): (value: unknown) => Static<S> {
|
|
22883
|
+
const compiled = Compile(schema);
|
|
22884
|
+
return value => { if (!compiled.Check(value)) throw new TypeError("Invalid order contract"); return value; };
|
|
22885
|
+
}
|
|
22886
|
+
export const decodeCreate = decoder(CreateInput);
|
|
22887
|
+
export const decodeApprove = decoder(ApproveInput);
|
|
22888
|
+
export const decodeDecision = decoder(Decision);
|
|
22889
|
+
export const decodeOrder = decoder(OrderResult);
|
|
22890
|
+
export const decodeReceipt = decoder(ReceiptResult);
|
|
22891
|
+
export interface OrderPort {
|
|
22892
|
+
create(context: unknown, key: string, input: CreateInput): Promise<OrderReceipt>;
|
|
22893
|
+
approve(context: unknown, key: string, input: ApproveInput): Promise<OrderReceipt>;
|
|
22894
|
+
read(context: unknown, id: string): Promise<{ order: OrderResult | null }>;
|
|
22895
|
+
}
|
|
22896
|
+
|
|
22897
|
+
export type OrderFailure = { readonly _tag: "OrderDenied" } | { readonly _tag: "OrderInvalid" }
|
|
22898
|
+
| { readonly _tag: "OrderReplayConflict" } | { readonly _tag: "OrderUnavailable" };
|
|
22899
|
+
export function publicFailure(error: unknown): OrderFailure {
|
|
22900
|
+
const code = error instanceof Error && "code" in error ? error.code : undefined;
|
|
22901
|
+
if (code === "COMMAND_REJECTED") return { _tag: "OrderDenied" };
|
|
22902
|
+
if (code === "COMMAND_INPUT_INVALID") return { _tag: "OrderInvalid" };
|
|
22903
|
+
if (code === "COMMAND_IDEMPOTENCY_CONFLICT") return { _tag: "OrderReplayConflict" };
|
|
22904
|
+
return { _tag: "OrderUnavailable" };
|
|
22905
|
+
}
|
|
22906
|
+
`;
|
|
22907
|
+
var COMMANDS = `import { Command, defineOperationAspect, type Aspect } from "@supacloud/app/core";
|
|
22908
|
+
import { createTypeBoxTransactionalCommand } from "@supacloud/commands/typebox";
|
|
22909
|
+
import { plaintextCommandInput } from "@supacloud/commands";
|
|
22910
|
+
import { CommandError, type CommandIdentity, type CommandStore } from "@supacloud/contracts";
|
|
22911
|
+
import type { ModelCommandTransaction } from "@supacloud/db/zenstack";
|
|
22912
|
+
import type { schema } from "../../../zenstack/generated/schema";
|
|
22913
|
+
import { Type } from "typebox";
|
|
22914
|
+
import { CreateInput, ApproveInput, Decision, decodeApprove, decodeDecision, decodeOrder, decoder, type Principal } from "./contracts";
|
|
22915
|
+
|
|
22916
|
+
type Tx = ModelCommandTransaction<typeof schema>;
|
|
22917
|
+
type Store = CommandStore<Tx>;
|
|
22918
|
+
const decodeCapabilities = decoder(Type.Object({ canApprove: Type.Boolean() }, { additionalProperties: false }));
|
|
22919
|
+
export const approvalAspect = defineOperationAspect({
|
|
22920
|
+
kind: "command", name: "orders.approve", input: decodeApprove, result: decodeDecision,
|
|
22921
|
+
capabilities: context => decodeCapabilities(context.services?.["approval"]),
|
|
22922
|
+
}, async ({ capabilities }, next) => {
|
|
22923
|
+
if (!capabilities.canApprove) throw new CommandError("COMMAND_REJECTED");
|
|
22924
|
+
return await next();
|
|
22925
|
+
});
|
|
22926
|
+
|
|
22927
|
+
function sameActor(identity: CommandIdentity, principal: Principal): boolean {
|
|
22928
|
+
return identity.actorId === principal.id && identity.tenantId === principal.tenantId;
|
|
22929
|
+
}
|
|
22930
|
+
|
|
22931
|
+
@Command({ name: "orders.create", permission: "orders:create", rpc: "modelOrders", transaction: "required", idempotency: "required", audit: "orders.create.decided" })
|
|
22932
|
+
export class CreateOrder {
|
|
22933
|
+
private readonly executor;
|
|
22934
|
+
constructor(store: Store, principal: Principal) {
|
|
22935
|
+
this.executor = createTypeBoxTransactionalCommand({
|
|
22936
|
+
name: "orders.create", store, schemas: { input: CreateInput, result: Decision },
|
|
22937
|
+
// This sample contains no secret inputs. Use an authenticated codec for sensitive data.
|
|
22938
|
+
inputCodec: plaintextCommandInput,
|
|
22939
|
+
authorize: identity => sameActor(identity, principal) && principal.canCreate ? "allow" : "deny",
|
|
22940
|
+
audit: { event: "orders.create.decided", details: (input, result) => ({ id: input.id, outcome: result.outcome }) },
|
|
22941
|
+
execute: async (tx, input): Promise<Decision> => {
|
|
22942
|
+
const created = await tx.db.order.createMany({ data: [{ ...input, tenantId: principal.tenantId, ownerId: principal.id, state: "draft", version: 1 }], skipDuplicates: true });
|
|
22943
|
+
if (created.count !== 1) return { outcome: "conflict", order: null };
|
|
22944
|
+
const row = await tx.db.order.findUniqueOrThrow({ where: { tenantId_id: { tenantId: principal.tenantId, id: input.id } }, select: { id: true, title: true, state: true, version: true } });
|
|
22945
|
+
return { outcome: "applied", order: decodeOrder(row) };
|
|
22946
|
+
},
|
|
22947
|
+
});
|
|
22948
|
+
}
|
|
22949
|
+
execute(identity: CommandIdentity, key: string, input: CreateInput, signal?: AbortSignal) {
|
|
22950
|
+
return this.executor.execute(identity, key, input, signal);
|
|
22951
|
+
}
|
|
22952
|
+
}
|
|
22953
|
+
|
|
22954
|
+
@Command({ name: "orders.approve", permission: "orders:approve", rpc: "modelOrders", transaction: "required", idempotency: "required", audit: "orders.approval.decided", aspects: [approvalAspect] })
|
|
22955
|
+
export class ApproveOrder {
|
|
22956
|
+
private readonly executor;
|
|
22957
|
+
constructor(store: Store, principal: Principal, pipeline: Aspect) {
|
|
22958
|
+
this.executor = createTypeBoxTransactionalCommand({
|
|
22959
|
+
name: "orders.approve", store, schemas: { input: ApproveInput, result: Decision }, inputCodec: plaintextCommandInput,
|
|
22960
|
+
authorize: identity => sameActor(identity, principal) && principal.canApprove ? "allow" : "deny",
|
|
22961
|
+
audit: { event: "orders.approval.decided", details: (input, result) => ({ id: input.id, outcome: result.outcome }) },
|
|
22962
|
+
execute: async (tx, input) => decodeDecision(await pipeline({
|
|
22963
|
+
kind: "command", name: "orders.approve", input,
|
|
22964
|
+
services: { approval: { canApprove: principal.canApprove } },
|
|
22965
|
+
}, async (): Promise<Decision> => {
|
|
22966
|
+
const changed = await tx.db.order.updateMany({
|
|
22967
|
+
where: { tenantId: principal.tenantId, id: input.id, state: "draft", version: input.expectedVersion },
|
|
22968
|
+
data: { state: "approved", version: { increment: 1 } },
|
|
22969
|
+
});
|
|
22970
|
+
if (changed.count !== 1) return { outcome: "conflict", order: null };
|
|
22971
|
+
const row = await tx.db.order.findUniqueOrThrow({ where: { tenantId_id: { tenantId: principal.tenantId, id: input.id } }, select: { id: true, title: true, state: true, version: true } });
|
|
22972
|
+
return { outcome: "applied", order: decodeOrder(row) };
|
|
22973
|
+
})),
|
|
22974
|
+
});
|
|
22975
|
+
}
|
|
22976
|
+
execute(identity: CommandIdentity, key: string, input: ApproveInput, signal?: AbortSignal) {
|
|
22977
|
+
return this.executor.execute(identity, key, input, signal);
|
|
22978
|
+
}
|
|
22979
|
+
}
|
|
22980
|
+
`;
|
|
22981
|
+
var HTTP = `import { Effect } from "effect";
|
|
22982
|
+
import { Body, Controller, Get, Headers, Inject, Injectable, InjectionToken, Module, Param, Post, REQUEST_CONTEXT } from "@supacloud/app/core";
|
|
22983
|
+
import { ApproveOrder, CreateOrder } from "./commands";
|
|
22984
|
+
import { CreateInput, ApproveBody, Params, KeyHeaders, ReadResult, ReceiptResult, publicFailure, type OrderFailure, type OrderPort, type OrderReceipt } from "./contracts";
|
|
22985
|
+
|
|
22986
|
+
export const ORDERS = new InjectionToken<OrderPort>("orders");
|
|
22987
|
+
const errors = [
|
|
22988
|
+
{ tag: "OrderDenied", status: 403, code: "ORDER_DENIED" },
|
|
22989
|
+
{ tag: "OrderInvalid", status: 400, code: "ORDER_INVALID" },
|
|
22990
|
+
{ tag: "OrderReplayConflict", status: 409, code: "ORDER_REPLAY_CONFLICT" },
|
|
22991
|
+
{ tag: "OrderUnavailable", status: 503, code: "ORDER_UNAVAILABLE" },
|
|
22992
|
+
] as const;
|
|
22993
|
+
|
|
22994
|
+
@Injectable({ scope: "request" })
|
|
22995
|
+
@Controller("/orders")
|
|
22996
|
+
export class OrdersController {
|
|
22997
|
+
constructor(@Inject(ORDERS) private readonly orders: OrderPort, @Inject(REQUEST_CONTEXT) private readonly context: unknown) {}
|
|
22998
|
+
@Post("/", { body: CreateInput, headers: KeyHeaders, idempotency: "required", responses: { 200: ReceiptResult }, effect: { required: true, dependencies: [], errors: errors, retry: "none" } })
|
|
22999
|
+
create(@Body() input: CreateInput, @Headers("idempotency-key") key: string): Effect.Effect<OrderReceipt, OrderFailure, never> {
|
|
23000
|
+
return Effect.tryPromise({ try: () => this.orders.create(this.context, key, input), catch: publicFailure });
|
|
23001
|
+
}
|
|
23002
|
+
@Post("/:id/approve", { params: Params, body: ApproveBody, headers: KeyHeaders, idempotency: "required", responses: { 200: ReceiptResult }, effect: { required: true, dependencies: [], errors: errors, retry: "none" } })
|
|
23003
|
+
approve(@Param("id") id: string, @Body() input: { expectedVersion: number }, @Headers("idempotency-key") key: string): Effect.Effect<OrderReceipt, OrderFailure, never> {
|
|
23004
|
+
return Effect.tryPromise({ try: () => this.orders.approve(this.context, key, { id, expectedVersion: input.expectedVersion }), catch: publicFailure });
|
|
23005
|
+
}
|
|
23006
|
+
@Get("/:id", { params: Params, responses: { 200: ReadResult }, effect: { required: true, dependencies: [], errors: errors, retry: "none" } })
|
|
23007
|
+
read(@Param("id") id: string): Effect.Effect<Awaited<ReturnType<OrderPort["read"]>>, OrderFailure, never> {
|
|
23008
|
+
return Effect.tryPromise({ try: () => this.orders.read(this.context, id), catch: publicFailure });
|
|
23009
|
+
}
|
|
23010
|
+
}
|
|
23011
|
+
|
|
23012
|
+
@Module({ name: "orders", tags: ["type:feature"], controllers: [OrdersController], commands: [CreateOrder, ApproveOrder] })
|
|
23013
|
+
export class OrdersModule {}
|
|
23014
|
+
`;
|
|
23015
|
+
var HOST = `import type { SQL } from "bun";
|
|
23016
|
+
import { createApplication, ApplicationError, type CompiledModule } from "@supacloud/elysia";
|
|
23017
|
+
import { createZenStackDatabase } from "@supacloud/db/zenstack";
|
|
23018
|
+
import { CommandError } from "@supacloud/contracts";
|
|
23019
|
+
import { schema } from "../../zenstack/generated/schema";
|
|
23020
|
+
import { createCompiledModules } from "../../generated/application";
|
|
23021
|
+
import { CreateOrder, ApproveOrder } from "../features/orders/commands";
|
|
23022
|
+
import { decodeApprove, decodeCreate, decodeOrder, decodeReceipt, type ApproveInput, type Principal, type OrderPort } from "../features/orders/contracts";
|
|
23023
|
+
|
|
23024
|
+
export interface ActorBinding { readonly id: string; readonly tenantId: string }
|
|
23025
|
+
export interface VerifiedClaim { readonly actor: ActorBinding; readonly operationId: string; readonly input: ApproveInput }
|
|
23026
|
+
export interface IdentityAuthority {
|
|
23027
|
+
verifyHttp(request: Request): Promise<ActorBinding>;
|
|
23028
|
+
// Verify a claimed job's issuer/project/actor and original operation key; do not trust its JSON fields.
|
|
23029
|
+
verifyWorker(claim: unknown): Promise<VerifiedClaim>;
|
|
23030
|
+
// Resolve current access for every HTTP or worker invocation, including receipt replay.
|
|
23031
|
+
resolve(actor: ActorBinding): Promise<Principal | null>;
|
|
23032
|
+
}
|
|
23033
|
+
|
|
23034
|
+
export async function createModelOrderHost(pool: SQL, authority: IdentityAuthority) {
|
|
23035
|
+
const roles = await pool<unknown[]>\`SELECT rolsuper, rolbypassrls, pg_has_role(current_user, 'model_orders_app', 'USAGE') AS allowed,
|
|
23036
|
+
EXISTS (SELECT FROM pg_class WHERE oid IN ('public.model_orders'::regclass, 'supacloud_commands.execution_receipts'::regclass, 'supacloud_commands.execution_audit'::regclass)
|
|
23037
|
+
AND pg_has_role(current_user, relowner, 'MEMBER')) AS owns_data
|
|
23038
|
+
FROM pg_roles WHERE rolname=current_user\`;
|
|
23039
|
+
const role: unknown = roles[0];
|
|
23040
|
+
if (!role || typeof role !== "object" || !("rolsuper" in role) || role.rolsuper !== false
|
|
23041
|
+
|| !("rolbypassrls" in role) || role.rolbypassrls !== false || !("allowed" in role) || role.allowed !== true
|
|
23042
|
+
|| !("owns_data" in role) || role.owns_data !== false) {
|
|
23043
|
+
throw new Error("Use a non-owner application login with model_orders_app membership");
|
|
23044
|
+
}
|
|
23045
|
+
const database = createZenStackDatabase(schema, pool, {});
|
|
23046
|
+
const modules: CompiledModule[] = createCompiledModules();
|
|
23047
|
+
const ordersModule = modules.find(module => module.name === "orders");
|
|
23048
|
+
const approval = ordersModule?.commands?.find(command => command.name === "orders.approve")?.aspectPipeline;
|
|
23049
|
+
if (!approval) { await database.dispose(); throw new Error("Compile the orders command and its aspect first"); }
|
|
23050
|
+
const bindings = new WeakMap<object, { actor: ActorBinding; signal: AbortSignal | undefined }>();
|
|
23051
|
+
const issue = (actor: ActorBinding, signal?: AbortSignal): object => {
|
|
23052
|
+
if (!actor || typeof actor.id !== "string" || !actor.id || typeof actor.tenantId !== "string" || !actor.tenantId) {
|
|
23053
|
+
throw new ApplicationError("Verified actor required", { status: 401, code: "IDENTITY_REQUIRED" });
|
|
23054
|
+
}
|
|
23055
|
+
const context = Object.freeze({ requestId: crypto.randomUUID() });
|
|
23056
|
+
bindings.set(context, { actor: Object.freeze({ id: actor.id, tenantId: actor.tenantId }), signal });
|
|
23057
|
+
return context;
|
|
23058
|
+
};
|
|
23059
|
+
const bind = async (context: unknown) => {
|
|
23060
|
+
const issued = context !== null && typeof context === "object" ? bindings.get(context) : undefined;
|
|
23061
|
+
if (!issued) throw new CommandError("COMMAND_REJECTED");
|
|
23062
|
+
const resolved = await authority.resolve(issued.actor);
|
|
23063
|
+
if (!resolved || resolved.id !== issued.actor.id || resolved.tenantId !== issued.actor.tenantId
|
|
23064
|
+
|| typeof resolved.canCreate !== "boolean" || typeof resolved.canApprove !== "boolean") throw new CommandError("COMMAND_REJECTED");
|
|
23065
|
+
const principal = Object.freeze({ id: resolved.id, tenantId: resolved.tenantId, canCreate: resolved.canCreate, canApprove: resolved.canApprove });
|
|
23066
|
+
return { principal, signal: issued.signal, identity: { tenantId: principal.tenantId, actorId: principal.id }, scoped: database.forIdentity(principal) };
|
|
23067
|
+
};
|
|
23068
|
+
const port: OrderPort = {
|
|
23069
|
+
create: async (context, key, input) => {
|
|
23070
|
+
const bound = await bind(context);
|
|
23071
|
+
return decodeReceipt(await new CreateOrder(bound.scoped.commandStore, bound.principal).execute(bound.identity, key, decodeCreate(input), bound.signal));
|
|
23072
|
+
},
|
|
23073
|
+
approve: async (context, key, input) => {
|
|
23074
|
+
const bound = await bind(context);
|
|
23075
|
+
return decodeReceipt(await new ApproveOrder(bound.scoped.commandStore, bound.principal, approval).execute(bound.identity, key, decodeApprove(input), bound.signal));
|
|
23076
|
+
},
|
|
23077
|
+
read: async (context, id) => {
|
|
23078
|
+
const bound = await bind(context);
|
|
23079
|
+
const row = await bound.scoped.models.order.findUnique({ where: { tenantId_id: { tenantId: bound.principal.tenantId, id } }, select: { id: true, title: true, state: true, version: true } });
|
|
23080
|
+
return { order: row ? decodeOrder(row) : null };
|
|
23081
|
+
},
|
|
23082
|
+
};
|
|
23083
|
+
const app = createApplication({
|
|
23084
|
+
name: "model-orders", modules, deps: { orders: port },
|
|
23085
|
+
requestContext: async (request, _context, signal) => issue(await authority.verifyHttp(request), signal),
|
|
23086
|
+
// These handlers enter the durable facade themselves. Accidental route-level
|
|
23087
|
+
// command binding must fail, rather than adding a second governance boundary.
|
|
23088
|
+
commandExecutor: () => { throw new ApplicationError("Use the identity-bound order facade", { code: "COMMAND_BOUNDARY_HANDLER_OWNED" }); },
|
|
23089
|
+
});
|
|
23090
|
+
return {
|
|
23091
|
+
app,
|
|
23092
|
+
worker: async (claim: unknown, signal?: AbortSignal) => {
|
|
23093
|
+
const verified = await authority.verifyWorker(claim);
|
|
23094
|
+
return port.approve(issue(verified.actor, signal), verified.operationId, decodeApprove(verified.input));
|
|
23095
|
+
},
|
|
23096
|
+
// The host owns pool.close(); stop HTTP/worker intake and drain it before disposal.
|
|
23097
|
+
dispose: () => database.dispose(),
|
|
23098
|
+
};
|
|
23099
|
+
}
|
|
23100
|
+
`;
|
|
23101
|
+
var MIGRATION = `CREATE TYPE "OrderState" AS ENUM ('draft', 'approved');
|
|
23102
|
+
CREATE TABLE public.model_orders (
|
|
23103
|
+
tenant_id text NOT NULL, id text NOT NULL, owner_id text NOT NULL, title text NOT NULL,
|
|
23104
|
+
state "OrderState" NOT NULL DEFAULT 'draft', version integer NOT NULL DEFAULT 1 CHECK (version > 0),
|
|
23105
|
+
PRIMARY KEY (tenant_id, id)
|
|
23106
|
+
);
|
|
23107
|
+
DO $role$ BEGIN
|
|
23108
|
+
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname='model_orders_app') THEN CREATE ROLE model_orders_app NOLOGIN; END IF;
|
|
23109
|
+
END $role$;
|
|
23110
|
+
REVOKE ALL ON public.model_orders FROM PUBLIC;
|
|
23111
|
+
ALTER TABLE public.model_orders ENABLE ROW LEVEL SECURITY;
|
|
23112
|
+
-- Only the trusted model host may use this role. Tenant/owner filtering is enforced by ZenStack.
|
|
23113
|
+
-- Do not grant this role to PostgREST/browser users; those paths need their own row policies.
|
|
23114
|
+
CREATE POLICY model_orders_host ON public.model_orders TO model_orders_app USING (true) WITH CHECK (true);
|
|
23115
|
+
GRANT USAGE ON SCHEMA public, supacloud_commands TO model_orders_app;
|
|
23116
|
+
GRANT SELECT, INSERT, UPDATE ON public.model_orders TO model_orders_app;
|
|
23117
|
+
GRANT SELECT, INSERT, UPDATE ON supacloud_commands.execution_receipts TO model_orders_app;
|
|
23118
|
+
GRANT SELECT, INSERT ON supacloud_commands.execution_audit TO model_orders_app;
|
|
23119
|
+
`;
|
|
23120
|
+
function modelCommandTemplateFiles(name, sdk) {
|
|
23121
|
+
const { app, compiler, elysia, commands, contracts, db } = starter_metadata_default.packages;
|
|
23122
|
+
const files = baseTemplateFiles(name, sdk);
|
|
23123
|
+
delete files["scripts/dev.ts"];
|
|
23124
|
+
delete files["scripts/serve.ts"];
|
|
23125
|
+
const receiptFunctions = {};
|
|
23126
|
+
for (const match of COMMAND_RECEIPT_SQL.matchAll(/CREATE OR REPLACE FUNCTION (supacloud_commands\.(\w+))\(\)[\s\S]+?\n\$(\w+)\$;/g)) {
|
|
23127
|
+
receiptFunctions[`db/functions/${match[2]}.sql`] = match[0] + `
|
|
23128
|
+
`;
|
|
23129
|
+
}
|
|
23130
|
+
if (Object.keys(receiptFunctions).length !== 2)
|
|
23131
|
+
throw new Error("Receipt function sources changed; update the model starter");
|
|
23132
|
+
return {
|
|
23133
|
+
...files,
|
|
23134
|
+
...receiptFunctions,
|
|
23135
|
+
"package.json": json2({
|
|
23136
|
+
name,
|
|
23137
|
+
version: "0.0.0",
|
|
23138
|
+
private: true,
|
|
23139
|
+
type: "module",
|
|
23140
|
+
engines: { bun: ">=1.4.4" },
|
|
23141
|
+
scripts: {
|
|
23142
|
+
"db:generate": "supacloud-model generate && supacloud-db generate",
|
|
23143
|
+
"db:check": "supacloud-model check && supacloud-db check",
|
|
23144
|
+
"db:diff": "supacloud-model diff",
|
|
23145
|
+
"db:pull": "supacloud-model pull",
|
|
23146
|
+
compile: "supacloud-compiler compile",
|
|
23147
|
+
"check:generated": "supacloud-compiler check",
|
|
23148
|
+
typecheck: "tsc --noEmit",
|
|
23149
|
+
check: "bun run db:check && bun run check:generated && bun run typecheck",
|
|
23150
|
+
test: "bun test",
|
|
23151
|
+
build: "bun run db:check && bun run compile && bun run typecheck && bun build src/application.ts --target bun --outdir output/supacloud",
|
|
23152
|
+
dev: "bun --no-env-file scripts/environment.ts development bun scripts/serve-model.ts"
|
|
23153
|
+
},
|
|
23154
|
+
dependencies: {
|
|
23155
|
+
"@supacloud/app": "^" + app.version,
|
|
23156
|
+
"@supacloud/elysia": "^" + elysia.version,
|
|
23157
|
+
"@supacloud/commands": "^" + commands.version,
|
|
23158
|
+
"@supacloud/contracts": "^" + contracts.version,
|
|
23159
|
+
"@supacloud/db": "^" + db.version,
|
|
23160
|
+
...db.dependencies,
|
|
23161
|
+
typebox: "1.4.3",
|
|
23162
|
+
effect: "4.0.5",
|
|
23163
|
+
elysia: "2.0.0-rc.1",
|
|
23164
|
+
...sdk
|
|
23165
|
+
},
|
|
23166
|
+
devDependencies: { "@supacloud/compiler": "^" + compiler.version, ...db.devDependencies, "@types/bun": "^1.4.4", typescript: "7.1.0-beta" }
|
|
23167
|
+
}),
|
|
23168
|
+
"supacloud.config.ts": `import { defineSupacloudConfig } from "@supacloud/compiler";
|
|
23169
|
+
export default defineSupacloudConfig({
|
|
23170
|
+
databaseGovernance: { mode: "check" },
|
|
23171
|
+
commandCapabilities: { requirePersistentAdapters: true, permission: true, audit: true, idempotency: true, transaction: true,
|
|
23172
|
+
rpc: { modelOrders: { boundary: "database", transaction: true, audit: true, idempotency: true } } },
|
|
23173
|
+
});
|
|
23174
|
+
`,
|
|
23175
|
+
"database.sources.json": json2({ version: 1, schema: ["zenstack/schema.zmodel", "zenstack/generated/schema.ts"], functions: "db/functions", migrations: "migrations", contracts: "db/contracts", audit: "output/database-audit", consumers: ["src", "scripts", "tests"], auditConsumers: [], trustedHosts: ["src/host", "src/application.ts"], role: "model_orders_app" }),
|
|
23176
|
+
"zenstack/schema.zmodel": MODEL,
|
|
23177
|
+
"migrations/001-command-receipts.sql": COMMAND_RECEIPT_SQL,
|
|
23178
|
+
"migrations/002-model-orders.sql": MIGRATION,
|
|
23179
|
+
"db/functions/README.md": `Maintain additional PostgreSQL functions and explicit ACL here. No RPC is required for this model recipe.
|
|
23180
|
+
`,
|
|
23181
|
+
"db/modules.ts": `import { defineDatabaseModule } from "@supacloud/db";
|
|
23182
|
+
export default defineDatabaseModule({ name: "orders", tables: ["public.model_orders"], policies: [
|
|
23183
|
+
{ name: "model_orders_host", table: "public.model_orders", operation: "all", roles: ["model_orders_app"], source: "migrations/002-model-orders.sql", tests: ["tests/database-governance.sql"] },
|
|
23184
|
+
] });
|
|
23185
|
+
`,
|
|
23186
|
+
"tests/database-governance.sql": `BEGIN READ ONLY;
|
|
23187
|
+
DO $check$ BEGIN
|
|
23188
|
+
IF NOT (SELECT relrowsecurity FROM pg_class WHERE oid='public.model_orders'::regclass) THEN
|
|
23189
|
+
RAISE EXCEPTION 'model_orders RLS is required';
|
|
23190
|
+
END IF;
|
|
23191
|
+
IF NOT EXISTS (SELECT FROM pg_policies WHERE schemaname='public' AND tablename='model_orders'
|
|
23192
|
+
AND policyname='model_orders_host' AND roles=ARRAY['model_orders_app']::name[] AND cmd='ALL') THEN
|
|
23193
|
+
RAISE EXCEPTION 'model_orders trusted host policy is required';
|
|
23194
|
+
END IF;
|
|
23195
|
+
END $check$;
|
|
23196
|
+
ROLLBACK;
|
|
23197
|
+
`,
|
|
23198
|
+
"src/features/orders/contracts.ts": CONTRACTS,
|
|
23199
|
+
"src/features/orders/commands.ts": COMMANDS,
|
|
23200
|
+
"src/features/orders/orders.ts": HTTP,
|
|
23201
|
+
"src/app.module.ts": `import { Module } from "@supacloud/app/core";
|
|
23202
|
+
import { OrdersModule } from "./features/orders/orders";
|
|
23203
|
+
@Module({ name: "app", tags: ["type:root"], imports: [OrdersModule] })
|
|
23204
|
+
export class AppModule {}
|
|
23205
|
+
`,
|
|
23206
|
+
"src/host/model-orders.ts": HOST,
|
|
23207
|
+
"src/application.ts": `export { createModelOrderHost } from "./host/model-orders";
|
|
23208
|
+
export type { IdentityAuthority, ActorBinding, VerifiedClaim } from "./host/model-orders";
|
|
23209
|
+
`,
|
|
23210
|
+
"scripts/serve-model.ts": `import { SQL } from "bun";
|
|
23211
|
+
import { createModelOrderHost, type IdentityAuthority } from "../src/application";
|
|
23212
|
+
// Local bootstrap accepts an explicitly supplied identity authority, never a built-in production login.
|
|
23213
|
+
if (process.env["APP_ENV"] !== "development") throw new Error("Development entry only");
|
|
23214
|
+
const raw = process.env["SUPACLOUD_MODEL_DATABASE_URL"];
|
|
23215
|
+
const authorityModule = process.env["MODEL_IDENTITY_MODULE"];
|
|
23216
|
+
if (!raw || !authorityModule) throw new Error("Set a local SUPACLOUD_MODEL_DATABASE_URL and MODEL_IDENTITY_MODULE exporting authority");
|
|
23217
|
+
const url = new URL(raw);
|
|
23218
|
+
if (!["postgres:", "postgresql:"].includes(url.protocol) || !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) || url.search || url.hash) throw new Error("Explicit loopback database required");
|
|
23219
|
+
const loaded: unknown = await import(authorityModule);
|
|
23220
|
+
if (!loaded || typeof loaded !== "object" || !("authority" in loaded) || !loaded.authority || typeof loaded.authority !== "object") throw new Error("Missing identity authority");
|
|
23221
|
+
const authority = loaded.authority;
|
|
23222
|
+
for (const key of ["verifyHttp", "verifyWorker", "resolve"] as const) {
|
|
23223
|
+
if (!(key in authority) || typeof Reflect.get(authority, key) !== "function") throw new Error("Incomplete identity authority");
|
|
23224
|
+
}
|
|
23225
|
+
const pool = new SQL(raw);
|
|
23226
|
+
const host = await createModelOrderHost(pool, authority as IdentityAuthority);
|
|
23227
|
+
const server = Bun.serve({ hostname: "127.0.0.1", port: Number(process.env["PORT"] ?? "3000"), fetch: request => host.app.handle(request) });
|
|
23228
|
+
const stop = async () => { await server.stop(); await host.dispose(); await pool.close(); };
|
|
23229
|
+
process.once("SIGINT", () => { void stop(); });
|
|
23230
|
+
process.once("SIGTERM", () => { void stop(); });
|
|
23231
|
+
console.log("Model orders: " + server.url);
|
|
23232
|
+
`,
|
|
23233
|
+
"AGENTS.md": `# Model command development
|
|
23234
|
+
|
|
23235
|
+
Maintain ZModel and TypeBox contracts. Regenerate and commit model/source/compiled artifacts together. Business writes use transaction.db inside the durable command. HTTP and worker use the same facade and original operation key. Bind trusted identity at src/host; resolve current access on every call. The dedicated database role is private to this host, never a browser/PostgREST role. Keep the compiled approval aspect inside the command transaction. Do not fake capabilities, replace results, retry writes in aspects, or add another receipt/audit store. Daily changes run one related test file and git diff --check.
|
|
23236
|
+
`,
|
|
23237
|
+
"README.md": `# ${name}
|
|
23238
|
+
|
|
23239
|
+
Model-backed order creation and approval use ZenStack + Bun SQL. HTTP and the worker handler share the same durable Command, compiled approval aspect, identity policy, receipt and transaction.
|
|
23240
|
+
|
|
23241
|
+
1. Install matching published package versions: bun install.
|
|
23242
|
+
2. Run bun run db:generate, bun run compile, then bun run check. Commit generated artifacts.
|
|
23243
|
+
3. Review migrations/ and apply through the existing SupaCloud db plan/apply flow to an explicitly selected local/shadow database. Startup never migrates. Provision a non-owner login with model_orders_app membership separately.
|
|
23244
|
+
4. Supply IdentityAuthority.verifyHttp (trusted token verification), verifyWorker (claimed job verification including actor/project and original operation key), and resolve (current access). createModelOrderHost rejects privileged database roles and has no default anonymous or memory identity.
|
|
23245
|
+
5. For local serving, set SUPACLOUD_MODEL_DATABASE_URL and MODEL_IDENTITY_MODULE (exports authority), then bun run dev. The script binds loopback only. For deployment, import createModelOrderHost with the platform's pool and identity authority.
|
|
23246
|
+
|
|
23247
|
+
POST /orders accepts { id, title }. POST /orders/:id/approve accepts { expectedVersion }. Both require Idempotency-Key and return a durable receipt; result.outcome is applied or conflict. A stale version is a persisted conflict decision; use a new operation key only for a genuinely new, reviewed attempt. GET /orders/:id returns a policy-filtered order or null. Tenant and owner are never accepted from request bodies.
|
|
23248
|
+
|
|
23249
|
+
Connect the existing queue consumer to host.worker(claim, signal). Acknowledge only a confirmed receipt with complete audit. Redelivery with the same verified actor/tenant/key replays the receipt without rerunning the write. Failed verification, revoked access and unknown outcomes must remain failures. The handler adds no claim loop, scheduler, implicit impersonation or external dispatch. Full queue infrastructure acceptance is separate from testing this handler.
|
|
23250
|
+
|
|
23251
|
+
The receipt migration uses the same supacloud_commands ledger as the platform. It supports local transactional commands; external commands and durable recovery still require the existing Commands/Workflow runtime. Never apply a second migration history.
|
|
23252
|
+
|
|
23253
|
+
The model_orders_app role is a trusted-server capability. ZenStack enforces row ownership and tenant isolation for this recipe; the SQL policy restricts access to that role. Do not grant it to PostgREST/authenticated users. Direct database APIs need their own row policies.
|
|
23254
|
+
|
|
23255
|
+
To change the schema: bun run db:generate, bun run db:check, then bun run db:diff -- --candidate output/database-audit/change.sql against an explicit shadow database. Review forward SQL before promotion. Stop intake and drain HTTP/worker work before host.dispose(), then close the caller-owned pool.
|
|
23256
|
+
`
|
|
23257
|
+
};
|
|
23258
|
+
}
|
|
23259
|
+
|
|
22746
23260
|
// src/shared/tools/app-starter-review-job.ts
|
|
22747
23261
|
var STARTER_REVIEW_JOB = `import { DB_CLIENT, Inject, Injectable, Job } from "@supacloud/app";
|
|
22748
23262
|
import { ApplicationError } from "@supacloud/elysia";
|
|
@@ -23875,81 +24389,90 @@ export async function createDeliveryApplication(modules: CompiledModule[], lifec
|
|
|
23875
24389
|
// src/shared/tools/app-starter-database.ts
|
|
23876
24390
|
var STARTER_DATABASE_CONFIG = {
|
|
23877
24391
|
version: 1,
|
|
23878
|
-
schema: ["db/schema.ts"],
|
|
24392
|
+
schema: ["zenstack/schema.zmodel", "zenstack/generated/schema.ts", "db/schema.ts"],
|
|
23879
24393
|
functions: "db/functions",
|
|
23880
24394
|
migrations: "migrations",
|
|
23881
24395
|
contracts: "db/contracts",
|
|
23882
24396
|
audit: "output/database-audit",
|
|
23883
24397
|
consumers: ["src", "scripts", "tests"],
|
|
23884
24398
|
auditConsumers: [],
|
|
24399
|
+
trustedHosts: ["src/host", "src/delivery-host.ts", "src/delivery-worker.ts"],
|
|
23885
24400
|
role: "starter_review_http"
|
|
23886
24401
|
};
|
|
23887
|
-
var
|
|
23888
|
-
|
|
23889
|
-
|
|
23890
|
-
|
|
23891
|
-
|
|
23892
|
-
|
|
23893
|
-
|
|
23894
|
-
|
|
23895
|
-
|
|
23896
|
-
|
|
23897
|
-
|
|
23898
|
-
|
|
23899
|
-
|
|
23900
|
-
|
|
23901
|
-
|
|
23902
|
-
|
|
23903
|
-
|
|
23904
|
-
|
|
23905
|
-
|
|
23906
|
-
|
|
23907
|
-
|
|
23908
|
-
|
|
23909
|
-
|
|
23910
|
-
|
|
23911
|
-
|
|
23912
|
-
|
|
23913
|
-
|
|
23914
|
-
|
|
23915
|
-
|
|
23916
|
-
|
|
23917
|
-
|
|
23918
|
-
|
|
23919
|
-
|
|
23920
|
-
|
|
23921
|
-
|
|
23922
|
-
|
|
23923
|
-
|
|
23924
|
-
|
|
23925
|
-
|
|
23926
|
-
|
|
23927
|
-
|
|
23928
|
-
|
|
23929
|
-
|
|
23930
|
-
|
|
23931
|
-
|
|
23932
|
-
|
|
23933
|
-
|
|
23934
|
-
|
|
23935
|
-
|
|
23936
|
-
|
|
23937
|
-
|
|
23938
|
-
|
|
23939
|
-
|
|
23940
|
-
|
|
23941
|
-
|
|
23942
|
-
|
|
23943
|
-
|
|
23944
|
-
|
|
23945
|
-
|
|
23946
|
-
|
|
23947
|
-
|
|
23948
|
-
|
|
24402
|
+
var STARTER_DATABASE_MODEL = `datasource db {
|
|
24403
|
+
provider = "postgresql"
|
|
24404
|
+
url = env("DATABASE_URL")
|
|
24405
|
+
}
|
|
24406
|
+
plugin policy {
|
|
24407
|
+
provider = "@zenstackhq/plugin-policy"
|
|
24408
|
+
}
|
|
24409
|
+
type Principal {
|
|
24410
|
+
id String
|
|
24411
|
+
canApprove Boolean
|
|
24412
|
+
@@auth()
|
|
24413
|
+
}
|
|
24414
|
+
model Application {
|
|
24415
|
+
singleton Boolean @id @default(true)
|
|
24416
|
+
projectId String @map("project_id")
|
|
24417
|
+
tenantId String @map("tenant_id")
|
|
24418
|
+
@@map("starter_application")
|
|
24419
|
+
@@allow("read", auth() != null)
|
|
24420
|
+
}
|
|
24421
|
+
model Review {
|
|
24422
|
+
id String @id
|
|
24423
|
+
ownerId String @map("owner_id")
|
|
24424
|
+
state String
|
|
24425
|
+
version Int
|
|
24426
|
+
attachment Attachment?
|
|
24427
|
+
results AttachmentResult[]
|
|
24428
|
+
@@map("starter_reviews")
|
|
24429
|
+
@@allow("read", auth() != null && (ownerId == auth().id || auth().canApprove))
|
|
24430
|
+
}
|
|
24431
|
+
model Member {
|
|
24432
|
+
subject String @id
|
|
24433
|
+
enabled Boolean @default(true)
|
|
24434
|
+
canApprove Boolean @default(false) @map("can_approve")
|
|
24435
|
+
storageSubject String? @unique @db.Uuid @map("storage_subject")
|
|
24436
|
+
@@map("starter_members")
|
|
24437
|
+
@@allow("read", auth() != null && subject == auth().id)
|
|
24438
|
+
}
|
|
24439
|
+
model Attachment {
|
|
24440
|
+
reviewId String @id @map("review_id")
|
|
24441
|
+
review Review @relation(fields: [reviewId], references: [id])
|
|
24442
|
+
artifactId String @unique @db.Uuid @map("artifact_id")
|
|
24443
|
+
ownerId String @map("owner_id")
|
|
24444
|
+
runId String @unique @db.Uuid @map("run_id")
|
|
24445
|
+
objectPath String @unique @map("object_path")
|
|
24446
|
+
retries AttachmentRetry[]
|
|
24447
|
+
@@map("starter_attachments")
|
|
24448
|
+
@@allow("read", auth() != null && ownerId == auth().id)
|
|
24449
|
+
}
|
|
24450
|
+
model AttachmentResult {
|
|
24451
|
+
reviewId String @map("review_id")
|
|
24452
|
+
review Review @relation(fields: [reviewId], references: [id])
|
|
24453
|
+
version Int
|
|
24454
|
+
artifactId String @db.Uuid @map("artifact_id")
|
|
24455
|
+
result Json
|
|
24456
|
+
@@id([reviewId, version, artifactId])
|
|
24457
|
+
@@map("starter_attachment_results")
|
|
24458
|
+
@@allow("read", auth() != null && review.ownerId == auth().id)
|
|
24459
|
+
}
|
|
24460
|
+
model AttachmentRetry {
|
|
24461
|
+
runId String @id @db.Uuid @map("run_id")
|
|
24462
|
+
reviewId String @map("review_id")
|
|
24463
|
+
attachment Attachment @relation(fields: [reviewId], references: [reviewId])
|
|
24464
|
+
previousRunId String @unique @db.Uuid @map("previous_run_id")
|
|
24465
|
+
generation Int
|
|
24466
|
+
@@unique([reviewId, generation])
|
|
24467
|
+
@@map("starter_attachment_retries")
|
|
24468
|
+
@@allow("read", auth() != null && attachment.ownerId == auth().id)
|
|
24469
|
+
}
|
|
24470
|
+
`;
|
|
24471
|
+
var STARTER_DATABASE_SCHEMA = `export type { Review as ReviewRow, Attachment as AttachmentRow, AttachmentRetry as AttachmentRetryRow } from "../zenstack/generated/models";
|
|
24472
|
+
import type { Review } from "../zenstack/generated/models";
|
|
24473
|
+
export type NewReview = Review;
|
|
23949
24474
|
`;
|
|
23950
24475
|
var STARTER_DATABASE_MODULES = `import { defineDatabaseModule } from "@supacloud/db";
|
|
23951
|
-
import { getTableConfig } from "drizzle-orm/pg-core";
|
|
23952
|
-
import { application, reviews, members, attachments, attachmentResults, attachmentRetries } from "./schema";
|
|
23953
24476
|
|
|
23954
24477
|
const backendPolicies = [
|
|
23955
24478
|
["starter_backend_binding_read", "public.starter_application", "select", ["starter_review_http", "starter_review_worker"]],
|
|
@@ -23972,10 +24495,7 @@ const backendPolicies = [
|
|
|
23972
24495
|
// The module is the single live-Catalog ownership contract for starter tables.
|
|
23973
24496
|
export default defineDatabaseModule({
|
|
23974
24497
|
name: "starter",
|
|
23975
|
-
tables: [
|
|
23976
|
-
const config = getTableConfig(table);
|
|
23977
|
-
return (config.schema ?? "public") + "." + config.name;
|
|
23978
|
-
}),
|
|
24498
|
+
tables: ["public.starter_application", "public.starter_reviews", "public.starter_members", "public.starter_attachments", "public.starter_attachment_results", "public.starter_attachment_retries"],
|
|
23979
24499
|
policies: [
|
|
23980
24500
|
...([
|
|
23981
24501
|
["starter_http_retry_read", "select", "starter_review_http"],
|
|
@@ -24030,41 +24550,23 @@ $test$;
|
|
|
24030
24550
|
ROLLBACK;
|
|
24031
24551
|
`;
|
|
24032
24552
|
var STARTER_DATABASE_GUIDE = `
|
|
24033
|
-
##
|
|
24034
|
-
|
|
24035
|
-
|
|
24036
|
-
|
|
24037
|
-
|
|
24038
|
-
|
|
24039
|
-
|
|
24040
|
-
|
|
24041
|
-
|
|
24042
|
-
|
|
24043
|
-
|
|
24044
|
-
|
|
24045
|
-
|
|
24046
|
-
|
|
24047
|
-
|
|
24048
|
-
|
|
24049
|
-
|
|
24050
|
-
drift fail closed; no contracts or migrations are silently regenerated.
|
|
24051
|
-
|
|
24052
|
-
- Maintain one schema-qualified function with explicit grants per db/functions/*.sql.
|
|
24053
|
-
- Preserve migrations/ and its existing executor/ledger. Add forward migrations only.
|
|
24054
|
-
- \`bun run db:diff\` generates Drizzle drafts under db/migration-candidates/, never
|
|
24055
|
-
into the deployment directory. The starter has existing SQL history, so establish
|
|
24056
|
-
and review a matching Drizzle baseline before promoting any draft; the first
|
|
24057
|
-
draft is not automatically an incremental production migration.
|
|
24058
|
-
- \`bun run db:pull\` requires an explicitly selected DATABASE_URL and writes only
|
|
24059
|
-
output/database-audit/drizzle-candidate/. Review candidates; never overwrite source blindly.
|
|
24060
|
-
- Full SQL dumps belong under the ignored output/database-audit/ directory. They are
|
|
24061
|
-
audit/recovery artifacts, never ordinary type, application or test inputs.
|
|
24062
|
-
- \`bun run db:assess\` explains adoption/findings without writing or connecting.
|
|
24063
|
-
- GraphQL/PostgREST exports remain legitimate protocol contracts. This check is not
|
|
24064
|
-
proof of deployed schema, effective role permissions or complete RLS equivalence.
|
|
24065
|
-
|
|
24066
|
-
Do not introduce any/@ts-ignore to bypass a contract. Use Drizzle-inferred types,
|
|
24067
|
-
preserve bigint/numeric precision and decode unknown results at the boundary.
|
|
24553
|
+
## Model and migration workflow
|
|
24554
|
+
|
|
24555
|
+
Maintain zenstack/schema.zmodel. Run \`bun run db:generate\` to compile model and RPC
|
|
24556
|
+
contracts; commit generated types with their sources. Do not introduce any/@ts-ignore
|
|
24557
|
+
to bypass model or contract diagnostics. \`bun run db:check\` compares
|
|
24558
|
+
fresh generation without writing files or opening a database. Model read policies
|
|
24559
|
+
complement existing database RLS; command writes still use the shared transaction,
|
|
24560
|
+
receipt and audit boundary, not unrestricted CRUD. SQL constraints, RPCs and RLS
|
|
24561
|
+
remain explicit reviewed migrations when the model language cannot express them.
|
|
24562
|
+
|
|
24563
|
+
Use \`bun run db:diff -- --candidate output/database-audit/change.sql\` with an
|
|
24564
|
+
explicit read-only SUPACLOUD_MODEL_DATABASE_URL. Review the SQL, then promote a new
|
|
24565
|
+
forward migration through the existing SupaCloud plan/apply ledger. Never run
|
|
24566
|
+
zen migrate deploy or db push against a managed production database.
|
|
24567
|
+
\`bun run db:pull -- --candidate output/database-audit/schema.zmodel\` writes a
|
|
24568
|
+
review candidate only; it never overwrites the maintained model. Add policies
|
|
24569
|
+
before adopting introspection output. Keep one migration history and preserve RLS.
|
|
24068
24570
|
`;
|
|
24069
24571
|
function starterDatabaseFiles() {
|
|
24070
24572
|
return {
|
|
@@ -24075,23 +24577,7 @@ function starterDatabaseFiles() {
|
|
|
24075
24577
|
"tests/database-governance.sql": STARTER_DATABASE_TEST,
|
|
24076
24578
|
"db/functions/README.md": `Maintain one schema-qualified function and its explicit EXECUTE ACL per SQL file. No RPC functions are needed by the initial transactional starter.
|
|
24077
24579
|
`,
|
|
24078
|
-
"
|
|
24079
|
-
export default defineConfig({
|
|
24080
|
-
dialect: "postgresql",
|
|
24081
|
-
schema: "./db/schema.ts",
|
|
24082
|
-
out: "./db/migration-candidates",
|
|
24083
|
-
});
|
|
24084
|
-
`,
|
|
24085
|
-
"drizzle.pull.config.ts": `import { defineConfig } from "drizzle-kit";
|
|
24086
|
-
const url = process.env["DATABASE_URL"];
|
|
24087
|
-
if (!url) throw new Error("Select an explicit DATABASE_URL for introspection");
|
|
24088
|
-
export default defineConfig({
|
|
24089
|
-
dialect: "postgresql",
|
|
24090
|
-
schema: "./db/schema.ts",
|
|
24091
|
-
out: "./output/database-audit/drizzle-candidate",
|
|
24092
|
-
dbCredentials: { url },
|
|
24093
|
-
});
|
|
24094
|
-
`
|
|
24580
|
+
"zenstack/schema.zmodel": STARTER_DATABASE_MODEL
|
|
24095
24581
|
};
|
|
24096
24582
|
}
|
|
24097
24583
|
|
|
@@ -25030,8 +25516,8 @@ export class ReviewReceiptsController {
|
|
|
25030
25516
|
var STARTER_REVIEW_QUERY = `import type { SupabaseClient } from "@supabase/supabase-js";
|
|
25031
25517
|
import type { ReviewRow } from "../../db/schema";
|
|
25032
25518
|
|
|
25033
|
-
// This read projection uses SQL column names shared with the
|
|
25034
|
-
// Do not expose camelCase
|
|
25519
|
+
// This read projection uses SQL column names shared with the model source.
|
|
25520
|
+
// Do not expose camelCase model property names as PostgREST column names.
|
|
25035
25521
|
export type ReviewSummary = Pick<ReviewRow, "id" | "state" | "version">;
|
|
25036
25522
|
export type ReviewReadDatabase = {
|
|
25037
25523
|
public: {
|
|
@@ -25224,11 +25710,10 @@ import { AttachmentInput, AttachmentResult } from "../review/attachment";
|
|
|
25224
25710
|
import { ReviewResult } from "../review/contracts";
|
|
25225
25711
|
import { RetryInput, RetryResult, TaskParams, TaskStatus, type ReviewRetryInput } from "../review/task-contracts";
|
|
25226
25712
|
import type { ReviewTaskPort } from "../review/tasks";
|
|
25227
|
-
import type {
|
|
25713
|
+
import type { ReviewRow } from "../../db/schema";
|
|
25228
25714
|
|
|
25229
25715
|
export interface ReviewTaskOptions { database: CommandDatabase; projectId: string; tenantId: string }
|
|
25230
|
-
type Binding =
|
|
25231
|
-
& Pick<typeof attachmentRetries.$inferSelect, "generation" | "runId">;
|
|
25716
|
+
type Binding = { artifactId: string; runId: string; generation: number };
|
|
25232
25717
|
const decodeInput = createSchemaDecoder(RetryInput, { normalize: false });
|
|
25233
25718
|
const decodeRetry = createSchemaDecoder(RetryResult, { normalize: false });
|
|
25234
25719
|
const decodeStatus = createSchemaDecoder(TaskStatus, { normalize: false });
|
|
@@ -25410,7 +25895,7 @@ export async function createReviewTaskAdapters(options: ReviewTaskOptions): Prom
|
|
|
25410
25895
|
|
|
25411
25896
|
// src/shared/tools/app-starter.ts
|
|
25412
25897
|
var { compiler: compilerMetadata2, app: appMetadata2, elysia: elysiaMetadata2, commands: commandsMetadata, contracts: contractsMetadata, db: dbMetadata, sdk: sdkMetadata } = starter_metadata_default.packages;
|
|
25413
|
-
var
|
|
25898
|
+
var json3 = (value) => `${JSON.stringify(value, null, 2)}
|
|
25414
25899
|
`;
|
|
25415
25900
|
function appStarterFiles(name) {
|
|
25416
25901
|
return {
|
|
@@ -25420,7 +25905,7 @@ function appStarterFiles(name) {
|
|
|
25420
25905
|
"src/review/tasks.ts": STARTER_TASK_FEATURE,
|
|
25421
25906
|
"src/host/review-tasks.ts": STARTER_TASK_HOST,
|
|
25422
25907
|
"migrations/005-review-task-recovery.sql": STARTER_TASK_SCHEMA,
|
|
25423
|
-
"package.json":
|
|
25908
|
+
"package.json": json3({
|
|
25424
25909
|
name,
|
|
25425
25910
|
version: "0.0.0",
|
|
25426
25911
|
private: true,
|
|
@@ -25430,11 +25915,11 @@ function appStarterFiles(name) {
|
|
|
25430
25915
|
compile: "bun --no-env-file node_modules/@supacloud/compiler/dist/cli.js compile",
|
|
25431
25916
|
"check:generated": "bun --no-env-file node_modules/@supacloud/compiler/dist/cli.js check",
|
|
25432
25917
|
typecheck: "tsc --noEmit",
|
|
25433
|
-
"db:generate": "supacloud-db generate",
|
|
25434
|
-
"db:check": "supacloud-db check",
|
|
25918
|
+
"db:generate": "supacloud-model generate && supacloud-db generate",
|
|
25919
|
+
"db:check": "supacloud-model check && supacloud-db check",
|
|
25435
25920
|
"db:assess": "supacloud-db assess",
|
|
25436
|
-
"db:diff": "
|
|
25437
|
-
"db:pull": "
|
|
25921
|
+
"db:diff": "supacloud-model diff",
|
|
25922
|
+
"db:pull": "supacloud-model pull",
|
|
25438
25923
|
check: "bun run db:check && bun run compile && bun run check:generated && bun run typecheck && bun run test",
|
|
25439
25924
|
test: "bun run compile && bun --no-env-file scripts/environment.ts test bun test",
|
|
25440
25925
|
dev: "bun --no-env-file scripts/environment.ts development bun scripts/dev.ts",
|
|
@@ -25451,7 +25936,7 @@ function appStarterFiles(name) {
|
|
|
25451
25936
|
"@supacloud/commands": `^${commandsMetadata.version}`,
|
|
25452
25937
|
"@supacloud/contracts": `^${contractsMetadata.version}`,
|
|
25453
25938
|
"@supacloud/db": `^${dbMetadata.version}`,
|
|
25454
|
-
|
|
25939
|
+
...dbMetadata.dependencies,
|
|
25455
25940
|
"@supacloud/js": `^${sdkMetadata.version}`,
|
|
25456
25941
|
"@supabase/supabase-js": sdkMetadata.peerDependencies["@supabase/supabase-js"],
|
|
25457
25942
|
effect: "4.0.5",
|
|
@@ -25460,12 +25945,12 @@ function appStarterFiles(name) {
|
|
|
25460
25945
|
},
|
|
25461
25946
|
devDependencies: {
|
|
25462
25947
|
"@supacloud/compiler": `^${compilerMetadata2.version}`,
|
|
25463
|
-
|
|
25948
|
+
...dbMetadata.devDependencies,
|
|
25464
25949
|
"@types/bun": "^1.4.4",
|
|
25465
|
-
typescript: "
|
|
25950
|
+
typescript: "7.1.0-beta"
|
|
25466
25951
|
}
|
|
25467
25952
|
}),
|
|
25468
|
-
"tsconfig.json":
|
|
25953
|
+
"tsconfig.json": json3({
|
|
25469
25954
|
compilerOptions: {
|
|
25470
25955
|
target: "ES2022",
|
|
25471
25956
|
module: "ESNext",
|
|
@@ -25483,7 +25968,7 @@ function appStarterFiles(name) {
|
|
|
25483
25968
|
noEmit: true,
|
|
25484
25969
|
types: ["bun"]
|
|
25485
25970
|
},
|
|
25486
|
-
include: ["src/**/*.ts", "scripts/**/*.ts", "tests/**/*.ts", "generated/**/*.ts", "db/schema.ts", "db/modules.ts", "db/contracts/**/*.ts", "supacloud.config.ts", "
|
|
25971
|
+
include: ["src/**/*.ts", "scripts/**/*.ts", "tests/**/*.ts", "generated/**/*.ts", "db/schema.ts", "db/modules.ts", "db/contracts/**/*.ts", "supacloud.config.ts", "zenstack/generated/**/*.ts"]
|
|
25487
25972
|
}),
|
|
25488
25973
|
"bunfig.toml": `env = false
|
|
25489
25974
|
`,
|
|
@@ -26040,7 +26525,7 @@ The projection is not a full database export and grants no write access.
|
|
|
26040
26525
|
|
|
26041
26526
|
GraphQL is not generated or enabled by this starter. For a specific Query Contract,
|
|
26042
26527
|
explicitly configure graphql.schema with a role-scoped database export and add
|
|
26043
|
-
checked query documents.
|
|
26528
|
+
checked query documents. ZModel and append-only migrations remain the database
|
|
26044
26529
|
authority; the export is a protocol snapshot, not a second schema source.
|
|
26045
26530
|
|
|
26046
26531
|
## Environments
|
|
@@ -26355,10 +26840,11 @@ async function initializeAppProject(options) {
|
|
|
26355
26840
|
throw new Error("app init requires an empty directory (an existing .git directory is allowed)");
|
|
26356
26841
|
}
|
|
26357
26842
|
const template = options.template ?? "minimal";
|
|
26358
|
-
const
|
|
26843
|
+
const sdk = {
|
|
26359
26844
|
"@supacloud/js": `^${sdkMetadata.version}`,
|
|
26360
26845
|
"@supabase/supabase-js": sdkMetadata.peerDependencies["@supabase/supabase-js"]
|
|
26361
|
-
}
|
|
26846
|
+
};
|
|
26847
|
+
const files = template === "command" ? appStarterFiles(name) : template === "model-command" ? modelCommandTemplateFiles(name, sdk) : appTemplateFiles(name, template, sdk);
|
|
26362
26848
|
for (const [relativePath, content] of Object.entries(files)) {
|
|
26363
26849
|
const path = join9(root, relativePath);
|
|
26364
26850
|
await mkdir3(dirname6(path), { recursive: true });
|
|
@@ -28070,10 +28556,13 @@ async function initProject(args) {
|
|
|
28070
28556
|
const { root, name, files } = await initializeAppProject({ root: args.root, name: args.name, template });
|
|
28071
28557
|
const next = [
|
|
28072
28558
|
"bun install",
|
|
28073
|
-
...template
|
|
28559
|
+
...template !== "minimal" ? ["bun run db:generate"] : [],
|
|
28560
|
+
...template === "model-command" ? ["bun run compile"] : [],
|
|
28074
28561
|
"bun run check",
|
|
28562
|
+
...template === "model-command" ? ["# Follow README.md: apply reviewed local migrations, provision the application role and configure IdentityAuthority before dev."] : [],
|
|
28075
28563
|
"bun run dev"
|
|
28076
28564
|
];
|
|
28565
|
+
const note = template === "model-command" ? "Requires an explicitly selected database, reviewed migrations and trusted HTTP/worker identity authority; see README.md." : "Local demo only. Production requires persistent governance and identity adapters; see README.md.";
|
|
28077
28566
|
if (args.format === "json")
|
|
28078
28567
|
return textResult(JSON.stringify({
|
|
28079
28568
|
version: 1,
|
|
@@ -28083,13 +28572,13 @@ async function initProject(args) {
|
|
|
28083
28572
|
template,
|
|
28084
28573
|
files,
|
|
28085
28574
|
next,
|
|
28086
|
-
note
|
|
28575
|
+
note
|
|
28087
28576
|
}, null, 2));
|
|
28088
28577
|
return textResult([
|
|
28089
28578
|
`Initialized ${name} in ${root} (${files.length} files, template: ${template}).`,
|
|
28090
28579
|
`cd '${root.replaceAll("'", "'\\''")}'`,
|
|
28091
28580
|
...next,
|
|
28092
|
-
|
|
28581
|
+
note
|
|
28093
28582
|
].join(`
|
|
28094
28583
|
`));
|
|
28095
28584
|
}
|
|
@@ -28467,7 +28956,7 @@ async function runContext(args) {
|
|
|
28467
28956
|
writeTransport: "command-rpc",
|
|
28468
28957
|
writeRetry: "disabled",
|
|
28469
28958
|
externalOutcome: "receipt-reconcile",
|
|
28470
|
-
databaseSource: "
|
|
28959
|
+
databaseSource: "zmodel-append-only"
|
|
28471
28960
|
}
|
|
28472
28961
|
};
|
|
28473
28962
|
if (args.format === "json")
|
|
@@ -29722,7 +30211,7 @@ function registerAppTools(server, options = {}) {
|
|
|
29722
30211
|
"promote-reconcile"
|
|
29723
30212
|
]), "App action; promote obtains and verifies its plan before one mutation request"),
|
|
29724
30213
|
kind: optional(stringEnum2(["module", "command", "query", "controller", "job", "contract", "resource", "feature"]), "[generate] Scaffold kind"),
|
|
29725
|
-
template: optional(stringEnum2(["minimal", "command"]), "[init] Minimal
|
|
30214
|
+
template: optional(stringEnum2(["minimal", "command", "model-command"]), "[init] Minimal by default; command adds the native-SQL reference; model-command adds ZenStack HTTP/worker commands"),
|
|
29726
30215
|
name: optional(String2(), "[init/generate] Project or object name"),
|
|
29727
30216
|
module: optional(String2(), "[generate] Target feature module (required for command/query/controller)"),
|
|
29728
30217
|
permission: optional(String2(), "[generate feature] Explicit approval permission; not inferred from name"),
|
|
@@ -30525,7 +31014,7 @@ function buildDatabaseAiContext(modules, root, moduleName, target) {
|
|
|
30525
31014
|
const objects = target ? allObjects.filter((object) => objectMatchesTarget(object, target)) : allObjects;
|
|
30526
31015
|
if (target && objects.length === 0)
|
|
30527
31016
|
throw new Error(`未找到数据库对象: ${target}`);
|
|
30528
|
-
const sqlFirst = existsSync13(join16(root, "supabase/schemas"));
|
|
31017
|
+
const sqlFirst = !existsSync13(join16(root, "zenstack/schema.zmodel")) && existsSync13(join16(root, "supabase/schemas"));
|
|
30529
31018
|
return {
|
|
30530
31019
|
version: 1,
|
|
30531
31020
|
scope: "database-ai-context",
|
|
@@ -30534,14 +31023,14 @@ function buildDatabaseAiContext(modules, root, moduleName, target) {
|
|
|
30534
31023
|
target: target ?? null,
|
|
30535
31024
|
objects,
|
|
30536
31025
|
maintenance: {
|
|
30537
|
-
structureSource: sqlFirst ? "declarative-sql" : "
|
|
31026
|
+
structureSource: sqlFirst ? "declarative-sql" : "zmodel",
|
|
30538
31027
|
behaviorSource: "sql",
|
|
30539
|
-
generatedPaths: [...sqlFirst ? ["db/schema.ts"] : [], "generated/", "bootstrap/schema.sql", "output/database-audit/"],
|
|
31028
|
+
generatedPaths: [...sqlFirst ? ["db/schema.ts"] : ["zenstack/generated/"], "generated/", "bootstrap/schema.sql", "output/database-audit/"],
|
|
30540
31029
|
protectedPaths: ["migrations/", "supabase/migrations/", "generated/"],
|
|
30541
31030
|
forwardMigrationPath: sqlFirst ? "supabase/migrations/<timestamp>_<intent>.sql" : "migrations/<timestamp>_<intent>.sql",
|
|
30542
31031
|
rules: [
|
|
30543
31032
|
"Edit the selected maintained source, not a generated snapshot.",
|
|
30544
|
-
...sqlFirst ? ["Author structure in supabase/schemas SQL; derive
|
|
31033
|
+
...sqlFirst ? ["Author structure in supabase/schemas SQL; derive query models, never run a second migration generator."] : [],
|
|
30545
31034
|
"Keep RPC, RLS, trigger and grant behavior in explicit SQL sources.",
|
|
30546
31035
|
"Create a new forward migration; never rewrite an applied migration.",
|
|
30547
31036
|
"Run lint, focused behavior tests and catalog reconciliation after edits."
|
|
@@ -33141,7 +33630,7 @@ import { compileProject as compileProject2 } from "@supacloud/compiler";
|
|
|
33141
33630
|
var SAFE_TOKEN = /^[A-Za-z0-9._:@/+,-]+$/;
|
|
33142
33631
|
var SAFE_REMOTE_ROOT = /^\/(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+\/?$/;
|
|
33143
33632
|
var remoteDevToolSchema = {
|
|
33144
|
-
action: withDescription(stringEnum2(["sync", "watch", "status"
|
|
33633
|
+
action: withDescription(stringEnum2(["sync", "watch", "status"]), "Remote development action"),
|
|
33145
33634
|
target: optional(stringEnum2(["db", "functions", "frontend", "project"]), "Sync target (default: project)"),
|
|
33146
33635
|
project_dir: optional(String2(), "Local project directory (default: current directory)"),
|
|
33147
33636
|
remote_root: optional(String2(), "Remote development root"),
|
|
@@ -33152,11 +33641,7 @@ var remoteDevToolSchema = {
|
|
|
33152
33641
|
function: optional(String2(), "Function slug"),
|
|
33153
33642
|
delete: optional(Boolean2(), "Delete remote files absent locally"),
|
|
33154
33643
|
reload: optional(Boolean2(), "Reload the affected target after sync (default: true)"),
|
|
33155
|
-
interval_ms: optional(Number2(), "Watch debounce interval in milliseconds (default: 300)")
|
|
33156
|
-
apply: optional(Boolean2(), "Apply generated migrations to the selected test database"),
|
|
33157
|
-
drizzle_config: optional(String2(), "Drizzle config path"),
|
|
33158
|
-
migrations_dir: optional(String2(), "Migration directory"),
|
|
33159
|
-
drizzle_bin: optional(String2(), "drizzle-kit executable")
|
|
33644
|
+
interval_ms: optional(Number2(), "Watch debounce interval in milliseconds (default: 300)")
|
|
33160
33645
|
};
|
|
33161
33646
|
async function runProcess(executable, args, cwd) {
|
|
33162
33647
|
const child = Bun.spawn([executable, ...args], { cwd, stdio: ["ignore", "pipe", "pipe"] });
|
|
@@ -33167,50 +33652,15 @@ async function runProcess(executable, args, cwd) {
|
|
|
33167
33652
|
]);
|
|
33168
33653
|
return { exitCode: exitCode ?? 1, stdout, stderr };
|
|
33169
33654
|
}
|
|
33170
|
-
function resolveDrizzleCommand(root, configured) {
|
|
33171
|
-
if (configured?.trim())
|
|
33172
|
-
return configured.trim();
|
|
33173
|
-
const local = join20(root, "node_modules", ".bin", "drizzle-kit");
|
|
33174
|
-
return existsSync17(local) ? local : "drizzle-kit";
|
|
33175
|
-
}
|
|
33176
|
-
function toolFailed(value) {
|
|
33177
|
-
if (!value || typeof value !== "object")
|
|
33178
|
-
return false;
|
|
33179
|
-
const result = value;
|
|
33180
|
-
const content = Array.isArray(result.content) ? result.content : [];
|
|
33181
|
-
return result.isError === true || content.some((chunk) => chunk !== null && typeof chunk === "object" && ("text" in chunk) && typeof chunk.text === "string" && chunk.text.trimStart().startsWith("❌"));
|
|
33182
|
-
}
|
|
33183
|
-
async function migrateDatabase(args, options) {
|
|
33184
|
-
const root = resolve27(String(args.project_dir || options.cwd || process.cwd()));
|
|
33185
|
-
const projectConfig = await readProjectConfig(root);
|
|
33186
|
-
const config = projectConfig.dev || {};
|
|
33187
|
-
const database = config.database || {};
|
|
33188
|
-
const execute = options.execute || ((command, commandArgs, cwd) => runProcess(command, commandArgs, cwd));
|
|
33189
|
-
const drizzleConfig = resolve27(root, String(args.drizzle_config || database.drizzleConfig || "drizzle.config.ts"));
|
|
33190
|
-
const migrationsDir = String(args.migrations_dir || database.migrationsDir || "supabase/migrations");
|
|
33191
|
-
if (!existsSync17(drizzleConfig))
|
|
33192
|
-
throw new Error(`Drizzle config not found: ${drizzleConfig}`);
|
|
33193
|
-
const generated = await execute(resolveDrizzleCommand(root, typeof args.drizzle_bin === "string" ? args.drizzle_bin : database.drizzleBin), ["generate", "--config", drizzleConfig], root);
|
|
33194
|
-
if (generated.exitCode !== 0)
|
|
33195
|
-
throw new Error(`Drizzle migration generation failed: ${generated.stderr.trim() || `exit ${generated.exitCode}`}`);
|
|
33196
|
-
if (!options.runDatabase)
|
|
33197
|
-
throw new Error("dev migrate requires Management API context");
|
|
33198
|
-
const dryRun = await options.runDatabase({ action: "push_migrations", dir: migrationsDir, dry_run: true, strict: database.strict !== false });
|
|
33199
|
-
if (toolFailed(dryRun))
|
|
33200
|
-
throw new Error("SupaCloud migration dry-run failed");
|
|
33201
|
-
if (args.apply !== true)
|
|
33202
|
-
return { ok: true, mode: "dev", action: "migrate", generated: true, applied: false, migrations_dir: migrationsDir, dry_run: dryRun };
|
|
33203
|
-
const applied = await options.runDatabase({ action: "push_migrations", dir: migrationsDir, strict: database.strict !== false });
|
|
33204
|
-
if (toolFailed(applied))
|
|
33205
|
-
throw new Error("SupaCloud migration apply failed");
|
|
33206
|
-
return { ok: true, mode: "dev", action: "migrate", generated: true, applied: true, migrations_dir: migrationsDir, result: applied };
|
|
33207
|
-
}
|
|
33208
33655
|
async function readProjectConfig(root) {
|
|
33209
33656
|
const file = join20(root, "supacloud.json");
|
|
33210
33657
|
if (!existsSync17(file))
|
|
33211
33658
|
return {};
|
|
33212
33659
|
try {
|
|
33213
33660
|
const parsed = JSON.parse(await readFile8(file, "utf8"));
|
|
33661
|
+
if (parsed && typeof parsed === "object" && "dev" in parsed && parsed.dev && typeof parsed.dev === "object" && "database" in parsed.dev) {
|
|
33662
|
+
throw new Error("dev.database was removed; use supacloud-model diff and db plan/apply");
|
|
33663
|
+
}
|
|
33214
33664
|
return parsed && typeof parsed === "object" ? parsed : {};
|
|
33215
33665
|
} catch (error) {
|
|
33216
33666
|
throw new Error(`Invalid supacloud.json: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -33377,9 +33827,6 @@ function registerRemoteDevTools(server, options = {}) {
|
|
|
33377
33827
|
if (args.action === "sync") {
|
|
33378
33828
|
return { content: [{ type: "text", text: JSON.stringify(await syncOnce(args, options), null, 2) }] };
|
|
33379
33829
|
}
|
|
33380
|
-
if (args.action === "migrate") {
|
|
33381
|
-
return { content: [{ type: "text", text: JSON.stringify(await migrateDatabase(args, options), null, 2) }] };
|
|
33382
|
-
}
|
|
33383
33830
|
if (args.action === "watch") {
|
|
33384
33831
|
const root = resolve27(String(args.project_dir || options.cwd || process.cwd()));
|
|
33385
33832
|
const interval = Math.max(100, Math.min(1e4, Number(args.interval_ms || 300)));
|
|
@@ -33843,7 +34290,7 @@ async function runProjectDeployment(http, args) {
|
|
|
33843
34290
|
// package.json
|
|
33844
34291
|
var package_default = {
|
|
33845
34292
|
name: "@supacloud/cli",
|
|
33846
|
-
version: "0.
|
|
34293
|
+
version: "0.117.1",
|
|
33847
34294
|
description: "Project-scoped CLI for SupaCloud users",
|
|
33848
34295
|
type: "module",
|
|
33849
34296
|
main: "./dist/index.js",
|
|
@@ -33872,7 +34319,7 @@ var package_default = {
|
|
|
33872
34319
|
],
|
|
33873
34320
|
scripts: {
|
|
33874
34321
|
dev: "bun run --watch src/index.ts",
|
|
33875
|
-
"prepare:db": "bun install --cwd ../contracts --frozen-lockfile && bun run --cwd ../contracts build && bun install --cwd ../db --force --frozen-lockfile && bun run --cwd ../db build && bun install --force --frozen-lockfile",
|
|
34322
|
+
"prepare:db": "bun install --cwd ../contracts --frozen-lockfile && bun run --cwd ../contracts build && bun install --cwd ../compiler --frozen-lockfile && bun run --cwd ../compiler build && bun install --cwd ../db --force --frozen-lockfile && bun run --cwd ../db build && bun install --force --frozen-lockfile",
|
|
33876
34323
|
prebuild: "bun run prepare:db",
|
|
33877
34324
|
build: "bun build src/index.ts --outdir dist --target node --conditions=supacloud-source --external @supacloud/compiler --external @supacloud/db && bun run build:tool-runtime && bun run build:types",
|
|
33878
34325
|
"build:tool-runtime": "bun build src/tool-runtime.ts --outdir dist --target node --external typebox && tsc -p tsconfig.tool-runtime.json --emitDeclarationOnly",
|
|
@@ -33895,23 +34342,27 @@ var package_default = {
|
|
|
33895
34342
|
directory: "packages/cli"
|
|
33896
34343
|
},
|
|
33897
34344
|
dependencies: {
|
|
33898
|
-
"@supacloud/compiler": "^0.
|
|
33899
|
-
"@supacloud/delivery": "0.
|
|
33900
|
-
"@supacloud/db": "0.
|
|
34345
|
+
"@supacloud/compiler": "^0.57.0",
|
|
34346
|
+
"@supacloud/delivery": "0.25.0",
|
|
34347
|
+
"@supacloud/db": "0.21.0",
|
|
33901
34348
|
typebox: "1.4.3"
|
|
33902
34349
|
},
|
|
33903
34350
|
overrides: {
|
|
33904
|
-
"@supacloud/contracts": "0.
|
|
33905
|
-
"@supacloud/delivery": "0.
|
|
33906
|
-
"@graphql-tools/utils": "^12.0.4"
|
|
34351
|
+
"@supacloud/contracts": "0.16.0",
|
|
34352
|
+
"@supacloud/delivery": "0.25.0",
|
|
34353
|
+
"@graphql-tools/utils": "^12.0.4",
|
|
34354
|
+
"@supacloud/compiler": "^0.57.0",
|
|
34355
|
+
"@supacloud/db": "0.21.0",
|
|
34356
|
+
"deepmerge-ts": "8.0.2",
|
|
34357
|
+
prisma: "6.19.3"
|
|
33907
34358
|
},
|
|
33908
34359
|
devDependencies: {
|
|
33909
34360
|
"@supabase/supabase-js": "2.118.0",
|
|
33910
|
-
"@supacloud/elysia": "0.
|
|
34361
|
+
"@supacloud/elysia": "0.40.0",
|
|
33911
34362
|
"@types/bun": "^1.4.4",
|
|
33912
34363
|
effect: "4.0.5",
|
|
33913
34364
|
elysia: "2.0.0-rc.1",
|
|
33914
|
-
typescript: "
|
|
34365
|
+
typescript: "7.1.0-beta"
|
|
33915
34366
|
}
|
|
33916
34367
|
};
|
|
33917
34368
|
|
|
@@ -34436,8 +34887,7 @@ function createCliTools(context, confirmProduction) {
|
|
|
34436
34887
|
sshPort: context.sshPort,
|
|
34437
34888
|
sshKey: context.sshKey,
|
|
34438
34889
|
projectRef: context.projectRef || undefined,
|
|
34439
|
-
environment: context.environment
|
|
34440
|
-
runDatabase: databaseTools.database?.callback
|
|
34890
|
+
environment: context.environment
|
|
34441
34891
|
})));
|
|
34442
34892
|
assign(captureTools((server) => registerAuthTools(server, http)));
|
|
34443
34893
|
assign(captureTools((server) => registerOAuthClientTools(server, http)));
|