better-supabase 0.2.0 → 0.3.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.
Files changed (139) hide show
  1. package/README.md +34 -31
  2. package/dist/base64-CQeB1eSf.js +42 -0
  3. package/dist/client/index.d.ts +1 -1
  4. package/dist/client/index.js +4 -14
  5. package/dist/{compiler-CZ9nIuqy.d.ts → compiler-2zqGzxVZ.d.ts} +2 -2
  6. package/dist/config/index.d.ts +4 -3
  7. package/dist/config/index.js +5 -3
  8. package/dist/config-Be4GwsqI.js +129 -0
  9. package/dist/{index-DOsjFvMf.d.ts → config-C1CYcm6o.d.ts} +49 -49
  10. package/dist/{config-ClDXmVtY.js → config-DOsGYSiT.js} +14 -137
  11. package/dist/{define-BXMYD9AY.js → define-DF341GDj.js} +71 -51
  12. package/dist/{define-e3zI4_4g.d.ts → define-DUbydmJa.d.ts} +10 -9
  13. package/dist/edge/index.d.ts +4 -4
  14. package/dist/edge/index.js +4 -4
  15. package/dist/{entitlements-Dng-ctuT.d.ts → entitlements-DvJXoI02.d.ts} +1 -1
  16. package/dist/env/index.js +203 -1
  17. package/dist/events/index.d.ts +1 -1
  18. package/dist/events/index.js +139 -1
  19. package/dist/{events-DOt3nSO-.d.ts → events-Do8jXh4D.d.ts} +3 -3
  20. package/dist/{executor-BYXQ9AGn.d.ts → executor-B26lgbHD.d.ts} +2 -2
  21. package/dist/{executor-DeppvirK.js → executor-C57jx2pn.js} +7 -2
  22. package/dist/{executor-CGdNQ27g.d.ts → executor-DynmIWhq.d.ts} +2 -2
  23. package/dist/hono/index.d.ts +5 -5
  24. package/dist/hono/index.js +4 -4
  25. package/dist/{index-CBDufH1M.d.ts → index-BNsABq7P.d.ts} +8 -8
  26. package/dist/{index-Bw1bwtC0.d.ts → index-CADlNHK-.d.ts} +27 -14
  27. package/dist/{index-DuP14VHo.d.ts → index-CTTMS6_1.d.ts} +19 -8
  28. package/dist/index-Cf-D2jk1.d.ts +50 -0
  29. package/dist/{index-K-3WM2Hp.d.ts → index-CriFFJ_p.d.ts} +4 -4
  30. package/dist/{index-Ciu5Xlml.d.ts → index-GV77NpRP.d.ts} +5 -4
  31. package/dist/{index-D4v7sncu.d.ts → index-UJ-LUxtI.d.ts} +3 -3
  32. package/dist/{index-CG69s15v.d.ts → index-kpgopLNv.d.ts} +4 -3
  33. package/dist/{index-DbxFr7XG.d.ts → index-qriRM9cZ.d.ts} +7 -2
  34. package/dist/index.d.ts +12 -12
  35. package/dist/index.js +16 -7
  36. package/dist/jobs/index.d.ts +25 -24
  37. package/dist/jobs/index.js +16 -10
  38. package/dist/{json-schema-BpYqkCKf.js → json-schema--aOXAGfU.js} +7 -2
  39. package/dist/lint/index.js +1 -1
  40. package/dist/list/index.d.ts +2 -2
  41. package/dist/list/index.js +128 -93
  42. package/dist/{live-DJyZMD6w.d.ts → live-QE3UPbGm.d.ts} +16 -6
  43. package/dist/mcp/index.d.ts +24 -17
  44. package/dist/mcp/index.js +41 -12
  45. package/dist/{mfa-CpLfJSde.js → mfa-BxoR1RkN.js} +74 -19
  46. package/dist/{mfa-TVia554c.d.ts → mfa-x3V3vGh-.d.ts} +1 -1
  47. package/dist/next/index.d.ts +39 -26
  48. package/dist/next/index.js +28 -23
  49. package/dist/openapi/index.d.ts +1 -1
  50. package/dist/openapi/index.js +57 -34
  51. package/dist/orpc/index.d.ts +6 -6
  52. package/dist/orpc/index.js +3 -3
  53. package/dist/otel/index.d.ts +2 -2
  54. package/dist/otel/index.js +4 -2
  55. package/dist/{permdock-sql-CghlHPuH.js → permdock-sql-Bta_G0v-.js} +11 -6
  56. package/dist/permdock-sql-DImJULY-.d.ts +17 -0
  57. package/dist/{plugin-C4TR9J0Z.d.ts → plugin-DVRB8qNE.d.ts} +5 -4
  58. package/dist/plugins/actor/index.d.ts +1 -1
  59. package/dist/plugins/rules/index.d.ts +2 -2
  60. package/dist/plugins/rules/index.js +4 -4
  61. package/dist/plugins/soft-delete/index.d.ts +3 -3
  62. package/dist/plugins/soft-delete/index.js +2 -2
  63. package/dist/plugins/tenant/index.d.ts +2 -2
  64. package/dist/plugins/timestamps/index.d.ts +1 -1
  65. package/dist/plugins/timestamps/index.js +1 -1
  66. package/dist/plugins/validation/index.d.ts +2 -2
  67. package/dist/pool-B9qsLyFR.d.ts +71 -0
  68. package/dist/postgres/index.d.ts +10 -5
  69. package/dist/postgres/index.js +36 -16
  70. package/dist/{postgrest-cAEQ_IQN.d.ts → postgrest-DmBlevh-.d.ts} +1 -1
  71. package/dist/{problem-BTkTtRV9.js → problem-CGt1ADix.js} +10 -4
  72. package/dist/{problem-DlgB0lYl.d.ts → problem-Z2RTQjZD.d.ts} +6 -4
  73. package/dist/query/index.d.ts +2 -2
  74. package/dist/query/index.js +1 -1
  75. package/dist/{query-ChvDbsDE.js → query-BdKLTPlj.js} +2 -2
  76. package/dist/react/index.d.ts +7 -7
  77. package/dist/react/index.js +2 -2
  78. package/dist/react/server.d.ts +3 -3
  79. package/dist/react/server.js +1 -1
  80. package/dist/react/session.d.ts +21 -2
  81. package/dist/react/session.js +19 -1
  82. package/dist/{react-C83BdBGt.js → react-DNBYNazu.js} +20 -16
  83. package/dist/{read-set-4lI3W_gZ.js → read-set-D0qBcboM.js} +3 -3
  84. package/dist/realtime/index.d.ts +4 -3
  85. package/dist/realtime/index.js +7 -6
  86. package/dist/{resolve-CjHILk2w.d.ts → resolve-BRciX2jK.d.ts} +6 -5
  87. package/dist/{resource-CgZa3YG_.d.ts → resource-CwVgiI5q.d.ts} +16 -7
  88. package/dist/{resource-BHEWmQJK.js → resource-D30rp0GN.js} +38 -16
  89. package/dist/{respond-DMcbQwfN.js → respond-C44EZAJo.js} +35 -19
  90. package/dist/{respond-Dne1ARSa.d.ts → respond-DAkPIdTH.d.ts} +15 -9
  91. package/dist/{result-CTkCZ6JA.d.ts → result-c2OYgCV2.d.ts} +13 -8
  92. package/dist/server/index.d.ts +35 -10
  93. package/dist/server/index.js +38 -9
  94. package/dist/{simplify-bwJpLnaS.js → simplify-LakqK1vH.js} +10 -16
  95. package/dist/sql/index.d.ts +139 -0
  96. package/dist/sql/index.js +1983 -0
  97. package/dist/{sql-DTjA1LPj.js → sql-BIgk12ew.js} +72 -16
  98. package/dist/ssr/index.d.ts +4 -4
  99. package/dist/ssr/index.js +2 -2
  100. package/dist/{standard-CyhRzctb.d.ts → standard-eudBiRk1.d.ts} +1 -1
  101. package/dist/{stats-C5W-rBfR.js → stats-D78UQ8Yu.js} +8 -7
  102. package/dist/storage/index.d.ts +4 -3
  103. package/dist/storage/index.js +530 -1
  104. package/dist/{tables-rZxRxNPW.js → tables-Dhha3BXM.js} +5 -5
  105. package/dist/temporal-BwshQk0W.js +27 -0
  106. package/dist/temporal-required-CMxeSVPo.js +19 -0
  107. package/dist/testing/index.d.ts +13 -11
  108. package/dist/testing/index.js +128 -29
  109. package/dist/{types-C83v5SQz.d.ts → types-DONv9SHN.d.ts} +14 -11
  110. package/dist/{version-Cqq1m3UY.js → version-BfpG2gks.js} +1 -1
  111. package/dist/{view-D1s0wa0T.d.ts → view-3Po_PVlr.d.ts} +34 -4
  112. package/dist/{view-aOYizTeE.js → view-wZ-9qIUz.js} +11 -2
  113. package/dist/webhooks/index.d.ts +18 -16
  114. package/dist/webhooks/index.js +1 -1
  115. package/dist/{webhooks-DMipjhSP.js → webhooks-CAIFQSTM.js} +11 -9
  116. package/package.json +24 -28
  117. package/schemas/config-v1.json +31 -1
  118. package/schemas/doctor-report-v1.json +17 -1
  119. package/schemas/snapshot-v2.json +35 -0
  120. package/skills/better-supabase/SKILL.md +23 -11
  121. package/skills/better-supabase/references/plugins.md +21 -18
  122. package/skills/better-supabase/references/troubleshooting.md +15 -15
  123. package/skills/better-supabase-api/SKILL.md +7 -7
  124. package/skills/better-supabase-api/references/adapters.md +30 -25
  125. package/skills/better-supabase-testing/SKILL.md +11 -8
  126. package/bin/better-supabase.js +0 -4
  127. package/dist/casing-da0uRTqt.js +0 -14
  128. package/dist/cli/bin.d.ts +0 -1
  129. package/dist/cli/bin.js +0 -15
  130. package/dist/cli/index.d.ts +0 -226
  131. package/dist/cli/index.js +0 -3
  132. package/dist/cli-DrSgDOQC.js +0 -6646
  133. package/dist/env-BEToab0I.js +0 -204
  134. package/dist/events-BuzTgn2D.js +0 -135
  135. package/dist/pool-R2m_DkXi.d.ts +0 -37
  136. package/dist/seed-CzecODcJ.js +0 -101
  137. package/dist/session-C3LxnQ0e.d.ts +0 -22
  138. package/dist/session-CqEwzVup.js +0 -20
  139. package/dist/storage-DuGn38fr.js +0 -527
@@ -1,527 +0,0 @@
1
- import { n as dbError, o as isDbError, t as DbException } from "./errors-Bl3rkOzo.js";
2
- import { i as ok, n as err, o as toDbError, t as AsyncResult } from "./result-DWXatkd6.js";
3
- import { i as tenantClaimPaths } from "./claims-CoTobNC-.js";
4
- import { a as sqlString, i as sqlIdent, n as parseTemplate, r as slug, t as permdockCheck } from "./permdock-sql-CghlHPuH.js";
5
- //#region src/storage/index.ts
6
- /** Storage operations that list objects; every other `select` is a read. */
7
- const LIST_OPERATIONS = [
8
- "object.list",
9
- "object.list_v2",
10
- "s3.object.list"
11
- ];
12
- const TTL = {
13
- minute: 60,
14
- hour: 3600,
15
- day: 86400,
16
- week: 604800
17
- };
18
- const SIZE_UNITS = {
19
- b: 1,
20
- kb: 1e3,
21
- kib: 1024,
22
- mb: 1e3 ** 2,
23
- mib: 1024 ** 2,
24
- gb: 1e3 ** 3,
25
- gib: 1024 ** 3
26
- };
27
- function parseSize(value) {
28
- if (typeof value === "number") return value;
29
- const match = /^\s*(\d+(?:\.\d+)?)\s*([a-z]*)\s*$/i.exec(value);
30
- const unit = SIZE_UNITS[(match?.[2] || "b").toLowerCase()];
31
- if (!match || unit === void 0) throw new TypeError(`Invalid size "${value}"`);
32
- return Math.round(Number(match[1]) * unit);
33
- }
34
- const SAFE_SEGMENT = /^[\w!\-.*'() &$@=;:+,?]+$/;
35
- function validateSegment(_name, value) {
36
- if (value === "." || value === "..") return "is a relative path";
37
- if (!SAFE_SEGMENT.test(value)) return "contains characters Storage does not allow";
38
- }
39
- function claimSql(claim) {
40
- const expressions = (typeof claim === "string" ? [claim] : claim).map((path) => {
41
- const keys = path.split(".");
42
- const last = keys.pop();
43
- return `(select auth.jwt())${keys.map((key) => ` -> ${sqlString(key)}`).join("")} ->> ${sqlString(last)}`;
44
- });
45
- return expressions.length === 1 ? expressions[0] : `coalesce(${expressions.join(", ")})`;
46
- }
47
- function mimeAllowed(allowed, type) {
48
- const base = type.split(";")[0].trim().toLowerCase();
49
- return allowed.some((entry) => {
50
- const pattern = entry.toLowerCase();
51
- return pattern.endsWith("/*") ? base.startsWith(pattern.slice(0, -1)) : base === pattern;
52
- });
53
- }
54
- function sizeLabel(bytes) {
55
- for (const [unit, size] of [
56
- ["GiB", 1024 ** 3],
57
- ["MiB", 1024 ** 2],
58
- ["KiB", 1024]
59
- ]) if (bytes >= size && bytes % size === 0) return `${String(bytes / size)}${unit}`;
60
- return `${String(bytes)}B`;
61
- }
62
- /** Maps a Storage error (`StorageApiError`, fetch failures) to a `DbError`. */
63
- function fromStorageError(raw, table) {
64
- if (isDbError(raw)) return raw;
65
- if (raw instanceof DbException) return raw.error;
66
- if (typeof raw !== "object" || raw === null) return toDbError(raw);
67
- const failure = raw;
68
- if (failure.name === "AbortError") return toDbError(raw);
69
- const message = failure.message ?? "Storage request failed";
70
- const code = failure.code ?? failure.statusCode;
71
- const base = {
72
- ...code ? { code } : {},
73
- ...table ? { table } : {}
74
- };
75
- const statusCode = Number(failure.statusCode);
76
- const status = Number.isFinite(statusCode) && statusCode >= 400 ? statusCode : failure.status ?? 0;
77
- if (/row-level security|unauthorized to|AccessDenied/i.test(`${message} ${code ?? ""}`)) return dbError("forbidden", message, base);
78
- if (/already exists|duplicate/i.test(`${message} ${code ?? ""}`)) return dbError("conflict", message, base);
79
- if (failure.name === "StorageUnknownError" && status === 0) return dbError("network", message, base);
80
- switch (status) {
81
- case 400: return dbError("invalid_request", message, base);
82
- case 401: return dbError("unauthorized", message, base);
83
- case 403: return dbError("forbidden", message, base);
84
- case 404: return dbError("not_found", message, base);
85
- case 409: return dbError("conflict", message, base);
86
- case 413:
87
- case 415: return dbError("invalid_input", message, {
88
- ...base,
89
- status
90
- });
91
- case 408:
92
- case 429: return dbError("network", message, {
93
- ...base,
94
- status
95
- });
96
- default: return status >= 500 ? dbError("network", message, base) : dbError("unexpected", message, base);
97
- }
98
- }
99
- /**
100
- * A typed Storage bucket: path builders from a template, limits, generated
101
- * SQL policies and `config.toml`, and helpers for the multi-step work apps
102
- * repeat (replace, signed uploads, orphan cleanup).
103
- *
104
- * ```ts
105
- * export const logos = defineBucket({
106
- * id: 'customer-logos',
107
- * path: '{orgId}/{customerId}/logo/{version}.webp',
108
- * policy: 'tenant',
109
- * fileSizeLimit: '5MiB',
110
- * allowedMimeTypes: ['image/webp'],
111
- * });
112
- * ```
113
- */
114
- function defineBucket(config) {
115
- const template = parseTemplate(config.path, "/", validateSegment);
116
- const policy = config.policy ?? "none";
117
- const fileSizeLimit = config.fileSizeLimit === void 0 ? void 0 : parseSize(config.fileSizeLimit);
118
- const allowedMimeTypes = config.allowedMimeTypes;
119
- function segmentFor(param, kind) {
120
- const index = template.segmentOf(param);
121
- if (index === void 0) throw new TypeError(`defineBucket: a ${kind} policy needs {${param}} as a whole path segment in "${config.path}"`);
122
- return index;
123
- }
124
- const mode = typeof policy === "string" ? policy : "permdock";
125
- const accessCheck = (() => {
126
- switch (mode) {
127
- case "tenant": {
128
- const index = segmentFor(config.tenant?.param ?? "orgId", "tenant");
129
- const expression = config.tenant?.sql ?? claimSql(config.tenant?.claim ?? tenantClaimPaths());
130
- return `split_part(name, '/', ${String(index)}) = (${expression})`;
131
- }
132
- case "owner": {
133
- const index = segmentFor(config.owner?.param ?? "userId", "owner");
134
- return `split_part(name, '/', ${String(index)}) = (select auth.uid())::text`;
135
- }
136
- case "public":
137
- case "none":
138
- case "permdock": return;
139
- default: throw new TypeError(`defineBucket: unknown policy "${String(mode)}"`);
140
- }
141
- })();
142
- const permdock = (() => {
143
- if (typeof policy === "string") return void 0;
144
- const where = `defineBucket(${config.id})`;
145
- const id = policy.scope === "global" ? void 0 : `split_part(name, '/', ${String(policy.segment ?? segmentFor(config.tenant?.param ?? "orgId", "PermDock"))})`;
146
- const check = (key) => permdockCheck(where, policy, key, id);
147
- const keys = policy.permdock;
148
- return {
149
- read: check(keys.read),
150
- ...keys.list === void 0 ? {} : { list: check(keys.list) },
151
- write: check(keys.write),
152
- delete: check(keys.delete ?? keys.write)
153
- };
154
- })();
155
- const resolve = (target) => {
156
- if (typeof target !== "string") return template.build(target);
157
- if (!template.match(target)) throw new DbException(dbError("invalid_input", `Path "${target}" does not match "${config.path}"`));
158
- return target;
159
- };
160
- const check = (file) => {
161
- if (fileSizeLimit !== void 0 && file.size !== void 0 && file.size > fileSizeLimit) return dbError("invalid_input", `File is larger than ${sizeLabel(fileSizeLimit)}`, { status: 413 });
162
- if (allowedMimeTypes && file.type && !mimeAllowed(allowedMimeTypes, file.type)) return dbError("invalid_input", `File type ${file.type} is not allowed`, { status: 415 });
163
- };
164
- const bucket = {
165
- id: config.id,
166
- template: config.path,
167
- params: template.params,
168
- owner: policy === "owner" ? config.owner?.param ?? "userId" : template.params.includes("userId") ? "userId" : void 0,
169
- public: config.public ?? false,
170
- policy,
171
- fileSizeLimit,
172
- allowedMimeTypes,
173
- path: (values) => template.build(values),
174
- match: (path) => template.match(path),
175
- prefix: (values = {}) => template.prefix(values, template.segments - 1),
176
- check,
177
- sql() {
178
- const id = sqlString(config.id);
179
- const name = slug(config.id);
180
- const lines = [
181
- `-- better-supabase: bucket ${config.id} (${config.path})`,
182
- "insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types)",
183
- `values (${id}, ${id}, ${String(bucket.public)}, ${fileSizeLimit === void 0 ? "null" : String(fileSizeLimit)}, ${allowedMimeTypes ? `array[${allowedMimeTypes.map(sqlString).join(", ")}]` : "null"})`,
184
- "on conflict (id) do update set public = excluded.public, file_size_limit = excluded.file_size_limit,",
185
- " allowed_mime_types = excluded.allowed_mime_types;"
186
- ];
187
- const policies = [];
188
- const inBucket = `bucket_id = ${id}`;
189
- const shape = `name ~ ${sqlString(template.sqlPattern)}`;
190
- if (accessCheck) {
191
- const using = `${inBucket} and ${accessCheck}`;
192
- const write = `${using} and ${shape}`;
193
- policies.push([
194
- "select",
195
- "select",
196
- "authenticated",
197
- using,
198
- void 0
199
- ], [
200
- "insert",
201
- "insert",
202
- "authenticated",
203
- void 0,
204
- write
205
- ], [
206
- "update",
207
- "update",
208
- "authenticated",
209
- using,
210
- write
211
- ], [
212
- "delete",
213
- "delete",
214
- "authenticated",
215
- using,
216
- void 0
217
- ]);
218
- } else if (policy === "public") policies.push([
219
- "select",
220
- "select",
221
- "anon, authenticated",
222
- inBucket,
223
- void 0
224
- ]);
225
- else if (permdock) {
226
- const listing = `storage.allow_any_operation(array[${LIST_OPERATIONS.map(sqlString).join(", ")}])`;
227
- if (permdock.list) policies.push([
228
- "select",
229
- "select",
230
- "authenticated",
231
- `${inBucket} and not ${listing} and ${permdock.read}`,
232
- void 0
233
- ], [
234
- "list",
235
- "select",
236
- "authenticated",
237
- `${inBucket} and ${listing} and ${permdock.list}`,
238
- void 0
239
- ]);
240
- else policies.push([
241
- "select",
242
- "select",
243
- "authenticated",
244
- `${inBucket} and ${permdock.read}`,
245
- void 0
246
- ]);
247
- const write = `${inBucket} and ${permdock.write}`;
248
- policies.push([
249
- "insert",
250
- "insert",
251
- "authenticated",
252
- void 0,
253
- `${write} and ${shape}`
254
- ], [
255
- "update",
256
- "update",
257
- "authenticated",
258
- write,
259
- `${write} and ${shape}`
260
- ], [
261
- "delete",
262
- "delete",
263
- "authenticated",
264
- `${inBucket} and ${permdock.delete}`,
265
- void 0
266
- ]);
267
- }
268
- for (const [suffix, command, roles, using, withCheck] of policies) {
269
- const policyName = sqlIdent(`bs_${name}_${suffix}`);
270
- lines.push("", `drop policy if exists ${policyName} on storage.objects;`, `create policy ${policyName} on storage.objects for ${command} to ${roles}${using ? `\n using (${using})` : ""}${withCheck ? `\n with check (${withCheck})` : ""};`);
271
- }
272
- if (permdock && !permdock.list) lines.push("", `drop policy if exists ${sqlIdent(`bs_${name}_list`)} on storage.objects;`);
273
- return `${lines.join("\n")}\n`;
274
- },
275
- toml() {
276
- const lines = [`[storage.buckets.${config.id}]`, `public = ${String(bucket.public)}`];
277
- if (config.fileSizeLimit !== void 0) lines.push(`file_size_limit = "${typeof config.fileSizeLimit === "number" ? sizeLabel(config.fileSizeLimit) : config.fileSizeLimit}"`);
278
- if (allowedMimeTypes) lines.push(`allowed_mime_types = [${allowedMimeTypes.map((type) => JSON.stringify(type)).join(", ")}]`);
279
- return `${lines.join("\n")}\n`;
280
- },
281
- drift(actual) {
282
- if (!actual) return [{
283
- field: "missing",
284
- expected: config.id,
285
- actual: void 0,
286
- message: `Bucket "${config.id}" does not exist`
287
- }];
288
- const issues = [];
289
- if (actual.public !== bucket.public) issues.push({
290
- field: "public",
291
- expected: bucket.public,
292
- actual: actual.public,
293
- message: `Bucket "${config.id}" public is ${String(actual.public)}`
294
- });
295
- if ((actual.fileSizeLimit ?? void 0) !== fileSizeLimit) issues.push({
296
- field: "fileSizeLimit",
297
- expected: fileSizeLimit,
298
- actual: actual.fileSizeLimit,
299
- message: `Bucket "${config.id}" file size limit differs`
300
- });
301
- const sorted = (list) => list ? [...list].sort().join(",") : "";
302
- if (sorted(actual.allowedMimeTypes) !== sorted(allowedMimeTypes)) issues.push({
303
- field: "allowedMimeTypes",
304
- expected: allowedMimeTypes,
305
- actual: actual.allowedMimeTypes,
306
- message: `Bucket "${config.id}" allowed MIME types differ`
307
- });
308
- return issues;
309
- },
310
- connect: (client) => connectBucket(bucket, client, resolve)
311
- };
312
- return bucket;
313
- }
314
- function bodyInfo(body, contentType) {
315
- const info = {};
316
- if (typeof Blob !== "undefined" && body instanceof Blob) {
317
- info.size = body.size;
318
- if (body.type) info.type = body.type;
319
- } else if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) info.size = body.byteLength;
320
- if (contentType) info.type = contentType;
321
- return info;
322
- }
323
- function ttlSeconds(ttl) {
324
- return typeof ttl === "number" ? ttl : TTL[ttl ?? "hour"];
325
- }
326
- function isErrorResult(value) {
327
- return typeof value === "object" && value !== null && value.ok === false && "error" in value;
328
- }
329
- function connectBucket(bucket, client, resolve) {
330
- const api = () => client.storage.from(bucket.id);
331
- const run = (fn) => AsyncResult.from(async () => {
332
- try {
333
- const { data, error } = await fn();
334
- return error || data === null ? err(fromStorageError(error, bucket.id)) : ok(data);
335
- } catch (cause) {
336
- return err(fromStorageError(cause, bucket.id));
337
- }
338
- });
339
- const fileOptions = (options, contentType) => ({
340
- ...contentType ? { contentType } : {},
341
- ...options?.cacheControl ? { cacheControl: options.cacheControl } : {},
342
- ...options?.metadata ? { metadata: { ...options.metadata } } : {},
343
- upsert: options?.upsert ?? false
344
- });
345
- const download = (value) => value === void 0 ? {} : { download: value };
346
- const upload = (target, body, options) => AsyncResult.from(async () => {
347
- options?.signal?.throwIfAborted();
348
- const path = resolve(target);
349
- const contentType = options?.contentType;
350
- const problem = bucket.check(bodyInfo(body, contentType));
351
- if (problem) return err(problem);
352
- return run(() => api().upload(path, body, fileOptions(options, contentType))).map(() => ({ path }));
353
- });
354
- const remove = (targets) => AsyncResult.from(async () => {
355
- const paths = targets.map(resolve);
356
- if (paths.length === 0) return ok([]);
357
- return run(() => api().remove(paths)).map(() => paths);
358
- });
359
- const walk = async (folder, signal, out) => {
360
- const limit = 1e3;
361
- for (let offset = 0;; offset += limit) {
362
- signal?.throwIfAborted();
363
- const { data, error } = await api().list(folder, {
364
- limit,
365
- offset,
366
- sortBy: {
367
- column: "name",
368
- order: "asc"
369
- }
370
- }, signal ? { signal } : {});
371
- if (error) throw new DbException(fromStorageError(error, bucket.id));
372
- for (const item of data) {
373
- const path = folder ? `${folder}/${item.name}` : item.name;
374
- if (item.id === null) await walk(path, signal, out);
375
- else {
376
- const metadata = item.metadata ?? {};
377
- out.push({
378
- path,
379
- ...typeof metadata.size === "number" ? { size: metadata.size } : {},
380
- ...metadata.mimetype ? { contentType: metadata.mimetype } : {},
381
- createdAt: item.created_at,
382
- updatedAt: item.updated_at
383
- });
384
- }
385
- }
386
- if (data.length < limit) return;
387
- }
388
- };
389
- const list = (within, options) => AsyncResult.from(async () => {
390
- const out = [];
391
- await walk(bucket.prefix(within ?? {}), options?.signal, out);
392
- return ok(out);
393
- }).mapError((error) => ({
394
- ...error,
395
- table: bucket.id
396
- }));
397
- const signedUrl = (target, options) => AsyncResult.from(async () => {
398
- const path = resolve(target);
399
- return run(() => api().createSignedUrl(path, ttlSeconds(options?.ttl), {
400
- ...download(options?.download),
401
- ...options?.transform ? { transform: { ...options.transform } } : {}
402
- })).map((data) => data.signedUrl);
403
- });
404
- return {
405
- bucket,
406
- upload,
407
- download: (target, options) => AsyncResult.from(async () => {
408
- const path = resolve(target);
409
- return run(() => api().download(path, {}, options?.signal ? { signal: options.signal } : {}));
410
- }),
411
- exists: (target) => AsyncResult.from(async () => {
412
- const path = resolve(target);
413
- const found = await api().exists(path);
414
- if (!found.data) return ok(false);
415
- return found.error ? err(fromStorageError(found.error, bucket.id)) : ok(true);
416
- }),
417
- remove,
418
- list,
419
- signedUrl,
420
- signedUrls: (targets, options) => AsyncResult.from(async () => {
421
- const paths = targets.map(resolve);
422
- if (paths.length === 0) return ok([]);
423
- return run(() => api().createSignedUrls(paths, ttlSeconds(options?.ttl), download(options?.download))).andThen(async (data) => {
424
- const failed = data.find((entry) => entry.error != null || !entry.signedUrl);
425
- if (failed) return err(dbError("not_found", failed.error ?? `No URL for ${String(failed.path)}`, { table: bucket.id }));
426
- return ok(data.map((entry) => entry.signedUrl));
427
- });
428
- }),
429
- publicUrl(target, options) {
430
- const path = resolve(target);
431
- return api().getPublicUrl(path, {
432
- ...download(options?.download),
433
- ...options?.transform ? { transform: { ...options.transform } } : {}
434
- }).data.publicUrl;
435
- },
436
- renderUrl(target, transform, options) {
437
- if (!bucket.public) return signedUrl(target, {
438
- ...options,
439
- transform
440
- });
441
- return AsyncResult.from(async () => ok(api().getPublicUrl(resolve(target), {
442
- ...download(options?.download),
443
- transform: { ...transform }
444
- }).data.publicUrl));
445
- },
446
- replace: (target, body, options = {}) => AsyncResult.from(async () => {
447
- const path = resolve(target);
448
- const previous = options.previous ?? null;
449
- const same = previous === path;
450
- const uploaded = await upload(path, body, {
451
- ...options,
452
- upsert: same || (options.upsert ?? false)
453
- });
454
- if (!uploaded.ok) return uploaded;
455
- const undo = async (error) => {
456
- if (!same) await remove([path]);
457
- return err(error);
458
- };
459
- try {
460
- options.signal?.throwIfAborted();
461
- const outcome = await options.commit?.(path);
462
- if (isErrorResult(outcome)) return await undo(outcome.error);
463
- } catch (cause) {
464
- return undo(fromStorageError(cause, bucket.id));
465
- }
466
- if (!previous || same) return ok({
467
- path,
468
- removed: null
469
- });
470
- const removed = await run(() => api().remove([previous]));
471
- return ok(removed.ok ? {
472
- path,
473
- removed: previous
474
- } : {
475
- path,
476
- removed: null,
477
- cleanup: removed.error
478
- });
479
- }),
480
- reserve: (target, options) => AsyncResult.from(async () => {
481
- const path = resolve(target);
482
- return run(() => api().createSignedUploadUrl(path, options?.upsert ? { upsert: true } : void 0)).map((data) => ({
483
- path: data.path,
484
- token: data.token,
485
- signedUrl: data.signedUrl
486
- }));
487
- }),
488
- uploadReserved: (reservation, body, options) => AsyncResult.from(async () => {
489
- options?.signal?.throwIfAborted();
490
- const path = resolve(reservation.path);
491
- const problem = bucket.check(bodyInfo(body, options?.contentType));
492
- if (problem) return err(problem);
493
- return run(() => api().uploadToSignedUrl(path, reservation.token, body, fileOptions(options, options?.contentType))).map(() => ({ path }));
494
- }),
495
- sweep: (options) => AsyncResult.from(async () => {
496
- const now = options.now?.() ?? Date.now();
497
- const cutoff = options.olderThan instanceof Date ? options.olderThan.getTime() : now - options.olderThan;
498
- const found = await list(options.within, options.signal ? { signal: options.signal } : void 0);
499
- if (!found.ok) return found;
500
- const candidates = found.data.filter((object) => bucket.match(object.path) !== null).filter((object) => {
501
- const created = Date.parse(object.createdAt ?? object.updatedAt ?? "");
502
- return Number.isFinite(created) && created < cutoff;
503
- }).map((object) => object.path);
504
- const size = options.batchSize ?? 100;
505
- const orphans = [];
506
- const removed = [];
507
- for (let index = 0; index < candidates.length; index += size) {
508
- options.signal?.throwIfAborted();
509
- const batch = candidates.slice(index, index + size);
510
- const keep = new Set(await options.referenced(batch));
511
- const unreferenced = batch.filter((path) => !keep.has(path));
512
- orphans.push(...unreferenced);
513
- if (options.dryRun || unreferenced.length === 0) continue;
514
- const result = await run(() => api().remove(unreferenced));
515
- if (!result.ok) return result;
516
- removed.push(...unreferenced);
517
- }
518
- return ok({
519
- scanned: found.data.length,
520
- orphans,
521
- removed
522
- });
523
- })
524
- };
525
- }
526
- //#endregion
527
- export { parseSize as i, defineBucket as n, fromStorageError as r, TTL as t };