create-expo-updates-server 0.1.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 (117) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -0
  3. package/bin/create-expo-updates-server.mjs +5 -0
  4. package/dist/template/.env.docker.example +15 -0
  5. package/dist/template/.env.example +35 -0
  6. package/dist/template/Dockerfile +42 -0
  7. package/dist/template/LICENSE +21 -0
  8. package/dist/template/README.md +665 -0
  9. package/dist/template/app/api/admin/access-tokens/[id]/route.ts +25 -0
  10. package/dist/template/app/api/admin/access-tokens/route.test.ts +73 -0
  11. package/dist/template/app/api/admin/access-tokens/route.ts +90 -0
  12. package/dist/template/app/api/admin/embedded-updates/[embeddedUpdateId]/route.ts +25 -0
  13. package/dist/template/app/api/admin/embedded-updates/route.test.ts +102 -0
  14. package/dist/template/app/api/admin/embedded-updates/route.ts +47 -0
  15. package/dist/template/app/api/admin/emergency-redirects/[id]/route.ts +62 -0
  16. package/dist/template/app/api/admin/emergency-redirects/route.test.ts +84 -0
  17. package/dist/template/app/api/admin/emergency-redirects/route.ts +56 -0
  18. package/dist/template/app/api/admin/login/route.test.ts +55 -0
  19. package/dist/template/app/api/admin/login/route.ts +52 -0
  20. package/dist/template/app/api/admin/logout/route.ts +20 -0
  21. package/dist/template/app/api/admin/session/route.ts +15 -0
  22. package/dist/template/app/api/admin/updates/[encodedKey]/deactivate/route.ts +33 -0
  23. package/dist/template/app/api/admin/updates/[encodedKey]/promote/route.ts +29 -0
  24. package/dist/template/app/api/admin/updates/[encodedKey]/rollback/route.ts +29 -0
  25. package/dist/template/app/api/admin/updates/[encodedKey]/route.ts +96 -0
  26. package/dist/template/app/api/admin/updates/route.test.ts +142 -0
  27. package/dist/template/app/api/admin/updates/route.ts +32 -0
  28. package/dist/template/app/api/assets/route.ts +6 -0
  29. package/dist/template/app/api/health/route.test.ts +26 -0
  30. package/dist/template/app/api/health/route.ts +42 -0
  31. package/dist/template/app/api/manifest/route.ts +6 -0
  32. package/dist/template/app/api/update-complete/route.ts +6 -0
  33. package/dist/template/app/favicon.ico +0 -0
  34. package/dist/template/app/globals.css +26 -0
  35. package/dist/template/app/layout.tsx +34 -0
  36. package/dist/template/app/login/page.tsx +77 -0
  37. package/dist/template/app/page.tsx +12 -0
  38. package/dist/template/app/updates/[encodedKey]/page.tsx +482 -0
  39. package/dist/template/app/updates/embedded/page.tsx +164 -0
  40. package/dist/template/app/updates/emergency-redirects/page.tsx +430 -0
  41. package/dist/template/app/updates/layout.tsx +14 -0
  42. package/dist/template/app/updates/page.tsx +281 -0
  43. package/dist/template/docker-compose.yml +100 -0
  44. package/dist/template/docs/expo-app-setup.md +497 -0
  45. package/dist/template/docs/getting-started.md +502 -0
  46. package/dist/template/docs/getting-started.ru.md +623 -0
  47. package/dist/template/docs/index.md +57 -0
  48. package/dist/template/docs/migrations/schema.sql +363 -0
  49. package/dist/template/docs/npm-installer.md +83 -0
  50. package/dist/template/docs/operations-guide.md +270 -0
  51. package/dist/template/docs/ota-emergency-recovery.md +109 -0
  52. package/dist/template/docs/supabase-setup.md +133 -0
  53. package/dist/template/eslint.config.mjs +30 -0
  54. package/dist/template/gitignore.template +58 -0
  55. package/dist/template/next.config.ts +7 -0
  56. package/dist/template/package-lock.json +12156 -0
  57. package/dist/template/package.json +50 -0
  58. package/dist/template/postcss.config.mjs +7 -0
  59. package/dist/template/public/file.svg +1 -0
  60. package/dist/template/public/globe.svg +1 -0
  61. package/dist/template/public/next.svg +1 -0
  62. package/dist/template/public/vercel.svg +1 -0
  63. package/dist/template/public/window.svg +1 -0
  64. package/dist/template/scripts/configure-expo-app.mjs +145 -0
  65. package/dist/template/scripts/create-access-token.mjs +135 -0
  66. package/dist/template/scripts/create-admin.mjs +169 -0
  67. package/dist/template/scripts/import-emergency-redirects.mjs +126 -0
  68. package/dist/template/scripts/lib/embedded-update-registrar.test.ts +64 -0
  69. package/dist/template/scripts/lib/expo-app-configurator.mjs +666 -0
  70. package/dist/template/scripts/lib/expo-app-configurator.test.ts +463 -0
  71. package/dist/template/scripts/lib/expo-app-prompts.mjs +139 -0
  72. package/dist/template/scripts/lib/expo-app-prompts.test.ts +97 -0
  73. package/dist/template/scripts/lib/expo-export-command.test.ts +31 -0
  74. package/dist/template/scripts/lib/ota-publish-retry.test.ts +33 -0
  75. package/dist/template/scripts/manage-emergency-redirect.mjs +483 -0
  76. package/dist/template/scripts/sync-docker-database-password.sh +16 -0
  77. package/dist/template/src/client/admin-api.ts +174 -0
  78. package/dist/template/src/client/admin-types.ts +93 -0
  79. package/dist/template/src/client/logout-button.tsx +31 -0
  80. package/dist/template/src/server/controllers/assets.ts +216 -0
  81. package/dist/template/src/server/controllers/manifest.test.ts +403 -0
  82. package/dist/template/src/server/controllers/manifest.ts +626 -0
  83. package/dist/template/src/server/controllers/update-complete.ts +36 -0
  84. package/dist/template/src/server/lib/admin-access-tokens.ts +169 -0
  85. package/dist/template/src/server/lib/admin-api.ts +101 -0
  86. package/dist/template/src/server/lib/admin-auth.ts +208 -0
  87. package/dist/template/src/server/lib/admin-embedded-updates.ts +150 -0
  88. package/dist/template/src/server/lib/admin-updates.ts +1282 -0
  89. package/dist/template/src/server/lib/common.js +24 -0
  90. package/dist/template/src/server/lib/emergency-channel-redirects.ts +310 -0
  91. package/dist/template/src/server/lib/env.js +8 -0
  92. package/dist/template/src/server/lib/manifest-helpers.js +91 -0
  93. package/dist/template/src/server/lib/response.js +11 -0
  94. package/dist/template/src/server/lib/signing.js +55 -0
  95. package/dist/template/src/server/lib/supabase.js +763 -0
  96. package/dist/template/src/server/manifest/manifest-repository.ts +269 -0
  97. package/dist/template/src/server/manifest/manifest-request.ts +21 -0
  98. package/dist/template/src/server/manifest/manifest-response.ts +235 -0
  99. package/dist/template/src/server/manifest/manifest-values.ts +62 -0
  100. package/dist/template/templates/expo-app/.env.ota.example +18 -0
  101. package/dist/template/templates/expo-app/ci_scripts/ci_post_xcodebuild.sh +6 -0
  102. package/dist/template/templates/expo-app/ci_scripts/register-embedded-update.sh +36 -0
  103. package/dist/template/templates/expo-app/plugins/with-ota-embedded-registration.js +33 -0
  104. package/dist/template/templates/expo-app/scripts/ota-publish/api/database-client.mjs +87 -0
  105. package/dist/template/templates/expo-app/scripts/ota-publish/api/storage-client.mjs +57 -0
  106. package/dist/template/templates/expo-app/scripts/ota-publish/index.mjs +182 -0
  107. package/dist/template/templates/expo-app/scripts/ota-publish/lib/common.mjs +84 -0
  108. package/dist/template/templates/expo-app/scripts/ota-publish/lib/expo-export-command.mjs +24 -0
  109. package/dist/template/templates/expo-app/scripts/ota-publish/lib/retry.mjs +25 -0
  110. package/dist/template/templates/expo-app/scripts/ota-publish/shared/config.mjs +48 -0
  111. package/dist/template/templates/expo-app/scripts/ota-register-embedded/android-register-embedded-update.sh +18 -0
  112. package/dist/template/templates/expo-app/scripts/ota-register-embedded/index.mjs +275 -0
  113. package/dist/template/tsconfig.json +36 -0
  114. package/dist/template/vitest.config.mts +20 -0
  115. package/dist/template-manifest.json +564 -0
  116. package/lib/cli.mjs +549 -0
  117. package/package.json +41 -0
@@ -0,0 +1,763 @@
1
+ import { Pool } from "pg";
2
+ import { createClient } from "@supabase/supabase-js";
3
+ import {
4
+ DeleteObjectsCommand,
5
+ GetObjectCommand,
6
+ ListObjectsV2Command,
7
+ S3Client,
8
+ } from "@aws-sdk/client-s3";
9
+ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
10
+
11
+ const DATABASE_URL = process.env.DATABASE_URL;
12
+ const DATABASE_SSL = (process.env.DATABASE_SSL || "false").toLowerCase();
13
+ const DATABASE_PROVIDER = (
14
+ process.env.DATABASE_PROVIDER ||
15
+ process.env.DB_PROVIDER ||
16
+ "pg"
17
+ ).toLowerCase();
18
+
19
+ const SUPABASE_URL =
20
+ process.env.SUPABASE_PROJECT_URL || process.env.SUPABASE_URL;
21
+ const SUPABASE_KEY =
22
+ process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_PUBLISHED_KEY;
23
+
24
+ const R2_ENDPOINT = process.env.R2_ENDPOINT;
25
+ const R2_ACCESS_KEY_ID = process.env.R2_ACCESS_KEY_ID;
26
+ const R2_SECRET_ACCESS_KEY = process.env.R2_SECRET_ACCESS_KEY;
27
+ const R2_REGION = process.env.R2_REGION || "auto";
28
+ const S3_FORCE_PATH_STYLE = ["true", "1"].includes(
29
+ (process.env.S3_FORCE_PATH_STYLE || "false").toLowerCase(),
30
+ );
31
+
32
+ const SUPABASE_BUCKET =
33
+ process.env.OTA_STORAGE_BUCKET ||
34
+ process.env.R2_BUCKET ||
35
+ process.env.SUPABASE_UPDATES_BUCKET ||
36
+ "expo-updates";
37
+ const SIGNED_URL_TTL = parseInt(
38
+ process.env.OTA_SIGNED_URL_TTL ||
39
+ process.env.SUPABASE_SIGNED_URL_TTL ||
40
+ "3600",
41
+ 10,
42
+ );
43
+
44
+ if (DATABASE_PROVIDER !== "pg" && DATABASE_PROVIDER !== "supabase") {
45
+ throw new Error(
46
+ `Unsupported DATABASE_PROVIDER value: ${DATABASE_PROVIDER}. Expected \"pg\" or \"supabase\".`,
47
+ );
48
+ }
49
+
50
+ const shouldUseSsl =
51
+ DATABASE_SSL === "true" || DATABASE_SSL === "1" || DATABASE_SSL === "require";
52
+
53
+ let pool = null;
54
+ let s3 = null;
55
+ let supabaseClient = null;
56
+
57
+ function getPool() {
58
+ if (pool) {
59
+ return pool;
60
+ }
61
+
62
+ if (!DATABASE_URL) {
63
+ throw new Error("Missing DATABASE_URL in environment.");
64
+ }
65
+
66
+ pool = new Pool({
67
+ connectionString: DATABASE_URL,
68
+ ssl: shouldUseSsl ? { rejectUnauthorized: false } : false,
69
+ });
70
+
71
+ return pool;
72
+ }
73
+
74
+ function getS3Client() {
75
+ if (s3) {
76
+ return s3;
77
+ }
78
+
79
+ if (!R2_ENDPOINT || !R2_ACCESS_KEY_ID || !R2_SECRET_ACCESS_KEY) {
80
+ throw new Error(
81
+ "Missing R2_ENDPOINT, R2_ACCESS_KEY_ID or R2_SECRET_ACCESS_KEY in environment.",
82
+ );
83
+ }
84
+
85
+ s3 = new S3Client({
86
+ region: R2_REGION,
87
+ endpoint: R2_ENDPOINT,
88
+ forcePathStyle: S3_FORCE_PATH_STYLE,
89
+ credentials: {
90
+ accessKeyId: R2_ACCESS_KEY_ID,
91
+ secretAccessKey: R2_SECRET_ACCESS_KEY,
92
+ },
93
+ });
94
+
95
+ return s3;
96
+ }
97
+
98
+ function getSupabaseClient() {
99
+ if (supabaseClient) {
100
+ return supabaseClient;
101
+ }
102
+
103
+ if (!SUPABASE_URL || !SUPABASE_KEY) {
104
+ throw new Error(
105
+ "Missing SUPABASE_PROJECT_URL/SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY/SUPABASE_PUBLISHED_KEY in environment.",
106
+ );
107
+ }
108
+
109
+ supabaseClient = createClient(SUPABASE_URL, SUPABASE_KEY, {
110
+ auth: {
111
+ persistSession: false,
112
+ autoRefreshToken: false,
113
+ },
114
+ });
115
+
116
+ return supabaseClient;
117
+ }
118
+
119
+ function toSqlColumns(columns) {
120
+ if (!columns || columns === "*") {
121
+ return "*";
122
+ }
123
+
124
+ return columns
125
+ .split(",")
126
+ .map((part) => part.trim())
127
+ .filter(Boolean)
128
+ .join(", ");
129
+ }
130
+
131
+ function isNullLike(value) {
132
+ return value === null || value === undefined;
133
+ }
134
+
135
+ async function readObjectBodyAsBuffer(body) {
136
+ if (!body) {
137
+ return Buffer.alloc(0);
138
+ }
139
+
140
+ if (typeof body.transformToByteArray === "function") {
141
+ const bytes = await body.transformToByteArray();
142
+ return Buffer.from(bytes);
143
+ }
144
+
145
+ if (typeof body.arrayBuffer === "function") {
146
+ const ab = await body.arrayBuffer();
147
+ return Buffer.from(ab);
148
+ }
149
+
150
+ if (typeof body[Symbol.asyncIterator] === "function") {
151
+ const chunks = [];
152
+ for await (const chunk of body) {
153
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
154
+ }
155
+ return Buffer.concat(chunks);
156
+ }
157
+
158
+ return Buffer.alloc(0);
159
+ }
160
+
161
+ class TableQuery {
162
+ constructor(tableName) {
163
+ this.tableName = tableName;
164
+ this.operation = "select";
165
+ this.selectedColumns = "*";
166
+ this.filters = [];
167
+ this.orderBy = null;
168
+ this.limitValue = null;
169
+ this.updatePayload = null;
170
+ this.upsertPayload = null;
171
+ this.upsertConflict = null;
172
+ this.singleMode = null;
173
+ }
174
+
175
+ select(columns) {
176
+ this.selectedColumns = columns || "*";
177
+ return this;
178
+ }
179
+
180
+ eq(column, value) {
181
+ this.filters.push({ type: "eq", column, value });
182
+ return this;
183
+ }
184
+
185
+ neq(column, value) {
186
+ this.filters.push({ type: "neq", column, value });
187
+ return this;
188
+ }
189
+
190
+ not(column, operator, value) {
191
+ this.filters.push({ type: "not", column, operator, value });
192
+ return this;
193
+ }
194
+
195
+ order(column, options = {}) {
196
+ this.orderBy = {
197
+ column,
198
+ ascending: options.ascending !== false,
199
+ nullsFirst: options.nullsFirst === true,
200
+ };
201
+ return this;
202
+ }
203
+
204
+ limit(value) {
205
+ this.limitValue = Number(value);
206
+ return this;
207
+ }
208
+
209
+ update(payload) {
210
+ this.operation = "update";
211
+ this.updatePayload = payload || {};
212
+ return this;
213
+ }
214
+
215
+ delete() {
216
+ this.operation = "delete";
217
+ return this;
218
+ }
219
+
220
+ upsert(payload, options = {}) {
221
+ this.operation = "upsert";
222
+ this.upsertPayload = payload || {};
223
+ this.upsertConflict = options.onConflict || null;
224
+ return this;
225
+ }
226
+
227
+ maybeSingle() {
228
+ this.singleMode = "maybeSingle";
229
+ return this.execute();
230
+ }
231
+
232
+ single() {
233
+ this.singleMode = "single";
234
+ return this.execute();
235
+ }
236
+
237
+ then(resolve, reject) {
238
+ return this.execute().then(resolve, reject);
239
+ }
240
+
241
+ buildWhereClause(startIndex = 1) {
242
+ const params = [];
243
+ const conditions = [];
244
+ let index = startIndex;
245
+
246
+ for (const filter of this.filters) {
247
+ if (filter.type === "eq") {
248
+ if (isNullLike(filter.value)) {
249
+ conditions.push(`${filter.column} IS NULL`);
250
+ } else {
251
+ conditions.push(`${filter.column} = $${index}`);
252
+ params.push(filter.value);
253
+ index += 1;
254
+ }
255
+ continue;
256
+ }
257
+
258
+ if (filter.type === "neq") {
259
+ if (isNullLike(filter.value)) {
260
+ conditions.push(`${filter.column} IS NOT NULL`);
261
+ } else {
262
+ conditions.push(`${filter.column} <> $${index}`);
263
+ params.push(filter.value);
264
+ index += 1;
265
+ }
266
+ continue;
267
+ }
268
+
269
+ if (filter.type === "not") {
270
+ if (filter.operator === "is") {
271
+ conditions.push(
272
+ isNullLike(filter.value)
273
+ ? `${filter.column} IS NOT NULL`
274
+ : `${filter.column} IS DISTINCT FROM $${index}`,
275
+ );
276
+ if (!isNullLike(filter.value)) {
277
+ params.push(filter.value);
278
+ index += 1;
279
+ }
280
+ continue;
281
+ }
282
+
283
+ throw new Error(`Unsupported filter operator: not ${filter.operator}`);
284
+ }
285
+ }
286
+
287
+ if (conditions.length === 0) {
288
+ return { text: "", params, nextIndex: index };
289
+ }
290
+
291
+ return {
292
+ text: ` WHERE ${conditions.join(" AND ")}`,
293
+ params,
294
+ nextIndex: index,
295
+ };
296
+ }
297
+
298
+ buildOrderClause() {
299
+ if (!this.orderBy) {
300
+ return "";
301
+ }
302
+
303
+ const direction = this.orderBy.ascending ? "ASC" : "DESC";
304
+ const nulls = this.orderBy.nullsFirst ? "NULLS FIRST" : "NULLS LAST";
305
+ return ` ORDER BY ${this.orderBy.column} ${direction} ${nulls}`;
306
+ }
307
+
308
+ buildLimitClause(index) {
309
+ if (!Number.isFinite(this.limitValue) || this.limitValue <= 0) {
310
+ return { text: "", params: [] };
311
+ }
312
+
313
+ return {
314
+ text: ` LIMIT $${index}`,
315
+ params: [this.limitValue],
316
+ };
317
+ }
318
+
319
+ async execute() {
320
+ try {
321
+ if (this.operation === "select") {
322
+ return await this.executeSelect();
323
+ }
324
+
325
+ if (this.operation === "update") {
326
+ return await this.executeUpdate();
327
+ }
328
+
329
+ if (this.operation === "delete") {
330
+ return await this.executeDelete();
331
+ }
332
+
333
+ if (this.operation === "upsert") {
334
+ return await this.executeUpsert();
335
+ }
336
+
337
+ throw new Error(`Unsupported operation: ${this.operation}`);
338
+ } catch (error) {
339
+ return {
340
+ data: null,
341
+ error: {
342
+ message: error instanceof Error ? error.message : String(error),
343
+ },
344
+ };
345
+ }
346
+ }
347
+
348
+ normalizeResultRows(rows) {
349
+ if (this.singleMode === "single") {
350
+ if (rows.length !== 1) {
351
+ throw new Error("Expected a single row.");
352
+ }
353
+ return rows[0];
354
+ }
355
+
356
+ if (this.singleMode === "maybeSingle") {
357
+ if (rows.length > 1) {
358
+ throw new Error("Expected zero or one row.");
359
+ }
360
+ return rows[0] || null;
361
+ }
362
+
363
+ return rows;
364
+ }
365
+
366
+ async executeSelect() {
367
+ const columnsSql = toSqlColumns(this.selectedColumns);
368
+ const whereClause = this.buildWhereClause(1);
369
+ const orderClause = this.buildOrderClause();
370
+ const limitClause = this.buildLimitClause(whereClause.nextIndex);
371
+
372
+ const sql = `SELECT ${columnsSql} FROM ${this.tableName}${whereClause.text}${orderClause}${limitClause.text}`;
373
+ const params = [...whereClause.params, ...limitClause.params];
374
+
375
+ const result = await getPool().query(sql, params);
376
+ return {
377
+ data: this.normalizeResultRows(result.rows),
378
+ error: null,
379
+ };
380
+ }
381
+
382
+ async executeUpdate() {
383
+ const entries = Object.entries(this.updatePayload || {});
384
+ if (entries.length === 0) {
385
+ throw new Error("Update payload is empty.");
386
+ }
387
+
388
+ const setParts = [];
389
+ const params = [];
390
+ let index = 1;
391
+
392
+ for (const [key, value] of entries) {
393
+ setParts.push(`${key} = $${index}`);
394
+ params.push(value);
395
+ index += 1;
396
+ }
397
+
398
+ const whereClause = this.buildWhereClause(index);
399
+ const returning = this.selectedColumns
400
+ ? ` RETURNING ${toSqlColumns(this.selectedColumns)}`
401
+ : "";
402
+
403
+ const sql = `UPDATE ${this.tableName} SET ${setParts.join(", ")}${whereClause.text}${returning}`;
404
+ const result = await getPool().query(sql, [
405
+ ...params,
406
+ ...whereClause.params,
407
+ ]);
408
+
409
+ return {
410
+ data: this.selectedColumns ? this.normalizeResultRows(result.rows) : null,
411
+ error: null,
412
+ };
413
+ }
414
+
415
+ async executeDelete() {
416
+ const whereClause = this.buildWhereClause(1);
417
+ const returning = this.selectedColumns
418
+ ? ` RETURNING ${toSqlColumns(this.selectedColumns)}`
419
+ : "";
420
+ const sql = `DELETE FROM ${this.tableName}${whereClause.text}${returning}`;
421
+ const result = await getPool().query(sql, whereClause.params);
422
+
423
+ return {
424
+ data: this.selectedColumns ? this.normalizeResultRows(result.rows) : null,
425
+ error: null,
426
+ };
427
+ }
428
+
429
+ async executeUpsert() {
430
+ const payload = this.upsertPayload || {};
431
+ const entries = Object.entries(payload);
432
+ if (entries.length === 0) {
433
+ throw new Error("Upsert payload is empty.");
434
+ }
435
+
436
+ const columns = entries.map(([key]) => key);
437
+ const values = entries.map(([, value]) => value);
438
+ const placeholders = values.map((_, idx) => `$${idx + 1}`);
439
+
440
+ const conflictColumns = (this.upsertConflict || "")
441
+ .split(",")
442
+ .map((part) => part.trim())
443
+ .filter(Boolean);
444
+
445
+ if (conflictColumns.length === 0) {
446
+ throw new Error("upsert requires onConflict columns.");
447
+ }
448
+
449
+ const updateColumns = columns.filter(
450
+ (column) => !conflictColumns.includes(column),
451
+ );
452
+ const updateSetSql =
453
+ updateColumns.length > 0
454
+ ? updateColumns
455
+ .map((column) => `${column} = EXCLUDED.${column}`)
456
+ .join(", ")
457
+ : `${conflictColumns[0]} = EXCLUDED.${conflictColumns[0]}`;
458
+
459
+ const returning = this.selectedColumns
460
+ ? ` RETURNING ${toSqlColumns(this.selectedColumns)}`
461
+ : " RETURNING *";
462
+
463
+ const sql = `INSERT INTO ${this.tableName} (${columns.join(", ")}) VALUES (${placeholders.join(", ")}) ON CONFLICT (${conflictColumns.join(", ")}) DO UPDATE SET ${updateSetSql}${returning}`;
464
+ const result = await getPool().query(sql, values);
465
+
466
+ return {
467
+ data: this.normalizeResultRows(result.rows),
468
+ error: null,
469
+ };
470
+ }
471
+ }
472
+
473
+ class BucketStorageQuery {
474
+ constructor(bucket) {
475
+ this.bucket = bucket;
476
+ }
477
+
478
+ async list(prefix = "", options = {}) {
479
+ try {
480
+ const client = getS3Client();
481
+
482
+ const normalizedPrefix = prefix
483
+ ? prefix.endsWith("/")
484
+ ? prefix
485
+ : `${prefix}/`
486
+ : "";
487
+ const maxPageSize = 1000;
488
+ const children = [];
489
+
490
+ let continuationToken = undefined;
491
+ do {
492
+ const response = await client.send(
493
+ new ListObjectsV2Command({
494
+ Bucket: this.bucket,
495
+ Prefix: normalizedPrefix,
496
+ Delimiter: "/",
497
+ ContinuationToken: continuationToken,
498
+ MaxKeys: maxPageSize,
499
+ }),
500
+ );
501
+
502
+ for (const folder of response.CommonPrefixes || []) {
503
+ const folderPrefix = folder.Prefix || "";
504
+ const folderName = folderPrefix
505
+ .replace(normalizedPrefix, "")
506
+ .replace(/\/$/, "");
507
+
508
+ if (folderName) {
509
+ children.push({ name: folderName, id: null });
510
+ }
511
+ }
512
+
513
+ for (const item of response.Contents || []) {
514
+ if (!item.Key) {
515
+ continue;
516
+ }
517
+
518
+ const relative = item.Key.replace(normalizedPrefix, "");
519
+ if (!relative || relative.includes("/")) {
520
+ continue;
521
+ }
522
+
523
+ children.push({ name: relative, id: item.ETag || item.Key });
524
+ }
525
+
526
+ continuationToken = response.IsTruncated
527
+ ? response.NextContinuationToken
528
+ : undefined;
529
+ } while (continuationToken);
530
+
531
+ const order = options.sortBy?.order === "desc" ? "desc" : "asc";
532
+ children.sort((a, b) => {
533
+ if (a.name < b.name) {
534
+ return order === "asc" ? -1 : 1;
535
+ }
536
+ if (a.name > b.name) {
537
+ return order === "asc" ? 1 : -1;
538
+ }
539
+ return 0;
540
+ });
541
+
542
+ const offset = Number.isFinite(options.offset) ? options.offset : 0;
543
+ const limit = Number.isFinite(options.limit)
544
+ ? options.limit
545
+ : children.length;
546
+
547
+ return {
548
+ data: children.slice(offset, offset + limit),
549
+ error: null,
550
+ };
551
+ } catch (error) {
552
+ return {
553
+ data: null,
554
+ error: {
555
+ message: error instanceof Error ? error.message : String(error),
556
+ },
557
+ };
558
+ }
559
+ }
560
+
561
+ async download(objectPath) {
562
+ try {
563
+ const client = getS3Client();
564
+
565
+ const result = await client.send(
566
+ new GetObjectCommand({
567
+ Bucket: this.bucket,
568
+ Key: objectPath,
569
+ }),
570
+ );
571
+
572
+ const buffer = await readObjectBodyAsBuffer(result.Body);
573
+ return {
574
+ data: new Blob([buffer]),
575
+ error: null,
576
+ };
577
+ } catch (error) {
578
+ return {
579
+ data: null,
580
+ error: {
581
+ message: error instanceof Error ? error.message : String(error),
582
+ },
583
+ };
584
+ }
585
+ }
586
+
587
+ async remove(paths) {
588
+ try {
589
+ const client = getS3Client();
590
+
591
+ if (!Array.isArray(paths) || paths.length === 0) {
592
+ return { data: [], error: null };
593
+ }
594
+
595
+ await client.send(
596
+ new DeleteObjectsCommand({
597
+ Bucket: this.bucket,
598
+ Delete: {
599
+ Objects: paths.map((key) => ({ Key: key })),
600
+ },
601
+ }),
602
+ );
603
+
604
+ return { data: paths, error: null };
605
+ } catch (error) {
606
+ return {
607
+ data: null,
608
+ error: {
609
+ message: error instanceof Error ? error.message : String(error),
610
+ },
611
+ };
612
+ }
613
+ }
614
+
615
+ async createSignedUrl(objectPath, ttlSeconds) {
616
+ try {
617
+ const client = getS3Client();
618
+
619
+ const signedUrl = await getSignedUrl(
620
+ client,
621
+ new GetObjectCommand({
622
+ Bucket: this.bucket,
623
+ Key: objectPath,
624
+ }),
625
+ { expiresIn: ttlSeconds },
626
+ );
627
+
628
+ return {
629
+ data: { signedUrl },
630
+ error: null,
631
+ };
632
+ } catch (error) {
633
+ return {
634
+ data: null,
635
+ error: {
636
+ message: error instanceof Error ? error.message : String(error),
637
+ },
638
+ };
639
+ }
640
+ }
641
+ }
642
+
643
+ class SupabaseTableQuery {
644
+ constructor(builder) {
645
+ this.builder = builder;
646
+ }
647
+
648
+ select(columns) {
649
+ this.builder = this.builder.select(columns || "*");
650
+ return this;
651
+ }
652
+
653
+ eq(column, value) {
654
+ this.builder = this.builder.eq(column, value);
655
+ return this;
656
+ }
657
+
658
+ neq(column, value) {
659
+ this.builder = this.builder.neq(column, value);
660
+ return this;
661
+ }
662
+
663
+ not(column, operator, value) {
664
+ this.builder = this.builder.not(column, operator, value);
665
+ return this;
666
+ }
667
+
668
+ order(column, options = {}) {
669
+ this.builder = this.builder.order(column, options);
670
+ return this;
671
+ }
672
+
673
+ limit(value) {
674
+ this.builder = this.builder.limit(value);
675
+ return this;
676
+ }
677
+
678
+ update(payload) {
679
+ this.builder = this.builder.update(payload || {});
680
+ return this;
681
+ }
682
+
683
+ delete() {
684
+ this.builder = this.builder.delete();
685
+ return this;
686
+ }
687
+
688
+ upsert(payload, options = {}) {
689
+ this.builder = this.builder.upsert(payload || {}, options);
690
+ return this;
691
+ }
692
+
693
+ maybeSingle() {
694
+ return this.builder.maybeSingle();
695
+ }
696
+
697
+ single() {
698
+ return this.builder.single();
699
+ }
700
+
701
+ execute() {
702
+ return this.builder;
703
+ }
704
+
705
+ then(resolve, reject) {
706
+ return this.builder.then(resolve, reject);
707
+ }
708
+ }
709
+
710
+ class SupabaseStorageQuery {
711
+ constructor(client, bucket) {
712
+ this.client = client;
713
+ this.bucket = bucket;
714
+ }
715
+
716
+ list(prefix = "", options = {}) {
717
+ return this.client.storage.from(this.bucket).list(prefix, options);
718
+ }
719
+
720
+ download(objectPath) {
721
+ return this.client.storage.from(this.bucket).download(objectPath);
722
+ }
723
+
724
+ remove(paths) {
725
+ return this.client.storage.from(this.bucket).remove(paths);
726
+ }
727
+
728
+ createSignedUrl(objectPath, ttlSeconds) {
729
+ return this.client.storage
730
+ .from(this.bucket)
731
+ .createSignedUrl(objectPath, ttlSeconds);
732
+ }
733
+ }
734
+
735
+ const supabase =
736
+ DATABASE_PROVIDER === "supabase"
737
+ ? {
738
+ from(tableName) {
739
+ return new SupabaseTableQuery(
740
+ getSupabaseClient().from(tableName),
741
+ );
742
+ },
743
+ storage: {
744
+ from(bucket) {
745
+ return new SupabaseStorageQuery(
746
+ getSupabaseClient(),
747
+ bucket || SUPABASE_BUCKET,
748
+ );
749
+ },
750
+ },
751
+ }
752
+ : {
753
+ from(tableName) {
754
+ return new TableQuery(tableName);
755
+ },
756
+ storage: {
757
+ from(bucket) {
758
+ return new BucketStorageQuery(bucket || SUPABASE_BUCKET);
759
+ },
760
+ },
761
+ };
762
+
763
+ export { supabase, SUPABASE_BUCKET, SIGNED_URL_TTL, DATABASE_PROVIDER };