@palbase/modules-db 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.
package/dist/index.cjs ADDED
@@ -0,0 +1,665 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ DatabaseClient: () => DatabaseClient,
24
+ MaybeSingleQueryBuilder: () => MaybeSingleQueryBuilder,
25
+ QueryBuilder: () => QueryBuilder,
26
+ SingleQueryBuilder: () => SingleQueryBuilder,
27
+ TransactionClient: () => TransactionClient,
28
+ executeTransaction: () => executeTransaction
29
+ });
30
+ module.exports = __toCommonJS(index_exports);
31
+
32
+ // src/admin-validation.ts
33
+ var IDENTIFIER_RE = /^[a-zA-Z_][a-zA-Z0-9_.]*$/;
34
+ function validateIdentifier(value, label) {
35
+ if (!IDENTIFIER_RE.test(value)) {
36
+ throw new Error(
37
+ `Invalid ${label}: "${value}". Identifiers must match ${IDENTIFIER_RE.source}`
38
+ );
39
+ }
40
+ }
41
+
42
+ // src/admin-columns.ts
43
+ var ColumnsClient = class {
44
+ httpClient;
45
+ constructor(httpClient) {
46
+ this.httpClient = httpClient;
47
+ }
48
+ /**
49
+ * Create a new column on the given table. Sends `POST /v1/meta/columns`.
50
+ *
51
+ * The column name is validated against the standard SQL identifier regex.
52
+ * The `type` field is forwarded as-is to postgres-meta — callers SHOULD
53
+ * restrict types to a known allowlist before calling this.
54
+ */
55
+ async create(def) {
56
+ validateIdentifier(def.name, "column name");
57
+ const response = await this.httpClient.request("POST", "/v1/meta/columns", {
58
+ body: def
59
+ });
60
+ if (response.error) {
61
+ throw response.error;
62
+ }
63
+ return response.data;
64
+ }
65
+ /**
66
+ * Drop a column. Sends `DELETE /v1/meta/columns/:tableId.:ordinalPosition`.
67
+ *
68
+ * postgres-meta identifies columns by `{tableId}.{ordinalPosition}` (the
69
+ * column's 1-based attnum within its table). Use `TablesClient.get(id)` to
70
+ * find a column id from a column name if needed.
71
+ */
72
+ async drop(columnId, options) {
73
+ if (!/^\d+\.\d+$/.test(columnId)) {
74
+ throw new Error(
75
+ `Invalid column id: "${columnId}". Expected format "{tableId}.{ordinalPosition}"`
76
+ );
77
+ }
78
+ const params = new URLSearchParams();
79
+ if (options?.cascade) {
80
+ params.set("cascade", "true");
81
+ }
82
+ const queryString = params.toString();
83
+ const path = queryString ? `/v1/meta/columns/${columnId}?${queryString}` : `/v1/meta/columns/${columnId}`;
84
+ const response = await this.httpClient.request("DELETE", path);
85
+ if (response.error) {
86
+ throw response.error;
87
+ }
88
+ return response.data;
89
+ }
90
+ };
91
+
92
+ // src/admin-schemas.ts
93
+ var SchemasClient = class {
94
+ httpClient;
95
+ constructor(httpClient) {
96
+ this.httpClient = httpClient;
97
+ }
98
+ async list() {
99
+ const response = await this.httpClient.request("GET", "/v1/meta/schemas");
100
+ if (response.error) {
101
+ throw response.error;
102
+ }
103
+ return response.data ?? [];
104
+ }
105
+ async create(name) {
106
+ validateIdentifier(name, "schema name");
107
+ const response = await this.httpClient.request("POST", "/v1/meta/schemas", {
108
+ body: { name }
109
+ });
110
+ if (response.error) {
111
+ throw response.error;
112
+ }
113
+ return response.data;
114
+ }
115
+ async drop(name, options) {
116
+ validateIdentifier(name, "schema name");
117
+ const schemas = await this.list();
118
+ const schema = schemas.find((s) => s.name === name);
119
+ if (!schema) {
120
+ throw new Error(`Schema "${name}" not found`);
121
+ }
122
+ const params = new URLSearchParams();
123
+ if (options?.cascade) {
124
+ params.set("cascade", "true");
125
+ }
126
+ const queryString = params.toString();
127
+ const path = queryString ? `/v1/meta/schemas/${schema.id}?${queryString}` : `/v1/meta/schemas/${schema.id}`;
128
+ const response = await this.httpClient.request("DELETE", path);
129
+ if (response.error) {
130
+ throw response.error;
131
+ }
132
+ }
133
+ };
134
+
135
+ // src/admin-tables.ts
136
+ var TablesClient = class {
137
+ httpClient;
138
+ constructor(httpClient) {
139
+ this.httpClient = httpClient;
140
+ }
141
+ async list(options) {
142
+ const params = new URLSearchParams();
143
+ if (options?.schema) {
144
+ validateIdentifier(options.schema, "schema name");
145
+ params.set("included_schemas", options.schema);
146
+ }
147
+ const queryString = params.toString();
148
+ const path = queryString ? `/v1/meta/tables?${queryString}` : "/v1/meta/tables";
149
+ const response = await this.httpClient.request("GET", path);
150
+ if (response.error) {
151
+ throw response.error;
152
+ }
153
+ return response.data ?? [];
154
+ }
155
+ async get(id) {
156
+ const response = await this.httpClient.request("GET", `/v1/meta/tables/${id}`);
157
+ if (response.error) {
158
+ throw response.error;
159
+ }
160
+ return response.data;
161
+ }
162
+ async create(def) {
163
+ validateIdentifier(def.name, "table name");
164
+ if (def.schema) {
165
+ validateIdentifier(def.schema, "schema name");
166
+ }
167
+ const response = await this.httpClient.request("POST", "/v1/meta/tables", {
168
+ body: def
169
+ });
170
+ if (response.error) {
171
+ throw response.error;
172
+ }
173
+ return response.data;
174
+ }
175
+ /**
176
+ * Apply table-level updates (rename, schema move, RLS toggle, comment, etc).
177
+ * Sends `PATCH /v1/meta/tables/:id`.
178
+ *
179
+ * Note: this does NOT add or drop columns. For column changes, use
180
+ * `ColumnsClient.create()` / `ColumnsClient.drop()`.
181
+ */
182
+ async update(id, patch) {
183
+ if (patch.name !== void 0) {
184
+ validateIdentifier(patch.name, "table name");
185
+ }
186
+ if (patch.schema !== void 0) {
187
+ validateIdentifier(patch.schema, "schema name");
188
+ }
189
+ if (patch.primary_keys) {
190
+ for (const pk of patch.primary_keys) {
191
+ validateIdentifier(pk.name, "primary key column name");
192
+ }
193
+ }
194
+ const response = await this.httpClient.request("PATCH", `/v1/meta/tables/${id}`, {
195
+ body: patch
196
+ });
197
+ if (response.error) {
198
+ throw response.error;
199
+ }
200
+ return response.data;
201
+ }
202
+ async drop(id, options) {
203
+ const params = new URLSearchParams();
204
+ if (options?.cascade) {
205
+ params.set("cascade", "true");
206
+ }
207
+ const queryString = params.toString();
208
+ const path = queryString ? `/v1/meta/tables/${id}?${queryString}` : `/v1/meta/tables/${id}`;
209
+ const response = await this.httpClient.request("DELETE", path);
210
+ if (response.error) {
211
+ throw response.error;
212
+ }
213
+ }
214
+ };
215
+
216
+ // src/admin-client.ts
217
+ var AdminClient = class {
218
+ schemas;
219
+ tables;
220
+ columns;
221
+ httpClient;
222
+ constructor(httpClient) {
223
+ this.httpClient = httpClient;
224
+ this.schemas = new SchemasClient(httpClient);
225
+ this.tables = new TablesClient(httpClient);
226
+ this.columns = new ColumnsClient(httpClient);
227
+ }
228
+ /**
229
+ * Execute a raw SQL query with full privileges (service role).
230
+ *
231
+ * Always use parameterized queries to prevent SQL injection.
232
+ * Never interpolate user input directly into the SQL string.
233
+ *
234
+ * @example
235
+ * ```ts
236
+ * // GOOD — parameterized
237
+ * await admin.query('SELECT * FROM users WHERE id = $1', [userId]);
238
+ *
239
+ * // BAD — string interpolation (SQL injection risk)
240
+ * await admin.query(`SELECT * FROM users WHERE id = '${userId}'`);
241
+ * ```
242
+ */
243
+ async query(sql, params) {
244
+ const response = await this.httpClient.request("POST", "/v1/meta/query", {
245
+ body: { query: sql, params }
246
+ });
247
+ if (response.error) {
248
+ throw response.error;
249
+ }
250
+ return response.data ?? [];
251
+ }
252
+ };
253
+
254
+ // src/query-builder.ts
255
+ var TABLE_NAME_RE = /^[a-zA-Z_][a-zA-Z0-9_.]*$/;
256
+ var COLUMN_NAME_RE = /^[a-zA-Z_][a-zA-Z0-9_.:\->#]*$/;
257
+ function validateTableName(table) {
258
+ if (!TABLE_NAME_RE.test(table)) {
259
+ throw new Error(`Invalid table name: "${table}". Table names must match ${TABLE_NAME_RE.source}`);
260
+ }
261
+ }
262
+ function validateColumnName(column) {
263
+ if (!COLUMN_NAME_RE.test(column)) {
264
+ throw new Error(`Invalid column name: "${column}". Column names must match ${COLUMN_NAME_RE.source}`);
265
+ }
266
+ }
267
+ function encodeFilterValue(value) {
268
+ return String(value).replace(/[&#]/g, (c) => encodeURIComponent(c));
269
+ }
270
+ var SingleQueryBuilder = class {
271
+ constructor(builder) {
272
+ this.builder = builder;
273
+ }
274
+ builder;
275
+ then(onfulfilled, onrejected) {
276
+ return this.builder["execute"]().then(
277
+ (res) => onfulfilled ? onfulfilled(res) : res,
278
+ onrejected ?? void 0
279
+ );
280
+ }
281
+ };
282
+ var MaybeSingleQueryBuilder = class {
283
+ constructor(builder) {
284
+ this.builder = builder;
285
+ }
286
+ builder;
287
+ then(onfulfilled, onrejected) {
288
+ return this.builder["execute"]().then(
289
+ (res) => onfulfilled ? onfulfilled(res) : res,
290
+ onrejected ?? void 0
291
+ );
292
+ }
293
+ };
294
+ var QueryBuilder = class {
295
+ httpClient;
296
+ basePath;
297
+ signal;
298
+ state;
299
+ constructor(httpClient, table, options) {
300
+ validateTableName(table);
301
+ this.httpClient = httpClient;
302
+ this.basePath = options?.basePath ?? `/v1/db/${table}`;
303
+ this.signal = options?.signal;
304
+ this.state = {
305
+ method: "GET",
306
+ headers: {},
307
+ filters: [],
308
+ params: {},
309
+ isSingle: false,
310
+ isMaybeSingle: false
311
+ };
312
+ }
313
+ // --- Operation methods ---
314
+ select(columns) {
315
+ this.state = {
316
+ ...this.state,
317
+ // Only set GET if no mutation method (POST/PATCH/DELETE) is already set
318
+ // insert().select() should stay POST with Prefer: return=representation
319
+ method: this.state.body !== void 0 ? this.state.method : "GET",
320
+ params: { ...this.state.params, select: columns ?? "*" }
321
+ };
322
+ return this;
323
+ }
324
+ insert(data) {
325
+ this.state = {
326
+ ...this.state,
327
+ method: "POST",
328
+ body: data,
329
+ headers: {
330
+ ...this.state.headers,
331
+ Prefer: "return=representation"
332
+ }
333
+ };
334
+ return this;
335
+ }
336
+ update(data) {
337
+ this.state = {
338
+ ...this.state,
339
+ method: "PATCH",
340
+ body: data,
341
+ headers: {
342
+ ...this.state.headers,
343
+ Prefer: "return=representation"
344
+ }
345
+ };
346
+ return this;
347
+ }
348
+ delete() {
349
+ this.state = {
350
+ ...this.state,
351
+ method: "DELETE"
352
+ };
353
+ return this;
354
+ }
355
+ upsert(data) {
356
+ this.state = {
357
+ ...this.state,
358
+ method: "POST",
359
+ body: data,
360
+ headers: {
361
+ ...this.state.headers,
362
+ Prefer: "resolution=merge-duplicates,return=representation"
363
+ }
364
+ };
365
+ return this;
366
+ }
367
+ // --- Filter methods ---
368
+ eq(column, value) {
369
+ validateColumnName(column);
370
+ this.state = {
371
+ ...this.state,
372
+ filters: [...this.state.filters, `${column}=eq.${encodeFilterValue(value)}`]
373
+ };
374
+ return this;
375
+ }
376
+ neq(column, value) {
377
+ validateColumnName(column);
378
+ this.state = {
379
+ ...this.state,
380
+ filters: [...this.state.filters, `${column}=neq.${encodeFilterValue(value)}`]
381
+ };
382
+ return this;
383
+ }
384
+ gt(column, value) {
385
+ validateColumnName(column);
386
+ this.state = {
387
+ ...this.state,
388
+ filters: [...this.state.filters, `${column}=gt.${encodeFilterValue(value)}`]
389
+ };
390
+ return this;
391
+ }
392
+ gte(column, value) {
393
+ validateColumnName(column);
394
+ this.state = {
395
+ ...this.state,
396
+ filters: [...this.state.filters, `${column}=gte.${encodeFilterValue(value)}`]
397
+ };
398
+ return this;
399
+ }
400
+ lt(column, value) {
401
+ validateColumnName(column);
402
+ this.state = {
403
+ ...this.state,
404
+ filters: [...this.state.filters, `${column}=lt.${encodeFilterValue(value)}`]
405
+ };
406
+ return this;
407
+ }
408
+ lte(column, value) {
409
+ validateColumnName(column);
410
+ this.state = {
411
+ ...this.state,
412
+ filters: [...this.state.filters, `${column}=lte.${encodeFilterValue(value)}`]
413
+ };
414
+ return this;
415
+ }
416
+ like(column, pattern) {
417
+ validateColumnName(column);
418
+ this.state = {
419
+ ...this.state,
420
+ filters: [...this.state.filters, `${column}=like.${encodeFilterValue(pattern)}`]
421
+ };
422
+ return this;
423
+ }
424
+ ilike(column, pattern) {
425
+ validateColumnName(column);
426
+ this.state = {
427
+ ...this.state,
428
+ filters: [...this.state.filters, `${column}=ilike.${encodeFilterValue(pattern)}`]
429
+ };
430
+ return this;
431
+ }
432
+ in(column, values) {
433
+ validateColumnName(column);
434
+ const encoded = values.map((v) => encodeFilterValue(v).replace(/[),]/g, (c) => encodeURIComponent(c)));
435
+ this.state = {
436
+ ...this.state,
437
+ filters: [...this.state.filters, `${column}=in.(${encoded.join(",")})`]
438
+ };
439
+ return this;
440
+ }
441
+ is(column, value) {
442
+ validateColumnName(column);
443
+ this.state = {
444
+ ...this.state,
445
+ filters: [...this.state.filters, `${column}=is.${encodeFilterValue(value)}`]
446
+ };
447
+ return this;
448
+ }
449
+ // --- Modifier methods ---
450
+ order(column, options) {
451
+ validateColumnName(column);
452
+ const direction = options?.ascending === false ? "desc" : "asc";
453
+ this.state = {
454
+ ...this.state,
455
+ params: { ...this.state.params, order: `${column}.${direction}` }
456
+ };
457
+ return this;
458
+ }
459
+ limit(count) {
460
+ this.state = {
461
+ ...this.state,
462
+ params: { ...this.state.params, limit: String(count) }
463
+ };
464
+ return this;
465
+ }
466
+ range(from, to) {
467
+ this.state = {
468
+ ...this.state,
469
+ headers: {
470
+ ...this.state.headers,
471
+ Range: `${from}-${to}`
472
+ }
473
+ };
474
+ return this;
475
+ }
476
+ single() {
477
+ this.state = {
478
+ ...this.state,
479
+ isSingle: true,
480
+ headers: {
481
+ ...this.state.headers,
482
+ Accept: "application/vnd.pgrst.object+json"
483
+ }
484
+ };
485
+ return new SingleQueryBuilder(this);
486
+ }
487
+ maybeSingle() {
488
+ this.state = {
489
+ ...this.state,
490
+ isMaybeSingle: true,
491
+ headers: {
492
+ ...this.state.headers,
493
+ Accept: "application/vnd.pgrst.object+json"
494
+ }
495
+ };
496
+ return new MaybeSingleQueryBuilder(this);
497
+ }
498
+ // --- Execution ---
499
+ then(onfulfilled, onrejected) {
500
+ return this.execute().then(onfulfilled, onrejected);
501
+ }
502
+ buildPath() {
503
+ const parts = [];
504
+ for (const [key, value] of Object.entries(this.state.params)) {
505
+ parts.push(`${key}=${value}`);
506
+ }
507
+ for (const filter of this.state.filters) {
508
+ parts.push(filter);
509
+ }
510
+ return parts.length > 0 ? `${this.basePath}?${parts.join("&")}` : this.basePath;
511
+ }
512
+ async execute() {
513
+ const path = this.buildPath();
514
+ const { method, body, headers } = this.state;
515
+ const response = await this.httpClient.request(method, path, {
516
+ body,
517
+ headers: Object.keys(headers).length > 0 ? headers : void 0,
518
+ signal: this.signal
519
+ });
520
+ if (this.state.isMaybeSingle && response.error && response.status === 406) {
521
+ return { data: null, error: null, status: 200 };
522
+ }
523
+ return response;
524
+ }
525
+ };
526
+
527
+ // src/transaction.ts
528
+ var import_core = require("@palbase/core");
529
+ var DEFAULT_TIMEOUT_MS = 3e4;
530
+ var TX_ID_RE = /^[a-zA-Z0-9_\-]+$/;
531
+ var TransactionClient = class {
532
+ httpClient;
533
+ txId;
534
+ signal;
535
+ constructor(httpClient, txId, signal) {
536
+ this.httpClient = httpClient;
537
+ this.txId = txId;
538
+ this.signal = signal;
539
+ }
540
+ from(table) {
541
+ return new QueryBuilder(this.httpClient, table, {
542
+ basePath: `/v1/db/transaction/${this.txId}/query/${table}`,
543
+ signal: this.signal
544
+ });
545
+ }
546
+ };
547
+ async function executeTransaction(httpClient, fn, options) {
548
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
549
+ const controller = new AbortController();
550
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
551
+ let txId;
552
+ try {
553
+ const beginResponse = await httpClient.request(
554
+ "POST",
555
+ "/v1/db/transaction/begin",
556
+ { signal: controller.signal }
557
+ );
558
+ if (beginResponse.error || !beginResponse.data) {
559
+ clearTimeout(timer);
560
+ return {
561
+ data: null,
562
+ error: beginResponse.error ?? new import_core.PalbaseError(
563
+ "transaction_error",
564
+ "Failed to begin transaction",
565
+ beginResponse.status
566
+ ),
567
+ status: beginResponse.status
568
+ };
569
+ }
570
+ txId = beginResponse.data.txId;
571
+ if (!TX_ID_RE.test(txId)) {
572
+ clearTimeout(timer);
573
+ return {
574
+ data: null,
575
+ error: new import_core.PalbaseError(
576
+ "transaction_error",
577
+ `Invalid transaction ID format: "${txId}"`,
578
+ 0
579
+ ),
580
+ status: 0
581
+ };
582
+ }
583
+ const tx = new TransactionClient(httpClient, txId, controller.signal);
584
+ const result = await fn(tx);
585
+ const commitResponse = await httpClient.request(
586
+ "POST",
587
+ `/v1/db/transaction/${txId}/commit`,
588
+ { signal: controller.signal }
589
+ );
590
+ clearTimeout(timer);
591
+ if (commitResponse.error) {
592
+ return {
593
+ data: null,
594
+ error: commitResponse.error,
595
+ status: commitResponse.status
596
+ };
597
+ }
598
+ return { data: result, error: null, status: 200 };
599
+ } catch (error) {
600
+ clearTimeout(timer);
601
+ if (txId) {
602
+ try {
603
+ await httpClient.request(
604
+ "POST",
605
+ `/v1/db/transaction/${txId}/rollback`,
606
+ { signal: void 0 }
607
+ );
608
+ } catch {
609
+ }
610
+ }
611
+ if (error instanceof import_core.PalbaseError) {
612
+ return { data: null, error, status: error.status };
613
+ }
614
+ const isAbort = error instanceof DOMException && error.name === "AbortError";
615
+ const code = isAbort ? "transaction_timeout" : "transaction_error";
616
+ const message = isAbort ? `Transaction timed out after ${timeoutMs}ms` : error instanceof Error ? error.message : "Transaction failed";
617
+ const status = isAbort ? 408 : 0;
618
+ return {
619
+ data: null,
620
+ error: new import_core.PalbaseError(code, message, status),
621
+ status
622
+ };
623
+ }
624
+ }
625
+
626
+ // src/database-client.ts
627
+ var FN_NAME_RE = /^[a-zA-Z_][a-zA-Z0-9_.]*$/;
628
+ var DatabaseClient = class {
629
+ httpClient;
630
+ pathPrefix;
631
+ admin;
632
+ constructor(httpClient, options) {
633
+ this.httpClient = httpClient;
634
+ this.pathPrefix = options?.pathPrefix ?? "/v1/db";
635
+ if (options?.enableAdmin) {
636
+ this.admin = new AdminClient(httpClient);
637
+ }
638
+ }
639
+ from(table) {
640
+ return new QueryBuilder(this.httpClient, table, {
641
+ basePath: `${this.pathPrefix}/${table}`
642
+ });
643
+ }
644
+ async rpc(fnName, params) {
645
+ if (!FN_NAME_RE.test(fnName)) {
646
+ throw new Error(`Invalid function name: "${fnName}". Function names must match ${FN_NAME_RE.source}`);
647
+ }
648
+ return this.httpClient.request("POST", `${this.pathPrefix}/rpc/${fnName}`, {
649
+ body: params
650
+ });
651
+ }
652
+ async transaction(fn, options) {
653
+ return executeTransaction(this.httpClient, fn, options);
654
+ }
655
+ };
656
+ // Annotate the CommonJS export names for ESM import in node:
657
+ 0 && (module.exports = {
658
+ DatabaseClient,
659
+ MaybeSingleQueryBuilder,
660
+ QueryBuilder,
661
+ SingleQueryBuilder,
662
+ TransactionClient,
663
+ executeTransaction
664
+ });
665
+ //# sourceMappingURL=index.cjs.map