@palbase/backend 10.3.0 → 12.0.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/db/index.cjs CHANGED
@@ -23,14 +23,19 @@ __export(db_exports, {
23
23
  EXTENSION_DEPENDENCIES: () => EXTENSION_DEPENDENCIES,
24
24
  PALBASE_EXTENSIONS: () => PALBASE_EXTENSIONS,
25
25
  PolicyBuilder: () => PolicyBuilder,
26
+ TxPlanError: () => TxPlanError,
27
+ TxRefError: () => TxRefError,
26
28
  bigint: () => bigint,
27
29
  boolean: () => boolean,
30
+ dec: () => dec,
28
31
  defineSchema: () => defineSchema,
29
32
  enumType: () => enumType,
33
+ inc: () => inc,
30
34
  integer: () => integer,
31
35
  isPalbaseExtension: () => isPalbaseExtension,
32
36
  jsonb: () => jsonb,
33
37
  makeTypedDB: () => makeTypedDB,
38
+ now: () => now,
34
39
  policy: () => policy,
35
40
  raw: () => raw,
36
41
  text: () => text,
@@ -300,6 +305,414 @@ function raw(name, up, opts) {
300
305
  return { name, up, ...opts?.down != null ? { down: opts.down } : {} };
301
306
  }
302
307
 
308
+ // src/db/tx-plan.ts
309
+ var TxRefError = class extends Error {
310
+ constructor(message) {
311
+ super(message);
312
+ this.name = "TxRefError";
313
+ }
314
+ };
315
+ var TxPlanError = class extends Error {
316
+ constructor(message) {
317
+ super(message);
318
+ this.name = "TxPlanError";
319
+ }
320
+ };
321
+ var EXPR = /* @__PURE__ */ Symbol.for("palbase.tx.expr");
322
+ var REF = /* @__PURE__ */ Symbol.for("palbase.tx.ref");
323
+ var ROW = /* @__PURE__ */ Symbol.for("palbase.tx.row");
324
+ var ROWS = /* @__PURE__ */ Symbol.for("palbase.tx.rows");
325
+ var TRAPPED_PROPS = [
326
+ "then",
327
+ "valueOf",
328
+ "toString",
329
+ "toJSON",
330
+ Symbol.toPrimitive
331
+ ];
332
+ function trap(prop, what, hint) {
333
+ const name = typeof prop === "symbol" ? prop.description ?? String(prop) : prop;
334
+ throw new TxRefError(
335
+ `${what} was used as a value (via \`${name}\`). Nothing in a transaction callback has run yet, so there is no value to read. ${hint}`
336
+ );
337
+ }
338
+ function now() {
339
+ return makeExpr({ fn: "now" });
340
+ }
341
+ function inc(by) {
342
+ assertFiniteNumber(by, "inc");
343
+ return makeExpr({ fn: "inc", by });
344
+ }
345
+ function dec(by) {
346
+ assertFiniteNumber(by, "dec");
347
+ return makeExpr({ fn: "dec", by });
348
+ }
349
+ function assertFiniteNumber(by, fn) {
350
+ if (typeof by !== "number" || !Number.isFinite(by)) {
351
+ throw new TxPlanError(`${fn}() needs a finite number, got ${String(by)}`);
352
+ }
353
+ }
354
+ function makeExpr(expr) {
355
+ return new Proxy(
356
+ { [EXPR]: expr },
357
+ {
358
+ get(target, prop) {
359
+ if (prop === EXPR) return target[EXPR];
360
+ if (TRAPPED_PROPS.includes(prop)) {
361
+ trap(prop, "A plan expression", "Write it into an operation instead.");
362
+ }
363
+ return void 0;
364
+ }
365
+ }
366
+ );
367
+ }
368
+ function makeRef(op, field) {
369
+ const target = { [REF]: { op, field } };
370
+ return new Proxy(target, {
371
+ get(t, prop) {
372
+ if (prop === REF) return t[REF];
373
+ if (TRAPPED_PROPS.includes(prop)) {
374
+ trap(
375
+ prop,
376
+ `\`${field}\` of a row this transaction has not written yet`,
377
+ "Pass it to another operation in the same plan, or return it from the callback and read it after `transaction()` resolves."
378
+ );
379
+ }
380
+ return void 0;
381
+ }
382
+ });
383
+ }
384
+ function makeRowHandle(op) {
385
+ const target = { [ROW]: op };
386
+ return new Proxy(target, {
387
+ get(t, prop) {
388
+ if (prop === ROW) return t[ROW];
389
+ if (TRAPPED_PROPS.includes(prop)) {
390
+ trap(
391
+ prop,
392
+ "A row this transaction has not written yet",
393
+ "Read one of its columns to reference it, or return the row from the callback and read it after `transaction()` resolves."
394
+ );
395
+ }
396
+ if (typeof prop === "symbol") return void 0;
397
+ return makeRef(op, prop);
398
+ }
399
+ });
400
+ }
401
+ function refDescriptor(v) {
402
+ if (typeof v !== "object" || v === null) return null;
403
+ const d = v[REF];
404
+ return isRefDescriptor(d) ? d : null;
405
+ }
406
+ function isRefDescriptor(d) {
407
+ return typeof d === "object" && d !== null && typeof d.op === "number" && typeof d.field === "string";
408
+ }
409
+ function rowOpIndex(v) {
410
+ if (typeof v !== "object" || v === null) return null;
411
+ const op = v[ROW];
412
+ return typeof op === "number" ? op : null;
413
+ }
414
+ function exprOf(v) {
415
+ if (typeof v !== "object" || v === null) return null;
416
+ const e = v[EXPR];
417
+ return typeof e === "object" && e !== null ? e : null;
418
+ }
419
+ function isRowsHandle(v) {
420
+ return typeof v === "object" && v !== null && v[ROWS] !== void 0;
421
+ }
422
+ function encodeValue(value, column, allowColumnExpr) {
423
+ const ref = refDescriptor(value);
424
+ if (ref) return { $ref: { op: ref.op, field: ref.field } };
425
+ const expr = exprOf(value);
426
+ if (expr) {
427
+ if (expr.fn !== "now" && !allowColumnExpr) {
428
+ throw new TxPlanError(
429
+ `\`${column}\`: ${expr.fn}() reads the column's current value, so it is only valid in updateWhere(where, set).`
430
+ );
431
+ }
432
+ return { $expr: expr };
433
+ }
434
+ if (rowOpIndex(value) !== null) {
435
+ throw new TxPlanError(
436
+ `\`${column}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`
437
+ );
438
+ }
439
+ if (isRowsHandle(value)) {
440
+ throw new TxPlanError(
441
+ `\`${column}\`: an operation result is not a value. Declare an expectation first (\`.expectOne(err)\`) and read a column from the row.`
442
+ );
443
+ }
444
+ assertNoNestedHandles(value, column);
445
+ return value;
446
+ }
447
+ function assertNoNestedHandles(value, column) {
448
+ if (typeof value !== "object" || value === null) return;
449
+ if (value instanceof Date) return;
450
+ if (refDescriptor(value) || exprOf(value) || rowOpIndex(value) !== null || isRowsHandle(value)) {
451
+ throw new TxPlanError(
452
+ `\`${column}\`: a plan handle is nested inside a value. The server would store it as literal JSON, not resolve it. Put the reference directly in the column.`
453
+ );
454
+ }
455
+ if (Array.isArray(value)) {
456
+ for (const item of value) assertNoNestedHandles(item, column);
457
+ return;
458
+ }
459
+ for (const item of Object.values(value)) {
460
+ assertNoNestedHandles(item, column);
461
+ }
462
+ }
463
+ function encodeMap(map, allowColumnExpr) {
464
+ const out = {};
465
+ for (const key of Object.keys(map).sort()) {
466
+ const value = map[key];
467
+ if (value === void 0) continue;
468
+ out[key] = encodeValue(value, key, allowColumnExpr);
469
+ }
470
+ return out;
471
+ }
472
+ var SKIPPED_OP = -1;
473
+ var TxRowsImpl = class {
474
+ constructor(builder, opIndex, what) {
475
+ this.builder = builder;
476
+ this.opIndex = opIndex;
477
+ this.what = what;
478
+ }
479
+ builder;
480
+ opIndex;
481
+ what;
482
+ // Present so `isRowsHandle` recognises the object; never read for its value.
483
+ [ROWS] = true;
484
+ guarded = false;
485
+ // The type-level `await` guard made real: TS rejects `await rows` at compile
486
+ // time, and reaching this means someone called `.then(...)` by hand.
487
+ then() {
488
+ throw new TxRefError(
489
+ `${this.what} cannot be awaited: a transaction callback builds a plan, it does not run statements. Remove the \`await\`.`
490
+ );
491
+ }
492
+ expectOne(error) {
493
+ this.declareGuard("one", 1, error);
494
+ if (this.opIndex === SKIPPED_OP) throw error;
495
+ return makeRowHandle(this.opIndex);
496
+ }
497
+ expectNone(error) {
498
+ this.declareGuard("none", 0, error);
499
+ }
500
+ expectAtLeast(n, error) {
501
+ assertGuardCount(n, "expectAtLeast");
502
+ this.declareGuard("atLeast", n, error);
503
+ if (this.opIndex === SKIPPED_OP && n > 0) throw error;
504
+ }
505
+ expectAtMost(n, error) {
506
+ assertGuardCount(n, "expectAtMost");
507
+ this.declareGuard("atMost", n, error);
508
+ }
509
+ declareGuard(kind, n, error) {
510
+ if (!(error instanceof Error)) {
511
+ throw new TxPlanError(
512
+ `${this.what}: an expectation needs the Error to throw when it does not hold (e.g. \`.expect\u2026(new Conflict("already accepted"))\`).`
513
+ );
514
+ }
515
+ if (this.guarded) {
516
+ throw new TxPlanError(
517
+ `${this.what} already has an expectation. One operation carries one expectation; declare the second one on its own operation.`
518
+ );
519
+ }
520
+ this.guarded = true;
521
+ if (this.opIndex === SKIPPED_OP) return;
522
+ this.builder.attachGuard(this.opIndex, kind, n, error);
523
+ }
524
+ };
525
+ function assertGuardCount(n, fn) {
526
+ if (!Number.isInteger(n) || n < 0) {
527
+ throw new TxPlanError(`${fn}(n) needs a non-negative integer, got ${String(n)}`);
528
+ }
529
+ }
530
+ var MAX_OPS = 1e3;
531
+ var MAX_ROWS = 5e3;
532
+ var TxPlanBuilder = class {
533
+ ops = [];
534
+ /** Errors handed to expectations, indexed by the `slot` the server echoes. */
535
+ slots = [];
536
+ /** The table surface handed to the callback. Untyped here; the public
537
+ * `transaction()` signatures put the schema types on top. */
538
+ table(name) {
539
+ return {
540
+ insert: (values) => {
541
+ const encoded = encodeMap(values, false);
542
+ if (Object.keys(encoded).length === 0) {
543
+ throw new TxPlanError(`${name}.insert() needs at least one column`);
544
+ }
545
+ return this.push({ op: "insert", table: name, values: encoded }, `${name}.insert()`);
546
+ },
547
+ insertMany: (rows) => {
548
+ if (rows.length === 0) {
549
+ return new TxRowsImpl(this, SKIPPED_OP, `${name}.insertMany()`);
550
+ }
551
+ if (rows.length > MAX_ROWS) {
552
+ throw new TxPlanError(
553
+ `${name}.insertMany() has ${rows.length} rows; the limit is ${MAX_ROWS}. Split the write across requests.`
554
+ );
555
+ }
556
+ const encoded = rows.map((row) => encodeMap(row, false));
557
+ assertUniformRows(encoded, name);
558
+ return this.push({ op: "insertMany", table: name, rows: encoded }, `${name}.insertMany()`);
559
+ },
560
+ updateWhere: (where, set) => {
561
+ const encodedWhere = encodeMap(where, false);
562
+ const encodedSet = encodeMap(set, true);
563
+ if (Object.keys(encodedWhere).length === 0) {
564
+ throw new TxPlanError(
565
+ `${name}.updateWhere() needs a filter. An update with no filter rewrites the whole table.`
566
+ );
567
+ }
568
+ if (Object.keys(encodedSet).length === 0) {
569
+ throw new TxPlanError(`${name}.updateWhere() needs at least one column to set`);
570
+ }
571
+ return this.push(
572
+ { op: "update", table: name, set: encodedSet, where: encodedWhere },
573
+ `${name}.updateWhere()`
574
+ );
575
+ },
576
+ deleteWhere: (where) => {
577
+ const encodedWhere = encodeMap(where, false);
578
+ if (Object.keys(encodedWhere).length === 0) {
579
+ throw new TxPlanError(
580
+ `${name}.deleteWhere() needs a filter. A delete with no filter empties the table.`
581
+ );
582
+ }
583
+ return this.push(
584
+ { op: "delete", table: name, where: encodedWhere },
585
+ `${name}.deleteWhere()`
586
+ );
587
+ },
588
+ select: (where, options) => {
589
+ const op = { op: "select", table: name };
590
+ const encodedWhere = encodeMap(where ?? {}, false);
591
+ if (Object.keys(encodedWhere).length > 0) op.where = encodedWhere;
592
+ if (options?.limit !== void 0) {
593
+ if (!Number.isInteger(options.limit) || options.limit < 0) {
594
+ throw new TxPlanError(
595
+ `${name}.select(): limit needs a non-negative integer, got ${String(options.limit)}`
596
+ );
597
+ }
598
+ op.limit = options.limit;
599
+ }
600
+ if (options?.lock !== void 0) op.lock = options.lock;
601
+ return this.push(op, `${name}.select()`);
602
+ }
603
+ };
604
+ }
605
+ push(op, what) {
606
+ if (this.ops.length >= MAX_OPS) {
607
+ throw new TxPlanError(
608
+ `this transaction has ${MAX_OPS} operations, which is the limit. Use insertMany() for bulk writes, or split the work across requests.`
609
+ );
610
+ }
611
+ const index = this.ops.length;
612
+ this.ops.push(op);
613
+ return new TxRowsImpl(this, index, what);
614
+ }
615
+ /** Attach an expectation to an op and record its error in the slot table. */
616
+ attachGuard(opIndex, kind, n, error) {
617
+ const op = this.ops[opIndex];
618
+ if (!op) throw new TxPlanError(`internal: expectation on unknown operation ${opIndex}`);
619
+ const slot = this.slots.length;
620
+ this.slots.push(error);
621
+ op.guard = { kind, n, slot };
622
+ }
623
+ /** The serialisable plan. Empty when the callback described no writes. */
624
+ body() {
625
+ return { ops: this.ops };
626
+ }
627
+ /** The error the server's `slot` selects, or `null` when it names one this
628
+ * plan never declared (a server/client disagreement, not a tenant error). */
629
+ errorForSlot(slot) {
630
+ return this.slots[slot] ?? null;
631
+ }
632
+ };
633
+ function assertUniformRows(rows, table) {
634
+ const first = rows[0];
635
+ if (!first) return;
636
+ const want = Object.keys(first);
637
+ const wantKey = want.join(",");
638
+ for (let i = 1; i < rows.length; i++) {
639
+ const got = Object.keys(rows[i]);
640
+ if (got.join(",") !== wantKey) {
641
+ throw new TxPlanError(
642
+ `${table}.insertMany(): every row must set the same columns. Row 0 sets [${want.join(", ")}] but row ${i} sets [${got.join(", ")}]. (A property set to \`undefined\` counts as absent \u2014 use \`null\`.)`
643
+ );
644
+ }
645
+ }
646
+ }
647
+ function materializeResult(value, results) {
648
+ const ref = refDescriptor(value);
649
+ if (ref) {
650
+ const row = rowOf(results, ref.op, `\`${ref.field}\``);
651
+ if (!(ref.field in row)) {
652
+ throw new TxPlanError(
653
+ `the transaction's operation ${ref.op} returned no column \`${ref.field}\`.`
654
+ );
655
+ }
656
+ return row[ref.field];
657
+ }
658
+ const rowOp = rowOpIndex(value);
659
+ if (rowOp !== null) return rowOf(results, rowOp, "a row");
660
+ if (isRowsHandle(value)) {
661
+ throw new TxPlanError(
662
+ "an operation result cannot be returned from a transaction callback: its row count is not known until the plan runs. Declare an expectation (`.expectOne(err)`) and return the row, or a column of it."
663
+ );
664
+ }
665
+ if (Array.isArray(value)) return value.map((item) => materializeResult(item, results));
666
+ if (isPlainObject(value)) {
667
+ const out = {};
668
+ for (const [key, item] of Object.entries(value)) out[key] = materializeResult(item, results);
669
+ return out;
670
+ }
671
+ return value;
672
+ }
673
+ function rowOf(results, opIndex, what) {
674
+ const result = results[opIndex];
675
+ if (!result) {
676
+ throw new TxPlanError(
677
+ `the transaction returned no result for operation ${opIndex}, so ${what} cannot be read.`
678
+ );
679
+ }
680
+ const row = result.rows[0];
681
+ if (!row) {
682
+ throw new TxPlanError(
683
+ `the transaction's operation ${opIndex} returned no row, so ${what} cannot be read.`
684
+ );
685
+ }
686
+ return row;
687
+ }
688
+ function isPlainObject(value) {
689
+ if (typeof value !== "object" || value === null) return false;
690
+ const proto = Object.getPrototypeOf(value);
691
+ return proto === Object.prototype || proto === null;
692
+ }
693
+ async function runTxPlan(transport, tables, builder, fn) {
694
+ const returned = fn({ tables });
695
+ const body = builder.body();
696
+ if (body.ops.length === 0) {
697
+ return materializeResult(returned, []);
698
+ }
699
+ let response;
700
+ try {
701
+ response = await transport.txPlan(body);
702
+ } catch (err) {
703
+ throw translateRejection(err, builder);
704
+ }
705
+ return materializeResult(returned, response.results);
706
+ }
707
+ function translateRejection(err, builder) {
708
+ if (typeof err !== "object" || err === null) return err;
709
+ const rejection = err;
710
+ if (rejection.error_code !== "tx_guard_failed" || typeof rejection.slot !== "number") {
711
+ return err;
712
+ }
713
+ return builder.errorForSlot(rejection.slot) ?? err;
714
+ }
715
+
303
716
  // src/db/typed-db.ts
304
717
  function makeTypedTable(name, raw2) {
305
718
  return {
@@ -311,19 +724,29 @@ function makeTypedTable(name, raw2) {
311
724
  };
312
725
  }
313
726
  function makeTypedDB(schema, raw2) {
314
- function buildTables(client) {
315
- const tables = {};
316
- for (const key of Object.keys(schema.tables)) {
317
- const tableDef = schema.tables[key];
318
- if (tableDef !== void 0) {
319
- tables[key] = makeTypedTable(tableDef.name, client);
320
- }
727
+ const tables = {};
728
+ for (const key of Object.keys(schema.tables)) {
729
+ const tableDef = schema.tables[key];
730
+ if (tableDef !== void 0) {
731
+ tables[key] = makeTypedTable(tableDef.name, raw2);
321
732
  }
322
- return tables;
323
733
  }
324
734
  const result = {
325
- tables: buildTables(raw2),
326
- transaction: (fn) => raw2.transaction((rawTx) => fn({ tables: buildTables(rawTx) }))
735
+ tables,
736
+ transaction(fn) {
737
+ const builder = new TxPlanBuilder();
738
+ const planTables = {};
739
+ for (const key of Object.keys(schema.tables)) {
740
+ const tableDef = schema.tables[key];
741
+ if (tableDef !== void 0) planTables[key] = builder.table(tableDef.name);
742
+ }
743
+ return runTxPlan(
744
+ raw2,
745
+ planTables,
746
+ builder,
747
+ fn
748
+ );
749
+ }
327
750
  };
328
751
  return result;
329
752
  }
@@ -332,14 +755,19 @@ function makeTypedDB(schema, raw2) {
332
755
  EXTENSION_DEPENDENCIES,
333
756
  PALBASE_EXTENSIONS,
334
757
  PolicyBuilder,
758
+ TxPlanError,
759
+ TxRefError,
335
760
  bigint,
336
761
  boolean,
762
+ dec,
337
763
  defineSchema,
338
764
  enumType,
765
+ inc,
339
766
  integer,
340
767
  isPalbaseExtension,
341
768
  jsonb,
342
769
  makeTypedDB,
770
+ now,
343
771
  policy,
344
772
  raw,
345
773
  text,