@supacloud/cli 0.129.7 → 0.131.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +480 -32
- package/dist/shared/tools/app-feature.d.ts +5 -0
- package/dist/shared/tools/app-starter-attachments.d.ts +1 -1
- package/dist/shared/tools/app-starter-database.d.ts +3 -4
- package/dist/shared/tools/app-starter-postgres.d.ts +1 -1
- package/dist/shared/tools/app-starter-tasks.d.ts +1 -1
- package/dist/shared/tools/app-starter-upload.d.ts +1 -1
- package/dist/shared/tools/app-tools.d.ts +21 -2
- package/dist/shared/tools/app-upgrade-and-governance.test.d.ts +1 -0
- package/package.json +6 -6
package/dist/index.js
CHANGED
|
@@ -19565,7 +19565,7 @@ var ACTION_POLICY = {
|
|
|
19565
19565
|
init: { local: ["init"] },
|
|
19566
19566
|
env: { local: ["list", "check", "sync"] },
|
|
19567
19567
|
app: {
|
|
19568
|
-
local: ["init", "generate", "infer", "dev", "watch", "verify-plan", "verify", "compile", "check", "graph", "explain", "export-tools", "context", "lens", "doctor", "fix", "plan", "build"],
|
|
19568
|
+
local: ["init", "generate", "infer", "dev", "watch", "verify-plan", "verify", "compile", "check", "graph", "explain", "export-tools", "context", "lens", "doctor", "fix", "upgrade", "client-sdk", "contract-diff", "sql-prepare", "plan", "build"],
|
|
19569
19569
|
read: ["status", "evidence", "logs", "transfer-plan", "promote-plan", "rollback-plan", "history", "deploy-plan", "diff", "promote-status", "preview-plan", "previews", "preview-list", "preview-status"],
|
|
19570
19570
|
write: ["release", "upload", "configure", "transfer", "promote", "promote-reconcile", "deploy", "rollback", "reconcile", "retire", "preview", "preview-create", "preview-reconcile", "preview-cleanup", "preview-pr"]
|
|
19571
19571
|
},
|
|
@@ -30033,6 +30033,7 @@ import { basename as basename8, dirname as dirname9, isAbsolute as isAbsolute6,
|
|
|
30033
30033
|
import { promisify as promisify2 } from "node:util";
|
|
30034
30034
|
import {
|
|
30035
30035
|
applyDiagnosticFix,
|
|
30036
|
+
assessMigration,
|
|
30036
30037
|
buildDeliveryProject,
|
|
30037
30038
|
checkProject,
|
|
30038
30039
|
compileProject,
|
|
@@ -30041,17 +30042,32 @@ import {
|
|
|
30041
30042
|
createExecutionContextPack,
|
|
30042
30043
|
createDiagnosticRepairPlan,
|
|
30043
30044
|
createInferencePlan,
|
|
30045
|
+
diffProjectContracts,
|
|
30044
30046
|
formatInferencePlan,
|
|
30045
30047
|
doctorProject,
|
|
30048
|
+
extractStaticSqlQueriesFromSource,
|
|
30049
|
+
formatContractDiffReport,
|
|
30046
30050
|
formatDoctorCheck,
|
|
30051
|
+
formatMigrationAssessment,
|
|
30052
|
+
generateMultiLangClient,
|
|
30053
|
+
lintArchitectureRules,
|
|
30054
|
+
lintAspectUsage,
|
|
30055
|
+
lintEffectErrorExhaustiveness,
|
|
30056
|
+
lintEnvContract,
|
|
30057
|
+
lintRlsIndexes,
|
|
30058
|
+
lintSqlAgainstCatalog,
|
|
30047
30059
|
loadSupacloudConfig,
|
|
30060
|
+
migrateProject,
|
|
30061
|
+
parseDataCatalogDocument,
|
|
30048
30062
|
formatDeliveryPlan,
|
|
30049
30063
|
planDeliveryProject,
|
|
30064
|
+
readOpenApiJson,
|
|
30050
30065
|
resolveSupacloudConfig,
|
|
30051
30066
|
readExecutionMetadata,
|
|
30052
30067
|
createProjectSemanticSnapshot,
|
|
30053
30068
|
createSemanticLens,
|
|
30054
|
-
watchProject
|
|
30069
|
+
watchProject,
|
|
30070
|
+
verifySqlQueriesAgainstPostgres
|
|
30055
30071
|
} from "@supacloud/compiler";
|
|
30056
30072
|
|
|
30057
30073
|
// src/shared/tools/app-tool-export.ts
|
|
@@ -30177,25 +30193,25 @@ var starter_metadata_default = {
|
|
|
30177
30193
|
generatedBy: "supacloud/starter-metadata-v1",
|
|
30178
30194
|
packages: {
|
|
30179
30195
|
compiler: {
|
|
30180
|
-
version: "0.
|
|
30196
|
+
version: "0.69.0"
|
|
30181
30197
|
},
|
|
30182
30198
|
app: {
|
|
30183
|
-
version: "0.
|
|
30199
|
+
version: "0.41.0",
|
|
30184
30200
|
dependencies: {
|
|
30185
30201
|
rxjs: "7.8.2"
|
|
30186
30202
|
}
|
|
30187
30203
|
},
|
|
30188
30204
|
elysia: {
|
|
30189
|
-
version: "0.
|
|
30205
|
+
version: "0.45.0"
|
|
30190
30206
|
},
|
|
30191
30207
|
commands: {
|
|
30192
|
-
version: "0.
|
|
30208
|
+
version: "0.15.0"
|
|
30193
30209
|
},
|
|
30194
30210
|
contracts: {
|
|
30195
30211
|
version: "0.17.0"
|
|
30196
30212
|
},
|
|
30197
30213
|
db: {
|
|
30198
|
-
version: "0.
|
|
30214
|
+
version: "0.29.0",
|
|
30199
30215
|
dependencies: {},
|
|
30200
30216
|
devDependencies: {},
|
|
30201
30217
|
peerDependencies: {
|
|
@@ -30203,7 +30219,7 @@ var starter_metadata_default = {
|
|
|
30203
30219
|
}
|
|
30204
30220
|
},
|
|
30205
30221
|
dbZenstack: {
|
|
30206
|
-
version: "0.
|
|
30222
|
+
version: "0.5.0",
|
|
30207
30223
|
dependencies: {
|
|
30208
30224
|
"@zenstackhq/orm": "3.10.0",
|
|
30209
30225
|
"@zenstackhq/schema": "3.10.0",
|
|
@@ -30220,7 +30236,7 @@ var starter_metadata_default = {
|
|
|
30220
30236
|
}
|
|
30221
30237
|
},
|
|
30222
30238
|
sdk: {
|
|
30223
|
-
version: "0.
|
|
30239
|
+
version: "0.50.0",
|
|
30224
30240
|
peerDependencies: {
|
|
30225
30241
|
"@supabase/supabase-js": "^2.118.0"
|
|
30226
30242
|
}
|
|
@@ -31391,6 +31407,9 @@ DROP POLICY IF EXISTS "model_orders_insert" ON "public"."model_orders";
|
|
|
31391
31407
|
CREATE POLICY "model_orders_insert" ON "public"."model_orders" FOR INSERT TO "authenticated" WITH CHECK (((((((auth.jwt() IS NOT NULL) AND ((auth.jwt() ->> 'canCreate') = 'true')) AND ("tenant_id" = (auth.jwt() ->> 'tenantId'))) AND ("owner_id" = (auth.jwt() ->> 'id'))) AND ("state" = 'draft')) AND ("version" = 1)));
|
|
31392
31408
|
DROP POLICY IF EXISTS "model_orders_update" ON "public"."model_orders";
|
|
31393
31409
|
CREATE POLICY "model_orders_update" ON "public"."model_orders" FOR UPDATE TO "authenticated" USING ((((auth.jwt() IS NOT NULL) AND ((auth.jwt() ->> 'canApprove') = 'true')) AND ("tenant_id" = (auth.jwt() ->> 'tenantId')))) WITH CHECK ((((auth.jwt() IS NOT NULL) AND ((auth.jwt() ->> 'canApprove') = 'true')) AND ("tenant_id" = (auth.jwt() ->> 'tenantId'))));
|
|
31410
|
+
REVOKE UPDATE ("tenant_id") ON "public"."model_orders" FROM "authenticated";
|
|
31411
|
+
REVOKE UPDATE ("id") ON "public"."model_orders" FROM "authenticated";
|
|
31412
|
+
REVOKE UPDATE ("owner_id") ON "public"."model_orders" FROM "authenticated";
|
|
31394
31413
|
GRANT USAGE ON SCHEMA public, supacloud_commands TO model_orders_app;
|
|
31395
31414
|
GRANT SELECT, INSERT, UPDATE ON public.model_orders TO model_orders_app;
|
|
31396
31415
|
GRANT SELECT, INSERT, UPDATE ON supacloud_commands.execution_receipts TO model_orders_app;
|
|
@@ -31739,6 +31758,10 @@ CREATE TABLE public.starter_attachment_results (
|
|
|
31739
31758
|
);
|
|
31740
31759
|
ALTER TABLE public.starter_attachments ENABLE ROW LEVEL SECURITY;
|
|
31741
31760
|
ALTER TABLE public.starter_attachment_results ENABLE ROW LEVEL SECURITY;
|
|
31761
|
+
DROP POLICY IF EXISTS "starter_attachments_select" ON "public"."starter_attachments";
|
|
31762
|
+
CREATE POLICY "starter_attachments_select" ON "public"."starter_attachments" FOR SELECT TO "authenticated" USING (((auth.jwt() IS NOT NULL) AND ("owner_id" = (auth.jwt() ->> 'id'))));
|
|
31763
|
+
DROP POLICY IF EXISTS "starter_attachment_results_select" ON "public"."starter_attachment_results";
|
|
31764
|
+
CREATE POLICY "starter_attachment_results_select" ON "public"."starter_attachment_results" FOR SELECT TO "authenticated" USING (((auth.jwt() IS NOT NULL) AND EXISTS (SELECT 1 FROM "public"."starter_reviews" AS "_rel_0" WHERE ("_rel_0"."id" = "public"."starter_attachment_results"."review_id") AND ("_rel_0"."owner_id" = (auth.jwt() ->> 'id')))));
|
|
31742
31765
|
`;
|
|
31743
31766
|
var STARTER_ATTACHMENT_POSTGRES = `import { SupaCloudArtifactsClient } from "@supacloud/js";
|
|
31744
31767
|
import type { SupabaseClient } from "@supabase/supabase-js";
|
|
@@ -32150,6 +32173,9 @@ GRANT SELECT (subject,enabled,can_approve,storage_subject) ON public.starter_mem
|
|
|
32150
32173
|
DROP POLICY IF EXISTS starter_member_read ON public.starter_members;
|
|
32151
32174
|
CREATE POLICY starter_member_read ON public.starter_members FOR SELECT TO authenticated
|
|
32152
32175
|
USING (subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND storage_subject=auth.uid());
|
|
32176
|
+
DROP POLICY IF EXISTS starter_member_storage_fence ON public.starter_members;
|
|
32177
|
+
CREATE POLICY starter_member_storage_fence ON public.starter_members AS RESTRICTIVE FOR SELECT TO authenticated
|
|
32178
|
+
USING (subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND storage_subject=auth.uid());
|
|
32153
32179
|
GRANT SELECT ON public.starter_reviews TO authenticated;
|
|
32154
32180
|
DROP POLICY IF EXISTS starter_review_read ON public.starter_reviews;
|
|
32155
32181
|
CREATE POLICY starter_review_read ON public.starter_reviews FOR SELECT TO authenticated
|
|
@@ -32157,6 +32183,12 @@ CREATE POLICY starter_review_read ON public.starter_reviews FOR SELECT TO authen
|
|
|
32157
32183
|
SELECT 1 FROM public.starter_members m WHERE m.subject=owner_id
|
|
32158
32184
|
AND m.enabled AND m.can_approve AND m.storage_subject=auth.uid()
|
|
32159
32185
|
));
|
|
32186
|
+
DROP POLICY IF EXISTS starter_review_storage_fence ON public.starter_reviews;
|
|
32187
|
+
CREATE POLICY starter_review_storage_fence ON public.starter_reviews AS RESTRICTIVE FOR SELECT TO authenticated
|
|
32188
|
+
USING (owner_id=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND EXISTS (
|
|
32189
|
+
SELECT 1 FROM public.starter_members m WHERE m.subject=owner_id
|
|
32190
|
+
AND m.enabled AND m.can_approve AND m.storage_subject=auth.uid()
|
|
32191
|
+
));
|
|
32160
32192
|
INSERT INTO storage.buckets(id,name,public,file_size_limit,allowed_mime_types)
|
|
32161
32193
|
VALUES ('review-attachments','review-attachments',false,1048576,ARRAY['text/plain']);
|
|
32162
32194
|
DROP POLICY IF EXISTS starter_attachment_read ON storage.objects;
|
|
@@ -32443,6 +32475,13 @@ CREATE TABLE public.starter_members (
|
|
|
32443
32475
|
ALTER TABLE public.starter_application ENABLE ROW LEVEL SECURITY;
|
|
32444
32476
|
ALTER TABLE public.starter_reviews ENABLE ROW LEVEL SECURITY;
|
|
32445
32477
|
ALTER TABLE public.starter_members ENABLE ROW LEVEL SECURITY;
|
|
32478
|
+
DO $supacloud_policy_rls$ BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'authenticated') THEN CREATE ROLE "authenticated" NOLOGIN; END IF; END $supacloud_policy_rls$;
|
|
32479
|
+
DROP POLICY IF EXISTS "starter_application_select" ON "public"."starter_application";
|
|
32480
|
+
CREATE POLICY "starter_application_select" ON "public"."starter_application" FOR SELECT TO "authenticated" USING ((auth.jwt() IS NOT NULL));
|
|
32481
|
+
DROP POLICY IF EXISTS "starter_reviews_select" ON "public"."starter_reviews";
|
|
32482
|
+
CREATE POLICY "starter_reviews_select" ON "public"."starter_reviews" FOR SELECT TO "authenticated" USING (((auth.jwt() IS NOT NULL) AND (("owner_id" = (auth.jwt() ->> 'id')) OR ((auth.jwt() ->> 'canApprove') = 'true'))));
|
|
32483
|
+
DROP POLICY IF EXISTS "starter_members_select" ON "public"."starter_members";
|
|
32484
|
+
CREATE POLICY "starter_members_select" ON "public"."starter_members" FOR SELECT TO "authenticated" USING (((auth.jwt() IS NOT NULL) AND ("subject" = (auth.jwt() ->> 'id'))));
|
|
32446
32485
|
`;
|
|
32447
32486
|
var STARTER_REVIEW_POSTGRES = `import { createTransactionalCommand, plaintextCommandInput } from "@supacloud/commands";
|
|
32448
32487
|
import { CommandError } from "@supacloud/contracts";
|
|
@@ -32723,8 +32762,7 @@ var STARTER_DATABASE_CONFIG = {
|
|
|
32723
32762
|
consumers: ["src", "scripts", "tests"],
|
|
32724
32763
|
auditConsumers: [],
|
|
32725
32764
|
trustedHosts: ["src/host", "src/delivery-host.ts", "src/delivery-worker.ts"],
|
|
32726
|
-
role: "starter_review_http"
|
|
32727
|
-
policyRls: "deferred"
|
|
32765
|
+
role: "starter_review_http"
|
|
32728
32766
|
};
|
|
32729
32767
|
var STARTER_DATABASE_MODEL = `datasource db {
|
|
32730
32768
|
provider = "postgresql"
|
|
@@ -32836,16 +32874,56 @@ export default defineDatabaseModule({
|
|
|
32836
32874
|
name, table, operation, roles: [...roles], source: "migrations/004-review-runtime-roles.sql",
|
|
32837
32875
|
tests: ["tests/database-governance.sql"],
|
|
32838
32876
|
})),
|
|
32877
|
+
{
|
|
32878
|
+
name: "starter_application_select", table: "public.starter_application", operation: "select",
|
|
32879
|
+
roles: ["authenticated"], source: "migrations/001-review.sql",
|
|
32880
|
+
tests: ["tests/database-governance.sql"],
|
|
32881
|
+
},
|
|
32882
|
+
{
|
|
32883
|
+
name: "starter_reviews_select", table: "public.starter_reviews", operation: "select",
|
|
32884
|
+
roles: ["authenticated"], source: "migrations/001-review.sql",
|
|
32885
|
+
tests: ["tests/database-governance.sql"],
|
|
32886
|
+
},
|
|
32887
|
+
{
|
|
32888
|
+
name: "starter_members_select", table: "public.starter_members", operation: "select",
|
|
32889
|
+
roles: ["authenticated"], source: "migrations/001-review.sql",
|
|
32890
|
+
tests: ["tests/database-governance.sql"],
|
|
32891
|
+
},
|
|
32892
|
+
{
|
|
32893
|
+
name: "starter_attachments_select", table: "public.starter_attachments", operation: "select",
|
|
32894
|
+
roles: ["authenticated"], source: "migrations/002-review-attachments.sql",
|
|
32895
|
+
tests: ["tests/database-governance.sql"],
|
|
32896
|
+
},
|
|
32897
|
+
{
|
|
32898
|
+
name: "starter_attachment_results_select", table: "public.starter_attachment_results", operation: "select",
|
|
32899
|
+
roles: ["authenticated"], source: "migrations/002-review-attachments.sql",
|
|
32900
|
+
tests: ["tests/database-governance.sql"],
|
|
32901
|
+
},
|
|
32902
|
+
{
|
|
32903
|
+
name: "starter_attachment_retries_select", table: "public.starter_attachment_retries", operation: "select",
|
|
32904
|
+
roles: ["authenticated"], source: "migrations/005-review-task-recovery.sql",
|
|
32905
|
+
tests: ["tests/database-governance.sql"],
|
|
32906
|
+
},
|
|
32839
32907
|
{
|
|
32840
32908
|
name: "starter_member_read", table: "public.starter_members", operation: "select",
|
|
32841
32909
|
roles: ["authenticated"], source: "migrations/003-review-uploads.sql",
|
|
32842
32910
|
tests: ["tests/database-governance.sql"],
|
|
32843
32911
|
},
|
|
32912
|
+
{
|
|
32913
|
+
name: "starter_member_storage_fence", table: "public.starter_members", operation: "select",
|
|
32914
|
+
roles: ["authenticated"], source: "migrations/003-review-uploads.sql",
|
|
32915
|
+
tests: ["tests/database-governance.sql"],
|
|
32916
|
+
},
|
|
32844
32917
|
{
|
|
32845
32918
|
name: "starter_review_read", table: "public.starter_reviews", operation: "select",
|
|
32846
32919
|
roles: ["authenticated"], source: "migrations/003-review-uploads.sql",
|
|
32847
32920
|
tests: ["tests/database-governance.sql"],
|
|
32848
32921
|
},
|
|
32922
|
+
{
|
|
32923
|
+
name: "starter_review_storage_fence", table: "public.starter_reviews", operation: "select",
|
|
32924
|
+
roles: ["authenticated"], source: "migrations/003-review-uploads.sql",
|
|
32925
|
+
tests: ["tests/database-governance.sql"],
|
|
32926
|
+
},
|
|
32849
32927
|
],
|
|
32850
32928
|
});
|
|
32851
32929
|
`;
|
|
@@ -32862,7 +32940,7 @@ BEGIN
|
|
|
32862
32940
|
END IF;
|
|
32863
32941
|
IF (SELECT count(*) FROM pg_policy p JOIN pg_class c ON c.oid=p.polrelid
|
|
32864
32942
|
JOIN pg_namespace n ON n.oid=c.relnamespace
|
|
32865
|
-
WHERE n.nspname='public' AND c.relname=ANY(owned)) <>
|
|
32943
|
+
WHERE n.nspname='public' AND c.relname=ANY(owned)) <> 28 THEN
|
|
32866
32944
|
RAISE EXCEPTION 'Starter policy inventory changed; reconcile db/modules.ts';
|
|
32867
32945
|
END IF;
|
|
32868
32946
|
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname IN ('starter_review_http','starter_review_worker')
|
|
@@ -32882,11 +32960,13 @@ var STARTER_DATABASE_GUIDE = `
|
|
|
32882
32960
|
Maintain zenstack/schema.zmodel. Run \`bun run db:generate\` to compile model and RPC
|
|
32883
32961
|
contracts; commit generated types with their sources. Do not introduce any/@ts-ignore
|
|
32884
32962
|
to bypass model or contract diagnostics. \`bun run db:check\` compares
|
|
32885
|
-
fresh generation without writing files or opening a database. This starter
|
|
32886
|
-
|
|
32887
|
-
|
|
32963
|
+
fresh generation without writing files or opening a database. This starter projects
|
|
32964
|
+
ZModel row policies (including explicit \`@relation(fields, references)\` EXISTS
|
|
32965
|
+
predicates) into \`authenticated\` RLS statements and checks them against the
|
|
32966
|
+
migration ledger, while storage fences and runtime-role policies remain explicit
|
|
32967
|
+
reviewed migrations. Command writes still use the shared
|
|
32888
32968
|
transaction, receipt and audit boundary, not unrestricted CRUD. SQL constraints, RPCs
|
|
32889
|
-
and
|
|
32969
|
+
and additional restrictive fences remain explicit reviewed migrations.
|
|
32890
32970
|
|
|
32891
32971
|
Use \`bun run db:plan\` to send the reviewed migration directory to the
|
|
32892
32972
|
Management API for a remote, read-only plan. Review the returned digest, then run
|
|
@@ -34039,6 +34119,8 @@ CREATE POLICY starter_http_retry_insert ON public.starter_attachment_retries
|
|
|
34039
34119
|
DROP POLICY IF EXISTS starter_worker_retry_read ON public.starter_attachment_retries;
|
|
34040
34120
|
CREATE POLICY starter_worker_retry_read ON public.starter_attachment_retries
|
|
34041
34121
|
FOR SELECT TO starter_review_worker USING (true);
|
|
34122
|
+
DROP POLICY IF EXISTS "starter_attachment_retries_select" ON "public"."starter_attachment_retries";
|
|
34123
|
+
CREATE POLICY "starter_attachment_retries_select" ON "public"."starter_attachment_retries" FOR SELECT TO "authenticated" USING (((auth.jwt() IS NOT NULL) AND EXISTS (SELECT 1 FROM "public"."starter_attachments" AS "_rel_0" WHERE ("_rel_0"."review_id" = "public"."starter_attachment_retries"."review_id") AND ("_rel_0"."owner_id" = (auth.jwt() ->> 'id')))));
|
|
34042
34124
|
-- Trusted HTTP adapters authorize the review before inspecting its bound run.
|
|
34043
34125
|
GRANT EXECUTE ON FUNCTION supacloud_workflows.snapshot(uuid,boolean) TO starter_review_http;
|
|
34044
34126
|
`;
|
|
@@ -36493,6 +36575,58 @@ Scenario: Delivery
|
|
|
36493
36575
|
`
|
|
36494
36576
|
};
|
|
36495
36577
|
}
|
|
36578
|
+
function featureTestingScaffold(name, className, table) {
|
|
36579
|
+
const [schemaName, tableName] = table.includes(".") ? table.split(".", 2) : ["public", table];
|
|
36580
|
+
return {
|
|
36581
|
+
[`${name}.governance.test.ts`]: `import { describe, test } from "bun:test";
|
|
36582
|
+
import { SQL } from "bun";
|
|
36583
|
+
import { assertRlsMatrix, runDurableCommandContractSuite, type SqlExecutor } from "@supacloud/testing";
|
|
36584
|
+
|
|
36585
|
+
const PG_URL = process.env["SUPACLOUD_TEST_PG_URL"];
|
|
36586
|
+
const runIfPg = PG_URL ? test : test.skip;
|
|
36587
|
+
|
|
36588
|
+
function adaptSql(db: SQL): SqlExecutor {
|
|
36589
|
+
return {
|
|
36590
|
+
async query<T = Record<string, unknown>>(statement: string, params?: unknown[]): Promise<T[]> {
|
|
36591
|
+
if (params && params.length > 0) return (await db.unsafe(statement, params)) as unknown as T[];
|
|
36592
|
+
return (await db.unsafe(statement)) as unknown as T[];
|
|
36593
|
+
},
|
|
36594
|
+
};
|
|
36595
|
+
}
|
|
36596
|
+
|
|
36597
|
+
describe("${className} governance contract", () => {
|
|
36598
|
+
runIfPg("enforces multi-role RLS matrix on ${schemaName}.${tableName}", async () => {
|
|
36599
|
+
const db = new SQL(PG_URL!);
|
|
36600
|
+
try {
|
|
36601
|
+
await assertRlsMatrix(adaptSql(db), {
|
|
36602
|
+
roles: [
|
|
36603
|
+
{ label: "anon", role: "anon" },
|
|
36604
|
+
{ label: "authenticated", role: "authenticated", jwtClaims: { sub: "00000000-0000-4000-8000-000000000001" } },
|
|
36605
|
+
],
|
|
36606
|
+
tables: [
|
|
36607
|
+
{
|
|
36608
|
+
schema: ${JSON.stringify(schemaName)},
|
|
36609
|
+
table: ${JSON.stringify(tableName)},
|
|
36610
|
+
probes: {},
|
|
36611
|
+
expectations: {
|
|
36612
|
+
anon: { select: "deny" },
|
|
36613
|
+
authenticated: { select: "empty" },
|
|
36614
|
+
},
|
|
36615
|
+
},
|
|
36616
|
+
],
|
|
36617
|
+
});
|
|
36618
|
+
} finally {
|
|
36619
|
+
await db.close();
|
|
36620
|
+
}
|
|
36621
|
+
});
|
|
36622
|
+
|
|
36623
|
+
test.skip("verifies ${name}.approve idempotency and rollback atomicity (wire runner)", async () => {
|
|
36624
|
+
void runDurableCommandContractSuite;
|
|
36625
|
+
});
|
|
36626
|
+
});
|
|
36627
|
+
`
|
|
36628
|
+
};
|
|
36629
|
+
}
|
|
36496
36630
|
|
|
36497
36631
|
// src/shared/tools/app-local-dev.ts
|
|
36498
36632
|
import { spawn } from "node:child_process";
|
|
@@ -37157,10 +37291,28 @@ export const ${prefix}Body = t.Object({});
|
|
|
37157
37291
|
export const ${prefix}Response = t.Object({});
|
|
37158
37292
|
`;
|
|
37159
37293
|
}
|
|
37294
|
+
function aspectScaffold(moduleName, name) {
|
|
37295
|
+
const prefix = pascalName(name);
|
|
37296
|
+
return `import { defineOperationAspect } from "@supacloud/app/core";
|
|
37297
|
+
|
|
37298
|
+
/**
|
|
37299
|
+
* Explicit static operation aspect for ${moduleName}.${camelName(name)}.
|
|
37300
|
+
* Keep capabilities minimal, return the actual continuation result unchanged,
|
|
37301
|
+
* preserve failures, and never start another transaction or automatic write retry.
|
|
37302
|
+
*/
|
|
37303
|
+
export const ${prefix}Aspect = defineOperationAspect({
|
|
37304
|
+
name: ${JSON.stringify(`${moduleName}.${camelName(name)}.aspect`)},
|
|
37305
|
+
capabilities: [],
|
|
37306
|
+
around(context, next) {
|
|
37307
|
+
return next(context);
|
|
37308
|
+
},
|
|
37309
|
+
});
|
|
37310
|
+
`;
|
|
37311
|
+
}
|
|
37160
37312
|
async function generateScaffold(args) {
|
|
37161
37313
|
const kind = args.kind;
|
|
37162
|
-
if (!kind || !["module", "command", "query", "controller", "job", "contract", "resource", "feature"].includes(kind)) {
|
|
37163
|
-
throw new ScaffoldError("SCAFFOLD_KIND_INVALID", "app generate requires --kind (module|command|query|controller|job|contract|resource|feature)");
|
|
37314
|
+
if (!kind || !["module", "command", "query", "controller", "job", "contract", "aspect", "resource", "feature"].includes(kind)) {
|
|
37315
|
+
throw new ScaffoldError("SCAFFOLD_KIND_INVALID", "app generate requires --kind (module|command|query|controller|job|contract|aspect|resource|feature)");
|
|
37164
37316
|
}
|
|
37165
37317
|
for (const flag of ["dry_run", "force"]) {
|
|
37166
37318
|
if (args[flag] !== undefined && typeof args[flag] !== "boolean") {
|
|
@@ -37255,18 +37407,23 @@ async function generateScaffold(args) {
|
|
|
37255
37407
|
}) : resourceScaffold(name, pascalName(name)))) {
|
|
37256
37408
|
writes.push({ path: join15(dir, name, file).replaceAll("\\", "/"), content });
|
|
37257
37409
|
}
|
|
37410
|
+
if (kind === "feature" && args.with_tests) {
|
|
37411
|
+
for (const [file, content] of Object.entries(featureTestingScaffold(name, pascalName(name), featureGovernance.database.table))) {
|
|
37412
|
+
writes.push({ path: join15(dir, name, file).replaceAll("\\", "/"), content });
|
|
37413
|
+
}
|
|
37414
|
+
}
|
|
37258
37415
|
} else {
|
|
37259
37416
|
if (!moduleName?.trim()) {
|
|
37260
37417
|
throw new ScaffoldError("SCAFFOLD_MODULE_REQUIRED", "app generate requires --module; no unique top-level module was inferred");
|
|
37261
37418
|
}
|
|
37262
37419
|
const targetModule = requireIdentifier(moduleName, "module");
|
|
37263
37420
|
const name = kind === "controller" ? targetModule : requireIdentifier(args.name, "name");
|
|
37264
|
-
const subdir = kind === "command" ? "commands" : kind === "query" ? "queries" : kind === "job" ? "jobs" : kind === "contract" ? "contracts" : "";
|
|
37421
|
+
const subdir = kind === "command" ? "commands" : kind === "query" ? "queries" : kind === "job" ? "jobs" : kind === "contract" ? "contracts" : kind === "aspect" ? "aspects" : "";
|
|
37265
37422
|
const path = join15(dir, targetModule, subdir, `${name}.${kind}.ts`).replaceAll("\\", "/");
|
|
37266
37423
|
if (kind === "controller" && existsSync13(scaffoldPath(root, path))) {
|
|
37267
37424
|
throw new ScaffoldError("SCAFFOLD_EXISTS", `Controller already exists: ${path}(请手工合并路由到现有 controller)`);
|
|
37268
37425
|
}
|
|
37269
|
-
const content = kind === "command" ? commandScaffold(targetModule, name) : kind === "query" ? queryScaffold(targetModule, name) : kind === "job" ? jobScaffold(targetModule, name) : kind === "contract" ? contractScaffold(targetModule, name) : controllerScaffold(targetModule);
|
|
37426
|
+
const content = kind === "command" ? commandScaffold(targetModule, name) : kind === "query" ? queryScaffold(targetModule, name) : kind === "job" ? jobScaffold(targetModule, name) : kind === "contract" ? contractScaffold(targetModule, name) : kind === "aspect" ? aspectScaffold(targetModule, name) : controllerScaffold(targetModule);
|
|
37270
37427
|
writes.push({ path, content, overwrite: args.force === true });
|
|
37271
37428
|
if (kind === "contract")
|
|
37272
37429
|
contractName = name;
|
|
@@ -38043,7 +38200,77 @@ async function runCheck(args) {
|
|
|
38043
38200
|
strict: args.strict ?? loadedConfig.strict ?? false
|
|
38044
38201
|
}, root);
|
|
38045
38202
|
const result = await checkProject(config);
|
|
38046
|
-
const
|
|
38203
|
+
const aspectDiagnostics = lintAspectUsage(result.graph);
|
|
38204
|
+
const effectDiagnostics = lintEffectErrorExhaustiveness(result.graph);
|
|
38205
|
+
const collectSourceFiles = async (dirPath) => {
|
|
38206
|
+
const out = [];
|
|
38207
|
+
const skipDirs = new Set(["node_modules", ".git", basename8(config.outDir)]);
|
|
38208
|
+
const walk = async (current) => {
|
|
38209
|
+
const entries = await readdir5(current, { withFileTypes: true }).catch(() => []);
|
|
38210
|
+
for (const entry of entries) {
|
|
38211
|
+
const full = join15(current, entry.name);
|
|
38212
|
+
if (entry.isDirectory()) {
|
|
38213
|
+
if (!skipDirs.has(entry.name))
|
|
38214
|
+
await walk(full);
|
|
38215
|
+
continue;
|
|
38216
|
+
}
|
|
38217
|
+
if (entry.isFile() && /\.(?:ts|mts|svelte)$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
|
|
38218
|
+
const relToSource = relative8(config.rootDir, full).replaceAll("\\", "/");
|
|
38219
|
+
out.push({
|
|
38220
|
+
file: relToSource,
|
|
38221
|
+
content: await readFile5(full, "utf8")
|
|
38222
|
+
});
|
|
38223
|
+
}
|
|
38224
|
+
}
|
|
38225
|
+
};
|
|
38226
|
+
await walk(config.rootDir);
|
|
38227
|
+
return out;
|
|
38228
|
+
};
|
|
38229
|
+
const sourceFiles = await collectSourceFiles(config.rootDir);
|
|
38230
|
+
const catalogCandidates = [
|
|
38231
|
+
join15(defaults.outDir, "data-catalog.json"),
|
|
38232
|
+
join15(root, "data-catalog.json"),
|
|
38233
|
+
join15(root, "generated", "data-catalog.json")
|
|
38234
|
+
];
|
|
38235
|
+
const catalogPath = catalogCandidates.find((candidate) => existsSync13(candidate));
|
|
38236
|
+
const sqlDiagnostics = [];
|
|
38237
|
+
if (catalogPath) {
|
|
38238
|
+
try {
|
|
38239
|
+
const catalogDoc = parseDataCatalogDocument(JSON.parse(await readFile5(catalogPath, "utf8")));
|
|
38240
|
+
for (const src of sourceFiles) {
|
|
38241
|
+
sqlDiagnostics.push(...lintSqlAgainstCatalog({ sourceText: src.content, file: src.file, catalog: catalogDoc }));
|
|
38242
|
+
}
|
|
38243
|
+
} catch {}
|
|
38244
|
+
}
|
|
38245
|
+
const archDiagnostics = loadedConfig.architectureRules?.length ? lintArchitectureRules({
|
|
38246
|
+
graph: result.graph,
|
|
38247
|
+
rules: loadedConfig.architectureRules,
|
|
38248
|
+
sourceFiles
|
|
38249
|
+
}) : [];
|
|
38250
|
+
const envDiagnostics = loadedConfig.envSchema ? lintEnvContract({
|
|
38251
|
+
envSchema: loadedConfig.envSchema,
|
|
38252
|
+
sourceFiles
|
|
38253
|
+
}) : [];
|
|
38254
|
+
const zmodelCandidates = [
|
|
38255
|
+
join15(root, "zenstack", "schema.zmodel"),
|
|
38256
|
+
join15(root, "prisma", "schema.zmodel"),
|
|
38257
|
+
join15(root, "schema.zmodel")
|
|
38258
|
+
];
|
|
38259
|
+
const zmodelPath = zmodelCandidates.find((candidate) => existsSync13(candidate));
|
|
38260
|
+
const rlsDiagnostics = zmodelPath ? lintRlsIndexes({
|
|
38261
|
+
file: projectRelativePath(root, zmodelPath) ?? "schema.zmodel",
|
|
38262
|
+
zmodelText: await readFile5(zmodelPath, "utf8")
|
|
38263
|
+
}) : [];
|
|
38264
|
+
const combinedDiagnostics = [
|
|
38265
|
+
...result.diagnostics,
|
|
38266
|
+
...aspectDiagnostics,
|
|
38267
|
+
...effectDiagnostics,
|
|
38268
|
+
...sqlDiagnostics,
|
|
38269
|
+
...archDiagnostics,
|
|
38270
|
+
...envDiagnostics,
|
|
38271
|
+
...rlsDiagnostics
|
|
38272
|
+
];
|
|
38273
|
+
const diagnosticError = combinedDiagnostics.some((diagnostic) => diagnostic.severity === "error");
|
|
38047
38274
|
const hasError = diagnosticError || result.mismatches.length > 0 || database?.ok === false;
|
|
38048
38275
|
const next = hasError ? diagnosticError || database?.ok === false ? ["supacloud app doctor --format json"] : ["supacloud app compile", "supacloud app check --format json"] : ["supacloud app verify-plan --target <module>"];
|
|
38049
38276
|
if (args.format === "json")
|
|
@@ -38052,7 +38279,7 @@ async function runCheck(args) {
|
|
|
38052
38279
|
ok: !hasError,
|
|
38053
38280
|
next,
|
|
38054
38281
|
source: "declaration",
|
|
38055
|
-
diagnostics:
|
|
38282
|
+
diagnostics: combinedDiagnostics,
|
|
38056
38283
|
mismatches: result.mismatches,
|
|
38057
38284
|
upToDate: result.upToDate,
|
|
38058
38285
|
written: [],
|
|
@@ -38061,7 +38288,7 @@ async function runCheck(args) {
|
|
|
38061
38288
|
}, null, 2), hasError);
|
|
38062
38289
|
const summary = `checked ${result.graph.modules.length} module(s), no files written`;
|
|
38063
38290
|
return textResult2([
|
|
38064
|
-
formatDiagnostics(
|
|
38291
|
+
formatDiagnostics(combinedDiagnostics),
|
|
38065
38292
|
...result.mismatches.map((path) => `generated artifact mismatch: ${path}`),
|
|
38066
38293
|
...database ? [formatDoctorCheck(database)] : [],
|
|
38067
38294
|
"",
|
|
@@ -38069,6 +38296,197 @@ async function runCheck(args) {
|
|
|
38069
38296
|
].join(`
|
|
38070
38297
|
`), hasError);
|
|
38071
38298
|
}
|
|
38299
|
+
async function runUpgrade(args) {
|
|
38300
|
+
const root = resolve20(args.root || process.cwd());
|
|
38301
|
+
const loadedConfig = await loadSupacloudConfig(root);
|
|
38302
|
+
const defaults = resolveSupacloudConfig(loadedConfig, root);
|
|
38303
|
+
const configuredRoot = sourceRoot(args, root, loadedConfig.root);
|
|
38304
|
+
const include = parseInclude(args.include) ?? loadedConfig.include;
|
|
38305
|
+
const compile = compileOptionsFromConfig({
|
|
38306
|
+
...loadedConfig,
|
|
38307
|
+
...configuredRoot === undefined ? {} : { root: configuredRoot },
|
|
38308
|
+
outDir: args.out_dir ? resolve20(root, args.out_dir) : defaults.outDir,
|
|
38309
|
+
...include === undefined ? {} : { include },
|
|
38310
|
+
strict: args.strict ?? loadedConfig.strict ?? false
|
|
38311
|
+
}, root);
|
|
38312
|
+
const assessment = await assessMigration({ projectDir: root, compile });
|
|
38313
|
+
const migrated = await migrateProject({ rootDir: compile.rootDir, include, write: args.write === true });
|
|
38314
|
+
const ok = assessment.ok && migrated.issues.length === 0;
|
|
38315
|
+
const payload = {
|
|
38316
|
+
version: 1,
|
|
38317
|
+
ok,
|
|
38318
|
+
dryRun: args.write !== true,
|
|
38319
|
+
status: assessment.status,
|
|
38320
|
+
findings: assessment.findings,
|
|
38321
|
+
migrations: migrated
|
|
38322
|
+
};
|
|
38323
|
+
if (args.format === "json") {
|
|
38324
|
+
return textResult2(JSON.stringify(payload, null, 2), !ok);
|
|
38325
|
+
}
|
|
38326
|
+
return textResult2([
|
|
38327
|
+
formatMigrationAssessment(assessment),
|
|
38328
|
+
"",
|
|
38329
|
+
`Migration ${args.write === true ? "applied" : "preview"}: ${migrated.files.length} file(s) scanned, ${migrated.changedFiles.length} changed.`
|
|
38330
|
+
].join(`
|
|
38331
|
+
`), !ok);
|
|
38332
|
+
}
|
|
38333
|
+
async function runClientSdk(args) {
|
|
38334
|
+
const root = resolve20(args.root || process.cwd());
|
|
38335
|
+
const language = args.lang;
|
|
38336
|
+
if (language !== "python" && language !== "go" && language !== "dart") {
|
|
38337
|
+
return textResult2("app client-sdk requires --lang python|go|dart", true);
|
|
38338
|
+
}
|
|
38339
|
+
const catalogFile = args.catalog ? resolve20(root, args.catalog) : undefined;
|
|
38340
|
+
const openapiFile = args.openapi ? resolve20(root, args.openapi) : undefined;
|
|
38341
|
+
const catalog = catalogFile && existsSync13(catalogFile) ? parseDataCatalogDocument(JSON.parse(await readFile5(catalogFile, "utf8"))) : undefined;
|
|
38342
|
+
const openapi = openapiFile && existsSync13(openapiFile) ? await readOpenApiJson(openapiFile) : undefined;
|
|
38343
|
+
const generated = generateMultiLangClient({
|
|
38344
|
+
language,
|
|
38345
|
+
catalog,
|
|
38346
|
+
openapi,
|
|
38347
|
+
packageName: args.package_name
|
|
38348
|
+
});
|
|
38349
|
+
if (args.out_dir) {
|
|
38350
|
+
const targetDir = resolve20(root, args.out_dir);
|
|
38351
|
+
await mkdir6(targetDir, { recursive: true });
|
|
38352
|
+
const targetFile = join15(targetDir, generated.filename);
|
|
38353
|
+
await writeFile5(targetFile, generated.content, "utf8");
|
|
38354
|
+
if (args.format === "json") {
|
|
38355
|
+
return textResult2(JSON.stringify({ ok: true, language, file: targetFile, summary: generated.summary }, null, 2));
|
|
38356
|
+
}
|
|
38357
|
+
return textResult2(`Generated ${language} SDK -> ${targetFile}`);
|
|
38358
|
+
}
|
|
38359
|
+
if (args.format === "json") {
|
|
38360
|
+
return textResult2(JSON.stringify({ ok: true, ...generated }, null, 2));
|
|
38361
|
+
}
|
|
38362
|
+
return textResult2(generated.content);
|
|
38363
|
+
}
|
|
38364
|
+
async function runContractDiff(args) {
|
|
38365
|
+
const root = resolve20(args.root || process.cwd());
|
|
38366
|
+
const loadedConfig = await loadSupacloudConfig(root);
|
|
38367
|
+
const defaults = resolveSupacloudConfig(loadedConfig, root);
|
|
38368
|
+
const outDir = args.out_dir ? resolve20(root, args.out_dir) : defaults.outDir;
|
|
38369
|
+
const resolveOptionalJson = async (explicitPath, fallbackPath) => {
|
|
38370
|
+
const candidate = explicitPath ? resolve20(root, explicitPath) : fallbackPath;
|
|
38371
|
+
if (!candidate || !existsSync13(candidate))
|
|
38372
|
+
return;
|
|
38373
|
+
return JSON.parse(await readFile5(candidate, "utf8"));
|
|
38374
|
+
};
|
|
38375
|
+
const resolveOptionalText = async (explicitPath, fallbackPath) => {
|
|
38376
|
+
const candidate = explicitPath ? resolve20(root, explicitPath) : fallbackPath;
|
|
38377
|
+
if (!candidate || !existsSync13(candidate))
|
|
38378
|
+
return;
|
|
38379
|
+
return await readFile5(candidate, "utf8");
|
|
38380
|
+
};
|
|
38381
|
+
const baselineOpenApi = args.baseline_openapi ? await readOpenApiJson(resolve20(root, args.baseline_openapi)) : undefined;
|
|
38382
|
+
const currentOpenApi = baselineOpenApi ? await resolveOptionalJson(args.current_openapi, join15(outDir, "openapi.json")) : undefined;
|
|
38383
|
+
const baselineAsyncApi = await resolveOptionalJson(args.baseline_asyncapi);
|
|
38384
|
+
const currentAsyncApi = baselineAsyncApi ? await resolveOptionalJson(args.current_asyncapi, join15(outDir, "asyncapi.json")) : undefined;
|
|
38385
|
+
const baselineCatalog = await resolveOptionalJson(args.baseline_catalog);
|
|
38386
|
+
const currentCatalog = baselineCatalog ? await resolveOptionalJson(args.current_catalog, join15(outDir, "data-catalog.json")) : undefined;
|
|
38387
|
+
const baselineRls = await resolveOptionalJson(args.baseline_rls);
|
|
38388
|
+
const currentRls = baselineRls ? await resolveOptionalJson(args.current_rls) : undefined;
|
|
38389
|
+
const baselineGraphqlSdl = await resolveOptionalText(args.baseline_graphql);
|
|
38390
|
+
const currentGraphqlSdl = baselineGraphqlSdl ? await resolveOptionalText(args.current_graphql, join15(outDir, "catalog.graphql")) : undefined;
|
|
38391
|
+
if (!baselineOpenApi && !baselineAsyncApi && !baselineCatalog && !baselineRls && !baselineGraphqlSdl) {
|
|
38392
|
+
return textResult2("app contract-diff requires at least one baseline contract (--baseline_openapi, --baseline_asyncapi, --baseline_catalog, --baseline_rls, or --baseline_graphql)", true);
|
|
38393
|
+
}
|
|
38394
|
+
const report = diffProjectContracts({
|
|
38395
|
+
...baselineOpenApi && currentOpenApi ? { baselineOpenApi, currentOpenApi } : {},
|
|
38396
|
+
...baselineAsyncApi && currentAsyncApi ? { baselineAsyncApi, currentAsyncApi } : {},
|
|
38397
|
+
...baselineCatalog && currentCatalog ? { baselineCatalog, currentCatalog } : {},
|
|
38398
|
+
...baselineRls && currentRls ? { baselineRls, currentRls } : {},
|
|
38399
|
+
...baselineGraphqlSdl && currentGraphqlSdl ? { baselineGraphqlSdl, currentGraphqlSdl } : {}
|
|
38400
|
+
});
|
|
38401
|
+
if (args.format === "json") {
|
|
38402
|
+
return textResult2(JSON.stringify(report, null, 2), !report.ok);
|
|
38403
|
+
}
|
|
38404
|
+
return textResult2(formatContractDiffReport(report), !report.ok);
|
|
38405
|
+
}
|
|
38406
|
+
async function collectTsFilesRecursive(dir, rootDir, out) {
|
|
38407
|
+
if (!existsSync13(dir))
|
|
38408
|
+
return;
|
|
38409
|
+
const entries = await readdir5(dir, { withFileTypes: true });
|
|
38410
|
+
for (const entry of entries) {
|
|
38411
|
+
if (entry.name === "node_modules" || entry.name === "generated" || entry.name.startsWith("."))
|
|
38412
|
+
continue;
|
|
38413
|
+
const full = join15(dir, entry.name);
|
|
38414
|
+
if (entry.isDirectory()) {
|
|
38415
|
+
await collectTsFilesRecursive(full, rootDir, out);
|
|
38416
|
+
} else if (entry.isFile() && entry.name.endsWith(".ts") && !entry.name.endsWith(".test.ts")) {
|
|
38417
|
+
out.push({
|
|
38418
|
+
file: relative8(rootDir, full).replaceAll("\\", "/"),
|
|
38419
|
+
content: await readFile5(full, "utf8")
|
|
38420
|
+
});
|
|
38421
|
+
}
|
|
38422
|
+
}
|
|
38423
|
+
}
|
|
38424
|
+
async function runSqlPrepare(args) {
|
|
38425
|
+
const root = resolve20(args.root || process.cwd());
|
|
38426
|
+
const srcFiles = [];
|
|
38427
|
+
await collectTsFilesRecursive(join15(root, "src"), root, srcFiles);
|
|
38428
|
+
const queries = extractStaticSqlQueriesFromSource(srcFiles);
|
|
38429
|
+
const cacheFile = args.cache_path ? resolve20(root, args.cache_path) : join15(root, ".supacloud", "sql-prepare-cache.json");
|
|
38430
|
+
const offline = args.offline === true || !args.database_url;
|
|
38431
|
+
if (offline) {
|
|
38432
|
+
const cache = existsSync13(cacheFile) ? JSON.parse(await readFile5(cacheFile, "utf8")) : undefined;
|
|
38433
|
+
const report = await verifySqlQueriesAgainstPostgres({
|
|
38434
|
+
queries,
|
|
38435
|
+
cache,
|
|
38436
|
+
offline: true,
|
|
38437
|
+
...args.schema_hash ? { schemaHash: args.schema_hash } : {}
|
|
38438
|
+
});
|
|
38439
|
+
if (args.format === "json") {
|
|
38440
|
+
return textResult2(JSON.stringify(report, null, 2), !report.ok);
|
|
38441
|
+
}
|
|
38442
|
+
return textResult2(report.ok ? `SQL prepare offline verification passed (${report.verifiedCount} query/queries).` : report.diagnostics.map((d) => `${d.errorCode ?? d.code}: ${d.message}`).join(`
|
|
38443
|
+
`), !report.ok);
|
|
38444
|
+
}
|
|
38445
|
+
const dbUrl = args.database_url;
|
|
38446
|
+
const pgClient = new Bun.SQL(dbUrl);
|
|
38447
|
+
let seq = 0;
|
|
38448
|
+
const executor = {
|
|
38449
|
+
async prepare(sqlText) {
|
|
38450
|
+
const cleanSql = sqlText.trim().replace(/;+$/, "").trim();
|
|
38451
|
+
if (!cleanSql)
|
|
38452
|
+
return { ok: false, error: "SQL statement must not be empty" };
|
|
38453
|
+
seq += 1;
|
|
38454
|
+
const stmt = `supacloud_cli_prepare_${seq}`;
|
|
38455
|
+
try {
|
|
38456
|
+
await pgClient.unsafe(`PREPARE ${stmt} AS ${cleanSql}`);
|
|
38457
|
+
const meta = await pgClient.unsafe("SELECT parameter_types::text[] AS param_types FROM pg_prepared_statements WHERE name = $1", [stmt]);
|
|
38458
|
+
const firstRow = Array.isArray(meta) ? meta[0] : undefined;
|
|
38459
|
+
const paramTypes = Array.isArray(firstRow?.param_types) ? firstRow.param_types.filter((t) => typeof t === "string") : [];
|
|
38460
|
+
return { ok: true, paramTypes, columns: [] };
|
|
38461
|
+
} catch (err) {
|
|
38462
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
38463
|
+
const code = err && typeof err === "object" && "code" in err && typeof err.code === "string" ? err.code : undefined;
|
|
38464
|
+
return { ok: false, error: msg, ...code ? { code } : {} };
|
|
38465
|
+
} finally {
|
|
38466
|
+
await pgClient.unsafe(`DEALLOCATE ${stmt}`).catch(() => {});
|
|
38467
|
+
}
|
|
38468
|
+
}
|
|
38469
|
+
};
|
|
38470
|
+
try {
|
|
38471
|
+
const report = await verifySqlQueriesAgainstPostgres({
|
|
38472
|
+
queries,
|
|
38473
|
+
executor,
|
|
38474
|
+
...args.schema_hash ? { schemaHash: args.schema_hash } : {}
|
|
38475
|
+
});
|
|
38476
|
+
if (report.ok && args.write === true) {
|
|
38477
|
+
await mkdir6(dirname9(cacheFile), { recursive: true });
|
|
38478
|
+
await writeFile5(cacheFile, `${JSON.stringify(report.cache, null, 2)}
|
|
38479
|
+
`, "utf8");
|
|
38480
|
+
}
|
|
38481
|
+
if (args.format === "json") {
|
|
38482
|
+
return textResult2(JSON.stringify(report, null, 2), !report.ok);
|
|
38483
|
+
}
|
|
38484
|
+
return textResult2(report.ok ? `SQL prepare live verification passed (${report.verifiedCount} query/queries).` : report.diagnostics.map((d) => `${d.errorCode ?? d.code}: ${d.message}`).join(`
|
|
38485
|
+
`), !report.ok);
|
|
38486
|
+
} finally {
|
|
38487
|
+
await pgClient.close();
|
|
38488
|
+
}
|
|
38489
|
+
}
|
|
38072
38490
|
function projectRelativePath(root, path) {
|
|
38073
38491
|
const value = relative8(root, path).replaceAll("\\", "/");
|
|
38074
38492
|
return value === ".." || value.startsWith("../") || value.startsWith("/") ? undefined : value;
|
|
@@ -38985,6 +39403,14 @@ async function runAppTool(request, options = {}) {
|
|
|
38985
39403
|
return runDoctor(request);
|
|
38986
39404
|
case "fix":
|
|
38987
39405
|
return runFix(request);
|
|
39406
|
+
case "upgrade":
|
|
39407
|
+
return runUpgrade(request);
|
|
39408
|
+
case "client-sdk":
|
|
39409
|
+
return runClientSdk(request);
|
|
39410
|
+
case "contract-diff":
|
|
39411
|
+
return runContractDiff(request);
|
|
39412
|
+
case "sql-prepare":
|
|
39413
|
+
return runSqlPrepare(request);
|
|
38988
39414
|
default:
|
|
38989
39415
|
return textResult2(`Unknown app action: ${String(request.action)}`, true);
|
|
38990
39416
|
}
|
|
@@ -39009,6 +39435,10 @@ function registerAppTools(server, options = {}) {
|
|
|
39009
39435
|
"lens",
|
|
39010
39436
|
"doctor",
|
|
39011
39437
|
"fix",
|
|
39438
|
+
"upgrade",
|
|
39439
|
+
"client-sdk",
|
|
39440
|
+
"contract-diff",
|
|
39441
|
+
"sql-prepare",
|
|
39012
39442
|
"plan",
|
|
39013
39443
|
"build",
|
|
39014
39444
|
"release",
|
|
@@ -39041,7 +39471,7 @@ function registerAppTools(server, options = {}) {
|
|
|
39041
39471
|
"promote-status",
|
|
39042
39472
|
"promote-reconcile"
|
|
39043
39473
|
]), "App action; promote obtains and verifies its plan before one mutation request"),
|
|
39044
|
-
kind: optional(stringEnum2(["module", "command", "query", "controller", "job", "contract", "resource", "feature"]), "[generate] Scaffold kind"),
|
|
39474
|
+
kind: optional(stringEnum2(["module", "command", "query", "controller", "job", "contract", "aspect", "resource", "feature"]), "[generate] Scaffold kind"),
|
|
39045
39475
|
template: optional(stringEnum2(["minimal", "client", "command", "model-command", "app"]), "[init] minimal (default) is the compiler/Effect stack; client is @supabase/supabase-js only; command is the native-SQL reference; model-command adds ZenStack HTTP/worker commands; app is an alias of minimal"),
|
|
39046
39476
|
name: optional(String2(), "[init/generate] Project or object name"),
|
|
39047
39477
|
module: optional(String2(), "[generate] Target feature module; inferred when the project has one top-level module"),
|
|
@@ -39072,8 +39502,26 @@ function registerAppTools(server, options = {}) {
|
|
|
39072
39502
|
fix: optional(String2(), "[fix] Path to a DiagnosticFix JSON file produced by `doctor --format json`"),
|
|
39073
39503
|
from_doctor: optional(String2(), "[fix] Read one fix from a doctor --format json output"),
|
|
39074
39504
|
fix_index: optional(Number2({ minimum: 0, multipleOf: 1 }), "[fix] Zero-based fixPlan index used with --from-doctor"),
|
|
39075
|
-
write: optional(Boolean2(), "[fix] Write
|
|
39076
|
-
skip_build: optional(Boolean2(), "[release] Reuse --manifest_path instead of running the local delivery build")
|
|
39505
|
+
write: optional(Boolean2(), "[fix/upgrade/client-sdk] Write changes or generated SDK files to disk (default: preview only)"),
|
|
39506
|
+
skip_build: optional(Boolean2(), "[release] Reuse --manifest_path instead of running the local delivery build"),
|
|
39507
|
+
lang: optional(stringEnum2(["python", "go", "dart"]), "[client-sdk] Target client language"),
|
|
39508
|
+
catalog: optional(String2(), "[client-sdk] Path to data-catalog.json"),
|
|
39509
|
+
openapi: optional(String2(), "[client-sdk] Path to OpenAPI JSON document"),
|
|
39510
|
+
baseline_openapi: optional(String2(), "[contract-diff] Baseline OpenAPI JSON path"),
|
|
39511
|
+
current_openapi: optional(String2(), "[contract-diff] Current OpenAPI JSON path"),
|
|
39512
|
+
baseline_asyncapi: optional(String2(), "[contract-diff] Baseline AsyncAPI JSON path"),
|
|
39513
|
+
current_asyncapi: optional(String2(), "[contract-diff] Current AsyncAPI JSON path"),
|
|
39514
|
+
baseline_catalog: optional(String2(), "[contract-diff] Baseline DataCatalog JSON path"),
|
|
39515
|
+
current_catalog: optional(String2(), "[contract-diff] Current DataCatalog JSON path"),
|
|
39516
|
+
baseline_graphql: optional(String2(), "[contract-diff] Baseline GraphQL SDL path"),
|
|
39517
|
+
current_graphql: optional(String2(), "[contract-diff] Current GraphQL SDL path"),
|
|
39518
|
+
baseline_rls: optional(String2(), "[contract-diff] Baseline RLS snapshot JSON path"),
|
|
39519
|
+
current_rls: optional(String2(), "[contract-diff] Current RLS snapshot JSON path"),
|
|
39520
|
+
cache_path: optional(String2(), "[sql-prepare] SQL prepare cache path (default: .supacloud/sql-prepare-cache.json)"),
|
|
39521
|
+
offline: optional(Boolean2(), "[sql-prepare] Verify SQL against offline cache without connecting to PostgreSQL"),
|
|
39522
|
+
schema_hash: optional(String2(), "[sql-prepare] Expected ZModel schema hash for drift check"),
|
|
39523
|
+
package_name: optional(String2(), "[client-sdk] Package/module name for generated client"),
|
|
39524
|
+
with_tests: optional(Boolean2(), "[generate feature] Also scaffold a @supacloud/testing test file")
|
|
39077
39525
|
}, (request) => runAppTool(request, options));
|
|
39078
39526
|
}
|
|
39079
39527
|
|
|
@@ -44686,7 +45134,7 @@ async function runProjectDeployment(http, args) {
|
|
|
44686
45134
|
// package.json
|
|
44687
45135
|
var package_default = {
|
|
44688
45136
|
name: "@supacloud/cli",
|
|
44689
|
-
version: "0.
|
|
45137
|
+
version: "0.131.0",
|
|
44690
45138
|
description: "Project-scoped CLI for SupaCloud users",
|
|
44691
45139
|
type: "module",
|
|
44692
45140
|
main: "./dist/index.js",
|
|
@@ -44738,23 +45186,23 @@ var package_default = {
|
|
|
44738
45186
|
directory: "packages/cli"
|
|
44739
45187
|
},
|
|
44740
45188
|
dependencies: {
|
|
44741
|
-
"@supacloud/compiler": "^0.
|
|
45189
|
+
"@supacloud/compiler": "^0.69.0",
|
|
44742
45190
|
"@supacloud/delivery": "0.30.1",
|
|
44743
|
-
"@supacloud/db": "0.
|
|
45191
|
+
"@supacloud/db": "0.29.0",
|
|
44744
45192
|
typebox: "1.4.3"
|
|
44745
45193
|
},
|
|
44746
45194
|
overrides: {
|
|
44747
45195
|
"@supacloud/contracts": "0.17.0",
|
|
44748
45196
|
"@supacloud/delivery": "0.30.1",
|
|
44749
45197
|
"@graphql-tools/utils": "^12.0.4",
|
|
44750
|
-
"@supacloud/compiler": "^0.
|
|
44751
|
-
"@supacloud/db": "0.
|
|
45198
|
+
"@supacloud/compiler": "^0.69.0",
|
|
45199
|
+
"@supacloud/db": "0.29.0",
|
|
44752
45200
|
"deepmerge-ts": "8.0.2",
|
|
44753
45201
|
prisma: "6.19.3"
|
|
44754
45202
|
},
|
|
44755
45203
|
devDependencies: {
|
|
44756
45204
|
"@supabase/supabase-js": "2.118.0",
|
|
44757
|
-
"@supacloud/elysia": "0.
|
|
45205
|
+
"@supacloud/elysia": "0.45.0",
|
|
44758
45206
|
"@types/bun": "^1.4.5",
|
|
44759
45207
|
effect: "4.0.5",
|
|
44760
45208
|
elysia: "2.0.0-rc.6",
|
|
@@ -13,3 +13,8 @@ export declare function featureScaffold(name: string, className: string, governa
|
|
|
13
13
|
};
|
|
14
14
|
databaseImportPath?: string;
|
|
15
15
|
}): Record<string, string>;
|
|
16
|
+
/**
|
|
17
|
+
* Generates an executable `@supacloud/testing` multi-role RLS matrix & Durable
|
|
18
|
+
* Command contract verification test template alongside a feature slice.
|
|
19
|
+
*/
|
|
20
|
+
export declare function featureTestingScaffold(name: string, className: string, table: string): Record<string, string>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const STARTER_ATTACHMENT_SCHEMA = "-- Apply with the migration owner, never from an application process.\nCREATE TABLE public.starter_attachments (\n review_id text PRIMARY KEY REFERENCES public.starter_reviews(id),\n artifact_id uuid NOT NULL UNIQUE, owner_id text NOT NULL, run_id uuid NOT NULL UNIQUE,\n object_path text NOT NULL UNIQUE\n);\nCREATE TABLE public.starter_attachment_results (\n review_id text NOT NULL REFERENCES public.starter_reviews(id),\n version integer NOT NULL CHECK (version >= 2), artifact_id uuid NOT NULL,\n result jsonb NOT NULL, PRIMARY KEY(review_id,version,artifact_id)\n);\nALTER TABLE public.starter_attachments ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.starter_attachment_results ENABLE ROW LEVEL SECURITY;\n";
|
|
1
|
+
export declare const STARTER_ATTACHMENT_SCHEMA = "-- Apply with the migration owner, never from an application process.\nCREATE TABLE public.starter_attachments (\n review_id text PRIMARY KEY REFERENCES public.starter_reviews(id),\n artifact_id uuid NOT NULL UNIQUE, owner_id text NOT NULL, run_id uuid NOT NULL UNIQUE,\n object_path text NOT NULL UNIQUE\n);\nCREATE TABLE public.starter_attachment_results (\n review_id text NOT NULL REFERENCES public.starter_reviews(id),\n version integer NOT NULL CHECK (version >= 2), artifact_id uuid NOT NULL,\n result jsonb NOT NULL, PRIMARY KEY(review_id,version,artifact_id)\n);\nALTER TABLE public.starter_attachments ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.starter_attachment_results ENABLE ROW LEVEL SECURITY;\nDROP POLICY IF EXISTS \"starter_attachments_select\" ON \"public\".\"starter_attachments\";\nCREATE POLICY \"starter_attachments_select\" ON \"public\".\"starter_attachments\" FOR SELECT TO \"authenticated\" USING (((auth.jwt() IS NOT NULL) AND (\"owner_id\" = (auth.jwt() ->> 'id'))));\nDROP POLICY IF EXISTS \"starter_attachment_results_select\" ON \"public\".\"starter_attachment_results\";\nCREATE POLICY \"starter_attachment_results_select\" ON \"public\".\"starter_attachment_results\" FOR SELECT TO \"authenticated\" USING (((auth.jwt() IS NOT NULL) AND EXISTS (SELECT 1 FROM \"public\".\"starter_reviews\" AS \"_rel_0\" WHERE (\"_rel_0\".\"id\" = \"public\".\"starter_attachment_results\".\"review_id\") AND (\"_rel_0\".\"owner_id\" = (auth.jwt() ->> 'id')))));\n";
|
|
2
2
|
export declare const STARTER_ATTACHMENT_POSTGRES = "import { SupaCloudArtifactsClient } from \"@supacloud/js\";\nimport type { SupabaseClient } from \"@supabase/supabase-js\";\nimport type { CommandDatabase, CommandTransaction } from \"@supacloud/db\";\nimport { createSchemaDecoder } from \"@supacloud/elysia\";\nimport { AttachmentResult, type ReviewAttachmentInput, type ReviewAttachmentResult, type ReviewAttachmentStore } from \"../review/attachment\";\n\nexport interface ReviewAttachmentOptions {\n database: CommandDatabase;\n // Provision this client for the same project as the database; never use a caller's bearer token.\n service: SupabaseClient;\n projectId: string;\n tenantId: string;\n}\n\nfunction rows(value: unknown): Record<string, unknown>[] {\n if (!Array.isArray(value)) throw new TypeError(\"Invalid attachment database result\");\n return value.map(record);\n}\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction record(value: unknown): Record<string, unknown> {\n if (!isRecord(value)) throw new TypeError(\"Invalid attachment record\");\n return value;\n}\nconst durableResult = createSchemaDecoder(AttachmentResult, { normalize: false });\n\nfunction resultFor(input: ReviewAttachmentInput, value: unknown): ReviewAttachmentResult {\n const result = durableResult(value);\n if (result.reviewId !== input.reviewId || result.version !== input.version\n || result.artifactId !== input.artifactId) throw new Error(\"Conflicting durable attachment result\");\n return result;\n}\n\nexport async function createReviewAttachmentAdapters(options: ReviewAttachmentOptions): Promise<{\n store: ReviewAttachmentStore;\n enqueue(tx: CommandTransaction, reviewId: string, version: number): Promise<void>;\n}> {\n const { database, service, projectId, tenantId } = options;\n if (!projectId.trim() || !tenantId.trim()) throw new TypeError(\"Attachment project/tenant is required\");\n const artifacts = new SupaCloudArtifactsClient(service);\n const binding = rows(await database.transaction(tx => tx.query(\n \"SELECT project_id,tenant_id FROM public.starter_application WHERE singleton\",\n )));\n if (binding.length !== 1 || binding[0]?.[\"project_id\"] !== projectId || binding[0]?.[\"tenant_id\"] !== tenantId) {\n throw new Error(\"Attachment database project/tenant binding mismatch\");\n }\n async function authorize(tx: CommandTransaction, input: ReviewAttachmentInput) {\n const allowed = rows(await tx.query(\n \"SELECT a.object_path,a.run_id FROM public.starter_attachments a \" +\n \"JOIN public.starter_reviews r ON r.id=a.review_id AND r.owner_id=a.owner_id \" +\n \"JOIN public.starter_members m ON m.subject=a.owner_id AND m.enabled AND m.can_approve \" +\n \"CROSS JOIN public.starter_application p \" +\n \"WHERE a.review_id=$1 AND a.artifact_id=$2 AND r.version=$3 AND r.state='approved' \" +\n \"AND p.singleton AND p.project_id=$4 AND p.tenant_id=$5 \" +\n \"FOR UPDATE OF r,a,m FOR SHARE OF p\",\n [input.reviewId, input.artifactId, input.version, projectId, tenantId],\n ));\n if (allowed.length !== 1 || typeof allowed[0]?.[\"object_path\"] !== \"string\") {\n throw new Error(\"Attachment worker authorization or review revision is no longer valid\");\n }\n return allowed[0];\n }\n return {\n async enqueue(tx, reviewId, version) {\n const found = rows(await tx.query(\n \"SELECT artifact_id FROM public.starter_attachments WHERE review_id=$1\", [reviewId],\n ))[0];\n if (!found) return;\n const input = { reviewId, version, artifactId: String(found[\"artifact_id\"]) };\n const allowed = await authorize(tx, input);\n // Bind serialized JSON as text so drivers cannot encode the string as a JSON scalar.\n await tx.query(\"SELECT supacloud_workflows.start_run($1::uuid,$2,'1','verify',$3::text::jsonb,3)\", [\n String(allowed[\"run_id\"]), \"review.verify-attachment\", JSON.stringify(input),\n ]);\n },\n store: {\n async readResult(input) {\n return database.transaction(async tx => {\n await authorize(tx, input);\n const saved = rows(await tx.query(\n \"SELECT result FROM public.starter_attachment_results WHERE review_id=$1 AND version=$2 AND artifact_id=$3\",\n [input.reviewId, input.version, input.artifactId],\n ));\n return saved.length === 0 ? null : resultFor(input, saved[0]?.[\"result\"]);\n });\n },\n async readAttachment(input) {\n const allowed = await database.transaction(tx => authorize(tx, input));\n const artifact = await artifacts.get(input.artifactId);\n if (!artifact || artifact.bucketId !== \"review-attachments\"\n || artifact.objectPath !== allowed[\"object_path\"] || artifact.artifactType !== \"review.attachment\"\n || artifact.mimeType !== \"text/plain\" || !/^[1-9][0-9]*$/.test(artifact.sizeBytes)\n || BigInt(artifact.sizeBytes) > 1048576n) throw new Error(\"Invalid attachment artifact\");\n const downloaded = await service.storage.from(artifact.bucketId).download(artifact.objectPath);\n if (downloaded.error || !downloaded.data) throw new Error(\"Attachment download failed\");\n if (downloaded.data.size !== Number(artifact.sizeBytes)) throw new Error(\"Attachment size mismatch\");\n return { body: new Uint8Array(await downloaded.data.arrayBuffer()), sha256: artifact.sha256 };\n },\n async recordAttachment(input, result) {\n const decoded = resultFor(input, result);\n return database.transaction(async tx => {\n await authorize(tx, input);\n await tx.query(\n \"INSERT INTO public.starter_attachment_results VALUES($1,$2,$3,$4::text::jsonb) ON CONFLICT DO NOTHING\",\n [input.reviewId, input.version, input.artifactId, JSON.stringify(decoded)],\n );\n const saved = rows(await tx.query(\n \"SELECT result FROM public.starter_attachment_results WHERE review_id=$1 AND version=$2 AND artifact_id=$3\",\n [input.reviewId, input.version, input.artifactId],\n ))[0]?.[\"result\"];\n const value = resultFor(input, saved);\n if (value.sha256 !== decoded.sha256 || value.bytes !== decoded.bytes) {\n throw new Error(\"Conflicting durable attachment result\");\n }\n return value;\n });\n },\n },\n };\n}\n";
|
|
@@ -9,11 +9,10 @@ export declare const STARTER_DATABASE_CONFIG: {
|
|
|
9
9
|
auditConsumers: never[];
|
|
10
10
|
trustedHosts: string[];
|
|
11
11
|
role: string;
|
|
12
|
-
policyRls: string;
|
|
13
12
|
};
|
|
14
13
|
export declare const STARTER_DATABASE_MODEL = "datasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\nplugin policy {\n provider = \"@zenstackhq/plugin-policy\"\n}\ntype Principal {\n id String\n canApprove Boolean\n @@auth()\n}\nmodel Application {\n singleton Boolean @id @default(true)\n projectId String @map(\"project_id\")\n tenantId String @map(\"tenant_id\")\n @@map(\"starter_application\")\n @@allow(\"read\", auth() != null)\n}\nmodel Review {\n id String @id\n ownerId String @map(\"owner_id\")\n state String\n version Int\n attachment Attachment?\n results AttachmentResult[]\n @@map(\"starter_reviews\")\n @@allow(\"read\", auth() != null && (ownerId == auth().id || auth().canApprove))\n}\nmodel Member {\n subject String @id\n enabled Boolean @default(true)\n canApprove Boolean @default(false) @map(\"can_approve\")\n storageSubject String? @unique @db.Uuid @map(\"storage_subject\")\n @@map(\"starter_members\")\n @@allow(\"read\", auth() != null && subject == auth().id)\n}\nmodel Attachment {\n reviewId String @id @map(\"review_id\")\n review Review @relation(fields: [reviewId], references: [id])\n artifactId String @unique @db.Uuid @map(\"artifact_id\")\n ownerId String @map(\"owner_id\")\n runId String @unique @db.Uuid @map(\"run_id\")\n objectPath String @unique @map(\"object_path\")\n retries AttachmentRetry[]\n @@map(\"starter_attachments\")\n @@allow(\"read\", auth() != null && ownerId == auth().id)\n}\nmodel AttachmentResult {\n reviewId String @map(\"review_id\")\n review Review @relation(fields: [reviewId], references: [id])\n version Int\n artifactId String @db.Uuid @map(\"artifact_id\")\n result Json\n @@id([reviewId, version, artifactId])\n @@map(\"starter_attachment_results\")\n @@allow(\"read\", auth() != null && review.ownerId == auth().id)\n}\nmodel AttachmentRetry {\n runId String @id @db.Uuid @map(\"run_id\")\n reviewId String @map(\"review_id\")\n attachment Attachment @relation(fields: [reviewId], references: [reviewId])\n previousRunId String @unique @db.Uuid @map(\"previous_run_id\")\n generation Int\n @@unique([reviewId, generation])\n @@map(\"starter_attachment_retries\")\n @@allow(\"read\", auth() != null && attachment.ownerId == auth().id)\n}\n";
|
|
15
14
|
export declare const STARTER_DATABASE_SCHEMA = "export type { Review as ReviewRow, Attachment as AttachmentRow, AttachmentRetry as AttachmentRetryRow } from \"../zenstack/generated/models\";\nimport type { Review } from \"../zenstack/generated/models\";\nexport type NewReview = Review;\n";
|
|
16
|
-
export declare const STARTER_DATABASE_MODULES = "import { defineDatabaseModule } from \"@supacloud/db\";\n\nconst backendPolicies = [\n [\"starter_backend_binding_read\", \"public.starter_application\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_binding_lock\", \"public.starter_application\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_binding_immutable\", \"public.starter_application\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_read\", \"public.starter_members\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_lock\", \"public.starter_members\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_immutable\", \"public.starter_members\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_review_read\", \"public.starter_reviews\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_review_update\", \"public.starter_reviews\", \"update\", [\"starter_review_http\"]],\n [\"starter_worker_review_immutable\", \"public.starter_reviews\", \"update\", [\"starter_review_worker\"]],\n [\"starter_backend_attachment_read\", \"public.starter_attachments\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_attachment_lock\", \"public.starter_attachments\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_attachment_immutable\", \"public.starter_attachments\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_http_attachment_insert\", \"public.starter_attachments\", \"insert\", [\"starter_review_http\"]],\n [\"starter_worker_result_read\", \"public.starter_attachment_results\", \"select\", [\"starter_review_worker\"]],\n [\"starter_worker_result_insert\", \"public.starter_attachment_results\", \"insert\", [\"starter_review_worker\"]],\n] as const;\n\n// The module is the single live-Catalog ownership contract for starter tables.\nexport default defineDatabaseModule({\n name: \"starter\",\n tables: [\"public.starter_application\", \"public.starter_reviews\", \"public.starter_members\", \"public.starter_attachments\", \"public.starter_attachment_results\", \"public.starter_attachment_retries\"],\n policies: [\n ...([\n [\"starter_http_retry_read\", \"select\", \"starter_review_http\"],\n [\"starter_http_retry_insert\", \"insert\", \"starter_review_http\"],\n [\"starter_worker_retry_read\", \"select\", \"starter_review_worker\"],\n ] as const).map(([name, operation, role]) => ({\n name, table: \"public.starter_attachment_retries\", operation, roles: [role],\n source: \"migrations/005-review-task-recovery.sql\", tests: [\"tests/database-governance.sql\"],\n })),\n ...backendPolicies.map(([name, table, operation, roles]) => ({\n name, table, operation, roles: [...roles], source: \"migrations/004-review-runtime-roles.sql\",\n tests: [\"tests/database-governance.sql\"],\n })),\n {\n name: \"starter_member_read\", table: \"public.starter_members\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_review_read\", table: \"public.starter_reviews\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n ],\n});\n";
|
|
17
|
-
export declare const STARTER_DATABASE_TEST = "-- Read-only catalog assertions; behavioral authorization tests remain separate.\nBEGIN READ ONLY;\nDO $test$\nDECLARE\n owned text[] := ARRAY['starter_application','starter_reviews','starter_members',\n 'starter_attachments','starter_attachment_results','starter_attachment_retries'];\nBEGIN\n IF (SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace\n WHERE n.nspname='public' AND c.relname=ANY(owned) AND c.relrowsecurity) <> 6 THEN\n RAISE EXCEPTION 'All starter tables must exist with RLS enabled';\n END IF;\n IF (SELECT count(*) FROM pg_policy p JOIN pg_class c ON c.oid=p.polrelid\n JOIN pg_namespace n ON n.oid=c.relnamespace\n WHERE n.nspname='public' AND c.relname=ANY(owned)) <>
|
|
18
|
-
export declare const STARTER_DATABASE_GUIDE = "\n## Model and migration workflow\n\nMaintain zenstack/schema.zmodel. Run `bun run db:generate` to compile model and RPC\ncontracts; commit generated types with their sources. Do not introduce any/@ts-ignore\nto bypass model or contract diagnostics. `bun run db:check` compares\nfresh generation without writing files or opening a database. This starter
|
|
15
|
+
export declare const STARTER_DATABASE_MODULES = "import { defineDatabaseModule } from \"@supacloud/db\";\n\nconst backendPolicies = [\n [\"starter_backend_binding_read\", \"public.starter_application\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_binding_lock\", \"public.starter_application\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_binding_immutable\", \"public.starter_application\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_read\", \"public.starter_members\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_lock\", \"public.starter_members\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_immutable\", \"public.starter_members\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_review_read\", \"public.starter_reviews\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_review_update\", \"public.starter_reviews\", \"update\", [\"starter_review_http\"]],\n [\"starter_worker_review_immutable\", \"public.starter_reviews\", \"update\", [\"starter_review_worker\"]],\n [\"starter_backend_attachment_read\", \"public.starter_attachments\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_attachment_lock\", \"public.starter_attachments\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_attachment_immutable\", \"public.starter_attachments\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_http_attachment_insert\", \"public.starter_attachments\", \"insert\", [\"starter_review_http\"]],\n [\"starter_worker_result_read\", \"public.starter_attachment_results\", \"select\", [\"starter_review_worker\"]],\n [\"starter_worker_result_insert\", \"public.starter_attachment_results\", \"insert\", [\"starter_review_worker\"]],\n] as const;\n\n// The module is the single live-Catalog ownership contract for starter tables.\nexport default defineDatabaseModule({\n name: \"starter\",\n tables: [\"public.starter_application\", \"public.starter_reviews\", \"public.starter_members\", \"public.starter_attachments\", \"public.starter_attachment_results\", \"public.starter_attachment_retries\"],\n policies: [\n ...([\n [\"starter_http_retry_read\", \"select\", \"starter_review_http\"],\n [\"starter_http_retry_insert\", \"insert\", \"starter_review_http\"],\n [\"starter_worker_retry_read\", \"select\", \"starter_review_worker\"],\n ] as const).map(([name, operation, role]) => ({\n name, table: \"public.starter_attachment_retries\", operation, roles: [role],\n source: \"migrations/005-review-task-recovery.sql\", tests: [\"tests/database-governance.sql\"],\n })),\n ...backendPolicies.map(([name, table, operation, roles]) => ({\n name, table, operation, roles: [...roles], source: \"migrations/004-review-runtime-roles.sql\",\n tests: [\"tests/database-governance.sql\"],\n })),\n {\n name: \"starter_application_select\", table: \"public.starter_application\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/001-review.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_reviews_select\", table: \"public.starter_reviews\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/001-review.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_members_select\", table: \"public.starter_members\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/001-review.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_attachments_select\", table: \"public.starter_attachments\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/002-review-attachments.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_attachment_results_select\", table: \"public.starter_attachment_results\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/002-review-attachments.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_attachment_retries_select\", table: \"public.starter_attachment_retries\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/005-review-task-recovery.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_member_read\", table: \"public.starter_members\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_member_storage_fence\", table: \"public.starter_members\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_review_read\", table: \"public.starter_reviews\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_review_storage_fence\", table: \"public.starter_reviews\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n ],\n});\n";
|
|
16
|
+
export declare const STARTER_DATABASE_TEST = "-- Read-only catalog assertions; behavioral authorization tests remain separate.\nBEGIN READ ONLY;\nDO $test$\nDECLARE\n owned text[] := ARRAY['starter_application','starter_reviews','starter_members',\n 'starter_attachments','starter_attachment_results','starter_attachment_retries'];\nBEGIN\n IF (SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace\n WHERE n.nspname='public' AND c.relname=ANY(owned) AND c.relrowsecurity) <> 6 THEN\n RAISE EXCEPTION 'All starter tables must exist with RLS enabled';\n END IF;\n IF (SELECT count(*) FROM pg_policy p JOIN pg_class c ON c.oid=p.polrelid\n JOIN pg_namespace n ON n.oid=c.relnamespace\n WHERE n.nspname='public' AND c.relname=ANY(owned)) <> 28 THEN\n RAISE EXCEPTION 'Starter policy inventory changed; reconcile db/modules.ts';\n END IF;\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname IN ('starter_review_http','starter_review_worker')\n AND (rolsuper OR rolbypassrls)) THEN\n RAISE EXCEPTION 'Starter roles must not bypass row security';\n END IF;\n IF (SELECT count(*) FROM pg_roles WHERE rolname IN ('starter_review_http','starter_review_worker')) <> 2 THEN\n RAISE EXCEPTION 'Starter runtime roles are missing';\n END IF;\nEND\n$test$;\nROLLBACK;\n";
|
|
17
|
+
export declare const STARTER_DATABASE_GUIDE = "\n## Model and migration workflow\n\nMaintain zenstack/schema.zmodel. Run `bun run db:generate` to compile model and RPC\ncontracts; commit generated types with their sources. Do not introduce any/@ts-ignore\nto bypass model or contract diagnostics. `bun run db:check` compares\nfresh generation without writing files or opening a database. This starter projects\nZModel row policies (including explicit `@relation(fields, references)` EXISTS\npredicates) into `authenticated` RLS statements and checks them against the\nmigration ledger, while storage fences and runtime-role policies remain explicit\nreviewed migrations. Command writes still use the shared\ntransaction, receipt and audit boundary, not unrestricted CRUD. SQL constraints, RPCs\nand additional restrictive fences remain explicit reviewed migrations.\n\nUse `bun run db:plan` to send the reviewed migration directory to the\nManagement API for a remote, read-only plan. Review the returned digest, then run\n`bun run db:apply -- --approved_digest <digest>` to apply the exact same bytes\nthrough the project migration ledger. Neither command needs DATABASE_URL or a\npublic PostgreSQL port. Never run zen migrate deploy or db push against a managed\nproduction database.\n`bun run db:pull -- --candidate output/database-audit/schema.zmodel` uses the\nsame Management API binding and writes a review candidate only; it never\noverwrites the maintained model. Add policies before adopting introspection\noutput. Keep one migration history and preserve RLS.\n\nAdopting a database that has no model yet starts with the same command: pull\nintrospects through a temporary datasource-only model inside the Management API,\nso no hand-written ZModel is required. Review the candidate, add the policy\nplugin and @@allow rules, move it to zenstack/schema.zmodel, then run\n`bun run db:generate`. Until that file exists, `db:plan` and\n`db:generate` fail closed instead of building from an unreviewed\nintrospection result. Keep the host wiring unchanged: one\ncreateZenStackDatabase composition root supplies read-only models and the\ntransactional command store.\n";
|
|
19
18
|
export declare function starterDatabaseFiles(): Record<string, string>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const STARTER_REVIEW_SCHEMA = "-- Apply with the platform migration owner, never from the HTTP process.\n-- One application database belongs to one explicitly provisioned project/tenant.\nCREATE TABLE public.starter_application (\n singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),\n project_id text NOT NULL CHECK (length(project_id) > 0),\n tenant_id text NOT NULL CHECK (length(tenant_id) > 0)\n);\nCREATE TABLE public.starter_reviews (\n id text PRIMARY KEY, owner_id text NOT NULL,\n state text NOT NULL CHECK (state IN ('draft','approved')),\n version integer NOT NULL CHECK (version > 0)\n);\nCREATE TABLE public.starter_members (\n subject text PRIMARY KEY, enabled boolean NOT NULL DEFAULT true,\n can_approve boolean NOT NULL DEFAULT false\n);\nALTER TABLE public.starter_application ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.starter_reviews ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.starter_members ENABLE ROW LEVEL SECURITY;\n";
|
|
1
|
+
export declare const STARTER_REVIEW_SCHEMA = "-- Apply with the platform migration owner, never from the HTTP process.\n-- One application database belongs to one explicitly provisioned project/tenant.\nCREATE TABLE public.starter_application (\n singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),\n project_id text NOT NULL CHECK (length(project_id) > 0),\n tenant_id text NOT NULL CHECK (length(tenant_id) > 0)\n);\nCREATE TABLE public.starter_reviews (\n id text PRIMARY KEY, owner_id text NOT NULL,\n state text NOT NULL CHECK (state IN ('draft','approved')),\n version integer NOT NULL CHECK (version > 0)\n);\nCREATE TABLE public.starter_members (\n subject text PRIMARY KEY, enabled boolean NOT NULL DEFAULT true,\n can_approve boolean NOT NULL DEFAULT false\n);\nALTER TABLE public.starter_application ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.starter_reviews ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.starter_members ENABLE ROW LEVEL SECURITY;\nDO $supacloud_policy_rls$ BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'authenticated') THEN CREATE ROLE \"authenticated\" NOLOGIN; END IF; END $supacloud_policy_rls$;\nDROP POLICY IF EXISTS \"starter_application_select\" ON \"public\".\"starter_application\";\nCREATE POLICY \"starter_application_select\" ON \"public\".\"starter_application\" FOR SELECT TO \"authenticated\" USING ((auth.jwt() IS NOT NULL));\nDROP POLICY IF EXISTS \"starter_reviews_select\" ON \"public\".\"starter_reviews\";\nCREATE POLICY \"starter_reviews_select\" ON \"public\".\"starter_reviews\" FOR SELECT TO \"authenticated\" USING (((auth.jwt() IS NOT NULL) AND ((\"owner_id\" = (auth.jwt() ->> 'id')) OR ((auth.jwt() ->> 'canApprove') = 'true'))));\nDROP POLICY IF EXISTS \"starter_members_select\" ON \"public\".\"starter_members\";\nCREATE POLICY \"starter_members_select\" ON \"public\".\"starter_members\" FOR SELECT TO \"authenticated\" USING (((auth.jwt() IS NOT NULL) AND (\"subject\" = (auth.jwt() ->> 'id'))));\n";
|
|
2
2
|
export declare const STARTER_REVIEW_POSTGRES = "import { createTransactionalCommand, plaintextCommandInput } from \"@supacloud/commands\";\nimport { CommandError } from \"@supacloud/contracts\";\nimport { createPostgresCommandStore, type CommandDatabase, type CommandTransaction } from \"@supacloud/db\";\nimport {\n ApplicationError, createSchemaDecoder, createSupAuthRequestContext, requireTrustedIdentity,\n createTransactionalCommandGovernance,\n type SupAuthContextOptions,\n} from \"@supacloud/elysia\";\nimport type { AppAdapters } from \"../application\";\nimport type { ReviewStore } from \"../review/review\";\nimport type { ReviewUploadPort } from \"../review/uploads\";\nimport type { ReviewTaskPort } from \"../review/tasks\";\nimport { ApprovalInput, ReviewResult } from \"../review/contracts\";\nimport type { ReviewRow } from \"../../db/schema\";\n\nconst input = createSchemaDecoder(ApprovalInput, { normalize: false });\nconst result: (value: unknown) => Pick<ReviewRow, \"state\" | \"version\"> =\n createSchemaDecoder(ReviewResult, { normalize: false });\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction record(value: unknown): Record<string, unknown> {\n if (!isRecord(value)) throw new TypeError(\"Invalid review record\");\n return value;\n}\nfunction rows(value: unknown): Record<string, unknown>[] {\n if (!Array.isArray(value)) throw new TypeError(\"Invalid database result\");\n return value.map(record);\n}\nfunction isPublicConflict(value: unknown): boolean {\n return value instanceof ApplicationError && value.status === 409\n || isRecord(value) && value[\"expose\"] === true && value[\"status\"] === 409 && typeof value[\"code\"] === \"string\";\n}\nexport interface ReviewPostgresOptions {\n database: CommandDatabase;\n tenantId: string;\n identity: Omit<SupAuthContextOptions, \"resolveAccess\">;\n uploads?: ReviewUploadPort;\n tasks?: ReviewTaskPort;\n // Only database effects here: they commit/rollback with the approval and receipt.\n afterApproved?(tx: CommandTransaction, id: string, version: number): Promise<void>;\n}\n\nexport async function createReviewPostgresAdapters(options: ReviewPostgresOptions): Promise<\n AppAdapters & { requestContext: ReturnType<typeof createSupAuthRequestContext> }\n> {\n const { database, tenantId, identity } = options;\n const projectId = identity.projectId;\n const afterApproved = options.afterApproved;\n if (!tenantId.trim()) throw new TypeError(\"Review tenantId is required\");\n const query = (text: string, parameters: readonly string[] = []) =>\n database.transaction(tx => tx.query(text, parameters));\n const binding = rows(await query(\n \"SELECT project_id,tenant_id FROM public.starter_application WHERE singleton\",\n ));\n if (binding.length !== 1 || binding[0]?.[\"project_id\"] !== projectId || binding[0]?.[\"tenant_id\"] !== tenantId) {\n throw new Error(\"Review database project/tenant binding mismatch\");\n }\n const requestContext = createSupAuthRequestContext({\n ...identity,\n async resolveAccess(who) {\n const found = rows(await query(\n \"SELECT m.can_approve FROM public.starter_members m,public.starter_application a \" +\n \"WHERE m.subject=$1 AND m.enabled AND a.singleton AND a.project_id=$2 AND a.tenant_id=$3\",\n [who.subject, projectId, tenantId],\n ));\n return found.length === 1 ? { projectId, tenantId,\n permissions: found[0]?.[\"can_approve\"] === true ? [\"review.approve\"] : [],\n } : null;\n },\n });\n const transaction = () => commandBinding.transaction();\n const store: ReviewStore = {\n ...options.uploads,\n ...options.tasks,\n async lookupOperation(context, operation) {\n const subject = actor(context);\n try {\n let confirmed: boolean = false;\n if (operation.kind === \"upload\") {\n if (!options.uploads?.lookupUpload) {\n throw new ApplicationError(\"Upload receipt lookup unavailable\", { status: 503, code: \"RECEIPTS_UNAVAILABLE\" });\n }\n confirmed = await options.uploads.lookupUpload(context, {\n reviewId: operation.reviewId, artifactId: operation.operationId, expectedVersion: operation.expectedVersion,\n });\n } else {\n const command = createTransactionalCommand({\n name: \"review.approve\", store: commandStore, inputCodec: plaintextCommandInput, input, result,\n authorize: authorizeApproval,\n execute: async () => { throw new Error(\"Receipt lookup cannot execute a command\"); },\n audit: { event: \"review.approved\", details: request => ({ reviewId: request.id }) },\n });\n const receipt = await command.lookup({ actorId: subject, tenantId }, operation.operationId,\n { id: operation.reviewId, expectedVersion: operation.expectedVersion });\n confirmed = receipt?.status === \"confirmed\";\n }\n return { status: confirmed ? \"confirmed\" : \"unknown\", operationId: operation.operationId, reviewId: operation.reviewId };\n } catch (error) {\n if (error instanceof ApplicationError) throw error;\n if (error instanceof CommandError && [\"COMMAND_REJECTED\", \"COMMAND_IDEMPOTENCY_CONFLICT\"].includes(error.code)) {\n throw new ApplicationError(error.code, { code: error.code, status: error.code === \"COMMAND_REJECTED\" ? 403 : 409 });\n }\n throw new ApplicationError(\"Receipt lookup unavailable\", { status: 503, code: \"RECEIPTS_UNAVAILABLE\" });\n }\n },\n async get(table, id) {\n if (table !== \"reviews\") throw new Error(\"Unsupported review table\");\n return rows(await transaction().query(\n \"SELECT state,version FROM public.starter_reviews WHERE id=$1 FOR UPDATE\", [id],\n ))[0];\n },\n async set(table, id, value) {\n if (table !== \"reviews\") throw new Error(\"Unsupported review table\");\n const review = result(value);\n const updated = rows(await transaction().query(\n \"UPDATE public.starter_reviews SET state=$2,version=$3 WHERE id=$1 RETURNING id\",\n [id, review.state, review.version],\n ));\n if (updated.length !== 1) throw new Error(\"Review write did not update one record\");\n await afterApproved?.(transaction(), id, review.version);\n },\n };\n function actor(context: unknown): string {\n const who = requireTrustedIdentity(context);\n const access = record(record(context)[\"access\"]);\n if (access[\"projectId\"] !== projectId || access[\"tenantId\"] !== tenantId\n || !Array.isArray(access[\"permissions\"]) || !access[\"permissions\"].includes(\"review.approve\")) {\n throw new ApplicationError(\"Command permission denied\", { status: 403, code: \"REVIEW_PERMISSION_DENIED\" });\n }\n return who.subject;\n }\n const commandStore = createPostgresCommandStore(database);\n async function authorizeApproval(who: { actorId: string; tenantId: string }, request: ReturnType<typeof input>, tx: CommandTransaction): Promise<\"allow\" | \"deny\"> {\n const found = rows(await tx.query(\n \"SELECT r.id FROM public.starter_reviews r JOIN public.starter_members m ON m.subject=r.owner_id \" +\n \"CROSS JOIN public.starter_application a \" +\n \"WHERE r.id=$1 AND r.owner_id=$2 AND m.enabled AND m.can_approve \" +\n \"AND a.singleton AND a.project_id=$3 AND a.tenant_id=$4 FOR UPDATE OF r,m FOR SHARE OF a\",\n [request.id, who.actorId, projectId, who.tenantId],\n ));\n return found.length === 1 ? \"allow\" : \"deny\";\n }\n const commandBinding = createTransactionalCommandGovernance({\n permission: \"review.approve\",\n identity: invocation => ({ actorId: actor(invocation.requestContext), tenantId }),\n input: invocation => ({\n ...record(invocation.input.body), id: invocation.input.params[\"id\"],\n }),\n rejection: error => isPublicConflict(error) ? new CommandError(\"COMMAND_IDEMPOTENCY_CONFLICT\") : undefined,\n definition: {\n name: \"review.approve\", store: commandStore,\n inputCodec: plaintextCommandInput, input, result,\n authorize: authorizeApproval,\n audit: { event: \"review.approved\", details: request => ({ reviewId: request.id }) },\n },\n });\n return { deps: { dbClient: store }, requestContext, commandGovernance: commandBinding.governance };\n}\n";
|
|
3
3
|
export declare const STARTER_REVIEW_POSTGRES_TEST = "import { expect, test } from \"bun:test\";\nimport { createReviewPostgresAdapters } from \"../src/host/review-postgres\";\nimport type { ReviewStore } from \"../src/review/review\";\n\nconst identity = {\n issuer: \"https://identity.example.test\", audience: \"review-test\", clientId: \"review-client\",\n projectId: \"review-test\", jwksUrl: \"https://identity.example.test/jwks\",\n};\nfunction database(binding: unknown) {\n const queries: string[] = [];\n return {\n queries,\n async transaction<T>(run: (tx: { query(text: string): Promise<unknown> }) => Promise<T>): Promise<T> {\n return run({ async query(text) { queries.push(text); return binding; } });\n },\n };\n}\n\ntest(\"PostgreSQL host rejects missing or mismatched application ownership without creating data\", async () => {\n for (const binding of [[], [{ project_id: \"other\", tenant_id: \"review-test\" }],\n [{ project_id: \"review-test\", tenant_id: \"other\" }]]) {\n const db = database(binding);\n await expect(createReviewPostgresAdapters({ database: db, identity, tenantId: \"review-test\" }))\n .rejects.toThrow(\"binding mismatch\");\n expect(db.queries).toEqual([\"SELECT project_id,tenant_id FROM public.starter_application WHERE singleton\"]);\n }\n});\n\ntest(\"PostgreSQL host never falls back to demo identity or unbound business storage\", async () => {\n const db = database([{ project_id: \"review-test\", tenant_id: \"review-test\" }]);\n const adapters = await createReviewPostgresAdapters({ database: db, identity, tenantId: \"review-test\" });\n await expect(adapters.requestContext(new Request(\"http://localhost/reviews/health\")))\n .rejects.toMatchObject({ code: \"AUTHENTICATION_REQUIRED\" });\n const store = adapters.deps[\"dbClient\"] as ReviewStore;\n await expect(store.get(\"reviews\", \"example\")).rejects.toThrow(\"not active\");\n await expect(store.set(\"reviews\", \"example\", { state: \"approved\", version: 2 }))\n .rejects.toThrow(\"not active\");\n expect(db.queries).toHaveLength(1);\n});\n";
|
|
4
4
|
export declare const STARTER_REVIEW_DELIVERY_HOST = "\nimport { createClient } from \"@supabase/supabase-js\";\nimport { createBunCommandDatabase, createBunSqlHost } from \"@supacloud/db/bun\";\nimport { createApplication, type CompiledModule } from \"@supacloud/elysia\";\nimport { createReviewPostgresAdapters } from \"./host/review-postgres\";\nimport { createReviewAttachmentAdapters } from \"./host/review-attachments\";\nimport { createReviewUploadAdapters } from \"./host/review-uploads\";\nimport { createReviewTaskAdapters } from \"./host/review-tasks\";\nimport { createReviewHttpObserver } from \"./host/review-execution-observability\";\n\nfunction required(name: string): string {\n const value = process.env[name];\n if (!value?.trim()) throw new Error(\"Missing required host setting: \" + name);\n return value;\n}\n\nexport async function createDeliveryApplication(modules: CompiledModule[], lifecycle: { signal: AbortSignal }) {\n lifecycle.signal.throwIfAborted();\n const attachments = process.env[\"REVIEW_ATTACHMENTS\"];\n if (attachments !== undefined && attachments !== \"enabled\") throw new Error(\"Invalid attachment configuration\");\n const settings = {\n tenantId: required(\"APP_TENANT_ID\"),\n identity: {\n issuer: required(\"SUPAUTH_ISSUER\"), audience: required(\"SUPAUTH_AUDIENCE\"),\n clientId: required(\"SUPAUTH_CLIENT_ID\"), projectId: required(\"SUPACLOUD_PROJECT_ID\"),\n jwksUrl: required(\"SUPAUTH_JWKS_URL\"),\n },\n };\n const host = createBunSqlHost({ max: 12, connectionTimeout: 5 });\n const pool = host.pool;\n let closing: Promise<void> | undefined;\n const close = () => closing ??= host.close();\n let stage: \"attachments\" | \"uploads\" | \"postgres\" | \"application\" = \"attachments\";\n try {\n const database = createBunCommandDatabase(pool);\n const attachmentOptions = attachments === \"enabled\" ? {\n database, tenantId: settings.tenantId, projectId: settings.identity.projectId,\n service: createClient(required(\"SUPACLOUD_URL\"), required(\"SUPACLOUD_SERVICE_ROLE_KEY\"), {\n auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false },\n }),\n } : undefined;\n const durable = attachmentOptions ? await createReviewAttachmentAdapters(attachmentOptions) : undefined;\n stage = \"uploads\";\n const uploads = attachmentOptions ? await createReviewUploadAdapters(attachmentOptions) : undefined;\n const tasks = attachmentOptions ? await createReviewTaskAdapters(attachmentOptions) : undefined;\n stage = \"postgres\";\n const adapters = await createReviewPostgresAdapters({\n database, tenantId: settings.tenantId, identity: settings.identity,\n ...(uploads ? { uploads } : {}),\n ...(tasks ? { tasks } : {}),\n ...(durable ? { afterApproved: durable.enqueue } : {}),\n });\n lifecycle.signal.throwIfAborted();\n stage = \"application\";\n const app = createApplication({ name: \"review\", modules, ...adapters, onExecution: createReviewHttpObserver() });\n return { fetch: (request: Request) => app.handle(request), close };\n } catch (error) {\n await close();\n const code = error !== null && typeof error === \"object\" && \"code\" in error\n && typeof error.code === \"string\" && /^[A-Z0-9_]{1,64}$/.test(error.code) ? error.code : \"UNKNOWN\";\n console.error(JSON.stringify({ event: \"review-host-initialization-failed\", stage, code }));\n // Database/identity errors can contain connection details; never echo the underlying cause.\n throw new Error(\"Review host initialization failed\");\n }\n}\n";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export declare const STARTER_TASK_CONTRACTS = "import { t, type UnwrapSchema } from \"elysia\";\nimport { AttachmentResult } from \"./attachment\";\nimport { REVIEW_VERSION_MAX } from \"./limits\";\nimport { ReviewVersion } from \"./contracts\";\n\nexport const TaskParams = t.Object({ id: t.String({ minLength: 1, maxLength: 100 }) }, { additionalProperties: false });\nexport const RetryBody = t.Object({\n expectedVersion: t.Integer({ minimum: 2, maximum: REVIEW_VERSION_MAX }),\n expectedRunId: t.String({ format: \"uuid\" }),\n recoveryId: t.String({ format: \"uuid\" }),\n}, { additionalProperties: false });\nexport const RetryInput = t.Object({\n reviewId: TaskParams.properties.id, ...RetryBody.properties,\n}, { additionalProperties: false });\nexport const TaskStatus = t.Object({\n reviewId: TaskParams.properties.id,\n version: ReviewVersion,\n artifactId: t.Nullable(t.String({ format: \"uuid\" })),\n runId: t.Nullable(t.String({ format: \"uuid\" })),\n state: t.Union([t.Literal(\"not_submitted\"), t.Literal(\"queued\"), t.Literal(\"running\"),\n t.Literal(\"completed\"), t.Literal(\"failed\"), t.Literal(\"cancelled\")]),\n attempts: t.Integer({ minimum: 0 }),\n maxAttempts: t.Literal(3),\n canRetry: t.Boolean(),\n result: t.Nullable(AttachmentResult),\n}, { additionalProperties: false });\nexport const RetryResult = t.Object({\n reviewId: TaskParams.properties.id,\n previousRunId: t.String({ format: \"uuid\" }),\n runId: t.String({ format: \"uuid\" }),\n state: t.Literal(\"queued\"),\n}, { additionalProperties: false });\nexport type ReviewTaskStatus = UnwrapSchema<typeof TaskStatus>;\nexport type ReviewRetryBody = UnwrapSchema<typeof RetryBody>;\nexport type ReviewRetryInput = UnwrapSchema<typeof RetryInput>;\nexport type ReviewRetryResult = UnwrapSchema<typeof RetryResult>;\n";
|
|
2
2
|
export declare const STARTER_TASK_FEATURE = "import { Effect } from \"effect\";\nimport { Body, Controller, DB_CLIENT, Get, Inject, Injectable, Param, Post, REQUEST_CONTEXT } from \"@supacloud/app\";\nimport { ApplicationError } from \"@supacloud/elysia\";\nimport { RetryBody, RetryResult, TaskParams, TaskStatus,\n type ReviewRetryBody, type ReviewRetryInput, type ReviewRetryResult, type ReviewTaskStatus } from \"./task-contracts\";\n\nexport interface ReviewTaskPort {\n attachmentTask(context: unknown, reviewId: string): Promise<ReviewTaskStatus>;\n retryAttachmentTask(context: unknown, input: ReviewRetryInput): Promise<ReviewRetryResult>;\n}\ntype TaskError =\n | { readonly _tag: \"AUTHENTICATION_REQUIRED\" }\n | { readonly _tag: \"TASK_INPUT_INVALID\" }\n | { readonly _tag: \"TASK_DENIED\" }\n | { readonly _tag: \"TASK_CONFLICT\" }\n | { readonly _tag: \"TASK_UNAVAILABLE\" }\n | { readonly _tag: \"TASK_OUTCOME_UNKNOWN\" };\n\n@Injectable({ scope: \"request\" })\nexport class ReviewTasks {\n constructor(@Inject(DB_CLIENT) private readonly store: Partial<ReviewTaskPort>,\n @Inject(REQUEST_CONTEXT) private readonly context: unknown) {}\n\n status(id: string): Promise<ReviewTaskStatus> {\n if (!this.store.attachmentTask) throw new ApplicationError(\"Attachment tasks are not configured\", { status: 501, code: \"TASK_UNAVAILABLE\" });\n return this.store.attachmentTask(this.context, id);\n }\n retry(input: ReviewRetryInput): Promise<ReviewRetryResult> {\n if (!this.store.retryAttachmentTask) throw new ApplicationError(\"Attachment tasks are not configured\", { status: 501, code: \"TASK_UNAVAILABLE\" });\n return this.store.retryAttachmentTask(this.context, input);\n }\n}\n\n@Controller(\"/reviews\")\nexport class ReviewTasksController {\n constructor(@Inject(ReviewTasks) private readonly tasks: ReviewTasks) {}\n\n @Get(\"/:id/attachment-task\", {\n params: TaskParams, responses: { 200: TaskStatus },\n effect: { required: true, dependencies: [], retry: \"none\", errors: [\n { tag: \"AUTHENTICATION_REQUIRED\", status: 401, code: \"AUTHENTICATION_REQUIRED\" },\n { tag: \"TASK_INPUT_INVALID\", status: 400, code: \"TASK_INPUT_INVALID\" },\n { tag: \"TASK_DENIED\", status: 403, code: \"TASK_DENIED\" },\n { tag: \"TASK_CONFLICT\", status: 409, code: \"TASK_CONFLICT\" },\n { tag: \"TASK_UNAVAILABLE\", status: 501, code: \"TASK_UNAVAILABLE\" },\n { tag: \"TASK_OUTCOME_UNKNOWN\", status: 503, code: \"TASK_OUTCOME_UNKNOWN\" },\n ] },\n })\n status(@Param(\"id\") id: string): Effect.Effect<ReviewTaskStatus, TaskError, never> {\n return Effect.promise(() => this.tasks.status(id));\n }\n\n @Post(\"/:id/attachment-task/retry\", {\n params: TaskParams, body: RetryBody, responses: { 200: RetryResult },\n effect: { required: true, dependencies: [], retry: \"none\", errors: [\n { tag: \"AUTHENTICATION_REQUIRED\", status: 401, code: \"AUTHENTICATION_REQUIRED\" },\n { tag: \"TASK_INPUT_INVALID\", status: 400, code: \"TASK_INPUT_INVALID\" },\n { tag: \"TASK_DENIED\", status: 403, code: \"TASK_DENIED\" },\n { tag: \"TASK_CONFLICT\", status: 409, code: \"TASK_CONFLICT\" },\n { tag: \"TASK_UNAVAILABLE\", status: 501, code: \"TASK_UNAVAILABLE\" },\n { tag: \"TASK_OUTCOME_UNKNOWN\", status: 503, code: \"TASK_OUTCOME_UNKNOWN\" },\n ] },\n })\n retry(@Param(\"id\") id: string, @Body() body: ReviewRetryBody): Effect.Effect<ReviewRetryResult, TaskError, never> {\n return Effect.promise(() => this.tasks.retry({ ...body, reviewId: id }));\n }\n}\n";
|
|
3
|
-
export declare const STARTER_TASK_SCHEMA = "-- Forward-only operator provisioning after 004 and the platform Workflow runtime.\nCREATE TABLE public.starter_attachment_retries (\n run_id uuid PRIMARY KEY,\n review_id text NOT NULL REFERENCES public.starter_attachments(review_id),\n previous_run_id uuid NOT NULL UNIQUE,\n generation integer NOT NULL CHECK (generation > 0),\n UNIQUE(review_id,generation),\n CHECK (run_id <> previous_run_id)\n);\nALTER TABLE public.starter_attachment_retries ENABLE ROW LEVEL SECURITY;\nREVOKE ALL ON public.starter_attachment_retries FROM PUBLIC, anon, authenticated;\nGRANT SELECT,INSERT ON public.starter_attachment_retries TO starter_review_http;\nGRANT SELECT ON public.starter_attachment_retries TO starter_review_worker;\nDROP POLICY IF EXISTS starter_http_retry_read ON public.starter_attachment_retries;\nCREATE POLICY starter_http_retry_read ON public.starter_attachment_retries\n FOR SELECT TO starter_review_http USING (true);\nDROP POLICY IF EXISTS starter_http_retry_insert ON public.starter_attachment_retries;\nCREATE POLICY starter_http_retry_insert ON public.starter_attachment_retries\n FOR INSERT TO starter_review_http WITH CHECK (true);\nDROP POLICY IF EXISTS starter_worker_retry_read ON public.starter_attachment_retries;\nCREATE POLICY starter_worker_retry_read ON public.starter_attachment_retries\n FOR SELECT TO starter_review_worker USING (true);\n-- Trusted HTTP adapters authorize the review before inspecting its bound run.\nGRANT EXECUTE ON FUNCTION supacloud_workflows.snapshot(uuid,boolean) TO starter_review_http;\n";
|
|
3
|
+
export declare const STARTER_TASK_SCHEMA = "-- Forward-only operator provisioning after 004 and the platform Workflow runtime.\nCREATE TABLE public.starter_attachment_retries (\n run_id uuid PRIMARY KEY,\n review_id text NOT NULL REFERENCES public.starter_attachments(review_id),\n previous_run_id uuid NOT NULL UNIQUE,\n generation integer NOT NULL CHECK (generation > 0),\n UNIQUE(review_id,generation),\n CHECK (run_id <> previous_run_id)\n);\nALTER TABLE public.starter_attachment_retries ENABLE ROW LEVEL SECURITY;\nREVOKE ALL ON public.starter_attachment_retries FROM PUBLIC, anon, authenticated;\nGRANT SELECT,INSERT ON public.starter_attachment_retries TO starter_review_http;\nGRANT SELECT ON public.starter_attachment_retries TO starter_review_worker;\nDROP POLICY IF EXISTS starter_http_retry_read ON public.starter_attachment_retries;\nCREATE POLICY starter_http_retry_read ON public.starter_attachment_retries\n FOR SELECT TO starter_review_http USING (true);\nDROP POLICY IF EXISTS starter_http_retry_insert ON public.starter_attachment_retries;\nCREATE POLICY starter_http_retry_insert ON public.starter_attachment_retries\n FOR INSERT TO starter_review_http WITH CHECK (true);\nDROP POLICY IF EXISTS starter_worker_retry_read ON public.starter_attachment_retries;\nCREATE POLICY starter_worker_retry_read ON public.starter_attachment_retries\n FOR SELECT TO starter_review_worker USING (true);\nDROP POLICY IF EXISTS \"starter_attachment_retries_select\" ON \"public\".\"starter_attachment_retries\";\nCREATE POLICY \"starter_attachment_retries_select\" ON \"public\".\"starter_attachment_retries\" FOR SELECT TO \"authenticated\" USING (((auth.jwt() IS NOT NULL) AND EXISTS (SELECT 1 FROM \"public\".\"starter_attachments\" AS \"_rel_0\" WHERE (\"_rel_0\".\"review_id\" = \"public\".\"starter_attachment_retries\".\"review_id\") AND (\"_rel_0\".\"owner_id\" = (auth.jwt() ->> 'id')))));\n-- Trusted HTTP adapters authorize the review before inspecting its bound run.\nGRANT EXECUTE ON FUNCTION supacloud_workflows.snapshot(uuid,boolean) TO starter_review_http;\n";
|
|
4
4
|
export declare const STARTER_TASK_HOST = "import { t } from \"elysia\";\nimport { createTransactionalCommand, plaintextCommandInput } from \"@supacloud/commands\";\nimport { CommandError } from \"@supacloud/contracts\";\nimport { createPostgresCommandStore, type CommandDatabase, type CommandTransaction } from \"@supacloud/db\";\nimport { ApplicationError, createSchemaDecoder, requireTrustedIdentity } from \"@supacloud/elysia\";\nimport { AttachmentInput, AttachmentResult } from \"../review/attachment\";\nimport { ReviewResult } from \"../review/contracts\";\nimport { RetryInput, RetryResult, TaskParams, TaskStatus, type ReviewRetryInput } from \"../review/task-contracts\";\nimport type { ReviewTaskPort } from \"../review/tasks\";\nimport type { ReviewRow } from \"../../db/schema\";\n\nexport interface ReviewTaskOptions { database: CommandDatabase; projectId: string; tenantId: string }\ntype Binding = { artifactId: string; runId: string; generation: number };\nconst decodeInput = createSchemaDecoder(RetryInput, { normalize: false });\nconst decodeRetry = createSchemaDecoder(RetryResult, { normalize: false });\nconst decodeStatus = createSchemaDecoder(TaskStatus, { normalize: false });\nconst decodeParams = createSchemaDecoder(TaskParams, { normalize: false });\nconst decodeReview: (value: unknown) => Pick<ReviewRow, \"state\" | \"version\"> =\n createSchemaDecoder(ReviewResult, { normalize: false });\nconst decodeResult = createSchemaDecoder(AttachmentResult, { normalize: false });\nconst decodeBinding: (value: unknown) => Binding = createSchemaDecoder(t.Object({\n artifactId: t.String({ format: \"uuid\" }), runId: t.String({ format: \"uuid\" }),\n generation: t.Integer({ minimum: 0 }),\n}), { normalize: false });\nconst decodeRun = createSchemaDecoder(t.Object({\n runId: t.String({ format: \"uuid\" }), workflowName: t.Literal(\"review.verify-attachment\"),\n workflowVersion: t.Literal(\"1\"),\n status: t.Union([t.Literal(\"queued\"), t.Literal(\"running\"), t.Literal(\"completed\"), t.Literal(\"failed\"), t.Literal(\"cancelled\")]),\n input: AttachmentInput, output: t.Unknown(), idempotent: t.Boolean(),\n steps: t.Array(t.Object({\n stepKey: t.Literal(\"verify\"), attempts: t.Integer({ minimum: 0 }),\n maxAttempts: t.Literal(3),\n status: t.Union([t.Literal(\"queued\"), t.Literal(\"running\"), t.Literal(\"completed\"), t.Literal(\"failed\"), t.Literal(\"dead_lettered\"), t.Literal(\"cancelled\")]),\n }, { additionalProperties: true }), { minItems: 1, maxItems: 1 }),\n}, { additionalProperties: true }), { normalize: false });\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction record(value: unknown): Record<string, unknown> {\n if (!isRecord(value)) throw new Error(\"Invalid task record\");\n return value;\n}\nfunction rows(value: unknown): Record<string, unknown>[] {\n if (!Array.isArray(value)) throw new Error(\"Invalid task rows\");\n return value.map(record);\n}\nfunction capture(value: unknown): ReviewRetryInput {\n try {\n const input = decodeInput(value);\n return { ...input, recoveryId: input.recoveryId.toLowerCase(), expectedRunId: input.expectedRunId.toLowerCase() };\n } catch { throw new ApplicationError(\"Invalid task request\", { status: 400, code: \"TASK_INPUT_INVALID\" }); }\n}\nfunction failure(error: unknown): never {\n if (error instanceof ApplicationError) throw error;\n if (error instanceof CommandError && error.code === \"COMMAND_REJECTED\") {\n throw new ApplicationError(\"Task access denied\", { status: 403, code: \"TASK_DENIED\" });\n }\n if (error instanceof CommandError && error.code === \"COMMAND_IDEMPOTENCY_CONFLICT\") {\n throw new ApplicationError(\"Task changed or is not retryable\", { status: 409, code: \"TASK_CONFLICT\" });\n }\n throw new ApplicationError(\"Task outcome could not be confirmed\", { status: 503, code: \"TASK_OUTCOME_UNKNOWN\" });\n}\nconst conflict = () => { throw new CommandError(\"COMMAND_IDEMPOTENCY_CONFLICT\"); };\n\nexport async function createReviewTaskAdapters(options: ReviewTaskOptions): Promise<ReviewTaskPort> {\n const { database, projectId, tenantId } = options;\n const configured = rows(await database.transaction(tx => tx.query(\n \"SELECT project_id,tenant_id FROM public.starter_application WHERE singleton\",\n )));\n if (!projectId.trim() || !tenantId.trim() || configured.length !== 1\n || configured[0]?.[\"project_id\"] !== projectId || configured[0]?.[\"tenant_id\"] !== tenantId) {\n throw new Error(\"Task database project/tenant binding mismatch\");\n }\n function actor(context: unknown): string {\n const who = requireTrustedIdentity(context);\n const access = record(record(context)[\"access\"]);\n if (access[\"projectId\"] !== projectId || access[\"tenantId\"] !== tenantId\n || !Array.isArray(access[\"permissions\"]) || !access[\"permissions\"].includes(\"review.approve\")) {\n throw new ApplicationError(\"Task access denied\", { status: 403, code: \"TASK_DENIED\" });\n }\n return who.subject;\n }\n async function authorize(tx: CommandTransaction, subject: string, reviewId: string) {\n const found = rows(await tx.query(\n \"SELECT r.state,r.version FROM public.starter_reviews r \" +\n \"JOIN public.starter_members m ON m.subject=r.owner_id CROSS JOIN public.starter_application p \" +\n \"WHERE r.id=$1 AND r.owner_id=$2 AND m.enabled AND m.can_approve \" +\n \"AND p.singleton AND p.project_id=$3 AND p.tenant_id=$4 FOR UPDATE OF r,m FOR SHARE OF p\",\n [reviewId, subject, projectId, tenantId],\n ));\n if (found.length !== 1) throw new ApplicationError(\"Task access denied\", { status: 403, code: \"TASK_DENIED\" });\n return decodeReview(found[0]);\n }\n async function binding(tx: CommandTransaction, reviewId: string) {\n const found = rows(await tx.query(\n 'SELECT a.artifact_id AS \"artifactId\",COALESCE(retry.run_id,a.run_id) AS \"runId\",COALESCE(retry.generation,0) AS generation ' +\n \"FROM public.starter_attachments a LEFT JOIN LATERAL (\" +\n \"SELECT run_id,generation FROM public.starter_attachment_retries WHERE review_id=a.review_id ORDER BY generation DESC LIMIT 1\" +\n \") retry ON true WHERE a.review_id=$1\", [reviewId],\n ));\n return found.length === 0 ? null : decodeBinding(found[0]);\n }\n async function snapshot(tx: CommandTransaction, runId: string) {\n return rows(await tx.query(\"SELECT supacloud_workflows.snapshot($1::uuid,false) AS run\", [runId]))[0]?.[\"run\"];\n }\n function boundRun(value: unknown, reviewId: string, version: number, bound: NonNullable<Awaited<ReturnType<typeof binding>>>) {\n const run = decodeRun(value);\n if (run.runId !== bound.runId || run.input.reviewId !== reviewId\n || run.input.version !== version || run.input.artifactId !== bound.artifactId) {\n throw new Error(\"Task Workflow binding mismatch\");\n }\n const step = run.steps[0];\n if (!step || (run.status === \"queued\" && step.status !== \"queued\")\n || (run.status === \"running\" && step.status !== \"queued\" && step.status !== \"running\")\n || (run.status === \"completed\" && step.status !== \"completed\")\n || (run.status === \"failed\" && step.status !== \"failed\" && step.status !== \"dead_lettered\")\n || (run.status === \"cancelled\" && step.status !== \"cancelled\")) {\n throw new Error(\"Task Workflow state mismatch\");\n }\n return run;\n }\n const retry = createTransactionalCommand({\n name: \"review.retry-attachment\", store: createPostgresCommandStore(database),\n inputCodec: plaintextCommandInput, input: capture, result: decodeRetry,\n async authorize(who, input, tx) {\n try {\n const review = await authorize(tx, who.actorId, input.reviewId);\n return review.state === \"approved\" && review.version === input.expectedVersion ? \"allow\" : \"deny\";\n } catch (error) {\n if (error instanceof ApplicationError && error.code === \"TASK_DENIED\") return \"deny\";\n throw error;\n }\n },\n async execute(tx, input) {\n const bound = await binding(tx, input.reviewId);\n if (!bound || bound.runId !== input.expectedRunId || input.recoveryId === bound.runId) return conflict();\n const previous = boundRun(await snapshot(tx, bound.runId), input.reviewId, input.expectedVersion, bound);\n if (previous.status !== \"failed\") return conflict();\n if (await snapshot(tx, input.recoveryId) !== null) return conflict();\n const started = rows(await tx.query(\n \"SELECT supacloud_workflows.start_run($1::uuid,'review.verify-attachment','1','verify',$2::text::jsonb,3) AS run\",\n [input.recoveryId, JSON.stringify(previous.input)],\n ))[0]?.[\"run\"];\n const next = boundRun(started, input.reviewId, input.expectedVersion, { ...bound, runId: input.recoveryId });\n if (next.idempotent || next.status !== \"queued\") return conflict();\n await tx.query(\"INSERT INTO public.starter_attachment_retries(run_id,review_id,previous_run_id,generation) VALUES($1,$2,$3,$4)\",\n [input.recoveryId, input.reviewId, bound.runId, bound.generation + 1]);\n return { reviewId: input.reviewId, previousRunId: bound.runId, runId: input.recoveryId, state: \"queued\" as const };\n },\n audit: { event: \"review.attachment-retried\", details: input => ({\n reviewId: input.reviewId, previousRunId: input.expectedRunId, runId: input.recoveryId,\n }) },\n });\n return {\n async attachmentTask(context, reviewId) {\n try {\n const subject = actor(context);\n try { decodeParams({ id: reviewId }); }\n catch { throw new ApplicationError(\"Invalid task request\", { status: 400, code: \"TASK_INPUT_INVALID\" }); }\n return await database.transaction(async tx => {\n const review = await authorize(tx, subject, reviewId);\n const bound = await binding(tx, reviewId);\n const empty = { reviewId, version: review.version, artifactId: bound?.artifactId ?? null,\n runId: null, state: \"not_submitted\", attempts: 0, maxAttempts: 3, canRetry: false, result: null } as const;\n if (!bound) return decodeStatus(empty);\n const value = await snapshot(tx, bound.runId);\n if (value === null && review.state === \"draft\" && bound.generation === 0) return decodeStatus(empty);\n const run = boundRun(value, reviewId, review.version, bound);\n const step = run.steps[0];\n if (!step) throw new Error(\"Missing task step\");\n const result = run.status === \"completed\" ? decodeResult(run.output) : null;\n if (result && (result.reviewId !== reviewId || result.version !== review.version || result.artifactId !== bound.artifactId)) {\n throw new Error(\"Task result binding mismatch\");\n }\n return decodeStatus({ ...empty, runId: run.runId,\n state: run.status === \"running\" && step.status === \"queued\" ? \"queued\" : run.status,\n attempts: step.attempts, canRetry: run.status === \"failed\", result });\n });\n } catch (error) { return failure(error); }\n },\n async retryAttachmentTask(context, value) {\n try {\n const subject = actor(context), input = capture(value);\n const receipt = await retry.execute({ actorId: subject, tenantId }, input.recoveryId, input);\n if (receipt.status !== \"confirmed\") throw new CommandError(\"COMMAND_OUTCOME_UNKNOWN\");\n return receipt.result;\n } catch (error) { return failure(error); }\n },\n };\n}\n";
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export declare const STARTER_UPLOAD_FEATURE = "import { Effect } from \"effect\";\nimport { Body, Controller, Inject, Injectable, Param, Post, DB_CLIENT, REQUEST_CONTEXT } from \"@supacloud/app\";\nimport { ApplicationError } from \"@supacloud/elysia\";\nimport { UploadBody, UploadLocation, UploadParams, UploadResult,\n type ReviewUploadBody, type ReviewUploadInput, type ReviewUploadLocation, type ReviewUploadResult } from \"./contracts\";\nexport type { ReviewUploadInput, ReviewUploadLocation, ReviewUploadResult } from \"./contracts\";\ntype PreviewUploadError =\n | { readonly _tag: \"AUTHENTICATION_REQUIRED\" }\n | { readonly _tag: \"UPLOAD_INPUT_INVALID\" }\n | { readonly _tag: \"UPLOAD_DENIED\" }\n | { readonly _tag: \"UPLOADS_UNAVAILABLE\" };\ntype RegisterUploadError =\n | PreviewUploadError\n | { readonly _tag: \"UPLOAD_CONTENT_INVALID\" }\n | { readonly _tag: \"COMMAND_IDEMPOTENCY_CONFLICT\" }\n | { readonly _tag: \"COMMAND_REJECTED\" }\n | { readonly _tag: \"UPLOAD_OUTCOME_UNKNOWN\" };\nexport interface ReviewUploadPort {\n previewUpload(context: unknown, input: ReviewUploadInput): Promise<ReviewUploadLocation>;\n registerUpload(context: unknown, input: ReviewUploadInput): Promise<ReviewUploadResult>;\n lookupUpload?(context: unknown, input: ReviewUploadInput): Promise<boolean>;\n}\n@Injectable({ scope: \"request\" })\nexport class ReviewUploads {\n constructor(@Inject(DB_CLIENT) private readonly store: Partial<ReviewUploadPort>,\n @Inject(REQUEST_CONTEXT) private readonly context: unknown) {}\n\n preview(input: ReviewUploadInput): Promise<ReviewUploadLocation> {\n if (!this.store.previewUpload) throw new ApplicationError(\"Attachment uploads are not configured\", { status: 501, code: \"UPLOADS_UNAVAILABLE\" });\n return this.store.previewUpload(this.context, input);\n }\n register(input: ReviewUploadInput): Promise<ReviewUploadResult> {\n if (!this.store.registerUpload) throw new ApplicationError(\"Attachment uploads are not configured\", { status: 501, code: \"UPLOADS_UNAVAILABLE\" });\n return this.store.registerUpload(this.context, input);\n }\n}\n\n@Controller(\"/reviews\")\nexport class ReviewUploadsController {\n constructor(@Inject(ReviewUploads) private readonly uploads: ReviewUploads) {}\n\n @Post(\"/:id/attachment-upload\", {\n params: UploadParams,\n body: UploadBody,\n responses: { 200: UploadLocation },\n effect: {\n required: true,\n dependencies: [],\n errors: [\n { tag: \"AUTHENTICATION_REQUIRED\", status: 401, code: \"AUTHENTICATION_REQUIRED\" },\n { tag: \"UPLOAD_INPUT_INVALID\", status: 400, code: \"UPLOAD_INPUT_INVALID\" },\n { tag: \"UPLOAD_DENIED\", status: 403, code: \"UPLOAD_DENIED\" },\n { tag: \"UPLOADS_UNAVAILABLE\", status: 501, code: \"UPLOADS_UNAVAILABLE\" },\n ],\n retry: \"none\",\n },\n })\n preview(@Param(\"id\") id: string, @Body() body: ReviewUploadBody): Effect.Effect<ReviewUploadLocation, PreviewUploadError, never> {\n return Effect.promise(() => this.uploads.preview({ reviewId: id, artifactId: body.artifactId, expectedVersion: body.expectedVersion }));\n }\n @Post(\"/:id/attachment-registration\", {\n params: UploadParams,\n body: UploadBody,\n responses: { 200: UploadResult },\n effect: {\n required: true,\n dependencies: [],\n errors: [\n { tag: \"AUTHENTICATION_REQUIRED\", status: 401, code: \"AUTHENTICATION_REQUIRED\" },\n { tag: \"UPLOAD_INPUT_INVALID\", status: 400, code: \"UPLOAD_INPUT_INVALID\" },\n { tag: \"UPLOAD_DENIED\", status: 403, code: \"UPLOAD_DENIED\" },\n { tag: \"UPLOAD_CONTENT_INVALID\", status: 400, code: \"UPLOAD_CONTENT_INVALID\" },\n { tag: \"COMMAND_IDEMPOTENCY_CONFLICT\", status: 409, code: \"COMMAND_IDEMPOTENCY_CONFLICT\" },\n { tag: \"COMMAND_REJECTED\", status: 403, code: \"COMMAND_REJECTED\" },\n { tag: \"UPLOADS_UNAVAILABLE\", status: 501, code: \"UPLOADS_UNAVAILABLE\" },\n { tag: \"UPLOAD_OUTCOME_UNKNOWN\", status: 503, code: \"UPLOAD_OUTCOME_UNKNOWN\" },\n ],\n retry: \"none\",\n },\n })\n register(@Param(\"id\") id: string, @Body() body: ReviewUploadBody): Effect.Effect<ReviewUploadResult, RegisterUploadError, never> {\n return Effect.promise(() => this.uploads.register({ reviewId: id, artifactId: body.artifactId, expectedVersion: body.expectedVersion }));\n }\n}\n";
|
|
2
|
-
export declare const STARTER_UPLOAD_SCHEMA = "-- Apply explicitly with the migration owner.\nALTER TABLE public.starter_members ADD COLUMN storage_subject uuid UNIQUE;\nGRANT SELECT (subject,enabled,can_approve,storage_subject) ON public.starter_members TO authenticated;\nDROP POLICY IF EXISTS starter_member_read ON public.starter_members;\nCREATE POLICY starter_member_read ON public.starter_members FOR SELECT TO authenticated\n USING (subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND storage_subject=auth.uid());\nGRANT SELECT ON public.starter_reviews TO authenticated;\nDROP POLICY IF EXISTS starter_review_read ON public.starter_reviews;\nCREATE POLICY starter_review_read ON public.starter_reviews FOR SELECT TO authenticated\n USING (owner_id=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND EXISTS (\n SELECT 1 FROM public.starter_members m WHERE m.subject=owner_id\n AND m.enabled AND m.can_approve AND m.storage_subject=auth.uid()\n ));\nINSERT INTO storage.buckets(id,name,public,file_size_limit,allowed_mime_types)\n VALUES ('review-attachments','review-attachments',false,1048576,ARRAY['text/plain']);\nDROP POLICY IF EXISTS starter_attachment_read ON storage.objects;\nCREATE POLICY starter_attachment_read ON storage.objects FOR SELECT TO authenticated\n USING (bucket_id='review-attachments');\nDROP POLICY IF EXISTS starter_attachment_insert ON storage.objects;\nCREATE POLICY starter_attachment_insert ON storage.objects FOR INSERT TO authenticated\n WITH CHECK (bucket_id='review-attachments');\n-- Restrictive fences also apply when the host already has permissive Storage policies.\nDROP POLICY IF EXISTS starter_attachment_owner_fence ON storage.objects;\nCREATE POLICY starter_attachment_owner_fence ON storage.objects AS RESTRICTIVE FOR ALL TO authenticated\n USING (bucket_id<>'review-attachments' OR (split_part(name,'/',1)=auth.uid()::text AND EXISTS (\n SELECT 1 FROM public.starter_reviews r JOIN public.starter_members m ON m.subject=r.owner_id\n WHERE r.id=split_part(name,'/',2) AND m.subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub')\n AND m.storage_subject=auth.uid() AND m.enabled AND m.can_approve\n )))\n WITH CHECK (bucket_id<>'review-attachments' OR (split_part(name,'/',1)=auth.uid()::text\n AND name ~ '^[a-f0-9-]{36}/[a-f0-9-]{36}/[a-f0-9-]{36}[.]txt$' AND EXISTS (\n SELECT 1 FROM public.starter_reviews r JOIN public.starter_members m ON m.subject=r.owner_id\n WHERE r.id=split_part(name,'/',2) AND r.state='draft' AND m.subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub')\n AND m.storage_subject=auth.uid() AND m.enabled AND m.can_approve\n )));\nDROP POLICY IF EXISTS starter_attachment_update_fence ON storage.objects;\nCREATE POLICY starter_attachment_update_fence ON storage.objects AS RESTRICTIVE FOR UPDATE TO authenticated\n USING (bucket_id<>'review-attachments') WITH CHECK (bucket_id<>'review-attachments');\nDROP POLICY IF EXISTS starter_attachment_delete_fence ON storage.objects;\nCREATE POLICY starter_attachment_delete_fence ON storage.objects AS RESTRICTIVE FOR DELETE TO authenticated\n USING (bucket_id<>'review-attachments');\n";
|
|
2
|
+
export declare const STARTER_UPLOAD_SCHEMA = "-- Apply explicitly with the migration owner.\nALTER TABLE public.starter_members ADD COLUMN storage_subject uuid UNIQUE;\nGRANT SELECT (subject,enabled,can_approve,storage_subject) ON public.starter_members TO authenticated;\nDROP POLICY IF EXISTS starter_member_read ON public.starter_members;\nCREATE POLICY starter_member_read ON public.starter_members FOR SELECT TO authenticated\n USING (subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND storage_subject=auth.uid());\nDROP POLICY IF EXISTS starter_member_storage_fence ON public.starter_members;\nCREATE POLICY starter_member_storage_fence ON public.starter_members AS RESTRICTIVE FOR SELECT TO authenticated\n USING (subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND storage_subject=auth.uid());\nGRANT SELECT ON public.starter_reviews TO authenticated;\nDROP POLICY IF EXISTS starter_review_read ON public.starter_reviews;\nCREATE POLICY starter_review_read ON public.starter_reviews FOR SELECT TO authenticated\n USING (owner_id=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND EXISTS (\n SELECT 1 FROM public.starter_members m WHERE m.subject=owner_id\n AND m.enabled AND m.can_approve AND m.storage_subject=auth.uid()\n ));\nDROP POLICY IF EXISTS starter_review_storage_fence ON public.starter_reviews;\nCREATE POLICY starter_review_storage_fence ON public.starter_reviews AS RESTRICTIVE FOR SELECT TO authenticated\n USING (owner_id=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND EXISTS (\n SELECT 1 FROM public.starter_members m WHERE m.subject=owner_id\n AND m.enabled AND m.can_approve AND m.storage_subject=auth.uid()\n ));\nINSERT INTO storage.buckets(id,name,public,file_size_limit,allowed_mime_types)\n VALUES ('review-attachments','review-attachments',false,1048576,ARRAY['text/plain']);\nDROP POLICY IF EXISTS starter_attachment_read ON storage.objects;\nCREATE POLICY starter_attachment_read ON storage.objects FOR SELECT TO authenticated\n USING (bucket_id='review-attachments');\nDROP POLICY IF EXISTS starter_attachment_insert ON storage.objects;\nCREATE POLICY starter_attachment_insert ON storage.objects FOR INSERT TO authenticated\n WITH CHECK (bucket_id='review-attachments');\n-- Restrictive fences also apply when the host already has permissive Storage policies.\nDROP POLICY IF EXISTS starter_attachment_owner_fence ON storage.objects;\nCREATE POLICY starter_attachment_owner_fence ON storage.objects AS RESTRICTIVE FOR ALL TO authenticated\n USING (bucket_id<>'review-attachments' OR (split_part(name,'/',1)=auth.uid()::text AND EXISTS (\n SELECT 1 FROM public.starter_reviews r JOIN public.starter_members m ON m.subject=r.owner_id\n WHERE r.id=split_part(name,'/',2) AND m.subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub')\n AND m.storage_subject=auth.uid() AND m.enabled AND m.can_approve\n )))\n WITH CHECK (bucket_id<>'review-attachments' OR (split_part(name,'/',1)=auth.uid()::text\n AND name ~ '^[a-f0-9-]{36}/[a-f0-9-]{36}/[a-f0-9-]{36}[.]txt$' AND EXISTS (\n SELECT 1 FROM public.starter_reviews r JOIN public.starter_members m ON m.subject=r.owner_id\n WHERE r.id=split_part(name,'/',2) AND r.state='draft' AND m.subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub')\n AND m.storage_subject=auth.uid() AND m.enabled AND m.can_approve\n )));\nDROP POLICY IF EXISTS starter_attachment_update_fence ON storage.objects;\nCREATE POLICY starter_attachment_update_fence ON storage.objects AS RESTRICTIVE FOR UPDATE TO authenticated\n USING (bucket_id<>'review-attachments') WITH CHECK (bucket_id<>'review-attachments');\nDROP POLICY IF EXISTS starter_attachment_delete_fence ON storage.objects;\nCREATE POLICY starter_attachment_delete_fence ON storage.objects AS RESTRICTIVE FOR DELETE TO authenticated\n USING (bucket_id<>'review-attachments');\n";
|
|
3
3
|
export declare const STARTER_UPLOAD_ADAPTER = "import { MIMEType } from \"node:util\";\nimport { SupaCloudArtifactsClient } from \"@supacloud/js\";\nimport { createTransactionalCommand, plaintextCommandInput } from \"@supacloud/commands\";\nimport { CommandError } from \"@supacloud/contracts\";\nimport { createPostgresCommandStore, type CommandTransaction } from \"@supacloud/db\";\nimport { ApplicationError, createSchemaDecoder, requireTrustedIdentity } from \"@supacloud/elysia\";\nimport { UploadInput, UploadResult } from \"../review/contracts\";\nimport type { ReviewAttachmentOptions } from \"./review-attachments\";\nimport type { ReviewUploadInput, ReviewUploadPort, ReviewUploadResult } from \"../review/uploads\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction record(value: unknown): Record<string, unknown> {\n if (!isRecord(value)) throw new TypeError(\"Invalid upload record\");\n return value;\n}\nfunction rows(value: unknown): Record<string, unknown>[] {\n if (!Array.isArray(value)) throw new TypeError(\"Invalid upload database result\");\n return value.map(record);\n}\nconst decodeInput = createSchemaDecoder(UploadInput, { normalize: false });\nconst result = createSchemaDecoder(UploadResult, { normalize: false });\nfunction capture(value: unknown): ReviewUploadInput {\n try {\n const input = decodeInput(value);\n return { ...input, reviewId: input.reviewId.toLowerCase(), artifactId: input.artifactId.toLowerCase() };\n } catch {\n throw new ApplicationError(\"Invalid upload input\", { status: 400, code: \"UPLOAD_INPUT_INVALID\" });\n }\n}\n\nexport async function createReviewUploadAdapters(options: ReviewAttachmentOptions): Promise<ReviewUploadPort> {\n const { database, service, projectId, tenantId } = options;\n const binding = rows(await database.transaction(tx => tx.query(\n \"SELECT project_id,tenant_id FROM public.starter_application WHERE singleton\",\n )));\n if (!projectId.trim() || !tenantId.trim() || binding.length !== 1\n || binding[0]?.[\"project_id\"] !== projectId || binding[0]?.[\"tenant_id\"] !== tenantId) {\n throw new Error(\"Upload database project/tenant binding mismatch\");\n }\n const artifacts = new SupaCloudArtifactsClient(service);\n function actor(context: unknown): string {\n const who = requireTrustedIdentity(context);\n const access = record(record(context)[\"access\"]);\n if (access[\"projectId\"] !== projectId || access[\"tenantId\"] !== tenantId\n || !Array.isArray(access[\"permissions\"]) || !access[\"permissions\"].includes(\"review.approve\")) {\n throw new ApplicationError(\"Upload permission denied\", { status: 403, code: \"UPLOAD_DENIED\" });\n }\n return who.subject;\n }\n async function authorize(tx: CommandTransaction, subject: string, input: ReviewUploadInput, replay = false) {\n const allowed = rows(await tx.query(\n \"SELECT m.storage_subject::text AS storage_subject FROM public.starter_reviews r \" +\n \"JOIN public.starter_members m ON m.subject=r.owner_id CROSS JOIN public.starter_application p \" +\n \"WHERE r.id=$1 AND r.owner_id=$2 AND ((r.state='draft' AND r.version=$3) OR \" +\n \"($6::boolean AND r.state='approved' AND r.version=$3::bigint+1 AND EXISTS (\" +\n \"SELECT 1 FROM public.starter_attachments b WHERE b.review_id=r.id AND b.artifact_id=$7::uuid AND b.owner_id=$2 \" +\n \"AND b.object_path=m.storage_subject::text || '/' || r.id || '/' || $7::text || '.txt'))) \" +\n \"AND m.enabled AND m.can_approve AND m.storage_subject IS NOT NULL \" +\n \"AND p.singleton AND p.project_id=$4 AND p.tenant_id=$5 FOR UPDATE OF r,m FOR SHARE OF p\",\n [input.reviewId, subject, input.expectedVersion, projectId, tenantId, replay, input.artifactId],\n ));\n if (allowed.length !== 1 || typeof allowed[0]?.[\"storage_subject\"] !== \"string\") {\n throw new ApplicationError(\"Upload ownership, permission or revision changed\", { status: 403, code: \"UPLOAD_DENIED\" });\n }\n return allowed[0][\"storage_subject\"] + \"/\" + input.reviewId + \"/\" + input.artifactId + \".txt\";\n }\n const receiptLookup = createTransactionalCommand({\n name: \"review.attach\", store: createPostgresCommandStore(database), inputCodec: plaintextCommandInput,\n input: capture, result,\n async authorize(who, request, tx) {\n try { await authorize(tx, who.actorId, request, true); return \"allow\"; }\n catch (error) {\n if (error instanceof ApplicationError && error.code === \"UPLOAD_DENIED\") return \"deny\";\n throw error;\n }\n },\n execute: async () => { throw new Error(\"Receipt lookup cannot register an upload\"); },\n audit: { event: \"review.attachment-bound\", details: request => ({ reviewId: request.reviewId, artifactId: request.artifactId }) },\n });\n return {\n async lookupUpload(context, value) {\n const input = capture(value), subject = actor(context);\n return (await receiptLookup.lookup({ actorId: subject, tenantId }, input.artifactId, input))?.status === \"confirmed\";\n },\n async previewUpload(context, value) {\n const input = capture(value), subject = actor(context);\n const objectPath = await database.transaction(tx => authorize(tx, subject, input));\n return { artifactId: input.artifactId, bucketId: \"review-attachments\", objectPath };\n },\n async registerUpload(context, value) {\n const input = capture(value), subject = actor(context);\n try {\n // Only an authorized, validated receipt can bypass external registration.\n const saved = await receiptLookup.lookup({ actorId: subject, tenantId }, input.artifactId, input);\n if (saved !== null) {\n if (saved.status !== \"confirmed\") throw new CommandError(\"COMMAND_RECEIPT_INVALID\");\n return saved.result;\n }\n const objectPath = await database.transaction(tx => authorize(tx, subject, input, true));\n const downloaded = await service.storage.from(\"review-attachments\").download(objectPath);\n if (downloaded.error || !downloaded.data) throw new Error(\"Upload unavailable\");\n const blob = downloaded.data;\n if (blob.size < 1 || blob.size > 1048576 || new MIMEType(blob.type).essence !== \"text/plain\") {\n throw new ApplicationError(\"Unsupported upload\", { status: 400, code: \"UPLOAD_CONTENT_INVALID\" });\n }\n const sha256 = Array.from(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", await blob.arrayBuffer())),\n byte => byte.toString(16).padStart(2, \"0\")).join(\"\");\n await artifacts.register({ artifactId: input.artifactId, bucketId: \"review-attachments\", objectPath,\n artifactType: \"review.attachment\", sha256, sizeBytes: blob.size, mimeType: \"text/plain\" });\n const command = createTransactionalCommand({\n name: \"review.attach\", store: createPostgresCommandStore(database), inputCodec: plaintextCommandInput,\n input: capture, result,\n async authorize(who, request, tx) {\n try {\n const currentPath = await authorize(tx, who.actorId, request, true);\n return currentPath === objectPath ? \"allow\" : \"deny\";\n } catch (error) {\n if (error instanceof ApplicationError && error.code === \"UPLOAD_DENIED\") return \"deny\";\n throw error;\n }\n },\n async execute(tx, request) {\n const existing = rows(await tx.query(\"SELECT artifact_id FROM public.starter_attachments WHERE review_id=$1\", [request.reviewId]));\n if (existing.length) throw new CommandError(\"COMMAND_IDEMPOTENCY_CONFLICT\");\n const bound: ReviewUploadResult = { artifactId: request.artifactId, runId: request.artifactId, objectPath, sha256, bytes: blob.size };\n await tx.query(\"INSERT INTO public.starter_attachments VALUES($1,$2,$3,$4,$5)\",\n [request.reviewId, bound.artifactId, subject, bound.runId, bound.objectPath]);\n return bound;\n },\n audit: { event: \"review.attachment-bound\", details: request => ({ reviewId: request.reviewId, artifactId: request.artifactId }) },\n });\n const receipt = await command.execute({ actorId: subject, tenantId }, input.artifactId, input);\n if (receipt.status !== \"confirmed\") throw new CommandError(\"COMMAND_OUTCOME_UNKNOWN\");\n return receipt.result;\n } catch (error) {\n if (error instanceof ApplicationError) throw error;\n if (error instanceof CommandError && error.code === \"COMMAND_IDEMPOTENCY_CONFLICT\") {\n throw new ApplicationError(\"Conflicting attachment binding\", { status: 409, code: error.code });\n }\n if (error instanceof CommandError && error.code === \"COMMAND_REJECTED\") {\n throw new ApplicationError(\"Upload permission denied\", { status: 403, code: error.code });\n }\n // Registration may have committed even when binding failed; never delete immutable evidence here.\n throw new ApplicationError(\"Upload registration could not be confirmed\", { status: 503, code: \"UPLOAD_OUTCOME_UNKNOWN\" });\n }\n },\n };\n}\n";
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ApplicationDeployRequest } from "@supacloud/delivery";
|
|
2
|
+
import { type MultiLangTarget } from "@supacloud/compiler";
|
|
2
3
|
import { type ToolServer } from "../tool-server";
|
|
3
4
|
import { type AppManifest } from "./app-tool-export";
|
|
4
5
|
declare const REMOTE_APP_ACTIONS: {
|
|
@@ -40,7 +41,25 @@ export interface AppToolOptions {
|
|
|
40
41
|
onDevProgress?: (result: ToolResult) => void;
|
|
41
42
|
}
|
|
42
43
|
export interface AppToolArguments {
|
|
43
|
-
action: "init" | "generate" | "infer" | "dev" | "watch" | "verify-plan" | "verify" | "compile" | "check" | "graph" | "explain" | "export-tools" | "context" | "lens" | "doctor" | "fix" | "plan" | "build" | "release" | "promote" | keyof typeof REMOTE_APP_ACTIONS;
|
|
44
|
+
action: "init" | "generate" | "infer" | "dev" | "watch" | "verify-plan" | "verify" | "compile" | "check" | "graph" | "explain" | "export-tools" | "context" | "lens" | "doctor" | "fix" | "upgrade" | "client-sdk" | "contract-diff" | "sql-prepare" | "plan" | "build" | "release" | "promote" | keyof typeof REMOTE_APP_ACTIONS;
|
|
45
|
+
lang?: MultiLangTarget;
|
|
46
|
+
catalog?: string;
|
|
47
|
+
openapi?: string;
|
|
48
|
+
baseline_openapi?: string;
|
|
49
|
+
current_openapi?: string;
|
|
50
|
+
baseline_asyncapi?: string;
|
|
51
|
+
current_asyncapi?: string;
|
|
52
|
+
baseline_catalog?: string;
|
|
53
|
+
current_catalog?: string;
|
|
54
|
+
baseline_graphql?: string;
|
|
55
|
+
current_graphql?: string;
|
|
56
|
+
baseline_rls?: string;
|
|
57
|
+
current_rls?: string;
|
|
58
|
+
cache_path?: string;
|
|
59
|
+
offline?: boolean;
|
|
60
|
+
schema_hash?: string;
|
|
61
|
+
package_name?: string;
|
|
62
|
+
with_tests?: boolean;
|
|
44
63
|
ref?: string;
|
|
45
64
|
id?: string;
|
|
46
65
|
environment_id?: string;
|
|
@@ -67,7 +86,7 @@ export interface AppToolArguments {
|
|
|
67
86
|
ttl_seconds?: number;
|
|
68
87
|
wait?: boolean;
|
|
69
88
|
timeout_seconds?: number;
|
|
70
|
-
kind?: "module" | "command" | "query" | "controller" | "job" | "contract" | "resource" | "feature";
|
|
89
|
+
kind?: "module" | "command" | "query" | "controller" | "job" | "contract" | "aspect" | "resource" | "feature";
|
|
71
90
|
template?: "minimal" | "client" | "command" | "model-command" | "app";
|
|
72
91
|
name?: string;
|
|
73
92
|
module?: string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supacloud/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.131.0",
|
|
4
4
|
"description": "Project-scoped CLI for SupaCloud users",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -52,23 +52,23 @@
|
|
|
52
52
|
"directory": "packages/cli"
|
|
53
53
|
},
|
|
54
54
|
"dependencies": {
|
|
55
|
-
"@supacloud/compiler": "^0.
|
|
55
|
+
"@supacloud/compiler": "^0.69.0",
|
|
56
56
|
"@supacloud/delivery": "0.30.1",
|
|
57
|
-
"@supacloud/db": "0.
|
|
57
|
+
"@supacloud/db": "0.29.0",
|
|
58
58
|
"typebox": "1.4.3"
|
|
59
59
|
},
|
|
60
60
|
"overrides": {
|
|
61
61
|
"@supacloud/contracts": "0.17.0",
|
|
62
62
|
"@supacloud/delivery": "0.30.1",
|
|
63
63
|
"@graphql-tools/utils": "^12.0.4",
|
|
64
|
-
"@supacloud/compiler": "^0.
|
|
65
|
-
"@supacloud/db": "0.
|
|
64
|
+
"@supacloud/compiler": "^0.69.0",
|
|
65
|
+
"@supacloud/db": "0.29.0",
|
|
66
66
|
"deepmerge-ts": "8.0.2",
|
|
67
67
|
"prisma": "6.19.3"
|
|
68
68
|
},
|
|
69
69
|
"devDependencies": {
|
|
70
70
|
"@supabase/supabase-js": "2.118.0",
|
|
71
|
-
"@supacloud/elysia": "0.
|
|
71
|
+
"@supacloud/elysia": "0.45.0",
|
|
72
72
|
"@types/bun": "^1.4.5",
|
|
73
73
|
"effect": "4.0.5",
|
|
74
74
|
"elysia": "2.0.0-rc.6",
|