better-supabase 0.21.0 → 0.22.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/{adapter-DZJZTY6g.js → adapter-D4aNBxhm.js} +2 -2
- package/dist/api-3C0AWFeP.js +696 -0
- package/dist/{api-Cj4W_pqT.d.ts → api-CHObZL7m.d.ts} +1 -1
- package/dist/{app-tables-C5HjXs2k.d.ts → app-tables-BGzdnQm5.d.ts} +1 -1
- package/dist/astro/index.js +5 -5
- package/dist/blocks/access-requests/index.js +1 -1
- package/dist/blocks/activities/index.js +1 -1
- package/dist/blocks/agents/index.js +1 -1
- package/dist/blocks/ai-chat/index.js +1 -1
- package/dist/blocks/ai-keys/index.js +1 -1
- package/dist/blocks/announcements/index.js +1 -1
- package/dist/blocks/api-keys/index.js +1 -1
- package/dist/blocks/approvals/index.js +1 -1
- package/dist/blocks/assets/index.js +1 -1
- package/dist/blocks/assignment/index.js +1 -1
- package/dist/blocks/attachments/index.js +1 -1
- package/dist/blocks/audit/index.d.ts +1 -1
- package/dist/blocks/audit/index.js +1 -1
- package/dist/blocks/automations/index.js +1 -1
- package/dist/blocks/billable-time/index.js +1 -1
- package/dist/blocks/billing/index.js +2 -2
- package/dist/blocks/bookings/index.js +1 -1
- package/dist/blocks/bulk/index.js +1 -1
- package/dist/blocks/calendar/index.js +1 -1
- package/dist/blocks/catalog/index.js +1 -1
- package/dist/blocks/channels/index.js +1 -1
- package/dist/blocks/collections/index.js +1 -1
- package/dist/blocks/compliance/index.js +1 -1
- package/dist/blocks/connectors/index.js +1 -1
- package/dist/blocks/contacts/index.js +1 -1
- package/dist/blocks/content/index.js +1 -1
- package/dist/blocks/contracts/index.js +1 -1
- package/dist/blocks/courses/index.js +1 -1
- package/dist/blocks/custom-fields/index.js +1 -1
- package/dist/blocks/data-lifecycle/index.js +1 -1
- package/dist/blocks/deals/index.js +1 -1
- package/dist/blocks/dispatch/index.js +1 -1
- package/dist/blocks/documents/index.js +1 -1
- package/dist/blocks/domains/index.js +1 -1
- package/dist/blocks/donations/index.js +1 -1
- package/dist/blocks/drive/index.js +1 -1
- package/dist/blocks/employees/index.js +1 -1
- package/dist/blocks/enrichment/index.js +1 -1
- package/dist/blocks/enrollments/index.js +1 -1
- package/dist/blocks/expenses/index.js +1 -1
- package/dist/blocks/flags/index.js +1 -1
- package/dist/blocks/forecasts/index.js +1 -1
- package/dist/blocks/forms/index.js +1 -1
- package/dist/blocks/guests/index.js +1 -1
- package/dist/blocks/hiring/index.js +1 -1
- package/dist/blocks/imports/index.js +1 -1
- package/dist/blocks/inbox/index.js +1 -1
- package/dist/blocks/incidents/index.js +1 -1
- package/dist/blocks/index.js +2 -2
- package/dist/blocks/inventory/index.js +1 -1
- package/dist/blocks/invoices/index.js +1 -1
- package/dist/blocks/leases/index.js +1 -1
- package/dist/blocks/leave/index.js +1 -1
- package/dist/blocks/ledger/index.js +1 -1
- package/dist/blocks/mail-sync/index.js +1 -1
- package/dist/blocks/messaging/index.js +1 -1
- package/dist/blocks/metrics/index.js +1 -1
- package/dist/blocks/moderation/index.js +1 -1
- package/dist/blocks/notifications/index.js +3 -3
- package/dist/blocks/numbering/index.js +1 -1
- package/dist/blocks/oauth-server/index.js +1 -1
- package/dist/blocks/orders/index.js +1 -1
- package/dist/blocks/organizations/index.js +1 -1
- package/dist/blocks/outbox/index.js +1 -1
- package/dist/blocks/passes/index.js +1 -1
- package/dist/blocks/pipelines/index.js +1 -1
- package/dist/blocks/posts/index.js +1 -1
- package/dist/blocks/promotions/index.js +1 -1
- package/dist/blocks/push/index.js +1 -1
- package/dist/blocks/quotes/index.js +1 -1
- package/dist/blocks/reactions/index.js +1 -1
- package/dist/blocks/relations/index.js +1 -1
- package/dist/blocks/reminders/index.js +1 -1
- package/dist/blocks/reviews/index.js +1 -1
- package/dist/blocks/saved-views/index.js +1 -1
- package/dist/blocks/scores/index.js +1 -1
- package/dist/blocks/search/index.js +1 -1
- package/dist/blocks/security-events/index.js +1 -1
- package/dist/blocks/segments/index.js +1 -1
- package/dist/blocks/sequences/index.js +1 -1
- package/dist/blocks/service-accounts/index.js +1 -1
- package/dist/blocks/settings/index.js +1 -1
- package/dist/blocks/share-links/index.js +1 -1
- package/dist/blocks/shipments/index.js +1 -1
- package/dist/blocks/signatures/index.js +1 -1
- package/dist/blocks/signing-keys/index.js +1 -1
- package/dist/blocks/sla/index.js +1 -1
- package/dist/blocks/sso/index.js +1 -1
- package/dist/blocks/state-machine/index.js +1 -1
- package/dist/blocks/tags/index.js +1 -1
- package/dist/blocks/tasks/index.js +2 -2
- package/dist/blocks/teams/index.js +1 -1
- package/dist/blocks/templates/index.js +1 -1
- package/dist/blocks/time-tracking/index.js +1 -1
- package/dist/blocks/timeline/index.js +1 -1
- package/dist/blocks/trash/index.js +1 -1
- package/dist/blocks/vercel-marketplace/index.js +1 -1
- package/dist/blocks/versions/index.js +1 -1
- package/dist/blocks/waitlist/index.js +1 -1
- package/dist/blocks/webhooks/index.js +4 -4
- package/dist/blocks/workflow-editor/index.js +1 -1
- package/dist/blocks/workflows/index.js +1 -1
- package/dist/cli/{add-C0w-mVTQ.js → add-B6CQOt3A.js} +2 -2
- package/dist/cli/{add-BTDPjVGC.js → add-BXFzr0Wf.js} +9 -9
- package/dist/cli/add-w_HumDPX.js +1 -0
- package/dist/cli/{backfill-BDdBs6Ne.js → backfill-Dflp6JZk.js} +1 -1
- package/dist/cli/bin.js +1 -1
- package/dist/cli/{blocks-Bs-lA-U_.js → blocks-CBH3N7Fy.js} +1 -1
- package/dist/cli/{blocks-CQLME-HQ.js → blocks-FtOIcUbu.js} +1 -1
- package/dist/cli/{cache-DDKao2Va.js → cache-61VwYKEv.js} +1 -1
- package/dist/cli/{codemod-Bjl998Do.js → codemod-CqPRa25J.js} +1 -1
- package/dist/cli/{content-mapper-DgSTl-DL.js → content-mapper-DGQQY5IA.js} +2 -2
- package/dist/cli/{doctor-CMLWbt44.js → doctor-BxxSO193.js} +19 -17
- package/dist/cli/{gen-D3VX8WdV.js → gen-D2cqqqTH.js} +11 -11
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.js +6 -6
- package/dist/cli/{init-D6D6eWze.js → init-BnG1IE1y.js} +5 -5
- package/dist/cli/{live-C_xgTOfD.js → live-D26OWOAb.js} +2 -2
- package/dist/cli/{mcp-B0Irjbes.js → mcp-1l3C_GdB.js} +2 -2
- package/dist/cli/{metadata-cLXra-XB.js → metadata-DDfPBHwI.js} +3 -3
- package/dist/cli/{migration-safety-OUK-Afbb.js → migration-safety-CQbrfZIx.js} +1 -1
- package/dist/cli/{migrations-CHenMvl_.js → migrations-Ch5Uuvyj.js} +1 -1
- package/dist/cli/{module-migration-6V7vXWUK.js → module-migration-Dul1uTYX.js} +2 -2
- package/dist/cli/{powersync-D83yAFbl.js → powersync-CfT-tRx1.js} +2 -2
- package/dist/cli/powersync-Vmhw5c1N.js +1 -0
- package/dist/cli/{print-C0OmQyTu.js → print-CbPT4PTL.js} +2 -2
- package/dist/cli/{remove-BWlOngNT.js → remove-kDH1yxKZ.js} +5 -5
- package/dist/cli/{render-9m70qveo.js → render-0Vd7BaNA.js} +3 -3
- package/dist/cli/{run-gE4eAazR.js → run-Dafms0D2.js} +8 -8
- package/dist/cli/{run-He3M-ZRq.js → run-DxTd55Ug.js} +21 -21
- package/dist/cli/{shared-Cx2WFVWq.js → shared-BQAMXvwd.js} +1 -1
- package/dist/cli/{snapshot-CZb3uVKE.js → snapshot-B8K6gYjA.js} +2 -2
- package/dist/cli/{source-CrYSCdPZ.js → source-CXDyCWz5.js} +1 -1
- package/dist/cli/{spec-Cn5RhuQc.js → spec-BGsnTkIl.js} +2 -2
- package/dist/cli/{spec-D4b9ePuQ.js → spec-CaN7nOqI.js} +1 -1
- package/dist/cli/{sql-layout-CLJ67h3L.js → sql-layout-BGAlcp1U.js} +2 -2
- package/dist/cli/{sync-B8VGiaHk.js → sync-CT_5VG0E.js} +3 -3
- package/dist/cli/{upgrade-DMiYx1C8.js → upgrade-DA7aO88E.js} +2 -2
- package/dist/cli/{upgrade-BvBWK3Fo.js → upgrade-frUtPDDb.js} +4 -4
- package/dist/cli/{version-BVg2Z6yv.js → version-CUdPyV6J.js} +1 -1
- package/dist/{composite-Dw5ofSF_.js → composite-CBRbvn5j.js} +2 -2
- package/dist/config/index.d.ts +1 -1
- package/dist/config/index.js +4 -4
- package/dist/{config-CD2OGfCG.js → config-C9AOcQ9S.js} +1 -1
- package/dist/{config-BOt5T6Vs.js → config-CH-D2B-4.js} +3 -3
- package/dist/{context-sgrUjA3U.d.ts → context-DEisra3V.d.ts} +15 -3
- package/dist/create/index.d.ts +72 -451
- package/dist/create/index.js +15 -1687
- package/dist/create/lite/index.d.ts +250 -13
- package/dist/create/lite/index.js +1007 -24
- package/dist/credentials/index.js +1 -1
- package/dist/edge/index.js +7 -7
- package/dist/elysia/index.js +1 -1
- package/dist/events/index.js +1 -1
- package/dist/expo/index.js +3 -3
- package/dist/{framework-DXM1vNcV.js → framework-DYEUraqt.js} +1 -1
- package/dist/h3/index.js +1 -1
- package/dist/h3/v1/index.js +1 -1
- package/dist/hono/index.js +6 -6
- package/dist/{index-5JSxY1MG.d.ts → index-3p_oWttZ.d.ts} +77 -2
- package/dist/{index-Bt7_mxn0.d.ts → index-CM2aGNRo.d.ts} +1 -1
- package/dist/{app-tables-DyswUg6J.js → instances-CK0jR3Pc.js} +147 -3
- package/dist/{kit-DhlB-vv_.js → kit-Bcd9wYCV.js} +1 -1
- package/dist/mapper/bin.js +5 -5
- package/dist/mcp/index.js +6 -6
- package/dist/mcp/sdk/index.js +2 -2
- package/dist/nestjs/index.js +1 -1
- package/dist/next/index.js +7 -7
- package/dist/node/index.js +1 -1
- package/dist/orpc/index.d.ts +1 -1
- package/dist/orpc/index.js +5 -5
- package/dist/otel/index.js +4 -4
- package/dist/preset/index.d.ts +4 -4
- package/dist/preset/index.js +4 -4
- package/dist/{preset-B3CukUhu.js → preset-CS490mYJ.js} +179 -7
- package/dist/project-NmP1NdLi.js +1760 -0
- package/dist/react/index.js +2 -2
- package/dist/react/server.js +2 -2
- package/dist/{react-_D_CeZMk.js → react-CcrQQl0_.js} +2 -2
- package/dist/react-router/index.js +5 -5
- package/dist/realtime/index.js +1 -1
- package/dist/{refusal-D48CMqpQ.js → refusal-DDlInPff.js} +2 -2
- package/dist/{instances-DDt7NdVl.js → resolved-names-DdlJzoMK.js} +2 -146
- package/dist/{resource-R3KToNze.js → resource-BUJcZKiW.js} +2 -2
- package/dist/{resources-DqIwoQsP.js → resources-jb3R6rEa.js} +1 -1
- package/dist/server/index.js +7 -7
- package/dist/{sign-in-1FJiXXyG.js → sign-in-NO7LWlw4.js} +2 -2
- package/dist/solid/index.js +1 -1
- package/dist/solid-start/index.js +5 -5
- package/dist/spec/index.d.ts +2 -2
- package/dist/spec/index.js +2 -693
- package/dist/sql/index.d.ts +3 -3
- package/dist/sql/index.js +2 -2
- package/dist/{sql-BjjgwJKg.js → sql-BMXEHTvr.js} +17 -3
- package/dist/svelte/index.js +1 -1
- package/dist/sveltekit/index.js +5 -5
- package/dist/tanstack-start/index.js +5 -5
- package/dist/testing/index.d.ts +2 -2
- package/dist/testing/index.js +4 -4
- package/dist/types-BC1HLEVx.d.ts +461 -0
- package/dist/vue/index.js +1 -1
- package/dist/yjs/index.js +1 -1
- package/package.json +1 -1
- package/dist/cli/add-CspY9jKT.js +0 -1
- package/dist/cli/powersync-DwhCH0gs.js +0 -1
- package/dist/types-DGHfTW8_.d.ts +0 -9
- package/dist/{build-CM8PJqwW.js → build-CH2N3Yf0.js} +3 -3
- package/dist/{create-blocks-CUS28FfS.js → create-blocks-BfrDUSM6.js} +1 -1
- package/dist/{data-hooks-tgF1Ct0F.js → data-hooks-CdcZfVS1.js} +1 -1
- package/dist/{respond-3RKp6VgU.js → respond-CZMWbUs3.js} +1 -1
- package/dist/{topic-J9I3yu6f.js → topic-DClSoqY7.js} +1 -1
|
@@ -1,4 +1,47 @@
|
|
|
1
|
+
import { y as appDefaultError } from "../../instances-CK0jR3Pc.js";
|
|
2
|
+
import { n as loadProject } from "../../project-NmP1NdLi.js";
|
|
1
3
|
import { n as loadLite, t as LITE_INSTALL } from "../../runtime-CoKxZibd.js";
|
|
4
|
+
import { t as defineApi } from "../../api-3C0AWFeP.js";
|
|
5
|
+
//#region src/create/lite/apply.ts
|
|
6
|
+
const MISSING_EXTENSION = /extension "([^"]+)" is not available/u;
|
|
7
|
+
function messageOf$1(error) {
|
|
8
|
+
return (error instanceof Error ? error.message : String(error)).replaceAll(/\s+/gu, " ").slice(0, 300);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Runs each file in order. A module that needs an extension PGlite doesn't ship
|
|
12
|
+
* is skipped, with its other files. pgTAP test files are left out.
|
|
13
|
+
*/
|
|
14
|
+
async function applyFiles(driver, files) {
|
|
15
|
+
const issues = [];
|
|
16
|
+
const skipped = /* @__PURE__ */ new Map();
|
|
17
|
+
for (const file of files) {
|
|
18
|
+
if (file.path.includes("/tests/") || skipped.has(file.module)) continue;
|
|
19
|
+
try {
|
|
20
|
+
await driver.exec(file.contents);
|
|
21
|
+
} catch (error) {
|
|
22
|
+
const message = messageOf$1(error);
|
|
23
|
+
const extension = MISSING_EXTENSION.exec(message)?.[1];
|
|
24
|
+
if (extension === void 0) issues.push({
|
|
25
|
+
code: "sql_error",
|
|
26
|
+
severity: "error",
|
|
27
|
+
source: "sql",
|
|
28
|
+
path: "",
|
|
29
|
+
table: file.module,
|
|
30
|
+
file: file.path,
|
|
31
|
+
message
|
|
32
|
+
});
|
|
33
|
+
else skipped.set(file.module, `Needs the ${extension} extension, which PGlite doesn't ship.`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
issues,
|
|
38
|
+
skipped: [...skipped].map(([module, reason]) => ({
|
|
39
|
+
module,
|
|
40
|
+
reason
|
|
41
|
+
}))
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
//#endregion
|
|
2
45
|
//#region src/create/lite/prelude.ts
|
|
3
46
|
/**
|
|
4
47
|
* What a Supabase project already has before the first migration runs: the API
|
|
@@ -71,11 +114,963 @@ create table if not exists storage.objects (
|
|
|
71
114
|
);
|
|
72
115
|
`;
|
|
73
116
|
//#endregion
|
|
74
|
-
//#region src/create/lite/
|
|
75
|
-
|
|
117
|
+
//#region src/create/lite/catalog.ts
|
|
118
|
+
function schemaList(schemas) {
|
|
119
|
+
return schemas.map((name) => `'${name.replaceAll("'", "''")}'`).join(", ");
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* One query that returns the whole catalog as JSON, so it runs through the
|
|
123
|
+
* Management API's read-only endpoint in a single call.
|
|
124
|
+
*/
|
|
125
|
+
function catalogQuery(schemas = ["public"]) {
|
|
126
|
+
const list = schemaList(schemas);
|
|
127
|
+
return `select json_build_object(
|
|
128
|
+
'tables', (
|
|
129
|
+
select coalesce(json_agg(t order by t.schema, t.name), '[]'::json) from (
|
|
130
|
+
select n.nspname as schema, c.relname as name, c.relkind::text as kind,
|
|
131
|
+
c.relrowsecurity as rls,
|
|
132
|
+
obj_description(c.oid, 'pg_class') as comment,
|
|
133
|
+
(select coalesce(json_agg(json_build_object(
|
|
134
|
+
'name', a.attname,
|
|
135
|
+
'type', format_type(a.atttypid, a.atttypmod),
|
|
136
|
+
'nullable', not a.attnotnull,
|
|
137
|
+
'default', pg_get_expr(d.adbin, d.adrelid),
|
|
138
|
+
'identity', nullif(a.attidentity::text, ''),
|
|
139
|
+
'generated', a.attgenerated::text <> '',
|
|
140
|
+
'comment', col_description(c.oid, a.attnum),
|
|
141
|
+
'udt', coalesce(el.typname, ty.typname),
|
|
142
|
+
'array', ty.typcategory = 'A',
|
|
143
|
+
'enumValues', (select coalesce(json_agg(e.enumlabel order by e.enumsortorder), '[]'::json)
|
|
144
|
+
from pg_enum e where e.enumtypid = coalesce(el.oid, ty.oid))
|
|
145
|
+
) order by a.attnum), '[]'::json)
|
|
146
|
+
from pg_attribute a
|
|
147
|
+
join pg_type ty on ty.oid = a.atttypid
|
|
148
|
+
left join pg_type el on el.oid = ty.typelem and ty.typcategory = 'A'
|
|
149
|
+
left join pg_attrdef d on d.adrelid = a.attrelid and d.adnum = a.attnum
|
|
150
|
+
where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped) as columns,
|
|
151
|
+
(select coalesce(json_agg(json_build_object(
|
|
152
|
+
'name', k.conname,
|
|
153
|
+
'type', k.contype::text,
|
|
154
|
+
'columns', (select json_agg(a.attname order by u.ord)
|
|
155
|
+
from unnest(k.conkey) with ordinality as u(attnum, ord)
|
|
156
|
+
join pg_attribute a on a.attrelid = k.conrelid and a.attnum = u.attnum),
|
|
157
|
+
'refSchema', fn.nspname,
|
|
158
|
+
'refTable', fc.relname,
|
|
159
|
+
'refColumns', (select json_agg(a.attname order by u.ord)
|
|
160
|
+
from unnest(k.confkey) with ordinality as u(attnum, ord)
|
|
161
|
+
join pg_attribute a on a.attrelid = k.confrelid and a.attnum = u.attnum),
|
|
162
|
+
'onDelete', k.confdeltype::text
|
|
163
|
+
)), '[]'::json)
|
|
164
|
+
from pg_constraint k
|
|
165
|
+
left join pg_class fc on fc.oid = k.confrelid
|
|
166
|
+
left join pg_namespace fn on fn.oid = fc.relnamespace
|
|
167
|
+
where k.conrelid = c.oid and k.contype in ('p', 'u', 'f')) as constraints,
|
|
168
|
+
(select coalesce(json_agg(json_build_object(
|
|
169
|
+
'columns', (select json_agg(a.attname order by u.ord)
|
|
170
|
+
from unnest(i.indkey::int2[]) with ordinality as u(attnum, ord)
|
|
171
|
+
join pg_attribute a on a.attrelid = i.indrelid and a.attnum = u.attnum),
|
|
172
|
+
'plain', (not i.indisunique and not i.indisprimary
|
|
173
|
+
and i.indpred is null and i.indexprs is null
|
|
174
|
+
and am.amname = 'btree')
|
|
175
|
+
)), '[]'::json)
|
|
176
|
+
from pg_index i
|
|
177
|
+
join pg_class ic on ic.oid = i.indexrelid
|
|
178
|
+
join pg_am am on am.oid = ic.relam
|
|
179
|
+
where i.indrelid = c.oid and not i.indisprimary and not i.indisunique) as indexes,
|
|
180
|
+
(select count(*)::int from pg_policy p where p.polrelid = c.oid) as policies,
|
|
181
|
+
(select count(*)::int from pg_trigger g
|
|
182
|
+
where g.tgrelid = c.oid and not g.tgisinternal) as triggers
|
|
183
|
+
from pg_class c
|
|
184
|
+
join pg_namespace n on n.oid = c.relnamespace
|
|
185
|
+
where n.nspname in (${list}) and c.relkind in ('r', 'p', 'v', 'm')
|
|
186
|
+
) t
|
|
187
|
+
),
|
|
188
|
+
'functions', (
|
|
189
|
+
select coalesce(json_agg(n.nspname || '.' || p.proname order by n.nspname, p.proname), '[]'::json)
|
|
190
|
+
from pg_proc p join pg_namespace n on n.oid = p.pronamespace
|
|
191
|
+
where n.nspname in (${list}) and p.prokind in ('f', 'p')
|
|
192
|
+
)
|
|
193
|
+
) as catalog`;
|
|
194
|
+
}
|
|
195
|
+
function isRecord(value) {
|
|
196
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
197
|
+
}
|
|
198
|
+
function str(value) {
|
|
199
|
+
return typeof value === "string" ? value : null;
|
|
200
|
+
}
|
|
201
|
+
function strings(value) {
|
|
202
|
+
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
203
|
+
}
|
|
204
|
+
function records(value) {
|
|
205
|
+
return Array.isArray(value) ? value.filter((item) => isRecord(item)) : [];
|
|
206
|
+
}
|
|
207
|
+
function readColumn(row) {
|
|
208
|
+
return {
|
|
209
|
+
name: str(row["name"]) ?? "",
|
|
210
|
+
type: str(row["type"]) ?? "",
|
|
211
|
+
nullable: row["nullable"] !== false,
|
|
212
|
+
default: str(row["default"]),
|
|
213
|
+
identity: str(row["identity"]),
|
|
214
|
+
generated: row["generated"] === true,
|
|
215
|
+
comment: str(row["comment"]),
|
|
216
|
+
udt: str(row["udt"]) ?? "",
|
|
217
|
+
array: row["array"] === true,
|
|
218
|
+
enumValues: strings(row["enumValues"])
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
function readConstraint(row) {
|
|
222
|
+
const type = str(row["type"]);
|
|
223
|
+
return {
|
|
224
|
+
name: str(row["name"]) ?? "",
|
|
225
|
+
type: type === "p" || type === "u" ? type : "f",
|
|
226
|
+
columns: strings(row["columns"]),
|
|
227
|
+
refSchema: str(row["refSchema"]),
|
|
228
|
+
refTable: str(row["refTable"]),
|
|
229
|
+
refColumns: Array.isArray(row["refColumns"]) ? strings(row["refColumns"]) : null,
|
|
230
|
+
onDelete: str(row["onDelete"])
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
function readTable(row) {
|
|
234
|
+
return {
|
|
235
|
+
schema: str(row["schema"]) ?? "public",
|
|
236
|
+
name: str(row["name"]) ?? "",
|
|
237
|
+
kind: str(row["kind"]) ?? "r",
|
|
238
|
+
rls: row["rls"] === true,
|
|
239
|
+
comment: str(row["comment"]),
|
|
240
|
+
columns: records(row["columns"]).map((each) => readColumn(each)),
|
|
241
|
+
constraints: records(row["constraints"]).map((each) => readConstraint(each)),
|
|
242
|
+
indexes: records(row["indexes"]).map((each) => ({
|
|
243
|
+
columns: strings(each["columns"]),
|
|
244
|
+
plain: each["plain"] === true
|
|
245
|
+
})),
|
|
246
|
+
policies: typeof row["policies"] === "number" ? row["policies"] : 0,
|
|
247
|
+
triggers: typeof row["triggers"] === "number" ? row["triggers"] : 0
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
/** Reads the one row `catalogQuery` returns; the JSON may arrive as text. */
|
|
251
|
+
function readCatalog(rows) {
|
|
252
|
+
const [row] = rows;
|
|
253
|
+
const cell = isRecord(row) ? row["catalog"] : void 0;
|
|
254
|
+
const catalog = typeof cell === "string" ? JSON.parse(cell) : cell;
|
|
255
|
+
if (!isRecord(catalog)) throw new TypeError("The catalog query returned an unexpected result.");
|
|
256
|
+
return {
|
|
257
|
+
tables: records(catalog["tables"]).map((each) => readTable(each)),
|
|
258
|
+
functions: strings(catalog["functions"])
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
//#endregion
|
|
262
|
+
//#region src/create/lite/import.ts
|
|
263
|
+
const BLOCK_PREFIX = "bsb_";
|
|
264
|
+
const SIMPLE_TYPES = [
|
|
265
|
+
[/^(?:text|character varying(?:\(\d+\))?|character(?:\(\d+\))?|citext)$/u, "text"],
|
|
266
|
+
[/^uuid$/u, "uuid"],
|
|
267
|
+
[/^(?:integer|smallint)$/u, "integer"],
|
|
268
|
+
[/^bigint$/u, "bigint"],
|
|
269
|
+
[/^numeric(?:\(\d+(?:,\d+)?\))?$/u, "numeric"],
|
|
270
|
+
[/^boolean$/u, "boolean"],
|
|
271
|
+
[/^timestamp with time zone$/u, "timestamptz"],
|
|
272
|
+
[/^date$/u, "date"],
|
|
273
|
+
[/^(?:jsonb|json)$/u, "jsonb"],
|
|
274
|
+
[/^(?:text|character varying(?:\(\d+\))?)\[\]$/u, "text[]"]
|
|
275
|
+
];
|
|
276
|
+
function columnType(type) {
|
|
277
|
+
return SIMPLE_TYPES.find(([pattern]) => pattern.test(type))?.[1];
|
|
278
|
+
}
|
|
279
|
+
/** `'x'::text` and `(0)::bigint` print as `'x'` and `0`. */
|
|
280
|
+
function plainDefault(value) {
|
|
281
|
+
return value.replace(/^\((.*)\)(?:::[\w\s."[\]]+)$/u, "$1").replace(/^('(?:[^']|'')*')(?:::[\w\s."[\]]+)$/u, "$1");
|
|
282
|
+
}
|
|
283
|
+
function onDelete(code) {
|
|
284
|
+
switch (code ?? "a") {
|
|
285
|
+
case "r": return "restrict";
|
|
286
|
+
case "c": return "cascade";
|
|
287
|
+
case "n": return "set null";
|
|
288
|
+
default: return "no action";
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
function rungOf(table) {
|
|
292
|
+
if (!table.rls) return "open";
|
|
293
|
+
return table.policies === 0 ? "locked" : "protected";
|
|
294
|
+
}
|
|
295
|
+
const qualified = (table) => `${table.schema}.${table.name}`;
|
|
296
|
+
/** A table the design can model: `public`, a single `id` key, no generated id. */
|
|
297
|
+
function idOf(table) {
|
|
298
|
+
const keys = table.constraints.filter((each) => each.type === "p");
|
|
299
|
+
if (keys.length !== 1 || keys[0]?.columns.length !== 1) return;
|
|
300
|
+
if (keys[0].columns[0] !== "id") return;
|
|
301
|
+
const type = table.columns.find((each) => each.name === "id")?.type;
|
|
302
|
+
if (type === "uuid") return "uuid";
|
|
303
|
+
return type === "bigint" ? "bigint" : void 0;
|
|
304
|
+
}
|
|
305
|
+
function modelTable(table, modeled, preserved) {
|
|
306
|
+
const id = idOf(table);
|
|
307
|
+
if (id === void 0) return;
|
|
308
|
+
const names = new Set(table.columns.map((each) => each.name));
|
|
309
|
+
const timestamps = ["created_at", "updated_at"].every((name) => table.columns.find((each) => each.name === name)?.type === "timestamp with time zone");
|
|
310
|
+
const implicit = /* @__PURE__ */ new Set(["id", ...timestamps ? ["created_at", "updated_at"] : []]);
|
|
311
|
+
const unique = /* @__PURE__ */ new Set();
|
|
312
|
+
const uniqueSets = [];
|
|
313
|
+
const references = /* @__PURE__ */ new Map();
|
|
314
|
+
for (const constraint of table.constraints) {
|
|
315
|
+
if (constraint.type === "u") {
|
|
316
|
+
if (constraint.columns.length === 1 && constraint.columns[0] !== void 0) unique.add(constraint.columns[0]);
|
|
317
|
+
else uniqueSets.push([...constraint.columns]);
|
|
318
|
+
}
|
|
319
|
+
if (constraint.type !== "f") continue;
|
|
320
|
+
const [column] = constraint.columns;
|
|
321
|
+
const target = `${constraint.refSchema ?? ""}.${constraint.refTable ?? ""}`;
|
|
322
|
+
const onlyOne = constraint.columns.length === 1 && column !== void 0;
|
|
323
|
+
const toId = constraint.refColumns?.join(",") === "id";
|
|
324
|
+
if (onlyOne && toId && target === "auth.users") references.set(column, {
|
|
325
|
+
table: "auth.users",
|
|
326
|
+
onDelete: onDelete(constraint.onDelete)
|
|
327
|
+
});
|
|
328
|
+
else if (onlyOne && toId && constraint.refSchema === "public" && modeled.has(target)) references.set(column, {
|
|
329
|
+
table: constraint.refTable ?? "",
|
|
330
|
+
onDelete: onDelete(constraint.onDelete)
|
|
331
|
+
});
|
|
332
|
+
else preserved.push({
|
|
333
|
+
kind: "foreign_key",
|
|
334
|
+
name: `${qualified(table)}(${constraint.columns.join(", ")})`,
|
|
335
|
+
reason: `References ${target}, which a design can't express.`
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
const columns = {};
|
|
339
|
+
for (const column of table.columns) {
|
|
340
|
+
if (implicit.has(column.name)) continue;
|
|
341
|
+
const type = columnType(column.type);
|
|
342
|
+
if (type === void 0 || column.generated) {
|
|
343
|
+
preserved.push({
|
|
344
|
+
kind: "column",
|
|
345
|
+
name: `${qualified(table)}.${column.name}`,
|
|
346
|
+
reason: column.generated ? "A generated column is kept as it is." : `The type ${column.type} is kept as it is.`
|
|
347
|
+
});
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
const reference = references.get(column.name);
|
|
351
|
+
let fallback;
|
|
352
|
+
if (column.default !== null) {
|
|
353
|
+
const value = plainDefault(column.default);
|
|
354
|
+
if (appDefaultError({ type }, value) === void 0) fallback = value;
|
|
355
|
+
else preserved.push({
|
|
356
|
+
kind: "default",
|
|
357
|
+
name: `${qualified(table)}.${column.name}`,
|
|
358
|
+
reason: `The default ${column.default} is kept as it is.`
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
columns[column.name] = {
|
|
362
|
+
type,
|
|
363
|
+
...column.nullable ? {} : { nullable: false },
|
|
364
|
+
...fallback === void 0 ? {} : { default: fallback },
|
|
365
|
+
...unique.has(column.name) ? { unique: true } : {},
|
|
366
|
+
...reference === void 0 ? {} : { references: reference },
|
|
367
|
+
...column.identity === null ? {} : { identity: true },
|
|
368
|
+
...column.comment === null ? {} : { comment: column.comment }
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
const indexes = [];
|
|
372
|
+
for (const index of table.indexes) if (index.plain && index.columns.every((name) => names.has(name))) indexes.push([...index.columns]);
|
|
373
|
+
else preserved.push({
|
|
374
|
+
kind: "index",
|
|
375
|
+
name: `${qualified(table)}(${index.columns.join(", ")})`,
|
|
376
|
+
reason: "An expression, partial or non-btree index is kept as it is."
|
|
377
|
+
});
|
|
378
|
+
return {
|
|
379
|
+
columns,
|
|
380
|
+
scope: "none",
|
|
381
|
+
...timestamps ? {} : { timestamps: false },
|
|
382
|
+
...id === "bigint" ? { id } : {},
|
|
383
|
+
...uniqueSets.length === 0 ? {} : { unique: uniqueSets },
|
|
384
|
+
...indexes.length === 0 ? {} : { indexes },
|
|
385
|
+
...table.comment === null ? {} : { comment: table.comment }
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
/** Turns a catalog into a design and the report the import shows. */
|
|
389
|
+
function designFromCatalog(catalog, issues = []) {
|
|
390
|
+
const preserved = [];
|
|
391
|
+
const verifier = [];
|
|
392
|
+
const blockOwned = [];
|
|
393
|
+
const imported = [];
|
|
394
|
+
const appTables = {};
|
|
395
|
+
const candidates = catalog.tables.filter((table) => {
|
|
396
|
+
if (table.kind === "v" || table.kind === "m") {
|
|
397
|
+
preserved.push({
|
|
398
|
+
kind: "view",
|
|
399
|
+
name: qualified(table),
|
|
400
|
+
reason: "A view is kept as it is."
|
|
401
|
+
});
|
|
402
|
+
return false;
|
|
403
|
+
}
|
|
404
|
+
if (table.name.startsWith(BLOCK_PREFIX)) {
|
|
405
|
+
blockOwned.push(qualified(table));
|
|
406
|
+
return false;
|
|
407
|
+
}
|
|
408
|
+
return true;
|
|
409
|
+
});
|
|
410
|
+
const modeled = new Set(candidates.filter((table) => table.schema === "public" && idOf(table) !== void 0).map((table) => qualified(table)));
|
|
411
|
+
for (const table of candidates) {
|
|
412
|
+
const model = modeled.has(qualified(table)) ? modelTable(table, modeled, preserved) : void 0;
|
|
413
|
+
if (model === void 0) preserved.push({
|
|
414
|
+
kind: "table",
|
|
415
|
+
name: qualified(table),
|
|
416
|
+
reason: table.schema === "public" ? "It has no single uuid or bigint id key, so it is kept as it is." : "Only the public schema is modeled."
|
|
417
|
+
});
|
|
418
|
+
else appTables[table.name] = model;
|
|
419
|
+
imported.push({
|
|
420
|
+
schema: table.schema,
|
|
421
|
+
name: table.name,
|
|
422
|
+
rung: rungOf(table),
|
|
423
|
+
modeled: model !== void 0,
|
|
424
|
+
columns: table.columns.length
|
|
425
|
+
});
|
|
426
|
+
if (!table.rls) verifier.push({
|
|
427
|
+
code: "verify_rls_disabled",
|
|
428
|
+
severity: "error",
|
|
429
|
+
source: "verifier",
|
|
430
|
+
path: "",
|
|
431
|
+
table: table.name,
|
|
432
|
+
message: `${qualified(table)} has row level security off, so the Data API exposes every row.`
|
|
433
|
+
});
|
|
434
|
+
else if (table.policies === 0) verifier.push({
|
|
435
|
+
code: "verify_no_policies",
|
|
436
|
+
severity: "info",
|
|
437
|
+
source: "verifier",
|
|
438
|
+
path: "",
|
|
439
|
+
table: table.name,
|
|
440
|
+
message: `${qualified(table)} has row level security on and no policies, so only the service role can read it.`
|
|
441
|
+
});
|
|
442
|
+
if (table.triggers > 0) preserved.push({
|
|
443
|
+
kind: "trigger",
|
|
444
|
+
name: qualified(table),
|
|
445
|
+
reason: `${String(table.triggers)} trigger(s) are kept as they are.`
|
|
446
|
+
});
|
|
447
|
+
if (table.policies > 0) preserved.push({
|
|
448
|
+
kind: "policy",
|
|
449
|
+
name: qualified(table),
|
|
450
|
+
reason: `${String(table.policies)} polic${table.policies === 1 ? "y is" : "ies are"} kept as ${table.policies === 1 ? "it is" : "they are"}.`
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
for (const name of catalog.functions) preserved.push({
|
|
454
|
+
kind: "function",
|
|
455
|
+
name,
|
|
456
|
+
reason: "A function is kept as it is."
|
|
457
|
+
});
|
|
458
|
+
return {
|
|
459
|
+
design: Object.keys(appTables).length === 0 ? {} : { appTables },
|
|
460
|
+
report: {
|
|
461
|
+
counts: {
|
|
462
|
+
tables: candidates.length,
|
|
463
|
+
modeledTables: Object.keys(appTables).length,
|
|
464
|
+
columns: candidates.reduce((sum, table) => sum + table.columns.length, 0),
|
|
465
|
+
views: catalog.tables.filter((table) => table.kind !== "r" && table.kind !== "p").length,
|
|
466
|
+
functions: catalog.functions.length,
|
|
467
|
+
triggers: catalog.tables.reduce((sum, table) => sum + table.triggers, 0),
|
|
468
|
+
policies: catalog.tables.reduce((sum, table) => sum + table.policies, 0)
|
|
469
|
+
},
|
|
470
|
+
tables: imported,
|
|
471
|
+
blockOwned,
|
|
472
|
+
preserved,
|
|
473
|
+
issues: [...issues, ...verifier]
|
|
474
|
+
}
|
|
475
|
+
};
|
|
476
|
+
}
|
|
76
477
|
function messageOf(error) {
|
|
77
478
|
return (error instanceof Error ? error.message : String(error)).replaceAll(/\s+/gu, " ").slice(0, 300);
|
|
78
479
|
}
|
|
480
|
+
async function readFiles(files, schemas, runtime) {
|
|
481
|
+
const lite = runtime ?? await loadLite();
|
|
482
|
+
if (lite === void 0) throw new Error(LITE_INSTALL);
|
|
483
|
+
const connection = await lite.createPgliteConnection();
|
|
484
|
+
try {
|
|
485
|
+
const { driver } = connection;
|
|
486
|
+
const issues = [];
|
|
487
|
+
await driver.exec(SUPABASE_PRELUDE);
|
|
488
|
+
const ordered = files.toSorted((left, right) => left.path.localeCompare(right.path));
|
|
489
|
+
for (const file of ordered) try {
|
|
490
|
+
await driver.exec(file.contents);
|
|
491
|
+
} catch (error) {
|
|
492
|
+
issues.push({
|
|
493
|
+
code: "sql_error",
|
|
494
|
+
severity: "error",
|
|
495
|
+
source: "sql",
|
|
496
|
+
path: "",
|
|
497
|
+
table: file.path,
|
|
498
|
+
file: file.path,
|
|
499
|
+
message: messageOf(error)
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
const { rows } = await driver.query(catalogQuery(schemas));
|
|
503
|
+
return designFromCatalog(readCatalog(rows), issues);
|
|
504
|
+
} finally {
|
|
505
|
+
await connection.close();
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
async function readSupabase(source, schemas) {
|
|
509
|
+
const base = (source.apiUrl ?? "https://api.supabase.com").replace(/\/$/u, "");
|
|
510
|
+
const response = await (source.fetch ?? fetch)(`${base}/v1/projects/${encodeURIComponent(source.projectRef)}/database/query/read-only`, {
|
|
511
|
+
method: "POST",
|
|
512
|
+
headers: {
|
|
513
|
+
authorization: `Bearer ${source.accessToken}`,
|
|
514
|
+
"content-type": "application/json"
|
|
515
|
+
},
|
|
516
|
+
body: JSON.stringify({ query: catalogQuery(schemas) })
|
|
517
|
+
});
|
|
518
|
+
if (!response.ok) throw new Error(`Supabase answered ${String(response.status)} for project ${source.projectRef}.`);
|
|
519
|
+
const rows = await response.json();
|
|
520
|
+
if (!Array.isArray(rows)) throw new TypeError(`Supabase sent an unexpected body for project ${source.projectRef}.`);
|
|
521
|
+
return designFromCatalog(readCatalog(rows));
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Reads an existing project into a `Design` and a report (ADR 0100). The design
|
|
525
|
+
* models the tables Create can express: `public` tables with a single `uuid` or
|
|
526
|
+
* `bigint` `id` key, their columns, references to other modeled tables or
|
|
527
|
+
* `auth.users`, unique keys and plain indexes. Everything else is listed under
|
|
528
|
+
* `report.preserved` and is never dropped: a deploy applies only what the
|
|
529
|
+
* design adds. Tables named `bsb_*` belong to blocks. The report also carries
|
|
530
|
+
* each table's adoption rung and the security findings (`source: "verifier"`).
|
|
531
|
+
*
|
|
532
|
+
* Throws when a `files` source needs `@supabase/lite` and it isn't installed,
|
|
533
|
+
* or when a `supabase` source answers with an error.
|
|
534
|
+
*/
|
|
535
|
+
async function importProject(options) {
|
|
536
|
+
const schemas = options.schemas ?? ["public"];
|
|
537
|
+
const { source } = options;
|
|
538
|
+
switch (source.kind) {
|
|
539
|
+
case "files": return readFiles(source.files, schemas, options.runtime);
|
|
540
|
+
case "queryable": {
|
|
541
|
+
const { rows } = await source.queryable.query(catalogQuery(schemas));
|
|
542
|
+
return designFromCatalog(readCatalog(rows));
|
|
543
|
+
}
|
|
544
|
+
case "supabase": return readSupabase(source, schemas);
|
|
545
|
+
default: return source;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
/** Files in the shape `previewFiles` returns, for callers that hold those. */
|
|
549
|
+
function importFilesOf(files) {
|
|
550
|
+
return files.filter((file) => !file.path.includes("/tests/")).map(({ path, contents }) => ({
|
|
551
|
+
path,
|
|
552
|
+
contents
|
|
553
|
+
}));
|
|
554
|
+
}
|
|
555
|
+
//#endregion
|
|
556
|
+
//#region src/create/lite/rest.ts
|
|
557
|
+
const FILTERS = {
|
|
558
|
+
eq: "=",
|
|
559
|
+
neq: "<>",
|
|
560
|
+
gt: ">",
|
|
561
|
+
gte: ">=",
|
|
562
|
+
lt: "<",
|
|
563
|
+
lte: "<=",
|
|
564
|
+
like: "like",
|
|
565
|
+
ilike: "ilike"
|
|
566
|
+
};
|
|
567
|
+
const RESERVED = /* @__PURE__ */ new Set([
|
|
568
|
+
"select",
|
|
569
|
+
"order",
|
|
570
|
+
"limit",
|
|
571
|
+
"offset",
|
|
572
|
+
"columns",
|
|
573
|
+
"on_conflict"
|
|
574
|
+
]);
|
|
575
|
+
const quote = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
576
|
+
const bad = (message, code = "PGRST100") => ({
|
|
577
|
+
status: 400,
|
|
578
|
+
code,
|
|
579
|
+
message
|
|
580
|
+
});
|
|
581
|
+
function json(status, body) {
|
|
582
|
+
return Response.json(body, { status });
|
|
583
|
+
}
|
|
584
|
+
function problem(error) {
|
|
585
|
+
return json(error.status, {
|
|
586
|
+
code: error.code,
|
|
587
|
+
message: error.message,
|
|
588
|
+
details: null,
|
|
589
|
+
hint: null
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
function decodeClaims(token) {
|
|
593
|
+
const [, payload] = token.split(".");
|
|
594
|
+
if (payload === void 0) return;
|
|
595
|
+
try {
|
|
596
|
+
const text = atob(payload.replaceAll("-", "+").replaceAll("_", "/"));
|
|
597
|
+
const parsed = JSON.parse(text);
|
|
598
|
+
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? Object.fromEntries(Object.entries(parsed)) : void 0;
|
|
599
|
+
} catch {
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* The persona a request's bearer token names. The sandbox decodes the payload
|
|
605
|
+
* and does not verify the signature.
|
|
606
|
+
*/
|
|
607
|
+
function personaOf(request) {
|
|
608
|
+
const header = request.headers.get("authorization") ?? "";
|
|
609
|
+
const token = header.startsWith("Bearer ") ? header.slice(7) : "";
|
|
610
|
+
const claims = token === "" ? void 0 : decodeClaims(token);
|
|
611
|
+
if (claims === void 0) return { role: "anon" };
|
|
612
|
+
const { sub, role, ...rest } = claims;
|
|
613
|
+
const known = role === "anon" || role === "authenticated" || role === "service_role" ? role : void 0;
|
|
614
|
+
return {
|
|
615
|
+
...typeof sub === "string" ? { sub } : {},
|
|
616
|
+
...known === void 0 ? {} : { role: known },
|
|
617
|
+
claims: rest
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
async function columnsOf(run, table) {
|
|
621
|
+
const result = await run({ role: "service_role" }, `select a.attname as name, t.typname as type, t.typcategory = 'A' as array
|
|
622
|
+
from pg_attribute a
|
|
623
|
+
join pg_class c on c.oid = a.attrelid
|
|
624
|
+
join pg_namespace n on n.oid = c.relnamespace
|
|
625
|
+
join pg_type t on t.oid = a.atttypid
|
|
626
|
+
where n.nspname = 'public' and c.relname = $1
|
|
627
|
+
and c.relkind in ('r', 'p', 'v', 'm')
|
|
628
|
+
and a.attnum > 0 and not a.attisdropped`, [table]);
|
|
629
|
+
if (!result.ok || result.rows.length === 0) return;
|
|
630
|
+
const columns = /* @__PURE__ */ new Map();
|
|
631
|
+
for (const row of result.rows) if (typeof row === "object" && row !== null && "name" in row && typeof row.name === "string" && "type" in row && typeof row.type === "string") columns.set(row.name, {
|
|
632
|
+
type: row.type,
|
|
633
|
+
array: "array" in row && row.array === true
|
|
634
|
+
});
|
|
635
|
+
return columns;
|
|
636
|
+
}
|
|
637
|
+
/** A value as the driver takes it for `column`. */
|
|
638
|
+
function bound(value, column) {
|
|
639
|
+
if (value === null || value === void 0) return null;
|
|
640
|
+
if (column?.array === true && Array.isArray(value)) return `{${value.map((item) => `"${String(item).replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`).join(",")}}`;
|
|
641
|
+
return typeof value === "object" ? JSON.stringify(value) : value;
|
|
642
|
+
}
|
|
643
|
+
var Builder = class {
|
|
644
|
+
params = [];
|
|
645
|
+
add(value) {
|
|
646
|
+
this.params.push(value);
|
|
647
|
+
return `$${String(this.params.length)}`;
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
function conditionOf(column, expression, columns, builder) {
|
|
651
|
+
if (columns.get(column) === void 0) return bad(`Could not find the column ${column}.`, "42703");
|
|
652
|
+
let negate = false;
|
|
653
|
+
let rest = expression;
|
|
654
|
+
if (rest.startsWith("not.")) {
|
|
655
|
+
negate = true;
|
|
656
|
+
rest = rest.slice(4);
|
|
657
|
+
}
|
|
658
|
+
const dot = rest.indexOf(".");
|
|
659
|
+
const op = dot === -1 ? rest : rest.slice(0, dot);
|
|
660
|
+
const value = dot === -1 ? "" : rest.slice(dot + 1);
|
|
661
|
+
const left = quote(column);
|
|
662
|
+
let sql;
|
|
663
|
+
if (op === "is") {
|
|
664
|
+
const keyword = value.toLowerCase();
|
|
665
|
+
if (![
|
|
666
|
+
"null",
|
|
667
|
+
"true",
|
|
668
|
+
"false",
|
|
669
|
+
"unknown"
|
|
670
|
+
].includes(keyword)) return bad(`Unsupported value for is: ${value}.`);
|
|
671
|
+
sql = `${left} is ${keyword}`;
|
|
672
|
+
} else if (op === "in") {
|
|
673
|
+
const inner = /^\((.*)\)$/u.exec(value)?.[1];
|
|
674
|
+
if (inner === void 0) return bad("in expects a parenthesized list.");
|
|
675
|
+
sql = `${left} in (${inner.split(",").map((item) => item.trim().replace(/^"(.*)"$/u, "$1")).map((item) => builder.add(item)).join(", ")})`;
|
|
676
|
+
} else if (op in FILTERS) {
|
|
677
|
+
const operator = FILTERS[op] ?? "=";
|
|
678
|
+
const pattern = op === "like" || op === "ilike" ? value.replaceAll("*", "%") : value;
|
|
679
|
+
sql = `${left} ${operator} ${builder.add(pattern)}`;
|
|
680
|
+
} else return bad(`Unsupported operator ${op}.`);
|
|
681
|
+
return negate ? `not (${sql})` : sql;
|
|
682
|
+
}
|
|
683
|
+
function whereOf(url, columns, builder) {
|
|
684
|
+
const conditions = [];
|
|
685
|
+
for (const [key, expression] of url.searchParams) {
|
|
686
|
+
if (RESERVED.has(key)) continue;
|
|
687
|
+
if (key === "or" || key === "and" || key === "not") return bad(`${key} filters are not supported by the sandbox.`);
|
|
688
|
+
const condition = conditionOf(key, expression, columns, builder);
|
|
689
|
+
if (typeof condition !== "string") return condition;
|
|
690
|
+
conditions.push(condition);
|
|
691
|
+
}
|
|
692
|
+
return conditions.length === 0 ? "" : ` where ${conditions.join(" and ")}`;
|
|
693
|
+
}
|
|
694
|
+
function selectOf(url, columns) {
|
|
695
|
+
const select = url.searchParams.get("select");
|
|
696
|
+
if (select === null || select === "*") return "*";
|
|
697
|
+
if (select.includes("(")) return bad("Embedding is not supported by the sandbox.");
|
|
698
|
+
const names = select.split(",").map((name) => name.trim());
|
|
699
|
+
const missing = names.find((name) => !columns.has(name));
|
|
700
|
+
return missing === void 0 ? names.map((name) => quote(name)).join(", ") : bad(`Could not find the column ${missing}.`, "42703");
|
|
701
|
+
}
|
|
702
|
+
function tailOf(url, columns) {
|
|
703
|
+
let sql = "";
|
|
704
|
+
const order = url.searchParams.get("order");
|
|
705
|
+
if (order !== null) {
|
|
706
|
+
const parts = [];
|
|
707
|
+
for (const item of order.split(",")) {
|
|
708
|
+
const [name = "", ...flags] = item.split(".");
|
|
709
|
+
if (!columns.has(name)) return bad(`Could not find the column ${name}.`, "42703");
|
|
710
|
+
parts.push(`${quote(name)}${flags.includes("desc") ? " desc" : ""}${flags.includes("nullsfirst") ? " nulls first" : flags.includes("nullslast") ? " nulls last" : ""}`);
|
|
711
|
+
}
|
|
712
|
+
sql += ` order by ${parts.join(", ")}`;
|
|
713
|
+
}
|
|
714
|
+
for (const key of ["limit", "offset"]) {
|
|
715
|
+
const value = url.searchParams.get(key);
|
|
716
|
+
if (value !== null) {
|
|
717
|
+
if (!/^\d+$/u.test(value)) return bad(`${key} must be a number.`);
|
|
718
|
+
sql += ` ${key} ${value}`;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
return sql;
|
|
722
|
+
}
|
|
723
|
+
function statusOf(code, persona) {
|
|
724
|
+
switch (code) {
|
|
725
|
+
case "42501": return persona.sub === void 0 && persona.role !== "service_role" ? 401 : 403;
|
|
726
|
+
case "23505":
|
|
727
|
+
case "23503":
|
|
728
|
+
case "23P01": return 409;
|
|
729
|
+
case "42P01":
|
|
730
|
+
case "42883": return 404;
|
|
731
|
+
default: return 400;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
async function readBody(request) {
|
|
735
|
+
const text = await request.text();
|
|
736
|
+
return text === "" ? void 0 : JSON.parse(text);
|
|
737
|
+
}
|
|
738
|
+
function isRow(value) {
|
|
739
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
740
|
+
}
|
|
741
|
+
async function writeRows(request, table, columns, url, builder) {
|
|
742
|
+
let body;
|
|
743
|
+
try {
|
|
744
|
+
body = await readBody(request);
|
|
745
|
+
} catch {
|
|
746
|
+
return bad("The body is not valid JSON.", "PGRST102");
|
|
747
|
+
}
|
|
748
|
+
const returning = request.headers.get("prefer")?.includes("return=representation") ? " returning *" : "";
|
|
749
|
+
if (request.method === "POST") {
|
|
750
|
+
const rows = (Array.isArray(body) ? body : [body]).filter((row) => isRow(row));
|
|
751
|
+
if (rows.length === 0) return bad("The body must be a JSON object or an array of objects.", "PGRST102");
|
|
752
|
+
const keys = [...new Set(rows.flatMap((row) => Object.keys(row)))];
|
|
753
|
+
const unknown = keys.find((key) => !columns.has(key));
|
|
754
|
+
if (unknown !== void 0) return bad(`Could not find the ${unknown} column of ${table}.`, "PGRST204");
|
|
755
|
+
if (keys.length === 0) return `insert into public.${quote(table)} default values${returning}`;
|
|
756
|
+
const values = rows.map((row) => `(${keys.map((key) => Object.hasOwn(row, key) ? builder.add(bound(row[key], columns.get(key))) : "default").join(", ")})`);
|
|
757
|
+
return `insert into public.${quote(table)} (${keys.map((key) => quote(key)).join(", ")}) values ${values.join(", ")}${returning}`;
|
|
758
|
+
}
|
|
759
|
+
if (!isRow(body)) return bad("The body must be a JSON object.", "PGRST102");
|
|
760
|
+
const keys = Object.keys(body);
|
|
761
|
+
const unknown = keys.find((key) => !columns.has(key));
|
|
762
|
+
if (unknown !== void 0) return bad(`Could not find the ${unknown} column of ${table}.`, "PGRST204");
|
|
763
|
+
if (keys.length === 0) return bad("There is nothing to update.", "PGRST102");
|
|
764
|
+
const sets = keys.map((key) => `${quote(key)} = ${builder.add(bound(body[key], columns.get(key)))}`);
|
|
765
|
+
const where = whereOf(url, columns, builder);
|
|
766
|
+
return typeof where === "string" ? `update public.${quote(table)} set ${sets.join(", ")}${where}${returning}` : where;
|
|
767
|
+
}
|
|
768
|
+
async function callFunction(request, name, persona, run) {
|
|
769
|
+
let body;
|
|
770
|
+
try {
|
|
771
|
+
body = await readBody(request);
|
|
772
|
+
} catch {
|
|
773
|
+
return problem(bad("The body is not valid JSON.", "PGRST102"));
|
|
774
|
+
}
|
|
775
|
+
const args = isRow(body) ? Object.entries(body) : [];
|
|
776
|
+
const builder = new Builder();
|
|
777
|
+
const list = args.map(([key, value]) => `${quote(key)} => ${builder.add(bound(value, void 0))}`).join(", ");
|
|
778
|
+
const result = await run(persona, `select * from public.${quote(name)}(${list})`, builder.params);
|
|
779
|
+
if (!result.ok) return problem({
|
|
780
|
+
status: statusOf(result.error.code, persona),
|
|
781
|
+
code: result.error.code,
|
|
782
|
+
message: result.error.message
|
|
783
|
+
});
|
|
784
|
+
const [first] = result.rows;
|
|
785
|
+
if (result.rows.length === 1 && isRow(first) && Object.keys(first).length === 1 && Object.hasOwn(first, name)) return json(200, first[name]);
|
|
786
|
+
return json(200, result.rows);
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* A subset of PostgREST: `GET`, `POST`, `PATCH` and `DELETE` on
|
|
790
|
+
* `/rest/v1/<table>` and `POST` on `/rest/v1/rpc/<function>`. With no `fixed`
|
|
791
|
+
* persona the bearer token names one.
|
|
792
|
+
*/
|
|
793
|
+
async function handleRest(request, run, fixed) {
|
|
794
|
+
const persona = fixed ?? personaOf(request);
|
|
795
|
+
const url = new URL(request.url);
|
|
796
|
+
const [name = "", extra] = url.pathname.replace(/^\/rest\/v1\/?/u, "").replace(/^\//u, "").split("/");
|
|
797
|
+
const isRpc = name === "rpc";
|
|
798
|
+
const target = isRpc ? extra ?? "" : name;
|
|
799
|
+
if (target === "" || !/^[\w$]+$/u.test(target)) return problem({
|
|
800
|
+
status: 404,
|
|
801
|
+
code: "PGRST125",
|
|
802
|
+
message: `Invalid path specified in request URL: ${url.pathname}`
|
|
803
|
+
});
|
|
804
|
+
if (isRpc) return request.method === "POST" ? callFunction(request, target, persona, run) : problem({
|
|
805
|
+
status: 405,
|
|
806
|
+
code: "PGRST101",
|
|
807
|
+
message: "Functions take POST."
|
|
808
|
+
});
|
|
809
|
+
const columns = await columnsOf(run, target);
|
|
810
|
+
if (columns === void 0) return problem({
|
|
811
|
+
status: 404,
|
|
812
|
+
code: "PGRST205",
|
|
813
|
+
message: `Could not find the table public.${target} in the schema cache`
|
|
814
|
+
});
|
|
815
|
+
const builder = new Builder();
|
|
816
|
+
let sql;
|
|
817
|
+
switch (request.method) {
|
|
818
|
+
case "GET":
|
|
819
|
+
case "HEAD": {
|
|
820
|
+
const select = selectOf(url, columns);
|
|
821
|
+
const where = whereOf(url, columns, builder);
|
|
822
|
+
const tail = tailOf(url, columns);
|
|
823
|
+
sql = [
|
|
824
|
+
select,
|
|
825
|
+
where,
|
|
826
|
+
tail
|
|
827
|
+
].find((part) => typeof part !== "string") ?? `select ${String(select)} from public.${quote(target)}${String(where)}${String(tail)}`;
|
|
828
|
+
break;
|
|
829
|
+
}
|
|
830
|
+
case "POST":
|
|
831
|
+
case "PATCH":
|
|
832
|
+
sql = await writeRows(request, target, columns, url, builder);
|
|
833
|
+
break;
|
|
834
|
+
case "DELETE": {
|
|
835
|
+
const where = whereOf(url, columns, builder);
|
|
836
|
+
const returning = request.headers.get("prefer")?.includes("return=representation") ? " returning *" : "";
|
|
837
|
+
sql = typeof where === "string" ? `delete from public.${quote(target)}${where}${returning}` : where;
|
|
838
|
+
break;
|
|
839
|
+
}
|
|
840
|
+
default: return problem({
|
|
841
|
+
status: 405,
|
|
842
|
+
code: "PGRST101",
|
|
843
|
+
message: `Unsupported HTTP method: ${request.method}`
|
|
844
|
+
});
|
|
845
|
+
}
|
|
846
|
+
if (typeof sql !== "string") return problem(sql);
|
|
847
|
+
const result = await run(persona, sql, builder.params);
|
|
848
|
+
if (!result.ok) return problem({
|
|
849
|
+
status: statusOf(result.error.code, persona),
|
|
850
|
+
code: result.error.code,
|
|
851
|
+
message: result.error.message
|
|
852
|
+
});
|
|
853
|
+
if (!(request.method === "GET" || request.method === "HEAD" || request.headers.get("prefer")?.includes("return=representation") === true)) return new Response(null, { status: request.method === "POST" ? 201 : 204 });
|
|
854
|
+
const status = request.method === "POST" ? 201 : 200;
|
|
855
|
+
if (request.headers.get("accept")?.includes("application/vnd.pgrst.object+json") === true) {
|
|
856
|
+
if (result.rows.length !== 1) return problem({
|
|
857
|
+
status: 406,
|
|
858
|
+
code: "PGRST116",
|
|
859
|
+
message: "JSON object requested, multiple (or no) rows returned"
|
|
860
|
+
});
|
|
861
|
+
return json(status, result.rows[0]);
|
|
862
|
+
}
|
|
863
|
+
return request.method === "HEAD" ? new Response(null, { status }) : json(status, result.rows);
|
|
864
|
+
}
|
|
865
|
+
//#endregion
|
|
866
|
+
//#region src/create/lite/sandbox.ts
|
|
867
|
+
/** What Supabase grants the API roles on `public` by default. */
|
|
868
|
+
const API_GRANTS = `
|
|
869
|
+
grant usage on schema public to anon, authenticated, service_role;
|
|
870
|
+
alter default privileges in schema public grant all on tables to anon, authenticated, service_role;
|
|
871
|
+
alter default privileges in schema public grant all on sequences to anon, authenticated, service_role;
|
|
872
|
+
alter default privileges in schema public grant all on functions to anon, authenticated, service_role;
|
|
873
|
+
`;
|
|
874
|
+
const ROLES = /* @__PURE__ */ new Set([
|
|
875
|
+
"anon",
|
|
876
|
+
"authenticated",
|
|
877
|
+
"service_role"
|
|
878
|
+
]);
|
|
879
|
+
function roleOf(persona) {
|
|
880
|
+
return persona.role ?? (persona.sub === void 0 ? "anon" : "authenticated");
|
|
881
|
+
}
|
|
882
|
+
function claimsOf(persona) {
|
|
883
|
+
return {
|
|
884
|
+
...persona.claims,
|
|
885
|
+
role: roleOf(persona),
|
|
886
|
+
...persona.sub === void 0 ? {} : { sub: persona.sub }
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
function errorOf(error) {
|
|
890
|
+
return {
|
|
891
|
+
code: typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "XX000",
|
|
892
|
+
message: messageOf$1(error)
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
/** Rows, as a plain array, from whatever PGlite returned. */
|
|
896
|
+
function rowsOf(result) {
|
|
897
|
+
return result.rows;
|
|
898
|
+
}
|
|
899
|
+
var Queue = class {
|
|
900
|
+
tail = Promise.resolve();
|
|
901
|
+
run(task) {
|
|
902
|
+
const next = this.tail.then(task);
|
|
903
|
+
this.tail = next.catch(() => void 0);
|
|
904
|
+
return next;
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
async function asPersona(driver, queue, persona, sql, params) {
|
|
908
|
+
return queue.run(async () => {
|
|
909
|
+
const role = roleOf(persona);
|
|
910
|
+
if (!ROLES.has(role)) return {
|
|
911
|
+
ok: false,
|
|
912
|
+
error: {
|
|
913
|
+
code: "22023",
|
|
914
|
+
message: `Unknown role ${role}.`
|
|
915
|
+
}
|
|
916
|
+
};
|
|
917
|
+
await driver.exec("begin");
|
|
918
|
+
try {
|
|
919
|
+
await driver.query(`select set_config('role', $1, true),
|
|
920
|
+
set_config('request.jwt.claims', $2, true),
|
|
921
|
+
set_config('request.jwt.claim.sub', $3, true),
|
|
922
|
+
set_config('request.jwt.claim.role', $1, true)`, [
|
|
923
|
+
role,
|
|
924
|
+
JSON.stringify(claimsOf(persona)),
|
|
925
|
+
persona.sub ?? ""
|
|
926
|
+
]);
|
|
927
|
+
const rows = rowsOf(await driver.query(sql, params));
|
|
928
|
+
await driver.exec("commit");
|
|
929
|
+
return {
|
|
930
|
+
ok: true,
|
|
931
|
+
rows
|
|
932
|
+
};
|
|
933
|
+
} catch (error) {
|
|
934
|
+
await driver.exec("rollback").catch(() => void 0);
|
|
935
|
+
return {
|
|
936
|
+
ok: false,
|
|
937
|
+
error: errorOf(error)
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* Opens an in-memory PGlite database with a project's files applied, the
|
|
944
|
+
* Supabase roles in place and the API roles granted what Supabase grants them
|
|
945
|
+
* by default. Queries run as the database owner, or as a persona through `as({
|
|
946
|
+
* sub, role, claims })` with row level security applied, and `rest` answers a
|
|
947
|
+
* subset of PostgREST: table reads and writes with `select`, filters, `order`,
|
|
948
|
+
* `limit` and `offset`, and `rpc` calls. Embedding, `or`, `and` and range
|
|
949
|
+
* headers are not supported. Throws when `@supabase/lite` isn't installed.
|
|
950
|
+
*/
|
|
951
|
+
async function openSandbox(project, options = {}) {
|
|
952
|
+
const runtime = options.runtime ?? await loadLite();
|
|
953
|
+
if (runtime === void 0) throw new Error(LITE_INSTALL);
|
|
954
|
+
const connection = await runtime.createPgliteConnection();
|
|
955
|
+
const { driver } = connection;
|
|
956
|
+
const queue = new Queue();
|
|
957
|
+
await driver.exec(SUPABASE_PRELUDE);
|
|
958
|
+
await driver.exec(API_GRANTS);
|
|
959
|
+
const { issues, skipped } = await applyFiles(driver, project.files);
|
|
960
|
+
const run = (persona, sql, params) => asPersona(driver, queue, persona, sql, params);
|
|
961
|
+
const session = (persona) => ({
|
|
962
|
+
query: (sql, params = []) => run(persona, sql, params),
|
|
963
|
+
rest: (request) => handleRest(request, run, persona)
|
|
964
|
+
});
|
|
965
|
+
const owner = (sql, params = []) => queue.run(async () => {
|
|
966
|
+
try {
|
|
967
|
+
return {
|
|
968
|
+
ok: true,
|
|
969
|
+
rows: rowsOf(await driver.query(sql, params))
|
|
970
|
+
};
|
|
971
|
+
} catch (error) {
|
|
972
|
+
return {
|
|
973
|
+
ok: false,
|
|
974
|
+
error: errorOf(error)
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
});
|
|
978
|
+
return {
|
|
979
|
+
query: owner,
|
|
980
|
+
rest: (request) => handleRest(request, run),
|
|
981
|
+
as: session,
|
|
982
|
+
issues,
|
|
983
|
+
skipped,
|
|
984
|
+
catalog: async () => {
|
|
985
|
+
const { rows } = await driver.query(catalogQuery(["public"]));
|
|
986
|
+
return readCatalog(rows);
|
|
987
|
+
},
|
|
988
|
+
close: () => connection.close()
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
//#endregion
|
|
992
|
+
//#region src/create/lite/data-api.ts
|
|
993
|
+
const JSON_TYPES = /* @__PURE__ */ new Set(["json", "jsonb"]);
|
|
994
|
+
function columnMeta(column) {
|
|
995
|
+
const identity = column.identity === "a" ? "always" : column.identity === "d" ? "by default" : void 0;
|
|
996
|
+
return {
|
|
997
|
+
db: column.name,
|
|
998
|
+
type: column.udt,
|
|
999
|
+
nullable: column.nullable,
|
|
1000
|
+
hasDefault: column.default !== null || identity !== void 0,
|
|
1001
|
+
...column.generated ? { generated: true } : {},
|
|
1002
|
+
...identity === void 0 ? {} : { identity },
|
|
1003
|
+
...column.array ? { array: true } : {},
|
|
1004
|
+
...JSON_TYPES.has(column.udt) ? { json: true } : {},
|
|
1005
|
+
...column.enumValues.length > 0 ? { enum: column.enumValues } : {},
|
|
1006
|
+
...column.comment === null ? {} : { description: column.comment }
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
1009
|
+
function tableMeta(table) {
|
|
1010
|
+
const uniqueKeys = {};
|
|
1011
|
+
for (const constraint of table.constraints) if (constraint.type === "u") uniqueKeys[constraint.name] = constraint.columns;
|
|
1012
|
+
return {
|
|
1013
|
+
key: table.name,
|
|
1014
|
+
name: table.name,
|
|
1015
|
+
schema: table.schema,
|
|
1016
|
+
kind: table.kind === "r" || table.kind === "p" ? "table" : "view",
|
|
1017
|
+
columns: Object.fromEntries(table.columns.map((column) => [column.name, columnMeta(column)])),
|
|
1018
|
+
primaryKey: table.constraints.find((each) => each.type === "p")?.columns ?? [],
|
|
1019
|
+
uniqueKeys,
|
|
1020
|
+
relations: {},
|
|
1021
|
+
flags: {},
|
|
1022
|
+
...table.comment === null ? {} : { description: table.comment }
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
/**
|
|
1026
|
+
* The runtime metadata of a catalog's `public` tables and views, in snake
|
|
1027
|
+
* casing, keyed by table name. It carries what the Data API document needs:
|
|
1028
|
+
* columns, keys and enums. Relations and functions are left out.
|
|
1029
|
+
*/
|
|
1030
|
+
function schemaMetaFromCatalog(catalog) {
|
|
1031
|
+
const tables = catalog.tables.filter((table) => table.schema === "public");
|
|
1032
|
+
const enums = {};
|
|
1033
|
+
for (const table of tables) for (const column of table.columns) if (column.enumValues.length > 0) enums[column.udt] = column.enumValues;
|
|
1034
|
+
return {
|
|
1035
|
+
version: 1,
|
|
1036
|
+
casing: "snake",
|
|
1037
|
+
tables: Object.fromEntries(tables.map((table) => [table.name, tableMeta(table)])),
|
|
1038
|
+
enums,
|
|
1039
|
+
functions: {}
|
|
1040
|
+
};
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* The OpenAPI document of the Data API a design produces: the files render to a
|
|
1044
|
+
* PGlite database, and the tables that come out become `/rest/v1` paths with
|
|
1045
|
+
* row, insert and update schemas. It never touches a project. Throws when
|
|
1046
|
+
* `@supabase/lite` isn't installed.
|
|
1047
|
+
*/
|
|
1048
|
+
async function designDataApi(preset, design = {}, options = {}) {
|
|
1049
|
+
const loaded = await loadProject(design, { preset });
|
|
1050
|
+
if (!loaded.ok) return loaded;
|
|
1051
|
+
const sandbox = await openSandbox(loaded.project, options);
|
|
1052
|
+
try {
|
|
1053
|
+
const meta = schemaMetaFromCatalog(await sandbox.catalog());
|
|
1054
|
+
const { document, diagnostics } = defineApi({ meta }, {
|
|
1055
|
+
info: {
|
|
1056
|
+
title: options.title ?? "Data API",
|
|
1057
|
+
version: options.version ?? "1.0.0"
|
|
1058
|
+
},
|
|
1059
|
+
dataApi: { tables: true },
|
|
1060
|
+
...options.supabaseUrl === void 0 ? {} : { supabaseUrl: options.supabaseUrl }
|
|
1061
|
+
}).openapi();
|
|
1062
|
+
return {
|
|
1063
|
+
ok: true,
|
|
1064
|
+
document,
|
|
1065
|
+
diagnostics,
|
|
1066
|
+
tables: Object.keys(meta.tables).toSorted()
|
|
1067
|
+
};
|
|
1068
|
+
} finally {
|
|
1069
|
+
await sandbox.close();
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
//#endregion
|
|
1073
|
+
//#region src/create/lite/index.ts
|
|
79
1074
|
/**
|
|
80
1075
|
* Applies the files `previewFiles` returns to an in-memory PGlite database and
|
|
81
1076
|
* reports what Postgres rejects. A module that needs an extension PGlite
|
|
@@ -90,38 +1085,26 @@ async function validateDesign(files, options = {}) {
|
|
|
90
1085
|
try {
|
|
91
1086
|
const { driver } = connection;
|
|
92
1087
|
await driver.exec(SUPABASE_PRELUDE);
|
|
93
|
-
const issues =
|
|
94
|
-
const skipped = /* @__PURE__ */ new Map();
|
|
95
|
-
for (const file of files) {
|
|
96
|
-
if (file.path.includes("/tests/") || skipped.has(file.module)) continue;
|
|
97
|
-
try {
|
|
98
|
-
await driver.exec(file.contents);
|
|
99
|
-
} catch (error) {
|
|
100
|
-
const message = messageOf(error);
|
|
101
|
-
const extension = MISSING_EXTENSION.exec(message)?.[1];
|
|
102
|
-
if (extension === void 0) issues.push({
|
|
103
|
-
module: file.module,
|
|
104
|
-
path: file.path,
|
|
105
|
-
message
|
|
106
|
-
});
|
|
107
|
-
else skipped.set(file.module, `Needs the ${extension} extension, which PGlite doesn't ship.`);
|
|
108
|
-
}
|
|
109
|
-
}
|
|
1088
|
+
const { issues, skipped } = await applyFiles(driver, files);
|
|
110
1089
|
const { rows } = await driver.query("select count(*)::int as count from pg_tables where schemaname = 'public'");
|
|
111
1090
|
const [row] = rows;
|
|
112
1091
|
const tables = typeof row === "object" && row !== null && "count" in row ? Number(row.count) : 0;
|
|
113
1092
|
return {
|
|
114
1093
|
ok: issues.length === 0,
|
|
115
1094
|
issues,
|
|
116
|
-
skipped
|
|
117
|
-
module,
|
|
118
|
-
reason
|
|
119
|
-
})),
|
|
1095
|
+
skipped,
|
|
120
1096
|
tables
|
|
121
1097
|
};
|
|
122
1098
|
} finally {
|
|
123
1099
|
await connection.close();
|
|
124
1100
|
}
|
|
125
1101
|
}
|
|
1102
|
+
/**
|
|
1103
|
+
* The issues `validateDesign` finds, for `checkProject`'s `sql` option:
|
|
1104
|
+
* `checkProject(project, { sql: sqlIssues })`.
|
|
1105
|
+
*/
|
|
1106
|
+
async function sqlIssues(files) {
|
|
1107
|
+
return (await validateDesign(files)).issues;
|
|
1108
|
+
}
|
|
126
1109
|
//#endregion
|
|
127
|
-
export { SUPABASE_PRELUDE, validateDesign };
|
|
1110
|
+
export { SUPABASE_PRELUDE, designDataApi, designFromCatalog, importFilesOf, importProject, openSandbox, schemaMetaFromCatalog, sqlIssues, validateDesign };
|