@pgxsinkit/client 0.1.36 → 0.1.40

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 (64) hide show
  1. package/dist/boot-report.d.ts +134 -0
  2. package/dist/boot-report.d.ts.map +1 -0
  3. package/dist/export-data.d.ts +100 -0
  4. package/dist/export-data.d.ts.map +1 -0
  5. package/dist/export-dump.d.ts +92 -0
  6. package/dist/export-dump.d.ts.map +1 -0
  7. package/dist/export-store.d.ts +214 -0
  8. package/dist/export-store.d.ts.map +1 -0
  9. package/dist/index.d.ts +206 -13
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +886 -69
  12. package/dist/index.js.map +21 -14
  13. package/dist/lazy-guard.d.ts +4 -3
  14. package/dist/lazy-guard.d.ts.map +1 -1
  15. package/dist/lifecycle-slot.d.ts +31 -0
  16. package/dist/lifecycle-slot.d.ts.map +1 -0
  17. package/dist/live-rows-sql.d.ts +21 -0
  18. package/dist/live-rows-sql.d.ts.map +1 -0
  19. package/dist/mutation-state.d.ts +9 -2
  20. package/dist/mutation-state.d.ts.map +1 -1
  21. package/dist/mutation.d.ts +12 -0
  22. package/dist/mutation.d.ts.map +1 -1
  23. package/dist/schema.d.ts +33 -0
  24. package/dist/schema.d.ts.map +1 -1
  25. package/dist/shape-sync.d.ts +10 -0
  26. package/dist/shape-sync.d.ts.map +1 -1
  27. package/dist/store-path.d.ts +132 -0
  28. package/dist/store-path.d.ts.map +1 -0
  29. package/dist/sync/index.d.ts +1 -1
  30. package/dist/sync/index.d.ts.map +1 -1
  31. package/dist/sync/types.d.ts +8 -0
  32. package/dist/sync/types.d.ts.map +1 -1
  33. package/dist/testing.d.ts +27 -0
  34. package/dist/testing.d.ts.map +1 -0
  35. package/dist/testing.js +17 -0
  36. package/dist/testing.js.map +11 -0
  37. package/dist/worker/attach-sync-client.d.ts +23 -2
  38. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  39. package/dist/worker/define-sync-worker.d.ts +5 -4
  40. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  41. package/dist/worker/protocol.d.ts +89 -8
  42. package/dist/worker/protocol.d.ts.map +1 -1
  43. package/package.json +9 -4
  44. package/skills/core/SKILL.md +14 -1
  45. package/skills/operating/SKILL.md +75 -15
  46. package/src/boot-report.ts +287 -0
  47. package/src/export-data.ts +300 -0
  48. package/src/export-dump.ts +239 -0
  49. package/src/export-store.ts +309 -0
  50. package/src/index.ts +623 -82
  51. package/src/lazy-guard.ts +23 -9
  52. package/src/lifecycle-slot.ts +66 -0
  53. package/src/live-rows-sql.ts +45 -0
  54. package/src/mutation-state.ts +11 -2
  55. package/src/mutation.ts +42 -0
  56. package/src/schema.ts +120 -1
  57. package/src/shape-sync.ts +21 -0
  58. package/src/store-path.ts +249 -0
  59. package/src/sync/index.ts +11 -0
  60. package/src/sync/types.ts +9 -0
  61. package/src/testing.ts +53 -0
  62. package/src/worker/attach-sync-client.ts +101 -6
  63. package/src/worker/define-sync-worker.ts +196 -30
  64. package/src/worker/protocol.ts +110 -10
package/dist/index.js.map CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/index.ts", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/entity.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/column-common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/column.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/table.utils.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/table.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/subquery.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/tracing-utils.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/tracing.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/view-common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/sql/sql.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/utils.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/array.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/codecs.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/codecs.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pglite/codecs.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/logger.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/count.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/query-promise.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/count.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/query.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/foreign-keys.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/int.common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/bigint.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/bigserial.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/boolean.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/char.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/cidr.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/custom.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/date.common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/date.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/double-precision.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/inet.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/integer.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/interval.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/json.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/jsonb.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/line.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/macaddr.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/macaddr8.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/numeric.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/point.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/real.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/serial.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/smallint.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/smallserial.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/text.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/time.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/timestamp.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/uuid.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/varchar.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/all.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/casing.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/table.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/primary-keys.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/checks.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/indexes.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/policies.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/unique-constraint.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/view-common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/utils.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/alias.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/selection-proxy.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/delete.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/delete.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/query-builders/query-builder.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/view-base.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/select.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/errors.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/sql/expressions/conditions.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/sql/expressions/select.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/relations.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/dialect.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/query-builder.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/insert.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/insert.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/query.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/raw.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/raw.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/refresh-materialized-view.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/select.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/update.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/update.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/db.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/session.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/cache/core/cache.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/session.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pglite/session.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pglite/driver.js", "../../../node_modules/drizzle-orm/relations.js", "../../contracts/src/apply-strategy.ts", "../../contracts/src/common.ts", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/enum.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/sequence.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/view.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/schema.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/alias.js", "../../contracts/src/config.ts", "../../../node_modules/drizzle-orm/utils.js", "../../contracts/src/registry.ts", "../../contracts/src/sql-identifier.ts", "../../contracts/src/convergence-model.ts", "../../contracts/src/fingerprint.ts", "../../contracts/src/mutation.ts", "../../contracts/src/sql-defaults.ts", "../../contracts/src/supabase-rls.ts", "../src/debug.ts", "../src/convergence.ts", "../src/lazy-guard.ts", "../src/sync/copy.ts", "../src/sync/drizzle-executor.ts", "../src/sync/apply.ts", "../src/sync/metadata-tables.ts", "../src/sync/tags.ts", "../src/schema.ts", "../src/local-tables.ts", "../src/local-store.ts", "../src/mutation-state.ts", "../src/mutation.ts", "../src/sync-auth.ts", "../src/shape-sync.ts", "../src/sync/index.ts", "../src/sync/nudge.ts", "../src/sync/shape-inbox.ts", "../src/sync/subscription-state.ts", "../src/sync/types.ts", "../src/worker/live-diff.ts", "../src/worker/protocol.ts", "../src/worker/attach-sync-client.ts", "../src/worker/token-cache.ts", "../src/worker/define-sync-worker.ts"],
3
+ "sources": ["../src/index.ts", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/entity.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/column-common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/column.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/table.utils.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/table.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/subquery.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/tracing-utils.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/tracing.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/view-common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/sql/sql.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/utils.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/array.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/codecs.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/codecs.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pglite/codecs.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/logger.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/count.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/query-promise.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/count.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/query.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/foreign-keys.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/int.common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/bigint.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/bigserial.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/boolean.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/char.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/cidr.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/custom.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/date.common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/date.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/double-precision.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/inet.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/integer.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/interval.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/json.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/jsonb.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/line.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/macaddr.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/macaddr8.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/numeric.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/point.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/real.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/serial.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/smallint.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/smallserial.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/text.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/time.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/timestamp.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/uuid.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/varchar.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/all.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/casing.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/table.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/primary-keys.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/checks.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/indexes.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/policies.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/unique-constraint.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/view-common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/utils.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/alias.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/selection-proxy.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/delete.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/delete.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/query-builders/query-builder.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/view-base.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/select.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/errors.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/sql/expressions/conditions.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/sql/expressions/select.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/relations.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/dialect.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/query-builder.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/insert.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/insert.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/query.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/raw.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/raw.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/refresh-materialized-view.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/select.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/update.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/update.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/db.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/session.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/cache/core/cache.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/session.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pglite/session.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pglite/driver.js", "../../../node_modules/drizzle-orm/relations.js", "../../contracts/src/apply-strategy.ts", "../../contracts/src/common.ts", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/enum.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/sequence.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/view.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/schema.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/alias.js", "../../contracts/src/config.ts", "../../../node_modules/drizzle-orm/utils.js", "../../contracts/src/registry.ts", "../../contracts/src/sql-identifier.ts", "../../contracts/src/convergence-model.ts", "../../contracts/src/fingerprint.ts", "../../contracts/src/mutation.ts", "../../contracts/src/sql-defaults.ts", "../../contracts/src/supabase-rls.ts", "../src/debug.ts", "../src/boot-report.ts", "../src/convergence.ts", "../src/export-dump.ts", "../src/export-store.ts", "../src/store-path.ts", "../src/export-data.ts", "../src/lazy-guard.ts", "../src/lifecycle-slot.ts", "../src/live-rows-sql.ts", "../src/sync/copy.ts", "../src/sync/drizzle-executor.ts", "../src/sync/apply.ts", "../src/sync/metadata-tables.ts", "../src/sync/tags.ts", "../src/schema.ts", "../src/local-tables.ts", "../src/local-store.ts", "../src/mutation-state.ts", "../src/mutation.ts", "../src/sync-auth.ts", "../src/shape-sync.ts", "../src/sync/index.ts", "../src/sync/nudge.ts", "../src/sync/shape-inbox.ts", "../src/sync/subscription-state.ts", "../src/sync/types.ts", "../src/worker/live-diff.ts", "../src/worker/protocol.ts", "../src/worker/attach-sync-client.ts", "../src/worker/token-cache.ts", "../src/worker/define-sync-worker.ts"],
4
4
  "sourcesContent": [
5
- "import { PGlite, type Results } from \"@electric-sql/pglite\";\nimport { live, type PGliteWithLive } from \"@electric-sql/pglite/live\";\nimport type { PgliteDatabase } from \"drizzle-orm/pglite\";\nimport { drizzle } from \"drizzle-orm/pglite\";\nimport { defineRelations } from \"drizzle-orm/relations\";\n\nimport type {\n MutationAck,\n MutationDiagnostics,\n RegistryRelations,\n RegistryTables,\n RegistryViews,\n SyncConfigInput,\n SyncRuntimeStatus,\n SyncTableCreateInput,\n SyncTableEntry,\n SyncTableName,\n SyncTableRegistry,\n SyncTableUpdateInput,\n WriteMode,\n} from \"@pgxsinkit/contracts\";\nimport { getSyncRegistrySchema } from \"@pgxsinkit/contracts\";\n\nimport { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from \"./convergence\";\nimport { syncDebug, timeAsync } from \"./debug\";\nimport { assertLazyRefsActivated, buildLazyGuardIndex, findReferencedLazyKeysInSql } from \"./lazy-guard\";\nimport {\n type LocalStoreVersionEvent,\n clearLazyGroupActivation,\n readActivatedLazyGroups,\n reconcileLocalStoreVersion,\n writeLazyGroupActivation,\n} from \"./local-store\";\nimport {\n createMutationRuntime,\n type MutationBatchItem,\n type MutationDetail,\n type MutationKind,\n type WriteUnit,\n} from \"./mutation\";\nimport { buildDesyncTableSql, buildDropReadCacheSql, buildWipeLocalStoreSql, generateLocalSchemaSql } from \"./schema\";\nimport { startConfiguredSync } from \"./shape-sync\";\nimport { createSyncEngine, type SyncEngine } from \"./sync\";\nimport { buildShapeHeaders } from \"./sync-auth\";\n\nexport { generateLocalSchemaSql };\nexport {\n type ConvergenceClient,\n type ConvergenceDriver,\n type ConvergenceDriverOptions,\n type ConvergenceTrigger,\n createBrowserConvergenceTrigger,\n createConvergenceDriver,\n createIntervalConvergenceTrigger,\n} from \"./convergence\";\nexport { instrumentShapeFetch, setSyncDebugSink, syncDebug, timeAsync } from \"./debug\";\nexport {\n type AttachedSyncClient,\n attachSyncClient,\n type AttachSyncClientOptions,\n provisionSyncWorker,\n} from \"./worker/attach-sync-client\";\nexport { defineSyncWorker, type DefineSyncWorkerOptions, type SyncWorkerHost } from \"./worker/define-sync-worker\";\nexport {\n computeLiveDiff,\n type LiveDiffState,\n LiveRowsMaterializer,\n rowKey,\n seedLiveDiffState,\n} from \"./worker/live-diff\";\nexport { createWorkerTokenCache, type WorkerTokenCache } from \"./worker/token-cache\";\nexport {\n type AttachAckPayload,\n type AttachPayload,\n type AuthTokenSnapshot,\n BRIDGE_CHANNEL,\n BRIDGE_PROTOCOL_VERSION,\n type BridgeCodec,\n type BridgeEnvelope,\n type BridgeEvent,\n type BridgeMessageType,\n type BridgePort,\n encodeEnvelope,\n identityCodec,\n isBridgeEnvelope,\n type LiveDiffPayload,\n type LiveInitialPayload,\n postBridgeMessage,\n type ProvisionAckPayload,\n type ProvisionPayload,\n type RpcOp,\n type RpcPayload,\n type RpcResultPayload,\n type SetOnlinePayload,\n type SubscribePayload,\n type TokenRequestPayload,\n type TokenResponsePayload,\n type WakePayload,\n} from \"./worker/protocol\";\nexport {\n assertLazyRefsActivated,\n buildLazyGuardIndex,\n findReferencedLazyKeysInSql,\n type LazyGuardIndex,\n LazyRelationNotActivatedError,\n} from \"./lazy-guard\";\nexport {\n getJournalTable,\n getLocalMetaTable,\n getOverlayTable,\n getReadModelView,\n getSyncedLocalTable,\n getSyncStateView,\n type JournalTable,\n type LocalMetaTable,\n type OverlayTable,\n type ReadModelView,\n type SyncStateView,\n} from \"./local-tables\";\nexport type { LocalStoreVersionEvent };\n\n// The store carries PGlite's own `live` extension (a genuine create-time extension) plus the pgxsinkit\n// sync engine's namespace, attached post-create by `createSyncClient` as the `electric` property (ADR-0032\n// S1) — no longer a create-time extension. The `electric` part is derived from `createSyncEngine`'s real\n// return so the type follows the attached object.\nexport type ClientPGlite = PGliteWithLive & { electric: SyncEngine[\"namespace\"] };\n\n/**\n * The pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), consumed by\n * {@link createClientPGlite} / {@link CreateSyncClientOptions.pgliteBootAssets}. The host fetches +\n * compiles these on an earlier screen and hands the promise in, so `PGlite.create` skips its own lazy\n * asset load — see the field's JSDoc for the accelerator geometry.\n */\nexport interface PgliteBootAssets {\n pgliteWasmModule?: WebAssembly.Module;\n initdbWasmModule?: WebAssembly.Module;\n fsBundle?: Blob;\n}\n\n/**\n * Create the raw local PGlite store the sync client runs on — the SAME `PGlite.create` call\n * {@link createSyncClient} makes internally (the `electric` + `live` extensions, pre-warmed boot-asset\n * consumption, and the `boot pglite.create` rail stamp), extracted so exactly one implementation exists\n * and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)\n * instance to {@link CreateSyncClientOptions.precreatedPglite}: the client then owns schema exec, prepare\n * hooks, journal recovery and store-version reconcile, exactly as its own `dataDir` path does.\n *\n * The instance is deliberately **schemaless** — the registry-derived local schema is role/registry\n * dependent, so it is applied post-create by `createSyncClient`. The eager create buys only the expensive\n * initdb (+ IDBFS open), which is the dominant cold-boot cost once the WASM is pre-warmed.\n *\n * `bootAssets` is the pre-warmed WASM/fs bundle (see {@link CreateSyncClientOptions.pgliteBootAssets}); a\n * rejected warm is caught to `undefined`, so PGlite falls back to loading its own assets — never a failure.\n */\nexport async function createClientPGlite(\n dataDir: string,\n options?: { bootAssets?: Promise<PgliteBootAssets> },\n): Promise<ClientPGlite> {\n // Stamp only the storage scheme (e.g. \"idb:\" / \"memory:\"), never the full path — the path can carry an\n // identity-specific store name, and the boot rail stays monotonic-and-scheme only.\n const dataDirScheme = dataDir.slice(0, dataDir.indexOf(\":\") + 1);\n // Resolve any pre-warmed boot assets BEFORE (and outside) the `boot pglite.create` stamp: the\n // fetch+compile was kicked off on an earlier screen, so this await just retrieves the already-settled\n // result and the stamp measures the create itself. A rejected warm is caught to `undefined` so a failed\n // pre-warm silently falls back to PGlite's own asset loading rather than failing the boot.\n const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => undefined) : undefined;\n return (await timeAsync(\n \"boot pglite.create\",\n () =>\n // Only PGlite's own `live` extension is a create-time extension; the pgxsinkit sync engine is NOT\n // (ADR-0032 S1) — it is a plain module `createSyncClient` attaches post-create as `pg.electric`. So\n // a store minted here is deliberately ENGINE-LESS by construction: a spare/pre-warmed store (e.g.\n // the board's login-screen mint) carries no engine, no shape streams, and no Electric connections\n // until it is claimed and handed to `createSyncClient`. The `as ClientPGlite` cast reflects that the\n // `electric` namespace is provisioned later, exactly as the registry-derived schema is.\n PGlite.create(dataDir, {\n ...(bootAssets ?? {}),\n extensions: {\n live,\n },\n }),\n { dataDir: dataDirScheme },\n // `as unknown as` because the raw store is deliberately engine-less here (only `live` is a create-time\n // extension); `createSyncClient` provisions the `electric` namespace post-create (ADR-0032 S1).\n )) as unknown as ClientPGlite;\n}\n\nexport interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {\n registry: TRegistry;\n electricUrl: string;\n writeUrl: string;\n getAuthToken?: () => Promise<string | undefined>;\n /**\n * Static headers added to **every** read-shape and write request, alongside the per-request\n * `Authorization` (which always wins). The toolkit is agnostic about deployment-gateway\n * credentials, so this is the seam for them — e.g. a Supabase Cloud `apikey` header the platform\n * function gateway expects. Sent even when no `getAuthToken` is supplied.\n */\n requestHeaders?: Record<string, string>;\n /**\n * Extra static headers sent on the **write** path only (the mutation-flush POST), merged over\n * {@link requestHeaders} (`{...requestHeaders, ...writeRequestHeaders}`). Read/shape requests never\n * see these. The seam exists because the two ingress points have opposite geometry: the write\n * function is DB-bound, so pinning it to the database's region (e.g. an `x-region` header) keeps its\n * chatty function→DB protocol on a ~1ms loop; the read proxy's upstream is a globally-distributed\n * CDN (Electric Cloud), so pinning reads away from the caller pays intercontinental round trips per\n * catch-up hop. Put region/DB-affinity headers here; keep gateway credentials the reads also need\n * (e.g. `apikey`) in the shared {@link requestHeaders}.\n */\n writeRequestHeaders?: Record<string, string>;\n syncEnabled?: boolean;\n dataDir?: string;\n /**\n * Pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), awaited and passed straight\n * into `PGlite.create`. The intent is to hide PGlite's ~2.5s cold `boot pglite.create` cost —\n * dominated by the WASM fetch+compile — behind user think-time: the host starts fetching/compiling\n * these on an earlier screen (e.g. the login/identity picker) and hands the still-pending promise\n * here, so by the time a store is opened the assets are already resolved and `PGlite.create` skips\n * its own lazy asset load. Ignored when {@link pgliteInstance} is supplied (the caller owns that\n * instance's boot). A rejected/failed warm is caught to `undefined` and never fails the boot — PGlite\n * falls back to loading its own assets, so this is a pure best-effort accelerator.\n */\n pgliteBootAssets?: Promise<PgliteBootAssets>;\n resetSubscriptionKeys?: string[];\n prepareLocalDbBeforeSchema?: (pglite: ClientPGlite) => Promise<void>;\n prepareLocalDb?: (pglite: ClientPGlite) => Promise<void>;\n onStatusChange?: (status: SyncRuntimeStatus) => void;\n onTableInitialSync?: (tableKey: string) => void;\n /**\n * A fully-provisioned PGlite instance the CALLER owns end-to-end. The client runs NONE of its\n * post-create boot steps against it — no schema exec, prepare hooks, or store-version reconcile\n * (journal recovery still runs, as it does on every path). Use it only when the caller has already\n * applied the registry schema itself. Contrast the three PGlite-provenance seams:\n * - {@link dataDir} (default) — the client creates the store AND runs every post-create step.\n * - {@link precreatedPglite} — the caller creates the raw store (via {@link createClientPGlite}), but\n * the client still runs every post-create step (schema/prepare/reconcile), exactly as `dataDir` does.\n * - `pgliteInstance` — the caller creates AND provisions the store; the client runs none of them.\n *\n * Mutually exclusive with {@link precreatedPglite} (supplying both throws).\n */\n pgliteInstance?: ClientPGlite;\n /**\n * A raw PGlite instance the caller created EAGERLY (via {@link createClientPGlite}) — typically on an\n * earlier screen, to hide the ~1.9s cold `initdb`/IDBFS open behind user think-time — but for which the\n * client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and store-version\n * reconcile all run exactly as on the {@link dataDir} path. This is the difference from\n * {@link pgliteInstance} (which skips schema/prepare/reconcile because the caller owns them); see that\n * option's JSDoc for the three-way distinction.\n *\n * The promise form lets the still-pending eager create be handed straight in. Precedence/validation:\n * - Supplying both this and {@link pgliteInstance} throws — they claim different ownership.\n * - {@link dataDir} is used ONLY as the fallback store id if this promise REJECTS: a failed eager\n * create is caught, logged on the boot rail, and the normal `dataDir` create path runs instead (also\n * consuming {@link pgliteBootAssets} if provided). The pattern is a pure accelerator, never a boot\n * dependency.\n */\n precreatedPglite?: Promise<ClientPGlite>;\n /**\n * PROVABLY-fresh store hint (ADR-0032 S4 / backlog-0003): the caller guarantees this store is brand-new\n * and schemaless — no prior schema, no synced rows, no persisted subscription state. When set (and sync\n * is enabled, and the client owns schema exec — i.e. not the {@link pgliteInstance} path), the shape\n * catch-up is started BEFORE the local boot phases (schema exec, journal recovery, store-version\n * reconcile) and buffered in memory, with commits gated until those phases finish — so the network\n * catch-up overlaps them instead of running strictly after. On a far-from-database caller this collapses\n * boot from `local-phases + catch-up` toward `max(local-phases, catch-up)`.\n *\n * MUST be set only when freshness is proven, never derived by probing — a claimed schemaless spare (the\n * board's claim path knows: a claimed spare is always fresh; a mapped/returning store never is). A wrong\n * `true` on a warm store would start the streams from offset 0 and skip the subscription-state read,\n * re-snapshotting instead of resuming. Absent/false → the exact sequential path (the default, correct for\n * every warm store).\n */\n freshStore?: boolean;\n /**\n * Hard cap on send attempts before a still-failing mutation is quarantined\n * (ADR-0005 congestion policy). Defaults to the library's built-in cap.\n */\n maxMutationAttempts?: number;\n /**\n * Invoked when mutations are quarantined (permanently rejected by the server, terminal). The library\n * surfaces them here rather than silently dropping or retry-looping (ADR-0006). Surface, then either\n * re-author + resubmit or roll back via {@link SyncClient.discardQuarantined} — which clears the kept\n * overlay + quarantined journal rows so the entity accepts new mutations again.\n */\n onQuarantine?: (quarantined: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked when mutations are `conflicted` — a stale write the server declined under the\n * `reject-if-stale` Conflict policy (ADR-0015). The optimistic Overlay is kept, so the app shows a\n * resolution/diff UI and resolves each as a new write (`mutate.update`) or `discardConflict`s it.\n */\n onConflict?: (conflicted: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked when a pessimistic write-unit is `rejected` (ADR-0022) — a business decline from the\n * authoritative endpoint (capacity/quota/uniqueness). The inverse of `onConflict`: the optimistic Overlay\n * was auto-discarded for the whole unit, so the app surfaces the typed reason rather than a resolve UI.\n */\n onReject?: (rejected: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked on boot when the registry fingerprint differs from the one the local store was\n * provisioned under (ADR-0006). `rebuilt` = the read cache was dropped and rebuilt at the\n * new shape; `deferred` = un-flushed/quarantined writes are still owed, so the rebuild is\n * postponed (and retried on a later boot) rather than dropping owed data.\n */\n onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;\n /**\n * Opt-in convergence driver (ADR-0005). Supply a {@link ConvergenceTrigger} (e.g.\n * `createBrowserConvergenceTrigger()`) and the client drives `flush`/`reconcile`/`retryFailed`\n * on the trigger's schedule, started once sync is ready and stopped on `stop()`/`destroy()`.\n * Omit it for fully-manual convergence (the mechanism primitives stay public either way).\n */\n autoSync?: ConvergenceTrigger;\n /** Invoked after each automatic convergence pass with its error, or `null` on success (only when `autoSync` is set). */\n onConvergencePass?: (error: unknown) => void;\n /**\n * Invoked when a read-path sync commit fails after exhausting its retries (ADR-0009 decision 5).\n * The runtime enters the `degraded` phase and holds the read cache at the last applied commit\n * instead of silently diverging from the server; recovery is a later commit or a restart/refetch.\n */\n onSyncError?: (error: Error) => void;\n}\n\nexport interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey extends SyncTableName<TRegistry>> {\n key: TKey;\n mode: TRegistry[TKey][\"mode\"];\n create: (input: SyncTableCreateInput<TRegistry, TKey>) => Promise<void>;\n update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => Promise<void>;\n delete: (entityKey: Record<string, string>) => Promise<void>;\n}\n\n/**\n * A table handle inside a {@link SyncClient.transaction} block (ADR-0022 §2). It *collects* mutations into\n * the open write-unit rather than enqueuing each immediately; the whole set is enqueued atomically when the\n * block's callback returns. The calls are synchronous (collection only) — no per-call await needed.\n */\nexport interface SyncTransactionTableHandle<\n TRegistry extends SyncTableRegistry,\n TKey extends SyncTableName<TRegistry>,\n> {\n create: (input: SyncTableCreateInput<TRegistry, TKey>) => void;\n update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;\n delete: (entityKey: Record<string, string>) => void;\n /**\n * An **update-by-key with no local base row** (ADR-0022 addendum). Ordinary `update` requires the entity\n * to be present in the actor's local read model (it seeds the optimistic overlay and captures the base\n * server version); `updateBlind` skips that presence check and writes NO overlay — nothing appears in the\n * read model. Use it when the write target is deliberately EXCLUDED from your read shape (a write-only\n * flow, or an anonymity-scoped moderation write whose row streams only to a different projection), so there\n * is no local row to update and nothing to show optimistically.\n *\n * **Pessimistic-only.** The /unit expander is authoritative for the outcome, so a blind write is meaningful\n * only inside a `transaction({ mode: \"pessimistic\" })` block (or over a statically-pessimistic table). An\n * optimistic-routed blind write has nothing to converge and THROWS at enqueue.\n *\n * The acked journal row **retires without a synced echo** (no visible row ever converges for it), so it does\n * not linger — unlike the seed-a-phantom-row workaround this replaces, whose acked row + overlay lingered\n * forever behind the echo barrier. A `conflicted` blind write stays dischargeable via `discardConflict`; a\n * `rejected` one is surfaced via `onReject`, both with no overlay to clean up.\n */\n updateBlind: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;\n}\n\n/** The handle passed to a {@link SyncClient.transaction} callback: collecting table handles for the unit. */\nexport interface SyncTransaction<TRegistry extends SyncTableRegistry> {\n tables: { [TKey in SyncTableName<TRegistry>]: SyncTransactionTableHandle<TRegistry, TKey> };\n}\n\n/**\n * The result of a {@link SyncClient.transaction}. A `pessimistic` block carries the authoritative server\n * `acks` (each `acked` / `conflicted` / `rejected`); an `optimistic` block enqueues atomically and flushes\n * in the background, so its `acks` are empty.\n */\nexport interface SyncTransactionResult {\n acks: MutationAck[];\n}\n\n/** Minimal shape of a Drizzle select builder: inspectable via `.toSQL()` and awaitable for its rows. */\nexport interface DrizzleQueryBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {\n toSQL(): { sql: string; params: unknown[] };\n}\n\n/**\n * The builder callback for a guarded read (ADR-0021): it receives the client and returns a Drizzle\n * select builder. Reach relations through `c.views` / `c.drizzle` / a directly-imported synced table.\n */\nexport type GuardedQueryFn<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> = (\n client: SyncClient<TRegistry>,\n) => DrizzleQueryBuilder<TRows>;\n\n/**\n * A guarded query whose builder MAY embed a raw `sql` template fragment (ADR-0021). A raw fragment can\n * name a lazy relation as a bare/unquoted identifier the compiled-SQL scan cannot see, so declare those\n * relations in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads need no\n * `use` (the scan detects every relation): pass the builder callback directly to `client.query`.\n */\nexport interface GuardedRawQuerySpec<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> {\n use?: readonly SyncTableName<TRegistry>[];\n build: GuardedQueryFn<TRegistry, TRows>;\n}\n\n/**\n * Inputs to the read-path safety seam {@link SyncClient.prepareQuery}. The lazy relations a query reads\n * are detected by scanning the compiled `sql` (union with the optional explicit `use`), then activated.\n * Shared by the live React hooks and the non-live facade.\n */\nexport interface PrepareQueryInput<TRegistry extends SyncTableRegistry> {\n /** The compiled (parameterised) Drizzle SQL the query will run — the scan's ground-truth target. */\n sql: string;\n /** Lazy relations to also activate, beyond those scanned from `sql` — a pre-activation hint, not required. */\n use?: readonly SyncTableName<TRegistry>[];\n}\n\n/**\n * The narrow live-rows seam (ADR-0032 S2 §4) both client modes implement so the `@pgxsinkit/react` hooks\n * work against either. Input for a reactive subscription: the compiled SQL + params (from a Drizzle\n * builder's `.toSQL()` or a raw string) and the result's `pkColumns` (drives worker-side diff keying;\n * omit for a keyless query). The in-process client runs it directly over `pglite.live`; the worker-attached\n * client runs the live query in the worker and streams DIFFs across the bridge.\n */\nexport interface SubscribeLiveRowsInput {\n sql: string;\n params: readonly unknown[];\n /** The result's PK columns — the diff-keying identity across the bridge (§4). Omit for a keyless query. */\n pkColumns?: readonly string[];\n /**\n * Lazy relations (ADR-0021) to activate before the query runs — forwarded to the worker so it can\n * `prepareQuery` before registering the live query (the tab's own `prepareQuery` is a no-op against the\n * worker bridge). Ignored by the in-process client, whose `prepareQuery` already ran on the tab.\n */\n use?: readonly string[];\n}\n\n/** A handle to a live-rows subscription: the initial ordered snapshot plus an idempotent unsubscribe. */\nexport interface LiveRowsSubscription<TRow> {\n initialRows: TRow[];\n unsubscribe: () => void;\n}\n\nexport interface SyncClient<TRegistry extends SyncTableRegistry> {\n drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;\n pglite: ClientPGlite;\n views: RegistryViews<TRegistry>;\n tables: {\n [TKey in SyncTableName<TRegistry>]: SyncClientTableHandle<TRegistry, TKey>;\n };\n ready: Promise<void>;\n status: SyncRuntimeStatus;\n start: () => Promise<void>;\n stop: () => Promise<void>;\n /**\n * Wipe the entire local store (synced cache + overlay + journal) and close the handle\n * (ADR-0005). Refuses if mutations are still owed to the server unless `force` is set, so\n * it never silently drops un-flushed writes. Distinct from `stop()`, which only halts sync.\n */\n destroy: (options?: { force?: boolean }) => Promise<void>;\n /**\n * Drop and rebuild the reconstructible synced read cache, preserving the overlay and\n * mutation journal (ADR-0006). The next sync refills it. Use to recover from a corrupt or\n * stale read cache without losing un-flushed writes.\n */\n dropReadCache: () => Promise<void>;\n flush: (table?: SyncTableName<TRegistry>) => Promise<void>;\n reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;\n retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;\n recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;\n readMutationDetails: (table?: SyncTableName<TRegistry>) => Promise<MutationDetail[]>;\n mutate: {\n create: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n input: SyncTableCreateInput<TRegistry, TKey>,\n ) => Promise<void>;\n update: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n patch: SyncTableUpdateInput<TRegistry, TKey>,\n ) => Promise<void>;\n delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;\n batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>) => Promise<void>;\n };\n /**\n * Discard a `conflicted` entity (ADR-0015): clear its conflicted journal entry and kept optimistic\n * Overlay, so the Read model falls back to the synced (server) value. Use when the user abandons a\n * stale edit instead of resolving it as a new write.\n */\n discardConflict: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n /**\n * Discard a `quarantined` entity (ADR-0006): clear its quarantined journal entry and kept optimistic\n * Overlay, so the Read model falls back to the synced (server) value. The rollback path for a write\n * the server permanently rejected — e.g. an RLS policy denial (42501) routed to quarantine. After the\n * discard the phantom optimistic row is gone and the entity accepts new mutations again (no longer\n * blocked behind the quarantined head). Symmetric to {@link SyncClient.discardConflict}; the overlay\n * is kept when another still-owed write depends on it. No-op for an entity with no quarantined entry.\n */\n discardQuarantined: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{ mutation: MutationDiagnostics }>;\n /**\n * The INSPECTION read surface (debug pages, REPLs, ad-hoc counts) — identical on the in-process and\n * worker-attached client (on the latter the statement runs in the worker). The statement runs raw\n * against the local store: it BYPASSES the mutation journal and optimistic overlay, and any write it\n * issues stays local and will NOT converge. For app data reads prefer the live-rows hooks /\n * {@link subscribeLiveRows} (or the guarded {@link query} family); reach for this only to look at the\n * store, not to read app state or mutate it.\n */\n rawQuery: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;\n /** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. */\n rawExec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;\n /**\n * Run a one-shot (non-live) typed **pure-Drizzle** query with the lazy-relation safety net (ADR-0021).\n * Pass the builder callback directly — pgxsinkit scans the compiled SQL and activates + awaits every\n * lazy relation it reads (FROM, JOIN, subquery, WHERE) before it runs, and the tripwire rejects any\n * lazy relation the SQL still references but that is not active, so the result is never silently\n * empty/stale. The guaranteed-safe alternative to a bare `client.drizzle` read. If the builder embeds\n * a raw `sql` template fragment, use {@link queryRaw} and declare the lazy relations in `use`.\n */\n query: <TRows extends readonly unknown[]>(build: GuardedQueryFn<TRegistry, TRows>) => Promise<TRows>;\n /** {@link query} returning the first row, or null when empty. */\n queryRow: <TRows extends readonly unknown[]>(\n build: GuardedQueryFn<TRegistry, TRows>,\n ) => Promise<TRows[number] | null>;\n /**\n * {@link query} for a builder that embeds a raw `sql` template fragment (ADR-0021). The compiled-SQL\n * scan can miss a lazy relation named as a bare/unquoted identifier inside raw SQL, so declare those\n * in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads should use\n * {@link query} instead (no `use` needed).\n */\n queryRaw: <TRows extends readonly unknown[]>(spec: GuardedRawQuerySpec<TRegistry, TRows>) => Promise<TRows>;\n /** {@link queryRaw} returning the first row, or null when empty. */\n queryRawRow: <TRows extends readonly unknown[]>(\n spec: GuardedRawQuerySpec<TRegistry, TRows>,\n ) => Promise<TRows[number] | null>;\n /**\n * Activate one or more lazy relations (ADR-0021): open their consistency-group subscription if held\n * out of the eager boot, resolving once their initial sync completes. Idempotent — eager or\n * already-started relations resolve immediately. Use to pre-activate before a raw/`client.drizzle`\n * read, or as the manual escape hatch the tripwire points to.\n */\n ensureSynced: (keys: readonly SyncTableName<TRegistry>[]) => Promise<void>;\n /**\n * Whether a relation's group has started and hydrated (ADR-0021). False for a still-dormant `lazy`\n * relation; true for eager relations once boot completes (and always when sync is disabled).\n */\n isSynced: (key: SyncTableName<TRegistry>) => boolean;\n /**\n * Revert a `lazy` relation to dormant (ADR-0021 §2) — the inverse of on-demand activation: stop its\n * consistency group's stream, clear any persisted `lazy + persistent` activation (so the next boot\n * holds it dormant again), and clean-truncate its local read cache. A later reference re-activates it\n * from scratch. Refuses when the relation is `eager` (always-on, would immediately re-sync) or owes\n * the server unsettled writes (the truncate would drop them — flush or discard first). The reclaim\n * primitive a host wires to navigation/idle for a rarely-opened lazy view; for an `ephemeral`\n * relation, idle-eviction is otherwise automatic at session end.\n */\n desync: (key: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * The read-path safety seam (ADR-0021): scan the compiled `sql` for the lazy relations it reads\n * (∪ the optional `use`), activate them, and await their initial sync — so a lazy relation\n * auto-activates on *any* reference (FROM, JOIN, subquery, WHERE). Resolves once it is safe to run the\n * query; a backstop throws {@link LazyRelationNotActivatedError} only if a referenced relation could\n * not be activated. Exposed for the React live hooks (which own their query build); `query`/`queryRow`\n * are the higher-level non-live wrappers. Raw, non-Drizzle SQL is out of scope — pass `use`, or\n * `ensureSynced` first.\n */\n prepareQuery: (input: PrepareQueryInput<TRegistry>) => Promise<void>;\n /**\n * Author an atomic write-**unit** (ADR-0022 §2). The callback receives collecting table handles; every\n * mutation it issues is tagged into one unit and enqueued atomically when the callback returns.\n *\n * - `mode: \"pessimistic\"` — **server-authoritative**: the unit flush-routes to the authoritative endpoint\n * and this call resolves only once the server has decided. The result's `acks` carry each member's\n * outcome — `acked`, `conflicted` (overlay kept, ADR-0015), or `rejected` (overlay auto-discarded for\n * the whole unit, surfaced via `onReject`, ADR-0022 §4). Throws on transport failure (overlay kept). A\n * pessimistic block may also issue {@link SyncTransactionTableHandle.updateBlind} — an update-by-key with\n * no local base row and no overlay, for a write target excluded from the actor's read shape.\n * - `mode: \"optimistic\"` — an atomic batch enqueue that flushes in the background (empty `acks`).\n */\n transaction: (\n options: { mode: WriteMode },\n run: (tx: SyncTransaction<TRegistry>) => void | Promise<void>,\n ) => Promise<SyncTransactionResult>;\n /**\n * Per-group readiness (ADR-0032 decision 6): a promise resolving the moment the given table's\n * consistency group is up-to-date. Resolves immediately for an already-ready (or sync-disabled)\n * group; stays pending for a still-dormant `lazy` relation until it is activated and caught up. The\n * opt-in progressive-paint signal beside the all-eager-groups `ready` gate. `status.groups` carries the\n * same readiness as a synchronous snapshot.\n */\n groupReady: (table: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * The live-rows seam (ADR-0032 S2 §4): register a reactive query and receive its initial ordered\n * snapshot plus subsequent updates via `onRows`. The React live hooks consume THIS (not `pglite.live`\n * directly), so they run unchanged against both the in-process client (which implements it over\n * `pglite.live`) and the worker-attached client (which implements it over the bridge). Prefer the\n * higher-level `@pgxsinkit/react` hooks; this is the lower-level primitive they build on.\n */\n subscribeLiveRows: <TRow extends Record<string, unknown> = Record<string, unknown>>(\n input: SubscribeLiveRowsInput,\n onRows: (rows: TRow[]) => void,\n ) => Promise<LiveRowsSubscription<TRow>>;\n}\n\nexport type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind };\n\n/**\n * The structured-clone-safe subset of PGlite's `QueryOptions` the inspection surface carries. Kept\n * narrow ON PURPOSE: on a worker-attached client the options object crosses the bridge via\n * `postMessage`, so function-valued options (`parsers`, `serializers`, `onNotice`) can never be part\n * of this contract. `rowMode: \"array\"` is what `@electric-sql/pglite-repl` asks for on every exec.\n */\nexport interface RawQueryOptions {\n rowMode?: \"object\" | \"array\";\n}\n\n/** The `{ query, exec }` duck `@electric-sql/pglite-repl` drives, backed by a client's inspection surface. */\nexport interface ReplInspectionSurface {\n query: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;\n exec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;\n}\n\n/**\n * Shape a {@link SyncClient}'s inspection surface (`rawQuery`/`rawExec`) as the `{ query, exec }` duck\n * `@electric-sql/pglite-repl` needs. Identical on the in-process and worker-attached client — on the latter\n * each statement routes through the worker bridge, so the REPL works even though `client.pglite` is\n * unavailable. Cast the result at the `<Repl pg={...}>` prop (the REPL types the prop as a full `PGlite`).\n * The surface is registry-independent, so it accepts any client's `rawQuery`/`rawExec` pair.\n */\nexport function replAdapter(\n client: Pick<SyncClient<SyncTableRegistry>, \"rawQuery\" | \"rawExec\">,\n): ReplInspectionSurface {\n return {\n // Thread the options through UNMODIFIED — the REPL execs with `{ rowMode: \"array\" }` and renders\n // each row with `row.map`, so dropping the options here breaks every REPL statement.\n query: (sql, params, options) => client.rawQuery(sql, params, options),\n exec: (sql, options) => client.rawExec(sql, options),\n };\n}\n\nexport async function createSyncClient<const TRegistry extends SyncTableRegistry>(\n options: CreateSyncClientOptions<TRegistry>,\n): Promise<SyncClient<TRegistry>> {\n const status: SyncRuntimeStatus = {\n phase: \"booting\",\n isRunning: false,\n };\n\n let resolveReady!: () => void;\n const ready = new Promise<void>((resolve) => {\n resolveReady = resolve;\n });\n\n if (options.pgliteInstance && options.precreatedPglite) {\n throw new Error(\n \"createSyncClient: pass at most one of `pgliteInstance` or `precreatedPglite` — they claim different ownership of the post-create boot steps (schema exec, prepare hooks, store-version reconcile).\",\n );\n }\n\n // Bind the boot-asset option once for the two create paths (fresh `dataDir`, and the `precreatedPglite`\n // reject-fallback), so both consume the same pre-warm.\n const createBootAssets = options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : undefined;\n const fallbackDataDir = options.dataDir ?? \"idb://pgxsinkit-overlay-v1\";\n\n let pglite: ClientPGlite;\n if (options.pgliteInstance) {\n // The caller created AND provisioned this store; the client runs NONE of the post-create boot steps\n // (schema/prepare/reconcile) — see the `pgliteInstance` JSDoc.\n pglite = options.pgliteInstance;\n } else if (options.precreatedPglite) {\n // The caller created the raw store eagerly via `createClientPGlite`; the client still owns every\n // post-create step below. A REJECTED eager create must never fail the boot: fall back to the normal\n // `dataDir` create here, so the pattern stays a pure accelerator.\n pglite = await options.precreatedPglite.catch((error: unknown) => {\n syncDebug(\"boot precreated pglite rejected — falling back to dataDir create\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return createClientPGlite(fallbackDataDir, createBootAssets);\n });\n } else {\n pglite = await createClientPGlite(fallbackDataDir, createBootAssets);\n }\n\n // Attach the sync engine explicitly, over the already-created instance, on ALL three provenance paths\n // (pgliteInstance, precreatedPglite, dataDir) — ADR-0032 S1. The engine is no longer a create-time\n // extension, so the raw store (a `createClientPGlite` mint, or a caller's own instance) carries no\n // `electric` namespace until this point; the property assignment gives `ClientPGlite` its exact former\n // structural shape (live + electric) so every `pglite.electric.…` call site is unchanged. It is attached\n // BEFORE the schema/prepare steps below so a `prepareLocalDb` hook sees the same `.electric` it did when\n // the extension provided it at create time. `engine.close` (the former extension close hook — abort every\n // shape stream) is kept private to this client and run explicitly by `stop`/`destroy` at the same moment\n // `pglite.close()` used to trigger it.\n const engine: SyncEngine = await createSyncEngine(pglite);\n (pglite as { electric: SyncEngine[\"namespace\"] }).electric = engine.namespace;\n\n const syncEnabled = options.syncEnabled ?? true;\n // Whether the read path's first initial sync has completed, so a recovery from `auth-needed` returns to\n // the right steady-state phase (`ready` if already caught up, else `syncing`).\n let initialSyncCompleted = false;\n // Why the runtime is `degraded` (#4). A read-stream error degraded clears on the next successful batch; a\n // commit-failure degraded is sticky (a fetch can succeed while applies still fail), so a bare\n // `onSyncActivity` must not clear it.\n let degradedReason: \"stream\" | \"commit\" | null = null;\n\n // ─── Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003) ─────────────────────────────────────\n // On a PROVABLY-FRESH store (the caller's `freshStore` hint — a claimed schemaless spare) the shape\n // catch-up needs none of the local boot phases, so start it NOW and gate its commits on `dbReady`, which\n // we resolve once schema exec + journal recovery + store-version reconcile complete. The network then\n // overlaps those phases instead of running strictly after them. Gated to the schema-owning paths (the\n // `pgliteInstance` path runs no schema step, so it has nothing to hide); warm stores keep the exact\n // sequential path. See the `freshStore` option's JSDoc for who sets the hint (the board's claim path).\n const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;\n let openDbGate: () => void = () => {};\n const dbReady = overlapPrefetch\n ? new Promise<void>((resolve) => {\n openDbGate = resolve;\n })\n : null;\n\n // The sync-start options, built once and used by BOTH the overlap early-start and the sequential start —\n // the only per-call difference is the promoted-lazy set (empty on a fresh store) and the overlap gate.\n const buildStartOptions = (promotedGroups: ReadonlySet<string>): Parameters<typeof startConfiguredSync>[1] => ({\n syncConfig: buildSyncConfigFromRegistry(options.registry, options.electricUrl),\n registry: options.registry,\n promotedGroups,\n ...(dbReady ? { dbReady } : {}),\n // Persist a durable lazy group's activation on first on-demand start, so the next boot promotes it.\n onLazyActivated: (groupKey) => {\n void writeLazyGroupActivation(pglite, options.registry, groupKey);\n },\n // The read path resolves the token per request (ADR-0013), not frozen at boot — so a long-lived session\n // never wedges on JWT expiry. Read and write share one token lifecycle.\n ...(options.getAuthToken || options.requestHeaders\n ? {\n shapeHeaders: buildShapeHeaders({\n ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),\n ...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),\n }),\n }\n : {}),\n ...(options.onTableInitialSync ? { onTableInitialSync: options.onTableInitialSync } : {}),\n // Per-group readiness (ADR-0032 decision 6): mirror each group's catch-up into `status.groups` and\n // re-emit, so an app can drive progressive per-group paint off `status` (and `client.groupReady`).\n onGroupReady: (groupKey) => {\n status.groups = { ...(status.groups ?? {}), [groupKey]: true };\n options.onStatusChange?.(status);\n },\n onInitialSync: () => {\n initialSyncCompleted = true;\n status.phase = \"ready\";\n options.onStatusChange?.(status);\n // Boot complete: the first initial sync landed and `ready` is about to resolve. One monotonic stamp\n // closes the boot rail opened by `boot pglite.create` (the stamp itself is the number).\n syncDebug(\"boot client ready\");\n resolveReady();\n },\n onSyncError: (error) => {\n // A sync commit exhausted its retries (ADR-0009 decision 5): go degraded and surface it, rather than\n // letting the read cache silently diverge from the server. Sticky (see below).\n status.phase = \"degraded\";\n degradedReason = \"commit\";\n status.lastError = error.message;\n options.onStatusChange?.(status);\n options.onSyncError?.(error);\n },\n // #4: a terminal/transient NON-auth read-stream error → `degraded`, so the runtime never keeps reporting\n // healthy while the read stream has stalled. Does not override the more-actionable `auth-needed`, nor a\n // commit-failure degraded. Cleared on the next successful batch below.\n onReadStreamError: (error) => {\n // Never mask the more-actionable auth-needed, nor a sticky commit-failure degraded (its lastError is\n // the more serious signal — a stream blip must not overwrite it).\n if (status.phase === \"auth-needed\") return;\n if (status.phase === \"degraded\" && degradedReason === \"commit\") return;\n // Enter, or refresh, a stream-degraded status. Refreshing keeps `lastError` pointing at the most\n // recent stream fault (and re-emits) rather than freezing on the first one, so a stream that fails one\n // way then another reports the current cause (observability).\n status.phase = \"degraded\";\n degradedReason = \"stream\";\n status.lastError = error.message;\n options.onStatusChange?.(status);\n },\n // Clear a recoverable status (auth-needed, or a read-stream degraded) the moment a batch is delivered\n // again. A commit-failure degraded is NOT cleared here — a fetch can succeed while applies keep failing,\n // so only `onSyncError` clearing (a clean commit) would lift it.\n onSyncActivity: () => {\n if (status.phase === \"auth-needed\" || (status.phase === \"degraded\" && degradedReason === \"stream\")) {\n degradedReason = null;\n status.phase = initialSyncCompleted ? \"ready\" : \"syncing\";\n options.onStatusChange?.(status);\n }\n },\n // ADR-0013 Phase 3: surface a persistent read-path auth failure as a distinct `auth-needed` status (the\n // app prompts re-login) while the stream keeps retrying for a fresh token. Only wired when a token\n // provider exists — without one there is no auth lifecycle to track.\n ...(options.getAuthToken\n ? {\n onAuthError: () => {\n if (status.phase !== \"auth-needed\") {\n status.phase = \"auth-needed\";\n options.onStatusChange?.(status);\n }\n },\n }\n : {}),\n });\n\n // Overlap: kick the shape streams off BEFORE schema exec (they buffer catch-up into the memory inbox,\n // commits gated on `dbReady`). A fresh store has no persisted lazy activations and no subscriptions to\n // reset, so both DB reads the sequential path makes first are skipped here.\n let earlySync: ReturnType<typeof startConfiguredSync> | null = null;\n if (overlapPrefetch) {\n status.isRunning = true;\n status.phase = \"syncing\";\n options.onStatusChange?.(status);\n earlySync = startConfiguredSync(\n pglite as unknown as Parameters<typeof startConfiguredSync>[0],\n buildStartOptions(new Set()),\n );\n }\n\n if (!options.pgliteInstance) {\n if (options.prepareLocalDbBeforeSchema) {\n const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;\n await timeAsync(\"boot prepare(before-schema)\", () => prepareBeforeSchema(pglite));\n }\n\n const schemaSql = generateLocalSchemaSql(options.registry);\n await timeAsync(\"boot local schema\", () => pglite.exec(schemaSql));\n\n if (options.prepareLocalDb) {\n const prepareLocalDb = options.prepareLocalDb;\n await timeAsync(\"boot prepare(local-db)\", () => prepareLocalDb(pglite));\n }\n }\n\n // The write path's headers are the shared base plus the write-only overrides (region/DB-affinity):\n // `{...requestHeaders, ...writeRequestHeaders}`. The read/shape path keeps `requestHeaders` alone\n // (below), so `writeRequestHeaders` never reach reads — the two ingress points pin independently.\n const writePathHeaders =\n options.requestHeaders || options.writeRequestHeaders\n ? { ...(options.requestHeaders ?? {}), ...(options.writeRequestHeaders ?? {}) }\n : undefined;\n\n const mutationRuntime = createMutationRuntime({\n db: pglite,\n registry: options.registry,\n writeUrl: options.writeUrl,\n ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),\n ...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),\n ...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),\n ...(options.onQuarantine ? { onQuarantine: options.onQuarantine } : {}),\n ...(options.onConflict ? { onConflict: options.onConflict } : {}),\n ...(options.onReject ? { onReject: options.onReject } : {}),\n });\n\n // Reclaim any in-flight mutations interrupted by a previous shutdown (ADR-0005), then\n // reconcile the local store against the current registry fingerprint before sync starts\n // (ADR-0006). Skipped when the caller supplies their own pglite (they own its schema).\n await timeAsync(\"boot journal recovery\", () => mutationRuntime.recoverSending());\n\n let versionEvent: LocalStoreVersionEvent | null = null;\n\n if (!options.pgliteInstance) {\n versionEvent = await timeAsync(\"boot store-version reconcile\", () =>\n reconcileLocalStoreVersion({\n db: pglite,\n registry: options.registry,\n runtime: mutationRuntime,\n ...(options.onSchemaChange ? { onSchemaChange: options.onSchemaChange } : {}),\n }),\n );\n }\n\n const drizzleDb = createDrizzleDatabase(pglite, buildSchema(options.registry));\n // Static index of the registry's lazy relations (ADR-0021), driving the read-path safety net.\n const lazyGuardIndex = buildLazyGuardIndex(options.registry);\n\n let sync: Awaited<ReturnType<typeof startConfiguredSync>> | null = null;\n let convergenceDriver: ConvergenceDriver | null = null;\n\n status.isRunning = true;\n\n // Open the overlap commit gate now the local store is ready (schema exec + journal recovery + reconcile\n // done): the catch-up the streams prefetched during those phases now drains in one commit train. A no-op\n // on the sequential path (`openDbGate` is the empty default there).\n openDbGate();\n\n if (syncEnabled) {\n if (earlySync) {\n // Overlap path: the shape streams have been prefetching since before schema exec; adopt the handle\n // (it resolves as soon as the streams are subscribed — catch-up drains via the gate just lifted, and\n // `onInitialSync` still gates `ready` on a fully-consistent first paint).\n sync = await earlySync;\n } else {\n // Sequential path (warm store / no fresh hint): the exact pre-S4 ordering — reset any rebuilt\n // subscriptions, promote durable lazy groups, then start (catch-up strictly after the local phases).\n // After a read-cache rebuild the Electric subscription bookkeeping is stale (it would believe the\n // dropped shapes are still caught up and never backfill), so reset every shape subscription to force a\n // fresh re-stream (ADR-0006).\n const resetKeys =\n versionEvent?.status === \"rebuilt\"\n ? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]\n : options.resetSubscriptionKeys;\n await resetSubscriptionsIfRequested(pglite, resetKeys);\n\n status.phase = \"syncing\";\n options.onStatusChange?.(status);\n\n // Promote any `lazy + persistent` group activated on a previous boot back into the eager set\n // (ADR-0021 §2); the sync engine does no DB read of its own.\n const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);\n\n sync = await timeAsync(\"boot sync start\", () =>\n startConfiguredSync(\n pglite as unknown as Parameters<typeof startConfiguredSync>[0],\n buildStartOptions(promotedGroups),\n ),\n );\n }\n } else {\n status.phase = \"ready\";\n options.onStatusChange?.(status);\n resolveReady();\n }\n\n if (options.autoSync) {\n convergenceDriver = createConvergenceDriver({\n client: {\n flush: () => mutationRuntime.flush(),\n reconcile: () => mutationRuntime.reconcile(),\n },\n trigger: options.autoSync,\n ...(options.onConvergencePass ? { onPass: options.onConvergencePass } : {}),\n });\n\n // Start driving convergence once the initial sync is ready, so a pass never races the\n // first shape load. stop()/destroy() halt it.\n void ready.then(() => convergenceDriver?.start());\n }\n\n // Event-driven convergence: the moment a mutation is enqueued, ask the driver to run a pass so the\n // write flushes immediately rather than waiting for the trigger's next interval tick. This is what\n // lets the interval be a rare fallback (and so run far less often). No-op when `autoSync` is off — the\n // caller drives `flush`/`reconcile` itself.\n const requestConvergence = () => convergenceDriver?.requestPass();\n const mutate: SyncClient<TRegistry>[\"mutate\"] = {\n create: async (table, input) => {\n await mutationRuntime.create(table, input);\n requestConvergence();\n },\n update: async (table, entityKey, patch) => {\n await mutationRuntime.update(table, entityKey, patch);\n requestConvergence();\n },\n delete: async (table, entityKey) => {\n await mutationRuntime.delete(table, entityKey);\n requestConvergence();\n },\n batch: async (items) => {\n await mutationRuntime.batch(items);\n requestConvergence();\n },\n };\n\n // ─── Lazy-relation activation + the declared-safe query facade (ADR-0021) ──────────────────────\n const ensureSynced: SyncClient<TRegistry>[\"ensureSynced\"] = async (keys) => {\n const activeSync = sync;\n if (activeSync == null || keys.length === 0) return;\n const groupKeys = new Set<string>();\n for (const key of keys) {\n const groupKey = activeSync.groupKeyForTable(key);\n if (groupKey != null) groupKeys.add(groupKey);\n }\n await Promise.all([...groupKeys].map((groupKey) => activeSync.ensureGroupStarted(groupKey)));\n };\n\n const isSynced: SyncClient<TRegistry>[\"isSynced\"] = (key) => {\n const activeSync = sync;\n // Sync disabled → local-only: reads hit whatever is in the local store, so nothing is \"dormant\".\n if (activeSync == null) return true;\n return activeSync.isTableStarted(key);\n };\n\n const desync: SyncClient<TRegistry>[\"desync\"] = async (key) => {\n const entry = options.registry[key];\n if (entry == null) throw new Error(`desync: unknown table ${String(key)}`);\n if (entry.subscription !== \"lazy\") {\n throw new Error(\n `desync('${String(key)}') refused: only a lazy relation can be desynced — an eager relation is always-on and would immediately re-sync.`,\n );\n }\n\n // ADR-0021 §2/§4: desync operates on the whole consistency GROUP — a group is one subscription / one\n // transaction frontier, so reverting one member to dormant reverts them all. Gather the group's tables\n // (a table with no `consistencyGroup` is its own singleton group).\n const targetGroup = entry.consistencyGroup;\n const groupTableKeys = (\n targetGroup == null\n ? [key]\n : (Object.keys(options.registry) as SyncTableName<TRegistry>[]).filter(\n (candidate) => options.registry[candidate]!.consistencyGroup === targetGroup,\n )\n ) as SyncTableName<TRegistry>[];\n\n // Refuse if ANY writable member owes the server unsent/unsettled writes: the truncate clears the\n // journal, so dropping un-acked local intent would be silent data loss. Flush (or discard) those first.\n let owed = 0;\n for (const member of groupTableKeys) {\n if (options.registry[member]!.mode === \"readonly\") continue;\n const stats = await mutationRuntime.readMutationStats(member);\n owed +=\n stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;\n }\n if (owed > 0) {\n throw new Error(\n `desync('${String(key)}') refused: ${owed} unsettled mutation(s) in the group's local journal. Flush or discard them first.`,\n );\n }\n\n const activeSync = sync;\n // The group key IS the Electric subscription key (`consistencyGroup ?? shapeKey`); fall back to the\n // registry derivation when sync is disabled.\n const groupKey = activeSync?.groupKeyForTable(key) ?? entry.consistencyGroup ?? entry.shape?.shapeKey;\n // Stop the stream BEFORE truncating so a live shape can't re-populate the rows we just cleared, and\n // revert the durable promotion (a no-op for ephemeral, which never persisted a flag) so the next boot\n // holds the relation dormant again.\n if (activeSync != null && groupKey != null) activeSync.stopGroup(groupKey);\n if (groupKey != null) await clearLazyGroupActivation(pglite, options.registry, groupKey);\n // CRITICAL: delete the group's persisted Electric subscription so a later re-activation re-streams the\n // shape from scratch. Without this it would resume from the old cursor and never re-send the rows we\n // truncate below — leaving the relation permanently missing its pre-desync data.\n if (groupKey != null) await resetSubscriptionsIfRequested(pglite, [groupKey]);\n // Clean-truncate every member's local cluster.\n for (const member of groupTableKeys) {\n await pglite.exec(buildDesyncTableSql(options.registry, member as string));\n }\n };\n\n const transaction: SyncClient<TRegistry>[\"transaction\"] = async ({ mode }, run) => {\n // The block's table handles only COLLECT mutations; the whole set is enqueued atomically as one unit.\n const collected: MutationBatchItem<TRegistry>[] = [];\n const txTables = Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n create: (input: unknown) => {\n collected.push({ table: tableKey, kind: \"create\", input } as MutationBatchItem<TRegistry>);\n },\n update: (entityKey: Record<string, string>, patch: unknown) => {\n collected.push({ table: tableKey, kind: \"update\", entityKey, patch } as MutationBatchItem<TRegistry>);\n },\n updateBlind: (entityKey: Record<string, string>, patch: unknown) => {\n collected.push({\n table: tableKey,\n kind: \"update\",\n entityKey,\n patch,\n blind: true,\n } as MutationBatchItem<TRegistry>);\n },\n delete: (entityKey: Record<string, string>) => {\n collected.push({ table: tableKey, kind: \"delete\", entityKey } as MutationBatchItem<TRegistry>);\n },\n },\n ]),\n ) as SyncTransaction<TRegistry>[\"tables\"];\n\n await run({ tables: txTables });\n\n if (collected.length === 0) {\n return { acks: [] };\n }\n\n const unit: WriteUnit = { id: globalThis.crypto.randomUUID(), mode };\n await mutationRuntime.batch(collected, unit);\n\n if (mode === \"optimistic\") {\n // An atomic batch enqueue; the background convergence loop flushes it (no foreground answer).\n void mutationRuntime.flush();\n return { acks: [] };\n }\n\n // Pessimistic: flush-route this unit to the authoritative endpoint and await the per-mutation result.\n return await mutationRuntime.flushUnit(unit.id);\n };\n\n const prepareQuery: SyncClient<TRegistry>[\"prepareQuery\"] = async ({ sql, use }) => {\n // Scan the compiled SQL for the lazy relations it reads (∪ the explicit `use`) and activate them.\n // The compiled SQL is ground truth and Drizzle quotes every relation, so any reference — FROM, JOIN,\n // subquery, WHERE — is caught; over-matching is bounded and harmless (one spurious persistent\n // subscription at worst, never a wrong result). Detection and activation are one step (ADR-0021).\n const toActivate = new Set<string>(use ?? []);\n for (const key of findReferencedLazyKeysInSql(sql, lazyGuardIndex)) toActivate.add(key);\n await ensureSynced([...toActivate] as SyncTableName<TRegistry>[]);\n // Backstop: if a referenced lazy relation is somehow still not active (a failed start, or no group),\n // throw rather than let the query read empty/stale. In the normal path everything scanned was just\n // activated, so this passes.\n assertLazyRefsActivated({\n sql,\n index: lazyGuardIndex,\n isActive: (key) => isSynced(key as SyncTableName<TRegistry>),\n });\n };\n\n const runGuardedQuery = async <TRows extends readonly unknown[]>(\n build: GuardedQueryFn<TRegistry, TRows>,\n use?: readonly SyncTableName<TRegistry>[],\n ): Promise<TRows> => {\n const builder = build(client);\n await prepareQuery({ sql: builder.toSQL().sql, ...(use ? { use } : {}) });\n return builder;\n };\n\n const client: SyncClient<TRegistry> = {\n drizzle: drizzleDb,\n pglite,\n views: buildViews(options.registry),\n tables: Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n key: tableKey,\n mode: options.registry[tableKey as SyncTableName<TRegistry>]!.mode,\n create: (input: SyncTableCreateInput<TRegistry, typeof tableKey>) =>\n mutate.create(tableKey as SyncTableName<TRegistry>, input),\n update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, typeof tableKey>) =>\n mutate.update(tableKey as SyncTableName<TRegistry>, entityKey, patch),\n delete: (entityKey: Record<string, string>) => mutate.delete(tableKey as SyncTableName<TRegistry>, entityKey),\n },\n ]),\n ) as SyncClient<TRegistry>[\"tables\"],\n ready,\n status,\n start: async () => {\n await ready;\n },\n stop: async () => {\n // Await any in-flight convergence pass before closing PGlite, so a pass never queries a\n // closed handle.\n await convergenceDriver?.stop();\n sync?.unsubscribe();\n status.isRunning = false;\n options.onStatusChange?.(status);\n // Tear the engine down (abort every shape stream) immediately before closing the DB — the exact\n // point PGlite's own close used to invoke the former extension's close hook (ADR-0032 S1). Order\n // preserved: convergence stop → sync unsubscribe → status → engine close → pglite close.\n await engine.close();\n await pglite.close();\n },\n destroy: async (destroyOptions) => {\n if (!destroyOptions?.force) {\n const stats = await mutationRuntime.readMutationStats();\n const owed =\n stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;\n\n if (owed > 0) {\n throw new Error(\n `destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`,\n );\n }\n }\n\n // Drain any in-flight convergence pass before wiping, so a pass never writes into a store\n // being torn down underneath it.\n await convergenceDriver?.stop();\n sync?.unsubscribe();\n status.isRunning = false;\n options.onStatusChange?.(status);\n await pglite.exec(buildWipeLocalStoreSql(options.registry));\n // Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment\n // the former extension close hook fired during `pglite.close()` (ADR-0032 S1).\n await engine.close();\n await pglite.close();\n },\n dropReadCache: async () => {\n await pglite.exec(buildDropReadCacheSql(options.registry));\n await pglite.exec(generateLocalSchemaSql(options.registry));\n // Reset the Electric subscriptions so the rebuilt synced tables re-stream from scratch\n // rather than the bookkeeping believing they are already caught up (ADR-0006).\n await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));\n },\n flush: (table) => mutationRuntime.flush(table),\n reconcile: (table) => mutationRuntime.reconcile(table),\n retryFailed: (table) => mutationRuntime.retryFailed(table),\n recoverSending: (table) => mutationRuntime.recoverSending(table),\n readMutationDetails: (table) => mutationRuntime.readMutationDetails(table),\n mutate,\n discardConflict: (table, entityKey) => mutationRuntime.discardConflict(table, entityKey),\n discardQuarantined: (table, entityKey) => mutationRuntime.discardQuarantined(table, entityKey),\n diagnostics: async (table) => ({\n mutation: await mutationRuntime.readMutationStats(table),\n }),\n // Inspection surface (see the interface doc): straight through to the underlying store, no journal /\n // overlay involvement. The worker facade runs the identical call inside the worker's own client.\n rawQuery: (sql, params, options) => pglite.query(sql, params as unknown[] | undefined, options),\n rawExec: (sql, options) => pglite.exec(sql, options),\n query: (build) => runGuardedQuery(build),\n queryRow: async (build) => {\n const rows = await runGuardedQuery(build);\n return rows[0] ?? null;\n },\n queryRaw: (spec) => runGuardedQuery(spec.build, spec.use),\n queryRawRow: async (spec) => {\n const rows = await runGuardedQuery(spec.build, spec.use);\n return rows[0] ?? null;\n },\n ensureSynced,\n isSynced,\n desync,\n prepareQuery,\n transaction,\n groupReady: async (table) => {\n const activeSync = sync;\n // Sync disabled → local-only: every relation is trivially \"ready\" (nothing to await).\n if (activeSync == null) return;\n const groupKey = activeSync.groupKeyForTable(table as string);\n if (groupKey == null) return;\n await activeSync.groupReady(groupKey);\n },\n // The live-rows seam over PGlite's own `live` extension (ADR-0032 S2 §4) — the EXACT call the React\n // hooks made inline before the seam existed (`pglite.live.query` → `initialResults.rows` + `subscribe`),\n // so the in-process path is unchanged. `pkColumns` is unused here: PGlite's live query already diffs\n // incrementally against its own materialized state; the column set only matters for the worker bridge.\n subscribeLiveRows: async ({ sql, params }, onRows) => {\n const registered = await pglite.live.query<Record<string, unknown>>(sql, params as unknown[]);\n const listener = (results: { rows: Record<string, unknown>[] }) => {\n onRows(results.rows as never);\n };\n registered.subscribe(listener);\n return {\n initialRows: registered.initialResults.rows as never,\n unsubscribe: () => {\n void registered.unsubscribe(listener);\n },\n };\n },\n };\n\n return client;\n}\n\n/**\n * Every persisted subscription key declared by the registry — one per consistency group (ADR-0009\n * decision 2), not per table. Grouped tables share a subscription-state row keyed by their group;\n * ungrouped tables are singleton groups keyed by their own `shapeKey`. Deduped, since several tables\n * collapse onto one group key.\n */\nfunction allGroupSubscriptionKeys<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {\n const keys = Object.values(registry)\n .filter((entry) => typeof entry.shape?.shapeKey === \"string\" && entry.shape.shapeKey.length > 0)\n .map((entry) => entry.consistencyGroup ?? entry.shape!.shapeKey);\n return [...new Set(keys)];\n}\n\nasync function resetSubscriptionsIfRequested(pglite: ClientPGlite, keys: string[] | undefined) {\n if (!keys || keys.length === 0) {\n return;\n }\n\n const uniqueKeys = [...new Set(keys.map((key) => key.trim()).filter((key) => key.length > 0))];\n\n if (uniqueKeys.length === 0) {\n return;\n }\n\n await pglite.electric.initMetadataTables();\n await Promise.all(uniqueKeys.map((key) => pglite.electric.deleteSubscription(key)));\n}\n\nfunction createDrizzleDatabase<TRegistry extends SyncTableRegistry>(\n client: ClientPGlite,\n schema: RegistryTables<TRegistry>,\n) {\n const relations = defineRelations(schema) as RegistryRelations<TRegistry>;\n\n const createDatabase = drizzle as unknown as (config: {\n client: ClientPGlite;\n relations: RegistryRelations<TRegistry>;\n }) => PgliteDatabase<RegistryRelations<TRegistry>>;\n\n return createDatabase({ client, relations });\n}\n\nfunction buildSchema<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n return Object.fromEntries(\n Object.entries(registry).map(([key, entry]) => [key, entry.table]),\n ) as RegistryTables<TRegistry>;\n}\n\nfunction buildViews<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n return Object.fromEntries(\n Object.entries(registry).flatMap(([key, entry]) => (entry.view != null ? [[key, entry.view]] : [])),\n ) as RegistryViews<TRegistry>;\n}\n\n/**\n * The tab-side READ handles a worker-attached client exposes (ADR-0032 S2): a build-only Drizzle instance\n * plus the registry views. On the attach client, Drizzle is used only to COMPILE queries to SQL\n * (`.toSQL()`) on the tab — execution happens in the worker via the live-rows bridge / RPC — so it is\n * constructed over a stub client that is never invoked (`construct` stores the client without calling it).\n * The same builders `createSyncClient` uses, so a query built on either client compiles identically.\n */\nexport function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): { drizzle: PgliteDatabase<RegistryRelations<TRegistry>>; views: RegistryViews<TRegistry> } {\n const stubClient = {} as ClientPGlite;\n return {\n drizzle: createDrizzleDatabase(stubClient, buildSchema(registry)),\n views: buildViews(registry),\n };\n}\n\nfunction buildSyncConfigFromRegistry<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n electricUrl: string,\n): SyncConfigInput {\n return {\n electricUrl,\n localSchema: getSyncRegistrySchema(registry),\n tables: Object.fromEntries(Object.entries(registry).map(([key, entry]) => [key, buildSyncTableInput(entry, key)])),\n };\n}\n\nfunction buildSyncTableInput(entry: SyncTableEntry, tableKey: string) {\n const clientProjection = getClientProjection(entry, tableKey);\n\n return {\n name: tableKey,\n mode: entry.mode,\n primaryKey: entry.primaryKey,\n ...(entry.shape !== undefined ? { shape: entry.shape } : {}),\n clientProjection,\n // The read-path apply ladder (strategy + json casts) is resolved by the engine directly from the\n // registry entry via `resolveApplyTarget` (ADR-0029 D1/D2) — `deriveSyncColumnTypes` /\n // `classifyTableApplyStrategy` on the model, never carried through this config surface.\n // Carry the consistency group (ADR-0009 decision 2) so the sync starter buckets grouped tables\n // onto one MultiShapeStream; absent → singleton group.\n ...(entry.consistencyGroup ? { consistencyGroup: entry.consistencyGroup } : {}),\n // Carry the lifecycle axes (ADR-0021) so the sync starter can hold lazy groups out of the eager\n // boot set and provision ephemeral clusters as TEMP; absent → eager/persistent (today's path).\n ...(entry.subscription ? { subscription: entry.subscription } : {}),\n ...(entry.retention ? { retention: entry.retention } : {}),\n };\n}\n\nfunction getClientProjection(entry: SyncTableEntry, tableKey: string) {\n if (!entry.clientProjection) {\n throw new Error(`clientProjection is required for client table ${tableKey}`);\n }\n\n return entry.clientProjection;\n}\n",
5
+ "import { PGlite, type Results } from \"@electric-sql/pglite\";\nimport { live, type PGliteWithLive } from \"@electric-sql/pglite/live\";\nimport type { PgliteDatabase } from \"drizzle-orm/pglite\";\nimport { drizzle } from \"drizzle-orm/pglite\";\nimport { defineRelations } from \"drizzle-orm/relations\";\n\nimport type {\n MutationAck,\n MutationDiagnostics,\n RegistryRelations,\n RegistryTables,\n RegistryViews,\n SyncConfigInput,\n SyncRuntimeStatus,\n SyncTableCreateInput,\n SyncTableEntry,\n SyncTableName,\n SyncTableRegistry,\n SyncTableUpdateInput,\n WriteMode,\n} from \"@pgxsinkit/contracts\";\nimport { fingerprintRegistry, getSyncRegistrySchema } from \"@pgxsinkit/contracts\";\n\nimport { type BootReport, type BootReportBuilder, createBootReportBuilder } from \"./boot-report\";\nimport { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from \"./convergence\";\nimport { syncDebug, timeAsync } from \"./debug\";\nimport { type DataExportOptions, type DataExportResult, performDataExport } from \"./export-data\";\nimport { type DiagnosticExportOptions, type DiagnosticExportResult, performDiagnosticExport } from \"./export-dump\";\nimport { performStoreExport, type StoreExportOptions, type StoreExportResult } from \"./export-store\";\nimport { assertLazyRefsActivated, buildLazyGuardIndex, findReferencedLazyKeysInSql } from \"./lazy-guard\";\nimport { createLifecycleSlot } from \"./lifecycle-slot\";\nimport { wrapLiveQueryForMaterialization } from \"./live-rows-sql\";\nimport {\n type LocalStoreVersionEvent,\n clearLazyGroupActivation,\n readActivatedLazyGroups,\n reconcileLocalStoreVersion,\n writeLazyGroupActivation,\n} from \"./local-store\";\nimport {\n createMutationRuntime,\n type MutationBatchItem,\n type MutationDetail,\n type MutationKind,\n type WriteUnit,\n} from \"./mutation\";\nimport {\n buildDataExportCloneCleanupSql,\n buildDataExportEnumHeaderSql,\n buildDesyncTableSql,\n buildDropReadCacheSql,\n buildWipeLocalStoreSql,\n collectDataExportSyncedTableNames,\n generateLocalSchemaSql,\n} from \"./schema\";\nimport { startConfiguredSync } from \"./shape-sync\";\nimport {\n classifyNonPersistentDataDir,\n NonPersistentStoreError,\n normaliseStorePathInput,\n readTestStoreMarker,\n resolveStoreDataDir,\n RestoreTargetExistsError,\n storeTargetExists,\n type StorePathInput,\n} from \"./store-path\";\nimport { createSyncEngine, type SyncEngine } from \"./sync\";\nimport { buildShapeHeaders } from \"./sync-auth\";\n\nexport { generateLocalSchemaSql };\nexport { wrapLiveQueryForMaterialization } from \"./live-rows-sql\";\nexport type { BootReport } from \"./boot-report\";\nexport {\n type CloneDumpPhases,\n type CloneDumpResult,\n type DiagnosticExportDeps,\n type DiagnosticExportOptions,\n type DiagnosticExportResult,\n performDiagnosticExport,\n runThrowawayCloneDump,\n} from \"./export-dump\";\nexport {\n type DataExportDeps,\n DataExportDrainError,\n type DataExportOptions,\n type DataExportResult,\n DEFAULT_DRAIN_TIMEOUT_MS,\n type DrainJournalOption,\n type DrainJournalOptions,\n performDataExport,\n} from \"./export-data\";\nexport {\n type DataExportReport,\n deriveStoreId,\n type DiagnosticDumpReport,\n type ExportReport,\n type ExportReportCommon,\n performDatadirDump,\n performStoreExport,\n type StoreBackupReport,\n type StoreExportDeps,\n type StoreExportOptions,\n type StoreExportResult,\n} from \"./export-store\";\nexport { createLifecycleSlot, LifecycleBusyError, type LifecycleSlot } from \"./lifecycle-slot\";\nexport {\n InvalidStorePathError,\n NonPersistentStoreError,\n resolveStoreDataDir,\n RestoreTargetExistsError,\n storeIndexedDbDatabaseName,\n storeTargetExists,\n} from \"./store-path\";\nexport {\n type ConvergenceClient,\n type ConvergenceDriver,\n type ConvergenceDriverOptions,\n type ConvergenceTrigger,\n createBrowserConvergenceTrigger,\n createConvergenceDriver,\n createIntervalConvergenceTrigger,\n} from \"./convergence\";\nexport { instrumentShapeFetch, setSyncDebugSink, syncDebug, timeAsync } from \"./debug\";\nexport {\n type AttachedSyncClient,\n attachSyncClient,\n type AttachSyncClientOptions,\n provisionSyncWorker,\n} from \"./worker/attach-sync-client\";\nexport { defineSyncWorker, type DefineSyncWorkerOptions, type SyncWorkerHost } from \"./worker/define-sync-worker\";\nexport {\n computeLiveDiff,\n type LiveDiffState,\n LiveRowsMaterializer,\n rowKey,\n seedLiveDiffState,\n} from \"./worker/live-diff\";\nexport { createWorkerTokenCache, type WorkerTokenCache } from \"./worker/token-cache\";\nexport {\n type AttachAckPayload,\n type AttachPayload,\n type AuthTokenSnapshot,\n BRIDGE_CHANNEL,\n BRIDGE_PROTOCOL_VERSION,\n type BridgeCodec,\n type BridgeEnvelope,\n type BridgeEvent,\n type BridgeMessageType,\n type BridgePort,\n encodeEnvelope,\n type ExportArtefactWire,\n identityCodec,\n isBridgeEnvelope,\n type LiveDiffPayload,\n type LiveInitialPayload,\n postBridgeMessage,\n type ProvisionAckPayload,\n type ProvisionPayload,\n type RpcOp,\n type RpcPayload,\n type RpcResultPayload,\n type SetOnlinePayload,\n type SubscribePayload,\n type TokenRequestPayload,\n type TokenResponsePayload,\n type WakePayload,\n} from \"./worker/protocol\";\nexport {\n assertLazyRefsActivated,\n buildLazyGuardIndex,\n findReferencedLazyKeysInSql,\n type LazyGuardIndex,\n LazyRelationNotActivatedError,\n} from \"./lazy-guard\";\nexport {\n getJournalTable,\n getLocalMetaTable,\n getOverlayTable,\n getReadModelView,\n getSyncedLocalTable,\n getSyncStateView,\n type JournalTable,\n type LocalMetaTable,\n type OverlayTable,\n type ReadModelView,\n type SyncStateView,\n} from \"./local-tables\";\nexport type { LocalStoreVersionEvent };\n\n// The store carries PGlite's own `live` extension (a genuine create-time extension) plus the pgxsinkit\n// sync engine's namespace, attached post-create by `createSyncClient` as the `electric` property (ADR-0032\n// S1) — no longer a create-time extension. The `electric` part is derived from `createSyncEngine`'s real\n// return so the type follows the attached object.\nexport type ClientPGlite = PGliteWithLive & { electric: SyncEngine[\"namespace\"] };\n\n/**\n * The pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), consumed by\n * {@link createClientPGlite} / {@link CreateSyncClientOptions.pgliteBootAssets}. The host fetches +\n * compiles these on an earlier screen and hands the promise in, so `PGlite.create` skips its own lazy\n * asset load — see the field's JSDoc for the accelerator geometry.\n */\nexport interface PgliteBootAssets {\n pgliteWasmModule?: WebAssembly.Module;\n initdbWasmModule?: WebAssembly.Module;\n fsBundle?: Blob;\n}\n\n/** Options for {@link createClientPGlite}. */\nexport interface CreateClientPGliteOptions {\n /**\n * Pre-warmed PGlite boot assets (see {@link CreateSyncClientOptions.pgliteBootAssets}). Awaited and\n * passed into `PGlite.create`; a rejected warm is caught to `undefined` (falls back to PGlite's own\n * asset load), so it never fails the create.\n */\n bootAssets?: Promise<PgliteBootAssets>;\n /**\n * @internal Test-only storage-backend override (ADR-0036). `\"memory\"` resolves the store to a\n * scheme-selected in-memory store — the sanctioned unit-test/ephemeral lane. Never a product\n * configuration: reached only through `@pgxsinkit/client/testing`, never consumer-facing.\n */\n backendOverride?: \"memory\";\n /**\n * A store-backup tarball to seed the new store from (ADR-0035 decision 6, restore) — a `File`/`Blob` as\n * produced by {@link SyncClient.exportStore}. Passed straight to PGlite's `loadDataDir`, so the created\n * store boots ON the backup's datadir. Restore is a CREATION-path feature: the caller (`createSyncClient`)\n * has already proven the target does not yet exist ({@link storeTargetExists}); this option carries no\n * freshness check of its own. A corrupt/foreign tarball surfaces as a PGlite boot failure here.\n */\n restoreFrom?: File | Blob;\n}\n\n/**\n * Create the raw local PGlite store the sync client runs on — the SAME `PGlite.create` call\n * {@link createSyncClient} makes internally (the `electric` + `live` extensions, pre-warmed boot-asset\n * consumption, and the `boot pglite.create` rail stamp), extracted so exactly one implementation exists\n * and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)\n * instance to {@link CreateSyncClientOptions.precreatedPglite}: the client then owns schema exec, prepare\n * hooks, journal recovery and store-version reconcile, exactly as its own `storePath` path does.\n *\n * Takes a plain store path (ADR-0036), never a storage URL — the backend is DERIVED (IndexedDB in a\n * browser/worker, the filesystem on Bun/Node); a scheme-bearing path throws {@link InvalidStorePathError}.\n * Also accepts the testing helper's output (`createClientPGlite(memoryStoreForTests(\"x\"))`) so a test can\n * mint a memory store without naming a backend.\n *\n * The instance is deliberately **schemaless** — the registry-derived local schema is role/registry\n * dependent, so it is applied post-create by `createSyncClient`. The eager create buys only the expensive\n * initdb (+ IDBFS open), which is the dominant cold-boot cost once the WASM is pre-warmed.\n *\n * `bootAssets` is the pre-warmed WASM/fs bundle (see {@link CreateSyncClientOptions.pgliteBootAssets}); a\n * rejected warm is caught to `undefined`, so PGlite falls back to loading its own assets — never a failure.\n */\nexport async function createClientPGlite(\n store: StorePathInput,\n options?: CreateClientPGliteOptions,\n): Promise<ClientPGlite> {\n // Normalise the store argument to a plain path (+ any internal memory override the testing helper carried),\n // then derive the concrete PGlite dataDir URL (ADR-0036) — the single resolution point. A scheme-bearing/\n // empty storePath throws here, so the old dataDir-URL contract fails loudly, never silently re-interpreted.\n const normalised = normaliseStorePathInput(store);\n const dataDir = resolveStoreDataDir(normalised.storePath, options?.backendOverride ?? normalised.backendOverride);\n // Stamp only the storage scheme (e.g. \"idb:\" / \"memory:\"), never the full path — the path can carry an\n // identity-specific store name, and the boot rail stays monotonic-and-scheme only.\n const dataDirScheme = dataDir.slice(0, dataDir.indexOf(\":\") + 1);\n // Resolve any pre-warmed boot assets BEFORE (and outside) the `boot pglite.create` stamp: the\n // fetch+compile was kicked off on an earlier screen, so this await just retrieves the already-settled\n // result and the stamp measures the create itself. A rejected warm is caught to `undefined` so a failed\n // pre-warm silently falls back to PGlite's own asset loading rather than failing the boot.\n const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => undefined) : undefined;\n return (await timeAsync(\n \"boot pglite.create\",\n () =>\n // Only PGlite's own `live` extension is a create-time extension; the pgxsinkit sync engine is NOT\n // (ADR-0032 S1) — it is a plain module `createSyncClient` attaches post-create as `pg.electric`. So\n // a store minted here is deliberately ENGINE-LESS by construction: a spare/pre-warmed store (e.g.\n // the board's login-screen mint) carries no engine, no shape streams, and no Electric connections\n // until it is claimed and handed to `createSyncClient`. The `as ClientPGlite` cast reflects that the\n // `electric` namespace is provisioned later, exactly as the registry-derived schema is.\n PGlite.create(dataDir, {\n ...(bootAssets ?? {}),\n // Restore (ADR-0035 decision 6): seed the brand-new store from the backup tarball. PGlite's\n // `loadDataDir` unpacks it into the datadir being created, so the store boots ON the backup's bytes —\n // the whole synced cache, Overlay, and Mutation journal that travelled inside it. Absent on a normal\n // create (the store initdbs empty).\n ...(options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {}),\n extensions: {\n live,\n },\n }),\n { dataDir: dataDirScheme },\n // `as unknown as` because the raw store is deliberately engine-less here (only `live` is a create-time\n // extension); `createSyncClient` provisions the `electric` namespace post-create (ADR-0032 S1).\n )) as unknown as ClientPGlite;\n}\n\nexport interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {\n registry: TRegistry;\n electricUrl: string;\n writeUrl: string;\n getAuthToken?: () => Promise<string | undefined>;\n /**\n * Static headers added to **every** read-shape and write request, alongside the per-request\n * `Authorization` (which always wins). The toolkit is agnostic about deployment-gateway\n * credentials, so this is the seam for them — e.g. a Supabase Cloud `apikey` header the platform\n * function gateway expects. Sent even when no `getAuthToken` is supplied.\n */\n requestHeaders?: Record<string, string>;\n /**\n * Extra static headers sent on the **write** path only (the mutation-flush POST), merged over\n * {@link requestHeaders} (`{...requestHeaders, ...writeRequestHeaders}`). Read/shape requests never\n * see these. The seam exists because the two ingress points have opposite geometry: the write\n * function is DB-bound, so pinning it to the database's region (e.g. an `x-region` header) keeps its\n * chatty function→DB protocol on a ~1ms loop; the read proxy's upstream is a globally-distributed\n * CDN (Electric Cloud), so pinning reads away from the caller pays intercontinental round trips per\n * catch-up hop. Put region/DB-affinity headers here; keep gateway credentials the reads also need\n * (e.g. `apikey`) in the shared {@link requestHeaders}.\n */\n writeRequestHeaders?: Record<string, string>;\n syncEnabled?: boolean;\n /**\n * The local store's name (ADR-0036) — a PLAIN path/name, never a PGlite storage URL. The storage backend\n * is DERIVED from the environment (IndexedDB in a browser/worker, the filesystem on Bun/Node); a\n * scheme-bearing string (anything containing `://`) is rejected with {@link InvalidStorePathError}\n * at boot. Defaults to a built-in overlay store name when omitted. A memory-backed store is not a product\n * configuration — for the test/ephemeral lane, spread `memoryStoreForTests(...)` from\n * `@pgxsinkit/client/testing` instead of naming one here.\n */\n storePath?: string;\n /**\n * Pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), awaited and passed straight\n * into `PGlite.create`. The intent is to hide PGlite's ~2.5s cold `boot pglite.create` cost —\n * dominated by the WASM fetch+compile — behind user think-time: the host starts fetching/compiling\n * these on an earlier screen (e.g. the login/identity picker) and hands the still-pending promise\n * here, so by the time a store is opened the assets are already resolved and `PGlite.create` skips\n * its own lazy asset load. Ignored when {@link pgliteInstance} is supplied (the caller owns that\n * instance's boot). A rejected/failed warm is caught to `undefined` and never fails the boot — PGlite\n * falls back to loading its own assets, so this is a pure best-effort accelerator.\n */\n pgliteBootAssets?: Promise<PgliteBootAssets>;\n resetSubscriptionKeys?: string[];\n prepareLocalDbBeforeSchema?: (pglite: ClientPGlite) => Promise<void>;\n prepareLocalDb?: (pglite: ClientPGlite) => Promise<void>;\n onStatusChange?: (status: SyncRuntimeStatus) => void;\n onTableInitialSync?: (tableKey: string) => void;\n /**\n * A fully-provisioned PGlite instance the CALLER owns end-to-end. The client runs NONE of its\n * post-create boot steps against it — no schema exec, prepare hooks, or store-version reconcile\n * (journal recovery still runs, as it does on every path). Use it only when the caller has already\n * applied the registry schema itself. Contrast the three PGlite-provenance seams:\n * - {@link storePath} (default) — the client creates the store AND runs every post-create step.\n * - {@link precreatedPglite} — the caller creates the raw store (via {@link createClientPGlite}), but\n * the client still runs every post-create step (schema/prepare/reconcile), exactly as `storePath` does.\n * - `pgliteInstance` — the caller creates AND provisions the store; the client runs none of them.\n *\n * A caller-owned instance is REFUSED with {@link NonPersistentStoreError} if it is provably\n * non-persistent (a `new PGlite()` default, or an in-memory store) — pgxsinkit's durability semantics\n * assume a persisted store (ADR-0036). Acknowledge a deliberate test store by spreading\n * `testStoreAcknowledgment()` from `@pgxsinkit/client/testing`.\n *\n * Mutually exclusive with {@link precreatedPglite} (supplying both throws).\n */\n pgliteInstance?: ClientPGlite;\n /**\n * A raw PGlite instance the caller created EAGERLY (via {@link createClientPGlite}) — typically on an\n * earlier screen, to hide the ~1.9s cold `initdb`/IDBFS open behind user think-time — but for which the\n * client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and store-version\n * reconcile all run exactly as on the {@link storePath} path. This is the difference from\n * {@link pgliteInstance} (which skips schema/prepare/reconcile because the caller owns them); see that\n * option's JSDoc for the three-way distinction.\n *\n * The promise form lets the still-pending eager create be handed straight in. Precedence/validation:\n * - Supplying both this and {@link pgliteInstance} throws — they claim different ownership.\n * - {@link storePath} is used ONLY as the fallback store name if this promise REJECTS: a failed eager\n * create is caught, logged on the boot rail, and the normal `storePath` create path runs instead (also\n * consuming {@link pgliteBootAssets} if provided). The pattern is a pure accelerator, never a boot\n * dependency.\n * - A successfully-adopted instance is subject to the same {@link NonPersistentStoreError} refusal as\n * {@link pgliteInstance} (checked after resolution, so the refusal propagates rather than being\n * swallowed by the reject-fallback).\n */\n precreatedPglite?: Promise<ClientPGlite>;\n /**\n * Restore the store from a **store backup** (ADR-0035 decision 6) — a `File`/`Blob` tarball as produced by\n * {@link SyncClient.exportStore}. The client creates its store with the backup handed to PGlite's\n * `loadDataDir`, so it boots ON the backup's datadir (synced cache + Overlay + Mutation journal, all the\n * bytes that travelled inside it). Three restore-only rules apply, none of them optional:\n *\n * - **Fresh target only.** Refused with {@link RestoreTargetExistsError} if a store already exists at the\n * resolved {@link storePath} — restore never overlays a live store (that would corrupt the datadir); the\n * remedy is a deliberate {@link SyncClient.destroy} of the existing store first.\n * - **Always boots offline.** The engine boots with sync OFF regardless of {@link syncEnabled}/{@link autoSync}\n * or anything captured in the backup — no shape streams, no read fetch, no flush, no convergence passes.\n * Restore wins over an explicit online option (a debug-rail warning notes the override). The app inspects\n * {@link SyncClient.diagnostics}, releases/discards the quarantined rows, then a subsequent NORMAL boot of\n * the (now-persisted) store brings sync online — `loadDataDir` happens exactly once, on this restore boot.\n * - **Journal quarantined.** Every non-terminal recovered row (`pending`/`sending`/`failed`) is moved to\n * `quarantined` — nothing recovered from a backup auto-flushes (the write path has no `mutationId` dedupe\n * ledger, so replay is unsafe on last-write-wins tables). Release (`retryFailed`) or discard\n * (`discardQuarantined`) them explicitly.\n *\n * Mutually exclusive with {@link pgliteInstance} AND {@link precreatedPglite} — restore owns the store's\n * creation (`loadDataDir` is a create-time seed), so a caller-supplied instance conflicts (supplying either\n * with `restoreFrom` throws).\n */\n restoreFrom?: File | Blob;\n /**\n * PROVABLY-fresh store hint (ADR-0032 S4 / backlog-0003): the caller guarantees this store is brand-new\n * and schemaless — no prior schema, no synced rows, no persisted subscription state. When set (and sync\n * is enabled, and the client owns schema exec — i.e. not the {@link pgliteInstance} path), the shape\n * catch-up is started BEFORE the local boot phases (schema exec, journal recovery, store-version\n * reconcile) and buffered in memory, with commits gated until those phases finish — so the network\n * catch-up overlaps them instead of running strictly after. On a far-from-database caller this collapses\n * boot from `local-phases + catch-up` toward `max(local-phases, catch-up)`.\n *\n * MUST be set only when freshness is proven, never derived by probing — a claimed schemaless spare (the\n * board's claim path knows: a claimed spare is always fresh; a mapped/returning store never is). A wrong\n * `true` on a warm store would start the streams from offset 0 and skip the subscription-state read,\n * re-snapshotting instead of resuming. Absent/false → the exact sequential path (the default, correct for\n * every warm store).\n */\n freshStore?: boolean;\n /**\n * Hard cap on send attempts before a still-failing mutation is quarantined\n * (ADR-0005 congestion policy). Defaults to the library's built-in cap.\n */\n maxMutationAttempts?: number;\n /**\n * Invoked when mutations are quarantined (permanently rejected by the server, terminal). The library\n * surfaces them here rather than silently dropping or retry-looping (ADR-0006). Surface, then either\n * re-author + resubmit or roll back via {@link SyncClient.discardQuarantined} — which clears the kept\n * overlay + quarantined journal rows so the entity accepts new mutations again.\n */\n onQuarantine?: (quarantined: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked when mutations are `conflicted` — a stale write the server declined under the\n * `reject-if-stale` Conflict policy (ADR-0015). The optimistic Overlay is kept, so the app shows a\n * resolution/diff UI and resolves each as a new write (`mutate.update`) or `discardConflict`s it.\n */\n onConflict?: (conflicted: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked when a pessimistic write-unit is `rejected` (ADR-0022) — a business decline from the\n * authoritative endpoint (capacity/quota/uniqueness). The inverse of `onConflict`: the optimistic Overlay\n * was auto-discarded for the whole unit, so the app surfaces the typed reason rather than a resolve UI.\n */\n onReject?: (rejected: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked on boot when the registry fingerprint differs from the one the local store was\n * provisioned under (ADR-0006). `rebuilt` = the read cache was dropped and rebuilt at the\n * new shape; `deferred` = un-flushed/quarantined writes are still owed, so the rebuild is\n * postponed (and retried on a later boot) rather than dropping owed data.\n */\n onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;\n /**\n * Opt-in convergence driver (ADR-0005). Supply a {@link ConvergenceTrigger} (e.g.\n * `createBrowserConvergenceTrigger()`) and the client drives `flush`/`reconcile`/`retryFailed`\n * on the trigger's schedule, started once sync is ready and stopped on `stop()`/`destroy()`.\n * Omit it for fully-manual convergence (the mechanism primitives stay public either way).\n */\n autoSync?: ConvergenceTrigger;\n /** Invoked after each automatic convergence pass with its error, or `null` on success (only when `autoSync` is set). */\n onConvergencePass?: (error: unknown) => void;\n /**\n * Invoked when a read-path sync commit fails after exhausting its retries (ADR-0009 decision 5).\n * The runtime enters the `degraded` phase and holds the read cache at the last applied commit\n * instead of silently diverging from the server; recovery is a later commit or a restart/refetch.\n */\n onSyncError?: (error: Error) => void;\n /**\n * Boot observability (ADR-0034): invoked exactly once, at boot completion, with the finalized\n * {@link BootReport}. The push counterpart of {@link SyncClient.bootReport} (the pull) for consumers that\n * want the numbers without polling — dashboards, CI budget gates. Never fired before initial sync; a\n * `stop()`/`destroy()` before then means it never fires.\n */\n onBootReport?: (report: BootReport) => void;\n /**\n * @internal Boot mode stamped into the {@link BootReport} (ADR-0034). `defineSyncWorker` sets `\"worker\"`;\n * absent → `\"in-process\"`. Not a behavior knob — it only labels the report.\n */\n bootMode?: BootReport[\"mode\"];\n /**\n * @internal Provision timing for a boot that ADOPTS a pre-provisioned store (ADR-0034). When the store was\n * minted ahead of boot (a spare's off-thread initdb), the provisioner stamps its create cost and ready\n * time here; the boot reports them as {@link BootReport.provision} and sets `phases.pgliteCreateMs = null`.\n * A promise because the stamp settles with the spare's `create`. Only honoured on the {@link precreatedPglite}\n * adoption path (ignored on a fallback create). `provisionReadyAt` must share this process's monotonic clock.\n */\n provisionStamp?: Promise<{ initdbMs: number; provisionReadyAt: number }>;\n}\n\nexport interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey extends SyncTableName<TRegistry>> {\n key: TKey;\n mode: TRegistry[TKey][\"mode\"];\n create: (input: SyncTableCreateInput<TRegistry, TKey>) => Promise<void>;\n update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => Promise<void>;\n delete: (entityKey: Record<string, string>) => Promise<void>;\n}\n\n/**\n * A table handle inside a {@link SyncClient.transaction} block (ADR-0022 §2). It *collects* mutations into\n * the open write-unit rather than enqueuing each immediately; the whole set is enqueued atomically when the\n * block's callback returns. The calls are synchronous (collection only) — no per-call await needed.\n */\nexport interface SyncTransactionTableHandle<\n TRegistry extends SyncTableRegistry,\n TKey extends SyncTableName<TRegistry>,\n> {\n create: (input: SyncTableCreateInput<TRegistry, TKey>) => void;\n update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;\n delete: (entityKey: Record<string, string>) => void;\n /**\n * An **update-by-key with no local base row** (ADR-0022 addendum). Ordinary `update` requires the entity\n * to be present in the actor's local read model (it seeds the optimistic overlay and captures the base\n * server version); `updateBlind` skips that presence check and writes NO overlay — nothing appears in the\n * read model. Use it when the write target is deliberately EXCLUDED from your read shape (a write-only\n * flow, or an anonymity-scoped moderation write whose row streams only to a different projection), so there\n * is no local row to update and nothing to show optimistically.\n *\n * **Pessimistic-only.** The /unit expander is authoritative for the outcome, so a blind write is meaningful\n * only inside a `transaction({ mode: \"pessimistic\" })` block (or over a statically-pessimistic table). An\n * optimistic-routed blind write has nothing to converge and THROWS at enqueue.\n *\n * The acked journal row **retires without a synced echo** (no visible row ever converges for it), so it does\n * not linger — unlike the seed-a-phantom-row workaround this replaces, whose acked row + overlay lingered\n * forever behind the echo barrier. A `conflicted` blind write stays dischargeable via `discardConflict`; a\n * `rejected` one is surfaced via `onReject`, both with no overlay to clean up.\n */\n updateBlind: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;\n}\n\n/** The handle passed to a {@link SyncClient.transaction} callback: collecting table handles for the unit. */\nexport interface SyncTransaction<TRegistry extends SyncTableRegistry> {\n tables: { [TKey in SyncTableName<TRegistry>]: SyncTransactionTableHandle<TRegistry, TKey> };\n}\n\n/**\n * The result of a {@link SyncClient.transaction}. A `pessimistic` block carries the authoritative server\n * `acks` (each `acked` / `conflicted` / `rejected`); an `optimistic` block enqueues atomically and flushes\n * in the background, so its `acks` are empty.\n */\nexport interface SyncTransactionResult {\n acks: MutationAck[];\n}\n\n/** Minimal shape of a Drizzle select builder: inspectable via `.toSQL()` and awaitable for its rows. */\nexport interface DrizzleQueryBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {\n toSQL(): { sql: string; params: unknown[] };\n}\n\n/**\n * The builder callback for a guarded read (ADR-0021): it receives the client and returns a Drizzle\n * select builder. Reach relations through `c.views` / `c.drizzle` / a directly-imported synced table.\n */\nexport type GuardedQueryFn<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> = (\n client: SyncClient<TRegistry>,\n) => DrizzleQueryBuilder<TRows>;\n\n/**\n * A guarded query whose builder MAY embed a raw `sql` template fragment (ADR-0021). A raw fragment can\n * name a lazy relation as a bare/unquoted identifier the compiled-SQL scan cannot see, so declare those\n * relations in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads need no\n * `use` (the scan detects every relation): pass the builder callback directly to `client.query`.\n */\nexport interface GuardedRawQuerySpec<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> {\n use?: readonly SyncTableName<TRegistry>[];\n build: GuardedQueryFn<TRegistry, TRows>;\n}\n\n/**\n * Inputs to the read-path safety seam {@link SyncClient.prepareQuery}. The lazy relations a query reads\n * are detected by scanning the compiled `sql` (union with the optional explicit `use`), then activated.\n * Shared by the live React hooks and the non-live facade.\n */\nexport interface PrepareQueryInput<TRegistry extends SyncTableRegistry> {\n /** The compiled (parameterised) Drizzle SQL the query will run — the scan's ground-truth target. */\n sql: string;\n /** Lazy relations to also activate, beyond those scanned from `sql` — a pre-activation hint, not required. */\n use?: readonly SyncTableName<TRegistry>[];\n}\n\n/**\n * The narrow live-rows seam (ADR-0032 S2 §4) both client modes implement so the `@pgxsinkit/react` hooks\n * work against either. Input for a reactive subscription: the compiled SQL + params (from a Drizzle\n * builder's `.toSQL()` or a raw string) and the result's `pkColumns` (drives worker-side diff keying;\n * omit for a keyless query). The in-process client runs it directly over `pglite.live`; the worker-attached\n * client runs the live query in the worker and streams DIFFs across the bridge.\n */\nexport interface SubscribeLiveRowsInput {\n sql: string;\n params: readonly unknown[];\n /**\n * The unique output aliases to render the query's columns under so it is SAFE TO MATERIALISE, in the\n * compiled SQL's column order (one per output column). Drizzle emits no output aliases, so a JOIN whose\n * tables share a column name compiles to duplicate output names — which PGlite's `live` extension\n * refuses to materialise (`column \"title\" specified more than once`) and which silently collapse\n * same-named columns even in a plain query. When supplied, the seam wraps the query so every output\n * column gets its alias and rows come back KEYED BY THESE ALIASES; the consumer's row-mapper must read\n * by alias (the `@pgxsinkit/react` hooks do). Omit for a raw or non-colliding query — the seam then\n * leaves the SQL untouched and rows stay keyed by the underlying column names (backward-compatible).\n */\n fields?: readonly string[];\n /**\n * The result's PK columns — the diff-keying identity across the bridge (§4). Omit for a keyless query.\n * When {@link fields} is supplied the result columns are the aliases, so a PK column here must be named\n * by its ALIAS (the aliased result column), not the underlying source column.\n */\n pkColumns?: readonly string[];\n /**\n * Lazy relations (ADR-0021) to activate before the query runs — forwarded to the worker so it can\n * `prepareQuery` before registering the live query (the tab's own `prepareQuery` is a no-op against the\n * worker bridge). Ignored by the in-process client, whose `prepareQuery` already ran on the tab.\n */\n use?: readonly string[];\n}\n\n/** A handle to a live-rows subscription: the initial ordered snapshot plus an idempotent unsubscribe. */\nexport interface LiveRowsSubscription<TRow> {\n initialRows: TRow[];\n unsubscribe: () => void;\n}\n\nexport interface SyncClient<TRegistry extends SyncTableRegistry> {\n drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;\n pglite: ClientPGlite;\n views: RegistryViews<TRegistry>;\n tables: {\n [TKey in SyncTableName<TRegistry>]: SyncClientTableHandle<TRegistry, TKey>;\n };\n ready: Promise<void>;\n status: SyncRuntimeStatus;\n start: () => Promise<void>;\n stop: () => Promise<void>;\n /**\n * Wipe the entire local store (synced cache + overlay + journal) and close the handle\n * (ADR-0005). Refuses if mutations are still owed to the server unless `force` is set, so\n * it never silently drops un-flushed writes. Distinct from `stop()`, which only halts sync.\n * Runs under the single lifecycle slot (ADR-0035 decision 4): a concurrent export — or another\n * `destroy`/`discardEphemeral`/`dropReadCache` — rejects with a {@link LifecycleBusyError} rather\n * than interleaving the wipe with a running export.\n */\n destroy: (options?: { force?: boolean }) => Promise<void>;\n /**\n * Drop and rebuild the reconstructible synced read cache, preserving the overlay and\n * mutation journal (ADR-0006). The next sync refills it. Use to recover from a corrupt or\n * stale read cache without losing un-flushed writes. Runs under the single lifecycle slot\n * (ADR-0035 decision 4) — it drops and rebuilds the synced tables, so an export must not capture a\n * half-rebuilt cache; a concurrent export (or `destroy`/`discardEphemeral`) rejects with a\n * {@link LifecycleBusyError}.\n */\n dropReadCache: () => Promise<void>;\n flush: (table?: SyncTableName<TRegistry>) => Promise<void>;\n reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;\n retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;\n recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;\n readMutationDetails: (table?: SyncTableName<TRegistry>) => Promise<MutationDetail[]>;\n mutate: {\n create: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n input: SyncTableCreateInput<TRegistry, TKey>,\n ) => Promise<void>;\n update: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n patch: SyncTableUpdateInput<TRegistry, TKey>,\n ) => Promise<void>;\n delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;\n batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>) => Promise<void>;\n };\n /**\n * Discard a `conflicted` entity (ADR-0015): clear its conflicted journal entry and kept optimistic\n * Overlay, so the Read model falls back to the synced (server) value. Use when the user abandons a\n * stale edit instead of resolving it as a new write.\n */\n discardConflict: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n /**\n * Discard a `quarantined` entity (ADR-0006): clear its quarantined journal entry and kept optimistic\n * Overlay, so the Read model falls back to the synced (server) value. The rollback path for a write\n * the server permanently rejected — e.g. an RLS policy denial (42501) routed to quarantine. After the\n * discard the phantom optimistic row is gone and the entity accepts new mutations again (no longer\n * blocked behind the quarantined head). Symmetric to {@link SyncClient.discardConflict}; the overlay\n * is kept when another still-owed write depends on it. No-op for an entity with no quarantined entry.\n */\n discardQuarantined: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{ mutation: MutationDiagnostics }>;\n /**\n * The INSPECTION read surface (debug pages, REPLs, ad-hoc counts) — identical on the in-process and\n * worker-attached client (on the latter the statement runs in the worker). The statement runs raw\n * against the local store: it BYPASSES the mutation journal and optimistic overlay, and any write it\n * issues stays local and will NOT converge. For app data reads prefer the live-rows hooks /\n * {@link subscribeLiveRows} (or the guarded {@link query} family); reach for this only to look at the\n * store, not to read app state or mutate it.\n */\n rawQuery: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;\n /** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. */\n rawExec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;\n /**\n * Run a one-shot (non-live) typed **pure-Drizzle** query with the lazy-relation safety net (ADR-0021).\n * Pass the builder callback directly — pgxsinkit scans the compiled SQL and activates + awaits every\n * lazy relation it reads (FROM, JOIN, subquery, WHERE) before it runs, and the tripwire rejects any\n * lazy relation the SQL still references but that is not active, so the result is never silently\n * empty/stale. The guaranteed-safe alternative to a bare `client.drizzle` read. If the builder embeds\n * a raw `sql` template fragment, use {@link queryRaw} and declare the lazy relations in `use`.\n */\n query: <TRows extends readonly unknown[]>(build: GuardedQueryFn<TRegistry, TRows>) => Promise<TRows>;\n /** {@link query} returning the first row, or null when empty. */\n queryRow: <TRows extends readonly unknown[]>(\n build: GuardedQueryFn<TRegistry, TRows>,\n ) => Promise<TRows[number] | null>;\n /**\n * {@link query} for a builder that embeds a raw `sql` template fragment (ADR-0021). The compiled-SQL\n * scan can miss a lazy relation named as a bare/unquoted identifier inside raw SQL, so declare those\n * in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads should use\n * {@link query} instead (no `use` needed).\n */\n queryRaw: <TRows extends readonly unknown[]>(spec: GuardedRawQuerySpec<TRegistry, TRows>) => Promise<TRows>;\n /** {@link queryRaw} returning the first row, or null when empty. */\n queryRawRow: <TRows extends readonly unknown[]>(\n spec: GuardedRawQuerySpec<TRegistry, TRows>,\n ) => Promise<TRows[number] | null>;\n /**\n * Activate one or more lazy relations (ADR-0021): open their consistency-group subscription if held\n * out of the eager boot, resolving once their initial sync completes. Idempotent — eager or\n * already-started relations resolve immediately. Use to pre-activate before a raw/`client.drizzle`\n * read, or as the manual escape hatch the tripwire points to.\n */\n ensureSynced: (keys: readonly SyncTableName<TRegistry>[]) => Promise<void>;\n /**\n * Whether a relation's group has started and hydrated (ADR-0021). False for a still-dormant `lazy`\n * relation; true for eager relations once boot completes (and always when sync is disabled).\n */\n isSynced: (key: SyncTableName<TRegistry>) => boolean;\n /**\n * Revert a `lazy` relation to dormant (ADR-0021 §2) — the inverse of on-demand activation: stop its\n * consistency group's stream, clear any persisted `lazy + persistent` activation (so the next boot\n * holds it dormant again), and clean-truncate its local read cache. A later reference re-activates it\n * from scratch. Refuses when the relation is `eager` (always-on, would immediately re-sync) or owes\n * the server unsettled writes (the truncate would drop them — flush or discard first). The reclaim\n * primitive a host wires to navigation/idle for a rarely-opened lazy view; for an `ephemeral`\n * relation, idle-eviction is otherwise automatic at session end.\n */\n desync: (key: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * Drop an **ephemeral** relation's local rows and revert it to dormant (ADR-0021) — the narrow,\n * scoped twin of {@link desync}. It runs the identical group-teardown machinery (stop the group stream,\n * clear the persisted lazy activation, reset the persisted subscription, clean-truncate every member),\n * but under a STRICTER gate: EVERY member of the relation's consistency group must be `retention:\n * \"ephemeral\"` — it refuses (naming the offender) if any member is persistent. Where a `desync` from one\n * tab reverts the shared group for every attached tab (the SharedWorker footgun), `discardEphemeral` is\n * safe under multi-tab because an ephemeral window is per-delivery-session and inherently single-consumer\n * — nothing durable, and no other tab, depends on it. Refuses an `eager` relation (always-on, would\n * immediately re-sync) and a group that owes the server unsettled writes, exactly as `desync` does. The\n * finalize primitive for a secure-delivery window: drop the local rows at session end without touching a\n * durable relation. Note the drop is local-lifecycle only: a later re-subscription re-activates the lazy\n * group and re-streams whatever the SERVER still serves — post-finalize non-redelivery is the server\n * gate's guarantee (e.g. a consumed server-owned cursor), not this method's. Runs under the single\n * lifecycle slot (ADR-0035 decision 4): a concurrent export (or `destroy`/`dropReadCache`) rejects with a\n * {@link LifecycleBusyError} rather than interleaving the cache truncate with a running export.\n */\n discardEphemeral: (key: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * The read-path safety seam (ADR-0021): scan the compiled `sql` for the lazy relations it reads\n * (∪ the optional `use`), activate them, and await their initial sync — so a lazy relation\n * auto-activates on *any* reference (FROM, JOIN, subquery, WHERE). Resolves once it is safe to run the\n * query; a backstop throws {@link LazyRelationNotActivatedError} only if a referenced relation could\n * not be activated. Exposed for the React live hooks (which own their query build); `query`/`queryRow`\n * are the higher-level non-live wrappers. Raw, non-Drizzle SQL is out of scope — pass `use`, or\n * `ensureSynced` first.\n */\n prepareQuery: (input: PrepareQueryInput<TRegistry>) => Promise<void>;\n /**\n * Author an atomic write-**unit** (ADR-0022 §2). The callback receives collecting table handles; every\n * mutation it issues is tagged into one unit and enqueued atomically when the callback returns.\n *\n * - `mode: \"pessimistic\"` — **server-authoritative**: the unit flush-routes to the authoritative endpoint\n * and this call resolves only once the server has decided. The result's `acks` carry each member's\n * outcome — `acked`, `conflicted` (overlay kept, ADR-0015), or `rejected` (overlay auto-discarded for\n * the whole unit, surfaced via `onReject`, ADR-0022 §4). Throws on transport failure (overlay kept). A\n * pessimistic block may also issue {@link SyncTransactionTableHandle.updateBlind} — an update-by-key with\n * no local base row and no overlay, for a write target excluded from the actor's read shape.\n * - `mode: \"optimistic\"` — an atomic batch enqueue that flushes in the background (empty `acks`).\n */\n transaction: (\n options: { mode: WriteMode },\n run: (tx: SyncTransaction<TRegistry>) => void | Promise<void>,\n ) => Promise<SyncTransactionResult>;\n /**\n * Per-group readiness (ADR-0032 decision 6): a promise resolving the moment the given table's\n * consistency group is up-to-date. Resolves immediately for an already-ready (or sync-disabled)\n * group; stays pending for a still-dormant `lazy` relation until it is activated and caught up. The\n * opt-in progressive-paint signal beside the all-eager-groups `ready` gate. `status.groups` carries the\n * same readiness as a synchronous snapshot.\n */\n groupReady: (table: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * The live-rows seam (ADR-0032 S2 §4): register a reactive query and receive its initial ordered\n * snapshot plus subsequent updates via `onRows`. The React live hooks consume THIS (not `pglite.live`\n * directly), so they run unchanged against both the in-process client (which implements it over\n * `pglite.live`) and the worker-attached client (which implements it over the bridge). Prefer the\n * higher-level `@pgxsinkit/react` hooks; this is the lower-level primitive they build on.\n */\n subscribeLiveRows: <TRow extends Record<string, unknown> = Record<string, unknown>>(\n input: SubscribeLiveRowsInput,\n onRows: (rows: TRow[]) => void,\n ) => Promise<LiveRowsSubscription<TRow>>;\n /**\n * Boot observability (ADR-0034): the engine's most recent COMPLETED boot report, or `null` before the\n * first boot finalizes (and after a `stop()`/`destroy()` that preceded initial sync). Pull — so a\n * late-attaching tab can read a boot that predates it; in worker mode it round-trips to the worker's\n * stored report. The push counterpart is the `onBootReport` client option.\n */\n bootReport: () => Promise<BootReport | null>;\n /**\n * Take a **store backup** (ADR-0035): a full-fidelity, PGlite-restorable tarball of the whole local\n * store — synced cache, Overlay, and Mutation journal (unflushed writes included) — via PGlite's\n * `dumpDataDir`. Taken LIVE (a `CHECKPOINT` serialised behind engine work, then the dump; no engine\n * suspension, no tab disruption), so it never blocks and is the only lossless export an offline device\n * with unflushed writes can take. Awaits engine-ready rather than rejecting during boot, then runs under\n * the single lifecycle slot: a second export (or, later, `destroy`/`discardEphemeral`) attempted while\n * one is in flight rejects immediately with a {@link LifecycleBusyError} — retry once it settles.\n * Resolves to the artefact `File` plus an {@link ExportReport} (phase timings + a diagnostics snapshot).\n */\n exportStore: (options?: StoreExportOptions) => Promise<StoreExportResult>;\n /**\n * Take a **diagnostic dump** (ADR-0035): human-readable SQL of EVERYTHING the store holds — synced tables,\n * the `_overlay`/`_mutations` journal (unflushed writes included — the evidence a diagnostic exists for),\n * the `pgxsinkit` metadata schema, the read-model views, and the reconcile functions/triggers — via\n * `pg_dump`. To keep `pg_dump`'s `DEALLOCATE ALL` away from the live engine, the dump runs against a\n * memory-backed THROWAWAY clone booted from a live datadir dump (ADR-0035 addendum): the running store is\n * never suspended and no tab is disrupted. Awaits engine-ready rather than rejecting during boot, then\n * runs under the single lifecycle slot — a concurrent export (or `destroy`/`discardEphemeral`) rejects\n * immediately with a {@link LifecycleBusyError}. Resolves to the SQL `File` (`application/sql`) plus a\n * {@link DiagnosticDumpReport} (phase timings + a diagnostics snapshot). Active ephemeral (`pg_temp`)\n * clusters are absent by construction (ADR-0035 decision 5 — `pg_dump` ignores temp objects).\n */\n exportDiagnostics: (options?: DiagnosticExportOptions) => Promise<DiagnosticExportResult>;\n /**\n * Take a **data export** (ADR-0035): the PORTABLE artefact — the synced tables and the enum types they\n * depend on, schema + data, nothing of pgxsinkit's machinery — as SQL loadable into a vanilla Postgres. It\n * is a generated enum DDL header concatenated ahead of `pg_dump -t <table> ... --no-owner` (one `-t` per\n * physical synced table; ephemeral/read-projection entries excluded by construction), run against the same\n * memory-backed THROWAWAY clone the diagnostic dump uses — so the live engine is never touched.\n *\n * Unlike the other two exports it GUARDS the journal (decision 3): a strict export requires a DRAINED\n * journal — all mutation counts zero, including `acked` writes whose synced echo has not landed (they live\n * only in the Overlay). The drain flushes drainable rows and awaits convergence up to\n * `drainJournal.timeoutMs` (default `15_000`); non-drainable states (`failed`/`quarantined`/`conflicted`)\n * fail FAST with a {@link DataExportDrainError} carrying the diagnostics. `drainJournal: false` is the\n * escape hatch — export synced state as-is (unflushed writes absent; `report.escapeHatch` records it). An\n * offline device with a clean journal exports strictly and instantly; one with a dirty journal cannot\n * produce a strict export (its lossless option is `exportStore`).\n *\n * Awaits engine-ready rather than rejecting during boot, then runs the whole drain+dump under the single\n * lifecycle slot — a concurrent export (or `destroy`/`discardEphemeral`) rejects with a\n * {@link LifecycleBusyError}. Resolves to the SQL `File` (`application/sql`) plus a {@link DataExportReport}\n * (drain + clone-pipeline phase timings, the applied `-t` table list, and the escape-hatch flag).\n */\n exportData: (options?: DataExportOptions) => Promise<DataExportResult>;\n}\n\nexport type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind };\n\n/**\n * The structured-clone-safe subset of PGlite's `QueryOptions` the inspection surface carries. Kept\n * narrow ON PURPOSE: on a worker-attached client the options object crosses the bridge via\n * `postMessage`, so function-valued options (`parsers`, `serializers`, `onNotice`) can never be part\n * of this contract. `rowMode: \"array\"` is what `@electric-sql/pglite-repl` asks for on every exec.\n */\nexport interface RawQueryOptions {\n rowMode?: \"object\" | \"array\";\n}\n\n/** The `{ query, exec }` duck `@electric-sql/pglite-repl` drives, backed by a client's inspection surface. */\nexport interface ReplInspectionSurface {\n query: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;\n exec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;\n}\n\n/**\n * Shape a {@link SyncClient}'s inspection surface (`rawQuery`/`rawExec`) as the `{ query, exec }` duck\n * `@electric-sql/pglite-repl` needs. Identical on the in-process and worker-attached client — on the latter\n * each statement routes through the worker bridge, so the REPL works even though `client.pglite` is\n * unavailable. Cast the result at the `<Repl pg={...}>` prop (the REPL types the prop as a full `PGlite`).\n * The surface is registry-independent, so it accepts any client's `rawQuery`/`rawExec` pair.\n */\nexport function replAdapter(\n client: Pick<SyncClient<SyncTableRegistry>, \"rawQuery\" | \"rawExec\">,\n): ReplInspectionSurface {\n return {\n // Thread the options through UNMODIFIED — the REPL execs with `{ rowMode: \"array\" }` and renders\n // each row with `row.map`, so dropping the options here breaks every REPL statement.\n query: (sql, params, options) => client.rawQuery(sql, params, options),\n exec: (sql, options) => client.rawExec(sql, options),\n };\n}\n\nexport async function createSyncClient<const TRegistry extends SyncTableRegistry>(\n options: CreateSyncClientOptions<TRegistry>,\n): Promise<SyncClient<TRegistry>> {\n const status: SyncRuntimeStatus = {\n phase: \"booting\",\n isRunning: false,\n };\n\n let resolveReady!: () => void;\n const ready = new Promise<void>((resolve) => {\n resolveReady = resolve;\n });\n\n if (options.pgliteInstance && options.precreatedPglite) {\n throw new Error(\n \"createSyncClient: pass at most one of `pgliteInstance` or `precreatedPglite` — they claim different ownership of the post-create boot steps (schema exec, prepare hooks, store-version reconcile).\",\n );\n }\n\n // Restore (ADR-0035 decision 6) owns the store's CREATION — the backup tarball is a `loadDataDir` seed on\n // the fresh store — so it cannot coexist with a caller-supplied instance (which claims the store already\n // exists and is provisioned). Fail loudly rather than silently ignore one.\n const restoreBoot = options.restoreFrom != null;\n if (restoreBoot && (options.pgliteInstance || options.precreatedPglite)) {\n throw new Error(\n \"createSyncClient: `restoreFrom` is mutually exclusive with `pgliteInstance` / `precreatedPglite` — restore boots a brand-new store from the backup (a create-time `loadDataDir` seed), so it cannot adopt a caller-owned instance. Drop the instance option, or drop `restoreFrom` (ADR-0035).\",\n );\n }\n\n // Restore ALWAYS boots offline (ADR-0035 decision 6), regardless of `syncEnabled`/`autoSync` or anything\n // captured in the backup: no shape streams, no read fetch, no flush, no convergence passes. The app deals\n // with the quarantined journal, then a subsequent NORMAL boot brings sync online. Restore wins over an\n // explicit online option — warn on the debug rail so the override is visible rather than silent.\n if (restoreBoot && (options.syncEnabled === true || options.autoSync != null)) {\n syncDebug(\"boot restore forces offline — ignoring the online sync option for this restore boot\", {\n syncEnabled: options.syncEnabled === true,\n autoSync: options.autoSync != null,\n });\n }\n const syncEnabled = restoreBoot ? false : (options.syncEnabled ?? true);\n // ADR-0032 S4 overlap flag, computed once up front so the boot report and the prefetch gate agree.\n const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;\n\n // Boot observability (ADR-0034): build a structured report across the boot, finalized once at initial\n // sync. Created FIRST so its monotonic anchor precedes every timed phase (including the PGlite create).\n const bootReportBuilder: BootReportBuilder = createBootReportBuilder({\n mode: options.bootMode ?? \"in-process\",\n freshStore: options.freshStore === true,\n overlapPrefetch,\n registryFingerprint: fingerprintRegistry(options.registry),\n });\n // The single engine lifecycle slot (ADR-0035 decision 4). The three exports plus the destructive\n // lifecycle ops — `destroy()`, `discardEphemeral()`, and `dropReadCache()` — all serialise through it,\n // so a wipe/rebuild can never interleave a running export (nor vice versa): the slot rejects the second\n // entrant with a typed LifecycleBusyError in either direction.\n const lifecycleSlot = createLifecycleSlot();\n\n let finalizedBootReport: BootReport | null = null;\n const finalizeBootReport = () => {\n if (finalizedBootReport) return;\n finalizedBootReport = bootReportBuilder.finalize();\n options.onBootReport?.(finalizedBootReport);\n };\n\n // The testing marker (ADR-0036 decision 3), read once off the options object: `\"memory\"` selects the\n // memory backend for a client-owned create AND acknowledges the BYO seam; `\"acknowledged\"` only unlocks\n // the BYO refusal. Absent for every production consumer — the marker rides in only via\n // `@pgxsinkit/client/testing`, never named in a public type.\n const testStoreMarker = readTestStoreMarker(options);\n const backendOverride = testStoreMarker === \"memory\" ? (\"memory\" as const) : undefined;\n\n // Bind the create options once for the two client-owned create paths (fresh `storePath`, and the\n // `precreatedPglite` reject-fallback), so both consume the same pre-warm + resolve the same backend.\n const createClientOptions: CreateClientPGliteOptions = {\n ...(options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {}),\n ...(backendOverride ? { backendOverride } : {}),\n // Restore (ADR-0035 decision 6): seed the fresh store from the backup via `loadDataDir`. Restore is\n // mutually exclusive with the BYO instance seams (checked above), so it only ever rides a client-owned\n // create — never the adopt paths, which leave `restoreFrom` unread.\n ...(restoreBoot ? { restoreFrom: options.restoreFrom } : {}),\n };\n const fallbackStorePath = options.storePath ?? \"pgxsinkit-overlay-v1\";\n\n // Fresh-target gate (ADR-0035 decision 6): restore refuses a store that already exists — it boots a\n // brand-new store and never overlays a live one. Checked BEFORE the create so we never touch (let alone\n // half-write) an existing datadir; the memory test lane is fresh by construction, so this is a no-op there.\n if (restoreBoot) {\n if (await storeTargetExists(fallbackStorePath, backendOverride)) {\n throw new RestoreTargetExistsError(fallbackStorePath);\n }\n }\n // Time a client-owned `createClientPGlite` into `phases.pgliteCreateMs`; an ADOPTED store (spare or\n // caller-supplied) leaves it `null` (create ran elsewhere — see the provision block below).\n const timedCreate = async (): Promise<ClientPGlite> => {\n const startedAt = performance.now();\n const created = await createClientPGlite(fallbackStorePath, createClientOptions);\n bootReportBuilder.setPgliteCreateMs(performance.now() - startedAt);\n return created;\n };\n\n // Refuse a caller-owned instance that is PROVABLY non-persistent (ADR-0036 decision 4), unless a testing\n // acknowledgment is present. `classifyNonPersistentDataDir` inspects the instance's own dataDir (the\n // `ClientPGlite` interface hides it, so via a narrow cast) — the two provably-non-persistent shapes are\n // an undefined dataDir (PGlite's in-memory default) and an explicit memory store. Checked AFTER a\n // successful resolution of the BYO promise, so the refusal PROPAGATES rather than being swallowed by the\n // `precreatedPglite` reject-fallback below (which only catches a create that never produced a store).\n const refuseIfNonPersistent = (instance: ClientPGlite): void => {\n if (testStoreMarker !== undefined) return; // a deliberate test store — acknowledged.\n const observed = classifyNonPersistentDataDir((instance as { dataDir?: string }).dataDir);\n if (observed !== null) throw new NonPersistentStoreError(observed);\n };\n\n let pglite: ClientPGlite;\n // Whether the boot adopted the caller's `precreatedPglite` (vs. falling back to a fresh create) — gates\n // whether the provision stamp is honoured (ADR-0034).\n let adoptedPrecreated = false;\n if (options.pgliteInstance) {\n // The caller created AND provisioned this store; the client runs NONE of the post-create boot steps\n // (schema/prepare/reconcile) — see the `pgliteInstance` JSDoc. No create here → `pgliteCreateMs` null.\n refuseIfNonPersistent(options.pgliteInstance);\n pglite = options.pgliteInstance;\n } else if (options.precreatedPglite) {\n // The caller created the raw store eagerly via `createClientPGlite`; the client still owns every\n // post-create step below. A REJECTED eager create must never fail the boot: fall back to the normal\n // `storePath` create, so the pattern stays a pure accelerator. Reify the promise's outcome first, THEN\n // branch — so the {@link NonPersistentStoreError} refusal runs on a SUCCESSFULLY resolved instance,\n // outside any catch, and PROPAGATES (never swallowed by the reject-fallback, which is only for a create\n // that never produced a store).\n const outcome = await options.precreatedPglite.then(\n (instance) => ({ ok: true as const, instance }),\n (error: unknown) => ({ ok: false as const, error }),\n );\n if (outcome.ok) {\n refuseIfNonPersistent(outcome.instance);\n pglite = outcome.instance;\n adoptedPrecreated = true;\n } else {\n syncDebug(\"boot precreated pglite rejected — falling back to storePath create\", {\n error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),\n });\n pglite = await timedCreate();\n }\n } else {\n pglite = await timedCreate();\n }\n\n // Provision block (ADR-0034): when the boot adopted a pre-provisioned store and the provisioner stamped\n // its create timing, report the spare's initdb cost + how long it sat ready, and leave `pgliteCreateMs`\n // null (the create was paid at provision time, off this boot's clock).\n if (adoptedPrecreated && options.provisionStamp) {\n const stamp = await options.provisionStamp.catch(() => null);\n if (stamp) {\n bootReportBuilder.setProvision({\n initdbMs: stamp.initdbMs,\n provisionedMsBeforeBoot: Math.max(0, bootReportBuilder.bootStartPerf - stamp.provisionReadyAt),\n });\n }\n }\n\n // Attach the sync engine explicitly, over the already-created instance, on ALL three provenance paths\n // (pgliteInstance, precreatedPglite, storePath) — ADR-0032 S1. The engine is no longer a create-time\n // extension, so the raw store (a `createClientPGlite` mint, or a caller's own instance) carries no\n // `electric` namespace until this point; the property assignment gives `ClientPGlite` its exact former\n // structural shape (live + electric) so every `pglite.electric.…` call site is unchanged. It is attached\n // BEFORE the schema/prepare steps below so a `prepareLocalDb` hook sees the same `.electric` it did when\n // the extension provided it at create time. `engine.close` (the former extension close hook — abort every\n // shape stream) is kept private to this client and run explicitly by `stop`/`destroy` at the same moment\n // `pglite.close()` used to trigger it.\n const engine: SyncEngine = await createSyncEngine(pglite);\n (pglite as { electric: SyncEngine[\"namespace\"] }).electric = engine.namespace;\n\n // Whether the read path's first initial sync has completed, so a recovery from `auth-needed` returns to\n // the right steady-state phase (`ready` if already caught up, else `syncing`).\n let initialSyncCompleted = false;\n // Why the runtime is `degraded` (#4). A read-stream error degraded clears on the next successful batch; a\n // commit-failure degraded is sticky (a fetch can succeed while applies still fail), so a bare\n // `onSyncActivity` must not clear it.\n let degradedReason: \"stream\" | \"commit\" | null = null;\n\n // ─── Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003) ─────────────────────────────────────\n // On a PROVABLY-FRESH store (the caller's `freshStore` hint — a claimed schemaless spare) the shape\n // catch-up needs none of the local boot phases, so start it NOW and gate its commits on `dbReady`, which\n // we resolve once schema exec + journal recovery + store-version reconcile complete. The network then\n // overlaps those phases instead of running strictly after them. Gated to the schema-owning paths (the\n // `pgliteInstance` path runs no schema step, so it has nothing to hide); warm stores keep the exact\n // sequential path. See the `freshStore` option's JSDoc for who sets the hint (the board's claim path).\n // (`overlapPrefetch` is computed once up front — see the boot-report builder above.)\n let openDbGate: () => void = () => {};\n const dbReady = overlapPrefetch\n ? new Promise<void>((resolve) => {\n openDbGate = resolve;\n })\n : null;\n\n // The sync-start options, built once and used by BOTH the overlap early-start and the sequential start —\n // the only per-call difference is the promoted-lazy set (empty on a fresh store) and the overlap gate.\n const buildStartOptions = (promotedGroups: ReadonlySet<string>): Parameters<typeof startConfiguredSync>[1] => ({\n syncConfig: buildSyncConfigFromRegistry(options.registry, options.electricUrl),\n registry: options.registry,\n promotedGroups,\n ...(dbReady ? { dbReady } : {}),\n // Boot observability (ADR-0034): the collector opens a per-boot-group accumulator (rows/requests/fetch/\n // apply wall) for the eager + promoted groups; lazy on-demand starts get none, so they never enter the report.\n bootCollector: bootReportBuilder,\n // Persist a durable lazy group's activation on first on-demand start, so the next boot promotes it.\n onLazyActivated: (groupKey) => {\n void writeLazyGroupActivation(pglite, options.registry, groupKey);\n },\n // The read path resolves the token per request (ADR-0013), not frozen at boot — so a long-lived session\n // never wedges on JWT expiry. Read and write share one token lifecycle.\n ...(options.getAuthToken || options.requestHeaders\n ? {\n shapeHeaders: buildShapeHeaders({\n ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),\n ...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),\n }),\n }\n : {}),\n ...(options.onTableInitialSync ? { onTableInitialSync: options.onTableInitialSync } : {}),\n // Per-group readiness (ADR-0032 decision 6): mirror each group's catch-up into `status.groups` and\n // re-emit, so an app can drive progressive per-group paint off `status` (and `client.groupReady`).\n onGroupReady: (groupKey) => {\n status.groups = { ...(status.groups ?? {}), [groupKey]: true };\n options.onStatusChange?.(status);\n },\n onInitialSync: () => {\n initialSyncCompleted = true;\n status.phase = \"ready\";\n options.onStatusChange?.(status);\n // Boot complete: the first initial sync landed and `ready` is about to resolve. One monotonic stamp\n // closes the boot rail opened by `boot pglite.create` (the stamp itself is the number).\n syncDebug(\"boot client ready\");\n // Boot observability (ADR-0034): finalize the report at exactly this moment — the `boot client ready`\n // rail line — and fire the one-shot `onBootReport` push. Idempotent, so the sync-disabled path's own\n // finalize below never double-fires it.\n finalizeBootReport();\n resolveReady();\n },\n onSyncError: (error) => {\n // A sync commit exhausted its retries (ADR-0009 decision 5): go degraded and surface it, rather than\n // letting the read cache silently diverge from the server. Sticky (see below).\n status.phase = \"degraded\";\n degradedReason = \"commit\";\n status.lastError = error.message;\n options.onStatusChange?.(status);\n options.onSyncError?.(error);\n },\n // #4: a terminal/transient NON-auth read-stream error → `degraded`, so the runtime never keeps reporting\n // healthy while the read stream has stalled. Does not override the more-actionable `auth-needed`, nor a\n // commit-failure degraded. Cleared on the next successful batch below.\n onReadStreamError: (error) => {\n // Never mask the more-actionable auth-needed, nor a sticky commit-failure degraded (its lastError is\n // the more serious signal — a stream blip must not overwrite it).\n if (status.phase === \"auth-needed\") return;\n if (status.phase === \"degraded\" && degradedReason === \"commit\") return;\n // Enter, or refresh, a stream-degraded status. Refreshing keeps `lastError` pointing at the most\n // recent stream fault (and re-emits) rather than freezing on the first one, so a stream that fails one\n // way then another reports the current cause (observability).\n status.phase = \"degraded\";\n degradedReason = \"stream\";\n status.lastError = error.message;\n options.onStatusChange?.(status);\n },\n // Clear a recoverable status (auth-needed, or a read-stream degraded) the moment a batch is delivered\n // again. A commit-failure degraded is NOT cleared here — a fetch can succeed while applies keep failing,\n // so only `onSyncError` clearing (a clean commit) would lift it.\n onSyncActivity: () => {\n if (status.phase === \"auth-needed\" || (status.phase === \"degraded\" && degradedReason === \"stream\")) {\n degradedReason = null;\n status.phase = initialSyncCompleted ? \"ready\" : \"syncing\";\n options.onStatusChange?.(status);\n }\n },\n // ADR-0013 Phase 3: surface a persistent read-path auth failure as a distinct `auth-needed` status (the\n // app prompts re-login) while the stream keeps retrying for a fresh token. Only wired when a token\n // provider exists — without one there is no auth lifecycle to track.\n ...(options.getAuthToken\n ? {\n onAuthError: () => {\n if (status.phase !== \"auth-needed\") {\n status.phase = \"auth-needed\";\n options.onStatusChange?.(status);\n }\n },\n }\n : {}),\n });\n\n // Overlap: kick the shape streams off BEFORE schema exec (they buffer catch-up into the memory inbox,\n // commits gated on `dbReady`). A fresh store has no persisted lazy activations and no subscriptions to\n // reset, so both DB reads the sequential path makes first are skipped here.\n let earlySync: ReturnType<typeof startConfiguredSync> | null = null;\n let earlySyncStartedAt = 0;\n if (overlapPrefetch) {\n status.isRunning = true;\n status.phase = \"syncing\";\n options.onStatusChange?.(status);\n earlySyncStartedAt = performance.now();\n earlySync = startConfiguredSync(\n pglite as unknown as Parameters<typeof startConfiguredSync>[0],\n buildStartOptions(new Set()),\n );\n }\n\n if (!options.pgliteInstance) {\n if (options.prepareLocalDbBeforeSchema) {\n const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;\n await bootReportBuilder.phase(\"prepare\", \"boot prepare(before-schema)\", () => prepareBeforeSchema(pglite));\n }\n\n const schemaSql = generateLocalSchemaSql(options.registry);\n await bootReportBuilder.phase(\"schemaExec\", \"boot local schema\", () => pglite.exec(schemaSql));\n\n if (options.prepareLocalDb) {\n const prepareLocalDb = options.prepareLocalDb;\n await bootReportBuilder.phase(\"prepare\", \"boot prepare(local-db)\", () => prepareLocalDb(pglite));\n }\n }\n\n // The write path's headers are the shared base plus the write-only overrides (region/DB-affinity):\n // `{...requestHeaders, ...writeRequestHeaders}`. The read/shape path keeps `requestHeaders` alone\n // (below), so `writeRequestHeaders` never reach reads — the two ingress points pin independently.\n const writePathHeaders =\n options.requestHeaders || options.writeRequestHeaders\n ? { ...(options.requestHeaders ?? {}), ...(options.writeRequestHeaders ?? {}) }\n : undefined;\n\n const mutationRuntime = createMutationRuntime({\n db: pglite,\n registry: options.registry,\n writeUrl: options.writeUrl,\n ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),\n ...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),\n ...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),\n ...(options.onQuarantine ? { onQuarantine: options.onQuarantine } : {}),\n ...(options.onConflict ? { onConflict: options.onConflict } : {}),\n ...(options.onReject ? { onReject: options.onReject } : {}),\n });\n\n // Reclaim any in-flight mutations interrupted by a previous shutdown (ADR-0005), then\n // reconcile the local store against the current registry fingerprint before sync starts\n // (ADR-0006). Skipped when the caller supplies their own pglite (they own its schema).\n await bootReportBuilder.phase(\"journalRecovery\", \"boot journal recovery\", () => mutationRuntime.recoverSending());\n\n // Restore-boot quarantine (ADR-0035 decision 6): the moment a store is booted FROM a backup, every\n // non-terminal recovered journal row (`pending`/`sending`/`failed`) is parked in `quarantined` so nothing\n // recovered auto-flushes — the write path has no `mutationId` dedupe ledger, making replay unsafe on\n // last-write-wins tables (silent stale reverts) and colliding on a recreated PK. Runs ONLY on the restore\n // boot (loadDataDir happens exactly once); a subsequent normal boot of the persisted store never re-runs\n // it. Placed AFTER `recoverSending` (which lifts any `sending` back to `pending`) so a single pass over\n // pending/sending/failed catches the lot. The app then inspects `diagnostics()` and releases/discards them.\n if (restoreBoot) {\n await mutationRuntime.quarantineRecovered();\n }\n\n let versionEvent: LocalStoreVersionEvent | null = null;\n\n // Registry-fingerprint mismatch on restore (ADR-0035 decision 6): an old backup restored against a NEWER\n // registry needs NO special handling — the existing local-schema-evolution path (ADR-0006) owns it, and\n // restore composes with it for free. On this restore boot the quarantine above ran FIRST, so every\n // recovered row now counts toward `owedMutations` (pending+sending+failed+quarantined) inside\n // `rebuildReadCacheOrDefer`: a stale fingerprint therefore DEFERS the read-cache rebuild rather than\n // dropping the quarantined writes, exactly as it would for any store that owes work. The rebuild completes\n // on a later boot once the app has released/discarded the quarantine and drained the journal.\n if (!options.pgliteInstance) {\n versionEvent = await bootReportBuilder.phase(\"storeVersionReconcile\", \"boot store-version reconcile\", () =>\n reconcileLocalStoreVersion({\n db: pglite,\n registry: options.registry,\n runtime: mutationRuntime,\n ...(options.onSchemaChange ? { onSchemaChange: options.onSchemaChange } : {}),\n }),\n );\n }\n\n const drizzleDb = createDrizzleDatabase(pglite, buildSchema(options.registry));\n // Static index of the registry's lazy relations (ADR-0021), driving the read-path safety net.\n const lazyGuardIndex = buildLazyGuardIndex(options.registry);\n\n let sync: Awaited<ReturnType<typeof startConfiguredSync>> | null = null;\n let convergenceDriver: ConvergenceDriver | null = null;\n\n status.isRunning = true;\n\n // Open the overlap commit gate now the local store is ready (schema exec + journal recovery + reconcile\n // done): the catch-up the streams prefetched during those phases now drains in one commit train. A no-op\n // on the sequential path (`openDbGate` is the empty default there).\n openDbGate();\n\n if (syncEnabled) {\n if (earlySync) {\n // Overlap path: the shape streams have been prefetching since before schema exec; adopt the handle\n // (it resolves as soon as the streams are subscribed — catch-up drains via the gate just lifted, and\n // `onInitialSync` still gates `ready` on a fully-consistent first paint). The construction was kicked\n // off before schema exec, so time it here (concurrent-segment wall) into `phases.syncStartMs`.\n sync = await earlySync;\n bootReportBuilder.setSyncStartMs(performance.now() - earlySyncStartedAt);\n bootReportBuilder.markSyncStartDone();\n } else {\n // Sequential path (warm store / no fresh hint): the exact pre-S4 ordering — reset any rebuilt\n // subscriptions, promote durable lazy groups, then start (catch-up strictly after the local phases).\n // After a read-cache rebuild the Electric subscription bookkeeping is stale (it would believe the\n // dropped shapes are still caught up and never backfill), so reset every shape subscription to force a\n // fresh re-stream (ADR-0006).\n const resetKeys =\n versionEvent?.status === \"rebuilt\"\n ? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]\n : options.resetSubscriptionKeys;\n await resetSubscriptionsIfRequested(pglite, resetKeys);\n\n status.phase = \"syncing\";\n options.onStatusChange?.(status);\n\n // Promote any `lazy + persistent` group activated on a previous boot back into the eager set\n // (ADR-0021 §2); the sync engine does no DB read of its own.\n const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);\n\n sync = await bootReportBuilder.phase(\"syncStart\", \"boot sync start\", () =>\n startConfiguredSync(\n pglite as unknown as Parameters<typeof startConfiguredSync>[0],\n buildStartOptions(promotedGroups),\n ),\n );\n bootReportBuilder.markSyncStartDone();\n }\n } else {\n status.phase = \"ready\";\n options.onStatusChange?.(status);\n // Sync disabled: there is no `onInitialSync` gate, but boot IS complete — finalize the report at the\n // same moment `ready` resolves (ADR-0034). Idempotent with the sync path's finalize.\n finalizeBootReport();\n resolveReady();\n }\n\n // Restore boots offline (ADR-0035 decision 6): never stand up the convergence driver on a restore boot,\n // so an `autoSync` trigger the caller passed (even an online one) drives NO flush/reconcile passes — the\n // recovered journal is quarantined and must stay put until the app releases it and a normal boot goes\n // online. On every other boot the driver behaves exactly as before.\n if (options.autoSync && !restoreBoot) {\n convergenceDriver = createConvergenceDriver({\n client: {\n flush: () => mutationRuntime.flush(),\n reconcile: () => mutationRuntime.reconcile(),\n },\n trigger: options.autoSync,\n ...(options.onConvergencePass ? { onPass: options.onConvergencePass } : {}),\n });\n\n // Start driving convergence once the initial sync is ready, so a pass never races the\n // first shape load. stop()/destroy() halt it.\n void ready.then(() => convergenceDriver?.start());\n }\n\n // Event-driven convergence: the moment a mutation is enqueued, ask the driver to run a pass so the\n // write flushes immediately rather than waiting for the trigger's next interval tick. This is what\n // lets the interval be a rare fallback (and so run far less often). No-op when `autoSync` is off — the\n // caller drives `flush`/`reconcile` itself.\n const requestConvergence = () => convergenceDriver?.requestPass();\n const mutate: SyncClient<TRegistry>[\"mutate\"] = {\n create: async (table, input) => {\n await mutationRuntime.create(table, input);\n requestConvergence();\n },\n update: async (table, entityKey, patch) => {\n await mutationRuntime.update(table, entityKey, patch);\n requestConvergence();\n },\n delete: async (table, entityKey) => {\n await mutationRuntime.delete(table, entityKey);\n requestConvergence();\n },\n batch: async (items) => {\n await mutationRuntime.batch(items);\n requestConvergence();\n },\n };\n\n // ─── Lazy-relation activation + the declared-safe query facade (ADR-0021) ──────────────────────\n const ensureSynced: SyncClient<TRegistry>[\"ensureSynced\"] = async (keys) => {\n const activeSync = sync;\n if (activeSync == null || keys.length === 0) return;\n const groupKeys = new Set<string>();\n for (const key of keys) {\n const groupKey = activeSync.groupKeyForTable(key);\n if (groupKey != null) groupKeys.add(groupKey);\n }\n await Promise.all([...groupKeys].map((groupKey) => activeSync.ensureGroupStarted(groupKey)));\n };\n\n const isSynced: SyncClient<TRegistry>[\"isSynced\"] = (key) => {\n const activeSync = sync;\n // Sync disabled → local-only: reads hit whatever is in the local store, so nothing is \"dormant\".\n if (activeSync == null) return true;\n return activeSync.isTableStarted(key);\n };\n\n // ADR-0021 §2/§4: the tables of `entry`'s consistency GROUP — a group is one subscription / one\n // transaction frontier, so reverting one member to dormant reverts them all (a table with no\n // `consistencyGroup` is its own singleton group).\n const groupTableKeysFor = (key: SyncTableName<TRegistry>, entry: SyncTableEntry): SyncTableName<TRegistry>[] => {\n const targetGroup = entry.consistencyGroup;\n return (\n targetGroup == null\n ? [key]\n : (Object.keys(options.registry) as SyncTableName<TRegistry>[]).filter(\n (candidate) => options.registry[candidate]!.consistencyGroup === targetGroup,\n )\n ) as SyncTableName<TRegistry>[];\n };\n\n // The shared group-teardown body of {@link desync} and {@link discardEphemeral} (ADR-0021 §2/§4). Both\n // revert a lazy relation's whole consistency group to dormant: refuse if any writable member owes\n // unsettled writes, stop the group stream, clear the persisted lazy activation, delete the persisted\n // Electric subscription (so re-activation re-streams from scratch), then clean-truncate every member's\n // local cluster. `label` names the calling primitive in the owed-writes refusal so each keeps its own\n // diagnostic (desync stays byte-identical). Callers apply their own lazy/retention gates BEFORE this.\n const tearDownLazyGroup = async (key: SyncTableName<TRegistry>, entry: SyncTableEntry, label: string) => {\n const groupTableKeys = groupTableKeysFor(key, entry);\n\n // Refuse if ANY writable member owes the server unsent/unsettled writes: the truncate clears the\n // journal, so dropping un-acked local intent would be silent data loss. Flush (or discard) those first.\n let owed = 0;\n for (const member of groupTableKeys) {\n if (options.registry[member]!.mode === \"readonly\") continue;\n const stats = await mutationRuntime.readMutationStats(member);\n owed +=\n stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;\n }\n if (owed > 0) {\n throw new Error(\n `${label}('${String(key)}') refused: ${owed} unsettled mutation(s) in the group's local journal. Flush or discard them first.`,\n );\n }\n\n const activeSync = sync;\n // The group key IS the Electric subscription key (`consistencyGroup ?? shapeKey`); fall back to the\n // registry derivation when sync is disabled.\n const groupKey = activeSync?.groupKeyForTable(key) ?? entry.consistencyGroup ?? entry.shape?.shapeKey;\n // Stop the stream BEFORE truncating so a live shape can't re-populate the rows we just cleared, and\n // revert the durable promotion (a no-op for ephemeral, which never persisted a flag) so the next boot\n // holds the relation dormant again.\n if (activeSync != null && groupKey != null) activeSync.stopGroup(groupKey);\n if (groupKey != null) await clearLazyGroupActivation(pglite, options.registry, groupKey);\n // CRITICAL: delete the group's persisted Electric subscription so a later re-activation re-streams the\n // shape from scratch. Without this it would resume from the old cursor and never re-send the rows we\n // truncate below — leaving the relation permanently missing its pre-desync data.\n if (groupKey != null) await resetSubscriptionsIfRequested(pglite, [groupKey]);\n // Clean-truncate every member's local cluster.\n for (const member of groupTableKeys) {\n await pglite.exec(buildDesyncTableSql(options.registry, member as string));\n }\n };\n\n const desync: SyncClient<TRegistry>[\"desync\"] = async (key) => {\n const entry = options.registry[key];\n if (entry == null) throw new Error(`desync: unknown table ${String(key)}`);\n if (entry.subscription !== \"lazy\") {\n throw new Error(\n `desync('${String(key)}') refused: only a lazy relation can be desynced — an eager relation is always-on and would immediately re-sync.`,\n );\n }\n await tearDownLazyGroup(key, entry, \"desync\");\n };\n\n const discardEphemeral: SyncClient<TRegistry>[\"discardEphemeral\"] = (key) =>\n // Run inside the SAME lifecycle slot the exports use (ADR-0035 decision 4): discardEphemeral\n // clean-truncates an ephemeral group's local cache, so an export must never interleave it (nor it an\n // export) — the slot's typed LifecycleBusyError fires in both directions. The existing lazy/ephemeral\n // gates below stay EXACTLY as they were, now inside the slot run. (`desync` is deliberately NOT slotted:\n // only the ADR-0035-named destructive ops — destroy/discardEphemeral/dropReadCache — serialise here.)\n lifecycleSlot.run(\"discardEphemeral\", async () => {\n const entry = options.registry[key];\n if (entry == null) throw new Error(`discardEphemeral: unknown table ${String(key)}`);\n // Keep the lazy gate desync has: eager+ephemeral is NOT forbidden by the type system (retention and\n // subscription are independent scalars on the entry — see contracts config.ts / registry.ts), and an\n // eager relation would immediately re-stream, so the same refusal applies here.\n if (entry.subscription !== \"lazy\") {\n throw new Error(\n `discardEphemeral('${String(key)}') refused: only a lazy relation can be discarded — an eager relation is always-on and would immediately re-sync.`,\n );\n }\n // STRICTER gate than desync: every member of the consistency group must be ephemeral. Retention is read\n // as `entry.retention ?? \"persistent\"` (absent → persistent, matching validateRegistryLifecycleGroups and\n // the schema generator); a read PROJECTION surfaces its declared retention on the same `retention` field\n // (withRetention/asEphemeral/defineReadProjection all set it), so this one read covers tables and\n // projections alike. Refuse (naming the offender) if any member is persistent — discardEphemeral is the\n // multi-tab-safe primitive for per-delivery-session windows, and truncating a persistent member's cache\n // would drop durable local data; use desync for a persistent lazy relation.\n for (const member of groupTableKeysFor(key, entry)) {\n if ((options.registry[member]!.retention ?? \"persistent\") !== \"ephemeral\") {\n throw new Error(\n `discardEphemeral('${String(key)}') refused: group member '${String(member)}' is persistent — ` +\n `discardEphemeral only drops an ephemeral relation's local rows. Use desync for a persistent lazy relation.`,\n );\n }\n }\n await tearDownLazyGroup(key, entry, \"discardEphemeral\");\n });\n\n const transaction: SyncClient<TRegistry>[\"transaction\"] = async ({ mode }, run) => {\n // The block's table handles only COLLECT mutations; the whole set is enqueued atomically as one unit.\n const collected: MutationBatchItem<TRegistry>[] = [];\n const txTables = Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n create: (input: unknown) => {\n collected.push({ table: tableKey, kind: \"create\", input } as MutationBatchItem<TRegistry>);\n },\n update: (entityKey: Record<string, string>, patch: unknown) => {\n collected.push({ table: tableKey, kind: \"update\", entityKey, patch } as MutationBatchItem<TRegistry>);\n },\n updateBlind: (entityKey: Record<string, string>, patch: unknown) => {\n collected.push({\n table: tableKey,\n kind: \"update\",\n entityKey,\n patch,\n blind: true,\n } as MutationBatchItem<TRegistry>);\n },\n delete: (entityKey: Record<string, string>) => {\n collected.push({ table: tableKey, kind: \"delete\", entityKey } as MutationBatchItem<TRegistry>);\n },\n },\n ]),\n ) as SyncTransaction<TRegistry>[\"tables\"];\n\n await run({ tables: txTables });\n\n if (collected.length === 0) {\n return { acks: [] };\n }\n\n const unit: WriteUnit = { id: globalThis.crypto.randomUUID(), mode };\n await mutationRuntime.batch(collected, unit);\n\n if (mode === \"optimistic\") {\n // An atomic batch enqueue; the background convergence loop flushes it (no foreground answer).\n void mutationRuntime.flush();\n return { acks: [] };\n }\n\n // Pessimistic: flush-route this unit to the authoritative endpoint and await the per-mutation result.\n return await mutationRuntime.flushUnit(unit.id);\n };\n\n const prepareQuery: SyncClient<TRegistry>[\"prepareQuery\"] = async ({ sql, use }) => {\n // Scan the compiled SQL for the lazy relations it reads (∪ the explicit `use`) and activate them.\n // The compiled SQL is ground truth and Drizzle quotes every relation, so any reference — FROM, JOIN,\n // subquery, WHERE — is caught; over-matching is bounded and harmless (one spurious persistent\n // subscription at worst, never a wrong result). Detection and activation are one step (ADR-0021).\n const toActivate = new Set<string>(use ?? []);\n for (const key of findReferencedLazyKeysInSql(sql, lazyGuardIndex)) toActivate.add(key);\n await ensureSynced([...toActivate] as SyncTableName<TRegistry>[]);\n // Backstop: if a referenced lazy relation is somehow still not active (a failed start, or no group),\n // throw rather than let the query read empty/stale. In the normal path everything scanned was just\n // activated, so this passes.\n assertLazyRefsActivated({\n sql,\n index: lazyGuardIndex,\n isActive: (key) => isSynced(key as SyncTableName<TRegistry>),\n });\n };\n\n const runGuardedQuery = async <TRows extends readonly unknown[]>(\n build: GuardedQueryFn<TRegistry, TRows>,\n use?: readonly SyncTableName<TRegistry>[],\n ): Promise<TRows> => {\n const builder = build(client);\n await prepareQuery({ sql: builder.toSQL().sql, ...(use ? { use } : {}) });\n return builder;\n };\n\n const client: SyncClient<TRegistry> = {\n drizzle: drizzleDb,\n pglite,\n views: buildViews(options.registry),\n tables: Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n key: tableKey,\n mode: options.registry[tableKey as SyncTableName<TRegistry>]!.mode,\n create: (input: SyncTableCreateInput<TRegistry, typeof tableKey>) =>\n mutate.create(tableKey as SyncTableName<TRegistry>, input),\n update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, typeof tableKey>) =>\n mutate.update(tableKey as SyncTableName<TRegistry>, entityKey, patch),\n delete: (entityKey: Record<string, string>) => mutate.delete(tableKey as SyncTableName<TRegistry>, entityKey),\n },\n ]),\n ) as SyncClient<TRegistry>[\"tables\"],\n ready,\n status,\n start: async () => {\n await ready;\n },\n stop: async () => {\n // Await any in-flight convergence pass before closing PGlite, so a pass never queries a\n // closed handle.\n await convergenceDriver?.stop();\n sync?.unsubscribe();\n status.isRunning = false;\n options.onStatusChange?.(status);\n // Tear the engine down (abort every shape stream) immediately before closing the DB — the exact\n // point PGlite's own close used to invoke the former extension's close hook (ADR-0032 S1). Order\n // preserved: convergence stop → sync unsubscribe → status → engine close → pglite close.\n await engine.close();\n await pglite.close();\n },\n destroy: (destroyOptions) =>\n // Run inside the SAME lifecycle slot the exports use (ADR-0035 decision 4), so a destructive wipe can\n // never interleave a running export (nor an export interleave this wipe) — the slot's typed\n // LifecycleBusyError fires in both directions. The refuse-if-owed guard stays EXACTLY as it was, now\n // inside the slot run.\n lifecycleSlot.run(\"destroy\", async () => {\n if (!destroyOptions?.force) {\n const stats = await mutationRuntime.readMutationStats();\n const owed =\n stats.pendingCount +\n stats.sendingCount +\n stats.failedCount +\n stats.quarantinedCount +\n stats.conflictedCount;\n\n if (owed > 0) {\n throw new Error(\n `destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`,\n );\n }\n }\n\n // Drain any in-flight convergence pass before wiping, so a pass never writes into a store\n // being torn down underneath it.\n await convergenceDriver?.stop();\n sync?.unsubscribe();\n status.isRunning = false;\n options.onStatusChange?.(status);\n await pglite.exec(buildWipeLocalStoreSql(options.registry));\n // Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment\n // the former extension close hook fired during `pglite.close()` (ADR-0032 S1).\n await engine.close();\n await pglite.close();\n }),\n dropReadCache: () =>\n // Under the SAME lifecycle slot as the exports (ADR-0035 decision 4). WHY dropReadCache is slotted and\n // not just destroy/discardEphemeral: it DROPS and rebuilds the synced read-cache tables, so an export\n // racing it would capture a half-rebuilt cache in the artefact (some tables dropped, some re-created,\n // none re-streamed yet). The slot makes the drop+rebuild atomic against any concurrent export.\n lifecycleSlot.run(\"dropReadCache\", async () => {\n await pglite.exec(buildDropReadCacheSql(options.registry));\n await pglite.exec(generateLocalSchemaSql(options.registry));\n // Reset the Electric subscriptions so the rebuilt synced tables re-stream from scratch\n // rather than the bookkeeping believing they are already caught up (ADR-0006).\n await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));\n }),\n flush: (table) => mutationRuntime.flush(table),\n reconcile: (table) => mutationRuntime.reconcile(table),\n retryFailed: (table) => mutationRuntime.retryFailed(table),\n recoverSending: (table) => mutationRuntime.recoverSending(table),\n readMutationDetails: (table) => mutationRuntime.readMutationDetails(table),\n mutate,\n discardConflict: (table, entityKey) => mutationRuntime.discardConflict(table, entityKey),\n discardQuarantined: (table, entityKey) => mutationRuntime.discardQuarantined(table, entityKey),\n diagnostics: async (table) => ({\n mutation: await mutationRuntime.readMutationStats(table),\n }),\n // Inspection surface (see the interface doc): straight through to the underlying store, no journal /\n // overlay involvement. The worker facade runs the identical call inside the worker's own client.\n rawQuery: (sql, params, options) => pglite.query(sql, params as unknown[] | undefined, options),\n rawExec: (sql, options) => pglite.exec(sql, options),\n query: (build) => runGuardedQuery(build),\n queryRow: async (build) => {\n const rows = await runGuardedQuery(build);\n return rows[0] ?? null;\n },\n queryRaw: (spec) => runGuardedQuery(spec.build, spec.use),\n queryRawRow: async (spec) => {\n const rows = await runGuardedQuery(spec.build, spec.use);\n return rows[0] ?? null;\n },\n ensureSynced,\n isSynced,\n desync,\n discardEphemeral,\n prepareQuery,\n transaction,\n groupReady: async (table) => {\n const activeSync = sync;\n // Sync disabled → local-only: every relation is trivially \"ready\" (nothing to await).\n if (activeSync == null) return;\n const groupKey = activeSync.groupKeyForTable(table as string);\n if (groupKey == null) return;\n await activeSync.groupReady(groupKey);\n },\n // The live-rows seam over PGlite's own `live` extension (ADR-0032 S2 §4) — the EXACT call the React\n // hooks made inline before the seam existed (`pglite.live.query` → `initialResults.rows` + `subscribe`),\n // so the in-process path is unchanged. `pkColumns` is unused here: PGlite's live query already diffs\n // incrementally against its own materialized state; the column set only matters for the worker bridge.\n subscribeLiveRows: async ({ sql, params, fields }, onRows) => {\n // Render the query safe to materialise: a JOIN with same-named columns fails `live.query`'s\n // temp-view creation (`column \"title\" specified more than once`) unless every output column has a\n // unique alias. No `fields` → SQL unchanged (backward-compatible name-keyed rows).\n const materialSql = wrapLiveQueryForMaterialization(sql, fields);\n const registered = await pglite.live.query<Record<string, unknown>>(materialSql, params as unknown[]);\n const listener = (results: { rows: Record<string, unknown>[] }) => {\n onRows(results.rows as never);\n };\n registered.subscribe(listener);\n return {\n initialRows: registered.initialResults.rows as never,\n unsubscribe: () => {\n void registered.unsubscribe(listener);\n },\n };\n },\n // Boot observability (ADR-0034): the finalized report (null before initial sync completes / after an\n // early stop). Resolves from the builder-owned ref this client holds — no round trip in-process.\n bootReport: async () => finalizedBootReport,\n exportStore: async (exportOptions) => {\n // Await engine-ready first (ADR-0035: exports wait out a boot rather than rejecting during it), THEN\n // take the lifecycle slot — a concurrent export/lifecycle op is refused with a typed busy error.\n await ready;\n // Name the backup from the configured plain store PATH (ADR-0036), never the PGlite instance's\n // resolved dataDir URL — a resolved URL is internal plumbing and must not leak into an artefact name\n // as something to imitate. The store id is the path's last segment (see `deriveStoreId`).\n return lifecycleSlot.run(\"exportStore\", () =>\n performStoreExport(\n {\n pglite,\n readMutationStats: () => mutationRuntime.readMutationStats(),\n ...(options.storePath != null ? { storePath: options.storePath } : {}),\n },\n exportOptions,\n ),\n );\n },\n exportDiagnostics: async (exportOptions) => {\n // Same lifecycle discipline as `exportStore` (ADR-0035): await engine-ready first (wait out a boot\n // rather than reject during it), THEN take the single slot so a concurrent export/lifecycle op is\n // refused with a typed busy error. The diagnostic dump runs the live datadir dump on `pglite`, then\n // clones it in memory — the live engine every reference here holds is never closed (the addendum's\n // whole reason for the throwaway clone over the abandoned suspend/reopen seam).\n await ready;\n return lifecycleSlot.run(\"exportDiagnostics\", () =>\n performDiagnosticExport(\n {\n pglite,\n readMutationStats: () => mutationRuntime.readMutationStats(),\n ...(options.storePath != null ? { storePath: options.storePath } : {}),\n },\n exportOptions,\n ),\n );\n },\n exportData: async (exportOptions) => {\n // Same lifecycle discipline (ADR-0035): await engine-ready first (wait out a boot rather than reject),\n // THEN take the single slot. The DRAIN runs inside the slot (the caller-side placement decision 3\n // makes): flush needs the running engine and is not lifecycle-exclusive, but the artefact must be\n // taken right after the drain, so export owns the store's lifecycle for the whole drain+dump. The\n // `-t` allowlist + enum header are resolved from the registry through the SAME projection the DDL\n // generator uses — never re-derived by string convention.\n await ready;\n return lifecycleSlot.run(\"exportData\", () =>\n performDataExport(\n {\n pglite,\n readMutationStats: () => mutationRuntime.readMutationStats(),\n flush: () => mutationRuntime.flush(),\n syncedTableNames: collectDataExportSyncedTableNames(options.registry),\n enumHeaderSql: buildDataExportEnumHeaderSql(options.registry),\n cloneCleanupSql: buildDataExportCloneCleanupSql(options.registry),\n ...(options.storePath != null ? { storePath: options.storePath } : {}),\n },\n exportOptions,\n ),\n );\n },\n };\n\n return client;\n}\n\n/**\n * Every persisted subscription key declared by the registry — one per consistency group (ADR-0009\n * decision 2), not per table. Grouped tables share a subscription-state row keyed by their group;\n * ungrouped tables are singleton groups keyed by their own `shapeKey`. Deduped, since several tables\n * collapse onto one group key.\n */\nfunction allGroupSubscriptionKeys<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {\n const keys = Object.values(registry)\n .filter((entry) => typeof entry.shape?.shapeKey === \"string\" && entry.shape.shapeKey.length > 0)\n .map((entry) => entry.consistencyGroup ?? entry.shape!.shapeKey);\n return [...new Set(keys)];\n}\n\nasync function resetSubscriptionsIfRequested(pglite: ClientPGlite, keys: string[] | undefined) {\n if (!keys || keys.length === 0) {\n return;\n }\n\n const uniqueKeys = [...new Set(keys.map((key) => key.trim()).filter((key) => key.length > 0))];\n\n if (uniqueKeys.length === 0) {\n return;\n }\n\n await pglite.electric.initMetadataTables();\n await Promise.all(uniqueKeys.map((key) => pglite.electric.deleteSubscription(key)));\n}\n\nfunction createDrizzleDatabase<TRegistry extends SyncTableRegistry>(\n client: ClientPGlite,\n schema: RegistryTables<TRegistry>,\n) {\n const relations = defineRelations(schema) as RegistryRelations<TRegistry>;\n\n const createDatabase = drizzle as unknown as (config: {\n client: ClientPGlite;\n relations: RegistryRelations<TRegistry>;\n }) => PgliteDatabase<RegistryRelations<TRegistry>>;\n\n return createDatabase({ client, relations });\n}\n\nfunction buildSchema<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n return Object.fromEntries(\n Object.entries(registry).map(([key, entry]) => [key, entry.table]),\n ) as RegistryTables<TRegistry>;\n}\n\nfunction buildViews<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n return Object.fromEntries(\n Object.entries(registry).flatMap(([key, entry]) => (entry.view != null ? [[key, entry.view]] : [])),\n ) as RegistryViews<TRegistry>;\n}\n\n/**\n * The tab-side READ handles a worker-attached client exposes (ADR-0032 S2): a build-only Drizzle instance\n * plus the registry views. On the attach client, Drizzle is used only to COMPILE queries to SQL\n * (`.toSQL()`) on the tab — execution happens in the worker via the live-rows bridge / RPC — so it is\n * constructed over a stub client that is never invoked (`construct` stores the client without calling it).\n * The same builders `createSyncClient` uses, so a query built on either client compiles identically.\n */\nexport function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): { drizzle: PgliteDatabase<RegistryRelations<TRegistry>>; views: RegistryViews<TRegistry> } {\n const stubClient = {} as ClientPGlite;\n return {\n drizzle: createDrizzleDatabase(stubClient, buildSchema(registry)),\n views: buildViews(registry),\n };\n}\n\nfunction buildSyncConfigFromRegistry<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n electricUrl: string,\n): SyncConfigInput {\n return {\n electricUrl,\n localSchema: getSyncRegistrySchema(registry),\n tables: Object.fromEntries(Object.entries(registry).map(([key, entry]) => [key, buildSyncTableInput(entry, key)])),\n };\n}\n\nfunction buildSyncTableInput(entry: SyncTableEntry, tableKey: string) {\n const clientProjection = getClientProjection(entry, tableKey);\n\n return {\n name: tableKey,\n mode: entry.mode,\n primaryKey: entry.primaryKey,\n ...(entry.shape !== undefined ? { shape: entry.shape } : {}),\n clientProjection,\n // The read-path apply ladder (strategy + json casts) is resolved by the engine directly from the\n // registry entry via `resolveApplyTarget` (ADR-0029 D1/D2) — `deriveSyncColumnTypes` /\n // `classifyTableApplyStrategy` on the model, never carried through this config surface.\n // Carry the consistency group (ADR-0009 decision 2) so the sync starter buckets grouped tables\n // onto one MultiShapeStream; absent → singleton group.\n ...(entry.consistencyGroup ? { consistencyGroup: entry.consistencyGroup } : {}),\n // Carry the lifecycle axes (ADR-0021) so the sync starter can hold lazy groups out of the eager\n // boot set and provision ephemeral clusters as TEMP; absent → eager/persistent (today's path).\n ...(entry.subscription ? { subscription: entry.subscription } : {}),\n ...(entry.retention ? { retention: entry.retention } : {}),\n };\n}\n\nfunction getClientProjection(entry: SyncTableEntry, tableKey: string) {\n if (!entry.clientProjection) {\n throw new Error(`clientProjection is required for client table ${tableKey}`);\n }\n\n return entry.clientProjection;\n}\n",
6
6
  "//#region src/entity.ts\nconst entityKind = Symbol.for(\"drizzle:entityKind\");\nconst hasOwnEntityKind = Symbol.for(\"drizzle:hasOwnEntityKind\");\nfunction is(value, type) {\n\tif (!value || typeof value !== \"object\") return false;\n\tif (value instanceof type) return true;\n\tif (!Object.prototype.hasOwnProperty.call(type, entityKind)) throw new Error(`Class \"${type.name ?? \"<unknown>\"}\" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);\n\tlet cls = Object.getPrototypeOf(value)?.constructor;\n\tif (cls) while (cls) {\n\t\tif (entityKind in cls && cls[entityKind] === type[entityKind]) return true;\n\t\tcls = Object.getPrototypeOf(cls);\n\t}\n\treturn false;\n}\n\n//#endregion\nexport { entityKind, hasOwnEntityKind, is };\n//# sourceMappingURL=entity.js.map",
7
7
  "//#region src/column-common.ts\nconst OriginalColumn = Symbol.for(\"drizzle:OriginalColumn\");\n\n//#endregion\nexport { OriginalColumn };\n//# sourceMappingURL=column-common.js.map",
8
8
  "import { entityKind } from \"./entity.js\";\nimport { OriginalColumn } from \"./column-common.js\";\n\n//#region src/column.ts\nconst noop = (v) => v;\nnoop.isNoop = true;\nvar Column = class {\n\tstatic [entityKind] = \"Column\";\n\t/** @internal */\n\tcodec;\n\tname;\n\tkeyAsName;\n\tprimary;\n\tnotNull;\n\tdefault;\n\tdefaultFn;\n\tonUpdateFn;\n\thasDefault;\n\tisUnique;\n\tuniqueName;\n\tuniqueType;\n\tdataType;\n\tcolumnType;\n\tenumValues = void 0;\n\tgenerated = void 0;\n\tgeneratedIdentity = void 0;\n\tlength;\n\tisLengthExact;\n\tisAlias;\n\t/** @internal */\n\tconfig;\n\t/** @internal */\n\ttable;\n\t/** @internal */\n\tonInit() {}\n\tconstructor(table, config) {\n\t\tthis.config = config;\n\t\tthis.onInit();\n\t\tthis.table = table;\n\t\tthis.name = config.name;\n\t\tthis.isAlias = false;\n\t\tthis.keyAsName = config.keyAsName;\n\t\tthis.notNull = config.notNull;\n\t\tthis.default = config.default;\n\t\tthis.defaultFn = config.defaultFn;\n\t\tthis.onUpdateFn = config.onUpdateFn;\n\t\tthis.hasDefault = config.hasDefault;\n\t\tthis.primary = config.primaryKey;\n\t\tthis.isUnique = config.isUnique;\n\t\tthis.uniqueName = config.uniqueName;\n\t\tthis.uniqueType = config.uniqueType;\n\t\tthis.dataType = config.dataType;\n\t\tthis.columnType = config.columnType;\n\t\tthis.generated = config.generated;\n\t\tthis.generatedIdentity = config.generatedIdentity;\n\t\tthis.length = config[\"length\"];\n\t\tthis.isLengthExact = config[\"isLengthExact\"];\n\t}\n\tmapFromDriverValue = noop;\n\tmapToDriverValue = noop;\n\t/** @internal */\n\tpostBuild() {\n\t\treturn this;\n\t}\n\t/** @internal */\n\tshouldDisableInsert() {\n\t\treturn this.config.generated !== void 0 && this.config.generated.type !== \"byDefault\";\n\t}\n\t/** @internal */\n\t[OriginalColumn]() {\n\t\treturn this;\n\t}\n};\nfunction getColumnTable(column) {\n\treturn column.table;\n}\n\n//#endregion\nexport { Column, getColumnTable };\n//# sourceMappingURL=column.js.map",
@@ -117,32 +117,39 @@
117
117
  "import { sql, type SQL } from \"drizzle-orm\";\n\n/**\n * The BODY of the canonical microsecond clock — `clock_timestamp()` epoch microseconds as BIGINT.\n * This text is the SINGLE source for the `public.pgxsinkit_clock_us()` function body rendered by the\n * server's utilities migration ({@link renderPgxsinkitUtilitiesMigration}) and NOTHING else. No column\n * DEFAULT and no generated apply-function DDL may embed this expression — every surface CALLS the\n * function ({@link CLOCK_US_CALL_SQL_TEXT} / {@link clockMicrosecondsSql}), so the semantic choices\n * (`clock_timestamp()` over `now()`; `FLOOR` + `BIGINT`) live in exactly one reviewable body.\n */\nexport const NOW_MICROSECONDS_SQL_TEXT = \"CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)\";\n\n/**\n * The CALL form of the canonical microsecond clock, for string-rendering contexts (the apply-function\n * generator's PL/pgSQL literals). Deliberately `clock_timestamp()` (via the function body), never\n * `now()`/`transaction_timestamp()`: `now()` freezes at transaction start, but LWW/audit ordering of a\n * multi-row apply within one transaction needs an ADVANCING clock. The DB function is the canonical\n * home — never inline the expression at a call site.\n */\nexport const CLOCK_US_CALL_SQL_TEXT = \"public.pgxsinkit_clock_us()\";\n\n/**\n * The canonical microsecond clock as a Drizzle fragment, for `.default(...)` column positions — the\n * CALL form `public.pgxsinkit_clock_us()`, never the inline expression. Deliberately `clock_timestamp()`\n * (inside the function), never `now()`/`transaction_timestamp()`: `now()` freezes at transaction start,\n * whereas LWW/audit ordering of a multi-row apply within one transaction needs an advancing clock. The\n * DB function (installed by the utilities migration) is the canonical home; never inline the expression.\n */\nexport const clockMicrosecondsSql: SQL = sql.raw(CLOCK_US_CALL_SQL_TEXT);\n",
118
118
  "import { and, eq, getTableName, or, sql, type AnyColumn, type SQL } from \"drizzle-orm\";\nimport { PgDialect, pgPolicy, type AnyPgTable, type PgRole } from \"drizzle-orm/pg-core\";\n\nimport { c, DENY_ALL, type JwtClaims } from \"./config\";\n\n// Render a typed fragment to inline-literal SQL text (CREATE POLICY DDL cannot carry `$n` binds).\n// The tier-② discipline for the text builders below: values enter as typed `${value}` interpolations\n// and drizzle owns the escaping; only the claim-extraction leaves stay raw text.\nconst textDialect = new PgDialect();\nfunction renderInlineSql(fragment: SQL): string {\n return textDialect.sqlToQuery(fragment.inlineParams()).sql;\n}\n\ntype SupabaseOwnerOrAdminPolicyKind = \"select\" | \"insert\" | \"update\" | \"delete\";\n\ntype SupabaseOwnerOrAdminPolicyShape = {\n command: SupabaseOwnerOrAdminPolicyKind;\n using: boolean;\n withCheck: boolean;\n};\n\n// Options for the raw predicate *text* builder (`buildSupabaseOwnerOrAdminPredicateSqlText`) — the\n// documented escape hatch that returns the predicate as a SQL string (for a hand-written trigger or\n// migration). It takes a column *name* because text has no column object. The native policy builder\n// below takes a real Drizzle column instead.\nexport type SupabaseOwnerOrAdminPredicateOptions = {\n ownerSqlColumn?: string;\n adminRoleName?: string;\n subjectCastType?: string;\n};\n\nexport type SupabaseOwnerOrAdminNativePoliciesOptions = {\n /** Owner column on the governed row (e.g. `authors.ownerId`). The governed table name is derived from it. */\n ownerColumn: AnyColumn;\n role: PgRole;\n /** Role value (in `app_metadata.roles`) that bypasses ownership (default \"admin\"). */\n adminRoleName?: string;\n /** SQL type the JWT subject is cast to before comparison (default \"uuid\"). */\n subjectCastType?: string;\n};\n\nconst defaultOwnerSqlColumn = \"owner_id\";\nconst defaultOwnerPropertyKey = \"ownerId\";\nconst defaultAuthenticatedRoleName = \"authenticated\";\nconst defaultAdminRoleName = \"admin\";\nconst defaultSubjectCastType = \"uuid\";\n\nconst ownerOrAdminPolicyShapes: SupabaseOwnerOrAdminPolicyShape[] = [\n {\n command: \"select\",\n using: true,\n withCheck: false,\n },\n {\n command: \"insert\",\n using: false,\n withCheck: true,\n },\n {\n command: \"update\",\n using: true,\n withCheck: true,\n },\n {\n command: \"delete\",\n using: true,\n withCheck: false,\n },\n];\n\nfunction assertIdentifier(value: string, label: string): void {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {\n throw new Error(`${label} must be a valid SQL identifier: ${value}`);\n }\n}\n\nfunction assertTypeName(value: string, label: string): void {\n if (!/^[A-Za-z_][A-Za-z0-9_]*(?:\\s+[A-Za-z_][A-Za-z0-9_]*)*$/.test(value)) {\n throw new Error(`${label} must be a valid SQL type name: ${value}`);\n }\n}\n\nfunction buildOwnerOrAdminPolicyName(tableName: string, command: SupabaseOwnerOrAdminPolicyKind) {\n return `${tableName}_${command}_owner_or_admin`;\n}\n\n// ---------------------------------------------------------------------------\n// Shared predicate leaves (used by both policy families). RLS is the *write* path\n// (Postgres), so columns may serialize qualified — unlike the Electric read `where`,\n// which needs bare columns. The only bits that stay raw `sql` are genuinely-Postgres\n// expressions with no Drizzle operator: the JWT-subject `(select current_setting(...)::type)`\n// and the admin-roles `EXISTS`. Literal values use `eq(col, value).inlineParams()` so the\n// value is inlined into the DDL — a bare `$n` is something `CREATE POLICY` cannot carry.\n// ---------------------------------------------------------------------------\n\n// The governed table name (for policy identifiers) derived from a built Drizzle column, so renaming\n// the table renames its policies. Columns built inside `defineSyncTable`'s `extras` callback carry\n// their `.table` — which is where these builders are meant to be called (the table object does not\n// yet exist when its own `policies:` array would be built).\nfunction tableNameForColumn(column: AnyColumn, label: string): string {\n const table = (column as { table?: AnyPgTable }).table;\n if (!table) {\n throw new Error(\n `${label} must be a built Drizzle column carrying its table — call this builder inside defineSyncTable's \\`extras\\` callback`,\n );\n }\n return getTableName(table);\n}\n\n// The JWT subject as a Postgres expression (irreducibly raw: `current_setting` + cast). Used as the\n// right-hand side of `eq(ownerColumn, subject)` — eq splices an SQL fragment verbatim (no bound\n// param), so the DDL carries the literal expression, not a `$n` CREATE POLICY cannot bind. Wrapped in\n// a scalar subquery — the Supabase RLS performance idiom: the stable `current_setting` expression is\n// evaluated once per statement (InitPlan), not once per row.\nfunction buildSubjectSql(subjectCastType: string): SQL {\n assertTypeName(subjectCastType, \"subjectCastType\");\n return sql.raw(`(select ${buildSubjectSqlText(subjectCastType)})`);\n}\n\nfunction buildSubjectSqlText(subjectCastType: string): string {\n return `coalesce(\n nullif(current_setting('request.jwt.claim.sub', true), ''),\n (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub')\n )::${subjectCastType}`;\n}\n\n// The admin-bypass test: `app_metadata.roles` (from the JWT claims) contains `adminRoleName`. No\n// column reference and no recursion risk, so it is inlined as text (shared by the text builder and\n// the native builder). The role value enters as a typed interpolation (drizzle owns the escaping);\n// the claim-extraction body is the allowed raw leaf.\nfunction buildAdminRoleExistsSqlText(adminRoleName: string): string {\n return renderInlineSql(sql`EXISTS (\n SELECT 1\n FROM jsonb_array_elements_text(\n COALESCE(\n (\n coalesce(\n nullif(current_setting('request.jwt.claim', true), ''),\n nullif(current_setting('request.jwt.claims', true), '')\n )::jsonb -> 'app_metadata' -> 'roles'\n ),\n '[]'::jsonb\n )\n ) AS assigned_role(role_name_value)\n WHERE assigned_role.role_name_value = ${adminRoleName}\n )`);\n}\n\nfunction normalizePredicateOptions(options: SupabaseOwnerOrAdminPredicateOptions = {}) {\n const ownerSqlColumn = options.ownerSqlColumn ?? defaultOwnerSqlColumn;\n const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;\n const subjectCastType = options.subjectCastType ?? defaultSubjectCastType;\n\n assertIdentifier(ownerSqlColumn, \"ownerSqlColumn\");\n assertTypeName(subjectCastType, \"subjectCastType\");\n\n return {\n ownerSqlColumn,\n adminRoleName,\n subjectCastType,\n };\n}\n\n/**\n * The owner-or-admin predicate as raw SQL **text** — the escape hatch for when you need the predicate\n * as a string (a hand-written trigger, a manual migration). For attaching RLS to a Drizzle table,\n * prefer `buildSupabaseOwnerOrAdminNativePolicies`, which takes the real column and is rename-tracked.\n */\nexport function buildSupabaseOwnerOrAdminPredicateSqlText(options: SupabaseOwnerOrAdminPredicateOptions = {}): string {\n const normalized = normalizePredicateOptions(options);\n\n return `\n ${normalized.ownerSqlColumn} = ${buildSubjectSqlText(normalized.subjectCastType)}\n OR ${buildAdminRoleExistsSqlText(normalized.adminRoleName)}\n`;\n}\n\n// owner-or-admin predicate built from the real Drizzle column: `eq(ownerColumn, subject)` (qualified,\n// rename-tracked) OR the raw admin-roles EXISTS (no column, no Drizzle operator). The single boolean\n// is `or(...)`.\nexport function buildSupabaseOwnerOrAdminNativePolicies(options: SupabaseOwnerOrAdminNativePoliciesOptions) {\n const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;\n const subject = buildSubjectSql(options.subjectCastType ?? defaultSubjectCastType);\n const adminExists = sql.raw(buildAdminRoleExistsSqlText(adminRoleName));\n const predicate = or(eq(options.ownerColumn, subject), adminExists)!;\n const tableName = tableNameForColumn(options.ownerColumn, \"ownerColumn\");\n\n return ownerOrAdminPolicyShapes.map((shape) =>\n pgPolicy(buildOwnerOrAdminPolicyName(tableName, shape.command), {\n as: \"permissive\",\n for: shape.command,\n to: options.role,\n ...(shape.using ? { using: predicate } : {}),\n ...(shape.withCheck ? { withCheck: predicate } : {}),\n }),\n );\n}\n\nexport const supabaseOwnerOrAdminDefaults = {\n ownerSqlColumn: defaultOwnerSqlColumn,\n ownerPropertyKey: defaultOwnerPropertyKey,\n authenticatedRoleName: defaultAuthenticatedRoleName,\n adminRoleName: defaultAdminRoleName,\n subjectCastType: defaultSubjectCastType,\n} as const;\n\n// ---------------------------------------------------------------------------\n// Membership-scoped policies (generic). A row belongs to a *container* and is\n// visible/writable through membership of that container — not just ownership.\n// This is the readwrite counterpart to a membership row-filter: every member of\n// the container may read the row (fan-out to non-owners); only the owner may\n// create it (as themselves) and edit it, while a container *manager* may moderate\n// any row. Domain-agnostic: the container, membership table, and manager role are\n// all parameters.\n//\n// The container, membership, and owner references are **real Drizzle columns/tables**\n// (not name strings), so the policy tracks the schema — a column or table rename is a\n// compile error, and the governed table name is *derived* from the container column\n// (no redundant `tableName` to drift). Predicate structure is built with Drizzle\n// operators (`and`/`or`/`eq`, with `.inlineParams()` on the `'manager'` / `false` literals so\n// they inline instead of becoming a `$n` CREATE POLICY cannot carry); only the irreducibly-Postgres\n// leaves stay `sql`: the `IN (subquery)` containment (Drizzle's `inArray` cannot wrap a raw subquery)\n// and the `(select current_setting(...)::type)` JWT-subject expression (wrapped in a scalar subquery —\n// the Supabase per-statement-eval RLS perf idiom). Columns serialize qualified\n// (`\"work_items\".\"workspace_id\"`) — fine for Postgres RLS (the write path, unlike Electric's bare rule).\n// ---------------------------------------------------------------------------\n\ntype MembershipPolicyKind = \"select\" | \"insert\" | \"update\" | \"delete\";\n\nexport type SupabaseMembershipPredicateColumns = {\n /** Column on the governed row naming its container (e.g. `workItems.workspaceId`). */\n containerColumn: AnyColumn;\n /** Membership link table (e.g. the `workspace_members` table). */\n membershipTable: AnyPgTable;\n /** Container column on the membership link table (e.g. `workspaceMembers.workspaceId`). */\n membershipContainerColumn: AnyColumn;\n /** Subject (member) column on the membership link table, compared to the JWT sub. */\n membershipSubjectColumn: AnyColumn;\n /** Owner column on the governed row (e.g. `workItems.ownerId`). */\n ownerColumn: AnyColumn;\n /** Optional role column on the membership link enabling manager moderation. */\n managerRoleColumn?: AnyColumn;\n /** Role value that grants moderation (default \"manager\"); only used with managerRoleColumn. */\n managerRoleValue?: string;\n /** SQL type the JWT subject is cast to before comparison (default \"uuid\"). */\n subjectCastType?: string;\n};\n\n// Optional write-state gate (generic). When supplied, INSERT and UPDATE are additionally gated on\n// mutable state: a *locked* container admits writes only from a manager (e.g. a frozen discussion\n// thread), and a *muted* member may not write at all. SELECT and DELETE are unaffected — reads and\n// moderation deletes still flow. Domain-agnostic: the container/lock and membership/mute columns are\n// parameters. Requires managerRoleColumn (managers bypass the lock).\nexport type SupabaseMembershipWriteGateColumns = {\n /** Container table holding the lock flag (e.g. the `workspaces` table). */\n containerTable: AnyPgTable;\n /** PK column on the container table the governed row's container column references (e.g. `workspaces.id`). */\n containerPkColumn: AnyColumn;\n /** Boolean column on the container table; when true, only a manager may write (e.g. `workspaces.locked`). */\n containerLockColumn: AnyColumn;\n /** Boolean column on the membership table; when true, that member may not write (e.g. `workspaceMembers.muted`). */\n membershipMutedColumn: AnyColumn;\n};\n\nexport type SupabaseMembershipNativePoliciesOptions = SupabaseMembershipPredicateColumns & {\n role: PgRole;\n /** Optional write-state gate applied to INSERT and UPDATE only. */\n writeGate?: SupabaseMembershipWriteGateColumns;\n};\n\nconst defaultManagerRoleValue = \"manager\";\n\nconst membershipPolicyShapes: { command: MembershipPolicyKind; using: boolean; withCheck: boolean }[] = [\n { command: \"select\", using: true, withCheck: false },\n { command: \"insert\", using: false, withCheck: true },\n { command: \"update\", using: true, withCheck: true },\n { command: \"delete\", using: true, withCheck: false },\n];\n\ntype NormalizedMembershipColumns = SupabaseMembershipPredicateColumns & {\n managerRoleValue: string;\n subjectCastType: string;\n};\n\nfunction normalizeMembershipColumns(options: SupabaseMembershipPredicateColumns): NormalizedMembershipColumns {\n return {\n ...options,\n managerRoleValue: options.managerRoleValue ?? defaultManagerRoleValue,\n subjectCastType: options.subjectCastType ?? defaultSubjectCastType,\n };\n}\n\n// Containment form (not a correlated EXISTS): the governed row's container column must be in the set\n// of containers the subject belongs to. Two reasons it is `= ANY(ARRAY(subquery))` and not\n// `IN (subquery)`, both load-bearing:\n// 1. Correctness — the subquery stays uncorrelated (its `WHERE` references only the subject), so the\n// membership table's same-named column can't shadow the outer container column. A correlated\n// `EXISTS (… WHERE m.container = container …)` would collapse the correlation.\n// 2. Performance — for a runtime-resolved set (the subject comes from `current_setting`, opaque to\n// the planner) `IN (subquery)` is costed as a hashed semi-join → **sequential scan** of the\n// governed table; `= ANY(ARRAY(subquery))` materializes the set once (InitPlan) and the\n// ScalarArrayOp drives a **bitmap index scan**. At scale that is ~25-45× faster (the rls-read\n// perf track proves it). `inArray` can't wrap a raw subquery, so this stays `sql`.\nfunction membershipMatch(cols: NormalizedMembershipColumns, subject: SQL, requireManager: boolean): SQL {\n const subjectIsMember = eq(cols.membershipSubjectColumn, subject);\n const where =\n requireManager && cols.managerRoleColumn\n ? and(subjectIsMember, eq(cols.managerRoleColumn, cols.managerRoleValue).inlineParams())!\n : subjectIsMember;\n\n return sql`${cols.containerColumn} = any(array(select ${cols.membershipContainerColumn} from ${cols.membershipTable} where ${where}))`;\n}\n\n/** owner-or-manager predicate (edit / moderate). */\nfunction ownerOrManager(cols: NormalizedMembershipColumns, subject: SQL): SQL {\n const owner = eq(cols.ownerColumn, subject);\n return cols.managerRoleColumn ? or(owner, membershipMatch(cols, subject, true))! : owner;\n}\n\n// write-state gate: ((container not locked) OR caller is a manager) AND caller's membership not muted.\n// Same `= ANY(ARRAY(subquery))` containment discipline as membershipMatch (uncorrelated set, index-scan\n// friendly), so the container/membership tables can reuse their own column names without shadowing the\n// governed row's container column.\nfunction membershipWriteGate(\n cols: NormalizedMembershipColumns,\n gate: SupabaseMembershipWriteGateColumns,\n subject: SQL,\n): SQL {\n const unlocked = sql`${cols.containerColumn} = any(array(select ${gate.containerPkColumn} from ${gate.containerTable} where ${eq(gate.containerLockColumn, false).inlineParams()}))`;\n const notMuted = sql`${cols.containerColumn} = any(array(select ${cols.membershipContainerColumn} from ${cols.membershipTable} where ${and(eq(cols.membershipSubjectColumn, subject), eq(gate.membershipMutedColumn, false).inlineParams())}))`;\n return and(or(unlocked, membershipMatch(cols, subject, true))!, notMuted)!;\n}\n\nexport function buildSupabaseMembershipNativePolicies(options: SupabaseMembershipNativePoliciesOptions) {\n const cols = normalizeMembershipColumns(options);\n const subject = buildSubjectSql(cols.subjectCastType);\n const tableName = tableNameForColumn(cols.containerColumn, \"containerColumn\");\n\n const memberPredicate = membershipMatch(cols, subject, false);\n const ownerAndMember = and(eq(cols.ownerColumn, subject), memberPredicate)!;\n const ownerOrManagerPredicate = ownerOrManager(cols, subject);\n\n let writeGateClause: SQL | null = null;\n if (options.writeGate) {\n if (!cols.managerRoleColumn) {\n throw new Error(\"writeGate requires managerRoleColumn so a manager can write into a locked container\");\n }\n writeGateClause = membershipWriteGate(cols, options.writeGate, subject);\n }\n\n const gatedForWrite = (base: SQL): SQL => (writeGateClause ? and(base, writeGateClause)! : base);\n\n const predicateFor = (command: MembershipPolicyKind): SQL => {\n switch (command) {\n case \"select\":\n return memberPredicate;\n case \"insert\":\n return gatedForWrite(ownerAndMember);\n case \"update\":\n return gatedForWrite(ownerOrManagerPredicate);\n case \"delete\":\n return ownerOrManagerPredicate;\n }\n };\n\n return membershipPolicyShapes.map((shape) => {\n const predicate = predicateFor(shape.command);\n\n return pgPolicy(`${tableName}_${shape.command}_membership`, {\n as: \"permissive\",\n for: shape.command,\n to: options.role,\n ...(shape.using ? { using: predicate } : {}),\n ...(shape.withCheck ? { withCheck: predicate } : {}),\n });\n });\n}\n\n// ---------------------------------------------------------------------------\n// Grant-scope policies (generic). Authorization is carried IN THE JWT, not a DB\n// table: `app_metadata.authorization.grants` is an array of\n// `{ role, scope: { kind, <kind>Id } }` minted into the token. A row is visible\n// when its scope column (e.g. `offering_id`) appears among the caller's grants for\n// one of the accepting roles. Because the grant set lives in the token, the\n// predicate needs NO join — it parses the claims jsonb and tests set membership.\n//\n// Two forms, deliberately:\n// - default (InitPlan-correct): an **uncorrelated** `scope_col IN (SELECT …\n// jsonb_array_elements(claims) …)`. The subquery never references the outer row,\n// so the planner hoists it to an InitPlan and the JWT is parsed **once per\n// statement**.\n// - `naive: true` (the cliff): a **correlated** `EXISTS (… WHERE (g->…->>id) =\n// scope_col)`. Referencing the outer row forces per-row re-evaluation — the JWT\n// is re-parsed for **every row scanned**. It exists only to demonstrate and\n// regression-guard the InitPlan discipline (see the `rls-read-load` perf track);\n// never ship it.\n//\n// The same grant set is mirrored on the Electric read path by {@link resolveGrantScopeIds}\n// + {@link buildGrantScopeShapeWhere}: the proxy resolves the ids from the claims in JS\n// and injects a literal `scope_col IN ('a','b')` — Electric cannot read RLS, so the two\n// surfaces are generated from one declaration and must agree.\n// ---------------------------------------------------------------------------\n\ntype GrantScopePolicyKind = \"select\" | \"insert\" | \"update\" | \"delete\";\n\nconst defaultGrantsClaimPath = [\"app_metadata\", \"authorization\", \"grants\"] as const;\nconst defaultGrantScopeCastType = \"uuid\";\n\nexport type GrantScopeClaimOptions = {\n /** Value matched against each grant's `scope.kind` (e.g. \"offering\"). */\n scopeKind: string;\n /** Grant `role` values that confer access (e.g. [\"teacher\", \"assistant\"]). */\n roleValues: string[];\n /** Field within `scope` holding the id (e.g. \"offeringId\"). Defaults to `${scopeKind}Id`. */\n scopeIdField?: string;\n /** Path to the grants array in the claims. Defaults to `app_metadata.authorization.grants`. */\n grantsClaimPath?: string[];\n};\n\nexport type SupabaseGrantScopePredicateColumns = GrantScopeClaimOptions & {\n /** Column on the governed row naming its scope (e.g. `offerings.id` reference column). Table name is derived from it. */\n scopeColumn: AnyColumn;\n /** SQL type the extracted grant id is cast to before comparison (default \"uuid\"). */\n scopeCastType?: string;\n /**\n * Optional unconditional bypass: any grant whose `role` ∈ `bypass.roleValues` and whose\n * `scope.kind` = `bypass.scopeKind` (default \"platform\") grants all rows — e.g. a\n * platform-scoped `platform_admin`. The bypass is an **uncorrelated** EXISTS, so it stays\n * InitPlan-hoisted in both the correct and naive forms.\n */\n bypass?: { roleValues: string[]; scopeKind?: string };\n};\n\nexport type SupabaseGrantScopeNativePoliciesOptions = SupabaseGrantScopePredicateColumns & {\n role: PgRole;\n /** Emit the deliberately-naive per-row correlated form (cliff demo / regression guard only). */\n naive?: boolean;\n};\n\nconst grantScopePolicyShapes: { command: GrantScopePolicyKind; using: boolean; withCheck: boolean }[] = [\n { command: \"select\", using: true, withCheck: false },\n { command: \"insert\", using: false, withCheck: true },\n { command: \"update\", using: true, withCheck: true },\n { command: \"delete\", using: true, withCheck: false },\n];\n\nfunction resolveGrantsClaimPath(path: readonly string[] | undefined): string[] {\n const segments = path && path.length > 0 ? [...path] : [...defaultGrantsClaimPath];\n for (const segment of segments) {\n assertIdentifier(segment, \"grantsClaimPath segment\");\n }\n return segments;\n}\n\n// The grants array as a Postgres jsonb expression, defaulting to `[]` when absent so\n// `jsonb_array_elements` never errors. `#>` takes a text[] path; the segments are validated\n// identifiers, so the `'{…}'` path literal is injection-safe.\nfunction buildGrantsArraySqlText(path: string[]): string {\n return `coalesce(\n (\n coalesce(\n nullif(current_setting('request.jwt.claim', true), ''),\n nullif(current_setting('request.jwt.claims', true), '')\n )::jsonb #> '{${path.join(\",\")}}'\n ),\n '[]'::jsonb\n )`;\n}\n\nfunction buildRoleInListSqlText(roleValues: string[]): string {\n if (roleValues.length === 0) {\n throw new Error(\"grant-scope policy requires at least one role value\");\n }\n return renderInlineSql(\n sql.join(\n roleValues.map((role) => sql`${role}`),\n sql`, `,\n ),\n );\n}\n\nfunction resolveGrantScopeIdField(options: GrantScopeClaimOptions): string {\n const field = options.scopeIdField ?? `${options.scopeKind}Id`;\n assertIdentifier(field, \"scopeIdField\");\n return field;\n}\n\n// Uncorrelated bypass test (never references the governed row), so it is InitPlan-hoisted in both forms.\nfunction buildBypassExistsSqlText(bypass: { roleValues: string[]; scopeKind?: string }, grantsText: string): string {\n const scopeKind = bypass.scopeKind ?? \"platform\";\n return `exists (\n select 1\n from jsonb_array_elements(${grantsText}) as bypass_grant\n where bypass_grant -> 'scope' ->> 'kind' = ${renderInlineSql(sql`${scopeKind}`)}\n and bypass_grant ->> 'role' in (${buildRoleInListSqlText(bypass.roleValues)})\n )`;\n}\n\nfunction buildGrantScopePredicate(options: SupabaseGrantScopeNativePoliciesOptions): SQL {\n const scopeKind = options.scopeKind;\n assertIdentifier(scopeKind, \"scopeKind\");\n const scopeIdField = resolveGrantScopeIdField(options);\n const castType = options.scopeCastType ?? defaultGrantScopeCastType;\n assertTypeName(castType, \"scopeCastType\");\n const grantsText = buildGrantsArraySqlText(resolveGrantsClaimPath(options.grantsClaimPath));\n const roleIn = buildRoleInListSqlText(options.roleValues);\n const kindMatch = `grant_elem -> 'scope' ->> 'kind' = ${renderInlineSql(sql`${scopeKind}`)} and grant_elem ->> 'role' in (${roleIn})`;\n const idExpr = `(grant_elem -> 'scope' ->> ${renderInlineSql(sql`${scopeIdField}`)})::${castType}`;\n\n // Correct: uncorrelated `= ANY(ARRAY(select …))` → the grant set materializes once (InitPlan, JWT\n // parsed once) and the ScalarArrayOp drives a bitmap index scan on the scope column — ~25-45× faster\n // at scale than `IN (select …)`, which the planner costs as a hashed semi-join → sequential scan (the\n // rls-read perf track proves both). Naive: correlated `EXISTS` referencing the governed scope column →\n // re-evaluated per row (JWT parsed per row). The column object is spliced so it serializes qualified —\n // valid CREATE POLICY DDL on the write path.\n const base = options.naive\n ? sql`exists (select 1 from jsonb_array_elements(${sql.raw(grantsText)}) as grant_elem where ${sql.raw(kindMatch)} and ${sql.raw(idExpr)} = ${options.scopeColumn})`\n : sql`${options.scopeColumn} = any(array(select ${sql.raw(idExpr)} from jsonb_array_elements(${sql.raw(grantsText)}) as grant_elem where ${sql.raw(kindMatch)}))`;\n\n if (!options.bypass) {\n return base;\n }\n return or(base, sql.raw(buildBypassExistsSqlText(options.bypass, grantsText)))!;\n}\n\n/**\n * Native Drizzle RLS policies for a JWT-resident grant set (see the section comment). Pass the real\n * scope column; the governed table name is derived from it. By default the predicate is the\n * InitPlan-correct uncorrelated `IN (subquery)`; pass `naive: true` for the correlated cliff variant.\n */\nexport function buildSupabaseGrantScopeNativePolicies(options: SupabaseGrantScopeNativePoliciesOptions) {\n const predicate = buildGrantScopePredicate(options);\n const tableName = tableNameForColumn(options.scopeColumn, \"scopeColumn\");\n const suffix = options.naive ? \"grant_scope_naive\" : \"grant_scope\";\n\n return grantScopePolicyShapes.map((shape) =>\n pgPolicy(`${tableName}_${shape.command}_${suffix}`, {\n as: \"permissive\",\n for: shape.command,\n to: options.role,\n ...(shape.using ? { using: predicate } : {}),\n ...(shape.withCheck ? { withCheck: predicate } : {}),\n }),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Electric read-path mirror of the grant-scope policy. Electric cannot read RLS, so the proxy must\n// resolve the same visible scope-id set from the claims in JS and inject a literal `IN (…)` shape\n// `where`. These two helpers are the read-path counterpart to the policy above — one declaration,\n// two enforcement surfaces, derived from the same grant data so they cannot drift.\n// ---------------------------------------------------------------------------\n\nfunction readClaimsPath(claims: JwtClaims | null, path: string[]): unknown {\n let current: unknown = claims;\n for (const segment of path) {\n if (typeof current !== \"object\" || current === null || Array.isArray(current)) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n}\n\n/**\n * The set of scope ids the caller can see, resolved from the JWT grants — the JS mirror of the\n * grant-scope RLS subquery. Returns a de-duplicated list (empty → no rows visible).\n */\nexport function resolveGrantScopeIds(claims: JwtClaims | null, options: GrantScopeClaimOptions): string[] {\n const grants = readClaimsPath(claims, resolveGrantsClaimPath(options.grantsClaimPath));\n if (!Array.isArray(grants)) {\n return [];\n }\n\n const scopeIdField = resolveGrantScopeIdField(options);\n const roleValues = new Set(options.roleValues);\n const ids = new Set<string>();\n\n for (const grant of grants) {\n if (typeof grant !== \"object\" || grant === null) {\n continue;\n }\n const record = grant as Record<string, unknown>;\n if (!roleValues.has(String(record[\"role\"]))) {\n continue;\n }\n const scope = record[\"scope\"];\n if (typeof scope !== \"object\" || scope === null) {\n continue;\n }\n const scopeRecord = scope as Record<string, unknown>;\n if (scopeRecord[\"kind\"] !== options.scopeKind) {\n continue;\n }\n const id = scopeRecord[scopeIdField];\n if (typeof id === \"string\" && id.length > 0) {\n ids.add(id);\n }\n }\n\n return [...ids];\n}\n\n/**\n * The Electric shape `where` for a grant-scope table: an `IN (…)` over the resolved ids (what the\n * proxy injects). Takes the real Drizzle scope column — referenced bare via `c()` (Electric's grammar\n * requires bare columns), so the reference is rename-safe — and returns a typed fragment whose ids\n * are **bound params** once `buildRowFilterShape` serializes it (never hand-escaped literals). An\n * empty id set denies all rows ({@link DENY_ALL}), mirroring the policy returning no rows.\n */\nexport function buildGrantScopeShapeWhere(scopeColumn: AnyColumn, ids: string[]): SQL {\n if (ids.length === 0) {\n return DENY_ALL;\n }\n return sql`${c(scopeColumn)} in (${sql.join(\n ids.map((id) => sql`${id}`),\n sql`, `,\n )})`;\n}\n",
119
119
  "// Opt-in runtime instrumentation for diagnosing convergence / sync latency in a live app (e.g. the\n// board demo). It is OFF by default and adds nothing to a normal run: every call early-returns unless\n// `globalThis.__pgxsinkitDebug` is truthy, so it is safe to leave the call sites in shipping code.\n//\n// Enable it from the browser console (`globalThis.__pgxsinkitDebug = true`) — or set it before the\n// client boots; the board's dev build turns it on automatically. Each line is stamped with a monotonic\n// millisecond clock so the gaps between phases (enqueue → flush → server ack → Electric echo →\n// overlay clear → live-query render) can be read straight off the console.\n\ninterface DebugGlobal {\n __pgxsinkitDebug?: boolean;\n}\n\nconst isEnabled = (): boolean => (globalThis as DebugGlobal).__pgxsinkitDebug === true;\n\nconst now = (): number => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n\n/**\n * A sink that receives every `syncDebug` line (event, the worker's monotonic stamp, optional data),\n * INDEPENDENT of the local `__pgxsinkitDebug` console gate. This is the seam `defineSyncWorker` installs\n * to forward the debug rail to tabs (ADR-0032 decision 7): a SharedWorker's own console is invisible\n * (`chrome://inspect`), so lines must cross the bridge and each tab re-prints them gated on ITS OWN flag.\n * Unset by default → no forwarding and zero cost on the in-process path.\n */\ntype SyncDebugSink = (event: string, stamp: number, data?: Record<string, unknown>) => void;\nlet syncDebugSink: SyncDebugSink | undefined;\n\n/** Install (or clear, with `undefined`) the debug-rail sink. Idempotent; `defineSyncWorker` owns it. */\nexport function setSyncDebugSink(sink: SyncDebugSink | undefined): void {\n syncDebugSink = sink;\n}\n\n/**\n * Log one timestamped event. Prints to the console only when `globalThis.__pgxsinkitDebug` is on, but ALSO\n * feeds any installed {@link setSyncDebugSink} sink (so the worker can forward the rail to tabs even when the\n * worker's own console gate is off). No sink AND not enabled → an early return, so the off-path pays nothing.\n */\nexport function syncDebug(event: string, data?: Record<string, unknown>): void {\n const enabled = isEnabled();\n if (!enabled && syncDebugSink === undefined) return;\n const stamp = now();\n if (enabled) {\n const prefix = `[pgxsinkit ${stamp.toFixed(0)}ms]`;\n if (data) {\n console.debug(`${prefix} ${event}`, data);\n } else {\n console.debug(`${prefix} ${event}`);\n }\n }\n syncDebugSink?.(event, stamp, data);\n}\n\n/** The request URL of a `fetch` first argument, in any of its accepted forms; undefined if unreadable. */\nfunction fetchInputUrl(input: Parameters<typeof fetch>[0]): string | undefined {\n if (typeof input === \"string\") return input;\n if (input instanceof URL) return input.toString();\n if (typeof input === \"object\" && input !== null && \"url\" in input) {\n return (input as { url: string }).url;\n }\n return undefined;\n}\n\n/**\n * Wrap a `fetch` so every ShapeStream request (the Electric read-path long-poll/catch-up) emits a start\n * line (shape/table, offset, live — derived from the request URL params) and a completion line (status,\n * ms, and whether the response is up-to-date). Passthrough when instrumentation is off: the early return\n * runs before any URL parsing, so the off-path pays nothing per request beyond this closure itself.\n *\n * Inject it as a ShapeStream `fetchClient`; pass the stream's existing `fetchClient` (if any) as the base\n * so the instrumentation composes rather than replaces.\n */\nexport function instrumentShapeFetch(baseFetch: typeof fetch = fetch): typeof fetch {\n const wrapped = (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]): Promise<Response> => {\n if (!isEnabled()) return baseFetch(input, init);\n const url = fetchInputUrl(input);\n const params = url ? new URL(url).searchParams : undefined;\n // Derive the shape identity ONCE and name it on BOTH the start and done lines, so a start/done pair\n // is readable without cross-referencing timing (multiple shapes' requests interleave on the rail).\n const shape = params?.get(\"table\") ?? undefined;\n const live = params?.get(\"live\") === \"true\";\n const offset = params?.get(\"offset\") ?? undefined;\n // The handle chain is the backlog-0001 forensic: WHICH handle each request carried, which one the\n // response minted, and whether the stale-cache ladder's params were on the wire — so a\n // dead-handle-served-N-times storm reads straight off the rail (same responseHandle across busted\n // attempts) instead of needing a network-tab capture at the moment of recurrence.\n const requestHandle = params?.get(\"handle\") ?? undefined;\n const cacheBuster = params?.has(\"cache-buster\") ?? false;\n const expiredHandle = params?.get(\"expired_handle\") ?? undefined;\n // The whole request identity rides in ONE compact string field: Chrome's console preview truncates\n // object previews at ~5 properties, and a captured log (the only artifact of a live recurrence) keeps\n // just the preview — separate fields silently vanish exactly when they matter (backlog 0001).\n const cursor = params?.get(\"cursor\") ?? undefined;\n const req = [\n `${shape ?? \"?\"}@${offset ?? \"?\"}`,\n live ? \"live\" : \"catchup\",\n requestHandle ? `h=${requestHandle}` : \"no-handle\",\n // The live-cycle cursor is Electric's CDN-collapse defense — its absence or non-advancement on\n // live polls is itself a finding (backlog 0001).\n cursor ? `c=${cursor}` : live ? \"NO-CURSOR\" : \"\",\n cacheBuster ? \"BUSTED\" : \"\",\n expiredHandle ? `expired=${expiredHandle}` : \"\",\n ]\n .filter(Boolean)\n .join(\" \");\n syncDebug(\"shape request start\", { req });\n const startedAt = now();\n return baseFetch(input, init).then((response) => {\n // Same single-string discipline for the response half: status/ms stay first-class (they are what\n // rail readers scan), the forensic chain (up-to-date, minted handle, end offset) folds into `resp`.\n const responseHandle = response.headers.get(\"electric-handle\");\n const responseOffset = response.headers.get(\"electric-offset\");\n const responseCursor = response.headers.get(\"electric-cursor\");\n const age = response.headers.get(\"age\");\n const resp = [\n response.headers.has(\"electric-up-to-date\") ? \"up-to-date\" : \"\",\n responseHandle && responseHandle !== requestHandle ? `minted h=${responseHandle}` : \"\",\n responseOffset ? `end=${responseOffset}` : \"\",\n responseCursor ? `c=${responseCursor}` : \"\",\n age ? `age=${age}` : \"\",\n ]\n .filter(Boolean)\n .join(\" \");\n syncDebug(\"shape request done\", {\n req,\n status: response.status,\n ms: Math.round(now() - startedAt),\n ...(resp ? { resp } : {}),\n });\n return response;\n });\n };\n // `typeof fetch` (Bun's global) carries a `preconnect` member the wrapper neither has nor needs — the\n // ShapeStream only ever invokes fetchClient as a plain fetch — so the shape-compatible cast is safe.\n return wrapped as typeof fetch;\n}\n\n/**\n * Run `fn`, logging `<event> done` with its wall-clock duration (and any extra `data`). When\n * instrumentation is off this is a thin pass-through with no logging and no timing overhead beyond the\n * call itself. Returns whatever `fn` returns.\n */\nexport async function timeAsync<T>(event: string, fn: () => Promise<T>, data?: Record<string, unknown>): Promise<T> {\n if (!isEnabled()) return fn();\n const startedAt = now();\n syncDebug(`${event} start`, data);\n try {\n return await fn();\n } finally {\n syncDebug(`${event} done`, { ms: Math.round(now() - startedAt) });\n }\n}\n",
120
+ "// Boot observability (ADR-0034). Every client boot builds a structured, versioned {@link BootReport} as it\n// runs and finalizes it exactly once at `onInitialSync` (the moment the `boot client ready` rail line fires\n// and `ready` resolves). The report is a plain, allocation-light object — no class instance leaks out — so\n// it structured-clones across the worker bridge unchanged.\n//\n// The numbers are captured INDEPENDENTLY of the debug rail: `timeAsync` only measures when\n// `__pgxsinkitDebug` is on, but the report must exist on every boot, so the builder always measures. It\n// still emits the SAME rail lines `timeAsync` would (`<event> start` / `<event> done {ms}`), gated by\n// `syncDebug`'s own console/sink gate, so the log text tools and tests match is unchanged.\n\nimport { syncDebug } from \"./debug\";\n\n/** Monotonic clock (ms) — `performance.now()` where available, else `Date.now()`. */\nconst nowMs = (): number => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n\n/**\n * A structured, versioned record of one client boot (ADR-0034). `reportVersion` is a contract number:\n * additive fields keep it, a breaking reshape bumps it. All durations are milliseconds; all `*AtMs` are\n * offsets from boot start (the `startedAt` epoch anchor is the only wall-clock value).\n */\nexport interface BootReport {\n reportVersion: 1;\n /** How the engine booted: the in-process client (bun/Node/fallback) or inside `defineSyncWorker`. */\n mode: \"in-process\" | \"worker\";\n /** Whether the caller proved the store a schemaless spare (the ADR-0032 S4 fresh-store hint). */\n freshStore: boolean;\n /** Whether the ADR-0032 S4 fetch/schema overlap was active for this boot. */\n overlapPrefetch: boolean;\n /** The registry fingerprint the store is provisioned under — the same value store-version reconcile stamps. */\n registryFingerprint: string;\n /** Epoch anchor (`Date.now()`) at boot start; every other duration/offset is monotonic relative to it. */\n startedAt: number;\n /** Boot start → `onInitialSync` (all eager groups caught up). */\n totalMs: number;\n /**\n * Present only when the store was pre-provisioned (a spare's initdb ran off-thread before this boot\n * adopted it); `null` otherwise. When present, `phases.pgliteCreateMs` is `null` — the create cost is\n * reported here instead.\n */\n provision: {\n /** The spare's PGlite create (initdb) cost, paid at provision time. */\n initdbMs: number;\n /** How long the provisioned store sat ready before this boot adopted it. */\n provisionedMsBeforeBoot: number;\n } | null;\n phases: {\n /** PGlite create cost, or `null` when the store was adopted from a spare (see {@link BootReport.provision}). */\n pgliteCreateMs: number | null;\n schemaExecMs: number;\n journalRecoveryMs: number;\n storeVersionReconcileMs: number;\n /**\n * `startConfiguredSync`: stream/group construction wall. On an overlap boot (ADR-0032 S4,\n * {@link BootReport.overlapPrefetch}) the early-started segment runs concurrently with schema/journal/\n * reconcile, so this includes that shared wall. Structurally 0 when the boot is ready inside the\n * sync-start call itself (zero eager groups / instant catch-up) — finalize runs before the phase closes.\n */\n syncStartMs: number;\n /** Sync-start done → last eager boot group ready. */\n catchupMs: number;\n /**\n * Cumulative time in configured prepare hooks (`prepareLocalDbBeforeSchema` + `prepareLocalDb`), present\n * only when at least one hook is configured. Not part of the required v1 shape (ADR-0034).\n */\n prepareMs?: number;\n };\n /**\n * Per consistency GROUP, for the eager + promoted boot groups only (a lazily-activated-later group never\n * appears — nor mutates a finalized report). Groups run concurrently, so `fetchMs`/`applyMs` are per-group\n * wall SEGMENTS, not a partition of `totalMs`.\n */\n groups: Array<{\n groupKey: string;\n /** Number of member tables (shapes) in the group. */\n tables: number;\n /** Offset from boot start when the group's streams started. */\n startedAtMs: number;\n /** Offset from boot start when the group reached its initial sync. */\n readyAtMs: number;\n /** Number of batch deliveries the group's stream chain received during boot catch-up. */\n requests: number;\n /** Number of change rows ingested during boot catch-up. */\n rows: number;\n /**\n * Settle→next-delivery wall within this group's chain. On the single-threaded WASM host this absorbs\n * OTHER groups' apply transactions and main-thread work between deliveries — read it as \"time this\n * group spent not applying\", an upper bound on its network wait, not pure network cost.\n */\n fetchMs: number;\n /**\n * Wall around this group's batch commits into PGlite. Includes waiting behind another group's\n * transaction on the shared connection (single writer), so concurrent groups' `applyMs` can overlap.\n */\n applyMs: number;\n }>;\n}\n\n/** The phase durations the builder captures by key; `catchupMs` is derived, not a captured phase. */\ntype PhaseKey = \"schemaExec\" | \"journalRecovery\" | \"storeVersionReconcile\" | \"syncStart\";\n\n/**\n * The per-group accumulator the engine stamps as a boot group's stream chain delivers and applies (ADR-0034).\n * One per consistency group (one `syncShapesToTables` call). Frozen at the group's ready edge so later live\n * traffic never mutates a finalized report.\n */\nexport interface GroupBootStamp {\n /** A batch was delivered to the group's subscribe callback (one response). `changeCount` = its change rows. */\n onBatchDelivered: (changeCount: number) => void;\n /** A commit transaction applied `ms` of work into PGlite for this group. */\n onApply: (ms: number) => void;\n /** The group reached its initial sync — stamp `readyAtMs` and freeze accumulation. */\n markReady: () => void;\n}\n\n/** The seam `startConfiguredSync` uses to open a boot group's accumulator (implemented by the builder). */\nexport interface BootStampCollector {\n beginGroup: (groupKey: string, tables: number) => GroupBootStamp;\n}\n\ninterface GroupAccumulator extends GroupBootStamp {\n snapshot: () => BootReport[\"groups\"][number];\n}\n\nfunction createGroupAccumulator(groupKey: string, tables: number, bootStartPerf: number): GroupAccumulator {\n const startedAtMs = nowMs() - bootStartPerf;\n let requests = 0;\n let rows = 0;\n let fetchMs = 0;\n let applyMs = 0;\n let readyAtMs: number | null = null;\n // `markReady` fires from INSIDE the ready-causing commit (before that delivery's `onApply` runs), so we\n // must record that commit's apply before freezing. So `markReady` only flags ready; the freeze snaps shut\n // at the START of the NEXT delivery — the first that is genuinely post-boot live traffic.\n let readyReached = false;\n let frozen = false;\n // Marks the last settle point; the gap to the next delivery is fetch (network) wait. Seeded at creation so\n // the first delivery's gap is the initial catch-up wait.\n let lastMark = nowMs();\n\n return {\n onBatchDelivered: (changeCount) => {\n // A delivery arriving after the group is ready is post-boot live traffic — freeze here so it (and its\n // apply) is excluded, leaving the ready-causing batch fully recorded.\n if (readyReached) frozen = true;\n if (frozen) return;\n const now = nowMs();\n fetchMs += Math.max(0, now - lastMark);\n lastMark = now;\n requests += 1;\n rows += changeCount;\n },\n onApply: (ms) => {\n if (frozen) return;\n applyMs += ms;\n // Exclude the apply wall from the NEXT fetch gap (the apply happens inside the delivery callback).\n lastMark = nowMs();\n },\n markReady: () => {\n if (readyAtMs != null) return;\n readyAtMs = nowMs() - bootStartPerf;\n readyReached = true;\n },\n snapshot: () => ({\n groupKey,\n tables,\n startedAtMs,\n readyAtMs: readyAtMs ?? nowMs() - bootStartPerf,\n requests,\n rows,\n fetchMs,\n applyMs,\n }),\n };\n}\n\n/** Builds a {@link BootReport} across a boot and finalizes it exactly once. Owned by `createSyncClient`. */\nexport interface BootReportBuilder extends BootStampCollector {\n /** The monotonic anchor (`performance.now()` at boot start) every offset is relative to. */\n readonly bootStartPerf: number;\n /**\n * Time `fn`, always measuring (unlike `timeAsync`, which only measures when the rail is on) and capturing\n * the duration into the report, while emitting the SAME rail lines `timeAsync` would. `key` is `null` for\n * a prepare hook (folded into the optional `prepareMs`).\n */\n phase: <T>(\n key: PhaseKey | \"prepare\",\n event: string,\n fn: () => Promise<T>,\n data?: Record<string, unknown>,\n ) => Promise<T>;\n setPgliteCreateMs: (ms: number | null) => void;\n setProvision: (provision: BootReport[\"provision\"]) => void;\n /**\n * Record `phases.syncStartMs` directly — for the ADR-0032 S4 overlap path, where sync construction is\n * kicked off before schema exec (not wrapped in {@link BootReportBuilder.phase}) and has no rail line.\n */\n setSyncStartMs: (ms: number) => void;\n /** Capture the offset at which sync construction completed — the base for `catchupMs`. */\n markSyncStartDone: () => void;\n /** Build + store the report once (idempotent). Returns the report, or the already-built one on a re-call. */\n finalize: () => BootReport;\n /** The finalized report, or `null` before the first boot completes / after an early stop. */\n report: () => BootReport | null;\n}\n\n/** Inputs known at boot start — the flags and identity the report carries verbatim. */\nexport interface BootReportInit {\n mode: BootReport[\"mode\"];\n freshStore: boolean;\n overlapPrefetch: boolean;\n registryFingerprint: string;\n}\n\nexport function createBootReportBuilder(init: BootReportInit): BootReportBuilder {\n const startedAt = Date.now();\n const bootStartPerf = nowMs();\n const durations = new Map<PhaseKey, number>();\n let prepareMs: number | null = null;\n let pgliteCreateMs: number | null = null;\n let provision: BootReport[\"provision\"] = null;\n let syncStartDoneOffset: number | null = null;\n const groups: GroupAccumulator[] = [];\n let built: BootReport | null = null;\n\n const duration = (key: PhaseKey): number => durations.get(key) ?? 0;\n\n return {\n bootStartPerf,\n phase: async (key, event, fn, data) => {\n const startedAtPerf = nowMs();\n // Mirror `timeAsync`'s rail lines exactly (text tools/tests match); `syncDebug` self-gates the console.\n syncDebug(`${event} start`, data);\n try {\n return await fn();\n } finally {\n const ms = nowMs() - startedAtPerf;\n syncDebug(`${event} done`, { ms: Math.round(ms) });\n if (key === \"prepare\") prepareMs = (prepareMs ?? 0) + ms;\n else durations.set(key, ms);\n }\n },\n setPgliteCreateMs: (ms) => {\n pgliteCreateMs = ms;\n },\n setProvision: (value) => {\n provision = value;\n },\n setSyncStartMs: (ms) => {\n durations.set(\"syncStart\", ms);\n },\n markSyncStartDone: () => {\n syncStartDoneOffset = nowMs() - bootStartPerf;\n },\n beginGroup: (groupKey, tables) => {\n const accumulator = createGroupAccumulator(groupKey, tables, bootStartPerf);\n groups.push(accumulator);\n return accumulator;\n },\n finalize: () => {\n if (built) return built;\n const totalMs = nowMs() - bootStartPerf;\n const syncStartBase = syncStartDoneOffset ?? totalMs;\n built = {\n reportVersion: 1,\n mode: init.mode,\n freshStore: init.freshStore,\n overlapPrefetch: init.overlapPrefetch,\n registryFingerprint: init.registryFingerprint,\n startedAt,\n totalMs,\n provision,\n phases: {\n pgliteCreateMs,\n schemaExecMs: duration(\"schemaExec\"),\n journalRecoveryMs: duration(\"journalRecovery\"),\n storeVersionReconcileMs: duration(\"storeVersionReconcile\"),\n syncStartMs: duration(\"syncStart\"),\n catchupMs: Math.max(0, totalMs - syncStartBase),\n ...(prepareMs != null ? { prepareMs } : {}),\n },\n groups: groups.map((group) => group.snapshot()),\n };\n return built;\n },\n report: () => built,\n };\n}\n",
120
121
  "/**\n * The opt-in convergence driver (ADR-0005 decision 3).\n *\n * The mechanism primitives (`flush` / `reconcile` / `retryFailed`) stay public and manual.\n * This driver is the *scheduling-policy seam*: the app decides WHEN to converge (online?\n * foregrounded? on power?) and how it learns those conditions, while the library owns the\n * convergence pass and the congestion policy (jittered backoff + attempt cap, already in the\n * mutation runtime). Pass nothing to `createSyncClient` → fully manual, today's behaviour.\n *\n * A pass is `flush` → `reconcile`. It deliberately does NOT call `retryFailed`: `flush`\n * already re-attempts `failed` mutations whose `next_retry_at_us` backoff has elapsed, so a\n * pass leaves the jittered backoff intact. Calling `retryFailed` on every pass would reset\n * every failed mutation to \"due now\" and, under a short trigger interval, burn the whole\n * attempt budget during a transient outage and quarantine writes prematurely. `retryFailed`\n * stays a manual, user-initiated primitive (\"retry my failed writes now\").\n */\n\nimport { syncDebug, timeAsync } from \"./debug\";\n\n/** The mechanism primitives a convergence pass schedules. */\nexport interface ConvergenceClient {\n flush: () => Promise<void>;\n reconcile: () => Promise<void>;\n}\n\n/**\n * The scheduling-policy seam. Browser (`online` / `visibilitychange`) and React Native\n * (`AppState` / `NetInfo`) are two genuine adapters — which is what earns this its place as a\n * seam rather than being inlined.\n */\nexport interface ConvergenceTrigger {\n /** Register a callback fired whenever the app wants a convergence attempt; returns an unsubscribe. */\n subscribe: (onSignal: () => void) => () => void;\n /** Whether a convergence pass should run right now (e.g. online and foregrounded). */\n shouldConverge: () => boolean;\n}\n\nexport interface ConvergenceDriverOptions {\n client: ConvergenceClient;\n trigger: ConvergenceTrigger;\n /** Invoked after each convergence pass with the error it raised, or `null` on success. */\n onPass?: (error: unknown) => void;\n}\n\nexport interface ConvergenceDriver {\n start: () => void;\n /**\n * Stop scheduling and **await any in-flight pass** before resolving, so a caller can then\n * safely close or wipe the underlying database without a pass racing against it. Idempotent.\n */\n stop: () => Promise<void>;\n /**\n * Request a convergence pass now — the event-driven path. The client calls this the moment a\n * mutation is enqueued, so a local write flushes immediately instead of waiting for the trigger's\n * next interval tick. Coalesced exactly like a trigger signal (one pass at a time; a request mid-pass\n * queues a single follow-up) and still gated by `shouldConverge()`, so a write made while offline\n * stages without flushing. With this, the trigger's interval is only a fallback (retries/recovery),\n * which lets it run far less often — the interval, not real convergence, is what costs idle CPU.\n */\n requestPass: () => void;\n}\n\n/**\n * Drive convergence from a {@link ConvergenceTrigger}. Each signal runs at most one pass at a\n * time (`flush` → `reconcile`); a signal arriving mid-pass coalesces into a single follow-up\n * pass, so a burst of triggers never stampedes the server (the per-mutation backoff in the\n * runtime handles the rest).\n */\nexport function createConvergenceDriver(options: ConvergenceDriverOptions): ConvergenceDriver {\n let unsubscribe: (() => void) | null = null;\n let running = false;\n let queued = false;\n let disposed = false;\n // The promise of the pass currently in flight, so stop() can await it before teardown.\n let currentPass: Promise<void> | null = null;\n\n const runPass = async (): Promise<void> => {\n if (disposed || running) {\n if (!disposed) {\n queued = true;\n }\n // The signal that mattered most for latency: a write asked to converge but a pass was already\n // running, so this one coalesces and waits for the current pass to finish before it flushes.\n syncDebug(\"convergence pass coalesced (one already running)\", { disposed, queued });\n return;\n }\n\n if (!options.trigger.shouldConverge()) {\n syncDebug(\"convergence pass skipped (shouldConverge=false: offline or backgrounded)\");\n return;\n }\n\n running = true;\n let error: unknown = null;\n const pass = (async () => {\n try {\n await timeAsync(\"convergence flush\", () => options.client.flush());\n await timeAsync(\"convergence reconcile\", () => options.client.reconcile());\n } catch (passError) {\n error = passError;\n }\n })();\n currentPass = pass;\n await pass;\n running = false;\n currentPass = null;\n options.onPass?.(error);\n\n if (queued && !disposed) {\n queued = false;\n void runPass();\n }\n };\n\n return {\n start: () => {\n if (unsubscribe || disposed) {\n return;\n }\n\n unsubscribe = options.trigger.subscribe(() => {\n void runPass();\n });\n void runPass();\n },\n stop: async () => {\n disposed = true;\n queued = false;\n unsubscribe?.();\n unsubscribe = null;\n // Await the in-flight pass (if any) so the DB is quiescent before the caller closes/wipes it.\n await currentPass;\n },\n requestPass: () => {\n syncDebug(\"convergence pass requested (event-driven, e.g. local write enqueued)\");\n void runPass();\n },\n };\n}\n\n/** Minimal browser globals the trigger needs, read off `globalThis` so the library carries no DOM lib dependency. */\ninterface EventTargetLike {\n addEventListener: (type: string, handler: () => void) => void;\n removeEventListener: (type: string, handler: () => void) => void;\n}\ninterface BrowserEnv {\n window?: EventTargetLike;\n document?: EventTargetLike & { visibilityState?: string };\n navigator?: { onLine?: boolean };\n}\n\n/**\n * Browser convergence trigger: fires on `online`, `visibilitychange`, and a fallback interval,\n * and converges only while online and not backgrounded. The adapter most apps use.\n */\nexport function createBrowserConvergenceTrigger(options: { intervalMs?: number } = {}): ConvergenceTrigger {\n const intervalMs = options.intervalMs ?? 1500;\n const env = globalThis as unknown as BrowserEnv;\n\n return {\n subscribe: (onSignal) => {\n const handler = () => {\n onSignal();\n };\n env.window?.addEventListener(\"online\", handler);\n env.document?.addEventListener(\"visibilitychange\", handler);\n const timer = setInterval(handler, intervalMs);\n\n return () => {\n env.window?.removeEventListener(\"online\", handler);\n env.document?.removeEventListener(\"visibilitychange\", handler);\n clearInterval(timer);\n };\n },\n shouldConverge: () => env.navigator?.onLine !== false && env.document?.visibilityState !== \"hidden\",\n };\n}\n\n/**\n * Interval convergence trigger: fires on a fixed cadence and always converges. The minimal\n * non-browser adapter — usable directly in tests/servers and the base a React Native\n * `AppState`/`NetInfo` adapter builds on — which is the second adapter that proves the seam.\n */\nexport function createIntervalConvergenceTrigger(intervalMs: number): ConvergenceTrigger {\n return {\n subscribe: (onSignal) => {\n const timer = setInterval(() => {\n onSignal();\n }, intervalMs);\n\n return () => {\n clearInterval(timer);\n };\n },\n shouldConverge: () => true,\n };\n}\n",
121
- "import { getTableConfig, getViewConfig } from \"drizzle-orm/pg-core\";\n\nimport type { SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\n/**\n * Lazy-relation safety (ADR-0021).\n *\n * A `lazy` relation is held out of the eager boot and only subscribed on first reference. The hazard is\n * a query reading it *before* it is hydrated — which silently returns empty/stale rows. This pure,\n * React-free core detects which lazy relations a query reads by scanning its **compiled** SQL, so the\n * caller can activate them (and hydrate-then-run) before the query executes.\n *\n * Why a single SQL scan is sufficient (and why there is no Proxy / builder-AST walk): Drizzle compiles\n * a query to parameterised SQL — values are bound (`$1`, `$2`), never inlined — and emits every relation\n * as a **quoted** identifier (`\"name\"`, or `\"schema\".\"name\"` when it carries a schema). So the compiled\n * SQL is ground truth: a relation the query reads must appear there by name, and the only things in the\n * text are quoted identifiers, keywords and `$n` placeholders. The index is built from the *same* Drizzle\n * objects that emit the SQL (`getTableConfig`/`getViewConfig`), so a token matches emission by\n * construction — schema and all. See \"Known limitations\" in ADR-0021 for the residual edges.\n */\n\n/** Static index of a registry's lazy relations and the exact quoted tokens their reads compile to. */\nexport interface LazyGuardIndex {\n /** Registry keys whose subscription timing is `lazy`. */\n readonly lazyKeys: ReadonlySet<string>;\n /**\n * Per lazy key, the exact quoted reference token(s) the compiled SQL emits when reading it: the synced\n * table (and, for readwrite, its read-model view) as `\"name\"` or `\"schema\".\"name\"`. Schema-qualified\n * when the Drizzle object carries a schema — which makes the token collision-proof against bare\n * aliases/CTEs.\n */\n readonly lazyTokens: ReadonlyMap<string, readonly string[]>;\n}\n\n/** Build the {@link LazyGuardIndex} for a registry. Cheap and pure — cache it per client. */\nexport function buildLazyGuardIndex(registry: SyncTableRegistry): LazyGuardIndex {\n const lazyKeys = new Set<string>();\n const lazyTokens = new Map<string, readonly string[]>();\n\n for (const [key, entry] of Object.entries(registry)) {\n if (entry.subscription !== \"lazy\") continue;\n lazyKeys.add(key);\n\n const tokens: string[] = [];\n const table = getTableConfig(entry.table);\n tokens.push(quotedRef(table.name, table.schema));\n if (entry.view != null) {\n const view = getViewConfig(entry.view);\n tokens.push(quotedRef(view.name, view.schema));\n }\n lazyTokens.set(key, tokens);\n }\n\n return { lazyKeys, lazyTokens };\n}\n\n/** The quoted identifier Drizzle emits for a relation: `\"schema\".\"name\"` when schema-qualified, else `\"name\"`. */\nfunction quotedRef(name: string, schema: string | undefined): string {\n return schema != null && schema.length > 0 ? `\"${schema}\".\"${name}\"` : `\"${name}\"`;\n}\n\n/**\n * The compiled-SQL scan: the lazy registry keys whose quoted reference token appears in `sql`. Because\n * the token is fully quoted it is self-delimiting (`\"a\"` cannot match inside `\"ab\"`), so a substring test\n * is exact. A *bare* token sitting in alias position (`… as \"name\"`, which Drizzle emits for `.as(\"name\")`)\n * is excluded — the one realistic collision for a schema-less relation; a schema-qualified token cannot be\n * aliased and so needs no such guard.\n */\nexport function findReferencedLazyKeysInSql(sql: string, index: LazyGuardIndex): Set<string> {\n const found = new Set<string>();\n for (const [key, tokens] of index.lazyTokens) {\n if (tokens.some((token) => sqlReferencesToken(sql, token))) found.add(key);\n }\n return found;\n}\n\nfunction sqlReferencesToken(sql: string, token: string): boolean {\n for (let from = 0; ; ) {\n const at = sql.indexOf(token, from);\n if (at === -1) return false;\n // Exclude an alias occurrence: `<expr> as \"token\"`. Only a bare token can be an alias, so this never\n // rejects a real (schema-qualified or FROM/JOIN) reference. Window comfortably covers Drizzle's ` as `.\n if (!/\\bas\\s+$/i.test(sql.slice(Math.max(0, at - 16), at))) return true;\n from = at + token.length;\n }\n}\n\n/**\n * The activation backstop (ADR-0021): throw if a query references a lazy relation that is still not\n * active. Called *after* the referenced lazy relations have been activated, so in the normal path every\n * scanned relation is now active and this passes. It fires only when activation could not make a\n * referenced relation active (a start that failed, or a lazy relation with no consistency group) —\n * converting a would-be silent empty/stale read into a loud error.\n */\nexport function assertLazyRefsActivated(args: {\n sql: string;\n index: LazyGuardIndex;\n isActive: (key: string) => boolean;\n}): void {\n const referenced = findReferencedLazyKeysInSql(args.sql, args.index);\n const missing = [...referenced].filter((key) => !args.isActive(key));\n if (missing.length > 0) throw new LazyRelationNotActivatedError(missing);\n}\n\n/** Thrown by the backstop ({@link assertLazyRefsActivated}) when a referenced lazy relation could not be activated. */\nexport class LazyRelationNotActivatedError extends Error {\n /** The lazy registry keys that were referenced but could not be activated. */\n readonly relations: readonly string[];\n\n constructor(relations: readonly string[]) {\n const quoted = relations.map((r) => `\"${r}\"`).join(\", \");\n super(\n `[pgxsinkit] query references lazy-synced relation(s) ${quoted} that could not be activated (ADR-0021), ` +\n `so it would read empty/stale data. This is usually a failed initial sync or a lazy relation with no ` +\n `consistency group. Activate it explicitly — client.ensureSynced([${quoted}]) — or check the sync ` +\n `status. See \"Known limitations\" in ADR-0021.`,\n );\n this.name = \"LazyRelationNotActivatedError\";\n this.relations = relations;\n }\n}\n",
122
+ "// Diagnostic dump (ADR-0035, via the throwaway clone of the addendum). Where a store backup keeps the\n// datadir tarball as its artefact, a diagnostic dump turns the store into human-readable SQL — every table\n// (synced + the `_overlay`/`_mutations` journal), the `pgxsinkit` metadata schema, the read-model views,\n// and the reconcile functions/triggers — so a support engineer sees the misbehaving store EXACTLY as it\n// holds it, unflushed writes and all.\n//\n// The mechanism is the addendum's throwaway clone, NOT the abandoned suspend/reopen seam: (1) take a LIVE\n// datadir dump of the running store (the SAME checkpoint + `dumpDataDir` core the store backup uses, but\n// uncompressed — the clone consumes it immediately, so the gzip+gunzip round trip is pure waste); (2) boot\n// a memory-backed THROWAWAY PGlite from that dump via `loadDataDir` — engine-less, no `live` extension,\n// nothing `pg_dump`'s `DEALLOCATE ALL` can corrupt; (3) run `pg_dump` against the throwaway; (4) discard\n// it. The live engine is never touched — the addendum's whole point — so tabs never notice beyond the\n// lifecycle slot reporting busy.\n//\n// `@electric-sql/pglite-tools` is loaded ONLY via the dynamic `import()` below (ADR-0035 decision 7): its\n// ~700 kB `pg_dump.wasm` (+ ~100 kB JS) stays off boot and off every non-exporting bundle, fetched on first\n// `exportDiagnostics`.\n\nimport { PGlite } from \"@electric-sql/pglite\";\n\nimport type { MutationDiagnostics } from \"@pgxsinkit/contracts\";\n\nimport { compactTimestamp, type DiagnosticDumpReport, deriveStoreId, nowMs, performDatadirDump } from \"./export-store\";\nimport type { ClientPGlite } from \"./index\";\nimport { resolveStoreDataDir } from \"./store-path\";\n\n/** Options for {@link SyncClient.exportDiagnostics}. */\nexport interface DiagnosticExportOptions {\n /**\n * Override the generated artefact file name. When omitted, the name is\n * `<storeId>-<timestamp>-diagnostics.sql`, where `storeId` is a filesystem-safe derivation of the store\n * path (see `deriveStoreId`).\n */\n fileName?: string;\n}\n\n/** The SQL artefact + its report — the resolved value of {@link SyncClient.exportDiagnostics}. */\nexport interface DiagnosticExportResult {\n /** The `pg_dump` output as a named `File` (`application/sql`), loadable into a vanilla Postgres. */\n file: File;\n /** The structured record of the export (ADR-0035). */\n report: DiagnosticDumpReport;\n}\n\n/** The dependencies {@link performDiagnosticExport} needs from the owning client — narrow, so it is unit-testable. */\nexport interface DiagnosticExportDeps {\n /** The live store to checkpoint and dump (the clone source; the live engine is never suspended). */\n pglite: Pick<ClientPGlite, \"exec\" | \"dumpDataDir\">;\n /** The Mutation diagnostics seam (`client.diagnostics().mutation` / `readMutationStats`). */\n readMutationStats: () => Promise<MutationDiagnostics>;\n /**\n * The store's configured plain store PATH (ADR-0036) — reduced to the `storeId` in the default artefact\n * file name. The resolved PGlite dataDir URL is deliberately NOT used: it is internal plumbing and must\n * not leak into an artefact name as something to imitate.\n */\n storePath?: string;\n}\n\n/**\n * The shape of `@electric-sql/pglite-tools/pg_dump` — declared locally so the dynamic `import()` stays\n * typed without a static top-level dependency on the module (which would pull its WASM into the boot\n * bundle). `pgDump` runs the WASM `pg_dump` on the given instance's single connection and returns the SQL\n * as a `File`. We run it against the THROWAWAY clone only, never the live engine.\n */\ninterface PgliteToolsModule {\n pgDump: (opts: { pg: PGlite; args?: string[]; fileName?: string }) => Promise<File>;\n}\n\n/**\n * A process-unique suffix source for the throwaway clone's store name. The clone is memory-backed and\n * closed in a `finally`, so a collision would only matter if two dumps overlapped — the lifecycle slot\n * already forbids that — but a monotonic counter plus a random token makes the name collision-free by\n * construction regardless, so a stray second clone can never adopt a live one's memory namespace.\n */\nlet cloneCounter = 0;\nconst nextCloneStorePath = (): string =>\n `pgxsinkit-export-clone-${++cloneCounter}-${Math.random().toString(36).slice(2, 10)}`;\n\n/** The four extra phase walls the throwaway-clone pipeline adds on top of the shared checkpoint/dump pair. */\nexport interface CloneDumpPhases {\n /** Offset from `startPerf` when the internal `dumpDataDir` (the clone's source) began. */\n dumpStartedAtMs: number;\n /** `dumpDataDir` wall — the uncompressed internal tarball the throwaway clone boots from (`compression: \"none\"`). */\n dumpMs: number;\n /** Offset from `startPerf` when the `CHECKPOINT` began. */\n checkpointStartedAtMs: number;\n /** `CHECKPOINT` wall — flushing dirty buffers before the internal datadir dump the clone consumes. */\n checkpointMs: number;\n /** Offset from `startPerf` when the throwaway clone's `PGlite.create({ loadDataDir })` began. */\n cloneBootStartedAtMs: number;\n /** Clone boot wall — booting the memory-backed throwaway from the internal dump. */\n cloneBootMs: number;\n /** Offset from `startPerf` when `pg_dump` began running against the clone. */\n pgDumpStartedAtMs: number;\n /** `pg_dump` wall — the WASM `pg_dump` reading the clone out to SQL. */\n pgDumpMs: number;\n}\n\n/** The raw SQL bytes plus the pipeline phase walls — {@link runThrowawayCloneDump}'s result. */\nexport interface CloneDumpResult {\n /** The `pg_dump` output bytes (unwrapped from pglite-tools' `File` polyfill). */\n sqlBytes: Uint8Array<ArrayBuffer>;\n /** The pipeline phase timings, all offset from the caller's `startPerf` anchor. */\n phases: CloneDumpPhases;\n}\n\n/**\n * The throwaway-clone dump core shared by BOTH `pgDump` exports (ADR-0035 addendum): (1) a LIVE datadir dump\n * of the running store (`compression: \"none\"` — the clone consumes the bytes immediately, so gzip+gunzip is\n * pure waste); (2) a memory-backed THROWAWAY PGlite booted from it via `loadDataDir` — engine-less, no\n * `live` extension, nothing `pg_dump`'s `DEALLOCATE ALL` can corrupt; (3) `pg_dump` against the throwaway\n * with the caller's `args` (none for a diagnostic dump; the `-t` allowlist + `--no-owner` for a data\n * export); (4) discard the clone in a `finally`. Factored out so `performDiagnosticExport` and\n * `performDataExport` cannot drift on the clone plumbing, the memory-scheme selection, or the timing house\n * style — the ONLY differences between the two dumps are the `pg_dump` args and the artefact assembly.\n *\n * `@electric-sql/pglite-tools` is loaded ONLY via the dynamic `import()` here (ADR-0035 decision 7): its\n * ~700 kB `pg_dump.wasm` (+ ~100 kB JS) stays off boot and off every non-exporting bundle.\n */\nexport interface CloneDumpOptions {\n /** The `pg_dump` args (none for a diagnostic dump; `-t` allowlist + `--no-owner` for a data export). */\n pgDumpArgs?: string[];\n /**\n * A hook run on the throwaway clone AFTER boot, BEFORE `pg_dump` — its one legitimate window to mutate the\n * clone (which is fully owned and discarded straight after). The data export uses it to drop the reconcile\n * triggers `pg_dump -t` would otherwise pull into the artefact (see `buildDataExportCloneCleanupSql`); a\n * diagnostic dump passes none (it wants the store verbatim).\n */\n prepareClone?: (clone: PGlite) => Promise<void>;\n}\n\nexport async function runThrowawayCloneDump(\n pglite: Pick<ClientPGlite, \"exec\" | \"dumpDataDir\">,\n startPerf: number,\n options: CloneDumpOptions = {},\n): Promise<CloneDumpResult> {\n // Step 1 — the LIVE datadir dump the clone boots from (checkpoint → `dumpDataDir`, the shared core).\n const { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs } = await performDatadirDump(\n pglite,\n \"none\",\n startPerf,\n );\n\n // Step 2 — boot the throwaway. Memory-backed via the resolution module's SCHEME selection (ADR-0036\n // decision 5: NEVER PGlite's explicit `fs: new MemoryFS()` — on 0.5.4 a `dumpDataDir` from an explicit-fs\n // instance silently omits post-initdb relation files). No extensions, no `electric` engine, no `live`:\n // the clone exists only to be read out by `pg_dump`, and `DEALLOCATE ALL` has nothing here to corrupt.\n const cloneDataDir = resolveStoreDataDir(nextCloneStorePath(), \"memory\");\n const cloneBootStartedAtMs = nowMs() - startPerf;\n const cloneBootStartPerf = nowMs();\n const throwaway = await PGlite.create({ dataDir: cloneDataDir, loadDataDir: dumped });\n const cloneBootMs = nowMs() - cloneBootStartPerf;\n\n let sqlBytes: Uint8Array<ArrayBuffer>;\n let pgDumpStartedAtMs: number;\n let pgDumpMs: number;\n try {\n // Between boot and dump — the clone's one mutation window (owned, discarded next) — run the caller's\n // prepare hook. The data export drops the reconcile triggers `-t` would otherwise capture; timed inside\n // the pgDump-prep gap, it is a couple of tiny DROPs, so it is not given its own report phase.\n if (options.prepareClone) {\n await options.prepareClone(throwaway);\n }\n\n // Step 3 — the lazy `pg_dump`. The subpath specifier (its export map's `./pg_dump` entry) keeps the\n // main pglite-tools entry — and its WASM — off this import. The caller rebuilds the artefact `File`\n // from the returned bytes, so `fileName` here is cosmetic only.\n pgDumpStartedAtMs = nowMs() - startPerf;\n const pgDumpStartPerf = nowMs();\n const { pgDump } = (await import(\"@electric-sql/pglite-tools/pg_dump\")) as PgliteToolsModule;\n const dumpFile = await pgDump({\n pg: throwaway,\n ...(options.pgDumpArgs != null ? { args: options.pgDumpArgs } : {}),\n fileName: \"pgxsinkit-export.sql\",\n });\n pgDumpMs = nowMs() - pgDumpStartPerf;\n sqlBytes = new Uint8Array(await dumpFile.arrayBuffer());\n } finally {\n // Step 4 — discard the throwaway in a `finally`, so a THROWING `pg_dump` never leaks the clone (its\n // memory is co-resident with the live engine for the export's duration; leaking one is a real cost).\n await throwaway.close();\n }\n\n return {\n sqlBytes,\n phases: {\n checkpointStartedAtMs,\n checkpointMs,\n dumpStartedAtMs,\n dumpMs,\n cloneBootStartedAtMs,\n cloneBootMs,\n pgDumpStartedAtMs,\n pgDumpMs,\n },\n };\n}\n\n/**\n * Run a diagnostic dump (ADR-0035): live datadir dump → memory-backed throwaway clone → `pg_dump` → discard\n * the clone → assemble the report. The caller (`createSyncClient`) awaits engine-ready and enters the\n * lifecycle slot BEFORE calling this, exactly as it does for the store backup — kept out of here so the\n * helper stays a pure \"do the dump\" unit.\n */\nexport async function performDiagnosticExport(\n deps: DiagnosticExportDeps,\n options: DiagnosticExportOptions = {},\n): Promise<DiagnosticExportResult> {\n const startedAt = Date.now();\n const startPerf = nowMs();\n\n // A diagnostic dump takes the WHOLE store (no `-t`): synced + overlay + journal + metadata + views +\n // functions — everything a support engineer needs to read a misbehaving store.\n const { sqlBytes, phases } = await runThrowawayCloneDump(deps.pglite, startPerf);\n\n const storeId = deriveStoreId(deps.storePath);\n const fileName = options.fileName ?? `${storeId}-${compactTimestamp()}-diagnostics.sql`;\n // Build the artefact `File` from the raw bytes, NOT by re-wrapping pglite-tools' `File`: it is a polyfill\n // in non-browser hosts, and `new File([polyfillFile], name)` keeps the polyfill's own name (the same bun\n // quirk the store backup hit) — the bytes-first path guarantees the store-scoped name/mime stick.\n const file = new File([sqlBytes], fileName, { type: \"application/sql\" });\n\n // Snapshot diagnostics of the LIVE store (the clone is already closed) — the journal state whose rows the\n // SQL also carries, so the report and the artefact agree on what was unflushed at dump time.\n const diagnostics = await deps.readMutationStats();\n\n const report: DiagnosticDumpReport = {\n reportVersion: 1,\n kind: \"diagnostic-dump\",\n scope: \"everything\",\n startedAt,\n totalMs: nowMs() - startPerf,\n byteLength: file.size,\n phases,\n diagnostics,\n };\n\n return { file, report };\n}\n",
123
+ "// Local store export (ADR-0035). Slice 1 ships the **store backup**: a full-fidelity, PGlite-restorable\n// tarball of the whole local store, taken LIVE (no engine suspension). It is a `CHECKPOINT` — run through\n// the engine's normal query serialisation so it orders behind in-flight engine work — followed by\n// PGlite's `dumpDataDir`. Because the dump is of the datadir itself, the Mutation journal and Overlay\n// travel INSIDE the artefact: a store backup is the lossless option, the only export an offline device\n// with unflushed writes can take (CONTEXT.md → Store backup).\n//\n// Every export resolves to an {@link ExportReport} alongside the artefact, extending the ADR-0034\n// observability rule (the BootReport house style) to exports: a versioned, allocation-light plain object\n// (structured-clones across the worker bridge unchanged) carrying phase timings, a {@link MutationDiagnostics}\n// snapshot, and a `startedAt` epoch anchor with every other value a monotonic offset/duration relative to it.\n\nimport type { MutationDiagnostics } from \"@pgxsinkit/contracts\";\n\nimport type { ClientPGlite } from \"./index\";\n\n/**\n * Monotonic clock (ms) — `performance.now()` where available, else `Date.now()` (mirrors BootReport).\n * Exported so the sibling diagnostic-dump path ({@link file://./export-dump.ts}) times its extra phases\n * (clone boot, pg_dump) on the SAME clock as this module's checkpoint/dump pair.\n */\nexport const nowMs = (): number => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n\n/** Options for {@link SyncClient.exportStore}. */\nexport interface StoreExportOptions {\n /**\n * How to compress the tarball, forwarded to PGlite's `dumpDataDir`. `\"auto\"` (the default) gzips when a\n * `CompressionStream` is available and falls back to an uncompressed tar otherwise; `\"gzip\"` forces\n * compression; `\"none\"` skips it. The report's `compression` records the compression that was actually\n * applied (which, under `\"auto\"`, is resolved at runtime).\n */\n compression?: \"auto\" | \"gzip\" | \"none\";\n /**\n * Override the generated artefact file name. When omitted, the name is\n * `<storeId>-<timestamp>.pgdata.tar[.gz]`, where `storeId` is a filesystem-safe derivation of the store\n * path and the extension reflects the applied compression.\n */\n fileName?: string;\n}\n\n/**\n * The fields EVERY export report carries, whatever its kind — built in the BootReport house style\n * (ADR-0034): `reportVersion` is a contract number (additive fields keep it, a breaking reshape bumps it);\n * all `*Ms` are milliseconds; `startedAt` is the only wall-clock value and every `*AtMs` is a monotonic\n * offset from it. The per-kind interfaces below add their `kind`/`scope`/`phases` discriminant on top.\n */\nexport interface ExportReportCommon {\n reportVersion: 1;\n /** Epoch anchor (`Date.now()`) at export start; every other duration/offset is monotonic relative to it. */\n startedAt: number;\n /** Export start → artefact ready. */\n totalMs: number;\n /** The artefact's byte length — the size the caller downloads / persists. */\n byteLength: number;\n /**\n * The {@link MutationDiagnostics} snapshot at export time — the journal state captured alongside the\n * artefact (for the store backup, the very journal that travels INSIDE the tarball; for the diagnostic\n * dump, the live store's journal at dump time, whose rows the SQL also carries).\n */\n diagnostics: MutationDiagnostics;\n}\n\n/**\n * A live **store backup** (ADR-0035): the whole datadir as a PGlite-restorable tarball, journal and overlay\n * included. `checkpoint`/`dump` are the only phases — a store backup is a `CHECKPOINT` + `dumpDataDir`, no\n * clone. Slice-1 shape, kept unchanged (the union is additive).\n */\nexport interface StoreBackupReport extends ExportReportCommon {\n /** Which export produced this artefact. */\n kind: \"store-backup\";\n /** What the artefact covers. A store backup is always the whole store, journal and overlay included. */\n scope: \"whole-store\";\n /** The compression actually applied to the tarball (resolved from `\"auto\"` at dump time). */\n compression: \"gzip\" | \"none\";\n phases: {\n /** Offset from export start when the `CHECKPOINT` began. */\n checkpointStartedAtMs: number;\n /** `CHECKPOINT` wall — flushing dirty buffers to the datadir before it is tarred, serialised behind engine work. */\n checkpointMs: number;\n /** Offset from export start when `dumpDataDir` began. */\n dumpStartedAtMs: number;\n /** `dumpDataDir` wall — reading the datadir out and assembling (optionally compressing) the tarball. */\n dumpMs: number;\n };\n}\n\n/**\n * A **diagnostic dump** (ADR-0035, via the throwaway clone of the addendum): human-readable SQL of\n * EVERYTHING the store holds — synced tables, the `_overlay`/`_mutations` journal, the `pgxsinkit` metadata\n * schema, the read-model views, and the reconcile functions/triggers. It is a live datadir dump (checkpoint\n * + `dumpDataDir`) fed into a memory-backed throwaway PGlite via `loadDataDir`, against which `pg_dump` runs\n * — so the live engine is never touched (the addendum's whole point). Its phases add the clone boot and the\n * `pg_dump` walls to the shared checkpoint/dump pair.\n */\nexport interface DiagnosticDumpReport extends ExportReportCommon {\n kind: \"diagnostic-dump\";\n /** A diagnostic dump covers everything the store holds — synced data, journal, metadata, views, functions. */\n scope: \"everything\";\n phases: {\n /** Offset from export start when the `CHECKPOINT` began. */\n checkpointStartedAtMs: number;\n /** `CHECKPOINT` wall — flushing dirty buffers before the internal datadir dump the clone consumes. */\n checkpointMs: number;\n /** Offset from export start when the internal `dumpDataDir` began. */\n dumpStartedAtMs: number;\n /** `dumpDataDir` wall — the uncompressed internal tarball the throwaway clone boots from (`compression: \"none\"`). */\n dumpMs: number;\n /** Offset from export start when the throwaway clone's `PGlite.create({ loadDataDir })` began. */\n cloneBootStartedAtMs: number;\n /** Clone boot wall — booting the memory-backed throwaway from the internal dump. */\n cloneBootMs: number;\n /** Offset from export start when `pg_dump` began running against the clone. */\n pgDumpStartedAtMs: number;\n /** `pg_dump` wall — the WASM `pg_dump` reading the clone out to SQL. */\n pgDumpMs: number;\n };\n}\n\n/**\n * A **data export** (ADR-0035 decision 1, via the throwaway clone of the addendum): the PORTABLE artefact —\n * the synced tables and the enum types they depend on, schema + data, nothing of pgxsinkit's machinery,\n * loadable into a vanilla Postgres. It is a generated enum DDL header concatenated ahead of a `pg_dump -t`\n * (per synced table) `--no-owner` run against the same memory-backed throwaway clone the diagnostic dump\n * uses. Unlike the other two exports it GUARDS: it requires a drained Mutation journal (or the explicit\n * `drainJournal: false` escape hatch), so its phases add the drain wall ahead of the clone pipeline, and it\n * records its provenance (`tables` = the `-t` allowlist actually applied, `escapeHatch` = whether the drain\n * was skipped).\n */\nexport interface DataExportReport extends ExportReportCommon {\n kind: \"data-export\";\n /** A data export covers the synced tables + their enum types only — never pgxsinkit's overlay/journal/metadata. */\n scope: \"synced-tables\";\n /**\n * The schema-qualified physical synced tables the `-t` allowlist targeted, in registry order — the\n * self-describing provenance of exactly what the artefact carries (ephemeral/read-projection entries\n * excluded by construction). May be empty when the registry declares no owning persistent table.\n */\n tables: string[];\n /**\n * `true` when `drainJournal: false` skipped the drain and the artefact reflects the SYNCED state as-is\n * (unflushed local writes silently absent). `false` on the strict path (a drained or empty journal).\n */\n escapeHatch: boolean;\n phases: {\n /** Offset from export start when the drain guard began (`0` when the escape hatch skipped it). */\n drainStartedAtMs: number;\n /** Drain wall — flushing + awaiting the journal reach fully-drained (`0` under the escape hatch). */\n drainMs: number;\n /** Offset from export start when the `CHECKPOINT` began. */\n checkpointStartedAtMs: number;\n /** `CHECKPOINT` wall — flushing dirty buffers before the internal datadir dump the clone consumes. */\n checkpointMs: number;\n /** Offset from export start when the internal `dumpDataDir` began. */\n dumpStartedAtMs: number;\n /** `dumpDataDir` wall — the uncompressed internal tarball the throwaway clone boots from (`compression: \"none\"`). */\n dumpMs: number;\n /** Offset from export start when the throwaway clone's `PGlite.create({ loadDataDir })` began. */\n cloneBootStartedAtMs: number;\n /** Clone boot wall — booting the memory-backed throwaway from the internal dump. */\n cloneBootMs: number;\n /** Offset from export start when `pg_dump -t` began running against the clone. */\n pgDumpStartedAtMs: number;\n /** `pg_dump -t` wall — the WASM `pg_dump` reading the allowlisted tables out to SQL. */\n pgDumpMs: number;\n };\n}\n\n/**\n * A structured, versioned record of one local-store export (ADR-0035) — a discriminated union on `kind`.\n * Every member shares {@link ExportReportCommon}; the `kind`/`scope`/`phases` discriminant tells the three\n * exports apart. `exportStore` resolves a {@link StoreBackupReport}; `exportDiagnostics` a\n * {@link DiagnosticDumpReport}; `exportData` a {@link DataExportReport}.\n */\nexport type ExportReport = StoreBackupReport | DiagnosticDumpReport | DataExportReport;\n\n/** The artefact + its report — the resolved value of {@link SyncClient.exportStore}. */\nexport interface StoreExportResult {\n /** The store-backup tarball as a named `File` (PGlite-restorable via `loadDataDir`, a later slice). */\n file: File;\n /** The structured record of the export (ADR-0035). */\n report: StoreBackupReport;\n}\n\n/**\n * Reduce a plain store PATH (ADR-0036) to a filesystem-safe token for the backup file name. Takes the\n * path's LAST segment (as PGlite's own `dumpDataDir` does when it names the inner db), then keeps only\n * `[A-Za-z0-9._-]`. No scheme stripping — the store path is a plain name, never a storage URL. Falls back\n * to a fixed token for an empty path so the name is always well formed.\n */\nexport function deriveStoreId(storePath: string | undefined): string {\n if (!storePath) return \"pgxsinkit-store\";\n const lastSegment = storePath.split(\"/\").filter(Boolean).pop() ?? storePath;\n const safe = lastSegment.replace(/[^A-Za-z0-9._-]/g, \"-\").replace(/^-+|-+$/g, \"\");\n return safe.length > 0 ? safe : \"pgxsinkit-store\";\n}\n\n/**\n * An ISO-ish, filesystem-safe timestamp (colons/dots → hyphens) for a default artefact file name. Exported\n * so the diagnostic-dump path names its `.sql` artefact with the identical timestamp shape.\n */\nexport const compactTimestamp = (): string => new Date().toISOString().replace(/[:.]/g, \"-\");\n\n/**\n * The datadir dump both exports share (ADR-0035): a `CHECKPOINT` through the store's normal query path,\n * then `dumpDataDir`. The store backup keeps its bytes as the artefact; the diagnostic dump feeds them to a\n * throwaway clone. Factored out so exactly one implementation of \"flush + tar the live datadir\" exists —\n * `performStoreExport` and `performDiagnosticExport` cannot drift on the checkpoint ordering or the timing\n * house style. Returns the raw `dumpDataDir` output plus the two phase walls, both offset from `startPerf`\n * (the caller's export-start monotonic anchor) so the timings compose into either report.\n *\n * The `CHECKPOINT` is a utility statement — Drizzle has no builder for it, so a raw `exec` is the justified\n * tier-③ form here. Running it via `pglite.exec` serialises it behind any in-flight engine work on PGlite's\n * single connection, flushing dirty buffers to the datadir the dump then reads — so the tarball reflects\n * committed state, not a torn mid-write datadir.\n */\nexport async function performDatadirDump(\n pglite: Pick<ClientPGlite, \"exec\" | \"dumpDataDir\">,\n compression: \"auto\" | \"gzip\" | \"none\",\n startPerf: number,\n): Promise<{\n dumped: Awaited<ReturnType<ClientPGlite[\"dumpDataDir\"]>>;\n checkpointStartedAtMs: number;\n checkpointMs: number;\n dumpStartedAtMs: number;\n dumpMs: number;\n}> {\n const checkpointStartedAtMs = nowMs() - startPerf;\n const checkpointStartPerf = nowMs();\n await pglite.exec(\"CHECKPOINT\");\n const checkpointMs = nowMs() - checkpointStartPerf;\n\n const dumpStartedAtMs = nowMs() - startPerf;\n const dumpStartPerf = nowMs();\n const dumped = await pglite.dumpDataDir(compression);\n const dumpMs = nowMs() - dumpStartPerf;\n\n return { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs };\n}\n\n/** The dependencies {@link performStoreExport} needs from the owning client — narrow, so it is unit-testable. */\nexport interface StoreExportDeps {\n /** The live store to checkpoint and dump. */\n pglite: Pick<ClientPGlite, \"exec\" | \"dumpDataDir\">;\n /** The Mutation diagnostics seam (`client.diagnostics().mutation` / `readMutationStats`). */\n readMutationStats: () => Promise<MutationDiagnostics>;\n /**\n * The store's configured plain store PATH (ADR-0036) — reduced to the `storeId` in the default backup\n * file name (`deriveStoreId`). The resolved PGlite dataDir URL is deliberately NOT used here: it is\n * internal plumbing and must not leak into an artefact name as something to imitate.\n */\n storePath?: string;\n}\n\n/**\n * Run a live store backup (ADR-0035): checkpoint → dump → snapshot diagnostics → assemble the report. The\n * caller (`createSyncClient`) is responsible for awaiting engine-ready and entering the lifecycle slot\n * BEFORE calling this — kept out of here so the helper stays a pure \"do the dump\" unit. No engine\n * suspension: the backup is live by design.\n */\nexport async function performStoreExport(\n deps: StoreExportDeps,\n options: StoreExportOptions = {},\n): Promise<StoreExportResult> {\n const startedAt = Date.now();\n const startPerf = nowMs();\n const compression = options.compression ?? \"auto\";\n\n // Live dump of the whole datadir (checkpoint → `dumpDataDir`, the shared core) — the journal and overlay\n // ride inside it (the lossless backup, ADR-0035).\n const { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs } = await performDatadirDump(\n deps.pglite,\n compression,\n startPerf,\n );\n\n // PGlite names its dump `<db>.tar.gz` (type `application/x-gzip`) when it compressed, `<db>.tar`\n // (`application/x-tar`) otherwise — so the RESULT, not the requested option, tells us what `\"auto\"`\n // resolved to. Detect from whichever of name/type the runtime populated (its `File` is a polyfill in\n // non-browser hosts, so trust both).\n const dumpedName = dumped instanceof File ? dumped.name : \"\";\n const gzipped = dumpedName.endsWith(\".gz\") || dumped.type.includes(\"gzip\");\n const appliedCompression: \"gzip\" | \"none\" = gzipped ? \"gzip\" : \"none\";\n const extension = gzipped ? \".pgdata.tar.gz\" : \".pgdata.tar\";\n const mimeType = gzipped ? \"application/x-gzip\" : \"application/x-tar\";\n const storeId = deriveStoreId(deps.storePath);\n const fileName = options.fileName ?? `${storeId}-${compactTimestamp()}${extension}`;\n // Build the artefact `File` from the raw bytes, NOT by re-wrapping `dumped`: PGlite's dump is a File\n // polyfill in non-browser hosts, and `new File([polyfillFile], name)` keeps the polyfill's own name\n // rather than the one we pass. Extracting the bytes first guarantees the store-scoped name sticks.\n const bytes = new Uint8Array(await dumped.arrayBuffer());\n const file = new File([bytes], fileName, { type: mimeType });\n\n // Snapshot diagnostics AFTER the dump so it describes the journal state the artefact actually holds.\n const diagnostics = await deps.readMutationStats();\n\n const report: StoreBackupReport = {\n reportVersion: 1,\n kind: \"store-backup\",\n scope: \"whole-store\",\n compression: appliedCompression,\n startedAt,\n totalMs: nowMs() - startPerf,\n byteLength: file.size,\n phases: { checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs },\n diagnostics,\n };\n\n return { file, report };\n}\n",
124
+ "// Store path contract (ADR-0036). The public seams (`createSyncClient`, `createClientPGlite`, the worker\n// attach/provision messages, the board store registry) take a `storePath` — a PLAIN path/name, never a\n// PGlite storage URL. The storage backend is DERIVED from the environment here, never chosen by the\n// consumer: IndexedDB in a browser (or a worker), the filesystem on Bun/Node. A memory-backed store is\n// not a product configuration — pgxsinkit's durability semantics (persistent retention, the optimistic\n// Mutation journal) assume a persisted store — so it exists ONLY behind the explicit testing\n// acknowledgment (`@pgxsinkit/client/testing`), carried into option handling as the module-internal\n// {@link TEST_STORE_BACKEND} symbol.\n//\n// This module is the ONLY place in the toolkit that assembles `idb://` / `file://` / `memory://` URLs (the\n// export machinery's throwaway clone, a later slice, is the one other internal `memory://` site). A\n// resolved URL is internal plumbing: it never leaks into config, results, reports, or errors as something\n// a consumer could copy back into a storePath — hence the scheme-rejection guard below fails the old\n// contract loudly at the boundary rather than silently re-interpreting it.\n\n/**\n * Thrown when a `storePath` is not a plain name (ADR-0036 decision 1): it carries a URL scheme (`://`) or\n * is empty/whitespace-only. A distinct type — not a bare `Error` — so a caller can `instanceof`-branch the\n * old dataDir-URL contract from a genuine store failure. The message names the plain-path contract and\n * shows the corrected form, without echoing a resolvable URL a consumer might imitate.\n */\nexport class InvalidStorePathError extends Error {\n constructor(message: string) {\n super(`[pgxsinkit] ${message}`);\n this.name = \"InvalidStorePathError\";\n }\n}\n\n/**\n * Thrown when a caller-owned PGlite handed to {@link CreateSyncClientOptions.pgliteInstance} /\n * {@link CreateSyncClientOptions.precreatedPglite} is PROVABLY non-persistent (ADR-0036 decision 4): its\n * `dataDir` is `undefined` (PGlite's in-memory default — the `new PGlite()` a copy-paste reaches) or begins\n * `memory://`. Names both the why (durability semantics assume a persisted store) and the two exits, so a\n * consumer is never left guessing which store to hand us instead.\n */\nexport class NonPersistentStoreError extends Error {\n constructor(observed: \"in-memory-default\" | \"memory-scheme\") {\n const reason =\n observed === \"in-memory-default\"\n ? \"its dataDir is undefined — PGlite's default is an in-memory store (`new PGlite()`)\"\n : \"its dataDir is a memory-backed store\";\n super(\n `[pgxsinkit] refusing a non-persistent PGlite instance: ${reason}. pgxsinkit's durability semantics ` +\n \"(persistent retention, the optimistic Mutation journal) assume a persisted store — a memory store \" +\n \"would silently forget acked-but-unflushed writes. Either hand a persisted instance (open it under a \" +\n \"plain store path so the backend is derived), or, for a test/ephemeral store, acknowledge it with \" +\n '`memoryStoreForTests` / `testStoreAcknowledgment` from \"@pgxsinkit/client/testing\" (ADR-0036).',\n );\n this.name = \"NonPersistentStoreError\";\n }\n}\n\n/**\n * Thrown when a restore (`restoreFrom`, ADR-0035 decision 6) targets a store path whose backend store ALREADY\n * exists. Restore is a CREATION-path feature — it boots a brand-new store on `loadDataDir` — and never\n * overlays a live store: silently merging a backup into an existing datadir would corrupt it. A distinct type\n * (not a bare `Error`) so a caller can `instanceof`-branch \"target already there\" from a genuine boot failure.\n * The remedy is a deliberate manual {@link SyncClient.destroy} of the existing store first (never automatic —\n * dropping a user's local store must be their explicit act).\n */\nexport class RestoreTargetExistsError extends Error {\n constructor(storePath: string) {\n super(\n `[pgxsinkit] refusing to restore into ${JSON.stringify(storePath)}: a store already exists at that path. ` +\n \"Restore only ever boots a brand-new store (it never overlays an existing one — that would corrupt the \" +\n \"datadir). Destroy the existing store first (a deliberate `destroy()`), then restore into the now-fresh \" +\n \"path (ADR-0035 decision 6).\",\n );\n this.name = \"RestoreTargetExistsError\";\n }\n}\n\n/**\n * The module-internal marker a testing helper stamps onto the options object so option handling can select\n * the memory backend / unlock the BYO refusal (ADR-0036 decision 3). `Symbol.for` (not a bare `Symbol()`)\n * on purpose: each public entry point is bundled STANDALONE (`scripts/build-public-packages.ts`,\n * `splitting: false`), so a plain module symbol would be DUPLICATED between the main bundle and the\n * `./testing` bundle — two distinct symbols, and the marker set by `./testing` would be invisible to the\n * main entry's reader. The global registry key guarantees ONE symbol across bundles. It is deliberately\n * absent from the main entry's exports and from every public type, so a production consumer cannot name it.\n */\nexport const TEST_STORE_BACKEND: unique symbol = Symbol.for(\"pgxsinkit.internal.testStoreBackend\");\n\n/**\n * What a testing helper's marker asks of option handling: `\"memory\"` mints a scheme-selected memory store\n * (and, being ours-under-the-covers, also unlocks the BYO refusal); `\"acknowledged\"` only unlocks the BYO\n * refusal for a caller who owns the (test) instance themselves. Both are visible, deliberate acts — an\n * import whose name says what it is.\n */\nexport type TestStoreMarker = \"memory\" | \"acknowledged\";\n\n/** An options object that MAY carry the internal testing marker (read via {@link readTestStoreMarker}). */\nexport type WithTestStoreMarker = { [TEST_STORE_BACKEND]?: TestStoreMarker };\n\n/** Read the internal testing marker off an options object, or `undefined` when none was stamped. */\nexport function readTestStoreMarker(options: unknown): TestStoreMarker | undefined {\n if (options == null || typeof options !== \"object\") return undefined;\n const marker = (options as WithTestStoreMarker)[TEST_STORE_BACKEND];\n return marker === \"memory\" || marker === \"acknowledged\" ? marker : undefined;\n}\n\n/**\n * What {@link createClientPGlite} (and any store-opening seam) accepts as its store argument: a plain\n * `storePath` string, or the option object a testing helper mints (`memoryStoreForTests(...)`) — carrying a\n * `storePath` plus the invisible internal marker. Accepting the object form is what lets the testing\n * helper's output flow STRAIGHT into `createClientPGlite(memoryStoreForTests(\"x\"))` without a consumer ever\n * naming a backend.\n */\nexport type StorePathInput = string | ({ storePath: string } & WithTestStoreMarker);\n\n/** Normalise a {@link StorePathInput} to a plain path plus any internal memory-backend override it carried. */\nexport function normaliseStorePathInput(input: StorePathInput): { storePath: string; backendOverride?: \"memory\" } {\n if (typeof input === \"string\") return { storePath: input };\n return {\n storePath: input.storePath,\n ...(readTestStoreMarker(input) === \"memory\" ? { backendOverride: \"memory\" as const } : {}),\n };\n}\n\n/**\n * The environment seam the backend derivation reads — factored out so a browser derivation is fakeable in\n * a Bun unit test (there is no `indexedDB` there). `hasIndexedDb` is the browser/worker signal: PGlite's\n * IndexedDB backend needs `indexedDB`, which a browser tab AND a Web/Shared/dedicated worker expose but\n * Bun/Node do not — so it distinguishes \"run in the browser\" (idb) from \"run on the server\" (filesystem)\n * without a DOM-lib dependency.\n */\nexport interface StoreEnv {\n hasIndexedDb: boolean;\n}\n\n/** Detect the ambient store environment off `globalThis` (the library carries no DOM lib dependency). */\nfunction detectStoreEnv(): StoreEnv {\n return { hasIndexedDb: typeof (globalThis as { indexedDB?: unknown }).indexedDB !== \"undefined\" };\n}\n\n/**\n * Resolve a plain {@link storePath} to the PGlite dataDir URL the store opens at — the ONE derivation point\n * (ADR-0036 decision 2). Browser/worker (`indexedDB` present) → `idb://<storePath>`; Bun/Node → `file://<storePath>`\n * (relative paths resolve against the working directory, exactly as PGlite's filesystem backend does — pass\n * an absolute path if that matters). The `backendOverride` is internal-only: `\"memory\"` selects a\n * scheme-selected `memory://<storePath>` store for the sanctioned test/ephemeral lanes.\n *\n * Rejects a scheme-bearing or empty/whitespace-only path with {@link InvalidStorePathError} — the storePath\n * contract fails loudly at the boundary, never silently re-interpreted (no-legacy rule). The returned URL is\n * internal plumbing; do not surface it to consumers as something to imitate.\n *\n * CRITICAL (ADR-0036 decision 5, probed on PGlite 0.5.4): memory selection is ALWAYS the scheme-selected\n * `memory://` form, NEVER PGlite's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an explicit-`fs`\n * instance silently omits relation files created after initdb, so a restored clone raises \"relation does not\n * exist\". Callers that need a memory store must route through this function, never construct `MemoryFS`.\n */\nexport function resolveStoreDataDir(\n storePath: string,\n backendOverride?: \"memory\",\n env: StoreEnv = detectStoreEnv(),\n): string {\n if (typeof storePath !== \"string\" || storePath.trim().length === 0) {\n throw new InvalidStorePathError(\n 'invalid storePath: expected a non-empty plain store name (e.g. \"my-app-store\"); received an empty or whitespace-only value (ADR-0036).',\n );\n }\n if (storePath.includes(\"://\")) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: a store path is a plain name, not a storage URL. ` +\n 'Pass just the name (e.g. \"my-app-store\") — the storage backend (IndexedDB in a browser, the ' +\n \"filesystem on Bun/Node) is derived for you; drop the scheme prefix (ADR-0036).\",\n );\n }\n if (backendOverride === \"memory\") return `memory://${storePath}`;\n return env.hasIndexedDb ? `idb://${storePath}` : `file://${storePath}`;\n}\n\n/**\n * The IndexedDB database name a browser store occupies (ADR-0036) — a browser-only OPERATIONAL helper for\n * orphan GC / corrupt-store deletion (`indexedDB.deleteDatabase(...)`), NOT part of the create path. PGlite\n * maps `idb://<storePath>` to the IndexedDB database `/pglite/<storePath>` (its `WASM_PREFIX` `/pglite`\n * joined with the path after the scheme; verified against `@electric-sql/pglite` 0.5.4 dist). Exposed so a\n * consumer that GCs its own stores routes that PGlite-internal naming knowledge through the library rather\n * than re-deriving the `/pglite/` prefix itself. Rejects a scheme-bearing/empty path exactly as\n * {@link resolveStoreDataDir} does, so the two stay in lockstep.\n */\nexport function storeIndexedDbDatabaseName(storePath: string): string {\n if (typeof storePath !== \"string\" || storePath.trim().length === 0) {\n throw new InvalidStorePathError(\n \"invalid storePath: storeIndexedDbDatabaseName expects a non-empty plain store name (ADR-0036).\",\n );\n }\n if (storePath.includes(\"://\")) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: storeIndexedDbDatabaseName expects a plain name, not a storage URL (ADR-0036).`,\n );\n }\n return `/pglite/${storePath}`;\n}\n\n/**\n * Classify a PGlite instance's `dataDir` for the BYO refusal (ADR-0036 decision 4). Returns the offending\n * shape when the instance is PROVABLY non-persistent (`undefined` = PGlite's in-memory default; a\n * `memory://` prefix = an explicit memory store), or `null` when it passes — anything else present,\n * including exotic custom-VFS configs we cannot classify, is the caller's own call (the guard catches the\n * two accidental non-persistent shapes, it is not a storage-backend whitelist).\n */\nexport function classifyNonPersistentDataDir(\n dataDir: string | undefined,\n): \"in-memory-default\" | \"memory-scheme\" | null {\n if (dataDir == null) return \"in-memory-default\";\n if (dataDir.startsWith(\"memory://\")) return \"memory-scheme\";\n return null;\n}\n\n/**\n * Does the backend store a plain {@link storePath} resolves to ALREADY exist? The fresh-target gate for a\n * restore (ADR-0035 decision 6) — restore refuses a target that is already there. Per backend:\n *\n * - **memory** (`backendOverride === \"memory\"`) — a scheme-selected memory store is fresh by construction:\n * it lives only for the instance about to be created, so there is nothing to collide with. Always `false`\n * (the sanctioned test/ephemeral lane never blocks a restore).\n * - **`file://`** (Bun/Node) — filesystem existence of the datadir directory. `node:fs` is imported\n * DYNAMICALLY inside this branch, never at module top level, so a browser bundle (which only ever hits the\n * `idb://` branch below) never pulls `node:fs` in. Relative paths resolve against the working directory,\n * exactly as PGlite's filesystem backend and {@link resolveStoreDataDir} do.\n * - **`idb://`** (browser/worker) — `indexedDB.databases()` enumerated for the store's database name\n * ({@link storeIndexedDbDatabaseName}). BEST-EFFORT: `databases()` is unavailable on some engines (older\n * Firefox, certain worker contexts); when absent we CANNOT prove existence, so we report `false` and let\n * the restore proceed rather than fabricate a result — a real overlay collision would still surface as a\n * PGlite-level boot failure. We never fake a positive.\n */\nexport async function storeTargetExists(\n storePath: string,\n backendOverride?: \"memory\",\n env: StoreEnv = detectStoreEnv(),\n): Promise<boolean> {\n const dataDir = resolveStoreDataDir(storePath, backendOverride, env);\n if (dataDir.startsWith(\"memory://\")) return false;\n if (dataDir.startsWith(\"file://\")) {\n // The datadir path is everything after the `file://` scheme; `node:fs` handles absolute and\n // cwd-relative paths identically to PGlite's own filesystem backend.\n const path = dataDir.slice(\"file://\".length);\n const { existsSync } = await import(\"node:fs\");\n return existsSync(path);\n }\n // `idb://` — enumerate the IndexedDB databases for this store's database name. `databases()` is optional in\n // the spec, so guard it: when absent, best-effort `false` (documented above), never a fabricated positive.\n const idb = (globalThis as { indexedDB?: { databases?: () => Promise<Array<{ name?: string }>> } }).indexedDB;\n if (idb?.databases == null) return false;\n const target = storeIndexedDbDatabaseName(storePath);\n const databases = await idb.databases();\n return databases.some((db) => db.name === target);\n}\n",
125
+ "// Data export (ADR-0035 decision 1, via the throwaway clone of the addendum). The PORTABLE artefact: the\n// synced tables and the enum types they depend on, schema + data, nothing of pgxsinkit's machinery —\n// loadable into a vanilla Postgres. It is `generated enum DDL header + pg_dump -t (per synced table)`\n// concatenated: `pg_dump -t` emits the allowlisted TABLES but not the enum TYPES their columns reference\n// (and `--exclude-*` cannot subtract the reconcile functions), so the header carries the enums and `-t`\n// carries exactly the physical synced tables — overlay/journal/metadata/views/functions fall outside `-t`\n// by construction. `--no-owner` keeps the SQL portable across roles.\n//\n// Unlike the store backup and the diagnostic dump, the data export is the ONE variant that silently loses\n// unflushed writes (decision 3): an `acked` write whose synced echo has not landed lives only in the Overlay\n// and the `destroy()`-style \"owed\" predicate does not count it. So `exportData` requires a DRAINED journal —\n// \"drained\" meaning all six mutation counts zero (CONTEXT.md → Data export: \"drained ≠ nothing owed\"), which\n// for `acked` rows clears only via the synced echo through the Convergence barrier. The drain actively\n// `flush()`es drainable rows and awaits that convergence, bounded by `drainJournal.timeoutMs`; non-drainable\n// states (`failed`/`quarantined`/`conflicted`) never drain on their own, so they fail FAST with the\n// diagnostics snapshot rather than burning the timeout. `drainJournal: false` is the explicit escape hatch\n// exporting synced state as-is.\n//\n// The drain runs INSIDE the lifecycle slot (the caller enters the slot, then calls this): `flush()` needs\n// the running engine and is not a lifecycle-exclusive op, but the artefact must be taken RIGHT AFTER the\n// drain with no window for a new write to slip in — so export owns the store's lifecycle for the whole\n// drain+dump, the simplest correct placement.\n\nimport type { MutationDiagnostics } from \"@pgxsinkit/contracts\";\n\nimport { runThrowawayCloneDump } from \"./export-dump\";\nimport { compactTimestamp, type DataExportReport, deriveStoreId, nowMs } from \"./export-store\";\nimport type { ClientPGlite } from \"./index\";\n\n/** The default drain budget: actively flush + await the convergence barrier for up to 15s before failing. */\nexport const DEFAULT_DRAIN_TIMEOUT_MS = 15_000;\n/** How often the drain re-checks the diagnostics seam while waiting for the journal to converge. */\nconst DRAIN_POLL_INTERVAL_MS = 50;\n\n/** The drain guard's tuning: the wait budget for reaching a fully-drained journal. */\nexport interface DrainJournalOptions {\n /** Milliseconds to flush + await convergence before throwing {@link DataExportDrainError}. */\n timeoutMs: number;\n}\n\n/**\n * `exportData`'s drain policy: the default `{ timeoutMs }` guard, or `false` — the explicit escape hatch\n * that skips the drain and exports the SYNCED state as-is (unflushed local writes silently absent). A plain\n * JSON shape, so it survives structured clone across the worker bridge unchanged.\n */\nexport type DrainJournalOption = DrainJournalOptions | false;\n\n/** Options for {@link SyncClient.exportData}. Plain JSON — structured-clone-safe across the worker bridge. */\nexport interface DataExportOptions {\n /**\n * Override the generated artefact file name. When omitted, the name is `<storeId>-<timestamp>-data.sql`,\n * where `storeId` is a filesystem-safe derivation of the store path (see `deriveStoreId`).\n */\n fileName?: string;\n /**\n * The drain guard (ADR-0035 decision 3). Default `{ timeoutMs: 15_000 }`: fail fast on non-drainable\n * states, else flush + await convergence up to the budget. `false` is the escape hatch — export synced\n * state as-is, skipping the drain entirely.\n */\n drainJournal?: DrainJournalOption;\n}\n\n/** The SQL artefact + its report — the resolved value of {@link SyncClient.exportData}. */\nexport interface DataExportResult {\n /** The portable SQL as a named `File` (`application/sql`), loadable into a vanilla Postgres. */\n file: File;\n /** The structured record of the export (ADR-0035). */\n report: DataExportReport;\n}\n\n/**\n * Thrown when `exportData`'s strict drain cannot produce a drained journal (ADR-0035 decision 3). Carries\n * the `MutationDiagnostics` snapshot at the moment of failure so the caller sees exactly what blocked the\n * export, and a `reason` distinguishing the two failure modes:\n *\n * - `\"non-drainable-state\"` — `failed`/`quarantined`/`conflicted` rows are present (either pre-existing, so\n * the failure is immediate with no waiting, or a mid-drain `flush()` failure that moved rows to `failed`);\n * these terminal states never drain on their own, so waiting is pointless.\n * - `\"timeout\"` — drainable rows (`pending`/`sending`/`acked`) did not reach fully-drained within the\n * budget; most commonly `acked` writes whose synced echo never arrived (an offline device, a stalled\n * read path).\n *\n * A distinct type — not a bare `Error` — so a caller can `instanceof`-branch a drain failure from a genuine\n * export failure, inspect the diagnostics, and choose the escape hatch (`drainJournal: false`) or the\n * lossless store backup instead.\n */\nexport class DataExportDrainError extends Error {\n /** Which drain failure occurred (see the class doc). */\n readonly reason: \"non-drainable-state\" | \"timeout\";\n /** The mutation diagnostics at the moment the drain gave up — the evidence of what was unflushed. */\n readonly diagnostics: MutationDiagnostics;\n\n constructor(reason: \"non-drainable-state\" | \"timeout\", diagnostics: MutationDiagnostics) {\n const detail =\n reason === \"non-drainable-state\"\n ? `non-drainable journal rows are present (failed=${diagnostics.failedCount}, ` +\n `quarantined=${diagnostics.quarantinedCount}, conflicted=${diagnostics.conflictedCount}) — these never ` +\n \"drain on their own\"\n : `the journal did not drain within the timeout (pending=${diagnostics.pendingCount}, ` +\n `sending=${diagnostics.sendingCount}, acked=${diagnostics.ackedCount}) — most likely acked writes whose ` +\n \"synced echo has not landed\";\n super(\n `[pgxsinkit] exportData refused: ${detail}. A strict data export needs a DRAINED journal (ADR-0035); ` +\n \"resolve the rows, retry once they converge, use `drainJournal: false` to export synced state as-is, or \" +\n \"take a lossless `exportStore` backup instead.\",\n );\n this.name = \"DataExportDrainError\";\n this.reason = reason;\n this.diagnostics = diagnostics;\n }\n}\n\n/** The dependencies {@link performDataExport} needs from the owning client — narrow, so it is unit-testable. */\nexport interface DataExportDeps {\n /** The live store to checkpoint and dump (the clone source; the live engine is never suspended). */\n pglite: Pick<ClientPGlite, \"exec\" | \"dumpDataDir\">;\n /** The Mutation diagnostics seam (`client.diagnostics().mutation` / `readMutationStats`). */\n readMutationStats: () => Promise<MutationDiagnostics>;\n /** The optimistic flush (`client.flush()`), driven during the drain to send drainable rows. */\n flush: () => Promise<void>;\n /**\n * The `-t` allowlist: the schema-qualified physical synced table names, resolved from the registry by the\n * SAME projection the DDL generator uses (`collectDataExportSyncedTableNames`) — never re-derived here.\n */\n syncedTableNames: string[];\n /**\n * The generated enum DDL header (`buildDataExportEnumHeaderSql`) — the `CREATE TYPE` statements for the\n * enums the exported tables reference, which `pg_dump -t` omits. `\"\"` when no exported table uses an enum.\n */\n enumHeaderSql: string;\n /**\n * The clone-cleanup SQL (`buildDataExportCloneCleanupSql`) run on the throwaway clone before `pg_dump -t`,\n * dropping the reconcile triggers `-t` would otherwise pull into the artefact (referencing pgxsinkit\n * functions the export excludes). `\"\"` when the registry has no writable owning table.\n */\n cloneCleanupSql: string;\n /**\n * The store's configured plain store PATH (ADR-0036) — reduced to the `storeId` in the default artefact\n * file name. The resolved PGlite dataDir URL is deliberately NOT used: internal plumbing, never an\n * artefact-name seed.\n */\n storePath?: string;\n}\n\n/** A non-drainable state is present when any terminal count is non-zero — waiting on these is pointless. */\nconst hasNonDrainableRows = (diagnostics: MutationDiagnostics): boolean =>\n diagnostics.failedCount > 0 || diagnostics.quarantinedCount > 0 || diagnostics.conflictedCount > 0;\n\n/**\n * Fully drained = all SIX counts zero. `acked` explicitly counts: an acked write whose echo has not landed\n * is still only in the Overlay (CONTEXT.md → Data export), so a strict export must wait for it to clear via\n * the Convergence barrier — that is the POINT of the drain, not merely \"nothing owed\".\n */\nconst isFullyDrained = (diagnostics: MutationDiagnostics): boolean =>\n diagnostics.pendingCount === 0 &&\n diagnostics.sendingCount === 0 &&\n diagnostics.ackedCount === 0 &&\n !hasNonDrainableRows(diagnostics);\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Drive the journal to fully-drained (ADR-0035 decision 3), or throw {@link DataExportDrainError}:\n *\n * 1. Read diagnostics and fail FAST — before any waiting — when a non-drainable state pre-exists (an offline\n * device with a dirty journal cannot produce a strict export).\n * 2. An already-empty journal returns instantly with ZERO network involvement — an offline device with a\n * clean journal exports strictly (the assert-in-a-test case).\n * 3. Otherwise drainable rows are present: `flush()` them and poll the diagnostics seam until fully-drained,\n * bounded by `timeoutMs`. A `flush()` that FAILS moves rows to `failed`, so the next poll sees a\n * non-drainable state and fails fast (well under the budget) rather than burning the whole timeout. Its\n * throw is swallowed — the diagnostics re-read, not the throw, is the source of truth for what happened.\n */\nasync function drainJournalForExport(\n deps: DataExportDeps,\n timeoutMs: number,\n): Promise<{ diagnostics: MutationDiagnostics; drainMs: number }> {\n const drainStartPerf = nowMs();\n\n // (1)/(2) — fail fast on pre-existing terminal rows; return instantly on an empty journal.\n let diagnostics = await deps.readMutationStats();\n if (hasNonDrainableRows(diagnostics)) {\n throw new DataExportDrainError(\"non-drainable-state\", diagnostics);\n }\n if (isFullyDrained(diagnostics)) {\n return { diagnostics, drainMs: nowMs() - drainStartPerf };\n }\n\n // (3) — drainable rows present: flush + await convergence, bounded by the budget.\n for (;;) {\n // A throwing flush (e.g. a dead write endpoint) still marks rows `failed`; the re-read below detects it.\n await deps.flush().catch(() => undefined);\n\n diagnostics = await deps.readMutationStats();\n // A flush that failed mid-wait shows up here as `failed` rows — fail fast, do not burn the timeout.\n if (hasNonDrainableRows(diagnostics)) {\n throw new DataExportDrainError(\"non-drainable-state\", diagnostics);\n }\n if (isFullyDrained(diagnostics)) {\n return { diagnostics, drainMs: nowMs() - drainStartPerf };\n }\n if (nowMs() - drainStartPerf >= timeoutMs) {\n throw new DataExportDrainError(\"timeout\", diagnostics);\n }\n await sleep(DRAIN_POLL_INTERVAL_MS);\n }\n}\n\n/**\n * A short SQL comment header describing the artefact and how it was produced — self-describing provenance so\n * a human reading the `.sql` knows what it is, which tables it carries, and whether the escape hatch dropped\n * unflushed writes. Emitted ahead of the enum header and the `pg_dump -t` output.\n */\nfunction buildArtefactCommentHeader(tableNames: string[], escapeHatch: boolean): string {\n const tableList = tableNames.length > 0 ? tableNames.join(\", \") : \"(none)\";\n return [\n \"-- pgxsinkit data export (ADR-0035): the synced tables + their enum types, schema + data,\",\n \"-- nothing of pgxsinkit's overlay/journal/metadata machinery — loadable into a vanilla Postgres.\",\n \"-- Produced by a generated enum DDL header concatenated ahead of `pg_dump -t <table> ... --no-owner`\",\n \"-- run against a throwaway in-memory clone of the local store.\",\n `-- Tables: ${tableList}`,\n escapeHatch\n ? \"-- Journal drain: SKIPPED (drainJournal: false) — reflects synced state as-is; unflushed local writes are absent.\"\n : \"-- Journal drain: enforced — the Mutation journal was fully drained before the dump.\",\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Run a data export (ADR-0035): drain the journal (unless the escape hatch is set) → throwaway-clone\n * `pg_dump -t` per synced table → concatenate the comment + enum DDL header → assemble the report. The\n * caller (`createSyncClient`) awaits engine-ready and enters the lifecycle slot BEFORE calling this, so the\n * whole drain+dump runs under the store's single lifecycle slot (the drain must sit inside it — see the\n * module header).\n */\nexport async function performDataExport(\n deps: DataExportDeps,\n options: DataExportOptions = {},\n): Promise<DataExportResult> {\n const startedAt = Date.now();\n const startPerf = nowMs();\n\n const drainOption: DrainJournalOption = options.drainJournal ?? { timeoutMs: DEFAULT_DRAIN_TIMEOUT_MS };\n const escapeHatch = drainOption === false;\n\n // Phase 1 — the drain guard. The escape hatch skips it entirely (0-wall); otherwise it may throw a typed\n // DataExportDrainError before any dump work happens.\n const drainStartedAtMs = nowMs() - startPerf;\n const drainMs = escapeHatch ? 0 : (await drainJournalForExport(deps, drainOption.timeoutMs)).drainMs;\n\n // Phase 2 — the throwaway-clone dump, restricted to the physical synced tables via `-t`, `--no-owner` for\n // portability. `-t` is repeated once per table. `runThrowawayCloneDump` phases are offset from the SAME\n // export-start anchor, so they compose after the drain wall into one timeline.\n const pgDumpArgs = [\"--no-owner\", ...deps.syncedTableNames.flatMap((name) => [\"-t\", name])];\n const { sqlBytes, phases } = await runThrowawayCloneDump(deps.pglite, startPerf, {\n pgDumpArgs,\n // Drop the reconcile triggers on the clone so `-t` yields portable, machinery-free tables.\n ...(deps.cloneCleanupSql.length > 0\n ? { prepareClone: async (clone) => void (await clone.exec(deps.cloneCleanupSql)) }\n : {}),\n });\n\n // Concatenate: comment header + generated enum DDL header + pg_dump output. The header is text; the dump\n // is raw bytes — `File` accepts a mixed BlobPart list and encodes both as UTF-8, so the bytes are decoded\n // exactly once (never a decode/re-encode round trip).\n const header = buildArtefactCommentHeader(deps.syncedTableNames, escapeHatch) + deps.enumHeaderSql;\n const storeId = deriveStoreId(deps.storePath);\n const fileName = options.fileName ?? `${storeId}-${compactTimestamp()}-data.sql`;\n const file = new File([header, sqlBytes], fileName, { type: \"application/sql\" });\n\n // Snapshot diagnostics AT dump time (post-drain): on the strict path this is a drained journal; under the\n // escape hatch it is whatever synced-as-is state the artefact reflects.\n const diagnostics = await deps.readMutationStats();\n\n const report: DataExportReport = {\n reportVersion: 1,\n kind: \"data-export\",\n scope: \"synced-tables\",\n tables: deps.syncedTableNames,\n escapeHatch,\n startedAt,\n totalMs: nowMs() - startPerf,\n byteLength: file.size,\n phases: {\n drainStartedAtMs,\n drainMs,\n checkpointStartedAtMs: phases.checkpointStartedAtMs,\n checkpointMs: phases.checkpointMs,\n dumpStartedAtMs: phases.dumpStartedAtMs,\n dumpMs: phases.dumpMs,\n cloneBootStartedAtMs: phases.cloneBootStartedAtMs,\n cloneBootMs: phases.cloneBootMs,\n pgDumpStartedAtMs: phases.pgDumpStartedAtMs,\n pgDumpMs: phases.pgDumpMs,\n },\n diagnostics,\n };\n\n return { file, report };\n}\n",
126
+ "import { getTableConfig, getViewConfig } from \"drizzle-orm/pg-core\";\n\nimport type { SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\n/**\n * Lazy-relation safety (ADR-0021).\n *\n * A `lazy` relation is held out of the eager boot and only subscribed on first reference. The hazard is\n * a query reading it *before* it is hydrated — which silently returns empty/stale rows. This pure,\n * React-free core detects which lazy relations a query reads by scanning its **compiled** SQL, so the\n * caller can activate them (and hydrate-then-run) before the query executes.\n *\n * Why a single SQL scan is sufficient (and why there is no Proxy / builder-AST walk): Drizzle compiles\n * a query to parameterised SQL — values are bound (`$1`, `$2`), never inlined — and emits every relation\n * as a **quoted** identifier (`\"name\"`, or `\"schema\".\"name\"` when it carries a schema). So the compiled\n * SQL is ground truth: a relation the query reads must appear there by name, and the only things in the\n * text are quoted identifiers, keywords and `$n` placeholders. The index is built from the *same* Drizzle\n * objects that emit the SQL (`getTableConfig`/`getViewConfig`), so a token matches emission by\n * construction — schema and all. See \"Known limitations\" in ADR-0021 for the residual edges.\n */\n\n/** Static index of a registry's lazy relations and the exact quoted tokens their reads compile to. */\nexport interface LazyGuardIndex {\n /** Registry keys whose subscription timing is `lazy`. */\n readonly lazyKeys: ReadonlySet<string>;\n /**\n * Per lazy key, the exact quoted reference token(s) the compiled SQL emits when reading it: the synced\n * table (and, for readwrite, its read-model view) as `\"name\"` or `\"schema\".\"name\"` — or, for a read\n * PROJECTION (ADR-0025), its DISTINCT local identity (`localTable`, the `as` name) rather than the\n * owner's physical table. Schema-qualified when the Drizzle object carries a schema — which makes the\n * token collision-proof against bare aliases/CTEs.\n */\n readonly lazyTokens: ReadonlyMap<string, readonly string[]>;\n}\n\n/** Build the {@link LazyGuardIndex} for a registry. Cheap and pure — cache it per client. */\nexport function buildLazyGuardIndex(registry: SyncTableRegistry): LazyGuardIndex {\n const lazyKeys = new Set<string>();\n const lazyTokens = new Map<string, readonly string[]>();\n\n for (const [key, entry] of Object.entries(registry)) {\n if (entry.subscription !== \"lazy\") continue;\n lazyKeys.add(key);\n\n const tokens: string[] = [];\n if (entry.readProjection) {\n // A read PROJECTION (defineReadProjection, ADR-0025) owns no physical table: its `entry.table` is the\n // OWNER's physical table, but a consumer reads it ONLY through its DISTINCT local identity\n // `entry.localTable` (the `as` name — where Electric syncs the projection's rows). Token that, NOT the\n // owner's physical name: a read of the projection's own local table then activates it, while a read of\n // the owner's table activates the OWNER entry (which carries the owner token) without falsely\n // activating this projection. (A projection is always readonly and has no read-model view.)\n const localTable = getTableConfig(entry.localTable);\n tokens.push(quotedRef(localTable.name, localTable.schema));\n } else {\n // A regular entry is read through the synced base table (and, for readwrite, its read-model view);\n // `entry.localTable` shares the base table's name here, so no extra token is needed.\n const table = getTableConfig(entry.table);\n tokens.push(quotedRef(table.name, table.schema));\n if (entry.view != null) {\n const view = getViewConfig(entry.view);\n tokens.push(quotedRef(view.name, view.schema));\n }\n }\n lazyTokens.set(key, tokens);\n }\n\n return { lazyKeys, lazyTokens };\n}\n\n/** The quoted identifier Drizzle emits for a relation: `\"schema\".\"name\"` when schema-qualified, else `\"name\"`. */\nfunction quotedRef(name: string, schema: string | undefined): string {\n return schema != null && schema.length > 0 ? `\"${schema}\".\"${name}\"` : `\"${name}\"`;\n}\n\n/**\n * The compiled-SQL scan: the lazy registry keys whose quoted reference token appears in `sql`. Because\n * the token is fully quoted it is self-delimiting (`\"a\"` cannot match inside `\"ab\"`), so a substring test\n * is exact. A *bare* token sitting in alias position (`… as \"name\"`, which Drizzle emits for `.as(\"name\")`)\n * is excluded — the one realistic collision for a schema-less relation; a schema-qualified token cannot be\n * aliased and so needs no such guard.\n */\nexport function findReferencedLazyKeysInSql(sql: string, index: LazyGuardIndex): Set<string> {\n const found = new Set<string>();\n for (const [key, tokens] of index.lazyTokens) {\n if (tokens.some((token) => sqlReferencesToken(sql, token))) found.add(key);\n }\n return found;\n}\n\nfunction sqlReferencesToken(sql: string, token: string): boolean {\n for (let from = 0; ;) {\n const at = sql.indexOf(token, from);\n if (at === -1) return false;\n // Exclude an alias occurrence: `<expr> as \"token\"`. Only a bare token can be an alias, so this never\n // rejects a real (schema-qualified or FROM/JOIN) reference. Window comfortably covers Drizzle's ` as `.\n if (!/\\bas\\s+$/i.test(sql.slice(Math.max(0, at - 16), at))) return true;\n from = at + token.length;\n }\n}\n\n/**\n * The activation backstop (ADR-0021): throw if a query references a lazy relation that is still not\n * active. Called *after* the referenced lazy relations have been activated, so in the normal path every\n * scanned relation is now active and this passes. It fires only when activation could not make a\n * referenced relation active (a start that failed, or a lazy relation with no consistency group) —\n * converting a would-be silent empty/stale read into a loud error.\n */\nexport function assertLazyRefsActivated(args: {\n sql: string;\n index: LazyGuardIndex;\n isActive: (key: string) => boolean;\n}): void {\n const referenced = findReferencedLazyKeysInSql(args.sql, args.index);\n const missing = [...referenced].filter((key) => !args.isActive(key));\n if (missing.length > 0) throw new LazyRelationNotActivatedError(missing);\n}\n\n/** Thrown by the backstop ({@link assertLazyRefsActivated}) when a referenced lazy relation could not be activated. */\nexport class LazyRelationNotActivatedError extends Error {\n /** The lazy registry keys that were referenced but could not be activated. */\n readonly relations: readonly string[];\n\n constructor(relations: readonly string[]) {\n const quoted = relations.map((r) => `\"${r}\"`).join(\", \");\n super(\n `[pgxsinkit] query references lazy-synced relation(s) ${quoted} that could not be activated (ADR-0021), ` +\n `so it would read empty/stale data. This is usually a failed initial sync or a lazy relation with no ` +\n `consistency group. Activate it explicitly — client.ensureSynced([${quoted}]) — or check the sync ` +\n `status. See \"Known limitations\" in ADR-0021.`,\n );\n this.name = \"LazyRelationNotActivatedError\";\n this.relations = relations;\n }\n}\n",
127
+ "// The engine lifecycle slot (ADR-0035 decision 4). A store holds ONE in-flight lifecycle operation at a\n// time — the three exports plus the destructive ops `destroy()`/`discardEphemeral()`/`dropReadCache()` — so\n// two blackout-class operations can never overlap and corrupt each other's view of the store. The slot does\n// NOT queue: a\n// second entrant while one is running is rejected immediately with a typed {@link LifecycleBusyError}\n// (the ADR's deliberate choice — a fresh artefact is better served by the caller retrying than by\n// stacking back-to-back operations the second could get fresher after the first settles).\n\n/**\n * Thrown when a lifecycle operation is attempted while another already holds the slot (ADR-0035). Carries\n * the running operation's `label` so a caller (or a retry policy) can report exactly what it collided with.\n * A distinct error type — not a bare `Error` — so callers can `instanceof`-branch a busy collision from a\n * genuine operation failure.\n */\nexport class LifecycleBusyError extends Error {\n /** The label of the lifecycle operation currently holding the slot. */\n readonly runningLabel: string;\n /** The label of the operation that was refused. */\n readonly attemptedLabel: string;\n\n constructor(attemptedLabel: string, runningLabel: string) {\n super(\n `[pgxsinkit] lifecycle busy: \"${attemptedLabel}\" refused while \"${runningLabel}\" is running (ADR-0035; retry once it settles).`,\n );\n this.name = \"LifecycleBusyError\";\n this.attemptedLabel = attemptedLabel;\n this.runningLabel = runningLabel;\n }\n}\n\n/** A single-occupancy lifecycle slot. One owner per store (`createSyncClient`); one operation at a time. */\nexport interface LifecycleSlot {\n /**\n * Run `fn` under the slot's exclusion. Rejects with a {@link LifecycleBusyError} — without invoking `fn`\n * — if the slot is already occupied; otherwise holds the slot for `fn`'s lifetime and releases it in a\n * `finally`, so a throwing operation never leaves the slot stuck. The occupancy check + claim run\n * synchronously on entry (before the first `await`), so two calls issued in the same tick resolve\n * deterministically: the first claims, the second is refused.\n */\n run: <T>(label: string, fn: () => Promise<T>) => Promise<T>;\n /** Whether an operation currently holds the slot. */\n isBusy: () => boolean;\n /** The label of the operation currently holding the slot, or `null` when free. */\n runningLabel: () => string | null;\n}\n\n/** Create an empty lifecycle slot (ADR-0035 decision 4). */\nexport function createLifecycleSlot(): LifecycleSlot {\n let running: string | null = null;\n\n return {\n run: async (label, fn) => {\n // Refuse before touching `fn` — a busy collision must have zero side effects on the running operation.\n if (running !== null) throw new LifecycleBusyError(label, running);\n // Claim synchronously (before the first `await` below) so a same-tick second entrant sees us busy.\n running = label;\n try {\n return await fn();\n } finally {\n running = null;\n }\n },\n isBusy: () => running !== null,\n runningLabel: () => running,\n };\n}\n",
128
+ "import { quoteIdentifier } from \"@pgxsinkit/contracts\";\n\n// ─── Live-read materialization safety (ADR-0032 S2 §4) ───────────────────────────────────────────────\n//\n// The live-rows seam feeds the compiled SQL of a Drizzle-built select into PGlite's `live` extension,\n// which MATERIALISES the query (a temp view + state table it diffs against). Drizzle emits no output\n// aliases — it maps result columns positionally — so a JOIN whose tables share a column name (two\n// `title`) compiles to a SELECT with duplicate OUTPUT column names. That is legal as a plain one-shot\n// query, but the live materialisation fails hard:\n//\n// column \"title\" specified more than once\n//\n// and even the plain query silently COLLAPSES the same-named columns into one value (the last one wins),\n// because rows are keyed by column name. The compiled SQL cannot dedupe itself, so the seam must render\n// it into a form that is safe to materialise.\n\n/** The derived-table alias the live-rows seam wraps a materialised query under. Kept unlikely to collide. */\nconst LIVE_QUERY_TABLE_ALIAS = \"__pgx_live\";\n\n/**\n * Make a live-read SQL statement SAFE TO MATERIALISE by giving every output column a UNIQUE explicit name.\n *\n * `fields` is the ordered list of unique output aliases — one per output column, in the compiled SQL's\n * column order (Drizzle emits columns depth-first over the select's field keys, which are unique by\n * construction). The statement is wrapped in a derived table with a POSITIONAL column-alias-list:\n *\n * SELECT * FROM (<sql>) \"__pgx_live\" (\"<a0>\", \"<a1>\", …)\n *\n * A plain `SELECT * FROM (<sql>)` does NOT dedupe — the inner duplicate names survive — so the\n * column-alias-list is what renames every output column POSITIONALLY to a distinct name. The wrapped\n * query materialises cleanly, and its rows come back keyed by the aliases (so same-named source columns\n * keep DISTINCT values). `SELECT *` from the aliased derived table is safe precisely because the alias\n * list has already made the names unique.\n *\n * Returns the SQL UNCHANGED when `fields` is absent or empty — the backward-compatible path for existing\n * callers (raw SQL strings, or non-colliding queries that pass no `fields`): they keep name-keyed rows\n * exactly as before. Only a caller that supplies `fields` opts into alias-keyed rows.\n */\nexport function wrapLiveQueryForMaterialization(sql: string, fields: readonly string[] | undefined): string {\n if (fields == null || fields.length === 0) {\n return sql;\n }\n const aliasList = fields.map((field) => quoteIdentifier(field)).join(\", \");\n return `SELECT * FROM (${sql}) ${quoteIdentifier(LIVE_QUERY_TABLE_ALIAS)} (${aliasList})`;\n}\n",
122
129
  "// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE) —\n// specifically a port of the serializer from electric-sql/pglite PR #1035.\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\n/**\n * Serialization of JavaScript values into a PostgreSQL `COPY ... WITH (FORMAT\n * text)` stream.\n *\n * The Electric client parses the wire values it receives into native JS values\n * before they reach this module: `int2`/`int4`/`float4`/`float8` become\n * `number`, `int8` becomes `bigint`, `bool` becomes `boolean`, `json`/`jsonb`\n * become parsed objects/arrays, array columns become (possibly nested) JS\n * arrays, and every other type is left as its raw Postgres text representation\n * (a `string`). To feed those values back into `COPY` we have to reverse that:\n * turn each value into the exact text Postgres' input functions expect, then\n * apply the COPY framing.\n *\n * Rather than invent an escaping scheme (the previous CSV-based approach broke\n * on arrays, JSON, embedded delimiters, etc.) this is a faithful port of the\n * two relevant PostgreSQL backend routines:\n *\n * - `CopyAttributeOutText` (src/backend/commands/copyto.c) — field escaping\n * - `array_out` (src/backend/utils/adt/arrayfuncs.c) — array literals\n *\n * The TEXT format is used (not CSV) because it is what Postgres itself emits\n * internally, has a single well-defined escaping algorithm, and round-trips\n * every built-in type.\n */\n\n// Defaults for COPY ... WITH (FORMAT text), matching the Postgres backend.\nconst DELIMITER = \"\\t\";\nconst NULL_MARKER = \"\\\\N\";\nconst ROW_SEPARATOR = \"\\n\";\n\n// CopyAttributeOutText escapes the backslash, the field delimiter, and the\n// control characters that have C-style escapes. Every other byte is emitted\n// literally. Our delimiter is a tab, which already has a C-style escape, so the\n// single map below covers all cases.\nconst COPY_TEXT_ESCAPES: Record<string, string> = {\n \"\\\\\": \"\\\\\\\\\",\n \"\\b\": \"\\\\b\",\n \"\\f\": \"\\\\f\",\n \"\\n\": \"\\\\n\",\n \"\\r\": \"\\\\r\",\n \"\\t\": \"\\\\t\",\n \"\\v\": \"\\\\v\",\n};\nconst COPY_TEXT_ESCAPE_RE = /[\\\\\\b\\f\\n\\r\\t\\v]/g;\n\n/** Escape an already-stringified field value per `CopyAttributeOutText`. */\nfunction escapeCopyText(value: string): string {\n return value.replace(COPY_TEXT_ESCAPE_RE, (c) => COPY_TEXT_ESCAPES[c] ?? c);\n}\n\n/**\n * Convert a Uint8Array to Postgres `bytea` hex-format text (`\\xDEADBEEF`).\n * Electric normally delivers `bytea` already as such a string, so this only\n * matters for callers using a custom parser that yields binary.\n */\nfunction byteaToText(bytes: Uint8Array): string {\n let hex = \"\";\n for (const byte of bytes) {\n hex += byte.toString(16).padStart(2, \"0\");\n }\n return \"\\\\x\" + hex;\n}\n\n/**\n * Render a JS `number` the way Postgres' float/int input accepts it. The only\n * special cases are the non-finite values, which Postgres spells out in words.\n */\nfunction numberToText(value: number): string {\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n return String(value);\n}\n\n// array_out quotes an element when it is empty, looks like the literal NULL, or\n// contains a brace, the element delimiter (comma), a double-quote, a backslash,\n// or ASCII whitespace. We mirror `array_isspace`, which is stricter than JS\n// `\\s` (it excludes Unicode whitespace), so the output matches Postgres' own\n// `array_out` TEXT format exactly and re-parses correctly on `COPY FROM`.\nconst ARRAY_NEEDS_QUOTE_RE = /[{}\",\\\\ \\t\\n\\r\\v\\f]/;\n\n/** Quote/escape a single array element's text per `array_out`. */\nfunction quoteArrayElement(text: string): string {\n const needsQuote = text.length === 0 || text.toLowerCase() === \"null\" || ARRAY_NEEDS_QUOTE_RE.test(text);\n if (!needsQuote) return text;\n // Inside quotes only `\"` and `\\` are escaped, each with a single backslash.\n return '\"' + text.replace(/([\"\\\\])/g, \"\\\\$1\") + '\"';\n}\n\n/**\n * Build a Postgres array literal (`{...}`) from a JS array, recursing into\n * nested arrays for multi-dimensional arrays. NULL elements become an unquoted\n * `NULL`; nested arrays are emitted as bare `{...}` (never quoted), exactly as\n * `array_out` does.\n */\nfunction arrayToText(arr: ReadonlyArray<unknown>): string {\n const elements = arr.map((el) => {\n if (el === null || el === undefined) return \"NULL\";\n if (Array.isArray(el)) return arrayToText(el);\n return quoteArrayElement(valueToText(el));\n });\n return \"{\" + elements.join(\",\") + \"}\";\n}\n\n/**\n * Convert a non-null JS value to its bare Postgres text representation (before\n * COPY field escaping is applied). Dispatch is on the runtime type produced by\n * the Electric parser. `json`/`jsonb` columns are handled ahead of this by\n * `serializeCopyValue` when a column type is known; reaching the object branch\n * here is the type-less fallback.\n */\nfunction valueToText(value: unknown): string {\n switch (typeof value) {\n case \"string\":\n return value;\n case \"number\":\n return numberToText(value);\n case \"bigint\":\n return value.toString();\n case \"boolean\":\n return value ? \"t\" : \"f\";\n case \"object\": {\n if (Array.isArray(value)) return arrayToText(value);\n if (value instanceof Date) return value.toISOString();\n if (value instanceof Uint8Array) return byteaToText(value);\n if (value instanceof ArrayBuffer) return byteaToText(new Uint8Array(value));\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n return byteaToText(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));\n }\n // json / jsonb arrive already parsed; re-serialize them.\n return JSON.stringify(value);\n }\n default:\n // Should be unreachable for Electric-parsed values; be defensive.\n return String(value);\n }\n}\n\n/**\n * Build a Postgres array literal from a `json[]`/`jsonb[]` value. Each element\n * is JSON text (re-serialized from the parsed value), so we cannot reuse the\n * generic array path: a JSON array element must stay JSON (`[1,2]`), not be\n * turned into a nested SQL array (`{1,2}`).\n */\nfunction jsonArrayToText(arr: ReadonlyArray<unknown>): string {\n const elements = arr.map((el) => (el === null || el === undefined ? \"NULL\" : quoteArrayElement(jsonToText(el))));\n return \"{\" + elements.join(\",\") + \"}\";\n}\n\n/**\n * Re-serialize a parsed `json`/`jsonb` value to its JSON text form. Electric\n * delivers these columns already run through `JSON.parse`, so the value is the\n * decoded JS value (object, array, string, number, boolean or null) and always\n * needs `JSON.stringify` to become valid JSON input again — including scalars\n * (the string `hi` must be written as `\"hi\"`).\n */\nfunction jsonToText(value: unknown): string {\n return JSON.stringify(value);\n}\n\n/**\n * Postgres `udt_name`s that need JSON-aware serialization rather than the\n * generic runtime-type dispatch. Used to resolve the otherwise undecidable\n * \"is this JS array a SQL array or a JSON array?\" ambiguity.\n */\nconst JSON_UDT_NAMES = new Set([\"json\", \"jsonb\"]);\nconst JSON_ARRAY_UDT_NAMES = new Set([\"_json\", \"_jsonb\"]);\n\n/**\n * Serialize a single value into one COPY TEXT field. `null`/`undefined` become\n * the NULL marker (`\\N`); everything else is converted to text and escaped.\n *\n * `udtName` is the column's Postgres `udt_name`. When supplied it disambiguates\n * `json`/`jsonb` columns; when omitted the value's runtime type is used (which\n * cannot tell a `jsonb` array from a SQL array).\n */\nexport function serializeCopyValue(value: unknown, udtName?: string): string {\n if (value === null || value === undefined) return NULL_MARKER;\n if (udtName !== undefined) {\n if (JSON_UDT_NAMES.has(udtName)) return escapeCopyText(jsonToText(value));\n if (JSON_ARRAY_UDT_NAMES.has(udtName) && Array.isArray(value)) return escapeCopyText(jsonArrayToText(value));\n }\n return escapeCopyText(valueToText(value));\n}\n\n/**\n * Serialize a list of row objects into the body of a `COPY ... FROM` request in\n * TEXT format. Columns are emitted in the given order, fields are tab\n * separated, and rows are newline separated.\n *\n * `columnTypes` optionally maps a column name to its Postgres `udt_name`; pass\n * it so `json`/`jsonb` columns serialize correctly.\n */\nexport function generateCopyData(\n rows: ReadonlyArray<Record<string, unknown>>,\n columns: ReadonlyArray<string>,\n columnTypes?: Readonly<Record<string, string | undefined>>,\n): string {\n return rows\n .map((row) => columns.map((column) => serializeCopyValue(row[column], columnTypes?.[column])).join(DELIMITER))\n .join(ROW_SEPARATOR);\n}\n",
123
130
  "import type { PGlite, PGliteInterface, Transaction } from \"@electric-sql/pglite\";\nimport { drizzle, type PgliteDatabase } from \"drizzle-orm/pglite\";\n\n/**\n * A Drizzle handle whose executor is an already-open PGlite connection *or* an open PGlite\n * `Transaction` — the tier-① authoring/execution surface for the sync engine's metadata-store DML\n * (ADR-0028 decision 4).\n *\n * The blocker the old convertibility report cited was \"`drizzle-orm/pglite` wraps only a PGlite\n * instance, not a Transaction\". That is a *type* boundary, not a runtime one: drizzle's pglite session\n * layer only ever calls `client.query(sql, params, { rowMode, parsers })` on the wrapped client (verified\n * against drizzle-orm 1.0.0-rc.4 `pglite/session.js` — the executor touches nothing but `.query`; the\n * only other member it would reach is `.transaction`, and only if someone calls `db.transaction()`).\n * PGlite's `Transaction` exposes a `query` with the identical `(sql, params, options)` shape, so a handle\n * built over a `Transaction` executes every statement **on that transaction** — participating in the\n * engine's commit boundary rather than opening its own.\n *\n * The cast to `PGlite` is the narrowest honest one: at runtime the session only calls `.query`, which\n * both `PGliteInterface` and `Transaction` satisfy; the type just does not express that union. It is the\n * expected single-expression cast for this seam.\n *\n * CONTRACT: `.transaction()` on the returned handle is **forbidden**. The engine owns transaction\n * boundaries itself (`pg.transaction(async (tx) => …)` + explicit `tx.rollback()` on unsubscribe, sync\n * index.ts); calling `db.transaction()` here would (a) require the wrapped client to be a full PGlite,\n * which a `Transaction` is not, and (b) open a nested boundary the engine does not expect. Do not expose\n * or use it.\n *\n * MUST be the `{ client }` config form: drizzle's pglite driver destructures `{ connection, client }`\n * from a bare first argument, so `drizzle(pg)` misdetects the handle as a config object and silently\n * constructs a NEW in-memory PGlite — every statement would then hit an empty, throwaway database.\n */\n\n// One drizzle handle per underlying connection/transaction object. The handle for a given `Transaction`\n// is short-lived (one commit) but reused across the several metadata statements that run within that\n// commit — the tag-store hot path — so memoizing per handle avoids re-wrapping on every statement while\n// never leaking across transactions (a `Transaction` object is a fresh identity each commit, and the\n// WeakMap drops it once the commit's closure is collected).\nconst handles = new WeakMap<PGliteInterface | Transaction, PgliteDatabase<never>>();\n\n/** A (memoized) Drizzle handle over an open PGlite connection or transaction — engine-internal. */\nexport function drizzleOverPg(pg: PGliteInterface | Transaction): PgliteDatabase<never> {\n let db = handles.get(pg);\n if (!db) {\n db = drizzle({ client: pg as unknown as PGlite }) as PgliteDatabase<never>;\n handles.set(pg, db);\n }\n return db;\n}\n",
124
131
  "// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\nimport type { ChangeMessage, Row } from \"@electric-sql/client\";\nimport type { PGliteInterface, Transaction } from \"@electric-sql/pglite\";\nimport { and, eq, fillPlaceholders, sql } from \"drizzle-orm\";\nimport { getTableConfig, type PgColumn } from \"drizzle-orm/pg-core\";\n\nimport { quoteIdentifier } from \"@pgxsinkit/contracts\";\n\nimport type { ApplyTarget } from \"../local-tables\";\nimport { generateCopyData } from \"./copy\";\nimport { drizzleOverPg } from \"./drizzle-executor\";\nimport type { InsertChangeMessage } from \"./types\";\n\n/**\n * Re-key an Electric change row (keyed by DB **column name**) to the Drizzle **property keys** the\n * query builder addresses columns by (ADR-0029 D1). A column absent from the local projected table is a\n * config error and surfaces, rather than silently binding to nothing.\n */\nfunction toDriverRow(target: ApplyTarget, data: Row<unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const name of Object.keys(data)) {\n const propertyKey = target.propertyKeyByName[name];\n if (propertyKey === undefined) {\n throw new Error(`sync apply: column ${JSON.stringify(name)} is not present on the local synced table`);\n }\n out[propertyKey] = data[name];\n }\n return out;\n}\n\n/** The `PgColumn` for a DB column name on the target table (for `eq`/conflict-target/COPY clauses). */\nfunction targetColumn(target: ApplyTarget, name: string): PgColumn {\n const column = target.columnByName[name];\n if (!column) {\n throw new Error(`sync apply: column ${JSON.stringify(name)} not found on the local synced table`);\n }\n return column;\n}\n\nexport interface ApplyMessageToTableOptions {\n pg: PGliteInterface | Transaction;\n target: ApplyTarget;\n message: ChangeMessage<Row<unknown>>;\n debug: boolean;\n}\n\nexport async function applyMessageToTable({ pg, target, message, debug }: ApplyMessageToTableOptions) {\n const data = message.value;\n const db = drizzleOverPg(pg);\n\n switch (message.headers.operation) {\n case \"insert\": {\n if (debug) console.log(\"inserting\", data);\n // Apply exactly what Electric sent: an `insert` is a new row (post-truncate or first send), so\n // it is a plain INSERT. A genuine primary-key collision must surface, never be silently upserted.\n return await db.insert(target.table).values(toDriverRow(target, data) as never);\n }\n\n case \"update\": {\n if (debug) console.log(\"updating\", data);\n const setColumns = Object.keys(data).filter((column) => !target.primaryKey.includes(column));\n if (setColumns.length === 0) return;\n const setValues: Record<string, unknown> = {};\n for (const column of setColumns) setValues[target.propertyKeyByName[column]!] = data[column];\n return await db\n .update(target.table)\n .set(setValues as never)\n .where(and(...target.primaryKey.map((column) => eq(targetColumn(target, column), data[column]))));\n }\n\n case \"delete\": {\n if (debug) console.log(\"deleting\", data);\n return await db\n .delete(target.table)\n .where(and(...target.primaryKey.map((column) => eq(targetColumn(target, column), data[column]))));\n }\n }\n}\n\nexport interface BulkApplyMessagesToTableOptions {\n pg: PGliteInterface | Transaction;\n target: ApplyTarget;\n messages: InsertChangeMessage[];\n debug: boolean;\n}\n\nconst MAX_INSERT_PARAMS = 32_000;\nconst MAX_INSERT_BYTES = 50 * 1024 * 1024;\n\n/**\n * The rendered `{sqlText, params}` for a batched INSERT of `rowCount` rows over `colNames` (ADR-0029\n * D5's render-once remedy). Rendered ONCE per distinct (column-set, row-count) via a placeholder INSERT\n * over the real table, then reused for every batch of that shape — driving the per-row × per-column\n * builder-AST cost to zero. `sql.placeholder` cells make Drizzle emit `$n` markers without applying a\n * codec at render time; the codec is applied per value at execution (see {@link executeInsertBatch}).\n */\nfunction renderInsert(\n db: ReturnType<typeof drizzleOverPg>,\n target: ApplyTarget,\n colNames: string[],\n rowCount: number,\n): { sqlText: string; params: unknown[] } {\n const key = JSON.stringify([rowCount, colNames]);\n const cached = target.insertRenderCache.get(key);\n if (cached) return cached;\n const placeholderRows = Array.from({ length: rowCount }, (_, r) =>\n Object.fromEntries(colNames.map((name, ci) => [target.propertyKeyByName[name]!, sql.placeholder(`${r}_${ci}`)])),\n );\n const rendered = db\n .insert(target.table)\n .values(placeholderRows as never)\n .toSQL();\n const value = { sqlText: rendered.sql, params: rendered.params as unknown[] };\n target.insertRenderCache.set(key, value);\n return value;\n}\n\n/**\n * Execute one rendered batch: fill the render-once placeholders with this batch's values, applying the\n * real per-column codec (`fillPlaceholders` runs each column's `mapToDriverValue`, with a null guard —\n * byte-identical to a plain `.values()` bind), then run the pre-rendered statement on the executor.\n */\nasync function executeInsertBatch(\n pg: PGliteInterface | Transaction,\n db: ReturnType<typeof drizzleOverPg>,\n target: ApplyTarget,\n colNames: string[],\n batch: Row<unknown>[],\n): Promise<void> {\n const rendered = renderInsert(db, target, colNames, batch.length);\n const values: Record<string, unknown> = {};\n for (let r = 0; r < batch.length; r++) {\n const row = batch[r]!;\n for (let ci = 0; ci < colNames.length; ci++) {\n values[`${r}_${ci}`] = row[colNames[ci]!];\n }\n }\n const flat = fillPlaceholders(rendered.params, values);\n await pg.query(rendered.sqlText, flat as unknown[]);\n}\n\nexport async function applyInsertsToTable({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {\n const data: Row<unknown>[] = messages.map((message) => message.value);\n const firstRow = data[0];\n if (!firstRow) {\n return;\n }\n\n if (debug) console.log(\"inserting\", data);\n const columns = Object.keys(firstRow);\n const db = drizzleOverPg(pg);\n\n const getValueSize = (value: unknown): number => {\n if (value === null) return 0;\n if (value instanceof ArrayBuffer) return value.byteLength;\n if (value instanceof Blob) return value.size;\n if (value instanceof Uint8Array) return value.byteLength;\n if (value instanceof DataView) return value.byteLength;\n if (ArrayBuffer.isView(value)) return value.byteLength;\n\n switch (typeof value) {\n case \"string\":\n return value.length;\n case \"number\":\n return 8;\n case \"boolean\":\n return 1;\n case \"bigint\":\n case \"symbol\":\n return value.toString().length;\n case \"function\":\n case \"undefined\":\n return 0;\n default: {\n // Remaining typeof: object (null was handled above).\n if (value instanceof Date) return 8;\n try {\n return JSON.stringify(value)?.length ?? 0;\n } catch {\n // Non-serialisable nested value (e.g. bigint inside jsonb).\n return 16;\n }\n }\n }\n };\n\n const getRowSize = (row: Row<unknown>): number => {\n return columns.reduce((size, column) => {\n const value = row[column];\n if (value === null) return size;\n\n if (Array.isArray(value)) {\n if (value.length === 0) return size;\n const firstElement = value[0];\n\n switch (typeof firstElement) {\n case \"number\":\n return size + value.length * 8;\n case \"string\":\n return size + value.reduce((arrSize, str) => arrSize + str.length, 0);\n case \"boolean\":\n return size + value.length;\n default:\n if (firstElement instanceof Date) {\n return size + value.length * 8;\n }\n return size + value.reduce((arrSize, item) => arrSize + getValueSize(item), 0);\n }\n }\n\n return size + getValueSize(value);\n }, 0);\n };\n\n let currentBatch: Row<unknown>[] = [];\n let currentBatchSize = 0;\n let currentBatchParams = 0;\n\n for (const row of data) {\n const rowSize = getRowSize(row);\n const rowParams = columns.length;\n\n if (\n currentBatch.length > 0 &&\n (currentBatchSize + rowSize > MAX_INSERT_BYTES || currentBatchParams + rowParams > MAX_INSERT_PARAMS)\n ) {\n if (debug && currentBatchSize + rowSize > MAX_INSERT_BYTES) {\n console.log(\"batch size limit exceeded, executing batch\");\n }\n if (debug && currentBatchParams + rowParams > MAX_INSERT_PARAMS) {\n console.log(\"batch params limit exceeded, executing batch\");\n }\n await executeInsertBatch(pg, db, target, columns, currentBatch);\n currentBatch = [];\n currentBatchSize = 0;\n currentBatchParams = 0;\n }\n\n currentBatch.push(row);\n currentBatchSize += rowSize;\n currentBatchParams += rowParams;\n }\n\n if (currentBatch.length > 0) {\n await executeInsertBatch(pg, db, target, columns, currentBatch);\n }\n\n if (debug) console.log(`Inserted ${messages.length} rows using INSERT`);\n}\n\n/**\n * Bulk **upsert** for tagged-subquery move-in rows (ADR-0024). A move-in is an existing row ENTERING the\n * shape — unlike a CDC `insert` (a brand-new row) it may already be present locally via an independent\n * grant, or be re-delivered on a resume from before the move-in's offset. So it is applied idempotently:\n * `INSERT … ON CONFLICT (pk) DO UPDATE` refreshes to the move-in's authoritative value (or `DO NOTHING`\n * for a pk-only table). The plain-`INSERT` invariant of the CDC path — a genuine PK collision must\n * surface ({@link applyInsertsToTable}) — is intentionally NOT used here, because for a move-in a present\n * row is expected, not a bug. Batched by parameter count (move-in volume is incremental, not a backfill).\n */\nexport async function applyUpsertsToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {\n const primaryKey = target.primaryKey;\n if (primaryKey.length === 0) throw new Error(\"applyUpsertsToTable requires a primary key\");\n\n const data: Row<unknown>[] = messages.map((message) => message.value);\n const firstRow = data[0];\n if (!firstRow) return;\n\n const columns = Object.keys(firstRow);\n const pkSet = new Set(primaryKey);\n const nonPkColumns = columns.filter((column) => !pkSet.has(column));\n\n const conflictTarget = primaryKey.map((column) => targetColumn(target, column));\n // `DO UPDATE SET col = excluded.col` for every non-pk column; `excluded.<col>` is the standard\n // conflict pseudo-relation reference, authored via `sql.identifier` so the column stays a quoted bare\n // identifier (not table-qualified). A pk-only table has nothing to refresh → `DO NOTHING`.\n const conflictSet: Record<string, unknown> = {};\n for (const column of nonPkColumns) {\n conflictSet[target.propertyKeyByName[column]!] = sql`excluded.${sql.identifier(column)}`;\n }\n\n const perRow = columns.length;\n const rowsPerBatch = Math.max(1, Math.floor(MAX_INSERT_PARAMS / perRow));\n const db = drizzleOverPg(pg);\n\n for (let i = 0; i < data.length; i += rowsPerBatch) {\n const batch = data.slice(i, i + rowsPerBatch).map((row) => toDriverRow(target, row));\n const insert = db.insert(target.table).values(batch as never);\n if (nonPkColumns.length > 0) {\n await insert.onConflictDoUpdate({ target: conflictTarget, set: conflictSet as never });\n } else {\n // Target the PK explicitly so a pk-only conflict is a no-op ONLY on the primary key — a bare\n // `ON CONFLICT DO NOTHING` would swallow conflicts on any unique constraint.\n await insert.onConflictDoNothing({ target: conflictTarget });\n }\n }\n\n if (debug) console.log(`Upserted ${messages.length} move-in rows`);\n}\n\n/** A column's name plus the SQL type to cast it to inside a `json_to_recordset` record definition. */\ninterface JsonRecordsetColumn {\n name: string;\n castType: string;\n}\n\n/**\n * The `json_to_recordset` casts for the rows being applied, narrowed to the columns actually present in\n * the synced row, from the model-derived {@link ApplyTarget.columnTypes} (ADR-0029 D2 — never from a\n * catalog probe: the types are always present, derived from the same Drizzle definitions the local\n * store was rendered from).\n */\nfunction jsonRecordsetColumns(target: ApplyTarget, firstRow: Row<unknown>): JsonRecordsetColumn[] {\n const present = (name: string) => Object.prototype.hasOwnProperty.call(firstRow, name);\n return target.columnTypes\n .filter((column) => present(column.name))\n .map((column) => ({ name: column.name, castType: `${column.sqlType}${column.isArray ? \"[]\" : \"\"}` }));\n}\n\nexport async function applyMessagesToTableWithJson({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {\n if (debug) console.log(\"applying messages with json_to_recordset\");\n\n const data: Row<unknown>[] = messages.map((message) => message.value);\n const firstRow = data[0];\n if (!firstRow) {\n return;\n }\n const columns = jsonRecordsetColumns(target, firstRow);\n const targetTable = target.table;\n // Tier ② (ADR-0028): the target table is an interpolated table object and the batch is a single bound\n // param (`sql.param` binds the raw JS array unchanged, exactly as the old `[batch]` did — critically,\n // NOT `JSON.stringify`, which would throw on the bigints this path carries). The `x(col type, …)`\n // record definition is raw text: `json_to_recordset`'s grammar requires bare column identifiers and\n // type names there, which no tier-①/② builder expresses.\n const recordDef = columns.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(\", \");\n const db = drizzleOverPg(pg);\n\n const max = 10_000;\n for (let i = 0; i < data.length; i += max) {\n const batch = data.slice(i, i + max);\n await db.execute(\n sql`INSERT INTO ${targetTable} SELECT x.* from json_to_recordset(${sql.param(batch)}) as x(${sql.raw(recordDef)})`,\n );\n }\n\n if (debug) {\n console.log(`Inserted ${messages.length} rows using json_to_recordset`);\n }\n}\n\n/**\n * Each column mapped to its Postgres `udt_name` for the COPY serializer, which needs it only to\n * disambiguate `json`/`jsonb` (whose parsed values are indistinguishable from SQL arrays/objects by\n * runtime type alone). Derived from the model ({@link ApplyTarget.columnTypes}), never introspected\n * (ADR-0029 D2).\n */\nfunction copyColumnUdts(target: ApplyTarget): Record<string, string> {\n const map: Record<string, string> = {};\n for (const column of target.columnTypes) {\n const base = column.sqlType\n .replace(/\\(.*\\)/g, \"\")\n .trim()\n .toLowerCase();\n if (base === \"json\" || base === \"jsonb\") {\n map[column.name] = column.isArray ? `_${base}` : base;\n }\n }\n return map;\n}\n\nexport async function applyMessagesToTableWithCopy({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {\n if (debug) console.log(\"applying messages with COPY\");\n\n const data: Row<unknown>[] = messages.map((message) => message.value);\n const firstRow = data[0];\n if (!firstRow) {\n return;\n }\n const columns = Object.keys(firstRow);\n\n // Serialize rows using Postgres' own COPY TEXT format — a faithful port of the backend's\n // CopyAttributeOutText / array_out routines (see ./copy) — so arrays (incl. multi-dimensional),\n // json/jsonb, bytea, timestamps and strings with embedded delimiters/newlines all round-trip,\n // unlike the previous hand-rolled CSV encoder.\n const columnUdts = copyColumnUdts(target);\n const copyData = generateCopyData(data, columns, columnUdts);\n const copyBlob = new Blob([copyData], { type: \"text/plain\" });\n\n // TEXT is the default COPY format; its default delimiter is a tab and NULL marker is `\\N`, both of\n // which generateCopyData emits.\n //\n // Tier ③ (ADR-0028 allow-list): `COPY … FROM '/dev/blob'` is PGlite's blob-ingest grammar — it has no\n // Drizzle builder form, so the statement stays a raw string. The table reference is taken from the real\n // synced table object: a bare name (ephemeral → `pg_temp` via search_path) or a schema-qualified one.\n const { name: tableName, schema } = getTableConfig(target.table);\n const copyTarget = schema ? `${quoteIdentifier(schema)}.${quoteIdentifier(tableName)}` : quoteIdentifier(tableName);\n await pg.query(\n `\n COPY ${copyTarget} (${columns.map((column) => quoteIdentifier(column)).join(\", \")})\n FROM '/dev/blob'\n WITH (FORMAT text)\n `,\n [],\n {\n blob: copyBlob,\n },\n );\n\n if (debug) console.log(`Inserted ${messages.length} rows using COPY`);\n}\n\nconst JSON_RECORDSET_BATCH = 10_000;\n\n/**\n * The `json_to_recordset` casts for an **explicit, ordered** column list — the bulk UPDATE/DELETE source\n * relations need the PK columns (plus, for updates, the group's SET columns) in a known order. Derived\n * from the model ({@link ApplyTarget.columnTypes}), never introspected (ADR-0029 D2).\n */\nfunction recordsetColumnCasts(target: ApplyTarget, columnNames: string[]): JsonRecordsetColumn[] {\n const byName = new Map(target.columnTypes.map((column) => [column.name, column]));\n return columnNames.map((name) => {\n const column = byName.get(name);\n if (!column) {\n throw new Error(`recordsetColumnCasts: no registered type for column ${JSON.stringify(name)}`);\n }\n return { name, castType: `${column.sqlType}${column.isArray ? \"[]\" : \"\"}` };\n });\n}\n\nexport interface BulkKeyedApplyOptions {\n pg: PGliteInterface | Transaction;\n target: ApplyTarget;\n /** Folded messages: for deletes the value carries the PK; for updates the PK plus merged columns. */\n messages: ChangeMessage<Row<unknown>>[];\n debug: boolean;\n}\n\n/**\n * Bulk DELETE by primary key via `DELETE … USING json_to_recordset(…)` (ADR-0014 Phase 3). Safe\n * because the read-path fold already left **one row per PK** — no same-PK duplicate in the source.\n */\nexport async function applyBulkDeletesToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {\n const primaryKey = target.primaryKey;\n if (primaryKey.length === 0) throw new Error(\"applyBulkDeletesToTable requires a primary key\");\n if (messages.length === 0) return;\n\n const rows = messages.map((message) => {\n const data = message.value;\n return Object.fromEntries(primaryKey.map((column) => [column, data[column]]));\n });\n\n const casts = recordsetColumnCasts(target, primaryKey);\n const recordDef = casts.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(\", \");\n const whereJoin = primaryKey\n .map((column) => `t.${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)\n .join(\" AND \");\n const targetTable = target.table;\n const db = drizzleOverPg(pg);\n\n for (let i = 0; i < rows.length; i += JSON_RECORDSET_BATCH) {\n const batch = rows.slice(i, i + JSON_RECORDSET_BATCH);\n // Tier ② (ADR-0028): the target table is an interpolated table object; the pk-projection batch is a\n // single bound param (`sql.param` binds the raw JS array unchanged — as the old `[batch]` did, and\n // NOT `JSON.stringify`, which would throw on bigint pks). No cast is needed — `json_to_recordset`\n // has a single json-typed signature. The `x(col type, …)` record definition and the alias-qualified\n // `t.*`/`x.*` join are raw text: the `USING`/recordset-join grammar requires those bare identifiers.\n await db.execute(\n sql`DELETE FROM ${targetTable} AS t USING json_to_recordset(${sql.param(batch)}) AS x(${sql.raw(recordDef)}) WHERE ${sql.raw(whereJoin)}`,\n );\n }\n\n if (debug) console.log(`Deleted ${messages.length} rows using json_to_recordset`);\n}\n\n/**\n * Bulk UPDATE via `UPDATE … FROM json_to_recordset(…)` (ADR-0014 Phase 3), **grouped by the set of\n * non-PK columns** each row carries. Electric's default replica sends only the changed columns, so\n * two rows in one batch can set different columns; one `UPDATE … FROM` per distinct column-set keeps\n * each statement uniform. Safe from the same-PK join hazard because the fold already left one row per\n * PK, so no PK appears twice within a group.\n */\nexport async function applyBulkUpdatesToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {\n const primaryKey = target.primaryKey;\n if (primaryKey.length === 0) throw new Error(\"applyBulkUpdatesToTable requires a primary key\");\n if (messages.length === 0) return;\n\n const pkSet = new Set(primaryKey);\n const groups = new Map<string, { setColumns: string[]; rows: Row<unknown>[] }>();\n for (const message of messages) {\n const data = message.value;\n const setColumns = Object.keys(data)\n .filter((column) => !pkSet.has(column))\n .sort();\n // A PK-only update sets nothing — the per-row applyMessageToTable returns early on this too.\n if (setColumns.length === 0) continue;\n const groupKey = setColumns.join(\" \");\n let group = groups.get(groupKey);\n if (!group) {\n group = { setColumns, rows: [] };\n groups.set(groupKey, group);\n }\n group.rows.push(Object.fromEntries([...primaryKey, ...setColumns].map((column) => [column, data[column]])));\n }\n\n const targetTable = target.table;\n const db = drizzleOverPg(pg);\n\n for (const { setColumns, rows } of groups.values()) {\n const casts = recordsetColumnCasts(target, [...primaryKey, ...setColumns]);\n const recordDef = casts.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(\", \");\n const setClause = setColumns\n .map((column) => `${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)\n .join(\", \");\n const whereJoin = primaryKey\n .map((column) => `t.${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)\n .join(\" AND \");\n\n for (let i = 0; i < rows.length; i += JSON_RECORDSET_BATCH) {\n const batch = rows.slice(i, i + JSON_RECORDSET_BATCH);\n // Tier ② (ADR-0028), as applyBulkDeletesToTable above: interpolated target table + single bound\n // `sql.param` batch (raw array, not `JSON.stringify` — bigint-safe), no cast needed; the `SET` /\n // `x(col type, …)` record def and the alias-qualified `t.*`/`x.*` join stay raw text (grammar).\n await db.execute(\n sql`UPDATE ${targetTable} AS t SET ${sql.raw(setClause)} FROM json_to_recordset(${sql.param(batch)}) AS x(${sql.raw(recordDef)}) WHERE ${sql.raw(whereJoin)}`,\n );\n }\n }\n\n if (debug) console.log(`Updated ${messages.length} rows using json_to_recordset`);\n}\n",
125
132
  "import { index, jsonb, pgSchema, primaryKey, text } from \"drizzle-orm/pg-core\";\n\nimport type { ShapeSubscriptionState } from \"./subscription-state\";\n\n/**\n * The two metadata-store relations the sync engine provisions at boot (ADR-0028 decision 4). The\n * metadata schema name is dynamic (per-client config) but fixed at engine construction, so the tables\n * are built per schema string and memoized.\n *\n * ADR-0029 D3: these pgTables are the SINGLE SOURCE for the relations. `migrateSubscriptionMetadataTables`\n * (subscription-state.ts) renders their `CREATE TABLE`/`CREATE INDEX` DDL FROM these definitions via the\n * in-house `renderCreateTableSql` (schema.ts), and the DML paths query them directly — so the DDL and the\n * pgTable can no longer diverge, and the former drift guard in `tests/unit/sync-drizzle-executor.test.ts`\n * is now a plain provisioning round-trip.\n *\n * Property keys are deliberately snake_case to mirror the row shapes the callers already consume\n * (`shape_metadata`, `last_lsn`, `pk_json`, …), so a `select()` returns rows in the existing shape with\n * no alias mapping.\n */\n\nexport interface MetadataTables {\n /** `<schema>.subscriptions_metadata` — one row per subscription key. */\n readonly subscriptionsMetadata: ReturnType<typeof buildSubscriptionsMetadata>;\n /** `<schema>.shape_row_tags` — the tagged-subquery reason-set store (ADR-0023). */\n readonly shapeRowTags: ReturnType<typeof buildShapeRowTags>;\n}\n\nfunction buildSubscriptionsMetadata(schema: ReturnType<typeof pgSchema>) {\n return schema.table(\"subscriptions_metadata\", {\n key: text(\"key\").primaryKey(),\n // JSONB NOT NULL — round-trips as a parsed object (drizzle's jsonb codec), matching the raw path.\n shape_metadata: jsonb(\"shape_metadata\").$type<Record<string, ShapeSubscriptionState>>().notNull(),\n // The LSN is persisted as TEXT (a bigint has no JSON/portable-column form); callers `BigInt(...)` it.\n last_lsn: text(\"last_lsn\").notNull(),\n });\n}\n\nfunction buildShapeRowTags(schema: ReturnType<typeof pgSchema>) {\n return schema.table(\n \"shape_row_tags\",\n {\n shape_table: text(\"shape_table\").notNull(),\n pk_json: text(\"pk_json\").notNull(),\n tag: text(\"tag\").notNull(),\n },\n (t) => [\n primaryKey({ columns: [t.shape_table, t.pk_json, t.tag] }),\n index(\"shape_row_tags_shape_tag_idx\").on(t.shape_table, t.tag),\n ],\n );\n}\n\nconst cache = new Map<string, MetadataTables>();\n\n/** The (memoized) metadata-store `pgTable`s for a given metadata schema name. */\nexport function getMetadataTables(metadataSchema: string): MetadataTables {\n let tables = cache.get(metadataSchema);\n if (!tables) {\n const schema = pgSchema(metadataSchema);\n tables = {\n subscriptionsMetadata: buildSubscriptionsMetadata(schema),\n shapeRowTags: buildShapeRowTags(schema),\n };\n cache.set(metadataSchema, tables);\n }\n return tables;\n}\n",
126
133
  "import type { ChangeMessage, MovePattern, Row } from \"@electric-sql/client\";\nimport type { PGliteInterface, Transaction } from \"@electric-sql/pglite\";\nimport { and, eq, inArray, like, sql } from \"drizzle-orm\";\nimport { getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport { quoteIdentifier, quoteSqlLiteral } from \"@pgxsinkit/contracts\";\n\nimport type { ApplyTarget } from \"../local-tables\";\nimport { applyBulkDeletesToTable } from \"./apply\";\nimport { drizzleOverPg } from \"./drizzle-executor\";\nimport { getMetadataTables } from \"./metadata-tables\";\n\n/**\n * Electric **tagged-subquery** reconciliation (ADR-0023). A shape whose `where` contains a subquery\n * (membership-style row filters: `container_id IN (SELECT … FROM memberships WHERE member = $sub)`)\n * streams two extra things the plain change path ignores:\n *\n * - every change message carries `headers.tags` — the **reasons** the row is in the shape (one tag per\n * grant/membership), plus `removed_tags` on an update;\n * - a **`move-out` `EventMessage`** carries `patterns: { pos, value }[]` — \"the tag whose component at\n * index `pos` equals `value` is withdrawn\", i.e. that grant was revoked.\n *\n * A row leaves the shape only when it has **no remaining tag**. The engine drops the `EventMessage`\n * today, so a removed member keeps the revoked rows. This module persists each row's tag-set in one\n * metadata table and evicts rows whose last tag is withdrawn — closing the move-out gap without an\n * Electric change.\n *\n * Tag storage is a single metadata table keyed by the synced table + a canonical primary-key JSON:\n * `shape_row_tags(shape_table, pk_json, tag)`. It is created in `migrateSubscriptionMetadataTables`.\n */\n\n/**\n * The pgxsinkit-owned metadata schema (ADR-0009 decision 6) the tag store + subscription state live in.\n * The sync engine defaults its `metadataSchema` to this, and `createSyncClient` never overrides it — so\n * the desync path (which is outside the engine) can key the tag store by this same constant.\n */\nexport const DEFAULT_METADATA_SCHEMA = \"pgxsinkit\";\n\n/**\n * A bare, lowercase, unqualified SQL identifier: begins with a lowercase letter or underscore, then\n * lowercase letters, digits, and underscores.\n */\nconst METADATA_SCHEMA_PATTERN = /^[a-z_][a-z0-9_]*$/;\n\n/**\n * Validate the metadata schema name at engine construction. The name is interpolated RAW into two\n * positions a double-quoted identifier cannot cover:\n * - GUC space — `SET LOCAL <schema>.syncing` (sync/index.ts) and `SET <schema>.syncing = false`\n * (the metadata migration). GUC grammar takes a `namespace.name` of bare identifiers; it does not\n * accept a quoted identifier the way a table/column position does, so the name cannot be safely\n * quoted there.\n * - the `CREATE SCHEMA <schema>` DDL identifier position.\n * Rather than trust arbitrary caller input in those raw positions, restrict the name to a bare\n * lowercase identifier and reject uppercase/exotic names outright. The default \"pgxsinkit\" passes.\n */\nexport function assertValidMetadataSchema(metadataSchema: string): void {\n if (!METADATA_SCHEMA_PATTERN.test(metadataSchema)) {\n throw new Error(\n `Invalid metadataSchema ${JSON.stringify(metadataSchema)}: it must be a bare lowercase SQL ` +\n `identifier matching ${String(METADATA_SCHEMA_PATTERN)}. The name is interpolated unquoted into ` +\n `GUC (\\`SET <schema>.syncing\\`) and \\`CREATE SCHEMA\\` identifier positions where a quoted ` +\n `identifier is not accepted, so uppercase and exotic names are rejected at construction.`,\n );\n }\n}\n\n/**\n * The tag store's schema-qualified identifier, derived from the `shape_row_tags` pgTable config\n * (ADR-0029 D3 — single source; no parallel name string). The store itself is provisioned by\n * `migrateSubscriptionMetadataTables`, which renders that same pgTable.\n */\nexport function shapeRowTagsTableName(metadataSchema: string): string {\n const config = getTableConfig(getMetadataTables(metadataSchema).shapeRowTags);\n return `${quoteIdentifier(config.schema ?? \"public\")}.${quoteIdentifier(config.name)}`;\n}\n\n/** The `shape_table` key for the tag store: the synced table, schema-qualified (defaults `public`). */\nexport function shapeTableId(schema: string | undefined, table: string): string {\n return `${schema ?? \"public\"}.${table}`;\n}\n\n/**\n * Static SQL to drop a shape's tag-set, **guarded** by `to_regclass` so it is a no-op when the tag store\n * does not exist. Used by `buildDesyncTableSql` (ADR-0023 Slice 2), which may be exec'd standalone (a\n * caller/test that builds the local schema without booting the sync engine that creates the store). The\n * engine's own `clearShapeTags` runs inside a commit where the store is guaranteed present, so it is not\n * guarded.\n */\nexport function buildClearShapeTagsSql(shapeTable: string, metadataSchema: string = DEFAULT_METADATA_SCHEMA): string {\n const table = shapeRowTagsTableName(metadataSchema);\n return `DO $$ BEGIN\n IF to_regclass(${quoteSqlLiteral(table)}) IS NOT NULL THEN\n DELETE FROM ${table} WHERE shape_table = ${quoteSqlLiteral(shapeTable)};\n END IF;\nEND $$;`;\n}\n\n/**\n * Canonical primary-key JSON for a synced row — the tag store's per-row key. Built from the **mapped**\n * value (synced-table column names), with pk columns sorted so the string is stable, and `bigint`\n * rendered as a string (JSON has no bigint). Reversible via `JSON.parse` for the eviction DELETE.\n */\nexport function serializeRowPk(value: Row<unknown>, primaryKey: readonly string[]): string {\n const obj: Record<string, unknown> = {};\n for (const column of [...primaryKey].sort()) {\n obj[column] = value[column];\n }\n return JSON.stringify(obj, (_key, v: unknown) => (typeof v === \"bigint\" ? v.toString() : v));\n}\n\n/**\n * Split a composite `MoveTag` into its positional columns. A tag for a shape with N subquery conditions\n * is the per-condition grant values joined by `/` (an absent condition is an empty column) — e.g. a\n * two-condition shape yields `\"<grantHash>/1//\"` and `\"//<grantHash>/<grantHash>\"`. `\\/` is a literal\n * `/`, `\\\\` a literal `\\`. A single-condition shape's tag has no separator → `[tag]`.\n *\n * (The `MovePattern.pos` indexes into THIS split — confirmed against Electric 1.7.4 wire messages,\n * ADR-0023. The upstream type doc mentions `|`; the actual column separator on the wire is `/`.)\n */\nexport function splitTagComponents(tag: string): string[] {\n const parts: string[] = [];\n let current = \"\";\n for (let i = 0; i < tag.length; i++) {\n const char = tag[i]!;\n if (char === \"\\\\\" && i + 1 < tag.length) {\n current += tag[i + 1];\n i += 1;\n continue;\n }\n if (char === \"/\") {\n parts.push(current);\n current = \"\";\n continue;\n }\n current += char;\n }\n parts.push(current);\n return parts;\n}\n\n/**\n * Whether a tag is withdrawn by a `move-out` event. A revoked grant can appear at more than one column\n * of the shape's tag structure (one position per subquery condition that references it), so the event\n * enumerates those positions and a tag is withdrawn if it carries the value at **any** of them. A row\n * is then evicted only once **every** tag keeping it in the shape has been withdrawn (the caller's\n * empty-tag-set check) — so a row held by an independent second grant survives. Empty pattern set\n * matches nothing.\n */\nexport function tagMatchesPatterns(tag: string, patterns: readonly MovePattern[]): boolean {\n if (patterns.length === 0) return false;\n const parts = splitTagComponents(tag);\n return patterns.some((pattern) => parts[pattern.pos] === pattern.value);\n}\n\ninterface TagSyncOptions {\n pg: PGliteInterface | Transaction;\n metadataSchema: string;\n shapeTable: string;\n messages: ChangeMessage<Row<unknown>>[];\n primaryKey: string[];\n}\n\n/**\n * Maintain the tag-set for a shape from its drained change batch (ADR-0023). For a subquery shape every\n * change carries `headers.tags` (the row's current full reason-set), so insert/update **replace** the\n * row's tags; a delete drops them. `removed_tags` (without `tags`) deletes just those. A non-subquery\n * shape carries no `tags`, so this is a no-op for it. Runs before the data apply and the move-out\n * eviction in the same commit, so an add-then-remove within one batch resolves correctly.\n */\nexport async function applyShapeTagSync({\n pg,\n metadataSchema,\n shapeTable,\n messages,\n primaryKey,\n}: TagSyncOptions): Promise<void> {\n const { shapeRowTags } = getMetadataTables(metadataSchema);\n const db = drizzleOverPg(pg);\n\n for (const message of messages) {\n const data = message.value;\n const pkJson = serializeRowPk(data, primaryKey);\n\n if (message.headers.operation === \"delete\") {\n await db\n .delete(shapeRowTags)\n .where(and(eq(shapeRowTags.shape_table, shapeTable), eq(shapeRowTags.pk_json, pkJson)));\n continue;\n }\n\n const tags = message.headers.tags;\n if (tags !== undefined) {\n // `tags` is the authoritative current reason-set → replace.\n await db\n .delete(shapeRowTags)\n .where(and(eq(shapeRowTags.shape_table, shapeTable), eq(shapeRowTags.pk_json, pkJson)));\n if (tags.length > 0) {\n await db\n .insert(shapeRowTags)\n .values(tags.map((tag) => ({ shape_table: shapeTable, pk_json: pkJson, tag })))\n .onConflictDoNothing();\n }\n continue;\n }\n\n const removedTags = message.headers.removed_tags;\n if (removedTags && removedTags.length > 0) {\n await db\n .delete(shapeRowTags)\n .where(\n and(\n eq(shapeRowTags.shape_table, shapeTable),\n eq(shapeRowTags.pk_json, pkJson),\n inArray(shapeRowTags.tag, removedTags),\n ),\n );\n }\n }\n}\n\n/**\n * Record (union) a **move-in** row's tags without clearing the tags the row already carries (ADR-0024).\n * A move-in ADDS a reason a row is in the shape, so — unlike a regular change, whose `tags` is the\n * authoritative full reason-set and therefore REPLACES (see {@link applyShapeTagSync}) — a move-in must\n * not drop tags from an independent grant. Inserting with `ON CONFLICT DO NOTHING` is correct whether\n * Electric sends the row's full reason-set or only the newly-added grant on a move-in, so move-out\n * eviction afterwards stays correct under multi-grant without depending on the move-in's tag cardinality.\n * A row with no `tags` (a non-subquery shape) is a no-op.\n */\nexport async function addShapeRowTags({\n pg,\n metadataSchema,\n shapeTable,\n messages,\n primaryKey,\n}: TagSyncOptions): Promise<void> {\n const { shapeRowTags } = getMetadataTables(metadataSchema);\n const db = drizzleOverPg(pg);\n\n for (const message of messages) {\n const tags = message.headers.tags;\n if (!tags || tags.length === 0) continue;\n\n const data = message.value;\n const pkJson = serializeRowPk(data, primaryKey);\n await db\n .insert(shapeRowTags)\n .values(tags.map((tag) => ({ shape_table: shapeTable, pk_json: pkJson, tag })))\n .onConflictDoNothing();\n }\n}\n\ninterface MoveOutOptions {\n pg: PGliteInterface | Transaction;\n metadataSchema: string;\n shapeTable: string;\n /** The resolved apply target for the synced table the evicted rows are deleted from (ADR-0029 D1). */\n target: ApplyTarget;\n /** One entry per buffered `move-out` event, each its own pattern set. */\n patternSets: MovePattern[][];\n debug: boolean;\n}\n\n/**\n * Apply buffered `move-out` events for a shape (ADR-0023): withdraw the matched tag from every row that\n * carries it, then evict the synced rows left with **no** remaining tag — so a row held by two grants\n * survives losing one. Eviction goes through the tested bulk-delete path, so it fires the reconcile\n * trigger and the read-model/overlay stays consistent. Returns the number of rows evicted.\n */\nexport async function applyShapeMoveOut({\n pg,\n metadataSchema,\n shapeTable,\n target,\n patternSets,\n debug,\n}: MoveOutOptions): Promise<number> {\n const { shapeRowTags } = getMetadataTables(metadataSchema);\n const db = drizzleOverPg(pg);\n const evictedPkJsons = new Set<string>();\n\n for (const patterns of patternSets) {\n if (patterns.length === 0) continue;\n\n // Candidate tags: those containing every pattern value as a substring — a cheap superset of a real\n // positional match, confirmed in JS so composite/positional tags are handled correctly. Each\n // `like(tag, \"%value%\")` reproduces the former `tag LIKE '%' || $n || '%'` exactly: a param bound to\n // the concatenated pattern string, so any LIKE metacharacters in the value keep the same semantics.\n const candidateRows = await db\n .select({ pk_json: shapeRowTags.pk_json, tag: shapeRowTags.tag })\n .from(shapeRowTags)\n .where(\n and(\n eq(shapeRowTags.shape_table, shapeTable),\n ...patterns.map((pattern) => like(shapeRowTags.tag, `%${pattern.value}%`)),\n ),\n );\n const matched = candidateRows.filter((row) => tagMatchesPatterns(row.tag, patterns));\n if (matched.length === 0) continue;\n\n // Withdraw the moved-out tag from each matching row (one set-based delete of the (pk, tag) pairs).\n // Tier ② (ADR-0028): a set-based delete joined against a JSON recordset has no tier-① builder form —\n // the shape-tag table object is interpolated and the pair list is a bound `::json` param; the\n // alias-qualified `t.*` / `x.*` identifiers are raw only because the `USING`/recordset-join grammar\n // requires them.\n const pairs = matched.map((row) => ({ pk_json: row.pk_json, tag: row.tag }));\n await db.execute(\n sql`DELETE FROM ${shapeRowTags} AS t USING json_to_recordset(${JSON.stringify(pairs)}::json) AS x(pk_json text, tag text)\n WHERE t.shape_table = ${shapeTable} AND t.pk_json = x.pk_json AND t.tag = x.tag`,\n );\n\n // A row is evicted only if it has no tag left.\n const affected = [...new Set(matched.map((row) => row.pk_json))];\n // Tier ② (ADR-0028): bind the affected pk_json list as ONE array param via `= ANY(${param}::text[])`\n // — drizzle has no ANY(array-param) builder, and `sql.param` binds the whole array as a single\n // placeholder (removing the per-element bound-param ceiling `inArray` emits: one placeholder per PK,\n // a ~65k-param wire cap on a huge move-out). The explicit `::text[]` cast pins the param type for the\n // driver's extended-protocol type resolution. The `eq(shape_table)` conjunct and `selectDistinct`\n // shape are preserved.\n const remaining = await db\n .selectDistinct({ pk_json: shapeRowTags.pk_json })\n .from(shapeRowTags)\n .where(\n and(\n eq(shapeRowTags.shape_table, shapeTable),\n sql`${shapeRowTags.pk_json} = ANY(${sql.param(affected)}::text[])`,\n ),\n );\n const stillTagged = new Set(remaining.map((row) => row.pk_json));\n for (const pkJson of affected) {\n if (!stillTagged.has(pkJson)) evictedPkJsons.add(pkJson);\n }\n }\n\n if (evictedPkJsons.size === 0) return 0;\n\n // Evict via the bulk-delete path so the reconcile trigger fires and the read model converges.\n const messages = [...evictedPkJsons].map((pkJson) => ({\n key: pkJson,\n value: JSON.parse(pkJson) as Row<unknown>,\n headers: { operation: \"delete\" as const },\n }));\n await applyBulkDeletesToTable({\n pg,\n target,\n messages,\n debug,\n });\n\n return evictedPkJsons.size;\n}\n\n/** Drop a shape's entire tag-set — for a `must-refetch`/read-cache rebuild, before the re-snapshot (ADR-0023 Slice 2). */\nexport async function clearShapeTags({\n pg,\n metadataSchema,\n shapeTable,\n}: {\n pg: PGliteInterface | Transaction;\n metadataSchema: string;\n shapeTable: string;\n}): Promise<void> {\n const { shapeRowTags } = getMetadataTables(metadataSchema);\n await drizzleOverPg(pg).delete(shapeRowTags).where(eq(shapeRowTags.shape_table, shapeTable));\n}\n",
127
- "import { getTableConfig, getViewConfig, type AnyPgTable } from \"drizzle-orm/pg-core\";\n\nimport {\n buildOverlayResolutionBarrier,\n buildSyncStateView,\n getLocalSyncPrimaryKeyColumns,\n getSyncRegistrySchema,\n getProjectedColumns,\n maybeQuoteIdentifier,\n quoteIdentifier,\n quoteSqlLiteral as quoteSqlStringLiteral,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport { buildClearShapeTagsSql, shapeTableId } from \"./sync/tags\";\n\n/** Internal fully-qualified projection used within schema generation. */\ninterface ResolvedProjection {\n syncedTable: string;\n overlayTable?: string;\n journalTable?: string;\n readModel: string;\n /** The per-table `<table>_sync_state` convergence view (writable tables only — ADR-0011). */\n syncState: string;\n /**\n * The reconcile trigger's function — schema-qualified, because a function is a schema object.\n * Suffix-then-qualify (never `${qualifiedTable}_reconcile_on_sync`, which double-quotes a\n * non-public schema's qualified name into invalid SQL).\n */\n reconcileFunction: string;\n /**\n * The reconcile trigger itself — an UNqualified identifier. A trigger is not a schema object; it\n * is bound to its table via `ON <qualified table>`, so its name must not be schema-qualified.\n */\n reconcileTrigger: string;\n}\n\n/**\n * Local key/value metadata table. Holds the registry fingerprint the local store was\n * provisioned under (ADR-0006), so a registry change is detected on boot and the read\n * cache is rebuilt — rather than relying on a hand-bumped `idb://…-vN` suffix.\n */\nexport const LOCAL_META_TABLE = \"pgxsinkit_local_meta\";\nexport const REGISTRY_FINGERPRINT_KEY = \"registry_fingerprint\";\n\ntype TableColumn = ReturnType<typeof getProjectedColumns<AnyPgTable>>[number][\"column\"];\n\nexport function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n const statements: string[] = [];\n const localSchema = getSyncRegistrySchema(registry);\n\n if (localSchema !== \"public\") {\n statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(localSchema)};`);\n }\n\n statements.push(\n `CREATE TABLE IF NOT EXISTS ${qualifyIdentifier(localSchema, LOCAL_META_TABLE)} (\\n ${[\n \"key TEXT PRIMARY KEY\",\n \"value TEXT NOT NULL\",\n ].join(\",\\n \")}\\n);`,\n );\n\n const enumDefinitions = collectEnumDefinitions(registry, localSchema);\n\n for (const enumDefinition of enumDefinitions) {\n statements.push(buildCreateEnumTypeSql(enumDefinition));\n }\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n // ADR-0021 §3: an `ephemeral` table's whole cluster is emitted as `TEMP` — bare (unqualified) object\n // names that resolve via `pg_temp` / search_path, so read- and write-ephemerality fall out together\n // (no durable trace). Object NAMES go bare+TEMP; column *types* (enums) stay in the persistent schema.\n // For a persistent table `temp` is \"\" and `objectSchema` is the registry schema → byte-identical output.\n const ephemeral = entry.retention === \"ephemeral\";\n const objectSchema = ephemeral ? \"public\" : localSchema;\n const temp = ephemeral ? \"TEMP \" : \"\";\n\n const projection = getClientProjection(entry, tableKey, objectSchema);\n const columns = getProjectedColumns(entry).map(({ column }) => column);\n const syncedTablePrimaryKeyColumns = getLocalSyncPrimaryKeyColumns(entry);\n const baseColumnsSql = buildTableColumnSql(columns, syncedTablePrimaryKeyColumns, localSchema);\n\n statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.syncedTable} (\\n ${baseColumnsSql}\\n);`);\n\n if (entry.mode === \"readonly\") {\n continue;\n }\n\n if (!projection.overlayTable || !projection.journalTable) {\n throw new Error(`overlay and journal tables are required for writable table ${tableKey}`);\n }\n\n const journalTableName = entry.clientProjection?.journalTable;\n\n if (!journalTableName) {\n throw new Error(`journal table is required for writable table ${tableKey}`);\n }\n\n const primaryKeyColumns = entry.primaryKey.columns.map((columnName) => {\n const column = columns.find((candidate) => candidate.name === columnName);\n\n if (!column) {\n throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);\n }\n\n return column;\n });\n const primaryKeyColumnNames = primaryKeyColumns.map((column) => column.name);\n const journalSequenceName = buildJournalSequenceName(journalTableName);\n const qualifiedJournalSequenceName = qualifyIdentifier(objectSchema, journalSequenceName);\n\n statements.push(\n `CREATE ${temp}TABLE IF NOT EXISTS ${projection.overlayTable} (\\n ${[\n ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumnNames, localSchema)),\n \"overlay_kind VARCHAR(24) NOT NULL\",\n \"local_updated_at_us BIGINT NOT NULL\",\n ...buildCompositePrimaryKeyClauses(primaryKeyColumnNames),\n ].join(\",\\n \")}\\n);`,\n );\n\n statements.push(\n `CREATE ${temp}SEQUENCE IF NOT EXISTS ${qualifiedJournalSequenceName} AS integer START WITH 1 INCREMENT BY 1;`,\n );\n\n statements.push(\n `CREATE ${temp}TABLE IF NOT EXISTS ${projection.journalTable} (\\n ${[\n \"mutation_id UUID PRIMARY KEY\",\n ...primaryKeyColumns.map((column) => `${column.name} ${mapColumnType(column, localSchema)} NOT NULL`),\n \"entity_key_json TEXT NOT NULL\",\n `mutation_seq INTEGER NOT NULL UNIQUE DEFAULT nextval(${quoteSqlStringLiteral(qualifiedJournalSequenceName)})::integer`,\n \"mutation_kind VARCHAR(24) NOT NULL\",\n \"status VARCHAR(24) NOT NULL\",\n // The registry fingerprint (ADR-0004) this mutation was authored under, so a\n // version-boundary crossing is known before sending (ADR-0006 decision 4).\n \"registry_version TEXT\",\n // ADR-0011 reserved hook: the Server version the entity was observed at when this mutation\n // was authored. The slot lives on the journal (per-mutation, like registry_version above);\n // the stale-write conflict policy (ADR-0015) decides its exact semantics and stamps it.\n \"base_server_version BIGINT\",\n // ADR-0022: the dynamic write-unit tag stamped by a `transaction({ mode })` block — the shared\n // unit id grouping co-committed mutations, and the unit's write-mode. NULL for the default path\n // (an untagged mutation), where the flusher derives mode + unit from the table's static group.\n \"write_unit TEXT\",\n \"write_mode VARCHAR(24)\",\n \"payload_json TEXT NOT NULL\",\n \"attempt_count INTEGER NOT NULL DEFAULT 0\",\n \"last_error TEXT\",\n \"last_http_status INTEGER\",\n \"conflict_reason TEXT\",\n \"server_updated_at_us BIGINT\",\n \"enqueued_at_us BIGINT NOT NULL\",\n \"next_retry_at_us BIGINT\",\n \"sent_at_us BIGINT\",\n \"acked_at_us BIGINT\",\n \"updated_at_us BIGINT NOT NULL\",\n ].join(\",\\n \")}\\n);`,\n );\n\n // Journal indexes render through the SAME core the pgTable-driven renderer uses\n // ({@link renderCreateIndexStatement}), so the two index-emitting paths cannot drift in statement\n // shape. These names/columns are registry-derived bare identifiers, passed verbatim (the pgTable\n // path is the one that quotes) — output stays byte-identical to the former hand-built statements.\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_idx`, [\n \"status\",\n \"enqueued_at_us\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_retry_idx`, [\n \"status\",\n \"next_retry_at_us\",\n \"enqueued_at_us\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_pk_seq_idx`, [\n ...entry.primaryKey.columns,\n \"mutation_seq\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_seq_idx`, [\n \"entity_key_json\",\n \"mutation_seq\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_status_seq_idx`, [\n \"entity_key_json\",\n \"status\",\n \"mutation_seq\",\n ]),\n );\n\n // Trigger: automatically clear overlay + journal entries when the sync\n // echo arrives. Fires on INSERT/UPDATE (new data from Electric) and DELETE\n // (row removed on server, synced back via Electric).\n const pkMatchSql = (alias: string) =>\n primaryKeyColumns\n .map((col) => `\"${alias}\".\"${col.name}\" = COALESCE(NEW.\"${col.name}\", OLD.\"${col.name}\")`)\n .join(\" AND \");\n const pkOverlayMatchSql = primaryKeyColumns\n .map((col) => `\"overlay\".\"${col.name}\" = COALESCE(NEW.\"${col.name}\", OLD.\"${col.name}\")`)\n .join(\" AND \");\n\n // ADR-0010: an acked create/update clears only once the synced echo's Server version reaches\n // the write's acked version — never on a bare key-match, which a stale or reordered echo could\n // satisfy and flip the read model to neither the optimistic nor the converged value. A delete\n // stays resolved by synced-row absence (NEW is NULL on the synced DELETE; the barrier reads\n // NULL there, so it never clears a create/update on a delete echo). One predicate, shared with\n // reconcileTable (mutation.ts), so the two sites cannot drift.\n const resolutionBarrier = buildOverlayResolutionBarrier(entry, { syncedAlias: \"NEW\" });\n\n // ADR-0021 §3: an ephemeral cluster's reconcile function lives in `pg_temp` alongside its temp table\n // (a permanent function cannot be a temp trigger's handler cleanly); a persistent one is unchanged.\n const reconcileFunctionRef = ephemeral ? `pg_temp.${projection.reconcileFunction}` : projection.reconcileFunction;\n\n statements.push(\n `CREATE OR REPLACE FUNCTION ${reconcileFunctionRef}() RETURNS TRIGGER AS $$\\n` +\n `BEGIN\\n` +\n ` -- ADR-0015: retire a terminal 'conflicted' row once a LATER write on the same entity has\\n` +\n ` -- been acked — that later write IS the resolution. The acked resolver is cleared by the\\n` +\n ` -- acked-delete below the moment its echo lands; if that echo wins the race against the\\n` +\n ` -- post-flush reconcileTable pass, the resolver is gone before reconcileTable's supersede-\\n` +\n ` -- retire can see it and the conflicted row orphans (its surfaced conflict_state never\\n` +\n ` -- clears). Doing the retire here too — in the trigger that has the echo context, BEFORE the\\n` +\n ` -- acked-clear — closes that race. Mirrors reconcileTable's retire (mutation.ts).\\n` +\n ` DELETE FROM ${projection.journalTable} AS \"conflicted\"\\n` +\n ` USING ${projection.journalTable} AS \"resolver\"\\n` +\n ` WHERE \"conflicted\".status = 'conflicted' AND (${pkMatchSql(\"conflicted\")})\\n` +\n ` AND \"resolver\".entity_key_json = \"conflicted\".entity_key_json\\n` +\n ` AND \"resolver\".mutation_seq > \"conflicted\".mutation_seq\\n` +\n ` AND \"resolver\".status = 'acked';\\n` +\n ` DELETE FROM ${projection.journalTable} AS \"journal\"\\n` +\n ` WHERE status = 'acked' AND (${pkMatchSql(\"journal\")})\\n` +\n ` AND (\\n` +\n ` (TG_OP <> 'DELETE' AND mutation_kind <> 'delete' AND ${resolutionBarrier})\\n` +\n ` OR (TG_OP = 'DELETE' AND mutation_kind = 'delete')\\n` +\n ` );\\n` +\n ` DELETE FROM ${projection.overlayTable} AS \"overlay\"\\n` +\n ` WHERE (${pkOverlayMatchSql})\\n` +\n ` AND NOT EXISTS (\\n` +\n ` SELECT 1 FROM ${projection.journalTable} AS j\\n` +\n ` WHERE (${pkMatchSql(\"j\")})\\n` +\n ` );\\n` +\n ` RETURN COALESCE(NEW, OLD);\\n` +\n `END;\\n` +\n `$$ LANGUAGE plpgsql;`,\n );\n\n statements.push(\n `CREATE OR REPLACE TRIGGER ${projection.reconcileTrigger}\\n` +\n `AFTER INSERT OR UPDATE OR DELETE ON ${projection.syncedTable}\\n` +\n `FOR EACH ROW EXECUTE FUNCTION ${reconcileFunctionRef}();`,\n );\n\n statements.push(\n `CREATE OR REPLACE ${temp}VIEW ${projection.readModel} AS\\n${buildReadModelViewSql(\n entry,\n projection,\n columns.map((column) => column.name),\n )};`,\n );\n\n // ADR-0011: the per-table convergence view — a derived projection over synced + overlay +\n // journal, distinct from the (lean) read model, whose acked-unobserved status derives from the\n // same barrier predicate the reconcile trigger above uses (decision 4, anti-drift).\n statements.push(\n `CREATE OR REPLACE ${temp}VIEW ${projection.syncState} AS\\n${buildSyncStateView(entry, {\n syncedTable: projection.syncedTable,\n overlayTable: projection.overlayTable,\n journalTable: projection.journalTable,\n })};`,\n );\n }\n\n return `${statements.join(\"\\n\\n\")}\\n`;\n}\n\nfunction buildReadModelViewSql(\n entry: SyncTableEntry<AnyPgTable>,\n projection: ResolvedProjection,\n columnNames: string[],\n) {\n if (!projection.overlayTable) {\n throw new Error(`overlay table is required for writable table ${projection.syncedTable}`);\n }\n\n const pkMatch = buildPrimaryKeyMatch(entry.primaryKey.columns);\n const syncedLocalUpdatedExpression = columnNames.includes(\"updated_at_us\") ? \"t.updated_at_us\" : \"CAST(0 AS BIGINT)\";\n\n return [\n \"SELECT\",\n ` ${columnNames.join(\",\\n \")},`,\n \" overlay_kind,\",\n \" local_updated_at_us\",\n `FROM ${projection.overlayTable}`,\n `WHERE overlay_kind <> 'pending_delete'`,\n \"UNION ALL\",\n \"SELECT\",\n ` ${columnNames.map((name) => `t.${name}`).join(\",\\n \")},`,\n ` 'synced' AS overlay_kind,`,\n ` ${syncedLocalUpdatedExpression} AS local_updated_at_us`,\n `FROM ${projection.syncedTable} AS t`,\n \"WHERE NOT EXISTS (\",\n \" SELECT 1\",\n ` FROM ${projection.overlayTable} AS o`,\n ` WHERE ${pkMatch}`,\n \")\",\n ].join(\"\\n\");\n}\n\nfunction buildTableColumnSql(columns: TableColumn[], primaryKeyColumns: string[], localSchema: string) {\n return [\n ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumns, localSchema)),\n ...buildCompositePrimaryKeyClauses(primaryKeyColumns),\n ].join(\",\\n \");\n}\n\n/**\n * Render `CREATE TABLE IF NOT EXISTS` (plus a `CREATE INDEX IF NOT EXISTS` per declared index) for a\n * Drizzle `pgTable` / `pgSchema.table`, through the SAME column/PK/type machinery\n * ({@link buildTableColumnSql} → {@link buildColumnDefinition} → {@link mapColumnType}) that\n * {@link generateLocalSchemaSql} uses for every other local relation. The table is schema-qualified\n * when it declares a schema and bare otherwise (per the table object). Column types come from each\n * column's `getSQLType()`, NOT NULL and single-column PRIMARY KEY inline, composite PKs as a trailing\n * clause. Enum column types are qualified into the table's own schema — the metadata pgTables carry\n * none, but the path is shared with the local-store generator so it must stay honest.\n *\n * ADR-0029 D3: the metadata-store DDL renders from its `metadata-tables.ts` pgTables through this,\n * making the pgTable the single source. The OUTPUT is tier-③-by-nature runtime DDL (schema/table\n * identifiers assembled at construction), but it is GENERATED from the model, never hand-maintained.\n */\nexport function renderCreateTableSql(table: AnyPgTable): string[] {\n const config = getTableConfig(table);\n const schemaName = config.schema ?? \"public\";\n const qualifiedTableName = qualifyIdentifier(schemaName, config.name);\n const primaryKeyColumns = collectPgTablePrimaryKeyColumns(config);\n const columnSql = buildTableColumnSql(config.columns as unknown as TableColumn[], primaryKeyColumns, schemaName);\n\n const statements = [`CREATE TABLE IF NOT EXISTS ${qualifiedTableName} (\\n ${columnSql}\\n);`];\n\n for (const index of config.indexes) {\n statements.push(renderCreateIndexSql(qualifiedTableName, index));\n }\n\n return statements;\n}\n\n/** The PK column names of a `pgTable` — column-level `.primaryKey()` first, then composite `primaryKey({…})`. */\nfunction collectPgTablePrimaryKeyColumns(config: ReturnType<typeof getTableConfig>): string[] {\n const columnLevel = config.columns.filter((column) => column.primary).map((column) => column.name);\n const composite = config.primaryKeys.flatMap((pk) => pk.columns.map((column) => column.name));\n return [...columnLevel, ...composite];\n}\n\nfunction renderCreateIndexSql(qualifiedTableName: string, index: ReturnType<typeof getTableConfig>[\"indexes\"][number]) {\n const { name, unique, columns, where, method, with: withParams } = index.config;\n if (!name) {\n throw new Error(\"renderCreateIndexSql: anonymous indexes are not supported (declare a name)\");\n }\n // This renderer emits only a plain ascending btree over bare columns. Any modifier it does not\n // render must fail loudly — silently dropping one would produce a local index that differs from the\n // pgTable declaration (the very DDL-vs-model divergence ADR-0029 D3 removes for the metadata store).\n if (where) {\n throw new Error(`renderCreateIndexSql: partial indexes (.where) are not supported (index ${name})`);\n }\n if (method && method.toLowerCase() !== \"btree\") {\n throw new Error(\n `renderCreateIndexSql: non-btree index methods (.using \"${method}\") are not supported (index ${name})`,\n );\n }\n if (withParams && Object.keys(withParams).length > 0) {\n throw new Error(`renderCreateIndexSql: index storage parameters (.with) are not supported (index ${name})`);\n }\n const columnExpressions = columns.map((column) => {\n const columnName = (column as { name?: unknown }).name;\n if (typeof columnName !== \"string\") {\n throw new Error(`renderCreateIndexSql: expression index columns are not supported (index ${name})`);\n }\n const indexConfig = (column as { indexConfig?: { order?: string; nulls?: string; opClass?: string } }).indexConfig;\n if (indexConfig?.order === \"desc\") {\n throw new Error(`renderCreateIndexSql: descending index columns (.desc()) are not supported (index ${name})`);\n }\n // Drizzle fills `nulls` with the ascending-btree default (\"last\") on every column; only an\n // explicit NULLS FIRST diverges from what we render (a plain ascending btree is NULLS LAST).\n if (indexConfig?.nulls === \"first\") {\n throw new Error(`renderCreateIndexSql: NULLS FIRST ordering (.nullsFirst()) is not supported (index ${name})`);\n }\n if (indexConfig?.opClass) {\n throw new Error(`renderCreateIndexSql: index operator classes (.op()) are not supported (index ${name})`);\n }\n return maybeQuoteIdentifier(columnName);\n });\n\n return renderCreateIndexStatement(qualifiedTableName, maybeQuoteIdentifier(name), columnExpressions, { unique });\n}\n\n/**\n * The shared `CREATE INDEX` core: assemble one\n * `CREATE [UNIQUE] INDEX IF NOT EXISTS <name> ON <table> (<cols>)` over a qualified table, an\n * already-rendered index name, and already-rendered plain ascending column expressions. BOTH the\n * pgTable-driven renderer ({@link renderCreateIndexSql}) and the journal-index emitter in\n * {@link generateLocalSchemaSql} go through here, so the two index-emitting paths cannot drift in\n * statement shape. Identifier quoting is the caller's responsibility — the pgTable path quotes via\n * `maybeQuoteIdentifier`; the journal path passes its registry-derived bare names/columns verbatim —\n * this core only fixes the surrounding statement text.\n */\nfunction renderCreateIndexStatement(\n qualifiedTableName: string,\n indexName: string,\n columnExpressions: readonly string[],\n options: { unique?: boolean } = {},\n): string {\n const uniqueSql = options.unique ? \"UNIQUE \" : \"\";\n return `CREATE ${uniqueSql}INDEX IF NOT EXISTS ${indexName} ON ${qualifiedTableName} (${columnExpressions.join(\", \")});`;\n}\n\nfunction buildColumnDefinition(column: TableColumn, primaryKeyColumns: string[], localSchema: string) {\n const typeSql = mapColumnType(column, localSchema);\n const notNullSql = column.notNull ? \" NOT NULL\" : \"\";\n const primaryKeySql = primaryKeyColumns.length === 1 && primaryKeyColumns.includes(column.name) ? \" PRIMARY KEY\" : \"\";\n return `${column.name} ${typeSql}${notNullSql}${primaryKeySql}`;\n}\n\nfunction buildCompositePrimaryKeyClauses(primaryKeyColumns: string[]) {\n if (primaryKeyColumns.length <= 1) {\n return [];\n }\n\n return [`PRIMARY KEY (${primaryKeyColumns.join(\", \")})`];\n}\n\nfunction mapColumnType(column: TableColumn, localSchema: string) {\n const baseTypeSql = readBaseColumnTypeSql(column, localSchema);\n const dimensions = readArrayDimensions(column);\n\n if (dimensions > 0) {\n return `${baseTypeSql}${\"[]\".repeat(dimensions)}`;\n }\n\n return baseTypeSql;\n}\n\nfunction readBaseColumnTypeSql(column: TableColumn, localSchema: string) {\n const enumDefinition = readEnumColumnDefinition(column, localSchema);\n\n if (enumDefinition) {\n return qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName);\n }\n\n const sqlType = (column as { getSQLType(): string }).getSQLType();\n\n if (!sqlType) {\n throw new Error(`Unsupported column type for local schema generation: ${column.columnType}`);\n }\n\n return sqlType;\n}\n\ntype EnumDefinition = {\n schemaName: string;\n enumName: string;\n enumValues: string[];\n};\n\nfunction collectEnumDefinitions(registry: SyncTableRegistry, localSchema: string) {\n const enumDefinitionsByName = new Map<string, EnumDefinition>();\n\n for (const entry of Object.values(registry)) {\n const columns = getProjectedColumns(entry).map(({ column }) => column);\n\n for (const column of columns) {\n const enumDefinition = readEnumColumnDefinition(column, localSchema);\n\n if (!enumDefinition) {\n continue;\n }\n\n const existingDefinition = enumDefinitionsByName.get(enumDefinition.enumName);\n\n if (!existingDefinition) {\n enumDefinitionsByName.set(enumDefinition.enumName, enumDefinition);\n continue;\n }\n\n if (!areEnumValuesEqual(existingDefinition.enumValues, enumDefinition.enumValues)) {\n throw new Error(\n `Enum ${enumDefinition.enumName} has conflicting values in sync registry: ${existingDefinition.enumValues.join(\", \")} vs ${enumDefinition.enumValues.join(\", \")}`,\n );\n }\n }\n }\n\n return [...enumDefinitionsByName.values()].sort((left, right) => left.enumName.localeCompare(right.enumName));\n}\n\nfunction buildCreateEnumTypeSql(enumDefinition: EnumDefinition) {\n const typeIdentifier = qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName);\n const enumValuesSql = enumDefinition.enumValues.map((value) => quoteSqlStringLiteral(value)).join(\", \");\n\n return [\n \"DO $$\",\n \"BEGIN\",\n \" IF NOT EXISTS (\",\n \" SELECT 1\",\n \" FROM pg_type AS t\",\n \" INNER JOIN pg_namespace AS n ON n.oid = t.typnamespace\",\n ` WHERE t.typname = ${quoteSqlStringLiteral(enumDefinition.enumName)}`,\n ` AND n.nspname = ${quoteSqlStringLiteral(enumDefinition.schemaName)}`,\n \" ) THEN\",\n ` CREATE TYPE ${typeIdentifier} AS ENUM (${enumValuesSql});`,\n \" END IF;\",\n \"END\",\n \"$$;\",\n ].join(\"\\n\");\n}\n\nfunction areEnumValuesEqual(left: string[], right: string[]) {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let index = 0; index < left.length; index += 1) {\n if (left[index] !== right[index]) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction readEnumColumnDefinition(column: TableColumn, localSchema: string): EnumDefinition | undefined {\n const candidate = column as TableColumn & {\n enum?: {\n enumName?: unknown;\n enumValues?: unknown;\n };\n };\n\n if (!candidate.enum || typeof candidate.enum.enumName !== \"string\" || !Array.isArray(candidate.enum.enumValues)) {\n return undefined;\n }\n\n const enumValues = candidate.enum.enumValues.filter((value): value is string => typeof value === \"string\");\n\n if (enumValues.length !== candidate.enum.enumValues.length) {\n throw new Error(\n `Enum ${candidate.enum.enumName} includes non-string values and cannot be emitted in local schema SQL`,\n );\n }\n\n return {\n schemaName: localSchema,\n enumName: candidate.enum.enumName,\n enumValues,\n };\n}\n\nfunction readArrayDimensions(column: TableColumn) {\n const arrayColumn = column as TableColumn & { dimensions?: number };\n return arrayColumn.dimensions ?? 0;\n}\n\nfunction buildPrimaryKeyMatch(primaryKeyColumns: string[]) {\n return primaryKeyColumns.map((column) => `o.${column} = t.${column}`).join(\" AND \");\n}\n\nfunction getClientProjection(entry: SyncTableEntry, tableKey: string, localSchema: string): ResolvedProjection {\n const projection = baseProjection(entry, tableKey);\n const syncedTableName = projection.syncedTable ?? tableKey;\n const readModelName = entry.view != null ? getViewConfig(entry.view).name : syncedTableName;\n\n return {\n syncedTable: qualifyIdentifier(localSchema, syncedTableName),\n ...(projection.overlayTable ? { overlayTable: qualifyIdentifier(localSchema, projection.overlayTable) } : {}),\n ...(projection.journalTable ? { journalTable: qualifyIdentifier(localSchema, projection.journalTable) } : {}),\n readModel: qualifyIdentifier(localSchema, readModelName),\n syncState: qualifyIdentifier(localSchema, `${syncedTableName}_sync_state`),\n reconcileFunction: qualifyIdentifier(localSchema, `${syncedTableName}_reconcile_on_sync`),\n reconcileTrigger: maybeQuoteIdentifier(`${syncedTableName}_reconcile_on_sync`),\n };\n}\n\nfunction baseProjection(entry: SyncTableEntry, tableKey: string) {\n if (!entry.clientProjection) {\n throw new Error(`clientProjection is required for local client table ${tableKey}`);\n }\n\n return entry.clientProjection;\n}\n\nfunction qualifyIdentifier(schemaName: string, objectName: string) {\n if (schemaName === \"public\") {\n // Quote only when required so existing generated SQL stays stable, but a table/view named\n // after a reserved word (e.g. `group`) is a valid Postgres identifier and MUST be quoted or\n // the generated DDL and read queries fail to parse. The row-applier (src/sync) always quotes.\n return maybeQuoteIdentifier(objectName);\n }\n\n return `${quoteIdentifier(schemaName)}.${quoteIdentifier(objectName)}`;\n}\n\nfunction buildJournalSequenceName(journalTable: string) {\n return `${journalTable}_mutation_seq`;\n}\n\n/**\n * Drop the reconstructible **read cache** — the synced tables and their read-model views\n * and reconcile triggers/functions — while preserving the authority tables (overlay,\n * journal, the local-meta table). Re-running {@link generateLocalSchemaSql} then rebuilds\n * the synced tables at the current shape, and a re-sync refills them (ADR-0006). This is\n * the named drop primitive a returning-online upgrade uses after a clean drain.\n */\nexport function buildDropReadCacheSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const statements: string[] = [];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n const projection = getClientProjection(entry, tableKey, localSchema);\n\n if (entry.mode !== \"readonly\") {\n statements.push(`DROP VIEW IF EXISTS ${projection.syncState};`);\n statements.push(`DROP VIEW IF EXISTS ${projection.readModel};`);\n statements.push(`DROP TRIGGER IF EXISTS ${projection.reconcileTrigger} ON ${projection.syncedTable};`);\n statements.push(`DROP FUNCTION IF EXISTS ${projection.reconcileFunction}();`);\n }\n\n statements.push(`DROP TABLE IF EXISTS ${projection.syncedTable} CASCADE;`);\n }\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n\n/**\n * Wipe the **entire** local store provisioned from the registry — the read cache plus the\n * authority tables (overlay, journal, sequences), the enum types, and the local-meta row.\n * This is the full teardown reused by `destroy()` (ADR-0005 decision 5) and by the\n * drain-then-drop upgrade once a clean drain has confirmed nothing is owed (ADR-0006).\n */\nexport function buildWipeLocalStoreSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const statements: string[] = [buildDropReadCacheSql(registry).trimEnd()];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n if (entry.mode === \"readonly\") {\n continue;\n }\n\n const projection = getClientProjection(entry, tableKey, localSchema);\n\n if (projection.overlayTable) {\n statements.push(`DROP TABLE IF EXISTS ${projection.overlayTable} CASCADE;`);\n }\n\n if (projection.journalTable && entry.clientProjection?.journalTable) {\n statements.push(`DROP TABLE IF EXISTS ${projection.journalTable} CASCADE;`);\n statements.push(\n `DROP SEQUENCE IF EXISTS ${qualifyIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable))};`,\n );\n }\n }\n\n for (const enumDefinition of collectEnumDefinitions(registry, localSchema)) {\n statements.push(`DROP TYPE IF EXISTS ${qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName)};`);\n }\n\n statements.push(`DROP TABLE IF EXISTS ${qualifyIdentifier(localSchema, LOCAL_META_TABLE)} CASCADE;`);\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n\n/**\n * Clean-truncate a single table's local read cache so a desynced `lazy` relation (ADR-0021 §2) returns\n * to an empty, dormant state: the synced table and — for a writable table — its optimistic overlay and\n * the journal, plus a sequence restart. It does NOT drop the cluster (the table/views/trigger persist),\n * so a later re-reference re-streams into it without a schema rebuild. Ephemeral-aware: bare/`pg_temp`\n * names for an ephemeral cluster, schema-qualified for a persistent one — mirroring\n * {@link generateLocalSchemaSql}. The caller (`desync`) first stops the group's stream (so nothing\n * re-populates mid-truncate) and refuses when the journal owes unsettled writes (so this never drops\n * un-acked local intent).\n */\nexport function buildDesyncTableSql<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n tableKey: string,\n): string {\n const entry = registry[tableKey];\n\n if (!entry) {\n throw new Error(`buildDesyncTableSql: unknown table ${tableKey}`);\n }\n\n const localSchema = getSyncRegistrySchema(registry);\n const ephemeral = entry.retention === \"ephemeral\";\n const objectSchema = ephemeral ? \"public\" : localSchema;\n const projection = getClientProjection(entry, tableKey, objectSchema);\n const statements: string[] = [`TRUNCATE TABLE ${projection.syncedTable};`];\n\n if (entry.mode !== \"readonly\") {\n if (projection.overlayTable) {\n statements.push(`TRUNCATE TABLE ${projection.overlayTable};`);\n }\n\n if (projection.journalTable && entry.clientProjection?.journalTable) {\n statements.push(`TRUNCATE TABLE ${projection.journalTable};`);\n statements.push(\n `ALTER SEQUENCE ${qualifyIdentifier(objectSchema, buildJournalSequenceName(entry.clientProjection.journalTable))} RESTART WITH 1;`,\n );\n }\n }\n\n // ADR-0023 Slice 2: a desync reverts the relation to dormant and deletes its subscription, so the next\n // activation re-streams from scratch — drop this shape's tag-set too, or it would orphan tags for rows\n // that never come back. The key matches what the engine writes (`shapeTableId(shape.schema, table)`):\n // for ephemeral the engine passes no schema (→ `public`), exactly this `objectSchema`.\n const syncedTableNameRaw = baseProjection(entry, tableKey).syncedTable ?? tableKey;\n statements.push(buildClearShapeTagsSql(shapeTableId(objectSchema, syncedTableNameRaw)));\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n",
134
+ "import { getTableConfig, getViewConfig, type AnyPgTable } from \"drizzle-orm/pg-core\";\n\nimport {\n buildOverlayResolutionBarrier,\n buildSyncStateView,\n getLocalSyncPrimaryKeyColumns,\n getSyncRegistrySchema,\n getProjectedColumns,\n maybeQuoteIdentifier,\n quoteIdentifier,\n quoteSqlLiteral as quoteSqlStringLiteral,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport { buildClearShapeTagsSql, shapeTableId } from \"./sync/tags\";\n\n/** Internal fully-qualified projection used within schema generation. */\ninterface ResolvedProjection {\n syncedTable: string;\n overlayTable?: string;\n journalTable?: string;\n readModel: string;\n /** The per-table `<table>_sync_state` convergence view (writable tables only — ADR-0011). */\n syncState: string;\n /**\n * The reconcile trigger's function — schema-qualified, because a function is a schema object.\n * Suffix-then-qualify (never `${qualifiedTable}_reconcile_on_sync`, which double-quotes a\n * non-public schema's qualified name into invalid SQL).\n */\n reconcileFunction: string;\n /**\n * The reconcile trigger itself — an UNqualified identifier. A trigger is not a schema object; it\n * is bound to its table via `ON <qualified table>`, so its name must not be schema-qualified.\n */\n reconcileTrigger: string;\n}\n\n/**\n * Local key/value metadata table. Holds the registry fingerprint the local store was\n * provisioned under (ADR-0006), so a registry change is detected on boot and the read\n * cache is rebuilt — rather than relying on a hand-bumped `idb://…-vN` suffix.\n */\nexport const LOCAL_META_TABLE = \"pgxsinkit_local_meta\";\nexport const REGISTRY_FINGERPRINT_KEY = \"registry_fingerprint\";\n\ntype TableColumn = ReturnType<typeof getProjectedColumns<AnyPgTable>>[number][\"column\"];\n\nexport function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n const statements: string[] = [];\n const localSchema = getSyncRegistrySchema(registry);\n\n if (localSchema !== \"public\") {\n statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(localSchema)};`);\n }\n\n statements.push(\n `CREATE TABLE IF NOT EXISTS ${qualifyIdentifier(localSchema, LOCAL_META_TABLE)} (\\n ${[\n \"key TEXT PRIMARY KEY\",\n \"value TEXT NOT NULL\",\n ].join(\",\\n \")}\\n);`,\n );\n\n const enumDefinitions = collectEnumDefinitions(registry, localSchema);\n\n for (const enumDefinition of enumDefinitions) {\n statements.push(buildCreateEnumTypeSql(enumDefinition));\n }\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n // ADR-0021 §3: an `ephemeral` table's whole cluster is emitted as `TEMP` — bare (unqualified) object\n // names that resolve via `pg_temp` / search_path, so read- and write-ephemerality fall out together\n // (no durable trace). Object NAMES go bare+TEMP; column *types* (enums) stay in the persistent schema.\n // For a persistent table `temp` is \"\" and `objectSchema` is the registry schema → byte-identical output.\n const ephemeral = entry.retention === \"ephemeral\";\n const objectSchema = ephemeral ? \"public\" : localSchema;\n const temp = ephemeral ? \"TEMP \" : \"\";\n\n const projection = getClientProjection(entry, tableKey, objectSchema);\n const columns = getProjectedColumns(entry).map(({ column }) => column);\n const syncedTablePrimaryKeyColumns = getLocalSyncPrimaryKeyColumns(entry);\n const baseColumnsSql = buildTableColumnSql(columns, syncedTablePrimaryKeyColumns, localSchema);\n\n statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.syncedTable} (\\n ${baseColumnsSql}\\n);`);\n\n if (entry.mode === \"readonly\") {\n continue;\n }\n\n if (!projection.overlayTable || !projection.journalTable) {\n throw new Error(`overlay and journal tables are required for writable table ${tableKey}`);\n }\n\n const journalTableName = entry.clientProjection?.journalTable;\n\n if (!journalTableName) {\n throw new Error(`journal table is required for writable table ${tableKey}`);\n }\n\n const primaryKeyColumns = entry.primaryKey.columns.map((columnName) => {\n const column = columns.find((candidate) => candidate.name === columnName);\n\n if (!column) {\n throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);\n }\n\n return column;\n });\n const primaryKeyColumnNames = primaryKeyColumns.map((column) => column.name);\n const journalSequenceName = buildJournalSequenceName(journalTableName);\n const qualifiedJournalSequenceName = qualifyIdentifier(objectSchema, journalSequenceName);\n\n statements.push(\n `CREATE ${temp}TABLE IF NOT EXISTS ${projection.overlayTable} (\\n ${[\n ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumnNames, localSchema)),\n \"overlay_kind VARCHAR(24) NOT NULL\",\n \"local_updated_at_us BIGINT NOT NULL\",\n ...buildCompositePrimaryKeyClauses(primaryKeyColumnNames),\n ].join(\",\\n \")}\\n);`,\n );\n\n statements.push(\n `CREATE ${temp}SEQUENCE IF NOT EXISTS ${qualifiedJournalSequenceName} AS integer START WITH 1 INCREMENT BY 1;`,\n );\n\n statements.push(\n `CREATE ${temp}TABLE IF NOT EXISTS ${projection.journalTable} (\\n ${[\n \"mutation_id UUID PRIMARY KEY\",\n ...primaryKeyColumns.map((column) => `${column.name} ${mapColumnType(column, localSchema)} NOT NULL`),\n \"entity_key_json TEXT NOT NULL\",\n `mutation_seq INTEGER NOT NULL UNIQUE DEFAULT nextval(${quoteSqlStringLiteral(qualifiedJournalSequenceName)})::integer`,\n \"mutation_kind VARCHAR(24) NOT NULL\",\n \"status VARCHAR(24) NOT NULL\",\n // The registry fingerprint (ADR-0004) this mutation was authored under, so a\n // version-boundary crossing is known before sending (ADR-0006 decision 4).\n \"registry_version TEXT\",\n // ADR-0011 reserved hook: the Server version the entity was observed at when this mutation\n // was authored. The slot lives on the journal (per-mutation, like registry_version above);\n // the stale-write conflict policy (ADR-0015) decides its exact semantics and stamps it.\n \"base_server_version BIGINT\",\n // ADR-0022: the dynamic write-unit tag stamped by a `transaction({ mode })` block — the shared\n // unit id grouping co-committed mutations, and the unit's write-mode. NULL for the default path\n // (an untagged mutation), where the flusher derives mode + unit from the table's static group.\n \"write_unit TEXT\",\n \"write_mode VARCHAR(24)\",\n \"payload_json TEXT NOT NULL\",\n \"attempt_count INTEGER NOT NULL DEFAULT 0\",\n \"last_error TEXT\",\n \"last_http_status INTEGER\",\n \"conflict_reason TEXT\",\n \"server_updated_at_us BIGINT\",\n \"enqueued_at_us BIGINT NOT NULL\",\n \"next_retry_at_us BIGINT\",\n \"sent_at_us BIGINT\",\n \"acked_at_us BIGINT\",\n \"updated_at_us BIGINT NOT NULL\",\n ].join(\",\\n \")}\\n);`,\n );\n\n // Journal indexes render through the SAME core the pgTable-driven renderer uses\n // ({@link renderCreateIndexStatement}), so the two index-emitting paths cannot drift in statement\n // shape. These names/columns are registry-derived bare identifiers, passed verbatim (the pgTable\n // path is the one that quotes) — output stays byte-identical to the former hand-built statements.\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_idx`, [\n \"status\",\n \"enqueued_at_us\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_retry_idx`, [\n \"status\",\n \"next_retry_at_us\",\n \"enqueued_at_us\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_pk_seq_idx`, [\n ...entry.primaryKey.columns,\n \"mutation_seq\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_seq_idx`, [\n \"entity_key_json\",\n \"mutation_seq\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_status_seq_idx`, [\n \"entity_key_json\",\n \"status\",\n \"mutation_seq\",\n ]),\n );\n\n // Trigger: automatically clear overlay + journal entries when the sync\n // echo arrives. Fires on INSERT/UPDATE (new data from Electric) and DELETE\n // (row removed on server, synced back via Electric).\n const pkMatchSql = (alias: string) =>\n primaryKeyColumns\n .map((col) => `\"${alias}\".\"${col.name}\" = COALESCE(NEW.\"${col.name}\", OLD.\"${col.name}\")`)\n .join(\" AND \");\n const pkOverlayMatchSql = primaryKeyColumns\n .map((col) => `\"overlay\".\"${col.name}\" = COALESCE(NEW.\"${col.name}\", OLD.\"${col.name}\")`)\n .join(\" AND \");\n\n // ADR-0010: an acked create/update clears only once the synced echo's Server version reaches\n // the write's acked version — never on a bare key-match, which a stale or reordered echo could\n // satisfy and flip the read model to neither the optimistic nor the converged value. A delete\n // stays resolved by synced-row absence (NEW is NULL on the synced DELETE; the barrier reads\n // NULL there, so it never clears a create/update on a delete echo). One predicate, shared with\n // reconcileTable (mutation.ts), so the two sites cannot drift.\n const resolutionBarrier = buildOverlayResolutionBarrier(entry, { syncedAlias: \"NEW\" });\n\n // ADR-0021 §3: an ephemeral cluster's reconcile function lives in `pg_temp` alongside its temp table\n // (a permanent function cannot be a temp trigger's handler cleanly); a persistent one is unchanged.\n const reconcileFunctionRef = ephemeral ? `pg_temp.${projection.reconcileFunction}` : projection.reconcileFunction;\n\n statements.push(\n `CREATE OR REPLACE FUNCTION ${reconcileFunctionRef}() RETURNS TRIGGER AS $$\\n` +\n `BEGIN\\n` +\n ` -- ADR-0015: retire a terminal 'conflicted' row once a LATER write on the same entity has\\n` +\n ` -- been acked — that later write IS the resolution. The acked resolver is cleared by the\\n` +\n ` -- acked-delete below the moment its echo lands; if that echo wins the race against the\\n` +\n ` -- post-flush reconcileTable pass, the resolver is gone before reconcileTable's supersede-\\n` +\n ` -- retire can see it and the conflicted row orphans (its surfaced conflict_state never\\n` +\n ` -- clears). Doing the retire here too — in the trigger that has the echo context, BEFORE the\\n` +\n ` -- acked-clear — closes that race. Mirrors reconcileTable's retire (mutation.ts).\\n` +\n ` DELETE FROM ${projection.journalTable} AS \"conflicted\"\\n` +\n ` USING ${projection.journalTable} AS \"resolver\"\\n` +\n ` WHERE \"conflicted\".status = 'conflicted' AND (${pkMatchSql(\"conflicted\")})\\n` +\n ` AND \"resolver\".entity_key_json = \"conflicted\".entity_key_json\\n` +\n ` AND \"resolver\".mutation_seq > \"conflicted\".mutation_seq\\n` +\n ` AND \"resolver\".status = 'acked';\\n` +\n ` DELETE FROM ${projection.journalTable} AS \"journal\"\\n` +\n ` WHERE status = 'acked' AND (${pkMatchSql(\"journal\")})\\n` +\n ` AND (\\n` +\n ` (TG_OP <> 'DELETE' AND mutation_kind <> 'delete' AND ${resolutionBarrier})\\n` +\n ` OR (TG_OP = 'DELETE' AND mutation_kind = 'delete')\\n` +\n ` );\\n` +\n ` DELETE FROM ${projection.overlayTable} AS \"overlay\"\\n` +\n ` WHERE (${pkOverlayMatchSql})\\n` +\n ` AND NOT EXISTS (\\n` +\n ` SELECT 1 FROM ${projection.journalTable} AS j\\n` +\n ` WHERE (${pkMatchSql(\"j\")})\\n` +\n ` );\\n` +\n ` RETURN COALESCE(NEW, OLD);\\n` +\n `END;\\n` +\n `$$ LANGUAGE plpgsql;`,\n );\n\n statements.push(\n `CREATE OR REPLACE TRIGGER ${projection.reconcileTrigger}\\n` +\n `AFTER INSERT OR UPDATE OR DELETE ON ${projection.syncedTable}\\n` +\n `FOR EACH ROW EXECUTE FUNCTION ${reconcileFunctionRef}();`,\n );\n\n statements.push(\n `CREATE OR REPLACE ${temp}VIEW ${projection.readModel} AS\\n${buildReadModelViewSql(\n entry,\n projection,\n columns.map((column) => column.name),\n )};`,\n );\n\n // ADR-0011: the per-table convergence view — a derived projection over synced + overlay +\n // journal, distinct from the (lean) read model, whose acked-unobserved status derives from the\n // same barrier predicate the reconcile trigger above uses (decision 4, anti-drift).\n statements.push(\n `CREATE OR REPLACE ${temp}VIEW ${projection.syncState} AS\\n${buildSyncStateView(entry, {\n syncedTable: projection.syncedTable,\n overlayTable: projection.overlayTable,\n journalTable: projection.journalTable,\n })};`,\n );\n }\n\n return `${statements.join(\"\\n\\n\")}\\n`;\n}\n\nfunction buildReadModelViewSql(\n entry: SyncTableEntry<AnyPgTable>,\n projection: ResolvedProjection,\n columnNames: string[],\n) {\n if (!projection.overlayTable) {\n throw new Error(`overlay table is required for writable table ${projection.syncedTable}`);\n }\n\n const pkMatch = buildPrimaryKeyMatch(entry.primaryKey.columns);\n const syncedLocalUpdatedExpression = columnNames.includes(\"updated_at_us\") ? \"t.updated_at_us\" : \"CAST(0 AS BIGINT)\";\n\n return [\n \"SELECT\",\n ` ${columnNames.join(\",\\n \")},`,\n \" overlay_kind,\",\n \" local_updated_at_us\",\n `FROM ${projection.overlayTable}`,\n `WHERE overlay_kind <> 'pending_delete'`,\n \"UNION ALL\",\n \"SELECT\",\n ` ${columnNames.map((name) => `t.${name}`).join(\",\\n \")},`,\n ` 'synced' AS overlay_kind,`,\n ` ${syncedLocalUpdatedExpression} AS local_updated_at_us`,\n `FROM ${projection.syncedTable} AS t`,\n \"WHERE NOT EXISTS (\",\n \" SELECT 1\",\n ` FROM ${projection.overlayTable} AS o`,\n ` WHERE ${pkMatch}`,\n \")\",\n ].join(\"\\n\");\n}\n\nfunction buildTableColumnSql(columns: TableColumn[], primaryKeyColumns: string[], localSchema: string) {\n return [\n ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumns, localSchema)),\n ...buildCompositePrimaryKeyClauses(primaryKeyColumns),\n ].join(\",\\n \");\n}\n\n/**\n * Render `CREATE TABLE IF NOT EXISTS` (plus a `CREATE INDEX IF NOT EXISTS` per declared index) for a\n * Drizzle `pgTable` / `pgSchema.table`, through the SAME column/PK/type machinery\n * ({@link buildTableColumnSql} → {@link buildColumnDefinition} → {@link mapColumnType}) that\n * {@link generateLocalSchemaSql} uses for every other local relation. The table is schema-qualified\n * when it declares a schema and bare otherwise (per the table object). Column types come from each\n * column's `getSQLType()`, NOT NULL and single-column PRIMARY KEY inline, composite PKs as a trailing\n * clause. Enum column types are qualified into the table's own schema — the metadata pgTables carry\n * none, but the path is shared with the local-store generator so it must stay honest.\n *\n * ADR-0029 D3: the metadata-store DDL renders from its `metadata-tables.ts` pgTables through this,\n * making the pgTable the single source. The OUTPUT is tier-③-by-nature runtime DDL (schema/table\n * identifiers assembled at construction), but it is GENERATED from the model, never hand-maintained.\n */\nexport function renderCreateTableSql(table: AnyPgTable): string[] {\n const config = getTableConfig(table);\n const schemaName = config.schema ?? \"public\";\n const qualifiedTableName = qualifyIdentifier(schemaName, config.name);\n const primaryKeyColumns = collectPgTablePrimaryKeyColumns(config);\n const columnSql = buildTableColumnSql(config.columns as unknown as TableColumn[], primaryKeyColumns, schemaName);\n\n const statements = [`CREATE TABLE IF NOT EXISTS ${qualifiedTableName} (\\n ${columnSql}\\n);`];\n\n for (const index of config.indexes) {\n statements.push(renderCreateIndexSql(qualifiedTableName, index));\n }\n\n return statements;\n}\n\n/** The PK column names of a `pgTable` — column-level `.primaryKey()` first, then composite `primaryKey({…})`. */\nfunction collectPgTablePrimaryKeyColumns(config: ReturnType<typeof getTableConfig>): string[] {\n const columnLevel = config.columns.filter((column) => column.primary).map((column) => column.name);\n const composite = config.primaryKeys.flatMap((pk) => pk.columns.map((column) => column.name));\n return [...columnLevel, ...composite];\n}\n\nfunction renderCreateIndexSql(qualifiedTableName: string, index: ReturnType<typeof getTableConfig>[\"indexes\"][number]) {\n const { name, unique, columns, where, method, with: withParams } = index.config;\n if (!name) {\n throw new Error(\"renderCreateIndexSql: anonymous indexes are not supported (declare a name)\");\n }\n // This renderer emits only a plain ascending btree over bare columns. Any modifier it does not\n // render must fail loudly — silently dropping one would produce a local index that differs from the\n // pgTable declaration (the very DDL-vs-model divergence ADR-0029 D3 removes for the metadata store).\n if (where) {\n throw new Error(`renderCreateIndexSql: partial indexes (.where) are not supported (index ${name})`);\n }\n if (method && method.toLowerCase() !== \"btree\") {\n throw new Error(\n `renderCreateIndexSql: non-btree index methods (.using \"${method}\") are not supported (index ${name})`,\n );\n }\n if (withParams && Object.keys(withParams).length > 0) {\n throw new Error(`renderCreateIndexSql: index storage parameters (.with) are not supported (index ${name})`);\n }\n const columnExpressions = columns.map((column) => {\n const columnName = (column as { name?: unknown }).name;\n if (typeof columnName !== \"string\") {\n throw new Error(`renderCreateIndexSql: expression index columns are not supported (index ${name})`);\n }\n const indexConfig = (column as { indexConfig?: { order?: string; nulls?: string; opClass?: string } }).indexConfig;\n if (indexConfig?.order === \"desc\") {\n throw new Error(`renderCreateIndexSql: descending index columns (.desc()) are not supported (index ${name})`);\n }\n // Drizzle fills `nulls` with the ascending-btree default (\"last\") on every column; only an\n // explicit NULLS FIRST diverges from what we render (a plain ascending btree is NULLS LAST).\n if (indexConfig?.nulls === \"first\") {\n throw new Error(`renderCreateIndexSql: NULLS FIRST ordering (.nullsFirst()) is not supported (index ${name})`);\n }\n if (indexConfig?.opClass) {\n throw new Error(`renderCreateIndexSql: index operator classes (.op()) are not supported (index ${name})`);\n }\n return maybeQuoteIdentifier(columnName);\n });\n\n return renderCreateIndexStatement(qualifiedTableName, maybeQuoteIdentifier(name), columnExpressions, { unique });\n}\n\n/**\n * The shared `CREATE INDEX` core: assemble one\n * `CREATE [UNIQUE] INDEX IF NOT EXISTS <name> ON <table> (<cols>)` over a qualified table, an\n * already-rendered index name, and already-rendered plain ascending column expressions. BOTH the\n * pgTable-driven renderer ({@link renderCreateIndexSql}) and the journal-index emitter in\n * {@link generateLocalSchemaSql} go through here, so the two index-emitting paths cannot drift in\n * statement shape. Identifier quoting is the caller's responsibility — the pgTable path quotes via\n * `maybeQuoteIdentifier`; the journal path passes its registry-derived bare names/columns verbatim —\n * this core only fixes the surrounding statement text.\n */\nfunction renderCreateIndexStatement(\n qualifiedTableName: string,\n indexName: string,\n columnExpressions: readonly string[],\n options: { unique?: boolean } = {},\n): string {\n const uniqueSql = options.unique ? \"UNIQUE \" : \"\";\n return `CREATE ${uniqueSql}INDEX IF NOT EXISTS ${indexName} ON ${qualifiedTableName} (${columnExpressions.join(\", \")});`;\n}\n\nfunction buildColumnDefinition(column: TableColumn, primaryKeyColumns: string[], localSchema: string) {\n const typeSql = mapColumnType(column, localSchema);\n const notNullSql = column.notNull ? \" NOT NULL\" : \"\";\n const primaryKeySql = primaryKeyColumns.length === 1 && primaryKeyColumns.includes(column.name) ? \" PRIMARY KEY\" : \"\";\n return `${column.name} ${typeSql}${notNullSql}${primaryKeySql}`;\n}\n\nfunction buildCompositePrimaryKeyClauses(primaryKeyColumns: string[]) {\n if (primaryKeyColumns.length <= 1) {\n return [];\n }\n\n return [`PRIMARY KEY (${primaryKeyColumns.join(\", \")})`];\n}\n\nfunction mapColumnType(column: TableColumn, localSchema: string) {\n const baseTypeSql = readBaseColumnTypeSql(column, localSchema);\n const dimensions = readArrayDimensions(column);\n\n if (dimensions > 0) {\n return `${baseTypeSql}${\"[]\".repeat(dimensions)}`;\n }\n\n return baseTypeSql;\n}\n\nfunction readBaseColumnTypeSql(column: TableColumn, localSchema: string) {\n const enumDefinition = readEnumColumnDefinition(column, localSchema);\n\n if (enumDefinition) {\n return qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName);\n }\n\n const sqlType = (column as { getSQLType(): string }).getSQLType();\n\n if (!sqlType) {\n throw new Error(`Unsupported column type for local schema generation: ${column.columnType}`);\n }\n\n return sqlType;\n}\n\ntype EnumDefinition = {\n schemaName: string;\n enumName: string;\n enumValues: string[];\n};\n\nfunction collectEnumDefinitions(registry: SyncTableRegistry, localSchema: string) {\n return collectEnumDefinitionsFromEntries(Object.values(registry), localSchema);\n}\n\n/**\n * Collect the distinct enum types referenced by a GIVEN set of registry entries (deduped by name, values\n * cross-checked for conflicts, sorted for stable output). Factored out of {@link collectEnumDefinitions} so\n * the Data export (ADR-0035) can emit ONLY the enums its `-t` allowlist tables reference — the whole-registry\n * caller passes every entry, the data export passes just its owning persistent entries — through one honest\n * implementation, never a second enum-scanning path that could drift on the conflict/sort rules.\n */\nfunction collectEnumDefinitionsFromEntries(entries: SyncTableEntry[], localSchema: string) {\n const enumDefinitionsByName = new Map<string, EnumDefinition>();\n\n for (const entry of entries) {\n const columns = getProjectedColumns(entry).map(({ column }) => column);\n\n for (const column of columns) {\n const enumDefinition = readEnumColumnDefinition(column, localSchema);\n\n if (!enumDefinition) {\n continue;\n }\n\n const existingDefinition = enumDefinitionsByName.get(enumDefinition.enumName);\n\n if (!existingDefinition) {\n enumDefinitionsByName.set(enumDefinition.enumName, enumDefinition);\n continue;\n }\n\n if (!areEnumValuesEqual(existingDefinition.enumValues, enumDefinition.enumValues)) {\n throw new Error(\n `Enum ${enumDefinition.enumName} has conflicting values in sync registry: ${existingDefinition.enumValues.join(\", \")} vs ${enumDefinition.enumValues.join(\", \")}`,\n );\n }\n }\n }\n\n return [...enumDefinitionsByName.values()].sort((left, right) => left.enumName.localeCompare(right.enumName));\n}\n\n/**\n * Does this entry OWN a physical, persistent synced table — i.e. is it a `-t` allowlist candidate for the\n * Data export (ADR-0035 decision 1)? Two entries are excluded:\n *\n * - a **read PROJECTION** (`readProjection`) owns no table (its `table` is another entry's), so it must\n * never be listed — it would double-target the owner's physical table;\n * - an **ephemeral** entry's cluster is emitted as `pg_temp` TEMP objects (ADR-0021 §3), absent from the\n * throwaway clone by construction — and a `pg_dump -t` pattern that matches NOTHING makes `pg_dump` fail,\n * so an ephemeral table must not appear in the allowlist at all.\n *\n * Overlay/journal/meta tables, read-model/sync-state views, and reconcile functions are excluded by `-t`\n * semantics automatically (they are neither the synced table nor matched by its name), so they need no\n * filter here.\n */\nfunction ownsPersistentSyncedTable(entry: SyncTableEntry): boolean {\n return !entry.readProjection && entry.retention !== \"ephemeral\";\n}\n\n/**\n * The `-t` allowlist for a Data export (ADR-0035 decision 1): the schema-qualified PHYSICAL synced table\n * name for every registry entry that owns one, resolved through the SAME `getClientProjection` the local\n * DDL generator uses — NOT re-derived by string convention. This is deliberately the physical `syncedTable`,\n * never the read-model view (whose name can carry the entry name while the table differs): `-t` must target\n * the tables that hold the rows. Read-projection and ephemeral entries are excluded (see\n * {@link ownsPersistentSyncedTable}).\n */\nexport function collectDataExportSyncedTableNames<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {\n const localSchema = getSyncRegistrySchema(registry);\n const names: string[] = [];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n if (!ownsPersistentSyncedTable(entry)) {\n continue;\n }\n\n names.push(getClientProjection(entry, tableKey, localSchema).syncedTable);\n }\n\n return names;\n}\n\n/**\n * The clone-cleanup SQL a Data export runs on its THROWAWAY clone before `pg_dump -t` (ADR-0035). The\n * reconcile trigger sits ON the synced table (`AFTER INSERT/UPDATE/DELETE ON <syncedTable>`), so\n * `pg_dump -t <syncedTable>` pulls the trigger into the dump — but its function is pgxsinkit machinery the\n * data export deliberately EXCLUDES, so the artefact would carry a trigger referencing a missing function\n * and fail to load into a vanilla Postgres. Because the clone is a memory-backed throwaway we fully own, we\n * drop each reconcile trigger (and its now-unreferenced function) on it first, so `-t` yields clean,\n * portable tables. Overlay/journal/views/metadata are NOT captured by `-t <syncedTable>` at all (a probe\n * confirmed only the table, its PK, its data, and this trigger appear), so nothing else needs dropping.\n * Returns `\"\"` when the registry declares no writable owning table.\n */\nexport function buildDataExportCloneCleanupSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const statements: string[] = [];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n if (!ownsPersistentSyncedTable(entry) || entry.mode === \"readonly\") {\n continue;\n }\n\n const projection = getClientProjection(entry, tableKey, localSchema);\n // Drop the trigger first, then its now-unreferenced function (drop order avoids a dependency error).\n statements.push(`DROP TRIGGER IF EXISTS ${projection.reconcileTrigger} ON ${projection.syncedTable};`);\n statements.push(`DROP FUNCTION IF EXISTS ${projection.reconcileFunction}();`);\n }\n\n return statements.join(\"\\n\");\n}\n\n/**\n * The enum DDL header for a Data export artefact (ADR-0035 decision 1). `pg_dump -t <table>` emits the\n * tables but NOT the enum types their columns reference, so the portable artefact is this generated header\n * concatenated ahead of the `pg_dump` output. It reuses the SAME `CREATE TYPE` generation the local-schema\n * generator emits ({@link buildCreateEnumTypeSql}) — every enum wrapped in an idempotent `IF NOT EXISTS`\n * guard — restricted to the enums actually referenced by the exported (owning, persistent) tables, so a\n * dropped/ephemeral-only enum never bloats the artefact. When the registry uses a non-`public` schema, a\n * `CREATE SCHEMA IF NOT EXISTS` precedes the types (they live in that schema, and the header runs before\n * `pg_dump`'s own schema creation), so the header is self-contained against a bare Postgres. Returns `\"\"`\n * when no exported table references an enum.\n */\nexport function buildDataExportEnumHeaderSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const exportedEntries = Object.values(registry).filter(ownsPersistentSyncedTable);\n const enumDefinitions = collectEnumDefinitionsFromEntries(exportedEntries, localSchema);\n\n if (enumDefinitions.length === 0) {\n return \"\";\n }\n\n const statements: string[] = [\n \"-- Enum types referenced by the exported tables. `pg_dump -t` does not emit the enum types\",\n \"-- its tables depend on, so pgxsinkit generates them here from the sync registry (ADR-0035).\",\n ];\n\n // A non-public schema must exist before its `CREATE TYPE` runs — this header precedes pg_dump's own\n // schema creation, so create it ourselves (idempotent), mirroring `generateLocalSchemaSql`.\n if (localSchema !== \"public\") {\n statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(localSchema)};`);\n }\n\n for (const enumDefinition of enumDefinitions) {\n statements.push(buildCreateEnumTypeSql(enumDefinition));\n }\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n\nfunction buildCreateEnumTypeSql(enumDefinition: EnumDefinition) {\n const typeIdentifier = qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName);\n const enumValuesSql = enumDefinition.enumValues.map((value) => quoteSqlStringLiteral(value)).join(\", \");\n\n return [\n \"DO $$\",\n \"BEGIN\",\n \" IF NOT EXISTS (\",\n \" SELECT 1\",\n \" FROM pg_type AS t\",\n \" INNER JOIN pg_namespace AS n ON n.oid = t.typnamespace\",\n ` WHERE t.typname = ${quoteSqlStringLiteral(enumDefinition.enumName)}`,\n ` AND n.nspname = ${quoteSqlStringLiteral(enumDefinition.schemaName)}`,\n \" ) THEN\",\n ` CREATE TYPE ${typeIdentifier} AS ENUM (${enumValuesSql});`,\n \" END IF;\",\n \"END\",\n \"$$;\",\n ].join(\"\\n\");\n}\n\nfunction areEnumValuesEqual(left: string[], right: string[]) {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let index = 0; index < left.length; index += 1) {\n if (left[index] !== right[index]) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction readEnumColumnDefinition(column: TableColumn, localSchema: string): EnumDefinition | undefined {\n const candidate = column as TableColumn & {\n enum?: {\n enumName?: unknown;\n enumValues?: unknown;\n };\n };\n\n if (!candidate.enum || typeof candidate.enum.enumName !== \"string\" || !Array.isArray(candidate.enum.enumValues)) {\n return undefined;\n }\n\n const enumValues = candidate.enum.enumValues.filter((value): value is string => typeof value === \"string\");\n\n if (enumValues.length !== candidate.enum.enumValues.length) {\n throw new Error(\n `Enum ${candidate.enum.enumName} includes non-string values and cannot be emitted in local schema SQL`,\n );\n }\n\n return {\n schemaName: localSchema,\n enumName: candidate.enum.enumName,\n enumValues,\n };\n}\n\nfunction readArrayDimensions(column: TableColumn) {\n const arrayColumn = column as TableColumn & { dimensions?: number };\n return arrayColumn.dimensions ?? 0;\n}\n\nfunction buildPrimaryKeyMatch(primaryKeyColumns: string[]) {\n return primaryKeyColumns.map((column) => `o.${column} = t.${column}`).join(\" AND \");\n}\n\nfunction getClientProjection(entry: SyncTableEntry, tableKey: string, localSchema: string): ResolvedProjection {\n const projection = baseProjection(entry, tableKey);\n const syncedTableName = projection.syncedTable ?? tableKey;\n const readModelName = entry.view != null ? getViewConfig(entry.view).name : syncedTableName;\n\n return {\n syncedTable: qualifyIdentifier(localSchema, syncedTableName),\n ...(projection.overlayTable ? { overlayTable: qualifyIdentifier(localSchema, projection.overlayTable) } : {}),\n ...(projection.journalTable ? { journalTable: qualifyIdentifier(localSchema, projection.journalTable) } : {}),\n readModel: qualifyIdentifier(localSchema, readModelName),\n syncState: qualifyIdentifier(localSchema, `${syncedTableName}_sync_state`),\n reconcileFunction: qualifyIdentifier(localSchema, `${syncedTableName}_reconcile_on_sync`),\n reconcileTrigger: maybeQuoteIdentifier(`${syncedTableName}_reconcile_on_sync`),\n };\n}\n\nfunction baseProjection(entry: SyncTableEntry, tableKey: string) {\n if (!entry.clientProjection) {\n throw new Error(`clientProjection is required for local client table ${tableKey}`);\n }\n\n return entry.clientProjection;\n}\n\nfunction qualifyIdentifier(schemaName: string, objectName: string) {\n if (schemaName === \"public\") {\n // Quote only when required so existing generated SQL stays stable, but a table/view named\n // after a reserved word (e.g. `group`) is a valid Postgres identifier and MUST be quoted or\n // the generated DDL and read queries fail to parse. The row-applier (src/sync) always quotes.\n return maybeQuoteIdentifier(objectName);\n }\n\n return `${quoteIdentifier(schemaName)}.${quoteIdentifier(objectName)}`;\n}\n\nfunction buildJournalSequenceName(journalTable: string) {\n return `${journalTable}_mutation_seq`;\n}\n\n/**\n * Drop the reconstructible **read cache** — the synced tables and their read-model views\n * and reconcile triggers/functions — while preserving the authority tables (overlay,\n * journal, the local-meta table). Re-running {@link generateLocalSchemaSql} then rebuilds\n * the synced tables at the current shape, and a re-sync refills them (ADR-0006). This is\n * the named drop primitive a returning-online upgrade uses after a clean drain.\n */\nexport function buildDropReadCacheSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const statements: string[] = [];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n const projection = getClientProjection(entry, tableKey, localSchema);\n\n if (entry.mode !== \"readonly\") {\n statements.push(`DROP VIEW IF EXISTS ${projection.syncState};`);\n statements.push(`DROP VIEW IF EXISTS ${projection.readModel};`);\n statements.push(`DROP TRIGGER IF EXISTS ${projection.reconcileTrigger} ON ${projection.syncedTable};`);\n statements.push(`DROP FUNCTION IF EXISTS ${projection.reconcileFunction}();`);\n }\n\n statements.push(`DROP TABLE IF EXISTS ${projection.syncedTable} CASCADE;`);\n }\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n\n/**\n * Wipe the **entire** local store provisioned from the registry — the read cache plus the\n * authority tables (overlay, journal, sequences), the enum types, and the local-meta row.\n * This is the full teardown reused by `destroy()` (ADR-0005 decision 5) and by the\n * drain-then-drop upgrade once a clean drain has confirmed nothing is owed (ADR-0006).\n */\nexport function buildWipeLocalStoreSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const statements: string[] = [buildDropReadCacheSql(registry).trimEnd()];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n if (entry.mode === \"readonly\") {\n continue;\n }\n\n const projection = getClientProjection(entry, tableKey, localSchema);\n\n if (projection.overlayTable) {\n statements.push(`DROP TABLE IF EXISTS ${projection.overlayTable} CASCADE;`);\n }\n\n if (projection.journalTable && entry.clientProjection?.journalTable) {\n statements.push(`DROP TABLE IF EXISTS ${projection.journalTable} CASCADE;`);\n statements.push(\n `DROP SEQUENCE IF EXISTS ${qualifyIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable))};`,\n );\n }\n }\n\n for (const enumDefinition of collectEnumDefinitions(registry, localSchema)) {\n statements.push(`DROP TYPE IF EXISTS ${qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName)};`);\n }\n\n statements.push(`DROP TABLE IF EXISTS ${qualifyIdentifier(localSchema, LOCAL_META_TABLE)} CASCADE;`);\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n\n/**\n * Clean-truncate a single table's local read cache so a desynced `lazy` relation (ADR-0021 §2) returns\n * to an empty, dormant state: the synced table and — for a writable table — its optimistic overlay and\n * the journal, plus a sequence restart. It does NOT drop the cluster (the table/views/trigger persist),\n * so a later re-reference re-streams into it without a schema rebuild. Ephemeral-aware: bare/`pg_temp`\n * names for an ephemeral cluster, schema-qualified for a persistent one — mirroring\n * {@link generateLocalSchemaSql}. The caller (`desync`) first stops the group's stream (so nothing\n * re-populates mid-truncate) and refuses when the journal owes unsettled writes (so this never drops\n * un-acked local intent).\n */\nexport function buildDesyncTableSql<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n tableKey: string,\n): string {\n const entry = registry[tableKey];\n\n if (!entry) {\n throw new Error(`buildDesyncTableSql: unknown table ${tableKey}`);\n }\n\n const localSchema = getSyncRegistrySchema(registry);\n const ephemeral = entry.retention === \"ephemeral\";\n const objectSchema = ephemeral ? \"public\" : localSchema;\n const projection = getClientProjection(entry, tableKey, objectSchema);\n const statements: string[] = [`TRUNCATE TABLE ${projection.syncedTable};`];\n\n if (entry.mode !== \"readonly\") {\n if (projection.overlayTable) {\n statements.push(`TRUNCATE TABLE ${projection.overlayTable};`);\n }\n\n if (projection.journalTable && entry.clientProjection?.journalTable) {\n statements.push(`TRUNCATE TABLE ${projection.journalTable};`);\n statements.push(\n `ALTER SEQUENCE ${qualifyIdentifier(objectSchema, buildJournalSequenceName(entry.clientProjection.journalTable))} RESTART WITH 1;`,\n );\n }\n }\n\n // ADR-0023 Slice 2: a desync reverts the relation to dormant and deletes its subscription, so the next\n // activation re-streams from scratch — drop this shape's tag-set too, or it would orphan tags for rows\n // that never come back. The key matches what the engine writes (`shapeTableId(shape.schema, table)`):\n // for ephemeral the engine passes no schema (→ `public`), exactly this `objectSchema`.\n const syncedTableNameRaw = baseProjection(entry, tableKey).syncedTable ?? tableKey;\n statements.push(buildClearShapeTagsSql(shapeTableId(objectSchema, syncedTableNameRaw)));\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n",
128
135
  "import type { ColumnBuilderBase } from \"drizzle-orm\";\nimport { getColumns } from \"drizzle-orm\";\nimport {\n bigint,\n boolean,\n customType,\n getTableConfig,\n integer,\n pgSchema,\n pgTable,\n pgView,\n text,\n uuid,\n varchar,\n type AnyPgTable,\n type PgColumn,\n type PgTableWithColumns,\n type PgViewWithSelection,\n} from \"drizzle-orm/pg-core\";\n\nimport {\n deriveSyncColumnTypes,\n getLocalSyncedTablePrimaryKeyColumns,\n getSyncRegistrySchema,\n type SyncColumnType,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport { LOCAL_META_TABLE } from \"./schema\";\n\n/**\n * Runtime Drizzle objects for the GENERATED local-store relations (ADR-0004): the per-writable-table\n * overlay (`<t>_overlay`), journal (`<t>_mutations`), sync-state view (`<t>_sync_state`), the projected\n * synced read cache, and the `pgxsinkit_local_meta` key/value table. The schema generator\n * (`schema.ts`) remains the one authority for the DDL — these objects exist so the mutation runtime,\n * consumers, and tests can AUTHOR queries against those relations as tier-① Drizzle objects\n * (rename-safe, type-checked) instead of hand-written SQL strings.\n *\n * They are query-authoring objects only — never feed them to drizzle-kit generation; the generated\n * DDL in `schema.ts` is the source of truth for the physical shape, and `local-tables.test`-level\n * coverage (the existing overlay/journal suites run against generator-provisioned stores) is what\n * keeps the two aligned.\n *\n * Every object is schema-QUALIFIED with the registry's own local schema (via `getSyncRegistrySchema`).\n * `entry.table` / `entry.localTable` are already qualified the same way (`defineSyncTable` builds them\n * with the caller's schema, and `attachSyncRegistrySchema` throws unless they match the registry schema),\n * so for the synced read cache the factory just tracks a `clientProjection.syncedTable` rename. The\n * factories earn their keep where no equally-qualified entry handle exists: `entry.view` is built\n * schema-UNqualified (a bare `pgView`), so a store in a non-public schema must author the read model\n * through `getReadModelView`; and the overlay / journal / sync-state relations have NO entry handle at all\n * — these factories are the only Drizzle objects for them. Each factory MEMOIZES its result per\n * `(registry, tableKey)` (the `pgxsinkit_local_meta` table per local schema), so repeated calls hand back\n * the same object identity.\n *\n * Typing tracks the registry the caller holds: with a concretely-typed registry (built by\n * `defineSyncRegistry`) the synced/overlay/read-model objects carry the entry's real per-column types, so\n * `.select({ x: overlay.col })`, `$inferInsert`, and `.values()` all typecheck by property key; with a\n * bare `SyncTableRegistry` they degrade to an open index-signature shape reached by bracket access.\n * `JournalTable` / `SyncStateView` are ALWAYS conservatively indexed for their entity/PK columns (the PK\n * name set is not recoverable at the type level — see those types).\n */\n\n/**\n * Microsecond/bigint columns the mutation runtime handles as **strings** (the JSON-safe form it has\n * always used): passthrough both ways, `bigint` in DDL position. Reads through the raw `MutationDb`\n * seam bypass drizzle result mapping anyway; this keeps `.values()`/`.set()` accepting the runtime's\n * string values without a lossy JS-number hop.\n */\nconst bigintText = customType<{ data: string; driverData: string }>({\n dataType() {\n return \"bigint\";\n },\n});\n\nfunction buildJournalFixedColumns() {\n return {\n mutationId: uuid(\"mutation_id\").primaryKey(),\n entityKeyJson: text(\"entity_key_json\").notNull(),\n mutationSeq: integer(\"mutation_seq\").notNull(),\n mutationKind: varchar(\"mutation_kind\", { length: 24 }).notNull(),\n status: varchar(\"status\", { length: 24 }).notNull(),\n registryVersion: text(\"registry_version\"),\n baseServerVersion: bigintText(\"base_server_version\"),\n writeUnit: text(\"write_unit\"),\n writeMode: varchar(\"write_mode\", { length: 24 }),\n payloadJson: text(\"payload_json\").notNull(),\n attemptCount: integer(\"attempt_count\").notNull().default(0),\n lastError: text(\"last_error\"),\n lastHttpStatus: integer(\"last_http_status\"),\n conflictReason: text(\"conflict_reason\"),\n serverUpdatedAtUs: bigintText(\"server_updated_at_us\"),\n enqueuedAtUs: bigintText(\"enqueued_at_us\").notNull(),\n nextRetryAtUs: bigintText(\"next_retry_at_us\"),\n sentAtUs: bigintText(\"sent_at_us\"),\n ackedAtUs: bigintText(\"acked_at_us\"),\n updatedAtUs: bigintText(\"updated_at_us\").notNull(),\n };\n}\n\nfunction buildOverlayFixedColumns() {\n return {\n overlayKind: varchar(\"overlay_kind\", { length: 24 }).notNull(),\n localUpdatedAtUs: bigintText(\"local_updated_at_us\").notNull(),\n };\n}\n\n/**\n * The two overlay columns the `<t>_read_model` view carries on top of the projected synced columns.\n * Read through real drizzle result mapping (a live query, not the raw `MutationDb` seam), so\n * `local_updated_at_us` is a `mode: \"bigint\"` int8 (PGlite returns it as a string at runtime) rather than\n * the journal/overlay `bigintText` passthrough. Snake-case property keys so consumers reach them the same\n * way the generator names them (`view[\"overlay_kind\"]`).\n */\nfunction buildReadModelFixedColumns() {\n return {\n overlay_kind: varchar(\"overlay_kind\", { length: 24 }).notNull(),\n local_updated_at_us: bigint(\"local_updated_at_us\", { mode: \"bigint\" }).notNull(),\n };\n}\n\nfunction buildSyncStateFixedColumns() {\n return {\n observedServerVersion: bigint(\"observed_server_version\", { mode: \"bigint\" }),\n ackedServerVersion: bigint(\"acked_server_version\", { mode: \"bigint\" }),\n pendingCount: bigint(\"pending_count\", { mode: \"number\" }).notNull(),\n hasAckedUnobservedWrite: boolean(\"has_acked_unobserved_write\").notNull(),\n localDeletePending: boolean(\"local_delete_pending\").notNull(),\n conflictState: text(\"conflict_state\"),\n quarantinedCount: bigint(\"quarantined_count\", { mode: \"number\" }).notNull(),\n quarantineState: text(\"quarantine_state\"),\n };\n}\n\n// Phantom shape tables: never created, never queried — they exist only so the derived relation types\n// carry strong typing on the FIXED column keys. The per-entry ENTITY columns are layered on top from\n// the concrete registry entry (see the `*<TEntry>` types below), so a caller whose registry is\n// concretely typed reaches real, projected `PgColumn`s by property key; only a caller holding a bare\n// `SyncTableRegistry` falls back to the open index-signature form these shapes' generic default gives.\nconst journalShape = pgTable(\"_pgxsinkit_journal_shape\", buildJournalFixedColumns());\nconst overlayShape = pgTable(\"_pgxsinkit_overlay_shape\", buildOverlayFixedColumns());\nconst syncStateShape = pgView(\"_pgxsinkit_sync_state_shape\", buildSyncStateFixedColumns()).existing();\nconst readModelShape = pgView(\"_pgxsinkit_read_model_shape\", buildReadModelFixedColumns()).existing();\nconst localMetaShape = pgTable(LOCAL_META_TABLE, {\n key: text(\"key\").primaryKey(),\n value: text(\"value\").notNull(),\n});\n\n/**\n * The entry's PROJECTED local table type — its server columns minus `clientProjection.omitColumns`,\n * exactly the shape `defineSyncTable` stamped onto `entry.localTable`. When `TEntry` is a concrete\n * entry (a registry built by `defineSyncRegistry`) this carries the real, typed columns; when it is a\n * bare `SyncTableEntry` (a generic `SyncTableRegistry`) it degrades to `AnyPgTable`, which pushes every\n * derived type below onto the open `Record<string, PgColumn>` index-signature fallback.\n */\ntype EntryLocalTable<TEntry> =\n TEntry extends SyncTableEntry<AnyPgTable, infer TLocal extends AnyPgTable> ? TLocal : AnyPgTable;\n\n/** The entry's projected columns keyed by drizzle property key (or the open `PgColumns` fallback). */\ntype EntryColumns<TEntry> = EntryLocalTable<TEntry>[\"_\"][\"columns\"];\ntype OverlayFixedColumns = (typeof overlayShape)[\"_\"][\"columns\"];\ntype ReadModelFixedColumns = (typeof readModelShape)[\"_\"][\"selectedFields\"];\n\n/**\n * The `<t>_overlay` optimistic-intent table: the entry's PROJECTED columns (same builders the generator\n * and `entry.localTable` carry) merged with the two fixed overlay columns. The entity columns read\n * back through real drizzle result mapping, so their types mirror the projected table exactly (a\n * `mode: \"bigint\"` column is `bigint`, etc.). The two overlay columns are `bigintText` passthrough\n * (`local_updated_at_us` reads as a string). `TEntry` defaults to a bare entry, giving the open\n * index-signature form the mutation runtime (generic over any registry) needs.\n */\nexport type OverlayTable<TEntry = SyncTableEntry> = PgTableWithColumns<{\n name: string;\n schema: string | undefined;\n columns: EntryColumns<TEntry> & OverlayFixedColumns;\n dialect: \"pg\";\n}>;\n\n/**\n * The `<t>_read_model` overlay-merged read view (ADR-0004): the entry's PROJECTED columns under their\n * property keys plus the two fixed overlay columns (`overlay_kind`, `local_updated_at_us`). Read\n * through a live query, so `local_updated_at_us` is an int8 `mode: \"bigint\"` column.\n */\nexport type ReadModelView<TEntry = SyncTableEntry> = PgViewWithSelection<\n string,\n true,\n EntryColumns<TEntry> & ReadModelFixedColumns\n>;\n\n/**\n * The projected SYNCED read-cache table — the entry's projected local table (or `AnyPgTable` fallback).\n * Type-level note: the phantom relation name here is the original `tableName` (inherited from\n * `ProjectedLocalTable`), but the runtime object `getSyncedLocalTable` returns honours a\n * `clientProjection.syncedTable` rename — so the rendered SQL uses the runtime name, not this type's name.\n */\nexport type SyncedLocalTable<TEntry = SyncTableEntry> = EntryLocalTable<TEntry>;\n\n/**\n * The `<t>_mutations` journal: fixed runtime columns + the entry's PK columns (index-signature access).\n * Kept conservatively indexed: the journal carries ONLY the PK columns, keyed by DB COLUMN NAME and\n * type-erased to `text`, but neither the PK column-name set nor the \"PK only\" subset is recoverable at\n * the type level from `SyncTableEntry` (its `primaryKey.columns` is an un-narrowed `string[]`), so an\n * honest per-entry type is not representable without a footgun (claiming non-PK columns that do not\n * exist on the journal at runtime). PK/entity columns therefore ride the index signature.\n */\nexport type JournalTable = typeof journalShape & { [columnName: string]: PgColumn };\n/**\n * The `<t>_sync_state` convergence view (ADR-0011): fixed state columns + the entry's PK columns.\n * Conservatively indexed for the same reason as {@link JournalTable} — it projects only the PK columns\n * (a subset not recoverable at the type level), so the PK columns ride the index signature.\n */\nexport type SyncStateView = typeof syncStateShape & { [columnName: string]: PgColumn };\n/** The `pgxsinkit_local_meta` key/value table (ADR-0006). */\nexport type LocalMetaTable = typeof localMetaShape;\n\n/**\n * Build a runtime `pgTable` for a local-store relation. An `ephemeral`-lifecycle entry (ADR-0021 §3)\n * renders **bare** regardless of the registry's local schema: its whole cluster is emitted as `TEMP`\n * with unqualified object names that resolve via `pg_temp`/search_path, exactly as\n * `generateLocalSchemaSql` renders it (a `pgSchema(localSchema).table(...)` reference would target a\n * durable schema the temp table does not live in — the latent qualification bug ADR-0029 records).\n */\nfunction makeTable(\n localSchema: string,\n name: string,\n columns: Record<string, ColumnBuilderBase>,\n ephemeral = false,\n): AnyPgTable {\n return localSchema === \"public\" || ephemeral ? pgTable(name, columns) : pgSchema(localSchema).table(name, columns);\n}\n\nfunction isEphemeral(entry: SyncTableEntry<AnyPgTable>): boolean {\n return entry.retention === \"ephemeral\";\n}\n\nfunction resolveSyncedTableName(entry: SyncTableEntry<AnyPgTable>): string {\n return entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name;\n}\n\n/**\n * The entry's projected column BUILDERS keyed by property key, re-created from the retained\n * `makeColumns` factory (registry.ts keeps it for exactly this kind of reuse) with\n * `clientProjection.omitColumns` applied — the same projection the generator's synced/overlay DDL\n * carries.\n */\nfunction projectedColumnBuilders(entry: SyncTableEntry<AnyPgTable>, tableKey: string) {\n const makeColumns = entry.makeColumns;\n if (!makeColumns) {\n throw new Error(\n `local table objects for ${tableKey} need the entry's makeColumns factory (built by defineSyncTable); ` +\n `hand-assembled entries cannot derive overlay/journal objects`,\n );\n }\n const omitted = new Set(entry.clientProjection?.omitColumns ?? []);\n return Object.fromEntries(Object.entries(makeColumns()).filter(([key]) => !omitted.has(key))) as Record<\n string,\n ColumnBuilderBase\n >;\n}\n\n/** Property-key ↔ column-name pairs for the entry's PK, resolved via the built local table. */\nfunction pkColumnPairs(entry: SyncTableEntry<AnyPgTable>, tableKey: string) {\n const localColumns = getColumns(entry.localTable) as Record<string, PgColumn>;\n return entry.primaryKey.columns.map((columnName) => {\n const pair = Object.entries(localColumns).find(([, column]) => column.name === columnName);\n if (!pair) {\n throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);\n }\n return { propertyKey: pair[0], columnName };\n });\n}\n\ninterface EntryLocalTables {\n synced?: AnyPgTable;\n overlay?: OverlayTable;\n journal?: JournalTable;\n syncState?: SyncStateView;\n readModel?: ReadModelView;\n}\n\nconst localTablesCache = new WeakMap<SyncTableRegistry, Map<string, EntryLocalTables>>();\nconst localMetaCache = new Map<string, LocalMetaTable>();\n\nfunction cacheFor(registry: SyncTableRegistry, tableKey: string): EntryLocalTables {\n let byKey = localTablesCache.get(registry);\n if (!byKey) {\n byKey = new Map();\n localTablesCache.set(registry, byKey);\n }\n let slot = byKey.get(tableKey);\n if (!slot) {\n slot = {};\n byKey.set(tableKey, slot);\n }\n return slot;\n}\n\nfunction requireEntry(registry: SyncTableRegistry, tableKey: string): SyncTableEntry<AnyPgTable> {\n const entry = registry[tableKey];\n if (!entry) {\n throw new Error(`Unknown sync table: ${tableKey}`);\n }\n return entry;\n}\n\nfunction requireWritable(entry: SyncTableEntry<AnyPgTable>, tableKey: string, relation: string) {\n if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {\n throw new Error(`${relation} exists only for a writable table; ${tableKey} has no overlay/journal projection`);\n }\n return entry.clientProjection as { overlayTable: string; journalTable: string; syncedTable?: string };\n}\n\n/**\n * The projected SYNCED read-cache table as a runtime Drizzle object, under the resolved local name\n * (`clientProjection.syncedTable` override honoured) and the registry's local schema — the exact\n * relation the generator's `CREATE TABLE` provisions. Prefer `entry.localTable` where its name\n * already matches; this object exists for the runtime/tests that must track the projection rename.\n * Carries the entry's real projected columns under a concretely-typed registry, `AnyPgTable` under a\n * bare `SyncTableRegistry` (see {@link SyncedLocalTable}).\n */\nexport function getSyncedLocalTable<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): SyncedLocalTable<TRegistry[TKey]> {\n const slot = cacheFor(registry, tableKey);\n if (slot.synced) {\n return slot.synced as SyncedLocalTable<TRegistry[TKey]>;\n }\n const entry = requireEntry(registry, tableKey);\n const localSchema = getSyncRegistrySchema(registry);\n const table = makeTable(\n localSchema,\n resolveSyncedTableName(entry),\n projectedColumnBuilders(entry, tableKey) as Record<string, ColumnBuilderBase>,\n isEphemeral(entry),\n );\n slot.synced = table;\n return table as SyncedLocalTable<TRegistry[TKey]>;\n}\n\n/**\n * The `<t>_overlay` optimistic-intent table as a runtime Drizzle object (writable tables only — throws\n * for a readonly entry, which has no overlay/journal projection). Its entity columns are typed exactly\n * as {@link OverlayTable} describes — real per-column types under a concretely-typed registry, the open\n * index-signature fallback under a bare `SyncTableRegistry` — plus the two fixed overlay columns.\n */\nexport function getOverlayTable<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): OverlayTable<TRegistry[TKey]> {\n const slot = cacheFor(registry, tableKey);\n if (slot.overlay) {\n return slot.overlay as OverlayTable<TRegistry[TKey]>;\n }\n const entry = requireEntry(registry, tableKey);\n const projection = requireWritable(entry, tableKey, \"the overlay table\");\n const localSchema = getSyncRegistrySchema(registry);\n const table = makeTable(\n localSchema,\n projection.overlayTable,\n {\n ...(projectedColumnBuilders(entry, tableKey) as Record<string, ColumnBuilderBase>),\n ...buildOverlayFixedColumns(),\n },\n isEphemeral(entry),\n ) as OverlayTable;\n slot.overlay = table;\n return table as OverlayTable<TRegistry[TKey]>;\n}\n\n/**\n * The `<t>_mutations` journal table as a runtime Drizzle object (writable tables only). The fixed runtime\n * columns are typed; the PK/entity columns ride the index signature and are reached by DB column NAME\n * (`journal[\"id\"]`), because per-entry typing is not representable — see {@link JournalTable}.\n */\nexport function getJournalTable<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n tableKey: string & keyof TRegistry,\n): JournalTable {\n const slot = cacheFor(registry, tableKey);\n if (slot.journal) {\n return slot.journal;\n }\n const entry = requireEntry(registry, tableKey);\n const projection = requireWritable(entry, tableKey, \"the journal table\");\n const localSchema = getSyncRegistrySchema(registry);\n const pkBuilders = Object.fromEntries(\n pkColumnPairs(entry, tableKey).map(({ columnName }) => [columnName, text(columnName).notNull()]),\n );\n const table = makeTable(\n localSchema,\n projection.journalTable,\n {\n ...pkBuilders,\n ...buildJournalFixedColumns(),\n },\n isEphemeral(entry),\n ) as JournalTable;\n slot.journal = table;\n return table;\n}\n\n/**\n * The `<t>_sync_state` convergence view (ADR-0011) as a runtime Drizzle object (writable tables only) —\n * PK columns under the entry's own property keys plus the fixed state columns, mirroring\n * `buildSyncStateView`'s projection. The fixed state columns are typed; the PK columns ride the index\n * signature (not recoverable at the type level — see {@link SyncStateView}) and are reached by their\n * drizzle PROPERTY key (`view[\"authorId\"]`), unlike the journal, which keys its PK columns by DB column\n * name.\n */\nexport function getSyncStateView<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n tableKey: string & keyof TRegistry,\n): SyncStateView {\n const slot = cacheFor(registry, tableKey);\n if (slot.syncState) {\n return slot.syncState;\n }\n const entry = requireEntry(registry, tableKey);\n requireWritable(entry, tableKey, \"the sync-state view\");\n const localSchema = getSyncRegistrySchema(registry);\n const viewName = `${resolveSyncedTableName(entry)}_sync_state`;\n const builders = projectedColumnBuilders(entry, tableKey);\n const pkBuilders = Object.fromEntries(\n pkColumnPairs(entry, tableKey).map(({ propertyKey }) => {\n const builder = builders[propertyKey];\n if (!builder) {\n throw new Error(`Primary key property ${propertyKey} was not found on table ${tableKey}`);\n }\n return [propertyKey, builder];\n }),\n ) as Record<string, ColumnBuilderBase>;\n const columns = {\n ...(pkBuilders as Record<string, ColumnBuilderBase>),\n ...buildSyncStateFixedColumns(),\n };\n const view = (\n localSchema === \"public\" || isEphemeral(entry)\n ? pgView(viewName, columns).existing()\n : pgSchema(localSchema).view(viewName, columns).existing()\n ) as SyncStateView;\n slot.syncState = view;\n return view;\n}\n\n/**\n * The `<t>_read_model` overlay-merged read view (ADR-0004) as a runtime Drizzle object: every projected\n * synced column under the entry's own property key plus the two overlay columns (`overlay_kind`,\n * `local_updated_at_us`), mirroring the generator's `CREATE VIEW`. The entry's own `entry.view` is\n * schema-UNQUALIFIED (`defineSyncTable` builds it with a bare `pgView`), so a consumer whose local store\n * lives in a non-public schema must author against this qualified object instead of `entry.view`.\n */\nexport function getReadModelView<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): ReadModelView<TRegistry[TKey]> {\n const slot = cacheFor(registry, tableKey);\n if (slot.readModel) {\n return slot.readModel as ReadModelView<TRegistry[TKey]>;\n }\n const entry = requireEntry(registry, tableKey);\n requireWritable(entry, tableKey, \"the read-model view\");\n const localSchema = getSyncRegistrySchema(registry);\n const viewName = `${resolveSyncedTableName(entry)}_read_model`;\n const columns = {\n ...(projectedColumnBuilders(entry, tableKey) as Record<string, ColumnBuilderBase>),\n ...buildReadModelFixedColumns(),\n };\n const view = (\n localSchema === \"public\" || isEphemeral(entry)\n ? pgView(viewName, columns).existing()\n : pgSchema(localSchema).view(viewName, columns).existing()\n ) as ReadModelView;\n slot.readModel = view;\n return view as ReadModelView<TRegistry[TKey]>;\n}\n\n/**\n * The read-path applier's resolved per-shape target (ADR-0029 D1/D2). Every table-scoped fact the\n * appliers need is derived once from the registry entry — the real projected synced table object, its\n * columns indexed by DB column name, the primary-key column names, and the model-derived column types —\n * so the appliers author over Drizzle objects (no name/schema strings, no `information_schema` probe).\n * Resolved once per shape at subscribe time; reused for every message. Electric change rows are keyed\n * by DB **column name**, while Drizzle DML keys by **property key**, so both indexes are carried.\n */\nexport interface ApplyTarget {\n /** The real projected synced local table (`getSyncedLocalTable`) — bare for ephemeral lifecycles. */\n table: AnyPgTable;\n /** DB column name → its Drizzle `PgColumn` (for `eq`/conflict-target/COPY clauses). */\n columnByName: Record<string, PgColumn>;\n /** DB column name → its Drizzle property key (to key `.values()`/`.set()` from a name-keyed row). */\n propertyKeyByName: Record<string, string>;\n /** Primary-key column NAMES, in order (from the entry, local-projection override honoured). */\n primaryKey: string[];\n /** Model-derived column types (`deriveSyncColumnTypes`), keyed by DB column name via `.name`. */\n columnTypes: SyncColumnType[];\n /**\n * Per-shape render-once cache for the batched-INSERT family (ADR-0029 D5): a rendered `{sqlText,\n * params}` per distinct (column-set, row-count), reused across batches with per-value codecs applied\n * at execution. Empty at resolution; populated lazily by the applier.\n */\n insertRenderCache: Map<string, { sqlText: string; params: unknown[] }>;\n}\n\n/**\n * Resolve a shape's {@link ApplyTarget} from its registry entry (ADR-0029 D1/D2). Called once per shape\n * at subscribe time — never per message. The single source is the registry item: identity via\n * `getSyncedLocalTable`, PKs via `getLocalSyncedTablePrimaryKeyColumns`, types via `deriveSyncColumnTypes`.\n */\nexport function resolveApplyTarget<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): ApplyTarget {\n const entry = requireEntry(registry, tableKey);\n const table = getSyncedLocalTable(registry, tableKey);\n const columns = getColumns(table as AnyPgTable) as Record<string, PgColumn>;\n const columnByName: Record<string, PgColumn> = {};\n const propertyKeyByName: Record<string, string> = {};\n for (const [propertyKey, column] of Object.entries(columns)) {\n columnByName[column.name] = column;\n propertyKeyByName[column.name] = propertyKey;\n }\n return {\n table: table as AnyPgTable,\n columnByName,\n propertyKeyByName,\n primaryKey: getLocalSyncedTablePrimaryKeyColumns(entry),\n columnTypes: deriveSyncColumnTypes(entry),\n insertRenderCache: new Map(),\n };\n}\n\n/** The `pgxsinkit_local_meta` key/value table (ADR-0006) under the registry's local schema. */\nexport function getLocalMetaTable(registry: SyncTableRegistry): LocalMetaTable {\n const localSchema = getSyncRegistrySchema(registry);\n const cached = localMetaCache.get(localSchema);\n if (cached) {\n return cached;\n }\n const table = makeTable(localSchema, LOCAL_META_TABLE, {\n key: text(\"key\").primaryKey(),\n value: text(\"value\").notNull(),\n }) as LocalMetaTable;\n localMetaCache.set(localSchema, table);\n return table;\n}\n",
129
136
  "import { eq, like } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/pglite\";\n\nimport { type MutationDiagnostics, type SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { getLocalMetaTable } from \"./local-tables\";\nimport type { MutationDb } from \"./mutation\";\nimport { buildWipeLocalStoreSql, generateLocalSchemaSql, REGISTRY_FINGERPRINT_KEY } from \"./schema\";\n\n// Statements are AUTHORED as Drizzle builders over the meta-table object (rename-safe, typed,\n// schema-qualification handled by the table object) and rendered to text+params here, because they\n// EXECUTE through the caller's raw `MutationDb` seam — the one connection the mutation runtime and\n// its tests own (and mock).\nconst metaQueryBuilder = drizzle.mock();\n\n/**\n * The fingerprint-keyed local store (ADR-0006). The registry fingerprint the local PGlite\n * database was provisioned under is recorded in the local-meta table; comparing it to the\n * current fingerprint on boot is how a registry change is *detected* (rather than a\n * hand-bumped `idb://…-vN` suffix), which drives the drain-then-drop read-cache rebuild.\n */\n\n/** A boot-time registry-version reconciliation outcome (ADR-0006 drain-then-drop). */\nexport interface LocalStoreVersionEvent {\n status: \"rebuilt\" | \"deferred\";\n previousFingerprint: string;\n nextFingerprint: string;\n /** Mutations still owed to the server (pending + sending + failed + quarantined). */\n owedMutations: number;\n}\n\n/** The minimal mutation-runtime surface the version reconciliation needs. */\ninterface VersionReconcileRuntime {\n registryVersion: string;\n readMutationStats: () => Promise<MutationDiagnostics>;\n}\n\n/** The registry fingerprint the local store was last provisioned under, or null if unstamped. */\nexport async function readStoredRegistryFingerprint(\n db: MutationDb,\n registry: SyncTableRegistry,\n): Promise<string | null> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .select({ value: meta.value })\n .from(meta)\n .where(eq(meta.key, REGISTRY_FINGERPRINT_KEY))\n .limit(1)\n .toSQL();\n const result = await db.query<{ value: string }>(query.sql, query.params as unknown[]);\n\n return result.rows[0]?.value ?? null;\n}\n\n/** Meta-key prefix for a persisted `lazy + persistent` group activation (ADR-0021 §2). */\nconst LAZY_ACTIVATION_PREFIX = \"lazy_active:\";\n\n/**\n * The consistency-group keys of `lazy + persistent` groups that were activated on a previous boot\n * (ADR-0021 §2). On boot these are promoted into the eager subscription set, so a once-activated durable\n * lazy group resumes permanently with no per-session re-evaluation. (`ephemeral` activation is never\n * persisted, so it never appears here.)\n */\nexport async function readActivatedLazyGroups(db: MutationDb, registry: SyncTableRegistry): Promise<Set<string>> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .select({ key: meta.key })\n .from(meta)\n .where(like(meta.key, `${LAZY_ACTIVATION_PREFIX}%`))\n .toSQL();\n const result = await db.query<{ key: string }>(query.sql, query.params as unknown[]);\n return new Set(result.rows.map((row) => row.key.slice(LAZY_ACTIVATION_PREFIX.length)));\n}\n\n/** Upsert one meta key — the shared write shape for activations and the fingerprint stamp. */\nasync function upsertMetaValue(db: MutationDb, registry: SyncTableRegistry, key: string, value: string): Promise<void> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .insert(meta)\n .values({ key, value })\n .onConflictDoUpdate({ target: meta.key, set: { value } })\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\n/** Persist a `lazy + persistent` group's activation, so the next boot promotes it to eager (ADR-0021 §2). */\nexport async function writeLazyGroupActivation(\n db: MutationDb,\n registry: SyncTableRegistry,\n groupKey: string,\n): Promise<void> {\n await upsertMetaValue(db, registry, `${LAZY_ACTIVATION_PREFIX}${groupKey}`, \"1\");\n}\n\n/** Clear a persisted lazy activation — an explicit `desync` reverts the group to dormant next boot (ADR-0021 §2). */\nexport async function clearLazyGroupActivation(\n db: MutationDb,\n registry: SyncTableRegistry,\n groupKey: string,\n): Promise<void> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .delete(meta)\n .where(eq(meta.key, `${LAZY_ACTIVATION_PREFIX}${groupKey}`))\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\n/** Stamp the local store with the fingerprint it is now provisioned under. */\nexport async function writeStoredRegistryFingerprint(\n db: MutationDb,\n registry: SyncTableRegistry,\n fingerprint: string,\n): Promise<void> {\n await upsertMetaValue(db, registry, REGISTRY_FINGERPRINT_KEY, fingerprint);\n}\n\n/**\n * Reconcile the local store against the current registry fingerprint (ADR-0006). A fresh\n * (unstamped) store is stamped; an unchanged fingerprint is a no-op. On a change, the read\n * cache is dropped and rebuilt at the new shape **only when nothing is owed locally** —\n * otherwise the rebuild is deferred (and retried on a later boot) so un-flushed/quarantined\n * writes are never silently dropped. The drain happens across sessions: pending writes flush\n * and reconcile during normal use, and the rebuild completes once the journal is clear.\n *\n * An unstamped store is always treated as brand-new. There is no pre-fingerprint-store path:\n * the fingerprint mechanism shipped before launch, so every store in existence was\n * provisioned with it (and a stamped store's journal therefore always has `registry_version`).\n */\nexport async function reconcileLocalStoreVersion<TRegistry extends SyncTableRegistry>(args: {\n db: MutationDb;\n registry: TRegistry;\n runtime: VersionReconcileRuntime;\n onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;\n}): Promise<LocalStoreVersionEvent | null> {\n const { db, registry, runtime } = args;\n const stored = await readStoredRegistryFingerprint(db, registry);\n const current = runtime.registryVersion;\n\n if (stored === current) {\n return null;\n }\n\n if (stored === null) {\n await writeStoredRegistryFingerprint(db, registry, current);\n return null;\n }\n\n return rebuildReadCacheOrDefer(args, stored);\n}\n\n/**\n * The drain-then-drop core (ADR-0006): rebuild the read cache at the current shape when\n * nothing is owed locally, otherwise defer so un-flushed/quarantined writes are never\n * dropped (the drain completes on a later boot).\n */\nasync function rebuildReadCacheOrDefer<TRegistry extends SyncTableRegistry>(\n args: {\n db: MutationDb;\n registry: TRegistry;\n runtime: VersionReconcileRuntime;\n onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;\n },\n previousFingerprint: string,\n): Promise<LocalStoreVersionEvent> {\n const { db, registry, runtime, onSchemaChange } = args;\n const current = runtime.registryVersion;\n const stats = await runtime.readMutationStats();\n const owedMutations = stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount;\n\n if (owedMutations > 0) {\n const event: LocalStoreVersionEvent = {\n status: \"deferred\",\n previousFingerprint,\n nextFingerprint: current,\n owedMutations,\n };\n await onSchemaChange?.(event);\n return event;\n }\n\n await db.exec(buildWipeLocalStoreSql(registry));\n await db.exec(generateLocalSchemaSql(registry));\n await writeStoredRegistryFingerprint(db, registry, current);\n const event: LocalStoreVersionEvent = {\n status: \"rebuilt\",\n previousFingerprint,\n nextFingerprint: current,\n owedMutations: 0,\n };\n await onSchemaChange?.(event);\n return event;\n}\n",
130
- "/**\n * The mutation-journal state machine (ADR-0005, extended by ADR-0006).\n *\n * The runtime is large; previously the legal status transitions were implicit,\n * scattered across SQL writes. This is the one named place that defines them, so the\n * rules are testable and a future change extends a single table. ADR-0006 splits the\n * old single `failed` into transient (retryable `failed`) and permanent (`quarantined`).\n */\n\nexport type MutationStatus = \"pending\" | \"sending\" | \"acked\" | \"failed\" | \"quarantined\" | \"conflicted\" | \"rejected\";\n\n/**\n * Legal transitions. `acked` is terminal at the journal level — it is cleared by\n * reconciliation once the synced echo reaches the acknowledged server timestamp, not\n * by another status transition. `quarantined` is terminal too: the server will never\n * accept the mutation as-is, so it is surfaced (callback + diagnostics), never retried.\n * `conflicted` (ADR-0015) is likewise terminal but a *different* outcome: the write was\n * well-formed but **stale** (an external write interleaved) and the table's `reject-if-stale`\n * policy declined it. The optimistic Overlay is KEPT (the user's edit is not lost) and the\n * conflict is surfaced via `onConflict`; resolution is an ordinary NEW mutation, and `discard`\n * clears the overlay + this entry. It is never retried as-is (the base would still be stale).\n * `rejected` (ADR-0022) is terminal as well, and the inverse of `conflicted` on disposition: the\n * authoritative endpoint declined the whole pessimistic write-**unit** for a business reason (a\n * capacity/quota/uniqueness rule the client could not evaluate locally), so the optimistic Overlay\n * is **auto-discarded** for every member of the unit and the typed reason is surfaced via `onReject`.\n * Never retried (the server's answer is authoritative).\n *\n * - `pending -> sending` a flush claims the row and posts it.\n * - `sending -> acked` the server acknowledged the mutation.\n * - `sending -> failed` transient transport/server error (network, 5xx, …).\n * - `sending -> quarantined` structural 4xx rejection the server will never accept.\n * - `sending -> conflicted` a stale write the reject-if-stale policy declined (ADR-0015).\n * - `sending -> rejected` a business rejection from the authoritative endpoint (ADR-0022).\n * - `sending -> pending` recoverSending re-queues an in-flight row on startup.\n * - `failed -> pending` retryFailed re-queues a failed row.\n * - `failed -> quarantined` the hard max-attempts cap is reached; stop retrying.\n */\nexport const MUTATION_TRANSITIONS = {\n pending: [\"sending\"],\n sending: [\"acked\", \"failed\", \"quarantined\", \"conflicted\", \"rejected\", \"pending\"],\n failed: [\"pending\", \"quarantined\"],\n quarantined: [],\n conflicted: [],\n rejected: [],\n acked: [],\n} as const satisfies Record<MutationStatus, readonly MutationStatus[]>;\n\nexport function isValidMutationTransition(from: MutationStatus, to: MutationStatus): boolean {\n return (MUTATION_TRANSITIONS[from] as readonly MutationStatus[]).includes(to);\n}\n\nexport function assertValidMutationTransition(from: MutationStatus, to: MutationStatus): void {\n if (!isValidMutationTransition(from, to)) {\n throw new Error(`Illegal mutation-journal transition: ${from} -> ${to}`);\n }\n}\n\n/**\n * The hard cap on send attempts (ADR-0005 congestion policy). A mutation that has\n * failed this many times — even with transient-looking errors — is given up on and\n * quarantined, so a permanently-unreachable server never produces an unbounded retry\n * loop. The consumer can raise/lower it via `createSyncClient({ maxMutationAttempts })`.\n */\nexport const DEFAULT_MAX_MUTATION_ATTEMPTS = 10;\n\n/**\n * 4xx statuses that are nonetheless transient: auth (the runtime refreshes the token and\n * retries), request-timeout, too-early, and rate-limit. Everything else in the 4xx range\n * is treated as a structural rejection the server will never accept as-is.\n */\nconst TRANSIENT_CLIENT_ERROR_STATUSES: ReadonlySet<number> = new Set([401, 403, 408, 425, 429]);\n\n/**\n * Classify a flush failure into its durable journal state (ADR-0006 decision 4):\n * - `quarantined` (terminal): a structural 4xx rejection — retrying is pointless, so it\n * is surfaced rather than retry-looped (the silent-data-loss case the runtime *can*\n * catch at send time).\n * - `failed` (retryable): network/transport (no status), any 5xx, or a transient 4xx.\n */\nexport function classifyFailureStatus(httpStatus: number | null | undefined): \"failed\" | \"quarantined\" {\n if (httpStatus == null) {\n return \"failed\";\n }\n\n if (httpStatus >= 400 && httpStatus < 500 && !TRANSIENT_CLIENT_ERROR_STATUSES.has(httpStatus)) {\n return \"quarantined\";\n }\n\n return \"failed\";\n}\n",
131
- "import {\n and,\n desc,\n eq,\n exists,\n getColumns,\n gt,\n inArray,\n is,\n isNotNull,\n isNull,\n lt,\n ne,\n notExists,\n SQL,\n sql,\n} from \"drizzle-orm\";\nimport {\n alias,\n getTableConfig,\n getViewConfig,\n PgDialect,\n type AnyPgTable,\n type PgColumn,\n type PgInsertValue,\n} from \"drizzle-orm/pg-core\";\nimport { drizzle } from \"drizzle-orm/pglite\";\n\nimport {\n getJournalTable,\n getOverlayTable,\n getSyncedLocalTable,\n type JournalTable,\n type OverlayTable,\n} from \"./local-tables\";\n\n// Statements are AUTHORED as Drizzle builders over the journal/overlay/synced table objects\n// (rename-safe, typed, schema-qualification handled by the table objects) and rendered to\n// text+params here, because they EXECUTE through the caller's raw `MutationDb` seam — the one\n// connection the mutation runtime and its tests own (and mock). `drizzle.mock()` builds queries\n// without a connection; `queryDialect` renders standalone `sql` fragments the builders cannot\n// express (compound CTE shapes, derived-table wrappers).\nconst queryBuilder = drizzle.mock();\nconst queryDialect = new PgDialect();\n\n/**\n * Strip the two internal overlay columns that appear on _read_model views\n * (`overlay_kind`, `local_updated_at_us`) from any user-supplied input or\n * patch object before it is serialised into a mutation payload. Callers\n * that spread a view row directly into a create/update call would otherwise\n * hit `TypeError: Do not know how to serialize a BigInt` because\n * `local_updated_at_us` is stored as a native JS `bigint`.\n */\nfunction stripReadModelOverlayFields<T>(value: T): T {\n if (value === null || typeof value !== \"object\") return value;\n const obj = value as Record<string, unknown>;\n if (!(\"overlay_kind\" in obj) && !(\"local_updated_at_us\" in obj)) return value;\n const { overlay_kind: _ok, local_updated_at_us: _lu, ...rest } = obj;\n return rest as T;\n}\n\n/**\n * JSON replacer that serialises `bigint` values as strings. PostgreSQL\n * accepts string literals for BIGINT columns, and JSON has no native bigint\n * type, so this is the safest cross-boundary representation.\n */\nfunction bigintReplacer(_key: string, value: unknown): unknown {\n return typeof value === \"bigint\" ? String(value) : value;\n}\n\nfunction jsonStringifyPayload(value: unknown): string {\n return JSON.stringify(value, bigintReplacer);\n}\n\nimport type {\n BatchMutationAck,\n MutationAck,\n MutationDiagnostics,\n MutationRejection,\n SyncTableCreateInput,\n SyncTableEntry,\n SyncTableName,\n SyncTableRecord,\n SyncTableRegistry,\n SyncTableUpdateInput,\n WriteMode,\n} from \"@pgxsinkit/contracts\";\nimport {\n batchMutationErrorSchema,\n buildOverlayResolutionBarrier,\n fingerprintRegistry,\n getProjectedColumns as getProjectedTableColumns,\n getSyncRegistrySchema,\n maybeQuoteIdentifier,\n quoteIdentifier,\n resolveServerVersionColumnName,\n} from \"@pgxsinkit/contracts\";\n\nimport { syncDebug } from \"./debug\";\nimport {\n assertValidMutationTransition,\n classifyFailureStatus,\n DEFAULT_MAX_MUTATION_ATTEMPTS,\n type MutationStatus,\n} from \"./mutation-state\";\n\nexport type { MutationStatus } from \"./mutation-state\";\nexport type MutationKind = \"create\" | \"update\" | \"delete\";\n\n/**\n * The dynamic write-unit tag (ADR-0022 §2) a `transaction({ mode })` block stamps onto the mutations\n * authored within it: a shared `id` grouping the co-committed mutations, and the unit's `mode`. Persisted\n * on each journal row (`write_unit` / `write_mode`); absent for the default path, where the flusher derives\n * mode + unit from the table's static consistency group.\n */\nexport interface WriteUnit {\n id: string;\n mode: WriteMode;\n}\n\nexport type MutationBatchItem<TRegistry extends SyncTableRegistry> = {\n [TKey in SyncTableName<TRegistry>]:\n | {\n table: TKey;\n kind: \"create\";\n input: SyncTableCreateInput<TRegistry, TKey>;\n }\n | {\n table: TKey;\n kind: \"update\";\n entityKey: Record<string, string>;\n patch: SyncTableUpdateInput<TRegistry, TKey>;\n /**\n * A **blind** update (ADR-0022 addendum): plan a journal row ONLY — no local base row is required\n * and no optimistic overlay is written. Set exclusively by the transaction handle's `updateBlind`;\n * valid only when the write routes pessimistically (a `pessimistic` unit, or a statically-pessimistic\n * table), and rejected at enqueue otherwise. Absent/false for an ordinary update.\n */\n blind?: boolean;\n }\n | {\n table: TKey;\n kind: \"delete\";\n entityKey: Record<string, string>;\n };\n}[SyncTableName<TRegistry>];\n\nexport const DEFAULT_FLUSH_BATCH_SIZE = 100;\n\nexport interface MutationDetail {\n tableName: string;\n entityKey: Record<string, string>;\n mutationId: string;\n mutationSeq: number;\n mutationKind: MutationKind;\n status: MutationStatus;\n attemptCount: number;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n updatedAtUs: string;\n /** Registry fingerprint (ADR-0004) the mutation was authored under, or null if unstamped. */\n registryVersion: string | null;\n}\n\nexport interface MutationDb {\n exec: (sql: string) => Promise<unknown>;\n query: <TRow extends Record<string, unknown> = Record<string, unknown>>(\n sql: string,\n params?: unknown[],\n ) => Promise<{ rows: TRow[] }>;\n}\n\nexport interface CreateMutationRuntimeOptions<TRegistry extends SyncTableRegistry> {\n db: MutationDb;\n registry: TRegistry;\n writeUrl: string;\n getAuthToken?: () => Promise<string | undefined>;\n /** Static headers added to every write request (e.g. a Supabase Cloud `apikey`); see {@link CreateSyncClientOptions.requestHeaders}. */\n requestHeaders?: Record<string, string>;\n /**\n * Registry fingerprint (ADR-0004) stamped onto each enqueued mutation as its\n * `registry_version`, so a version-boundary crossing is known before sending (ADR-0006).\n */\n registryVersion?: string;\n /**\n * Hard cap on send attempts before a still-failing mutation is quarantined\n * (ADR-0005 congestion policy). Defaults to {@link DEFAULT_MAX_MUTATION_ATTEMPTS}.\n */\n maxMutationAttempts?: number;\n /**\n * Max mutations drained per flush HTTP request; a flush loops slices until the journal is empty.\n * Defaults to {@link DEFAULT_FLUSH_BATCH_SIZE}. Primarily a test seam (a small value exercises the\n * multi-slice drain path without enqueueing hundreds of mutations).\n */\n flushBatchSize?: number;\n /**\n * Invoked after a flush whenever mutations transition to `quarantined` (terminal,\n * permanently rejected). Receives the newly-quarantined details so the app can surface\n * them, then either re-author + resubmit or roll back via {@link MutationRuntime.discardQuarantined}\n * (clears the kept overlay + quarantined journal rows, so the entity accepts new mutations again).\n * The library never silently drops these (ADR-0006 decision 4).\n */\n onQuarantine?: (quarantined: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked after a flush whenever mutations transition to `conflicted` — a stale write the\n * server declined under the `reject-if-stale` Conflict policy (ADR-0015). Distinct from\n * `onQuarantine` (structural rejection): the optimistic Overlay is KEPT, so the app surfaces a\n * resolution/diff UI and resolves each as a new write (or `discardConflict`s it). Never silent.\n */\n onConflict?: (conflicted: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked after an authoritative (pessimistic) flush whenever a write-unit was `rejected` (ADR-0022) —\n * a business decline the client could not evaluate locally (capacity/quota/uniqueness). The inverse of\n * `onConflict`: the optimistic Overlay was **auto-discarded** for every member of the unit, so the app\n * surfaces the typed reason (e.g. \"full\") rather than a resolve/diff UI. Never silent.\n */\n onReject?: (rejected: MutationDetail[]) => void | Promise<void>;\n}\n\ninterface TableContext {\n key: string;\n entry: SyncTableEntry<AnyPgTable>;\n readModel: string;\n syncedTable: string;\n overlayTable: string;\n journalTable: string;\n journalSequence: string;\n pkColumnNames: string[];\n pkPropertyKeys: string[];\n /**\n * The Server version (ADR-0010) column name (e.g. `updated_at_us`) and its drizzle property key,\n * resolved from the table's managed fields. Used to capture the Base server version (ADR-0015) at\n * enqueue — the value the user's edit was authored against. `null` would mean no Server version,\n * which registry validation already forbids for a writable table.\n */\n serverVersionColumnName: string | null;\n serverVersionPropertyKey: string | null;\n /**\n * Property keys of the table's `nowMicroseconds` managed fields (governance), resolved generically\n * rather than by the `createdAtUs`/`updatedAtUs` naming convention. The optimistic overlay stamps\n * these client-side so a custom-named managed timestamp (e.g. a Server version not called\n * `updated_at_us`) is materialised correctly — closing the split interpreter between the generic\n * server applier (which reads governance) and the local path (ADR-0004).\n *\n * - `managedNowMicrosecondsPropertyKeys` — every `nowMicroseconds` field, stamped on create.\n * - `updateManagedNowMicrosecondsPropertyKeys` — those that apply on update, re-stamped each update.\n *\n * These augment, and never remove, the convention fill in `createOptimisticRecordFromContext`,\n * which remains the safety net for a `created_at_us`/`updated_at_us` column that carries a SQL\n * `DEFAULT` (unmaterialisable client-side) yet is not declared a managed field.\n */\n managedNowMicrosecondsPropertyKeys: string[];\n updateManagedNowMicrosecondsPropertyKeys: string[];\n /**\n * The table's `authClaim` managed fields that apply on create (governance), each with the JSON\n * claimPath it stamps from. The server stamps these from the verified request claims, so they are\n * stripped from the create input type and never sent in the flushed payload. But the optimistic\n * overlay still needs a value — such a column is typically `NOT NULL` (an owner/author/created_by) —\n * so the runtime fills it client-side from the decoded JWT claim at the same path (the same value the\n * server will stamp), so the local row renders attributed immediately and never flips on convergence.\n * (`auth.uid()` is just `claimPath: [\"sub\"]`, so this one path covers it.)\n */\n managedAuthClaimCreateFields: Array<{ propertyKey: string; claimPath: string[] }>;\n recordIncludesOverlayState: boolean;\n columns: Array<{\n propertyKey: string;\n column: ReturnType<typeof getProjectedTableColumns<AnyPgTable>>[number][\"column\"];\n }>;\n /**\n * The generated local relations as runtime Drizzle table objects (local-tables.ts), so the\n * runtime's statements are AUTHORED as tier-① builders while still EXECUTING through the raw\n * `MutationDb` seam. Journal fixed columns are camelCase-keyed; per-entry PK columns are keyed\n * by DB column name; overlay/synced columns are keyed by drizzle property key.\n */\n tables: {\n synced: AnyPgTable;\n overlay: OverlayTable;\n journal: JournalTable;\n };\n /** Overlay columns keyed by property key (`getColumns` memo — overlay keys are property keys, not DB names). */\n overlayColumnsByPropertyKey: Record<string, PgColumn>;\n /** Synced read-cache columns keyed by property key. */\n syncedColumnsByPropertyKey: Record<string, PgColumn>;\n /** The entry's PK columns ON THE OVERLAY, resolved by DB column name (ordered like `pkColumnNames`). */\n overlayPkColumns: PgColumn[];\n /** The entry's PK columns ON THE SYNCED table, resolved by DB column name (ordered like `pkColumnNames`). */\n syncedPkColumns: PgColumn[];\n /** The Server version column ON THE SYNCED table (ADR-0010), or null when the table declares none. */\n syncedServerVersionColumn: PgColumn | null;\n /**\n * Memoized render of the reconcile idle probe (the per-tick hot statement): built once per\n * context so every convergence tick pays only a plain `db.query` of a cached string.\n */\n reconcileIdleProbe?: { sql: string; params: unknown[] };\n}\n\nexport interface MutationRuntime<TRegistry extends SyncTableRegistry> {\n /** The registry fingerprint (ADR-0004) this runtime stamps onto enqueued mutations. */\n registryVersion: string;\n create: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n input: SyncTableCreateInput<TRegistry, TKey>,\n ) => Promise<void>;\n update: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n patch: SyncTableUpdateInput<TRegistry, TKey>,\n ) => Promise<void>;\n delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;\n /**\n * Enqueue an atomic batch of mutations. An optional {@link WriteUnit} tags every row of the batch as one\n * dynamic write-unit (ADR-0022 §2) — the `transaction({ mode })` block passes it; the per-table\n * `create`/`update`/`delete` helpers do not (their write-mode comes from the static group at flush).\n */\n batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>, unit?: WriteUnit) => Promise<void>;\n /**\n * Discard a `conflicted` entity (ADR-0015): clear its conflicted journal entries and the kept\n * optimistic Overlay, so the Read model falls back to the synced (server) value. Use when the user\n * abandons their stale edit instead of resolving it as a new write. No-op for an entity with no\n * conflicted entry.\n */\n discardConflict: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n /**\n * Discard a `quarantined` entity (ADR-0006): clear its quarantined journal entries and the kept\n * optimistic Overlay, so the Read model falls back to the synced (server) value and the entity\n * accepts new mutations again. The rollback path for a permanently-rejected write (e.g. an RLS\n * policy denial routed to quarantine). Symmetric to {@link discardConflict}. No-op for an entity\n * with no quarantined entry; the overlay is kept when another still-owed write depends on it.\n */\n discardQuarantined: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n flush: (table?: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * Flush one pessimistic write-unit (ADR-0022) to the authoritative endpoint and apply its per-mutation\n * result inline: `acked` clears via the synced echo, `conflicted` keeps the overlay (surfaced), and\n * `rejected` auto-discards the overlay for the whole unit (surfaced via `onReject`). A foreground\n * operation — it resolves once the server has decided. Throws on transport failure (the overlay is kept\n * for a retry). Returns the server acks. Used by the client `transaction({ mode: \"pessimistic\" })` block.\n */\n flushUnit: (unitId: string) => Promise<{ acks: MutationAck[] }>;\n reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;\n retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;\n recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;\n readMutationStats: (table?: SyncTableName<TRegistry>) => Promise<MutationDiagnostics>;\n readMutationDetails: (table?: SyncTableName<TRegistry>) => Promise<MutationDetail[]>;\n createOptimisticRecord: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n input: SyncTableCreateInput<TRegistry, TKey>,\n ) => SyncTableRecord<TRegistry, TKey>;\n}\n\nexport function nowMicroseconds(): string {\n return (BigInt(Date.now()) * 1000n).toString();\n}\n\n/**\n * Best-effort decode of a JWT's claims payload, for stamping `authClaim` managed fields into the\n * optimistic overlay (the value the server will independently stamp from the same claim path). This is\n * **not** a verification — the token is trusted only for a local, optimistic projection that the server\n * re-stamps authoritatively on apply; a forged claim could never make the server attribute the row\n * differently. Returns `undefined` for a malformed token.\n */\nexport function decodeJwtClaims(token: string): Record<string, unknown> | undefined {\n const segments = token.split(\".\");\n if (segments.length < 2 || !segments[1]) {\n return undefined;\n }\n try {\n const normalized = segments[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = normalized.padEnd(normalized.length + ((4 - (normalized.length % 4)) % 4), \"=\");\n const binary = atob(padded);\n const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));\n const payload = JSON.parse(new TextDecoder().decode(bytes)) as unknown;\n return typeof payload === \"object\" && payload !== null ? (payload as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Read a claim at a JSON path out of a decoded claims object, returning it as a string (the form the\n * optimistic overlay column expects, mirroring the server's `jsonb #>>` text extraction). Returns\n * `undefined` if the path is absent or the leaf is not a string/number.\n */\nexport function readJwtClaimPath(claims: Record<string, unknown>, claimPath: string[]): string | undefined {\n let cursor: unknown = claims;\n for (const segment of claimPath) {\n if (typeof cursor !== \"object\" || cursor === null) {\n return undefined;\n }\n cursor = (cursor as Record<string, unknown>)[segment];\n }\n if (typeof cursor === \"string\") {\n return cursor;\n }\n return typeof cursor === \"number\" ? String(cursor) : undefined;\n}\n\nexport function computeBackoffDelayMs(attemptCount: number) {\n const exponent = Math.max(attemptCount - 1, 0);\n return Math.min(1000 * 2 ** exponent, 30_000);\n}\n\n/**\n * Retry delay with equal jitter around the {@link computeBackoffDelayMs} ceiling: half\n * the ceiling plus a random share of the other half. Spreads retries so a fleet of\n * clients does not stampede the server in lockstep after an outage (ADR-0005 congestion\n * policy). `random` is injectable for deterministic tests.\n */\nexport function computeRetryDelayMs(attemptCount: number, random: () => number = Math.random) {\n const ceiling = computeBackoffDelayMs(attemptCount);\n return Math.round(ceiling / 2 + random() * (ceiling / 2));\n}\n\nexport function computeNextRetryAtUs(nowUs: string, attemptCount: number, random: () => number = Math.random) {\n return (BigInt(nowUs) + BigInt(computeRetryDelayMs(attemptCount, random)) * 1000n).toString();\n}\n\nexport function createMutationRuntime<TRegistry extends SyncTableRegistry>(\n options: CreateMutationRuntimeOptions<TRegistry>,\n): MutationRuntime<TRegistry> {\n const resolveAuthToken = async () => {\n if (options.getAuthToken) {\n return await options.getAuthToken();\n }\n\n return undefined;\n };\n\n // The decoded JWT claims for stamping `authClaim` create-managed fields into the optimistic overlay\n // (the same value the server stamps from the same claim path). Resolved only when a create needs it\n // (a table with such a field), so tokenless registries never pay a token lookup.\n const resolveAuthClaims = async (): Promise<Record<string, unknown> | undefined> => {\n const token = await resolveAuthToken();\n return token ? decodeJwtClaims(token) : undefined;\n };\n\n const tableContexts = buildTableContexts(options.registry);\n const maxMutationAttempts = options.maxMutationAttempts ?? DEFAULT_MAX_MUTATION_ATTEMPTS;\n const flushBatchSize = options.flushBatchSize ?? DEFAULT_FLUSH_BATCH_SIZE;\n // The fingerprint (ADR-0004) stamped onto each enqueued mutation (ADR-0006). The runtime\n // owns the registry, so it derives this itself; an explicit override is honoured for tests.\n const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);\n let flushQueue = Promise.resolve();\n\n const getTableContext = (table: SyncTableName<TRegistry>) => {\n const context = tableContexts[table];\n\n if (!context) {\n throw new Error(`Unknown mutation table: ${String(table)}`);\n }\n\n return context;\n };\n\n const runInTransaction = async (operation: () => Promise<void>) => {\n await options.db.exec(\"BEGIN\");\n\n try {\n await operation();\n await options.db.exec(\"COMMIT\");\n } catch (error) {\n await options.db.exec(\"ROLLBACK\");\n throw error;\n }\n };\n\n const normalizeBatchItem = (\n item: MutationBatchItem<TRegistry>,\n order: number,\n claims: Record<string, unknown> | undefined,\n ): NormalizedBatchItem => {\n const context = getTableContext(item.table as SyncTableName<TRegistry>);\n const mutationId = globalThis.crypto.randomUUID();\n const nowUs = nowMicroseconds();\n\n switch (item.kind) {\n case \"create\": {\n const strippedInput = stripReadModelOverlayFields(item.input);\n const optimisticRecord = ensureRecord(createOptimisticRecordFromContext(context, strippedInput, claims));\n const entityKey = buildEntityKeyFromRecord(context, optimisticRecord);\n\n return {\n context,\n kind: \"create\",\n entityKey,\n entityKeyJson: serializeEntityKey(entityKey),\n optimisticRecord,\n input: strippedInput,\n mutationId,\n nowUs,\n order,\n };\n }\n case \"update\": {\n const entityKey = normalizeEntityKey(context, item.entityKey);\n const patch = ensureRecord(stripReadModelOverlayFields(item.patch));\n\n return {\n context,\n kind: \"update\",\n entityKey,\n entityKeyJson: serializeEntityKey(entityKey),\n patch,\n blind: item.blind ?? false,\n mutationId,\n nowUs,\n order,\n };\n }\n case \"delete\": {\n const entityKey = normalizeEntityKey(context, item.entityKey);\n\n return {\n context,\n kind: \"delete\",\n entityKey,\n entityKeyJson: serializeEntityKey(entityKey),\n mutationId,\n nowUs,\n order,\n };\n }\n }\n };\n\n const enqueueBatch = async (\n items: ReadonlyArray<MutationBatchItem<TRegistry>>,\n unit?: WriteUnit,\n ): Promise<string[]> => {\n if (items.length === 0) {\n return [];\n }\n\n // The distinct pessimistic write-unit ids this enqueue tagged — returned so the caller can\n // foreground-route them to the authoritative endpoint (ADR-0022). Empty for a purely optimistic batch.\n const pessimisticUnitIds = new Set<string>();\n\n // Resolve the decoded claims once per batch, but only if a create actually needs them (a target\n // table with an `authClaim` create-managed field). Avoids a token lookup for every other write.\n const needsAuthClaims = items.some(\n (item) =>\n item.kind === \"create\" &&\n getTableContext(item.table as SyncTableName<TRegistry>).managedAuthClaimCreateFields.length > 0,\n );\n const claims = needsAuthClaims ? await resolveAuthClaims() : undefined;\n\n const normalizedItems = items.map((item, index) => normalizeBatchItem(item, index, claims));\n const batchGroups = new Map<string, { context: TableContext; items: NormalizedBatchItem[] }>();\n\n for (const item of normalizedItems) {\n const existing = batchGroups.get(item.context.key);\n\n if (existing) {\n existing.items.push(item);\n continue;\n }\n\n batchGroups.set(item.context.key, {\n context: item.context,\n items: [item],\n });\n }\n\n for (const { context, items: groupedItems } of batchGroups.values()) {\n groupedItems.sort((left, right) => left.order - right.order);\n const uniqueEntities = dedupeBatchEntities(groupedItems);\n const latestMutationStates = await readLatestMutationStates(options.db, context, uniqueEntities);\n const currentRecordStates = await readCurrentRecordStates(options.db, context, uniqueEntities);\n const entityStates = new Map<string, BatchEntityState>();\n\n for (const entity of uniqueEntities) {\n const latestState = latestMutationStates.get(entity.entityKeyJson);\n const currentState = currentRecordStates.get(entity.entityKeyJson);\n\n entityStates.set(entity.entityKeyJson, {\n entityKey: entity.entityKey,\n entityKeyJson: entity.entityKeyJson,\n record: currentState ? extractRecordFromState(context, currentState) : null,\n overlayKind: currentState?.overlayKind ?? null,\n localUpdatedAtUs: currentState?.localUpdatedAtUs ?? null,\n latestMutationSeq: latestState?.latestMutationSeq ?? null,\n latestMutationKind: latestState?.latestMutationKind ?? null,\n latestMutationStatus: latestState?.latestMutationStatus ?? null,\n });\n }\n\n const plannedMutations: PlannedMutationInsert[] = [];\n const plannedOverlays = new Map<string, PlannedOverlayUpsert>();\n\n for (const item of groupedItems) {\n const entityState = entityStates.get(item.entityKeyJson);\n\n if (!entityState) {\n throw new Error(`Missing batch state for table ${context.key}`);\n }\n\n switch (item.kind) {\n case \"create\": {\n if ((entityState.latestMutationSeq ?? 0) !== 0) {\n throw new Error(`${context.key} already has queued mutations`);\n }\n\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"create\",\n payloadJson: jsonStringifyPayload({\n kind: \"create\",\n value: item.input,\n }),\n nowUs: item.nowUs,\n // A create has no Base server version (ADR-0015): its conflict is a PK collision, a\n // separate concern from the stale-write check.\n baseServerVersion: null,\n });\n\n entityState.record = item.optimisticRecord;\n entityState.overlayKind = \"pending_create\";\n entityState.localUpdatedAtUs = item.nowUs;\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"create\";\n entityState.latestMutationStatus = \"pending\";\n plannedOverlays.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n record: item.optimisticRecord,\n overlayKind: \"pending_create\",\n localUpdatedAtUs: item.nowUs,\n });\n break;\n }\n case \"update\": {\n if (item.blind) {\n // ADR-0022 addendum — a BLIND update: the write target is excluded from the actor's read\n // shape (its rows never stream here), so there is no local base row to seed and no optimistic\n // state to show. It is meaningful ONLY when the write routes to the authoritative endpoint (the\n // /unit expander is authoritative): an optimistic-routed blind write has nothing to converge, so\n // it is rejected at enqueue. The `unit` fixes the route inside a `transaction` block; a plain\n // enqueue on a statically-pessimistic table earns its own pessimistic unit downstream.\n const routesPessimistic = unit ? unit.mode === \"pessimistic\" : context.entry.writeMode === \"pessimistic\";\n if (!routesPessimistic) {\n throw new Error(\n `${context.key}: updateBlind requires a pessimistic write unit — use transaction({ mode: \"pessimistic\" }) (an optimistic blind write has nothing to show and no base to converge)`,\n );\n }\n\n // KEEP the already-queued-for-deletion guard (journal-derived; needs no local record).\n if (entityState.latestMutationKind === \"delete\" && entityState.latestMutationStatus !== \"acked\") {\n throw new Error(`${context.key} is already queued for deletion`);\n }\n\n // Plan a journal row ONLY — no overlay, so nothing enters the read model and nothing can linger\n // there. `baseServerVersion: null`: the /unit expander is authoritative, there is no base to\n // capture. The `pessimistic-blind` marker keeps the row off the optimistic flusher and lets\n // reconcile retire it after ack WITHOUT a synced echo (there is no visible row to converge).\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"update\",\n payloadJson: jsonStringifyPayload({\n kind: \"update\",\n patch: item.patch,\n }),\n nowUs: item.nowUs,\n baseServerVersion: null,\n writeMode: \"pessimistic-blind\",\n });\n\n // Advance only the journal-derived tracking (no record/overlay): so a later same-batch item on\n // this entity chains in author order and sees the pending blind write.\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"update\";\n entityState.latestMutationStatus = \"pending\";\n break;\n }\n\n if (!entityState.record) {\n throw new Error(`${context.key} not found in local read model`);\n }\n\n if (entityState.latestMutationKind === \"delete\" && entityState.latestMutationStatus !== \"acked\") {\n throw new Error(`${context.key} is already queued for deletion`);\n }\n\n // ADR-0015: capture the Base server version BEFORE the record is replaced by the\n // optimistic value below (which overwrites the Server version with the client clock).\n const updateBaseServerVersion = captureChainHeadBase(context, entityState);\n const overlayKind = entityState.overlayKind === \"pending_create\" ? \"pending_create\" : \"pending_update\";\n const optimisticRecord = ensureRecord(\n buildOptimisticRecord(\n context,\n {\n ...entityState.record,\n ...item.patch,\n // Re-stamp the on-update managed timestamp(s) generically (governance-driven) — for a\n // convention table this is exactly `updatedAtUs`, for a custom-named Server version\n // it is that column, so the optimistic row never carries a stale managed value.\n ...buildUpdateManagedNowStamp(context, item.nowUs),\n },\n {\n overlayKind,\n localUpdatedAtUs: item.nowUs,\n },\n ),\n );\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"update\",\n payloadJson: jsonStringifyPayload({\n kind: \"update\",\n patch: item.patch,\n }),\n nowUs: item.nowUs,\n baseServerVersion: updateBaseServerVersion,\n });\n\n entityState.record = optimisticRecord;\n entityState.overlayKind = overlayKind;\n entityState.localUpdatedAtUs = item.nowUs;\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"update\";\n entityState.latestMutationStatus = \"pending\";\n plannedOverlays.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n record: optimisticRecord,\n overlayKind,\n localUpdatedAtUs: item.nowUs,\n });\n break;\n }\n case \"delete\": {\n if (!entityState.record) {\n throw new Error(`${context.key} not found in local read model`);\n }\n\n if (entityState.latestMutationKind === \"delete\" && entityState.latestMutationStatus !== \"acked\") {\n throw new Error(`${context.key} is already queued for deletion`);\n }\n\n const deleteBaseServerVersion = captureChainHeadBase(context, entityState);\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"delete\",\n payloadJson: jsonStringifyPayload({\n kind: \"delete\",\n entityKey: item.entityKey,\n }),\n nowUs: item.nowUs,\n baseServerVersion: deleteBaseServerVersion,\n });\n\n entityState.overlayKind = \"pending_delete\";\n entityState.localUpdatedAtUs = item.nowUs;\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"delete\";\n entityState.latestMutationStatus = \"pending\";\n plannedOverlays.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n record: entityState.record,\n overlayKind: \"pending_delete\",\n localUpdatedAtUs: item.nowUs,\n });\n break;\n }\n }\n }\n\n // ADR-0022: an explicit unit (from a `transaction` block) tags the whole batch; otherwise a\n // statically-`pessimistic` table earns its own per-enqueue unit, so its writes route to the\n // authoritative endpoint too. An optimistic table with no explicit unit stays untagged.\n const effectiveUnit: WriteUnit | undefined =\n unit ??\n (context.entry.writeMode === \"pessimistic\"\n ? { id: globalThis.crypto.randomUUID(), mode: \"pessimistic\" }\n : undefined);\n if (effectiveUnit?.mode === \"pessimistic\") {\n pessimisticUnitIds.add(effectiveUnit.id);\n }\n await insertMutationsBulk(options.db, context, plannedMutations, registryVersion, effectiveUnit);\n await upsertOverlayRecordsBulk(options.db, context, [...plannedOverlays.values()]);\n }\n\n return [...pessimisticUnitIds];\n };\n\n const runFlush = async (table?: SyncTableName<TRegistry>) => {\n const affectedContexts = new Map<string, TableContext>();\n const quarantinedMutationIds = new Set<string>();\n const conflictedMutationIds = new Set<string>();\n let processedCount = 0;\n\n do {\n const batchResult = await flushBatch(\n options.db,\n tableContexts as Record<string, TableContext>,\n options.writeUrl,\n maxMutationAttempts,\n flushBatchSize,\n table,\n resolveAuthToken,\n options.requestHeaders,\n );\n\n processedCount = batchResult.processedCount;\n\n for (const context of batchResult.affectedContexts) {\n affectedContexts.set(context.key, context);\n }\n\n for (const mutationId of batchResult.quarantinedMutationIds) {\n quarantinedMutationIds.add(mutationId);\n }\n\n for (const mutationId of batchResult.conflictedMutationIds) {\n conflictedMutationIds.add(mutationId);\n }\n } while (processedCount > 0);\n\n for (const context of affectedContexts.values()) {\n await reconcileTable(options.db, context);\n }\n\n // Surface newly-quarantined mutations after reconciliation so the app never has to\n // poll for permanently-rejected writes (ADR-0006 decision 4). Never silent loss.\n if (quarantinedMutationIds.size > 0 && options.onQuarantine) {\n const details = await readMutationDetailsForContexts(\n options.db,\n [...affectedContexts.values()],\n quarantinedMutationIds,\n );\n\n if (details.length > 0) {\n await options.onQuarantine(details);\n }\n }\n\n // Surface newly-conflicted (stale) writes (ADR-0015). The optimistic Overlay is kept, so the app\n // can show a resolution/diff UI and resolve each as a new write (or discard it). Never silent.\n if (conflictedMutationIds.size > 0 && options.onConflict) {\n const details = await readMutationDetailsForContexts(\n options.db,\n [...affectedContexts.values()],\n conflictedMutationIds,\n );\n\n if (details.length > 0) {\n await options.onConflict(details);\n }\n }\n };\n\n const runtime: MutationRuntime<TRegistry> = {\n registryVersion,\n create: async (table, input) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch([{ table, kind: \"create\", input }]);\n });\n // A statically-`pessimistic` table foreground-routes its write to the authoritative endpoint\n // (ADR-0022) — the write is server-authoritative, so it is sent immediately, not left for the\n // optimistic convergence loop (which skips pessimistic rows).\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n },\n update: async (table, entityKeyInput, patch) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch([{ table, kind: \"update\", entityKey: entityKeyInput, patch }]);\n });\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n },\n delete: async (table, entityKeyInput) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch([{ table, kind: \"delete\", entityKey: entityKeyInput }]);\n });\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n },\n batch: async (items, unit) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch(items, unit);\n });\n // An explicit unit (from a `transaction` block) is flushed by the caller; only foreground-route the\n // units a plain `batch()` generated for statically-pessimistic tables.\n if (!unit) {\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n }\n },\n discardConflict: async (table, entityKeyInput) => {\n const context = getTableContext(table);\n const entityKey = normalizeEntityKey(context, entityKeyInput);\n const entityKeyJson = serializeEntityKey(entityKey);\n\n // discardTerminalEntity owns its own transaction (like reconcileTable), so it is not wrapped.\n await discardTerminalEntity(options.db, context, entityKey, entityKeyJson, \"conflicted\");\n },\n discardQuarantined: async (table, entityKeyInput) => {\n const context = getTableContext(table);\n const entityKey = normalizeEntityKey(context, entityKeyInput);\n const entityKeyJson = serializeEntityKey(entityKey);\n\n // Symmetric to discardConflict — retire the entity's `quarantined` journal rows and clear the\n // kept overlay behind the same owed-guard, so a permanently-rejected write is a real rollback.\n await discardTerminalEntity(options.db, context, entityKey, entityKeyJson, \"quarantined\");\n },\n flush: async (table) => {\n const nextFlush = flushQueue.then(() => runFlush(table));\n flushQueue = nextFlush.catch(() => undefined);\n await nextFlush;\n },\n flushUnit: async (unitId) => {\n const contexts = Object.values(tableContexts).filter((context): context is TableContext => context != null);\n const unitRows = await readUnitPendingRows(options.db, contexts, unitId);\n if (unitRows.length === 0) {\n return { acks: [] };\n }\n\n // Prepare the unit's rows (entity key + envelope payload) and group them by table.\n const prepared: PreparedBatchRow[] = [];\n const byContext = new Map<string, PreparedBatchRow[]>();\n for (const row of unitRows) {\n const context = tableContexts[row.tableKey];\n if (!context) {\n continue;\n }\n const entityKey = JSON.parse(row.entityKeyJson) as Record<string, string>;\n const rawPayload = JSON.parse(row.payloadJson) as Record<string, unknown>;\n const preparedRow: PreparedBatchRow = {\n ...row,\n context,\n entityKey,\n envelopePayload:\n row.mutationKind === \"delete\"\n ? entityKey\n : toSqlColumnPayload(\n context,\n stripManagedFields(\n context,\n (rawPayload[\"value\"] ?? rawPayload[\"patch\"] ?? rawPayload) as Record<string, unknown>,\n row.mutationKind as \"create\" | \"update\",\n ),\n ),\n sqlTableName: context.entry.shape?.tableName ?? context.key,\n };\n prepared.push(preparedRow);\n const list = byContext.get(context.key);\n if (list) {\n list.push(preparedRow);\n } else {\n byContext.set(context.key, [preparedRow]);\n }\n }\n\n // Mark every member sending (persist the resolved Base server version, like the batch path).\n const sentAtUs = nowMicroseconds();\n for (const rows of byContext.values()) {\n await applyMutationStatusUpdates(\n options.db,\n rows[0]!.context,\n rows.map((row) => ({\n mutationId: row.mutationId,\n status: \"sending\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: sentAtUs,\n sentAtUs,\n replaceSentAtUs: true,\n baseServerVersion: row.baseServerVersion,\n replaceBaseServerVersion: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: null,\n conflictReason: null,\n })),\n );\n }\n\n const mutations = prepared.map((row) => ({\n tableName: row.sqlTableName,\n entityKey: row.entityKey,\n mutationId: row.mutationId,\n mutationSeq: row.mutationSeq,\n kind: row.mutationKind as \"create\" | \"update\" | \"delete\",\n payload: row.envelopePayload,\n clientTimestampUs: sentAtUs,\n ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),\n }));\n\n const url = resolveAuthoritativeMutationUrl(options.writeUrl);\n let acksByMutationId: Map<string, BatchMutationAck[\"acks\"][number]>;\n\n try {\n const authToken = await options.getAuthToken?.();\n let response = await fetch(url, {\n method: \"POST\",\n headers: buildRequestHeaders(authToken, options.requestHeaders),\n body: jsonStringifyPayload({ writeUnit: unitId, mutations }),\n });\n\n if ([401, 403].includes(response.status) && options.getAuthToken) {\n response = await fetch(url, {\n method: \"POST\",\n headers: buildRequestHeaders(await options.getAuthToken(), options.requestHeaders),\n body: jsonStringifyPayload({ writeUnit: unitId, mutations }),\n });\n }\n\n if (!response.ok) {\n const text = await response.text();\n throw new MutationRequestError(\n text.length > 0 ? text : `Authoritative write responded with ${response.status}`,\n response.status,\n parseBatchRejections(text),\n );\n }\n\n const responseJson = (await response.json()) as BatchMutationAck;\n acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));\n } catch (error) {\n // A pessimistic write is foreground: it never reached the server (transport / non-2xx), so the\n // unit did not happen. Mark it failed — KEEPING the optimistic overlay so a retry can resend — and\n // rethrow so the caller surfaces it. There is no background retry for pessimistic units.\n const failedAtUs = nowMicroseconds();\n const httpStatus = error instanceof MutationRequestError ? error.status : null;\n const errorMessage = error instanceof Error ? error.message : \"Authoritative write failed\";\n for (const rows of byContext.values()) {\n await applyMutationStatusUpdates(\n options.db,\n rows[0]!.context,\n rows.map((row) => {\n const attemptCount = row.attemptCount + 1;\n const outcome = resolveBatchFailureOutcome(attemptCount, maxMutationAttempts, failedAtUs);\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: errorMessage,\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: httpStatus,\n conflictReason: null,\n };\n }),\n );\n }\n throw error;\n }\n\n // Apply each member's ack.\n const ackedAtUs = nowMicroseconds();\n const failedAtUs = nowMicroseconds();\n const rejectedIds = new Set<string>();\n const conflictedIds = new Set<string>();\n\n for (const rows of byContext.values()) {\n await applyMutationStatusUpdates(\n options.db,\n rows[0]!.context,\n rows.map((row) => {\n const ack = acksByMutationId.get(row.mutationId);\n\n if (ack?.status === \"rejected\") {\n // ADR-0022 §4: a business rejection. Terminal `rejected`; the overlay is auto-discarded below.\n rejectedIds.add(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"rejected\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: failedAtUs,\n lastError: ack.rejectionReason ?? \"Rejected by the authoritative endpoint\",\n nextRetryAtUs: null,\n lastHttpStatus: ack.httpStatus ?? 409,\n conflictReason: ack.rejectionReason ?? \"Rejected by the authoritative endpoint\",\n };\n }\n\n if (ack?.status === \"conflicted\") {\n // ADR-0015: a stale member — terminal `conflicted`, overlay KEPT (resolve as a new write).\n conflictedIds.add(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"conflicted\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: failedAtUs,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n nextRetryAtUs: null,\n lastHttpStatus: ack.httpStatus ?? 409,\n conflictReason: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n };\n }\n\n if (!ack || ack.status !== \"acked\") {\n const attemptCount = row.attemptCount + 1;\n const outcome = resolveFailureOutcome(\n ack?.httpStatus ?? null,\n attemptCount,\n maxMutationAttempts,\n failedAtUs,\n );\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: ack?.conflictReason ?? \"Authoritative write not acknowledged\",\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: ack?.httpStatus ?? null,\n conflictReason: null,\n };\n }\n\n return {\n mutationId: row.mutationId,\n status: \"acked\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: ackedAtUs,\n ackedAtUs,\n replaceAckedAtUs: true,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: row.mutationKind === \"delete\" ? 204 : 200,\n conflictReason: null,\n };\n }),\n );\n }\n\n // ADR-0022 §4: auto-discard the optimistic overlay for every rejected entity (the whole unit was\n // declined). The terminal `rejected` journal row is kept for diagnostics + `onReject`.\n for (const row of prepared) {\n if (rejectedIds.has(row.mutationId)) {\n await discardOverlayForSettledEntity(options.db, row.context, row.entityKey, row.entityKeyJson);\n }\n }\n\n const affectedContexts = [...byContext.keys()]\n .map((key) => tableContexts[key])\n .filter((context): context is TableContext => context != null);\n for (const context of affectedContexts) {\n await reconcileTable(options.db, context);\n }\n\n if (rejectedIds.size > 0 && options.onReject) {\n const details = await readMutationDetailsForContexts(options.db, affectedContexts, rejectedIds);\n if (details.length > 0) {\n await options.onReject(details);\n }\n }\n if (conflictedIds.size > 0 && options.onConflict) {\n const details = await readMutationDetailsForContexts(options.db, affectedContexts, conflictedIds);\n if (details.length > 0) {\n await options.onConflict(details);\n }\n }\n\n return { acks: [...acksByMutationId.values()] };\n },\n reconcile: async (table) => {\n const contexts = filterContexts(tableContexts, table);\n\n for (const context of contexts) {\n await reconcileTable(options.db, context);\n }\n },\n retryFailed: async (table) => {\n assertValidMutationTransition(\"failed\", \"pending\");\n const contexts = filterContexts(tableContexts, table);\n const nowUs = nowMicroseconds();\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n const query = queryBuilder\n .update(journal)\n .set({ status: \"pending\", nextRetryAtUs: nowUs, updatedAtUs: nowUs, conflictReason: null })\n .where(eq(journal.status, \"failed\"))\n .toSQL();\n await options.db.query(query.sql, query.params as unknown[]);\n }\n },\n recoverSending: async (table) => {\n assertValidMutationTransition(\"sending\", \"pending\");\n const contexts = filterContexts(tableContexts, table);\n const nowUs = nowMicroseconds();\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n const query = queryBuilder\n .update(journal)\n .set({\n status: \"pending\",\n updatedAtUs: nowUs,\n sentAtUs: null,\n nextRetryAtUs: nowUs,\n lastError: null,\n lastHttpStatus: null,\n conflictReason: null,\n })\n .where(eq(journal.status, \"sending\"))\n .toSQL();\n await options.db.query(query.sql, query.params as unknown[]);\n }\n },\n readMutationStats: async (table) => {\n const contexts = filterContexts(tableContexts, table);\n const totals: MutationDiagnostics = {\n pendingCount: 0,\n sendingCount: 0,\n failedCount: 0,\n quarantinedCount: 0,\n conflictedCount: 0,\n ackedCount: 0,\n };\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n // Drizzle has no `FILTER` operator (tier ②): each aggregate is a typed `sql` fragment over the\n // journal `status` column object with a bound status literal, aliased to the exact camelCase row\n // key the totals below read (the raw seam returns rows UNMAPPED, so aliases are load-bearing).\n const filteredCount = (status: MutationStatus, columnAlias: string) =>\n sql<number>`count(*) filter (where ${journal.status} = ${status})::int`.as(columnAlias);\n const query = queryBuilder\n .select({\n pendingCount: filteredCount(\"pending\", \"pendingCount\"),\n sendingCount: filteredCount(\"sending\", \"sendingCount\"),\n failedCount: filteredCount(\"failed\", \"failedCount\"),\n quarantinedCount: filteredCount(\"quarantined\", \"quarantinedCount\"),\n conflictedCount: filteredCount(\"conflicted\", \"conflictedCount\"),\n ackedCount: filteredCount(\"acked\", \"ackedCount\"),\n })\n .from(journal)\n .toSQL();\n const result = await options.db.query<MutationDiagnostics & Record<string, unknown>>(\n query.sql,\n query.params as unknown[],\n );\n\n const row = result.rows[0];\n if (!row) {\n continue;\n }\n\n totals.pendingCount += row.pendingCount;\n totals.sendingCount += row.sendingCount;\n totals.failedCount += row.failedCount;\n totals.quarantinedCount += row.quarantinedCount;\n totals.conflictedCount += row.conflictedCount;\n totals.ackedCount += row.ackedCount;\n }\n\n return totals;\n },\n readMutationDetails: async (table) => {\n const contexts = filterContexts(tableContexts, table);\n return readMutationDetailsForContexts(options.db, contexts);\n },\n createOptimisticRecord: (table, input) => {\n const context = getTableContext(table);\n return createOptimisticRecordFromContext(context, input);\n },\n };\n\n return runtime;\n}\n\n/**\n * Read journal entries across the given contexts as {@link MutationDetail}s, newest first.\n * Shared by the public `readMutationDetails` and the flush path's quarantine surfacing,\n * optionally narrowed to a set of mutation ids.\n */\nasync function readMutationDetailsForContexts(\n db: MutationDb,\n contexts: TableContext[],\n mutationIds?: ReadonlySet<string>,\n): Promise<MutationDetail[]> {\n const rows: MutationDetail[] = [];\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n // The raw seam returns rows UNMAPPED (no drizzle result mapping), so every field is aliased\n // explicitly to its camelCase row key, and the `_us` bigints keep their `::text` casts.\n const query = queryBuilder\n .select({\n mutationId: sql<string>`${journal.mutationId}`.as(\"mutationId\"),\n entityKeyJson: sql<string>`${journal.entityKeyJson}`.as(\"entityKeyJson\"),\n mutationSeq: sql<number>`${journal.mutationSeq}`.as(\"mutationSeq\"),\n mutationKind: sql<MutationKind>`${journal.mutationKind}`.as(\"mutationKind\"),\n status: journal.status,\n attemptCount: sql<number>`${journal.attemptCount}`.as(\"attemptCount\"),\n lastHttpStatus: sql<number | null>`${journal.lastHttpStatus}`.as(\"lastHttpStatus\"),\n lastError: sql<string | null>`${journal.lastError}`.as(\"lastError\"),\n conflictReason: sql<string | null>`${journal.conflictReason}`.as(\"conflictReason\"),\n nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as(\"nextRetryAtUs\"),\n serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as(\"serverUpdatedAtUs\"),\n updatedAtUs: sql<string>`${journal.updatedAtUs}::text`.as(\"updatedAtUs\"),\n registryVersion: sql<string | null>`${journal.registryVersion}`.as(\"registryVersion\"),\n })\n .from(journal)\n .orderBy(desc(journal.updatedAtUs), desc(journal.mutationSeq))\n .toSQL();\n const result = await db.query<MutationDetailRow>(query.sql, query.params as unknown[]);\n\n for (const row of result.rows) {\n if (mutationIds && !mutationIds.has(row.mutationId)) {\n continue;\n }\n\n rows.push({\n tableName: context.key,\n entityKey: JSON.parse(row.entityKeyJson) as Record<string, string>,\n mutationId: row.mutationId,\n mutationSeq: row.mutationSeq,\n mutationKind: row.mutationKind,\n status: row.status,\n attemptCount: row.attemptCount,\n lastHttpStatus: row.lastHttpStatus,\n lastError: row.lastError,\n conflictReason: row.conflictReason,\n nextRetryAtUs: row.nextRetryAtUs,\n serverUpdatedAtUs: row.serverUpdatedAtUs,\n updatedAtUs: row.updatedAtUs,\n registryVersion: row.registryVersion,\n });\n }\n }\n\n return rows.sort((left, right) => Number(right.updatedAtUs) - Number(left.updatedAtUs));\n}\n\ninterface MutationRow extends Record<string, unknown> {\n mutationId: string;\n entityKeyJson: string;\n mutationSeq: number;\n mutationKind: MutationKind;\n status: MutationStatus;\n payloadJson: string;\n attemptCount: number;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n registryVersion: string | null;\n}\n\ninterface MutationDetailRow extends Record<string, unknown> {\n mutationId: string;\n entityKeyJson: string;\n mutationSeq: number;\n mutationKind: MutationKind;\n status: MutationStatus;\n attemptCount: number;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n updatedAtUs: string;\n registryVersion: string | null;\n}\n\ninterface CurrentRecordStateRow extends Record<string, unknown> {\n overlayKind: string;\n localUpdatedAtUs: string;\n latestMutationSeq: number | null;\n latestMutationKind: MutationKind | null;\n latestMutationStatus: MutationStatus | null;\n}\n\ninterface BatchLatestMutationStateRow extends Record<string, unknown> {\n entityKeyJson: string;\n latestMutationSeq: number | null;\n latestMutationKind: MutationKind | null;\n latestMutationStatus: MutationStatus | null;\n}\n\ninterface BatchCurrentRecordStateRow extends Record<string, unknown> {\n entityKeyJson: string;\n overlayKind: string;\n localUpdatedAtUs: string;\n}\n\ninterface BatchEntityRef {\n entityKey: Record<string, string>;\n entityKeyJson: string;\n}\n\ninterface PlannedMutationInsert {\n mutationId: string;\n entityKey: Record<string, string>;\n entityKeyJson: string;\n mutationKind: MutationKind;\n payloadJson: string;\n nowUs: string;\n /**\n * The Base server version (ADR-0015) stamped at enqueue: the synced Server version the user saw,\n * for a **chain head** (the first staged write on the entity). `null` for a `create` (no base) and\n * for a **chained** write — the latter resolves its base at flush from its acked predecessor\n * (readPendingBatchRows), by Per-entity flush serialization (ADR-0014).\n */\n baseServerVersion: string | null;\n /**\n * A per-row `write_mode` override (ADR-0022 addendum). Left unset for an ordinary row, which inherits the\n * unit's mode at insert. A blind update sets `\"pessimistic-blind\"` so the row is flushed only by its unit's\n * foreground path (never the optimistic batch) and retires from the journal without a synced echo.\n */\n writeMode?: string | null;\n}\n\ninterface PlannedOverlayUpsert {\n entityKey: Record<string, string>;\n record: Record<string, unknown>;\n overlayKind: string;\n localUpdatedAtUs: string;\n}\n\ninterface BatchEntityState {\n entityKey: Record<string, string>;\n entityKeyJson: string;\n record: Record<string, unknown> | null;\n overlayKind: string | null;\n localUpdatedAtUs: string | null;\n latestMutationSeq: number | null;\n latestMutationKind: MutationKind | null;\n latestMutationStatus: MutationStatus | null;\n}\n\ntype NormalizedBatchItem =\n | {\n context: TableContext;\n kind: \"create\";\n entityKey: Record<string, string>;\n entityKeyJson: string;\n optimisticRecord: Record<string, unknown>;\n input: unknown;\n mutationId: string;\n nowUs: string;\n order: number;\n }\n | {\n context: TableContext;\n kind: \"update\";\n entityKey: Record<string, string>;\n entityKeyJson: string;\n patch: Record<string, unknown>;\n /** A blind update (ADR-0022 addendum): journal-only, no base-row presence check, no overlay. */\n blind: boolean;\n mutationId: string;\n nowUs: string;\n order: number;\n }\n | {\n context: TableContext;\n kind: \"delete\";\n entityKey: Record<string, string>;\n entityKeyJson: string;\n mutationId: string;\n nowUs: string;\n order: number;\n };\n\n/**\n * The Base server version (ADR-0015) to stamp at enqueue for an update/delete. Only a **chain head**\n * — the first staged write on the entity (no earlier unresolved mutation) — captures an enqueue-time\n * base: the synced Server version the user's edit was authored against, so a genuine external write\n * between view and apply is caught. A **chained** write (an earlier same-entity mutation is still\n * owed) returns `null` here; it resolves its base at flush from its acked predecessor, so an entity's\n * own successive edits never self-conflict (decision 2).\n */\nfunction captureChainHeadBase(context: TableContext, entityState: BatchEntityState): string | null {\n if ((entityState.latestMutationSeq ?? 0) !== 0) {\n return null;\n }\n\n if (!context.serverVersionPropertyKey || !entityState.record) {\n return null;\n }\n\n // The Server version is a bigint count of microseconds, surfaced as a string/number/bigint\n // depending on the read path. Anything else (null/object) means no observable base.\n const raw = entityState.record[context.serverVersionPropertyKey];\n if (typeof raw === \"string\" || typeof raw === \"number\" || typeof raw === \"bigint\") {\n return String(raw);\n }\n\n return null;\n}\n\nfunction buildTableContexts<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n const localSchema = getSyncRegistrySchema(registry);\n\n return Object.fromEntries(\n Object.entries(registry)\n .filter(([, entry]) => entry.mode !== \"readonly\")\n .map(([key, entry]) => [key, buildTableContext(registry, key, entry, localSchema)]),\n ) as Partial<Record<SyncTableName<TRegistry>, TableContext>>;\n}\n\nfunction buildTableContext<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n key: string,\n entry: SyncTableEntry<AnyPgTable>,\n localSchema: string,\n): TableContext {\n if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {\n throw new Error(`overlay and journal tables are required for writable table ${key}`);\n }\n\n const columns = getProjectedTableColumns(entry).map(({ propertyKey, column }) => ({\n propertyKey,\n column,\n }));\n\n const pkPropertyKeys = entry.primaryKey.columns.map((columnName) => {\n const column = columns.find((candidate) => candidate.column.name === columnName);\n\n if (!column) {\n throw new Error(`Primary key column ${columnName} was not found on table ${key}`);\n }\n\n return column.propertyKey;\n });\n\n const serverVersionColumnName = resolveServerVersionColumnName(entry) ?? null;\n const serverVersionPropertyKey = serverVersionColumnName\n ? (columns.find((candidate) => candidate.column.name === serverVersionColumnName)?.propertyKey ?? null)\n : null;\n\n // Resolve the `nowMicroseconds` managed fields generically from governance, not by property name.\n // `field.column` is a drizzle property key, but tolerate a column-name declaration too.\n const resolveManagedPropertyKey = (fieldColumn: string): string | undefined =>\n columns.find((candidate) => candidate.propertyKey === fieldColumn || candidate.column.name === fieldColumn)\n ?.propertyKey;\n const nowMicrosecondsManagedFields = (entry.governance?.managedFields ?? []).filter(\n (field) => field.strategy === \"nowMicroseconds\",\n );\n const managedNowMicrosecondsPropertyKeys = nowMicrosecondsManagedFields\n .map((field) => resolveManagedPropertyKey(field.column as string))\n .filter((propertyKey): propertyKey is string => propertyKey !== undefined);\n const updateManagedNowMicrosecondsPropertyKeys = nowMicrosecondsManagedFields\n .filter((field) => field.applyOn.includes(\"update\"))\n .map((field) => resolveManagedPropertyKey(field.column as string))\n .filter((propertyKey): propertyKey is string => propertyKey !== undefined);\n\n const managedAuthClaimCreateFields = (entry.governance?.managedFields ?? [])\n .filter((field) => field.strategy === \"authClaim\" && field.applyOn.includes(\"create\"))\n .flatMap((field) => {\n const propertyKey = resolveManagedPropertyKey(field.column as string);\n return propertyKey && field.claimPath ? [{ propertyKey, claimPath: field.claimPath }] : [];\n });\n\n // The generated local relations as runtime Drizzle objects (memoized per registry+key in\n // local-tables.ts), plus name-resolved column handles the statement authors below need:\n // overlay/synced columns are keyed by PROPERTY key, so PK columns (a DB-column-name concept,\n // ADR-0012) are resolved once here by matching `.name`.\n const tables = {\n synced: getSyncedLocalTable(registry, key as string & keyof TRegistry),\n overlay: getOverlayTable(registry, key as string & keyof TRegistry),\n journal: getJournalTable(registry, key as string & keyof TRegistry),\n };\n const overlayColumnsByPropertyKey = getColumns(tables.overlay) as Record<string, PgColumn>;\n const syncedColumnsByPropertyKey = getColumns(tables.synced) as Record<string, PgColumn>;\n const resolvePkColumns = (columnsByKey: Record<string, PgColumn>, relation: string) =>\n entry.primaryKey.columns.map((columnName) => {\n const column = Object.values(columnsByKey).find((candidate) => candidate.name === columnName);\n if (!column) {\n throw new Error(`Primary key column ${columnName} was not found on the ${relation} table for ${key}`);\n }\n return column;\n });\n const syncedServerVersionColumn = serverVersionColumnName\n ? (Object.values(syncedColumnsByPropertyKey).find((candidate) => candidate.name === serverVersionColumnName) ??\n null)\n : null;\n\n return {\n key,\n entry,\n readModel: qualifyLocalIdentifier(\n localSchema,\n entry.view != null\n ? getViewConfig(entry.view).name\n : (entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name),\n ),\n syncedTable: qualifyLocalIdentifier(\n localSchema,\n entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name,\n ),\n overlayTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.overlayTable),\n journalTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.journalTable),\n journalSequence: qualifyLocalIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable)),\n pkColumnNames: [...entry.primaryKey.columns],\n pkPropertyKeys,\n serverVersionColumnName,\n serverVersionPropertyKey,\n managedNowMicrosecondsPropertyKeys,\n updateManagedNowMicrosecondsPropertyKeys,\n managedAuthClaimCreateFields,\n recordIncludesOverlayState: \"overlayTable\" in (entry.clientProjection ?? {}),\n columns,\n tables,\n overlayColumnsByPropertyKey,\n syncedColumnsByPropertyKey,\n overlayPkColumns: resolvePkColumns(overlayColumnsByPropertyKey, \"overlay\"),\n syncedPkColumns: resolvePkColumns(syncedColumnsByPropertyKey, \"synced\"),\n syncedServerVersionColumn,\n };\n}\n\nfunction filterContexts<TRegistry extends SyncTableRegistry>(\n contexts: Partial<Record<SyncTableName<TRegistry>, TableContext>>,\n table?: SyncTableName<TRegistry>,\n) {\n if (table) {\n const context = contexts[table];\n return context ? [context] : [];\n }\n\n return Object.values(contexts).filter((context): context is TableContext => context !== undefined);\n}\n\n/**\n * Materialise a column's default into a concrete JS value for the optimistic overlay\n * row. The overlay INSERT writes an explicit value for every projected column (an\n * omitted column becomes a literal `NULL`, which overrides any table-level DEFAULT), so\n * a column declared `NOT NULL DEFAULT <x>` that the caller omits would violate the\n * overlay's NOT NULL constraint unless we fill the default here — mirroring what the\n * authoritative server applies on the base table.\n *\n * Only values we can produce client-side are materialised: a value-returning `defaultFn`\n * (e.g. `$defaultFn`) or a literal `.default(value)`. SQL-expression defaults\n * (`.default(sql\\`…\\`)`, `defaultRandom()`, `defaultNow()`) cannot be evaluated without\n * the database, so they are left to the server (the column is then expected to be either\n * caller-supplied or nullable in the optimistic row).\n */\nfunction materializeColumnDefault(column: TableContext[\"columns\"][number][\"column\"]): {\n ok: boolean;\n value?: unknown;\n} {\n if (!column.hasDefault) {\n return { ok: false };\n }\n\n if (typeof column.defaultFn === \"function\") {\n const produced = column.defaultFn();\n return is(produced, SQL) ? { ok: false } : { ok: true, value: produced };\n }\n\n if (column.default !== undefined && !is(column.default, SQL)) {\n return { ok: true, value: column.default };\n }\n\n return { ok: false };\n}\n\nfunction createOptimisticRecordFromContext<TCreate, TRecord>(\n context: TableContext,\n input: TCreate,\n claims?: Record<string, unknown>,\n): TRecord {\n const record = {\n ...(isRecord(input) ? input : {}),\n };\n const nowUs = nowMicroseconds();\n\n // Stamp `authClaim` create-managed fields (owner/author/created_by) from the decoded claim at the\n // field's path, so the optimistic overlay row is attributed locally and satisfies the column's NOT\n // NULL — the server independently stamps the same claim on apply, so the value never flips on\n // convergence. (`auth.uid()` is just `claimPath: [\"sub\"]`.)\n if (claims != null) {\n for (const { propertyKey, claimPath } of context.managedAuthClaimCreateFields) {\n if (record[propertyKey] === undefined) {\n const value = readJwtClaimPath(claims, claimPath);\n if (value !== undefined) {\n record[propertyKey] = value;\n }\n }\n }\n }\n\n if (hasProperty(context, \"createdAtUs\") && record[\"createdAtUs\"] === undefined) {\n record[\"createdAtUs\"] = nowUs;\n }\n\n if (hasProperty(context, \"updatedAtUs\") && record[\"updatedAtUs\"] === undefined) {\n record[\"updatedAtUs\"] = nowUs;\n }\n\n // Generic managed-timestamp fill (governance-driven): stamp any `nowMicroseconds` managed field the\n // convention block above did not — e.g. a Server version column not named `updated_at_us`. Additive\n // and idempotent, so convention tables are unaffected (their fields are already filled).\n for (const propertyKey of context.managedNowMicrosecondsPropertyKeys) {\n if (record[propertyKey] === undefined) {\n record[propertyKey] = nowUs;\n }\n }\n\n for (const { propertyKey, column } of context.columns) {\n if (record[propertyKey] !== undefined) {\n continue;\n }\n\n const materialized = materializeColumnDefault(column);\n if (materialized.ok) {\n record[propertyKey] = materialized.value;\n }\n }\n\n return buildOptimisticRecord(context, record, {\n overlayKind: \"pending_create\",\n localUpdatedAtUs: nowUs,\n }) as TRecord;\n}\n\n/**\n * Stamp every on-update `nowMicroseconds` managed field with `nowUs` (governance-driven, ADR-0004),\n * keyed by drizzle property key. For a convention table this is exactly `{ updatedAtUs: nowUs }`; for\n * a custom-named Server version it targets that column — so the local optimistic path never assumes\n * the demo naming the generic server applier does not.\n */\nfunction buildUpdateManagedNowStamp(context: TableContext, nowUs: string): Record<string, string> {\n return Object.fromEntries(\n context.updateManagedNowMicrosecondsPropertyKeys.map((propertyKey) => [propertyKey, nowUs]),\n );\n}\n\nfunction buildOptimisticRecord(\n context: TableContext,\n record: Record<string, unknown>,\n options: {\n overlayKind: string;\n localUpdatedAtUs: string;\n },\n) {\n if (!context.recordIncludesOverlayState) {\n return record;\n }\n\n return {\n ...record,\n overlayKind: options.overlayKind,\n localUpdatedAtUs: options.localUpdatedAtUs,\n };\n}\n\nfunction buildEntityKeyFromRecord(context: TableContext, record: unknown) {\n const recordObject = ensureRecord(record);\n return normalizeEntityKey(\n context,\n Object.fromEntries(context.pkPropertyKeys.map((propertyKey) => [propertyKey, String(recordObject[propertyKey])])),\n );\n}\n\nfunction normalizeEntityKey(context: TableContext, input: Record<string, string>) {\n // The public API accepts the identity by drizzle property name (ergonomics); past this\n // boundary the canonical Entity identity is column-keyed (ADR-0012), matching the\n // journal/overlay PK columns, entity_key_json, and the applier's `v_entity_key->>'<column>'`.\n // pkPropertyKeys[i] ↔ pkColumnNames[i] by construction (buildTableContext), so we map once here.\n return Object.fromEntries(\n context.pkPropertyKeys.map((propertyKey, index) => {\n const value = input[propertyKey];\n\n if (value === undefined) {\n throw new Error(`Missing entity key property ${propertyKey} for table ${context.key}`);\n }\n\n return [context.pkColumnNames[index]!, String(value)];\n }),\n );\n}\n\nfunction serializeEntityKey(entityKey: Record<string, string>) {\n return JSON.stringify(entityKey);\n}\n\nfunction dedupeBatchEntities(items: ReadonlyArray<NormalizedBatchItem>): BatchEntityRef[] {\n const entities = new Map<string, BatchEntityRef>();\n\n for (const item of items) {\n if (!entities.has(item.entityKeyJson)) {\n entities.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n });\n }\n }\n\n return [...entities.values()];\n}\n\nasync function readLatestMutationStates(\n db: MutationDb,\n context: TableContext,\n entities: ReadonlyArray<BatchEntityRef>,\n) {\n if (entities.length === 0) {\n return new Map<string, BatchLatestMutationStateRow>();\n }\n\n // The old VALUES-CTE + LEFT-JOIN-back-to-input existed only to emit null rows for entities with\n // no journal history; the caller reads via `map.get(...) ?? null`, so a missing key is equivalent.\n const journal = context.tables.journal;\n const query = queryBuilder\n .selectDistinctOn([journal.entityKeyJson], {\n entityKeyJson: sql<string>`${journal.entityKeyJson}`.as(\"entityKeyJson\"),\n latestMutationSeq: sql<number>`${journal.mutationSeq}`.as(\"latestMutationSeq\"),\n latestMutationKind: sql<MutationKind>`${journal.mutationKind}`.as(\"latestMutationKind\"),\n latestMutationStatus: sql<MutationStatus>`${journal.status}`.as(\"latestMutationStatus\"),\n })\n .from(journal)\n .where(\n inArray(\n journal.entityKeyJson,\n entities.map((entity) => entity.entityKeyJson),\n ),\n )\n .orderBy(journal.entityKeyJson, desc(journal.mutationSeq))\n .toSQL();\n const result = await db.query<BatchLatestMutationStateRow>(query.sql, query.params as unknown[]);\n\n return new Map(result.rows.map((row) => [row.entityKeyJson, row]));\n}\n\nasync function readCurrentRecordStates(db: MutationDb, context: TableContext, entities: ReadonlyArray<BatchEntityRef>) {\n if (entities.length === 0) {\n return new Map<string, BatchCurrentRecordStateRow>();\n }\n\n // Tier ②: the overlay-∪-synced shape over an input VALUES table. The input CTE carries each\n // entity's `entity_key_json` alongside its PK values (the caller maps rows back by that JSON), so\n // it cannot be a plain builder select; every identifier still comes from the table objects /\n // `sql.identifier`, and every value is a bound (cast-typed) param.\n const overlay = context.tables.overlay;\n const synced = context.tables.synced;\n const inputCte = buildEntityInputCte(context, entities);\n const overlaySelectColumns = buildProjectedSelectColumns(context, context.overlayColumnsByPropertyKey);\n const syncedSelectColumns = buildProjectedSelectColumns(context, context.syncedColumnsByPropertyKey);\n const inputOverlayJoin = buildEntityInputJoin(context.pkColumnNames, context.overlayPkColumns);\n const inputSyncedJoin = buildEntityInputJoin(context.pkColumnNames, context.syncedPkColumns);\n const syncedUpdatedAtColumn = context.syncedColumnsByPropertyKey[\"updatedAtUs\"];\n const syncedLocalUpdated =\n hasProperty(context, \"updatedAtUs\") && syncedUpdatedAtColumn\n ? sql`${syncedUpdatedAtColumn}::text AS \"localUpdatedAtUs\"`\n : sql`'0' AS \"localUpdatedAtUs\"`;\n\n const query = queryDialect.sqlToQuery(sql`\n WITH ${inputCte},\n overlay_rows AS (\n SELECT\n input.entity_key_json AS \"entityKeyJson\",\n ${overlaySelectColumns},\n ${overlay.overlayKind} AS \"overlayKind\",\n ${overlay.localUpdatedAtUs}::text AS \"localUpdatedAtUs\"\n FROM input_entities AS input\n JOIN ${overlay}\n ON ${inputOverlayJoin}\n ),\n synced_rows AS (\n SELECT\n input.entity_key_json AS \"entityKeyJson\",\n ${syncedSelectColumns},\n ${\"synced\"} AS \"overlayKind\",\n ${syncedLocalUpdated}\n FROM input_entities AS input\n JOIN ${synced}\n ON ${inputSyncedJoin}\n WHERE NOT EXISTS (\n SELECT 1\n FROM ${overlay}\n WHERE ${inputOverlayJoin}\n )\n )\n SELECT *\n FROM overlay_rows\n UNION ALL\n SELECT *\n FROM synced_rows\n `);\n const result = await db.query<BatchCurrentRecordStateRow>(query.sql, query.params as unknown[]);\n\n return new Map(result.rows.map((row) => [row.entityKeyJson, row]));\n}\n\nasync function insertMutationsBulk(\n db: MutationDb,\n context: TableContext,\n rows: ReadonlyArray<PlannedMutationInsert>,\n registryVersion: string | null,\n unit?: WriteUnit,\n) {\n if (rows.length === 0) {\n return;\n }\n\n // ADR-0022: a dynamic write-unit tags every row of the batch with one shared unit id + mode; the\n // default path leaves both NULL (the flusher derives mode/unit from the static group). A blind row\n // carries its own `write_mode` override (`pessimistic-blind`), so the mode is resolved per row.\n const writeUnit = unit?.id ?? null;\n const journal = context.tables.journal;\n // `mutationSeq` is intentionally omitted: the generated journal DDL carries\n // `mutation_seq ... DEFAULT nextval(<journal sequence>)`, so the DB default assigns it — drizzle\n // renders `default` for every column a row does not provide.\n const values = rows.map((row) => ({\n mutationId: row.mutationId,\n ...Object.fromEntries(context.pkColumnNames.map((columnName) => [columnName, row.entityKey[columnName]])),\n entityKeyJson: row.entityKeyJson,\n mutationKind: row.mutationKind,\n status: \"pending\",\n registryVersion,\n baseServerVersion: row.baseServerVersion,\n payloadJson: row.payloadJson,\n enqueuedAtUs: row.nowUs,\n nextRetryAtUs: row.nowUs,\n updatedAtUs: row.nowUs,\n writeUnit,\n writeMode: row.writeMode ?? unit?.mode ?? null,\n }));\n\n const query = queryBuilder\n .insert(journal)\n .values(values as PgInsertValue<JournalTable>[])\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n\n // Lifecycle origin: the moment each mutation is first staged into the journal. Correlates by id with\n // the later \"board-write sending\"/\"board-write acks\" lines (staged → sent → acked, per id).\n for (const row of rows) {\n syncDebug(\"mutation staged\", { mutationId: row.mutationId, table: context.key });\n }\n}\n\nasync function upsertOverlayRecordsBulk(\n db: MutationDb,\n context: TableContext,\n rows: ReadonlyArray<PlannedOverlayUpsert>,\n) {\n if (rows.length === 0) {\n return;\n }\n\n const overlay = context.tables.overlay;\n const values = rows.map((row) => ({\n ...Object.fromEntries(context.columns.map(({ propertyKey }) => [propertyKey, row.record[propertyKey] ?? null])),\n overlayKind: row.overlayKind,\n localUpdatedAtUs: row.localUpdatedAtUs,\n }));\n // Every inserted column (the projection + the two overlay columns) takes its EXCLUDED value on\n // conflict — the fixed alias PostgreSQL defines for the proposed row; its column names are the\n // table's own, so they come from the column objects via `sql.identifier`.\n const excludedSet = Object.fromEntries([\n ...context.columns.map(({ propertyKey, column }) => [propertyKey, sql`excluded.${sql.identifier(column.name)}`]),\n [\"overlayKind\", sql`excluded.${sql.identifier(overlay.overlayKind.name)}`],\n [\"localUpdatedAtUs\", sql`excluded.${sql.identifier(overlay.localUpdatedAtUs.name)}`],\n ]) as Record<string, SQL>;\n\n const query = queryBuilder\n .insert(overlay)\n .values(values as PgInsertValue<OverlayTable>[])\n .onConflictDoUpdate({ target: context.overlayPkColumns, set: excludedSet })\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\n/**\n * The batch-input CTE as a typed fragment: `input_entities (entity_key_json, <pks…>) AS (VALUES …)`\n * with every value a bound param, cast to its PK column's type (an untyped VALUES column would\n * otherwise default to text and break the join against a uuid/int PK).\n */\nfunction buildEntityInputCte(context: TableContext, entities: ReadonlyArray<BatchEntityRef>): SQL {\n const columnNames = [\"entity_key_json\", ...context.pkColumnNames];\n const tuples = entities.map((entity) => {\n const values = [\n sql`${entity.entityKeyJson}`,\n ...context.pkColumnNames.map((columnName) => {\n const columnEntry = context.columns.find(({ column }) => column.name === columnName);\n const castSuffix = columnEntry ? resolveInputCastSuffix(columnEntry.column.columnType) : \"\";\n // The cast keyword is a FIXED type suffix selected from the closed switch below — never\n // derived from user data — so `sql.raw` is safe here; the value itself is a bound param.\n return castSuffix\n ? sql`${entity.entityKey[columnName]}${sql.raw(castSuffix)}`\n : sql`${entity.entityKey[columnName]}`;\n }),\n ];\n return sql`(${sql.join(values, sql`, `)})`;\n });\n\n return sql`input_entities (${sql.join(\n columnNames.map((columnName) => sql.identifier(columnName)),\n sql`, `,\n )}) AS (VALUES ${sql.join(tuples, sql`, `)})`;\n}\n\nfunction resolveInputCastSuffix(columnType: string): string {\n switch (columnType) {\n case \"PgUUID\":\n return \"::uuid\";\n case \"PgBigInt64\":\n case \"PgBigInt53\":\n return \"::bigint\";\n case \"PgInteger\":\n case \"PgSerial\":\n case \"PgSmallInt\":\n return \"::int\";\n case \"PgBoolean\":\n return \"::boolean\";\n case \"PgTimestamp\":\n case \"PgTimestampString\":\n return \"::timestamp\";\n default:\n return \"\";\n }\n}\n\n/**\n * The projected columns of one branch (overlay or synced) as select-list fragments, aliased to\n * their camelCase property keys — the raw seam returns rows unmapped, so the aliases ARE the row\n * keys — with `::text` casts on the bigint columns (matching how the runtime reads them).\n */\nfunction buildProjectedSelectColumns(context: TableContext, columnsByPropertyKey: Record<string, PgColumn>): SQL {\n return sql.join(\n context.columns.map(({ propertyKey, column }) => {\n const target = columnsByPropertyKey[propertyKey];\n if (!target) {\n throw new Error(`Projected column ${propertyKey} was not found on the local tables for ${context.key}`);\n }\n if (column.columnType === \"PgBigInt64\" || column.columnType === \"PgBigInt53\") {\n return sql`${target}::text AS ${sql.identifier(propertyKey)}`;\n }\n return sql`${target} AS ${sql.identifier(propertyKey)}`;\n }),\n sql`, `,\n );\n}\n\n/** PK equality between a branch table's columns and the `input` CTE, as a typed fragment. */\nfunction buildEntityInputJoin(pkColumnNames: string[], pkColumns: PgColumn[]): SQL {\n return sql.join(\n pkColumnNames.map((columnName, index) => sql`${pkColumns[index]!} = input.${sql.identifier(columnName)}`),\n sql` AND `,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Batch flush — sends one send-eligible slice of pending mutations across all\n// target tables in a single POST /api/mutations call. The public flush()\n// wrapper loops until no more eligible rows remain.\n// ---------------------------------------------------------------------------\n\ninterface PendingBatchRow extends MutationRow {\n tableKey: string;\n enqueuedAtUs: string;\n /** The resolved Base server version (ADR-0015), or null when the table predates the policy. */\n baseServerVersion: string | null;\n}\n\ninterface PreparedBatchRow extends PendingBatchRow {\n context: TableContext;\n entityKey: Record<string, string>;\n envelopePayload: Record<string, unknown>;\n sqlTableName: string;\n}\n\ninterface FlushBatchResult {\n processedCount: number;\n affectedContexts: TableContext[];\n /** Mutation ids that transitioned to `quarantined` in this slice (ADR-0006), for surfacing. */\n quarantinedMutationIds: string[];\n /** Mutation ids that transitioned to `conflicted` in this slice (ADR-0015), for surfacing. */\n conflictedMutationIds: string[];\n}\n\ninterface MutationStatusUpdate {\n mutationId: string;\n status: MutationStatus;\n attemptCount: number;\n updatedAtUs: string;\n sentAtUs?: string | null;\n replaceSentAtUs?: boolean;\n ackedAtUs?: string | null;\n replaceAckedAtUs?: boolean;\n serverUpdatedAtUs?: string | null;\n replaceServerUpdatedAtUs?: boolean;\n baseServerVersion?: string | null;\n replaceBaseServerVersion?: boolean;\n lastError?: string | null;\n nextRetryAtUs?: string | null;\n lastHttpStatus?: number | null;\n conflictReason?: string | null;\n}\n\n/**\n * The resolved Base server version (ADR-0015) for a row at flush. A **chain head** already carries\n * `base_server_version` (stamped at enqueue), so COALESCE returns it untouched — keeping the\n * enqueue-time base means a genuine external write between view and apply is still caught. A\n * **chained** write has NULL there; it resolves to its **acked predecessor's** Server version (by\n * Per-entity flush serialization the predecessor is already acked when this row flushes), falling\n * back to the entity's current synced version once that predecessor has been reconciled away. Either\n * fallback yields the entity's own latest server state, so its own chain never self-conflicts.\n */\nfunction buildResolvedBaseServerVersion(context: TableContext): SQL {\n const journal = context.tables.journal;\n const synced = context.tables.synced;\n const pred = alias(journal, \"pred\");\n const predecessor = queryBuilder\n .select({ value: sql`MAX(${pred.serverUpdatedAtUs})` })\n .from(pred)\n .where(\n and(\n eq(pred.entityKeyJson, journal.entityKeyJson),\n lt(pred.mutationSeq, journal.mutationSeq),\n eq(pred.status, \"acked\"),\n ),\n );\n\n if (!context.syncedServerVersionColumn) {\n return sql`COALESCE(${journal.baseServerVersion}, ${predecessor})::text`;\n }\n\n const syncedFallback = queryBuilder\n .select({ value: sql`${context.syncedServerVersionColumn}` })\n .from(synced)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) => eq(context.syncedPkColumns[index]!, journal[columnName]!)),\n ),\n );\n\n return sql`COALESCE(${journal.baseServerVersion}, ${predecessor}, ${syncedFallback})::text`;\n}\n\n/**\n * One table's send-eligible journal rows as a builder select with the shared {@link PendingBatchRow}\n * projection — the aliases ARE the row keys (raw seam), `tableKey` rides as a bound param, and the\n * resolved Base server version (ADR-0015) is the typed COALESCE fragment above.\n */\nfunction buildPendingRowsProjection(context: TableContext) {\n const journal = context.tables.journal;\n return {\n tableKey: sql<string>`${context.key}`.as(\"tableKey\"),\n mutationId: sql<string>`${journal.mutationId}`.as(\"mutationId\"),\n entityKeyJson: sql<string>`${journal.entityKeyJson}`.as(\"entityKeyJson\"),\n mutationSeq: sql<number>`${journal.mutationSeq}`.as(\"mutationSeq\"),\n mutationKind: sql<MutationKind>`${journal.mutationKind}`.as(\"mutationKind\"),\n status: journal.status,\n payloadJson: sql<string>`${journal.payloadJson}`.as(\"payloadJson\"),\n attemptCount: sql<number>`${journal.attemptCount}`.as(\"attemptCount\"),\n lastHttpStatus: sql<number | null>`${journal.lastHttpStatus}`.as(\"lastHttpStatus\"),\n lastError: sql<string | null>`${journal.lastError}`.as(\"lastError\"),\n conflictReason: sql<string | null>`${journal.conflictReason}`.as(\"conflictReason\"),\n nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as(\"nextRetryAtUs\"),\n serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as(\"serverUpdatedAtUs\"),\n baseServerVersion: buildResolvedBaseServerVersion(context).as(\"baseServerVersion\"),\n enqueuedAtUs: sql<string>`${journal.enqueuedAtUs}::text`.as(\"enqueuedAtUs\"),\n };\n}\n\nasync function readPendingBatchRows(db: MutationDb, contexts: TableContext[], nowUs: string, batchSize: number) {\n if (contexts.length === 0) {\n return [] as PendingBatchRow[];\n }\n\n const branches = contexts.map((context) => {\n const journal = context.tables.journal;\n const earlier = alias(journal, \"earlier\");\n return queryBuilder\n .select(buildPendingRowsProjection(context))\n .from(journal)\n .where(\n and(\n inArray(journal.status, [\"pending\", \"failed\"]),\n // ADR-0022: pessimistic rows are flushed by the authoritative unit path (flushUnit), never the\n // optimistic batch — exclude them here so a tagged write is never optimistically sent. The\n // `NOT LIKE 'pessimistic%'` also excludes a `pessimistic-blind` row (ADR-0022 addendum), which\n // belongs to its unit's foreground flush too.\n sql`COALESCE(${journal.writeMode}, '') NOT LIKE 'pessimistic%'`,\n sql`COALESCE(${journal.nextRetryAtUs}, 0) <= ${nowUs}::bigint`,\n notExists(\n queryBuilder\n .select({ one: sql`1` })\n .from(earlier)\n .where(\n and(\n eq(earlier.entityKeyJson, journal.entityKeyJson),\n lt(earlier.mutationSeq, journal.mutationSeq),\n // A still-unresolved earlier mutation blocks later same-entity ones so the\n // server applies them in author order. The quarantined status is included: a\n // later mutation must not flush past a prerequisite the server permanently\n // rejected (it would itself fail); resolving the quarantine unblocks the queue.\n inArray(earlier.status, [\"pending\", \"failed\", \"sending\", \"quarantined\"]),\n ),\n ),\n ),\n ),\n );\n });\n\n // The union rides inside a derived table because the outer ORDER BY casts the (text) output\n // columns — a set operation's own ORDER BY may only name plain output columns. The `pending`\n // alias and its two quoted output-column names are fixed by the projection above, not data.\n const query = queryDialect.sqlToQuery(\n sql`SELECT * FROM (${sql.join(branches, sql` UNION ALL `)}) AS pending ORDER BY pending.\"enqueuedAtUs\"::bigint ASC, pending.\"mutationSeq\" ASC LIMIT ${batchSize}`,\n );\n const result = await db.query<PendingBatchRow>(query.sql, query.params as unknown[]);\n\n return result.rows;\n}\n\n/**\n * Read one pessimistic write-unit's send-eligible rows (ADR-0022) across every table, ordered by author\n * sequence. Unlike {@link readPendingBatchRows} it has no per-entity ordering gate: a unit is enqueued and\n * sent atomically, so its members go together.\n */\nasync function readUnitPendingRows(\n db: MutationDb,\n contexts: TableContext[],\n unitId: string,\n): Promise<PendingBatchRow[]> {\n if (contexts.length === 0) {\n return [];\n }\n\n const branches = contexts.map((context) => {\n const journal = context.tables.journal;\n return queryBuilder\n .select(buildPendingRowsProjection(context))\n .from(journal)\n .where(and(eq(journal.writeUnit, unitId), inArray(journal.status, [\"pending\", \"failed\"])));\n });\n\n const query = queryDialect.sqlToQuery(\n sql`SELECT * FROM (${sql.join(branches, sql` UNION ALL `)}) AS unit ORDER BY unit.\"mutationSeq\" ASC`,\n );\n const result = await db.query<PendingBatchRow>(query.sql, query.params as unknown[]);\n\n return result.rows;\n}\n\nasync function flushBatch(\n db: MutationDb,\n tableContexts: Record<string, TableContext>,\n batchWriteUrl: string,\n maxAttempts: number,\n batchSize: number,\n tableFilter?: string,\n getAuthToken?: () => Promise<string | undefined>,\n requestHeaders?: Record<string, string>,\n): Promise<FlushBatchResult> {\n const contexts = filterContexts(tableContexts, tableFilter);\n const nowUs = nowMicroseconds();\n const quarantinedMutationIds: string[] = [];\n const conflictedMutationIds: string[] = [];\n\n // Collect send-eligible mutations across all target tables.\n const pendingRows = await readPendingBatchRows(db, contexts, nowUs, batchSize);\n const pending: PreparedBatchRow[] = [];\n const pendingByTable = new Map<string, PreparedBatchRow[]>();\n\n for (const row of pendingRows) {\n const context = tableContexts[row.tableKey];\n\n if (!context) {\n continue;\n }\n\n const entityKey = JSON.parse(row.entityKeyJson) as Record<string, string>;\n const rawPayload = JSON.parse(row.payloadJson) as Record<string, unknown>;\n const preparedRow: PreparedBatchRow = {\n ...row,\n context,\n entityKey,\n envelopePayload:\n row.mutationKind === \"delete\"\n ? entityKey\n : toSqlColumnPayload(\n context,\n stripManagedFields(\n context,\n (rawPayload[\"value\"] ?? rawPayload[\"patch\"] ?? rawPayload) as Record<string, unknown>,\n row.mutationKind as \"create\" | \"update\",\n ),\n ),\n sqlTableName: context.entry.shape?.tableName ?? context.key,\n };\n\n pending.push(preparedRow);\n\n const existingTableRows = pendingByTable.get(context.key);\n\n if (existingTableRows) {\n existingTableRows.push(preparedRow);\n } else {\n pendingByTable.set(context.key, [preparedRow]);\n }\n }\n\n if (pending.length === 0) {\n // If a write just enqueued and requested a pass, but this flush sees nothing, the pass raced the\n // journal commit (or everything is already in-flight/backed-off) — the write then waits for a\n // later pass. Worth seeing explicitly when chasing flush latency.\n syncDebug(\"flushBatch: no send-eligible mutations this pass\");\n return {\n processedCount: 0,\n affectedContexts: [],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n }\n\n syncDebug(\"flushBatch sending to board-write\", { count: pending.length });\n\n // Mark all as sending.\n const sentAtUs = nowMicroseconds();\n\n for (const rows of pendingByTable.values()) {\n await applyMutationStatusUpdates(\n db,\n rows[0]!.context,\n rows.map((row) => ({\n mutationId: row.mutationId,\n status: \"sending\",\n attemptCount: row.attemptCount + 1,\n updatedAtUs: sentAtUs,\n sentAtUs,\n replaceSentAtUs: true,\n // Persist the resolved Base server version (ADR-0015) so a chained write's flush-resolved\n // base is durable and matches exactly what the envelope carries to the server.\n baseServerVersion: row.baseServerVersion,\n replaceBaseServerVersion: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: null,\n conflictReason: null,\n })),\n );\n }\n\n const mutations = pending.map((row) => {\n return {\n tableName: row.sqlTableName,\n entityKey: row.entityKey,\n mutationId: row.mutationId,\n mutationSeq: row.mutationSeq,\n kind: row.mutationKind as \"create\" | \"update\" | \"delete\",\n payload: row.envelopePayload,\n clientTimestampUs: sentAtUs,\n // ADR-0015: carry the resolved Base server version so the applier can detect a stale write.\n // Omitted for a create / a table that predates the policy (null) — then no stale check runs.\n ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),\n };\n });\n\n let responseOk = false;\n let acksByMutationId: Map<string, BatchMutationAck[\"acks\"][number]> = new Map();\n const batchMutationUrl = resolveBatchMutationUrl(batchWriteUrl);\n\n try {\n // Resolve the auth token and the network round-trip separately: in the board, `getAuthToken` calls\n // `supabase.auth.getSession()` per send, which can itself stall (token refresh) and would otherwise\n // be invisibly folded into \"the write was slow\".\n const authStart = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n const authToken = await getAuthToken?.();\n const fetchStart = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n syncDebug(\"board-write auth token resolved\", { ms: Math.round(fetchStart - authStart) });\n\n let response = await fetch(batchMutationUrl, {\n method: \"POST\",\n headers: buildRequestHeaders(authToken, requestHeaders),\n body: jsonStringifyPayload({ mutations }),\n });\n\n if ([401, 403].includes(response.status) && getAuthToken) {\n response = await fetch(batchMutationUrl, {\n method: \"POST\",\n headers: buildRequestHeaders(await getAuthToken(), requestHeaders),\n body: jsonStringifyPayload({ mutations }),\n });\n }\n\n const fetchEnd = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n syncDebug(\"board-write responded\", { status: response.status, ms: Math.round(fetchEnd - fetchStart) });\n\n if (response.ok) {\n const responseJson = (await response.json()) as BatchMutationAck;\n responseOk = true;\n acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));\n syncDebug(\"board-write acks\", {\n acks: responseJson.acks.map((ack) => `${ack.mutationId.slice(0, 8)}:${ack.status}`),\n });\n } else {\n const text = await response.text();\n throw new MutationRequestError(\n text.length > 0 ? text : `Bulk write responded with ${response.status}`,\n response.status,\n parseBatchRejections(text),\n );\n }\n } catch (error) {\n const failedAtUs = nowMicroseconds();\n const httpStatus = error instanceof MutationRequestError ? error.status : null;\n const errorMessage = error instanceof Error ? error.message : \"Unknown batch write failure\";\n // The server attributed the failure to specific mutations (a structural validation\n // rejection of an atomic batch). When present, we quarantine exactly those and leave the\n // innocent siblings immediately retryable; absent (transport / 5xx / auth / malformed\n // envelope), the whole batch stays retryable under the shared attempt cap.\n const rejectionById =\n error instanceof MutationRequestError && error.rejections\n ? new Map(error.rejections.map((rejection) => [rejection.mutationId, rejection]))\n : null;\n\n for (const rows of pendingByTable.values()) {\n await applyMutationStatusUpdates(\n db,\n rows[0]!.context,\n rows.map((row) => {\n const attemptCount = row.attemptCount + 1;\n\n if (rejectionById) {\n const rejection = rejectionById.get(row.mutationId);\n\n if (rejection) {\n // Named as the cause: terminal quarantine (it will never succeed unchanged).\n quarantinedMutationIds.push(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"quarantined\" as const,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: rejection.reason,\n nextRetryAtUs: null,\n lastHttpStatus: httpStatus,\n conflictReason: rejection.reason,\n };\n }\n\n // Innocent sibling: nothing was applied (atomic batch), so make it immediately\n // retryable — no backoff (the fault was the now-quarantined mutation, not\n // congestion) — and the next flush proceeds without the poison.\n return {\n mutationId: row.mutationId,\n status: \"failed\" as const,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: \"Batch rejected due to a sibling mutation; retrying without it\",\n nextRetryAtUs: null,\n lastHttpStatus: httpStatus,\n conflictReason: null,\n };\n }\n\n // Unattributed batch-level failure: stays retryable with jittered backoff; only the\n // hard attempt cap escalates to terminal quarantined. A structural 4xx is NOT\n // quarantined here (a stray 404/413/malformed envelope would otherwise permanently\n // kill unrelated valid writes).\n const outcome = resolveBatchFailureOutcome(attemptCount, maxAttempts, failedAtUs);\n\n if (outcome.status === \"quarantined\") {\n quarantinedMutationIds.push(row.mutationId);\n }\n\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: errorMessage,\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: httpStatus,\n conflictReason: null,\n };\n }),\n );\n }\n\n return {\n processedCount: pending.length,\n affectedContexts: [...new Set(pending.map((row) => row.context))],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n }\n\n if (!responseOk) {\n return {\n processedCount: pending.length,\n affectedContexts: [...new Set(pending.map((row) => row.context))],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n }\n\n // Apply per-mutation ack results.\n const ackedAtUs = nowMicroseconds();\n const failedAtUs = nowMicroseconds();\n\n for (const rows of pendingByTable.values()) {\n await applyMutationStatusUpdates(\n db,\n rows[0]!.context,\n rows.map((row) => {\n const ack = acksByMutationId.get(row.mutationId);\n\n if (ack && ack.status === \"conflicted\") {\n // ADR-0015: a stale write the reject-if-stale policy declined. Move to the terminal\n // `conflicted` status — NOT a failure (never retried as-is, the base is still stale) — and\n // KEEP the optimistic Overlay (reconcile only clears acked rows, so the user's edit stays\n // visible). The server's current Server version rides on the journal row for the diff UI.\n conflictedMutationIds.push(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"conflicted\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: failedAtUs,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n nextRetryAtUs: null,\n lastHttpStatus: ack.httpStatus ?? 409,\n conflictReason: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n };\n }\n\n if (!ack || ack.status !== \"acked\") {\n const attemptCount = row.attemptCount + 1;\n const httpStatus = ack?.httpStatus ?? null;\n const outcome = resolveFailureOutcome(httpStatus, attemptCount, maxAttempts, failedAtUs);\n\n if (outcome.status === \"quarantined\") {\n quarantinedMutationIds.push(row.mutationId);\n }\n\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: ack?.conflictReason ?? \"Batch mutation not acknowledged\",\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: httpStatus,\n conflictReason: ack?.conflictReason ?? null,\n };\n }\n\n if (row.mutationKind === \"delete\") {\n return {\n mutationId: row.mutationId,\n status: \"acked\",\n attemptCount: row.attemptCount + 1,\n updatedAtUs: ackedAtUs,\n ackedAtUs,\n replaceAckedAtUs: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: 204,\n conflictReason: null,\n };\n }\n\n return {\n mutationId: row.mutationId,\n status: \"acked\",\n attemptCount: row.attemptCount + 1,\n updatedAtUs: ackedAtUs,\n ackedAtUs,\n replaceAckedAtUs: true,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: 200,\n conflictReason: null,\n };\n }),\n );\n }\n\n return {\n processedCount: pending.length,\n affectedContexts: [...new Set(pending.map((row) => row.context))],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n}\n\n/**\n * Resolve a flush failure into the durable journal outcome (ADR-0006). A structural\n * rejection ({@link classifyFailureStatus}) or hitting the hard attempt cap ends the\n * retry loop with a terminal `quarantined` (no `next_retry_at_us`); otherwise the\n * mutation stays `failed` with a jittered backoff (ADR-0005 congestion policy).\n */\nfunction resolveFailureOutcome(\n httpStatus: number | null,\n attemptCount: number,\n maxAttempts: number,\n failedAtUs: string,\n): { status: \"failed\" | \"quarantined\"; nextRetryAtUs: string | null } {\n if (classifyFailureStatus(httpStatus) === \"quarantined\" || attemptCount >= maxAttempts) {\n return { status: \"quarantined\", nextRetryAtUs: null };\n }\n\n return { status: \"failed\", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };\n}\n\n/**\n * Resolve a *batch-level* failure — the whole POST failed (transport error, 5xx, auth, or a\n * non-2xx the server did not attribute to a specific mutation). Unlike a per-mutation ack\n * rejection, the fault cannot be pinned on any one mutation, so a structural 4xx must NOT\n * quarantine the batch (a stray 404/413/malformed envelope would permanently kill unrelated\n * valid offline writes). These failures stay retryable `failed` with jittered backoff; only\n * the hard attempt cap escalates to terminal `quarantined`.\n */\nfunction resolveBatchFailureOutcome(\n attemptCount: number,\n maxAttempts: number,\n failedAtUs: string,\n): { status: \"failed\" | \"quarantined\"; nextRetryAtUs: string | null } {\n if (attemptCount >= maxAttempts) {\n return { status: \"quarantined\", nextRetryAtUs: null };\n }\n\n return { status: \"failed\", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };\n}\n\nfunction resolveBatchMutationUrl(batchWriteUrl: string): string {\n const trimmed = batchWriteUrl.replace(/\\/+$/, \"\");\n\n if (trimmed.endsWith(\"/mutations\")) {\n return trimmed;\n }\n\n return `${trimmed}/mutations`;\n}\n\n/** The authoritative (pessimistic) write endpoint (ADR-0022): the batch URL with `/unit` appended. */\nfunction resolveAuthoritativeMutationUrl(batchWriteUrl: string): string {\n return `${resolveBatchMutationUrl(batchWriteUrl)}/unit`;\n}\n\nfunction stripManagedFields(\n context: TableContext,\n payload: Record<string, unknown>,\n operation: \"create\" | \"update\",\n): Record<string, unknown> {\n const managedColumns = new Set<string>();\n\n for (const mf of context.entry.governance?.managedFields ?? []) {\n if (mf.applyOn.includes(operation)) {\n managedColumns.add(mf.column);\n }\n }\n\n if (managedColumns.size === 0) return payload;\n\n return Object.fromEntries(Object.entries(payload).filter(([key]) => !managedColumns.has(key)));\n}\n\nfunction toSqlColumnPayload(context: TableContext, payload: Record<string, unknown>): Record<string, unknown> {\n const normalized: Record<string, unknown> = {};\n\n for (const { propertyKey, column } of context.columns) {\n const columnName = column.name;\n\n if (Object.prototype.hasOwnProperty.call(payload, columnName)) {\n normalized[columnName] = payload[columnName];\n continue;\n }\n\n if (Object.prototype.hasOwnProperty.call(payload, propertyKey)) {\n normalized[columnName] = payload[propertyKey];\n }\n }\n\n return normalized;\n}\n\n/**\n * Discard a terminal-state entity: clear its journal rows in the given terminal status\n * (`conflicted` — ADR-0015; or `quarantined` — ADR-0006) and its kept optimistic Overlay row, so the\n * Read model falls back to the synced (server) value. The overlay is removed only when no OTHER journal\n * row still owes the entity (a pending/sending/failed/acked write), mirroring reconcileTable's\n * overlay-clear guard — so a discard never strips an overlay another un-resolved write still depends\n * on. Both public discards (`discardConflict`, `discardQuarantined`) are this one body parameterized by\n * the terminal status they retire; owning its own transaction (like reconcileTable), it is not wrapped.\n */\nasync function discardTerminalEntity(\n db: MutationDb,\n context: TableContext,\n entityKey: Record<string, string>,\n entityKeyJson: string,\n terminalStatus: \"conflicted\" | \"quarantined\",\n) {\n await db.exec(\"BEGIN\");\n\n try {\n const journal = context.tables.journal;\n const clearQuery = queryBuilder\n .delete(journal)\n .where(and(eq(journal.status, terminalStatus), eq(journal.entityKeyJson, entityKeyJson)))\n .toSQL();\n await db.query(clearQuery.sql, clearQuery.params as unknown[]);\n\n // Clear the kept overlay only when no journal row still owes this entity — so a discard never\n // strips an overlay another un-resolved write (e.g. a resolution already enqueued) depends on.\n const overlayQuery = buildOverlayDiscardQuery(context, entityKey, entityKeyJson);\n await db.query(overlayQuery.sql, overlayQuery.params as unknown[]);\n\n await db.exec(\"COMMIT\");\n } catch (error) {\n await db.exec(\"ROLLBACK\");\n throw error;\n }\n}\n\n/**\n * The shared overlay-discard statement: delete the entity's overlay row unless a journal row still\n * owes the entity — `owedStatuses` narrows which journal rows count as \"owed\" (all of them for a\n * conflict discard; only the un-sent pending/sending/failed set for a settled-unit discard).\n */\nfunction buildOverlayDiscardQuery(\n context: TableContext,\n entityKey: Record<string, string>,\n entityKeyJson: string,\n owedStatuses?: MutationStatus[],\n) {\n const overlay = context.tables.overlay;\n const journal = context.tables.journal;\n const owed = queryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(\n owedStatuses\n ? and(eq(journal.entityKeyJson, entityKeyJson), inArray(journal.status, owedStatuses))\n : eq(journal.entityKeyJson, entityKeyJson),\n );\n\n return queryBuilder\n .delete(overlay)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.overlayPkColumns[index]!, entityKey[columnName]),\n ),\n notExists(owed),\n ),\n )\n .toSQL();\n}\n\n/**\n * Auto-discard the optimistic overlay for an entity whose pessimistic write-unit the authoritative endpoint\n * `rejected` (ADR-0022 §4). Unlike {@link discardTerminalEntity} this KEEPS the terminal `rejected` journal\n * row (for diagnostics + `onReject`); it only clears the overlay, and only when no still-owed\n * (`pending`/`sending`/`failed`) journal row depends on it — so a later un-sent write never loses its overlay.\n */\nasync function discardOverlayForSettledEntity(\n db: MutationDb,\n context: TableContext,\n entityKey: Record<string, string>,\n entityKeyJson: string,\n) {\n const query = buildOverlayDiscardQuery(context, entityKey, entityKeyJson, [\"pending\", \"sending\", \"failed\"]);\n await db.query(query.sql, query.params as unknown[]);\n}\n\nasync function reconcileTable(db: MutationDb, context: TableContext) {\n // Idle fast-path. Reconcile only retires/clears journal rows in a terminal-clearable state — 'acked'\n // (clear the overlay once the echo lands) or 'conflicted' (retire once a later write resolved it). When\n // none exist — the steady state of an idle entity set — all three statements below are no-ops, so skip\n // the whole transaction. This matters because the convergence driver runs reconcile for EVERY writable\n // table on its interval (default 1.5s), and each CTE pays full PGlite plan+execute cost even against an\n // empty journal: left unguarded it is the dominant idle-CPU cost. The real-time cleanup path is the\n // <table>_reconcile_on_sync trigger; this bulk pass is a fallback, so skipping it when there is nothing\n // to clear changes no outcome. The guard is a single existence probe over the (small, usually empty)\n // journal.\n const journal = context.tables.journal;\n const overlay = context.tables.overlay;\n const synced = context.tables.synced;\n // This is the idle-CPU hot statement (it runs for every writable table on every convergence\n // tick), so the rendered text+params are memoized per context — each tick pays only a plain\n // `db.query` of a cached string, and it stays OUTSIDE any transaction (no BEGIN on the idle path).\n let idleProbe = context.reconcileIdleProbe;\n if (!idleProbe) {\n const probeQuery = queryDialect.sqlToQuery(\n sql`SELECT ${exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(inArray(journal.status, [\"acked\", \"conflicted\"])),\n )} AS \"hasWork\"`,\n );\n idleProbe = { sql: probeQuery.sql, params: probeQuery.params as unknown[] };\n context.reconcileIdleProbe = idleProbe;\n }\n const work = await db.query<{ hasWork: boolean }>(idleProbe.sql, idleProbe.params);\n if (work.rows[0]?.hasWork !== true) {\n return;\n }\n\n // The Convergence barrier (ADR-0010) gates the acked-row clearing below; the synced-table trigger\n // handles real-time cleanup, and this is the bulk recovery/fallback path that runs after every flush.\n await db.exec(\"BEGIN\");\n\n try {\n // ADR-0015: retire a terminal `conflicted` row once the user has RESOLVED it — i.e. a LATER write\n // on the same entity has been acked (resolution is an ordinary new mutation). Without this, the old\n // conflicted row lingers forever: `<table>_sync_state.conflict_state` keeps surfacing the resolved\n // conflict and `diagnostics().conflictedCount` never drops. Run before the acked-clear below so the\n // resolving row is still present to supersede it. (`discardConflict` is the explicit throw-away path.)\n // Drizzle DELETE has no USING; the resolver leg is the equivalent EXISTS semi-join.\n const resolver = alias(journal, \"resolver\");\n const retireQuery = queryBuilder\n .delete(journal)\n .where(\n and(\n eq(journal.status, \"conflicted\"),\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(resolver)\n .where(\n and(\n eq(resolver.entityKeyJson, journal.entityKeyJson),\n gt(resolver.mutationSeq, journal.mutationSeq),\n eq(resolver.status, \"acked\"),\n ),\n ),\n ),\n ),\n )\n .toSQL();\n await db.query(retireQuery.sql, retireQuery.params as unknown[]);\n\n // ADR-0022 addendum — retire an acked `pessimistic-blind` row with NO echo barrier. A blind update's\n // write target is excluded from this actor's read shape, so no synced echo will ever land for it and no\n // overlay was ever planned: the standard acked-clear below (gated on a synced row reaching the acked\n // version) would keep it forever. Nothing local converges for these rows, so once the authoritative unit\n // acked them there is nothing left to do but drop the journal row. Crash-safe: any later reconcile tick\n // clears a blind row the foreground flushUnit didn't survive to reconcile.\n const blindRetireQuery = queryBuilder\n .delete(journal)\n .where(and(eq(journal.status, \"acked\"), eq(journal.writeMode, \"pessimistic-blind\")))\n .toSQL();\n await db.query(blindRetireQuery.sql, blindRetireQuery.params as unknown[]);\n\n // Clear acknowledged non-delete mutations + matching overlays. ADR-0010: gated by the\n // Convergence barrier (same predicate as the trigger) — the acked write clears only once the\n // synced echo's Server version has reached its acked version. Joining the synced table makes\n // the comparison possible (and means an un-synced acked write is held until its echo lands).\n // Drizzle authoring: DELETE..USING becomes the equivalent EXISTS semi-join, chained through a\n // data-modifying CTE (both sub-statements see the same statement-start snapshot, exactly like\n // the USING form). The barrier predicate stays the shared contracts helper (single authority\n // with the trigger); it renders against the tables' own names, which is how drizzle references\n // their columns here (no aliases on a DELETE target).\n const barrier = sql.raw(\n buildOverlayResolutionBarrier(context.entry, {\n journalAlias: quoteIdentifier(getTableConfig(journal).name),\n syncedAlias: quoteIdentifier(getTableConfig(synced).name),\n }),\n );\n const clearedJournal = queryBuilder.$with(\"cleared_journal\").as(\n queryBuilder\n .delete(journal)\n .where(\n and(\n eq(journal.status, \"acked\"),\n isNotNull(journal.serverUpdatedAtUs),\n ne(journal.mutationKind, \"delete\"),\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(synced)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.syncedPkColumns[index]!, journal[columnName]!),\n ),\n barrier,\n ),\n ),\n ),\n ),\n )\n .returning(\n Object.fromEntries([\n [\"entity_key_json\", journal.entityKeyJson],\n ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]!]),\n ]),\n ),\n );\n const clearedJournalColumns = clearedJournal as unknown as Record<string, PgColumn>;\n const ackedClearQuery = queryBuilder\n .with(clearedJournal)\n .delete(overlay)\n .where(\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(clearedJournal)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.overlayPkColumns[index]!, clearedJournalColumns[columnName]!),\n ),\n notExists(\n queryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(\n and(\n eq(journal.entityKeyJson, clearedJournalColumns[\"entity_key_json\"]!),\n inArray(journal.status, [\"pending\", \"sending\", \"failed\"]),\n ),\n ),\n ),\n ),\n ),\n ),\n )\n .toSQL();\n await db.query(ackedClearQuery.sql, ackedClearQuery.params as unknown[]);\n\n // Clear acknowledged delete mutations where synced row is absent\n // Single compound CTE — PGlite does not support multi-statement query().\n const clearableEntities = queryBuilder.$with(\"clearable_entities\").as(\n queryBuilder\n .selectDistinct(\n Object.fromEntries([\n [\"entity_key_json\", journal.entityKeyJson],\n ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]!]),\n ]),\n )\n .from(journal)\n .leftJoin(\n synced,\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.syncedPkColumns[index]!, journal[columnName]!),\n ),\n ),\n )\n .where(\n and(eq(journal.status, \"acked\"), eq(journal.mutationKind, \"delete\"), isNull(context.syncedPkColumns[0]!)),\n ),\n );\n const clearableEntityColumns = clearableEntities as unknown as Record<string, PgColumn>;\n const deletedOverlay = queryBuilder.$with(\"deleted_overlay\").as(\n queryBuilder.delete(overlay).where(\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(clearableEntities)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.overlayPkColumns[index]!, clearableEntityColumns[columnName]!),\n ),\n ),\n ),\n ),\n ),\n );\n const deleteClearQuery = queryBuilder\n .with(clearableEntities, deletedOverlay)\n .delete(journal)\n .where(\n and(\n eq(journal.status, \"acked\"),\n eq(journal.mutationKind, \"delete\"),\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(clearableEntities)\n .where(\n and(\n ...context.pkColumnNames.map((columnName) =>\n eq(journal[columnName]!, clearableEntityColumns[columnName]!),\n ),\n ),\n ),\n ),\n ),\n )\n .toSQL();\n await db.query(deleteClearQuery.sql, deleteClearQuery.params as unknown[]);\n await db.exec(\"COMMIT\");\n } catch (error) {\n await db.exec(\"ROLLBACK\");\n throw error;\n }\n}\n\nfunction buildRequestHeaders(bearerToken?: string, requestHeaders?: Record<string, string>): Record<string, string> {\n // Static headers first so the toolkit-owned Content-Type/Authorization always win.\n return {\n ...(requestHeaders ?? {}),\n \"Content-Type\": \"application/json\",\n ...(bearerToken ? { Authorization: `Bearer ${bearerToken}` } : {}),\n };\n}\n\nasync function applyMutationStatusUpdates(db: MutationDb, context: TableContext, updates: MutationStatusUpdate[]) {\n if (updates.length === 0) {\n return;\n }\n\n // Tier ②: `update().from(<VALUES>)`. Every value is a bound param with the same cast as before;\n // the `updates` alias and its column list are fixed by this function (not derived from data), so\n // the alias-qualified references in SET/WHERE are fixed template text, while the journal side of\n // each CASE interpolates the column objects.\n const journal = context.tables.journal;\n const tuples = updates.map(\n (update) =>\n sql`(${update.mutationId}, ${update.status}, ${update.attemptCount}::int, ${update.updatedAtUs}::bigint, ${\n update.sentAtUs ?? null\n }::bigint, ${update.replaceSentAtUs ?? false}::boolean, ${update.ackedAtUs ?? null}::bigint, ${\n update.replaceAckedAtUs ?? false\n }::boolean, ${update.serverUpdatedAtUs ?? null}::bigint, ${update.replaceServerUpdatedAtUs ?? false}::boolean, ${\n update.baseServerVersion ?? null\n }::bigint, ${update.replaceBaseServerVersion ?? false}::boolean, ${update.lastError ?? null}, ${\n update.nextRetryAtUs ?? null\n }::bigint, ${update.lastHttpStatus ?? null}::int, ${update.conflictReason ?? null})`,\n );\n const updatesTable = sql`(VALUES ${sql.join(\n tuples,\n sql`, `,\n )}) AS updates (mutation_id, status, attempt_count, updated_at_us, sent_at_us, replace_sent_at_us, acked_at_us, replace_acked_at_us, server_updated_at_us, replace_server_updated_at_us, base_server_version, replace_base_server_version, last_error, next_retry_at_us, last_http_status, conflict_reason)`;\n\n const query = queryBuilder\n .update(journal)\n .set({\n status: sql`updates.status`,\n attemptCount: sql`updates.attempt_count`,\n updatedAtUs: sql`updates.updated_at_us::bigint`,\n sentAtUs: sql`CASE WHEN updates.replace_sent_at_us THEN updates.sent_at_us::bigint ELSE ${journal.sentAtUs} END`,\n ackedAtUs: sql`CASE WHEN updates.replace_acked_at_us THEN updates.acked_at_us::bigint ELSE ${journal.ackedAtUs} END`,\n serverUpdatedAtUs: sql`CASE WHEN updates.replace_server_updated_at_us THEN updates.server_updated_at_us::bigint ELSE ${journal.serverUpdatedAtUs} END`,\n baseServerVersion: sql`CASE WHEN updates.replace_base_server_version THEN updates.base_server_version::bigint ELSE ${journal.baseServerVersion} END`,\n lastError: sql`updates.last_error`,\n nextRetryAtUs: sql`updates.next_retry_at_us::bigint`,\n lastHttpStatus: sql`updates.last_http_status`,\n conflictReason: sql`updates.conflict_reason`,\n })\n .from(updatesTable)\n .where(eq(journal.mutationId, sql`updates.mutation_id::uuid`))\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\nfunction qualifyLocalIdentifier(schemaName: string, tableName: string) {\n if (schemaName === \"public\") {\n // Quote-when-needed: a reserved-word or mixed-case table name (e.g. `group`)\n // MUST be quoted or the generated SQL fails to parse (ADR-0004). Normal names\n // stay bare, so existing generated SQL is unchanged.\n return maybeQuoteIdentifier(tableName);\n }\n\n return `${quoteIdentifier(schemaName)}.${quoteIdentifier(tableName)}`;\n}\n\nfunction buildJournalSequenceName(journalTable: string) {\n return `${journalTable}_mutation_seq`;\n}\n\nfunction hasProperty(context: TableContext, propertyKey: string) {\n return context.columns.some((column) => column.propertyKey === propertyKey);\n}\n\nfunction ensureRecord(value: unknown) {\n if (!isRecord(value)) {\n throw new Error(\"Mutation runtime expected a record payload\");\n }\n\n return value;\n}\n\nfunction extractRecordFromState(context: TableContext, state: CurrentRecordStateRow | BatchCurrentRecordStateRow) {\n return Object.fromEntries(context.columns.map(({ propertyKey }) => [propertyKey, state[propertyKey] ?? null]));\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nclass MutationRequestError extends Error {\n readonly status: number;\n /** Per-mutation attribution the server returned for a structural rejection, or null. */\n readonly rejections: MutationRejection[] | null;\n\n constructor(message: string, status: number, rejections: MutationRejection[] | null = null) {\n super(message);\n this.name = \"MutationRequestError\";\n this.status = status;\n this.rejections = rejections;\n }\n}\n\n/**\n * Extract per-mutation attribution from a non-2xx batch-write body. The server names the\n * offending mutations on a structural (validation) rejection; an absent, non-JSON, or\n * empty-`rejections` body yields null, so the failure is treated as non-attributable\n * (whole batch stays retryable).\n */\nfunction parseBatchRejections(body: string): MutationRejection[] | null {\n if (body.length === 0) {\n return null;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return null;\n }\n\n const result = batchMutationErrorSchema.safeParse(parsed);\n const rejections = result.success ? result.data.rejections : undefined;\n return rejections && rejections.length > 0 ? rejections : null;\n}\n",
137
+ "/**\n * The mutation-journal state machine (ADR-0005, extended by ADR-0006).\n *\n * The runtime is large; previously the legal status transitions were implicit,\n * scattered across SQL writes. This is the one named place that defines them, so the\n * rules are testable and a future change extends a single table. ADR-0006 splits the\n * old single `failed` into transient (retryable `failed`) and permanent (`quarantined`).\n */\n\nexport type MutationStatus = \"pending\" | \"sending\" | \"acked\" | \"failed\" | \"quarantined\" | \"conflicted\" | \"rejected\";\n\n/**\n * Legal transitions. `acked` is terminal at the journal level — it is cleared by\n * reconciliation once the synced echo reaches the acknowledged server timestamp, not\n * by another status transition. `quarantined` is terminal too: the server will never\n * accept the mutation as-is, so it is surfaced (callback + diagnostics), never retried.\n * `conflicted` (ADR-0015) is likewise terminal but a *different* outcome: the write was\n * well-formed but **stale** (an external write interleaved) and the table's `reject-if-stale`\n * policy declined it. The optimistic Overlay is KEPT (the user's edit is not lost) and the\n * conflict is surfaced via `onConflict`; resolution is an ordinary NEW mutation, and `discard`\n * clears the overlay + this entry. It is never retried as-is (the base would still be stale).\n * `rejected` (ADR-0022) is terminal as well, and the inverse of `conflicted` on disposition: the\n * authoritative endpoint declined the whole pessimistic write-**unit** for a business reason (a\n * capacity/quota/uniqueness rule the client could not evaluate locally), so the optimistic Overlay\n * is **auto-discarded** for every member of the unit and the typed reason is surfaced via `onReject`.\n * Never retried (the server's answer is authoritative).\n *\n * - `pending -> sending` a flush claims the row and posts it.\n * - `sending -> acked` the server acknowledged the mutation.\n * - `sending -> failed` transient transport/server error (network, 5xx, …).\n * - `sending -> quarantined` structural 4xx rejection the server will never accept.\n * - `sending -> conflicted` a stale write the reject-if-stale policy declined (ADR-0015).\n * - `sending -> rejected` a business rejection from the authoritative endpoint (ADR-0022).\n * - `sending -> pending` recoverSending re-queues an in-flight row on startup.\n * - `pending -> quarantined` a RESTORE boot quarantines every non-terminal row recovered from a\n * backup (ADR-0035 decision 6). A `pending` row is normally only ever claimed (`-> sending`), but a\n * store restored from a backup must NOT auto-flush anything it recovered — the write path has no\n * `mutationId` dedupe ledger, so replaying a recovered `pending`/`sending`/`failed` mutation is unsafe\n * (silent last-write-wins reverts, create PK collisions). Restore is therefore the ONE producer of this\n * edge; ordinary boots never move a `pending` row straight to `quarantined`.\n * - `failed -> pending` retryFailed re-queues a failed row.\n * - `failed -> quarantined` the hard max-attempts cap is reached; stop retrying (also the restore\n * quarantine of a recovered `failed` row, ADR-0035 decision 6 — the edge already existed).\n */\nexport const MUTATION_TRANSITIONS = {\n // `pending -> quarantined` exists ONLY for the restore-boot quarantine (ADR-0035 decision 6); the normal\n // flush path only ever claims a pending row (`-> sending`).\n pending: [\"sending\", \"quarantined\"],\n sending: [\"acked\", \"failed\", \"quarantined\", \"conflicted\", \"rejected\", \"pending\"],\n failed: [\"pending\", \"quarantined\"],\n quarantined: [],\n conflicted: [],\n rejected: [],\n acked: [],\n} as const satisfies Record<MutationStatus, readonly MutationStatus[]>;\n\nexport function isValidMutationTransition(from: MutationStatus, to: MutationStatus): boolean {\n return (MUTATION_TRANSITIONS[from] as readonly MutationStatus[]).includes(to);\n}\n\nexport function assertValidMutationTransition(from: MutationStatus, to: MutationStatus): void {\n if (!isValidMutationTransition(from, to)) {\n throw new Error(`Illegal mutation-journal transition: ${from} -> ${to}`);\n }\n}\n\n/**\n * The hard cap on send attempts (ADR-0005 congestion policy). A mutation that has\n * failed this many times — even with transient-looking errors — is given up on and\n * quarantined, so a permanently-unreachable server never produces an unbounded retry\n * loop. The consumer can raise/lower it via `createSyncClient({ maxMutationAttempts })`.\n */\nexport const DEFAULT_MAX_MUTATION_ATTEMPTS = 10;\n\n/**\n * 4xx statuses that are nonetheless transient: auth (the runtime refreshes the token and\n * retries), request-timeout, too-early, and rate-limit. Everything else in the 4xx range\n * is treated as a structural rejection the server will never accept as-is.\n */\nconst TRANSIENT_CLIENT_ERROR_STATUSES: ReadonlySet<number> = new Set([401, 403, 408, 425, 429]);\n\n/**\n * Classify a flush failure into its durable journal state (ADR-0006 decision 4):\n * - `quarantined` (terminal): a structural 4xx rejection — retrying is pointless, so it\n * is surfaced rather than retry-looped (the silent-data-loss case the runtime *can*\n * catch at send time).\n * - `failed` (retryable): network/transport (no status), any 5xx, or a transient 4xx.\n */\nexport function classifyFailureStatus(httpStatus: number | null | undefined): \"failed\" | \"quarantined\" {\n if (httpStatus == null) {\n return \"failed\";\n }\n\n if (httpStatus >= 400 && httpStatus < 500 && !TRANSIENT_CLIENT_ERROR_STATUSES.has(httpStatus)) {\n return \"quarantined\";\n }\n\n return \"failed\";\n}\n",
138
+ "import {\n and,\n desc,\n eq,\n exists,\n getColumns,\n gt,\n inArray,\n is,\n isNotNull,\n isNull,\n lt,\n ne,\n notExists,\n SQL,\n sql,\n} from \"drizzle-orm\";\nimport {\n alias,\n getTableConfig,\n getViewConfig,\n PgDialect,\n type AnyPgTable,\n type PgColumn,\n type PgInsertValue,\n} from \"drizzle-orm/pg-core\";\nimport { drizzle } from \"drizzle-orm/pglite\";\n\nimport {\n getJournalTable,\n getOverlayTable,\n getSyncedLocalTable,\n type JournalTable,\n type OverlayTable,\n} from \"./local-tables\";\n\n// Statements are AUTHORED as Drizzle builders over the journal/overlay/synced table objects\n// (rename-safe, typed, schema-qualification handled by the table objects) and rendered to\n// text+params here, because they EXECUTE through the caller's raw `MutationDb` seam — the one\n// connection the mutation runtime and its tests own (and mock). `drizzle.mock()` builds queries\n// without a connection; `queryDialect` renders standalone `sql` fragments the builders cannot\n// express (compound CTE shapes, derived-table wrappers).\nconst queryBuilder = drizzle.mock();\nconst queryDialect = new PgDialect();\n\n/**\n * Strip the two internal overlay columns that appear on _read_model views\n * (`overlay_kind`, `local_updated_at_us`) from any user-supplied input or\n * patch object before it is serialised into a mutation payload. Callers\n * that spread a view row directly into a create/update call would otherwise\n * hit `TypeError: Do not know how to serialize a BigInt` because\n * `local_updated_at_us` is stored as a native JS `bigint`.\n */\nfunction stripReadModelOverlayFields<T>(value: T): T {\n if (value === null || typeof value !== \"object\") return value;\n const obj = value as Record<string, unknown>;\n if (!(\"overlay_kind\" in obj) && !(\"local_updated_at_us\" in obj)) return value;\n const { overlay_kind: _ok, local_updated_at_us: _lu, ...rest } = obj;\n return rest as T;\n}\n\n/**\n * JSON replacer that serialises `bigint` values as strings. PostgreSQL\n * accepts string literals for BIGINT columns, and JSON has no native bigint\n * type, so this is the safest cross-boundary representation.\n */\nfunction bigintReplacer(_key: string, value: unknown): unknown {\n return typeof value === \"bigint\" ? String(value) : value;\n}\n\nfunction jsonStringifyPayload(value: unknown): string {\n return JSON.stringify(value, bigintReplacer);\n}\n\nimport type {\n BatchMutationAck,\n MutationAck,\n MutationDiagnostics,\n MutationRejection,\n SyncTableCreateInput,\n SyncTableEntry,\n SyncTableName,\n SyncTableRecord,\n SyncTableRegistry,\n SyncTableUpdateInput,\n WriteMode,\n} from \"@pgxsinkit/contracts\";\nimport {\n batchMutationErrorSchema,\n buildOverlayResolutionBarrier,\n fingerprintRegistry,\n getProjectedColumns as getProjectedTableColumns,\n getSyncRegistrySchema,\n maybeQuoteIdentifier,\n quoteIdentifier,\n resolveServerVersionColumnName,\n} from \"@pgxsinkit/contracts\";\n\nimport { syncDebug } from \"./debug\";\nimport {\n assertValidMutationTransition,\n classifyFailureStatus,\n DEFAULT_MAX_MUTATION_ATTEMPTS,\n type MutationStatus,\n} from \"./mutation-state\";\n\nexport type { MutationStatus } from \"./mutation-state\";\nexport type MutationKind = \"create\" | \"update\" | \"delete\";\n\n/**\n * The dynamic write-unit tag (ADR-0022 §2) a `transaction({ mode })` block stamps onto the mutations\n * authored within it: a shared `id` grouping the co-committed mutations, and the unit's `mode`. Persisted\n * on each journal row (`write_unit` / `write_mode`); absent for the default path, where the flusher derives\n * mode + unit from the table's static consistency group.\n */\nexport interface WriteUnit {\n id: string;\n mode: WriteMode;\n}\n\nexport type MutationBatchItem<TRegistry extends SyncTableRegistry> = {\n [TKey in SyncTableName<TRegistry>]:\n | {\n table: TKey;\n kind: \"create\";\n input: SyncTableCreateInput<TRegistry, TKey>;\n }\n | {\n table: TKey;\n kind: \"update\";\n entityKey: Record<string, string>;\n patch: SyncTableUpdateInput<TRegistry, TKey>;\n /**\n * A **blind** update (ADR-0022 addendum): plan a journal row ONLY — no local base row is required\n * and no optimistic overlay is written. Set exclusively by the transaction handle's `updateBlind`;\n * valid only when the write routes pessimistically (a `pessimistic` unit, or a statically-pessimistic\n * table), and rejected at enqueue otherwise. Absent/false for an ordinary update.\n */\n blind?: boolean;\n }\n | {\n table: TKey;\n kind: \"delete\";\n entityKey: Record<string, string>;\n };\n}[SyncTableName<TRegistry>];\n\nexport const DEFAULT_FLUSH_BATCH_SIZE = 100;\n\nexport interface MutationDetail {\n tableName: string;\n entityKey: Record<string, string>;\n mutationId: string;\n mutationSeq: number;\n mutationKind: MutationKind;\n status: MutationStatus;\n attemptCount: number;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n updatedAtUs: string;\n /** Registry fingerprint (ADR-0004) the mutation was authored under, or null if unstamped. */\n registryVersion: string | null;\n}\n\nexport interface MutationDb {\n exec: (sql: string) => Promise<unknown>;\n query: <TRow extends Record<string, unknown> = Record<string, unknown>>(\n sql: string,\n params?: unknown[],\n ) => Promise<{ rows: TRow[] }>;\n}\n\nexport interface CreateMutationRuntimeOptions<TRegistry extends SyncTableRegistry> {\n db: MutationDb;\n registry: TRegistry;\n writeUrl: string;\n getAuthToken?: () => Promise<string | undefined>;\n /** Static headers added to every write request (e.g. a Supabase Cloud `apikey`); see {@link CreateSyncClientOptions.requestHeaders}. */\n requestHeaders?: Record<string, string>;\n /**\n * Registry fingerprint (ADR-0004) stamped onto each enqueued mutation as its\n * `registry_version`, so a version-boundary crossing is known before sending (ADR-0006).\n */\n registryVersion?: string;\n /**\n * Hard cap on send attempts before a still-failing mutation is quarantined\n * (ADR-0005 congestion policy). Defaults to {@link DEFAULT_MAX_MUTATION_ATTEMPTS}.\n */\n maxMutationAttempts?: number;\n /**\n * Max mutations drained per flush HTTP request; a flush loops slices until the journal is empty.\n * Defaults to {@link DEFAULT_FLUSH_BATCH_SIZE}. Primarily a test seam (a small value exercises the\n * multi-slice drain path without enqueueing hundreds of mutations).\n */\n flushBatchSize?: number;\n /**\n * Invoked after a flush whenever mutations transition to `quarantined` (terminal,\n * permanently rejected). Receives the newly-quarantined details so the app can surface\n * them, then either re-author + resubmit or roll back via {@link MutationRuntime.discardQuarantined}\n * (clears the kept overlay + quarantined journal rows, so the entity accepts new mutations again).\n * The library never silently drops these (ADR-0006 decision 4).\n */\n onQuarantine?: (quarantined: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked after a flush whenever mutations transition to `conflicted` — a stale write the\n * server declined under the `reject-if-stale` Conflict policy (ADR-0015). Distinct from\n * `onQuarantine` (structural rejection): the optimistic Overlay is KEPT, so the app surfaces a\n * resolution/diff UI and resolves each as a new write (or `discardConflict`s it). Never silent.\n */\n onConflict?: (conflicted: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked after an authoritative (pessimistic) flush whenever a write-unit was `rejected` (ADR-0022) —\n * a business decline the client could not evaluate locally (capacity/quota/uniqueness). The inverse of\n * `onConflict`: the optimistic Overlay was **auto-discarded** for every member of the unit, so the app\n * surfaces the typed reason (e.g. \"full\") rather than a resolve/diff UI. Never silent.\n */\n onReject?: (rejected: MutationDetail[]) => void | Promise<void>;\n}\n\ninterface TableContext {\n key: string;\n entry: SyncTableEntry<AnyPgTable>;\n readModel: string;\n syncedTable: string;\n overlayTable: string;\n journalTable: string;\n journalSequence: string;\n pkColumnNames: string[];\n pkPropertyKeys: string[];\n /**\n * The Server version (ADR-0010) column name (e.g. `updated_at_us`) and its drizzle property key,\n * resolved from the table's managed fields. Used to capture the Base server version (ADR-0015) at\n * enqueue — the value the user's edit was authored against. `null` would mean no Server version,\n * which registry validation already forbids for a writable table.\n */\n serverVersionColumnName: string | null;\n serverVersionPropertyKey: string | null;\n /**\n * Property keys of the table's `nowMicroseconds` managed fields (governance), resolved generically\n * rather than by the `createdAtUs`/`updatedAtUs` naming convention. The optimistic overlay stamps\n * these client-side so a custom-named managed timestamp (e.g. a Server version not called\n * `updated_at_us`) is materialised correctly — closing the split interpreter between the generic\n * server applier (which reads governance) and the local path (ADR-0004).\n *\n * - `managedNowMicrosecondsPropertyKeys` — every `nowMicroseconds` field, stamped on create.\n * - `updateManagedNowMicrosecondsPropertyKeys` — those that apply on update, re-stamped each update.\n *\n * These augment, and never remove, the convention fill in `createOptimisticRecordFromContext`,\n * which remains the safety net for a `created_at_us`/`updated_at_us` column that carries a SQL\n * `DEFAULT` (unmaterialisable client-side) yet is not declared a managed field.\n */\n managedNowMicrosecondsPropertyKeys: string[];\n updateManagedNowMicrosecondsPropertyKeys: string[];\n /**\n * The table's `authClaim` managed fields that apply on create (governance), each with the JSON\n * claimPath it stamps from. The server stamps these from the verified request claims, so they are\n * stripped from the create input type and never sent in the flushed payload. But the optimistic\n * overlay still needs a value — such a column is typically `NOT NULL` (an owner/author/created_by) —\n * so the runtime fills it client-side from the decoded JWT claim at the same path (the same value the\n * server will stamp), so the local row renders attributed immediately and never flips on convergence.\n * (`auth.uid()` is just `claimPath: [\"sub\"]`, so this one path covers it.)\n */\n managedAuthClaimCreateFields: Array<{ propertyKey: string; claimPath: string[] }>;\n recordIncludesOverlayState: boolean;\n columns: Array<{\n propertyKey: string;\n column: ReturnType<typeof getProjectedTableColumns<AnyPgTable>>[number][\"column\"];\n }>;\n /**\n * The generated local relations as runtime Drizzle table objects (local-tables.ts), so the\n * runtime's statements are AUTHORED as tier-① builders while still EXECUTING through the raw\n * `MutationDb` seam. Journal fixed columns are camelCase-keyed; per-entry PK columns are keyed\n * by DB column name; overlay/synced columns are keyed by drizzle property key.\n */\n tables: {\n synced: AnyPgTable;\n overlay: OverlayTable;\n journal: JournalTable;\n };\n /** Overlay columns keyed by property key (`getColumns` memo — overlay keys are property keys, not DB names). */\n overlayColumnsByPropertyKey: Record<string, PgColumn>;\n /** Synced read-cache columns keyed by property key. */\n syncedColumnsByPropertyKey: Record<string, PgColumn>;\n /** The entry's PK columns ON THE OVERLAY, resolved by DB column name (ordered like `pkColumnNames`). */\n overlayPkColumns: PgColumn[];\n /** The entry's PK columns ON THE SYNCED table, resolved by DB column name (ordered like `pkColumnNames`). */\n syncedPkColumns: PgColumn[];\n /** The Server version column ON THE SYNCED table (ADR-0010), or null when the table declares none. */\n syncedServerVersionColumn: PgColumn | null;\n /**\n * Memoized render of the reconcile idle probe (the per-tick hot statement): built once per\n * context so every convergence tick pays only a plain `db.query` of a cached string.\n */\n reconcileIdleProbe?: { sql: string; params: unknown[] };\n}\n\nexport interface MutationRuntime<TRegistry extends SyncTableRegistry> {\n /** The registry fingerprint (ADR-0004) this runtime stamps onto enqueued mutations. */\n registryVersion: string;\n create: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n input: SyncTableCreateInput<TRegistry, TKey>,\n ) => Promise<void>;\n update: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n patch: SyncTableUpdateInput<TRegistry, TKey>,\n ) => Promise<void>;\n delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;\n /**\n * Enqueue an atomic batch of mutations. An optional {@link WriteUnit} tags every row of the batch as one\n * dynamic write-unit (ADR-0022 §2) — the `transaction({ mode })` block passes it; the per-table\n * `create`/`update`/`delete` helpers do not (their write-mode comes from the static group at flush).\n */\n batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>, unit?: WriteUnit) => Promise<void>;\n /**\n * Discard a `conflicted` entity (ADR-0015): clear its conflicted journal entries and the kept\n * optimistic Overlay, so the Read model falls back to the synced (server) value. Use when the user\n * abandons their stale edit instead of resolving it as a new write. No-op for an entity with no\n * conflicted entry.\n */\n discardConflict: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n /**\n * Discard a `quarantined` entity (ADR-0006): clear its quarantined journal entries and the kept\n * optimistic Overlay, so the Read model falls back to the synced (server) value and the entity\n * accepts new mutations again. The rollback path for a permanently-rejected write (e.g. an RLS\n * policy denial routed to quarantine). Symmetric to {@link discardConflict}. No-op for an entity\n * with no quarantined entry; the overlay is kept when another still-owed write depends on it.\n */\n discardQuarantined: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n flush: (table?: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * Flush one pessimistic write-unit (ADR-0022) to the authoritative endpoint and apply its per-mutation\n * result inline: `acked` clears via the synced echo, `conflicted` keeps the overlay (surfaced), and\n * `rejected` auto-discards the overlay for the whole unit (surfaced via `onReject`). A foreground\n * operation — it resolves once the server has decided. Throws on transport failure (the overlay is kept\n * for a retry). Returns the server acks. Used by the client `transaction({ mode: \"pessimistic\" })` block.\n */\n flushUnit: (unitId: string) => Promise<{ acks: MutationAck[] }>;\n reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;\n retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;\n recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * Quarantine EVERY non-terminal journal row recovered from a backup (`pending`/`sending`/`failed` →\n * `quarantined`) — the restore-boot rule (ADR-0035 decision 6). Nothing recovered from a store backup\n * may ever auto-flush: the write path keeps `mutationId` in `operations_log` but never consults it, so\n * there is no dedupe ledger, and a replayed mutation would silently re-apply stale values over newer\n * writes on a last-write-wins table (and a replayed create collides on its PK). Terminal states\n * (`acked`/`conflicted`/`rejected`) are left untouched. Run ONCE, on the restore boot only, AFTER\n * `recoverSending` (which first lifts any `sending` back to `pending`); the app then inspects\n * `diagnostics()` and resolves each row via `discardQuarantined` (quarantine is terminal — \"release\"\n * means discard and re-author as a new mutation) before going online. A no-op on a clean journal.\n */\n quarantineRecovered: (table?: SyncTableName<TRegistry>) => Promise<void>;\n readMutationStats: (table?: SyncTableName<TRegistry>) => Promise<MutationDiagnostics>;\n readMutationDetails: (table?: SyncTableName<TRegistry>) => Promise<MutationDetail[]>;\n createOptimisticRecord: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n input: SyncTableCreateInput<TRegistry, TKey>,\n ) => SyncTableRecord<TRegistry, TKey>;\n}\n\nexport function nowMicroseconds(): string {\n return (BigInt(Date.now()) * 1000n).toString();\n}\n\n/**\n * Best-effort decode of a JWT's claims payload, for stamping `authClaim` managed fields into the\n * optimistic overlay (the value the server will independently stamp from the same claim path). This is\n * **not** a verification — the token is trusted only for a local, optimistic projection that the server\n * re-stamps authoritatively on apply; a forged claim could never make the server attribute the row\n * differently. Returns `undefined` for a malformed token.\n */\nexport function decodeJwtClaims(token: string): Record<string, unknown> | undefined {\n const segments = token.split(\".\");\n if (segments.length < 2 || !segments[1]) {\n return undefined;\n }\n try {\n const normalized = segments[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = normalized.padEnd(normalized.length + ((4 - (normalized.length % 4)) % 4), \"=\");\n const binary = atob(padded);\n const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));\n const payload = JSON.parse(new TextDecoder().decode(bytes)) as unknown;\n return typeof payload === \"object\" && payload !== null ? (payload as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Read a claim at a JSON path out of a decoded claims object, returning it as a string (the form the\n * optimistic overlay column expects, mirroring the server's `jsonb #>>` text extraction). Returns\n * `undefined` if the path is absent or the leaf is not a string/number.\n */\nexport function readJwtClaimPath(claims: Record<string, unknown>, claimPath: string[]): string | undefined {\n let cursor: unknown = claims;\n for (const segment of claimPath) {\n if (typeof cursor !== \"object\" || cursor === null) {\n return undefined;\n }\n cursor = (cursor as Record<string, unknown>)[segment];\n }\n if (typeof cursor === \"string\") {\n return cursor;\n }\n return typeof cursor === \"number\" ? String(cursor) : undefined;\n}\n\nexport function computeBackoffDelayMs(attemptCount: number) {\n const exponent = Math.max(attemptCount - 1, 0);\n return Math.min(1000 * 2 ** exponent, 30_000);\n}\n\n/**\n * Retry delay with equal jitter around the {@link computeBackoffDelayMs} ceiling: half\n * the ceiling plus a random share of the other half. Spreads retries so a fleet of\n * clients does not stampede the server in lockstep after an outage (ADR-0005 congestion\n * policy). `random` is injectable for deterministic tests.\n */\nexport function computeRetryDelayMs(attemptCount: number, random: () => number = Math.random) {\n const ceiling = computeBackoffDelayMs(attemptCount);\n return Math.round(ceiling / 2 + random() * (ceiling / 2));\n}\n\nexport function computeNextRetryAtUs(nowUs: string, attemptCount: number, random: () => number = Math.random) {\n return (BigInt(nowUs) + BigInt(computeRetryDelayMs(attemptCount, random)) * 1000n).toString();\n}\n\nexport function createMutationRuntime<TRegistry extends SyncTableRegistry>(\n options: CreateMutationRuntimeOptions<TRegistry>,\n): MutationRuntime<TRegistry> {\n const resolveAuthToken = async () => {\n if (options.getAuthToken) {\n return await options.getAuthToken();\n }\n\n return undefined;\n };\n\n // The decoded JWT claims for stamping `authClaim` create-managed fields into the optimistic overlay\n // (the same value the server stamps from the same claim path). Resolved only when a create needs it\n // (a table with such a field), so tokenless registries never pay a token lookup.\n const resolveAuthClaims = async (): Promise<Record<string, unknown> | undefined> => {\n const token = await resolveAuthToken();\n return token ? decodeJwtClaims(token) : undefined;\n };\n\n const tableContexts = buildTableContexts(options.registry);\n const maxMutationAttempts = options.maxMutationAttempts ?? DEFAULT_MAX_MUTATION_ATTEMPTS;\n const flushBatchSize = options.flushBatchSize ?? DEFAULT_FLUSH_BATCH_SIZE;\n // The fingerprint (ADR-0004) stamped onto each enqueued mutation (ADR-0006). The runtime\n // owns the registry, so it derives this itself; an explicit override is honoured for tests.\n const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);\n let flushQueue = Promise.resolve();\n\n const getTableContext = (table: SyncTableName<TRegistry>) => {\n const context = tableContexts[table];\n\n if (!context) {\n throw new Error(`Unknown mutation table: ${String(table)}`);\n }\n\n return context;\n };\n\n const runInTransaction = async (operation: () => Promise<void>) => {\n await options.db.exec(\"BEGIN\");\n\n try {\n await operation();\n await options.db.exec(\"COMMIT\");\n } catch (error) {\n await options.db.exec(\"ROLLBACK\");\n throw error;\n }\n };\n\n const normalizeBatchItem = (\n item: MutationBatchItem<TRegistry>,\n order: number,\n claims: Record<string, unknown> | undefined,\n ): NormalizedBatchItem => {\n const context = getTableContext(item.table as SyncTableName<TRegistry>);\n const mutationId = globalThis.crypto.randomUUID();\n const nowUs = nowMicroseconds();\n\n switch (item.kind) {\n case \"create\": {\n const strippedInput = stripReadModelOverlayFields(item.input);\n const optimisticRecord = ensureRecord(createOptimisticRecordFromContext(context, strippedInput, claims));\n const entityKey = buildEntityKeyFromRecord(context, optimisticRecord);\n\n return {\n context,\n kind: \"create\",\n entityKey,\n entityKeyJson: serializeEntityKey(entityKey),\n optimisticRecord,\n input: strippedInput,\n mutationId,\n nowUs,\n order,\n };\n }\n case \"update\": {\n const entityKey = normalizeEntityKey(context, item.entityKey);\n const patch = ensureRecord(stripReadModelOverlayFields(item.patch));\n\n return {\n context,\n kind: \"update\",\n entityKey,\n entityKeyJson: serializeEntityKey(entityKey),\n patch,\n blind: item.blind ?? false,\n mutationId,\n nowUs,\n order,\n };\n }\n case \"delete\": {\n const entityKey = normalizeEntityKey(context, item.entityKey);\n\n return {\n context,\n kind: \"delete\",\n entityKey,\n entityKeyJson: serializeEntityKey(entityKey),\n mutationId,\n nowUs,\n order,\n };\n }\n }\n };\n\n const enqueueBatch = async (\n items: ReadonlyArray<MutationBatchItem<TRegistry>>,\n unit?: WriteUnit,\n ): Promise<string[]> => {\n if (items.length === 0) {\n return [];\n }\n\n // The distinct pessimistic write-unit ids this enqueue tagged — returned so the caller can\n // foreground-route them to the authoritative endpoint (ADR-0022). Empty for a purely optimistic batch.\n const pessimisticUnitIds = new Set<string>();\n\n // Resolve the decoded claims once per batch, but only if a create actually needs them (a target\n // table with an `authClaim` create-managed field). Avoids a token lookup for every other write.\n const needsAuthClaims = items.some(\n (item) =>\n item.kind === \"create\" &&\n getTableContext(item.table as SyncTableName<TRegistry>).managedAuthClaimCreateFields.length > 0,\n );\n const claims = needsAuthClaims ? await resolveAuthClaims() : undefined;\n\n const normalizedItems = items.map((item, index) => normalizeBatchItem(item, index, claims));\n const batchGroups = new Map<string, { context: TableContext; items: NormalizedBatchItem[] }>();\n\n for (const item of normalizedItems) {\n const existing = batchGroups.get(item.context.key);\n\n if (existing) {\n existing.items.push(item);\n continue;\n }\n\n batchGroups.set(item.context.key, {\n context: item.context,\n items: [item],\n });\n }\n\n for (const { context, items: groupedItems } of batchGroups.values()) {\n groupedItems.sort((left, right) => left.order - right.order);\n const uniqueEntities = dedupeBatchEntities(groupedItems);\n const latestMutationStates = await readLatestMutationStates(options.db, context, uniqueEntities);\n const currentRecordStates = await readCurrentRecordStates(options.db, context, uniqueEntities);\n const entityStates = new Map<string, BatchEntityState>();\n\n for (const entity of uniqueEntities) {\n const latestState = latestMutationStates.get(entity.entityKeyJson);\n const currentState = currentRecordStates.get(entity.entityKeyJson);\n\n entityStates.set(entity.entityKeyJson, {\n entityKey: entity.entityKey,\n entityKeyJson: entity.entityKeyJson,\n record: currentState ? extractRecordFromState(context, currentState) : null,\n overlayKind: currentState?.overlayKind ?? null,\n localUpdatedAtUs: currentState?.localUpdatedAtUs ?? null,\n latestMutationSeq: latestState?.latestMutationSeq ?? null,\n latestMutationKind: latestState?.latestMutationKind ?? null,\n latestMutationStatus: latestState?.latestMutationStatus ?? null,\n });\n }\n\n const plannedMutations: PlannedMutationInsert[] = [];\n const plannedOverlays = new Map<string, PlannedOverlayUpsert>();\n\n for (const item of groupedItems) {\n const entityState = entityStates.get(item.entityKeyJson);\n\n if (!entityState) {\n throw new Error(`Missing batch state for table ${context.key}`);\n }\n\n switch (item.kind) {\n case \"create\": {\n if ((entityState.latestMutationSeq ?? 0) !== 0) {\n throw new Error(`${context.key} already has queued mutations`);\n }\n\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"create\",\n payloadJson: jsonStringifyPayload({\n kind: \"create\",\n value: item.input,\n }),\n nowUs: item.nowUs,\n // A create has no Base server version (ADR-0015): its conflict is a PK collision, a\n // separate concern from the stale-write check.\n baseServerVersion: null,\n });\n\n entityState.record = item.optimisticRecord;\n entityState.overlayKind = \"pending_create\";\n entityState.localUpdatedAtUs = item.nowUs;\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"create\";\n entityState.latestMutationStatus = \"pending\";\n plannedOverlays.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n record: item.optimisticRecord,\n overlayKind: \"pending_create\",\n localUpdatedAtUs: item.nowUs,\n });\n break;\n }\n case \"update\": {\n if (item.blind) {\n // ADR-0022 addendum — a BLIND update: the write target is excluded from the actor's read\n // shape (its rows never stream here), so there is no local base row to seed and no optimistic\n // state to show. It is meaningful ONLY when the write routes to the authoritative endpoint (the\n // /unit expander is authoritative): an optimistic-routed blind write has nothing to converge, so\n // it is rejected at enqueue. The `unit` fixes the route inside a `transaction` block; a plain\n // enqueue on a statically-pessimistic table earns its own pessimistic unit downstream.\n const routesPessimistic = unit ? unit.mode === \"pessimistic\" : context.entry.writeMode === \"pessimistic\";\n if (!routesPessimistic) {\n throw new Error(\n `${context.key}: updateBlind requires a pessimistic write unit — use transaction({ mode: \"pessimistic\" }) (an optimistic blind write has nothing to show and no base to converge)`,\n );\n }\n\n // KEEP the already-queued-for-deletion guard (journal-derived; needs no local record).\n if (entityState.latestMutationKind === \"delete\" && entityState.latestMutationStatus !== \"acked\") {\n throw new Error(`${context.key} is already queued for deletion`);\n }\n\n // Plan a journal row ONLY — no overlay, so nothing enters the read model and nothing can linger\n // there. `baseServerVersion: null`: the /unit expander is authoritative, there is no base to\n // capture. The `pessimistic-blind` marker keeps the row off the optimistic flusher and lets\n // reconcile retire it after ack WITHOUT a synced echo (there is no visible row to converge).\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"update\",\n payloadJson: jsonStringifyPayload({\n kind: \"update\",\n patch: item.patch,\n }),\n nowUs: item.nowUs,\n baseServerVersion: null,\n writeMode: \"pessimistic-blind\",\n });\n\n // Advance only the journal-derived tracking (no record/overlay): so a later same-batch item on\n // this entity chains in author order and sees the pending blind write.\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"update\";\n entityState.latestMutationStatus = \"pending\";\n break;\n }\n\n if (!entityState.record) {\n throw new Error(`${context.key} not found in local read model`);\n }\n\n if (entityState.latestMutationKind === \"delete\" && entityState.latestMutationStatus !== \"acked\") {\n throw new Error(`${context.key} is already queued for deletion`);\n }\n\n // ADR-0015: capture the Base server version BEFORE the record is replaced by the\n // optimistic value below (which overwrites the Server version with the client clock).\n const updateBaseServerVersion = captureChainHeadBase(context, entityState);\n const overlayKind = entityState.overlayKind === \"pending_create\" ? \"pending_create\" : \"pending_update\";\n const optimisticRecord = ensureRecord(\n buildOptimisticRecord(\n context,\n {\n ...entityState.record,\n ...item.patch,\n // Re-stamp the on-update managed timestamp(s) generically (governance-driven) — for a\n // convention table this is exactly `updatedAtUs`, for a custom-named Server version\n // it is that column, so the optimistic row never carries a stale managed value.\n ...buildUpdateManagedNowStamp(context, item.nowUs),\n },\n {\n overlayKind,\n localUpdatedAtUs: item.nowUs,\n },\n ),\n );\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"update\",\n payloadJson: jsonStringifyPayload({\n kind: \"update\",\n patch: item.patch,\n }),\n nowUs: item.nowUs,\n baseServerVersion: updateBaseServerVersion,\n });\n\n entityState.record = optimisticRecord;\n entityState.overlayKind = overlayKind;\n entityState.localUpdatedAtUs = item.nowUs;\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"update\";\n entityState.latestMutationStatus = \"pending\";\n plannedOverlays.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n record: optimisticRecord,\n overlayKind,\n localUpdatedAtUs: item.nowUs,\n });\n break;\n }\n case \"delete\": {\n if (!entityState.record) {\n throw new Error(`${context.key} not found in local read model`);\n }\n\n if (entityState.latestMutationKind === \"delete\" && entityState.latestMutationStatus !== \"acked\") {\n throw new Error(`${context.key} is already queued for deletion`);\n }\n\n const deleteBaseServerVersion = captureChainHeadBase(context, entityState);\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"delete\",\n payloadJson: jsonStringifyPayload({\n kind: \"delete\",\n entityKey: item.entityKey,\n }),\n nowUs: item.nowUs,\n baseServerVersion: deleteBaseServerVersion,\n });\n\n entityState.overlayKind = \"pending_delete\";\n entityState.localUpdatedAtUs = item.nowUs;\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"delete\";\n entityState.latestMutationStatus = \"pending\";\n plannedOverlays.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n record: entityState.record,\n overlayKind: \"pending_delete\",\n localUpdatedAtUs: item.nowUs,\n });\n break;\n }\n }\n }\n\n // ADR-0022: an explicit unit (from a `transaction` block) tags the whole batch; otherwise a\n // statically-`pessimistic` table earns its own per-enqueue unit, so its writes route to the\n // authoritative endpoint too. An optimistic table with no explicit unit stays untagged.\n const effectiveUnit: WriteUnit | undefined =\n unit ??\n (context.entry.writeMode === \"pessimistic\"\n ? { id: globalThis.crypto.randomUUID(), mode: \"pessimistic\" }\n : undefined);\n if (effectiveUnit?.mode === \"pessimistic\") {\n pessimisticUnitIds.add(effectiveUnit.id);\n }\n await insertMutationsBulk(options.db, context, plannedMutations, registryVersion, effectiveUnit);\n await upsertOverlayRecordsBulk(options.db, context, [...plannedOverlays.values()]);\n }\n\n return [...pessimisticUnitIds];\n };\n\n const runFlush = async (table?: SyncTableName<TRegistry>) => {\n const affectedContexts = new Map<string, TableContext>();\n const quarantinedMutationIds = new Set<string>();\n const conflictedMutationIds = new Set<string>();\n let processedCount = 0;\n\n do {\n const batchResult = await flushBatch(\n options.db,\n tableContexts as Record<string, TableContext>,\n options.writeUrl,\n maxMutationAttempts,\n flushBatchSize,\n table,\n resolveAuthToken,\n options.requestHeaders,\n );\n\n processedCount = batchResult.processedCount;\n\n for (const context of batchResult.affectedContexts) {\n affectedContexts.set(context.key, context);\n }\n\n for (const mutationId of batchResult.quarantinedMutationIds) {\n quarantinedMutationIds.add(mutationId);\n }\n\n for (const mutationId of batchResult.conflictedMutationIds) {\n conflictedMutationIds.add(mutationId);\n }\n } while (processedCount > 0);\n\n for (const context of affectedContexts.values()) {\n await reconcileTable(options.db, context);\n }\n\n // Surface newly-quarantined mutations after reconciliation so the app never has to\n // poll for permanently-rejected writes (ADR-0006 decision 4). Never silent loss.\n if (quarantinedMutationIds.size > 0 && options.onQuarantine) {\n const details = await readMutationDetailsForContexts(\n options.db,\n [...affectedContexts.values()],\n quarantinedMutationIds,\n );\n\n if (details.length > 0) {\n await options.onQuarantine(details);\n }\n }\n\n // Surface newly-conflicted (stale) writes (ADR-0015). The optimistic Overlay is kept, so the app\n // can show a resolution/diff UI and resolve each as a new write (or discard it). Never silent.\n if (conflictedMutationIds.size > 0 && options.onConflict) {\n const details = await readMutationDetailsForContexts(\n options.db,\n [...affectedContexts.values()],\n conflictedMutationIds,\n );\n\n if (details.length > 0) {\n await options.onConflict(details);\n }\n }\n };\n\n const runtime: MutationRuntime<TRegistry> = {\n registryVersion,\n create: async (table, input) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch([{ table, kind: \"create\", input }]);\n });\n // A statically-`pessimistic` table foreground-routes its write to the authoritative endpoint\n // (ADR-0022) — the write is server-authoritative, so it is sent immediately, not left for the\n // optimistic convergence loop (which skips pessimistic rows).\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n },\n update: async (table, entityKeyInput, patch) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch([{ table, kind: \"update\", entityKey: entityKeyInput, patch }]);\n });\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n },\n delete: async (table, entityKeyInput) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch([{ table, kind: \"delete\", entityKey: entityKeyInput }]);\n });\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n },\n batch: async (items, unit) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch(items, unit);\n });\n // An explicit unit (from a `transaction` block) is flushed by the caller; only foreground-route the\n // units a plain `batch()` generated for statically-pessimistic tables.\n if (!unit) {\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n }\n },\n discardConflict: async (table, entityKeyInput) => {\n const context = getTableContext(table);\n const entityKey = normalizeEntityKey(context, entityKeyInput);\n const entityKeyJson = serializeEntityKey(entityKey);\n\n // discardTerminalEntity owns its own transaction (like reconcileTable), so it is not wrapped.\n await discardTerminalEntity(options.db, context, entityKey, entityKeyJson, \"conflicted\");\n },\n discardQuarantined: async (table, entityKeyInput) => {\n const context = getTableContext(table);\n const entityKey = normalizeEntityKey(context, entityKeyInput);\n const entityKeyJson = serializeEntityKey(entityKey);\n\n // Symmetric to discardConflict — retire the entity's `quarantined` journal rows and clear the\n // kept overlay behind the same owed-guard, so a permanently-rejected write is a real rollback.\n await discardTerminalEntity(options.db, context, entityKey, entityKeyJson, \"quarantined\");\n },\n flush: async (table) => {\n const nextFlush = flushQueue.then(() => runFlush(table));\n flushQueue = nextFlush.catch(() => undefined);\n await nextFlush;\n },\n flushUnit: async (unitId) => {\n const contexts = Object.values(tableContexts).filter((context): context is TableContext => context != null);\n const unitRows = await readUnitPendingRows(options.db, contexts, unitId);\n if (unitRows.length === 0) {\n return { acks: [] };\n }\n\n // Prepare the unit's rows (entity key + envelope payload) and group them by table.\n const prepared: PreparedBatchRow[] = [];\n const byContext = new Map<string, PreparedBatchRow[]>();\n for (const row of unitRows) {\n const context = tableContexts[row.tableKey];\n if (!context) {\n continue;\n }\n const entityKey = JSON.parse(row.entityKeyJson) as Record<string, string>;\n const rawPayload = JSON.parse(row.payloadJson) as Record<string, unknown>;\n const preparedRow: PreparedBatchRow = {\n ...row,\n context,\n entityKey,\n envelopePayload:\n row.mutationKind === \"delete\"\n ? entityKey\n : toSqlColumnPayload(\n context,\n stripManagedFields(\n context,\n (rawPayload[\"value\"] ?? rawPayload[\"patch\"] ?? rawPayload) as Record<string, unknown>,\n row.mutationKind as \"create\" | \"update\",\n ),\n ),\n sqlTableName: context.entry.shape?.tableName ?? context.key,\n };\n prepared.push(preparedRow);\n const list = byContext.get(context.key);\n if (list) {\n list.push(preparedRow);\n } else {\n byContext.set(context.key, [preparedRow]);\n }\n }\n\n // Mark every member sending (persist the resolved Base server version, like the batch path).\n const sentAtUs = nowMicroseconds();\n for (const rows of byContext.values()) {\n await applyMutationStatusUpdates(\n options.db,\n rows[0]!.context,\n rows.map((row) => ({\n mutationId: row.mutationId,\n status: \"sending\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: sentAtUs,\n sentAtUs,\n replaceSentAtUs: true,\n baseServerVersion: row.baseServerVersion,\n replaceBaseServerVersion: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: null,\n conflictReason: null,\n })),\n );\n }\n\n const mutations = prepared.map((row) => ({\n tableName: row.sqlTableName,\n entityKey: row.entityKey,\n mutationId: row.mutationId,\n mutationSeq: row.mutationSeq,\n kind: row.mutationKind as \"create\" | \"update\" | \"delete\",\n payload: row.envelopePayload,\n clientTimestampUs: sentAtUs,\n ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),\n }));\n\n const url = resolveAuthoritativeMutationUrl(options.writeUrl);\n let acksByMutationId: Map<string, BatchMutationAck[\"acks\"][number]>;\n\n try {\n const authToken = await options.getAuthToken?.();\n let response = await fetch(url, {\n method: \"POST\",\n headers: buildRequestHeaders(authToken, options.requestHeaders),\n body: jsonStringifyPayload({ writeUnit: unitId, mutations }),\n });\n\n if ([401, 403].includes(response.status) && options.getAuthToken) {\n response = await fetch(url, {\n method: \"POST\",\n headers: buildRequestHeaders(await options.getAuthToken(), options.requestHeaders),\n body: jsonStringifyPayload({ writeUnit: unitId, mutations }),\n });\n }\n\n if (!response.ok) {\n const text = await response.text();\n throw new MutationRequestError(\n text.length > 0 ? text : `Authoritative write responded with ${response.status}`,\n response.status,\n parseBatchRejections(text),\n );\n }\n\n const responseJson = (await response.json()) as BatchMutationAck;\n acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));\n } catch (error) {\n // A pessimistic write is foreground: it never reached the server (transport / non-2xx), so the\n // unit did not happen. Mark it failed — KEEPING the optimistic overlay so a retry can resend — and\n // rethrow so the caller surfaces it. There is no background retry for pessimistic units.\n const failedAtUs = nowMicroseconds();\n const httpStatus = error instanceof MutationRequestError ? error.status : null;\n const errorMessage = error instanceof Error ? error.message : \"Authoritative write failed\";\n for (const rows of byContext.values()) {\n await applyMutationStatusUpdates(\n options.db,\n rows[0]!.context,\n rows.map((row) => {\n const attemptCount = row.attemptCount + 1;\n const outcome = resolveBatchFailureOutcome(attemptCount, maxMutationAttempts, failedAtUs);\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: errorMessage,\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: httpStatus,\n conflictReason: null,\n };\n }),\n );\n }\n throw error;\n }\n\n // Apply each member's ack.\n const ackedAtUs = nowMicroseconds();\n const failedAtUs = nowMicroseconds();\n const rejectedIds = new Set<string>();\n const conflictedIds = new Set<string>();\n\n for (const rows of byContext.values()) {\n await applyMutationStatusUpdates(\n options.db,\n rows[0]!.context,\n rows.map((row) => {\n const ack = acksByMutationId.get(row.mutationId);\n\n if (ack?.status === \"rejected\") {\n // ADR-0022 §4: a business rejection. Terminal `rejected`; the overlay is auto-discarded below.\n rejectedIds.add(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"rejected\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: failedAtUs,\n lastError: ack.rejectionReason ?? \"Rejected by the authoritative endpoint\",\n nextRetryAtUs: null,\n lastHttpStatus: ack.httpStatus ?? 409,\n conflictReason: ack.rejectionReason ?? \"Rejected by the authoritative endpoint\",\n };\n }\n\n if (ack?.status === \"conflicted\") {\n // ADR-0015: a stale member — terminal `conflicted`, overlay KEPT (resolve as a new write).\n conflictedIds.add(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"conflicted\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: failedAtUs,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n nextRetryAtUs: null,\n lastHttpStatus: ack.httpStatus ?? 409,\n conflictReason: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n };\n }\n\n if (!ack || ack.status !== \"acked\") {\n const attemptCount = row.attemptCount + 1;\n const outcome = resolveFailureOutcome(\n ack?.httpStatus ?? null,\n attemptCount,\n maxMutationAttempts,\n failedAtUs,\n );\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: ack?.conflictReason ?? \"Authoritative write not acknowledged\",\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: ack?.httpStatus ?? null,\n conflictReason: null,\n };\n }\n\n return {\n mutationId: row.mutationId,\n status: \"acked\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: ackedAtUs,\n ackedAtUs,\n replaceAckedAtUs: true,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: row.mutationKind === \"delete\" ? 204 : 200,\n conflictReason: null,\n };\n }),\n );\n }\n\n // ADR-0022 §4: auto-discard the optimistic overlay for every rejected entity (the whole unit was\n // declined). The terminal `rejected` journal row is kept for diagnostics + `onReject`.\n for (const row of prepared) {\n if (rejectedIds.has(row.mutationId)) {\n await discardOverlayForSettledEntity(options.db, row.context, row.entityKey, row.entityKeyJson);\n }\n }\n\n const affectedContexts = [...byContext.keys()]\n .map((key) => tableContexts[key])\n .filter((context): context is TableContext => context != null);\n for (const context of affectedContexts) {\n await reconcileTable(options.db, context);\n }\n\n if (rejectedIds.size > 0 && options.onReject) {\n const details = await readMutationDetailsForContexts(options.db, affectedContexts, rejectedIds);\n if (details.length > 0) {\n await options.onReject(details);\n }\n }\n if (conflictedIds.size > 0 && options.onConflict) {\n const details = await readMutationDetailsForContexts(options.db, affectedContexts, conflictedIds);\n if (details.length > 0) {\n await options.onConflict(details);\n }\n }\n\n return { acks: [...acksByMutationId.values()] };\n },\n reconcile: async (table) => {\n const contexts = filterContexts(tableContexts, table);\n\n for (const context of contexts) {\n await reconcileTable(options.db, context);\n }\n },\n retryFailed: async (table) => {\n assertValidMutationTransition(\"failed\", \"pending\");\n const contexts = filterContexts(tableContexts, table);\n const nowUs = nowMicroseconds();\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n const query = queryBuilder\n .update(journal)\n .set({ status: \"pending\", nextRetryAtUs: nowUs, updatedAtUs: nowUs, conflictReason: null })\n .where(eq(journal.status, \"failed\"))\n .toSQL();\n await options.db.query(query.sql, query.params as unknown[]);\n }\n },\n recoverSending: async (table) => {\n assertValidMutationTransition(\"sending\", \"pending\");\n const contexts = filterContexts(tableContexts, table);\n const nowUs = nowMicroseconds();\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n const query = queryBuilder\n .update(journal)\n .set({\n status: \"pending\",\n updatedAtUs: nowUs,\n sentAtUs: null,\n nextRetryAtUs: nowUs,\n lastError: null,\n lastHttpStatus: null,\n conflictReason: null,\n })\n .where(eq(journal.status, \"sending\"))\n .toSQL();\n await options.db.query(query.sql, query.params as unknown[]);\n }\n },\n quarantineRecovered: async (table) => {\n // The restore-boot quarantine (ADR-0035 decision 6): every non-terminal recovered row is parked in the\n // terminal `quarantined` state so NOTHING recovered from a backup auto-flushes (no dedupe ledger →\n // unsafe replay). `pending -> quarantined` is a restore-only edge (see mutation-state.ts); `sending`\n // and `failed` already reach quarantine. Assert all three edges up front so a future transition-table\n // change that breaks restore fails loudly here rather than silently skipping the quarantine.\n assertValidMutationTransition(\"pending\", \"quarantined\");\n assertValidMutationTransition(\"sending\", \"quarantined\");\n assertValidMutationTransition(\"failed\", \"quarantined\");\n const contexts = filterContexts(tableContexts, table);\n const nowUs = nowMicroseconds();\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n const query = queryBuilder\n .update(journal)\n .set({\n status: \"quarantined\",\n updatedAtUs: nowUs,\n // Terminal: never retried, so clear the retry cursor and name restore as the cause on the row so\n // an inspecting app can tell a restore-quarantined write from a server-rejected one.\n nextRetryAtUs: null,\n lastError: \"Quarantined on restore: recovered from a store backup, not replayed (ADR-0035).\",\n conflictReason: null,\n })\n .where(inArray(journal.status, [\"pending\", \"sending\", \"failed\"]))\n .toSQL();\n await options.db.query(query.sql, query.params as unknown[]);\n }\n },\n readMutationStats: async (table) => {\n const contexts = filterContexts(tableContexts, table);\n const totals: MutationDiagnostics = {\n pendingCount: 0,\n sendingCount: 0,\n failedCount: 0,\n quarantinedCount: 0,\n conflictedCount: 0,\n ackedCount: 0,\n };\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n // Drizzle has no `FILTER` operator (tier ②): each aggregate is a typed `sql` fragment over the\n // journal `status` column object with a bound status literal, aliased to the exact camelCase row\n // key the totals below read (the raw seam returns rows UNMAPPED, so aliases are load-bearing).\n const filteredCount = (status: MutationStatus, columnAlias: string) =>\n sql<number>`count(*) filter (where ${journal.status} = ${status})::int`.as(columnAlias);\n const query = queryBuilder\n .select({\n pendingCount: filteredCount(\"pending\", \"pendingCount\"),\n sendingCount: filteredCount(\"sending\", \"sendingCount\"),\n failedCount: filteredCount(\"failed\", \"failedCount\"),\n quarantinedCount: filteredCount(\"quarantined\", \"quarantinedCount\"),\n conflictedCount: filteredCount(\"conflicted\", \"conflictedCount\"),\n ackedCount: filteredCount(\"acked\", \"ackedCount\"),\n })\n .from(journal)\n .toSQL();\n const result = await options.db.query<MutationDiagnostics & Record<string, unknown>>(\n query.sql,\n query.params as unknown[],\n );\n\n const row = result.rows[0];\n if (!row) {\n continue;\n }\n\n totals.pendingCount += row.pendingCount;\n totals.sendingCount += row.sendingCount;\n totals.failedCount += row.failedCount;\n totals.quarantinedCount += row.quarantinedCount;\n totals.conflictedCount += row.conflictedCount;\n totals.ackedCount += row.ackedCount;\n }\n\n return totals;\n },\n readMutationDetails: async (table) => {\n const contexts = filterContexts(tableContexts, table);\n return readMutationDetailsForContexts(options.db, contexts);\n },\n createOptimisticRecord: (table, input) => {\n const context = getTableContext(table);\n return createOptimisticRecordFromContext(context, input);\n },\n };\n\n return runtime;\n}\n\n/**\n * Read journal entries across the given contexts as {@link MutationDetail}s, newest first.\n * Shared by the public `readMutationDetails` and the flush path's quarantine surfacing,\n * optionally narrowed to a set of mutation ids.\n */\nasync function readMutationDetailsForContexts(\n db: MutationDb,\n contexts: TableContext[],\n mutationIds?: ReadonlySet<string>,\n): Promise<MutationDetail[]> {\n const rows: MutationDetail[] = [];\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n // The raw seam returns rows UNMAPPED (no drizzle result mapping), so every field is aliased\n // explicitly to its camelCase row key, and the `_us` bigints keep their `::text` casts.\n const query = queryBuilder\n .select({\n mutationId: sql<string>`${journal.mutationId}`.as(\"mutationId\"),\n entityKeyJson: sql<string>`${journal.entityKeyJson}`.as(\"entityKeyJson\"),\n mutationSeq: sql<number>`${journal.mutationSeq}`.as(\"mutationSeq\"),\n mutationKind: sql<MutationKind>`${journal.mutationKind}`.as(\"mutationKind\"),\n status: journal.status,\n attemptCount: sql<number>`${journal.attemptCount}`.as(\"attemptCount\"),\n lastHttpStatus: sql<number | null>`${journal.lastHttpStatus}`.as(\"lastHttpStatus\"),\n lastError: sql<string | null>`${journal.lastError}`.as(\"lastError\"),\n conflictReason: sql<string | null>`${journal.conflictReason}`.as(\"conflictReason\"),\n nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as(\"nextRetryAtUs\"),\n serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as(\"serverUpdatedAtUs\"),\n updatedAtUs: sql<string>`${journal.updatedAtUs}::text`.as(\"updatedAtUs\"),\n registryVersion: sql<string | null>`${journal.registryVersion}`.as(\"registryVersion\"),\n })\n .from(journal)\n .orderBy(desc(journal.updatedAtUs), desc(journal.mutationSeq))\n .toSQL();\n const result = await db.query<MutationDetailRow>(query.sql, query.params as unknown[]);\n\n for (const row of result.rows) {\n if (mutationIds && !mutationIds.has(row.mutationId)) {\n continue;\n }\n\n rows.push({\n tableName: context.key,\n entityKey: JSON.parse(row.entityKeyJson) as Record<string, string>,\n mutationId: row.mutationId,\n mutationSeq: row.mutationSeq,\n mutationKind: row.mutationKind,\n status: row.status,\n attemptCount: row.attemptCount,\n lastHttpStatus: row.lastHttpStatus,\n lastError: row.lastError,\n conflictReason: row.conflictReason,\n nextRetryAtUs: row.nextRetryAtUs,\n serverUpdatedAtUs: row.serverUpdatedAtUs,\n updatedAtUs: row.updatedAtUs,\n registryVersion: row.registryVersion,\n });\n }\n }\n\n return rows.sort((left, right) => Number(right.updatedAtUs) - Number(left.updatedAtUs));\n}\n\ninterface MutationRow extends Record<string, unknown> {\n mutationId: string;\n entityKeyJson: string;\n mutationSeq: number;\n mutationKind: MutationKind;\n status: MutationStatus;\n payloadJson: string;\n attemptCount: number;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n registryVersion: string | null;\n}\n\ninterface MutationDetailRow extends Record<string, unknown> {\n mutationId: string;\n entityKeyJson: string;\n mutationSeq: number;\n mutationKind: MutationKind;\n status: MutationStatus;\n attemptCount: number;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n updatedAtUs: string;\n registryVersion: string | null;\n}\n\ninterface CurrentRecordStateRow extends Record<string, unknown> {\n overlayKind: string;\n localUpdatedAtUs: string;\n latestMutationSeq: number | null;\n latestMutationKind: MutationKind | null;\n latestMutationStatus: MutationStatus | null;\n}\n\ninterface BatchLatestMutationStateRow extends Record<string, unknown> {\n entityKeyJson: string;\n latestMutationSeq: number | null;\n latestMutationKind: MutationKind | null;\n latestMutationStatus: MutationStatus | null;\n}\n\ninterface BatchCurrentRecordStateRow extends Record<string, unknown> {\n entityKeyJson: string;\n overlayKind: string;\n localUpdatedAtUs: string;\n}\n\ninterface BatchEntityRef {\n entityKey: Record<string, string>;\n entityKeyJson: string;\n}\n\ninterface PlannedMutationInsert {\n mutationId: string;\n entityKey: Record<string, string>;\n entityKeyJson: string;\n mutationKind: MutationKind;\n payloadJson: string;\n nowUs: string;\n /**\n * The Base server version (ADR-0015) stamped at enqueue: the synced Server version the user saw,\n * for a **chain head** (the first staged write on the entity). `null` for a `create` (no base) and\n * for a **chained** write — the latter resolves its base at flush from its acked predecessor\n * (readPendingBatchRows), by Per-entity flush serialization (ADR-0014).\n */\n baseServerVersion: string | null;\n /**\n * A per-row `write_mode` override (ADR-0022 addendum). Left unset for an ordinary row, which inherits the\n * unit's mode at insert. A blind update sets `\"pessimistic-blind\"` so the row is flushed only by its unit's\n * foreground path (never the optimistic batch) and retires from the journal without a synced echo.\n */\n writeMode?: string | null;\n}\n\ninterface PlannedOverlayUpsert {\n entityKey: Record<string, string>;\n record: Record<string, unknown>;\n overlayKind: string;\n localUpdatedAtUs: string;\n}\n\ninterface BatchEntityState {\n entityKey: Record<string, string>;\n entityKeyJson: string;\n record: Record<string, unknown> | null;\n overlayKind: string | null;\n localUpdatedAtUs: string | null;\n latestMutationSeq: number | null;\n latestMutationKind: MutationKind | null;\n latestMutationStatus: MutationStatus | null;\n}\n\ntype NormalizedBatchItem =\n | {\n context: TableContext;\n kind: \"create\";\n entityKey: Record<string, string>;\n entityKeyJson: string;\n optimisticRecord: Record<string, unknown>;\n input: unknown;\n mutationId: string;\n nowUs: string;\n order: number;\n }\n | {\n context: TableContext;\n kind: \"update\";\n entityKey: Record<string, string>;\n entityKeyJson: string;\n patch: Record<string, unknown>;\n /** A blind update (ADR-0022 addendum): journal-only, no base-row presence check, no overlay. */\n blind: boolean;\n mutationId: string;\n nowUs: string;\n order: number;\n }\n | {\n context: TableContext;\n kind: \"delete\";\n entityKey: Record<string, string>;\n entityKeyJson: string;\n mutationId: string;\n nowUs: string;\n order: number;\n };\n\n/**\n * The Base server version (ADR-0015) to stamp at enqueue for an update/delete. Only a **chain head**\n * — the first staged write on the entity (no earlier unresolved mutation) — captures an enqueue-time\n * base: the synced Server version the user's edit was authored against, so a genuine external write\n * between view and apply is caught. A **chained** write (an earlier same-entity mutation is still\n * owed) returns `null` here; it resolves its base at flush from its acked predecessor, so an entity's\n * own successive edits never self-conflict (decision 2).\n */\nfunction captureChainHeadBase(context: TableContext, entityState: BatchEntityState): string | null {\n if ((entityState.latestMutationSeq ?? 0) !== 0) {\n return null;\n }\n\n if (!context.serverVersionPropertyKey || !entityState.record) {\n return null;\n }\n\n // The Server version is a bigint count of microseconds, surfaced as a string/number/bigint\n // depending on the read path. Anything else (null/object) means no observable base.\n const raw = entityState.record[context.serverVersionPropertyKey];\n if (typeof raw === \"string\" || typeof raw === \"number\" || typeof raw === \"bigint\") {\n return String(raw);\n }\n\n return null;\n}\n\nfunction buildTableContexts<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n const localSchema = getSyncRegistrySchema(registry);\n\n return Object.fromEntries(\n Object.entries(registry)\n .filter(([, entry]) => entry.mode !== \"readonly\")\n .map(([key, entry]) => [key, buildTableContext(registry, key, entry, localSchema)]),\n ) as Partial<Record<SyncTableName<TRegistry>, TableContext>>;\n}\n\nfunction buildTableContext<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n key: string,\n entry: SyncTableEntry<AnyPgTable>,\n localSchema: string,\n): TableContext {\n if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {\n throw new Error(`overlay and journal tables are required for writable table ${key}`);\n }\n\n const columns = getProjectedTableColumns(entry).map(({ propertyKey, column }) => ({\n propertyKey,\n column,\n }));\n\n const pkPropertyKeys = entry.primaryKey.columns.map((columnName) => {\n const column = columns.find((candidate) => candidate.column.name === columnName);\n\n if (!column) {\n throw new Error(`Primary key column ${columnName} was not found on table ${key}`);\n }\n\n return column.propertyKey;\n });\n\n const serverVersionColumnName = resolveServerVersionColumnName(entry) ?? null;\n const serverVersionPropertyKey = serverVersionColumnName\n ? (columns.find((candidate) => candidate.column.name === serverVersionColumnName)?.propertyKey ?? null)\n : null;\n\n // Resolve the `nowMicroseconds` managed fields generically from governance, not by property name.\n // `field.column` is a drizzle property key, but tolerate a column-name declaration too.\n const resolveManagedPropertyKey = (fieldColumn: string): string | undefined =>\n columns.find((candidate) => candidate.propertyKey === fieldColumn || candidate.column.name === fieldColumn)\n ?.propertyKey;\n const nowMicrosecondsManagedFields = (entry.governance?.managedFields ?? []).filter(\n (field) => field.strategy === \"nowMicroseconds\",\n );\n const managedNowMicrosecondsPropertyKeys = nowMicrosecondsManagedFields\n .map((field) => resolveManagedPropertyKey(field.column as string))\n .filter((propertyKey): propertyKey is string => propertyKey !== undefined);\n const updateManagedNowMicrosecondsPropertyKeys = nowMicrosecondsManagedFields\n .filter((field) => field.applyOn.includes(\"update\"))\n .map((field) => resolveManagedPropertyKey(field.column as string))\n .filter((propertyKey): propertyKey is string => propertyKey !== undefined);\n\n const managedAuthClaimCreateFields = (entry.governance?.managedFields ?? [])\n .filter((field) => field.strategy === \"authClaim\" && field.applyOn.includes(\"create\"))\n .flatMap((field) => {\n const propertyKey = resolveManagedPropertyKey(field.column as string);\n return propertyKey && field.claimPath ? [{ propertyKey, claimPath: field.claimPath }] : [];\n });\n\n // The generated local relations as runtime Drizzle objects (memoized per registry+key in\n // local-tables.ts), plus name-resolved column handles the statement authors below need:\n // overlay/synced columns are keyed by PROPERTY key, so PK columns (a DB-column-name concept,\n // ADR-0012) are resolved once here by matching `.name`.\n const tables = {\n synced: getSyncedLocalTable(registry, key as string & keyof TRegistry),\n overlay: getOverlayTable(registry, key as string & keyof TRegistry),\n journal: getJournalTable(registry, key as string & keyof TRegistry),\n };\n const overlayColumnsByPropertyKey = getColumns(tables.overlay) as Record<string, PgColumn>;\n const syncedColumnsByPropertyKey = getColumns(tables.synced) as Record<string, PgColumn>;\n const resolvePkColumns = (columnsByKey: Record<string, PgColumn>, relation: string) =>\n entry.primaryKey.columns.map((columnName) => {\n const column = Object.values(columnsByKey).find((candidate) => candidate.name === columnName);\n if (!column) {\n throw new Error(`Primary key column ${columnName} was not found on the ${relation} table for ${key}`);\n }\n return column;\n });\n const syncedServerVersionColumn = serverVersionColumnName\n ? (Object.values(syncedColumnsByPropertyKey).find((candidate) => candidate.name === serverVersionColumnName) ??\n null)\n : null;\n\n return {\n key,\n entry,\n readModel: qualifyLocalIdentifier(\n localSchema,\n entry.view != null\n ? getViewConfig(entry.view).name\n : (entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name),\n ),\n syncedTable: qualifyLocalIdentifier(\n localSchema,\n entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name,\n ),\n overlayTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.overlayTable),\n journalTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.journalTable),\n journalSequence: qualifyLocalIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable)),\n pkColumnNames: [...entry.primaryKey.columns],\n pkPropertyKeys,\n serverVersionColumnName,\n serverVersionPropertyKey,\n managedNowMicrosecondsPropertyKeys,\n updateManagedNowMicrosecondsPropertyKeys,\n managedAuthClaimCreateFields,\n recordIncludesOverlayState: \"overlayTable\" in (entry.clientProjection ?? {}),\n columns,\n tables,\n overlayColumnsByPropertyKey,\n syncedColumnsByPropertyKey,\n overlayPkColumns: resolvePkColumns(overlayColumnsByPropertyKey, \"overlay\"),\n syncedPkColumns: resolvePkColumns(syncedColumnsByPropertyKey, \"synced\"),\n syncedServerVersionColumn,\n };\n}\n\nfunction filterContexts<TRegistry extends SyncTableRegistry>(\n contexts: Partial<Record<SyncTableName<TRegistry>, TableContext>>,\n table?: SyncTableName<TRegistry>,\n) {\n if (table) {\n const context = contexts[table];\n return context ? [context] : [];\n }\n\n return Object.values(contexts).filter((context): context is TableContext => context !== undefined);\n}\n\n/**\n * Materialise a column's default into a concrete JS value for the optimistic overlay\n * row. The overlay INSERT writes an explicit value for every projected column (an\n * omitted column becomes a literal `NULL`, which overrides any table-level DEFAULT), so\n * a column declared `NOT NULL DEFAULT <x>` that the caller omits would violate the\n * overlay's NOT NULL constraint unless we fill the default here — mirroring what the\n * authoritative server applies on the base table.\n *\n * Only values we can produce client-side are materialised: a value-returning `defaultFn`\n * (e.g. `$defaultFn`) or a literal `.default(value)`. SQL-expression defaults\n * (`.default(sql\\`…\\`)`, `defaultRandom()`, `defaultNow()`) cannot be evaluated without\n * the database, so they are left to the server (the column is then expected to be either\n * caller-supplied or nullable in the optimistic row).\n */\nfunction materializeColumnDefault(column: TableContext[\"columns\"][number][\"column\"]): {\n ok: boolean;\n value?: unknown;\n} {\n if (!column.hasDefault) {\n return { ok: false };\n }\n\n if (typeof column.defaultFn === \"function\") {\n const produced = column.defaultFn();\n return is(produced, SQL) ? { ok: false } : { ok: true, value: produced };\n }\n\n if (column.default !== undefined && !is(column.default, SQL)) {\n return { ok: true, value: column.default };\n }\n\n return { ok: false };\n}\n\nfunction createOptimisticRecordFromContext<TCreate, TRecord>(\n context: TableContext,\n input: TCreate,\n claims?: Record<string, unknown>,\n): TRecord {\n const record = {\n ...(isRecord(input) ? input : {}),\n };\n const nowUs = nowMicroseconds();\n\n // Stamp `authClaim` create-managed fields (owner/author/created_by) from the decoded claim at the\n // field's path, so the optimistic overlay row is attributed locally and satisfies the column's NOT\n // NULL — the server independently stamps the same claim on apply, so the value never flips on\n // convergence. (`auth.uid()` is just `claimPath: [\"sub\"]`.)\n if (claims != null) {\n for (const { propertyKey, claimPath } of context.managedAuthClaimCreateFields) {\n if (record[propertyKey] === undefined) {\n const value = readJwtClaimPath(claims, claimPath);\n if (value !== undefined) {\n record[propertyKey] = value;\n }\n }\n }\n }\n\n if (hasProperty(context, \"createdAtUs\") && record[\"createdAtUs\"] === undefined) {\n record[\"createdAtUs\"] = nowUs;\n }\n\n if (hasProperty(context, \"updatedAtUs\") && record[\"updatedAtUs\"] === undefined) {\n record[\"updatedAtUs\"] = nowUs;\n }\n\n // Generic managed-timestamp fill (governance-driven): stamp any `nowMicroseconds` managed field the\n // convention block above did not — e.g. a Server version column not named `updated_at_us`. Additive\n // and idempotent, so convention tables are unaffected (their fields are already filled).\n for (const propertyKey of context.managedNowMicrosecondsPropertyKeys) {\n if (record[propertyKey] === undefined) {\n record[propertyKey] = nowUs;\n }\n }\n\n for (const { propertyKey, column } of context.columns) {\n if (record[propertyKey] !== undefined) {\n continue;\n }\n\n const materialized = materializeColumnDefault(column);\n if (materialized.ok) {\n record[propertyKey] = materialized.value;\n }\n }\n\n return buildOptimisticRecord(context, record, {\n overlayKind: \"pending_create\",\n localUpdatedAtUs: nowUs,\n }) as TRecord;\n}\n\n/**\n * Stamp every on-update `nowMicroseconds` managed field with `nowUs` (governance-driven, ADR-0004),\n * keyed by drizzle property key. For a convention table this is exactly `{ updatedAtUs: nowUs }`; for\n * a custom-named Server version it targets that column — so the local optimistic path never assumes\n * the demo naming the generic server applier does not.\n */\nfunction buildUpdateManagedNowStamp(context: TableContext, nowUs: string): Record<string, string> {\n return Object.fromEntries(\n context.updateManagedNowMicrosecondsPropertyKeys.map((propertyKey) => [propertyKey, nowUs]),\n );\n}\n\nfunction buildOptimisticRecord(\n context: TableContext,\n record: Record<string, unknown>,\n options: {\n overlayKind: string;\n localUpdatedAtUs: string;\n },\n) {\n if (!context.recordIncludesOverlayState) {\n return record;\n }\n\n return {\n ...record,\n overlayKind: options.overlayKind,\n localUpdatedAtUs: options.localUpdatedAtUs,\n };\n}\n\nfunction buildEntityKeyFromRecord(context: TableContext, record: unknown) {\n const recordObject = ensureRecord(record);\n return normalizeEntityKey(\n context,\n Object.fromEntries(context.pkPropertyKeys.map((propertyKey) => [propertyKey, String(recordObject[propertyKey])])),\n );\n}\n\nfunction normalizeEntityKey(context: TableContext, input: Record<string, string>) {\n // The public API accepts the identity by drizzle property name (ergonomics); past this\n // boundary the canonical Entity identity is column-keyed (ADR-0012), matching the\n // journal/overlay PK columns, entity_key_json, and the applier's `v_entity_key->>'<column>'`.\n // pkPropertyKeys[i] ↔ pkColumnNames[i] by construction (buildTableContext), so we map once here.\n return Object.fromEntries(\n context.pkPropertyKeys.map((propertyKey, index) => {\n const value = input[propertyKey];\n\n if (value === undefined) {\n throw new Error(`Missing entity key property ${propertyKey} for table ${context.key}`);\n }\n\n return [context.pkColumnNames[index]!, String(value)];\n }),\n );\n}\n\nfunction serializeEntityKey(entityKey: Record<string, string>) {\n return JSON.stringify(entityKey);\n}\n\nfunction dedupeBatchEntities(items: ReadonlyArray<NormalizedBatchItem>): BatchEntityRef[] {\n const entities = new Map<string, BatchEntityRef>();\n\n for (const item of items) {\n if (!entities.has(item.entityKeyJson)) {\n entities.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n });\n }\n }\n\n return [...entities.values()];\n}\n\nasync function readLatestMutationStates(\n db: MutationDb,\n context: TableContext,\n entities: ReadonlyArray<BatchEntityRef>,\n) {\n if (entities.length === 0) {\n return new Map<string, BatchLatestMutationStateRow>();\n }\n\n // The old VALUES-CTE + LEFT-JOIN-back-to-input existed only to emit null rows for entities with\n // no journal history; the caller reads via `map.get(...) ?? null`, so a missing key is equivalent.\n const journal = context.tables.journal;\n const query = queryBuilder\n .selectDistinctOn([journal.entityKeyJson], {\n entityKeyJson: sql<string>`${journal.entityKeyJson}`.as(\"entityKeyJson\"),\n latestMutationSeq: sql<number>`${journal.mutationSeq}`.as(\"latestMutationSeq\"),\n latestMutationKind: sql<MutationKind>`${journal.mutationKind}`.as(\"latestMutationKind\"),\n latestMutationStatus: sql<MutationStatus>`${journal.status}`.as(\"latestMutationStatus\"),\n })\n .from(journal)\n .where(\n inArray(\n journal.entityKeyJson,\n entities.map((entity) => entity.entityKeyJson),\n ),\n )\n .orderBy(journal.entityKeyJson, desc(journal.mutationSeq))\n .toSQL();\n const result = await db.query<BatchLatestMutationStateRow>(query.sql, query.params as unknown[]);\n\n return new Map(result.rows.map((row) => [row.entityKeyJson, row]));\n}\n\nasync function readCurrentRecordStates(db: MutationDb, context: TableContext, entities: ReadonlyArray<BatchEntityRef>) {\n if (entities.length === 0) {\n return new Map<string, BatchCurrentRecordStateRow>();\n }\n\n // Tier ②: the overlay-∪-synced shape over an input VALUES table. The input CTE carries each\n // entity's `entity_key_json` alongside its PK values (the caller maps rows back by that JSON), so\n // it cannot be a plain builder select; every identifier still comes from the table objects /\n // `sql.identifier`, and every value is a bound (cast-typed) param.\n const overlay = context.tables.overlay;\n const synced = context.tables.synced;\n const inputCte = buildEntityInputCte(context, entities);\n const overlaySelectColumns = buildProjectedSelectColumns(context, context.overlayColumnsByPropertyKey);\n const syncedSelectColumns = buildProjectedSelectColumns(context, context.syncedColumnsByPropertyKey);\n const inputOverlayJoin = buildEntityInputJoin(context.pkColumnNames, context.overlayPkColumns);\n const inputSyncedJoin = buildEntityInputJoin(context.pkColumnNames, context.syncedPkColumns);\n const syncedUpdatedAtColumn = context.syncedColumnsByPropertyKey[\"updatedAtUs\"];\n const syncedLocalUpdated =\n hasProperty(context, \"updatedAtUs\") && syncedUpdatedAtColumn\n ? sql`${syncedUpdatedAtColumn}::text AS \"localUpdatedAtUs\"`\n : sql`'0' AS \"localUpdatedAtUs\"`;\n\n const query = queryDialect.sqlToQuery(sql`\n WITH ${inputCte},\n overlay_rows AS (\n SELECT\n input.entity_key_json AS \"entityKeyJson\",\n ${overlaySelectColumns},\n ${overlay.overlayKind} AS \"overlayKind\",\n ${overlay.localUpdatedAtUs}::text AS \"localUpdatedAtUs\"\n FROM input_entities AS input\n JOIN ${overlay}\n ON ${inputOverlayJoin}\n ),\n synced_rows AS (\n SELECT\n input.entity_key_json AS \"entityKeyJson\",\n ${syncedSelectColumns},\n ${\"synced\"} AS \"overlayKind\",\n ${syncedLocalUpdated}\n FROM input_entities AS input\n JOIN ${synced}\n ON ${inputSyncedJoin}\n WHERE NOT EXISTS (\n SELECT 1\n FROM ${overlay}\n WHERE ${inputOverlayJoin}\n )\n )\n SELECT *\n FROM overlay_rows\n UNION ALL\n SELECT *\n FROM synced_rows\n `);\n const result = await db.query<BatchCurrentRecordStateRow>(query.sql, query.params as unknown[]);\n\n return new Map(result.rows.map((row) => [row.entityKeyJson, row]));\n}\n\nasync function insertMutationsBulk(\n db: MutationDb,\n context: TableContext,\n rows: ReadonlyArray<PlannedMutationInsert>,\n registryVersion: string | null,\n unit?: WriteUnit,\n) {\n if (rows.length === 0) {\n return;\n }\n\n // ADR-0022: a dynamic write-unit tags every row of the batch with one shared unit id + mode; the\n // default path leaves both NULL (the flusher derives mode/unit from the static group). A blind row\n // carries its own `write_mode` override (`pessimistic-blind`), so the mode is resolved per row.\n const writeUnit = unit?.id ?? null;\n const journal = context.tables.journal;\n // `mutationSeq` is intentionally omitted: the generated journal DDL carries\n // `mutation_seq ... DEFAULT nextval(<journal sequence>)`, so the DB default assigns it — drizzle\n // renders `default` for every column a row does not provide.\n const values = rows.map((row) => ({\n mutationId: row.mutationId,\n ...Object.fromEntries(context.pkColumnNames.map((columnName) => [columnName, row.entityKey[columnName]])),\n entityKeyJson: row.entityKeyJson,\n mutationKind: row.mutationKind,\n status: \"pending\",\n registryVersion,\n baseServerVersion: row.baseServerVersion,\n payloadJson: row.payloadJson,\n enqueuedAtUs: row.nowUs,\n nextRetryAtUs: row.nowUs,\n updatedAtUs: row.nowUs,\n writeUnit,\n writeMode: row.writeMode ?? unit?.mode ?? null,\n }));\n\n const query = queryBuilder\n .insert(journal)\n .values(values as PgInsertValue<JournalTable>[])\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n\n // Lifecycle origin: the moment each mutation is first staged into the journal. Correlates by id with\n // the later \"board-write sending\"/\"board-write acks\" lines (staged → sent → acked, per id).\n for (const row of rows) {\n syncDebug(\"mutation staged\", { mutationId: row.mutationId, table: context.key });\n }\n}\n\nasync function upsertOverlayRecordsBulk(\n db: MutationDb,\n context: TableContext,\n rows: ReadonlyArray<PlannedOverlayUpsert>,\n) {\n if (rows.length === 0) {\n return;\n }\n\n const overlay = context.tables.overlay;\n const values = rows.map((row) => ({\n ...Object.fromEntries(context.columns.map(({ propertyKey }) => [propertyKey, row.record[propertyKey] ?? null])),\n overlayKind: row.overlayKind,\n localUpdatedAtUs: row.localUpdatedAtUs,\n }));\n // Every inserted column (the projection + the two overlay columns) takes its EXCLUDED value on\n // conflict — the fixed alias PostgreSQL defines for the proposed row; its column names are the\n // table's own, so they come from the column objects via `sql.identifier`.\n const excludedSet = Object.fromEntries([\n ...context.columns.map(({ propertyKey, column }) => [propertyKey, sql`excluded.${sql.identifier(column.name)}`]),\n [\"overlayKind\", sql`excluded.${sql.identifier(overlay.overlayKind.name)}`],\n [\"localUpdatedAtUs\", sql`excluded.${sql.identifier(overlay.localUpdatedAtUs.name)}`],\n ]) as Record<string, SQL>;\n\n const query = queryBuilder\n .insert(overlay)\n .values(values as PgInsertValue<OverlayTable>[])\n .onConflictDoUpdate({ target: context.overlayPkColumns, set: excludedSet })\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\n/**\n * The batch-input CTE as a typed fragment: `input_entities (entity_key_json, <pks…>) AS (VALUES …)`\n * with every value a bound param, cast to its PK column's type (an untyped VALUES column would\n * otherwise default to text and break the join against a uuid/int PK).\n */\nfunction buildEntityInputCte(context: TableContext, entities: ReadonlyArray<BatchEntityRef>): SQL {\n const columnNames = [\"entity_key_json\", ...context.pkColumnNames];\n const tuples = entities.map((entity) => {\n const values = [\n sql`${entity.entityKeyJson}`,\n ...context.pkColumnNames.map((columnName) => {\n const columnEntry = context.columns.find(({ column }) => column.name === columnName);\n const castSuffix = columnEntry ? resolveInputCastSuffix(columnEntry.column.columnType) : \"\";\n // The cast keyword is a FIXED type suffix selected from the closed switch below — never\n // derived from user data — so `sql.raw` is safe here; the value itself is a bound param.\n return castSuffix\n ? sql`${entity.entityKey[columnName]}${sql.raw(castSuffix)}`\n : sql`${entity.entityKey[columnName]}`;\n }),\n ];\n return sql`(${sql.join(values, sql`, `)})`;\n });\n\n return sql`input_entities (${sql.join(\n columnNames.map((columnName) => sql.identifier(columnName)),\n sql`, `,\n )}) AS (VALUES ${sql.join(tuples, sql`, `)})`;\n}\n\nfunction resolveInputCastSuffix(columnType: string): string {\n switch (columnType) {\n case \"PgUUID\":\n return \"::uuid\";\n case \"PgBigInt64\":\n case \"PgBigInt53\":\n return \"::bigint\";\n case \"PgInteger\":\n case \"PgSerial\":\n case \"PgSmallInt\":\n return \"::int\";\n case \"PgBoolean\":\n return \"::boolean\";\n case \"PgTimestamp\":\n case \"PgTimestampString\":\n return \"::timestamp\";\n default:\n return \"\";\n }\n}\n\n/**\n * The projected columns of one branch (overlay or synced) as select-list fragments, aliased to\n * their camelCase property keys — the raw seam returns rows unmapped, so the aliases ARE the row\n * keys — with `::text` casts on the bigint columns (matching how the runtime reads them).\n */\nfunction buildProjectedSelectColumns(context: TableContext, columnsByPropertyKey: Record<string, PgColumn>): SQL {\n return sql.join(\n context.columns.map(({ propertyKey, column }) => {\n const target = columnsByPropertyKey[propertyKey];\n if (!target) {\n throw new Error(`Projected column ${propertyKey} was not found on the local tables for ${context.key}`);\n }\n if (column.columnType === \"PgBigInt64\" || column.columnType === \"PgBigInt53\") {\n return sql`${target}::text AS ${sql.identifier(propertyKey)}`;\n }\n return sql`${target} AS ${sql.identifier(propertyKey)}`;\n }),\n sql`, `,\n );\n}\n\n/** PK equality between a branch table's columns and the `input` CTE, as a typed fragment. */\nfunction buildEntityInputJoin(pkColumnNames: string[], pkColumns: PgColumn[]): SQL {\n return sql.join(\n pkColumnNames.map((columnName, index) => sql`${pkColumns[index]!} = input.${sql.identifier(columnName)}`),\n sql` AND `,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Batch flush — sends one send-eligible slice of pending mutations across all\n// target tables in a single POST /api/mutations call. The public flush()\n// wrapper loops until no more eligible rows remain.\n// ---------------------------------------------------------------------------\n\ninterface PendingBatchRow extends MutationRow {\n tableKey: string;\n enqueuedAtUs: string;\n /** The resolved Base server version (ADR-0015), or null when the table predates the policy. */\n baseServerVersion: string | null;\n}\n\ninterface PreparedBatchRow extends PendingBatchRow {\n context: TableContext;\n entityKey: Record<string, string>;\n envelopePayload: Record<string, unknown>;\n sqlTableName: string;\n}\n\ninterface FlushBatchResult {\n processedCount: number;\n affectedContexts: TableContext[];\n /** Mutation ids that transitioned to `quarantined` in this slice (ADR-0006), for surfacing. */\n quarantinedMutationIds: string[];\n /** Mutation ids that transitioned to `conflicted` in this slice (ADR-0015), for surfacing. */\n conflictedMutationIds: string[];\n}\n\ninterface MutationStatusUpdate {\n mutationId: string;\n status: MutationStatus;\n attemptCount: number;\n updatedAtUs: string;\n sentAtUs?: string | null;\n replaceSentAtUs?: boolean;\n ackedAtUs?: string | null;\n replaceAckedAtUs?: boolean;\n serverUpdatedAtUs?: string | null;\n replaceServerUpdatedAtUs?: boolean;\n baseServerVersion?: string | null;\n replaceBaseServerVersion?: boolean;\n lastError?: string | null;\n nextRetryAtUs?: string | null;\n lastHttpStatus?: number | null;\n conflictReason?: string | null;\n}\n\n/**\n * The resolved Base server version (ADR-0015) for a row at flush. A **chain head** already carries\n * `base_server_version` (stamped at enqueue), so COALESCE returns it untouched — keeping the\n * enqueue-time base means a genuine external write between view and apply is still caught. A\n * **chained** write has NULL there; it resolves to its **acked predecessor's** Server version (by\n * Per-entity flush serialization the predecessor is already acked when this row flushes), falling\n * back to the entity's current synced version once that predecessor has been reconciled away. Either\n * fallback yields the entity's own latest server state, so its own chain never self-conflicts.\n */\nfunction buildResolvedBaseServerVersion(context: TableContext): SQL {\n const journal = context.tables.journal;\n const synced = context.tables.synced;\n const pred = alias(journal, \"pred\");\n const predecessor = queryBuilder\n .select({ value: sql`MAX(${pred.serverUpdatedAtUs})` })\n .from(pred)\n .where(\n and(\n eq(pred.entityKeyJson, journal.entityKeyJson),\n lt(pred.mutationSeq, journal.mutationSeq),\n eq(pred.status, \"acked\"),\n ),\n );\n\n if (!context.syncedServerVersionColumn) {\n return sql`COALESCE(${journal.baseServerVersion}, ${predecessor})::text`;\n }\n\n const syncedFallback = queryBuilder\n .select({ value: sql`${context.syncedServerVersionColumn}` })\n .from(synced)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) => eq(context.syncedPkColumns[index]!, journal[columnName]!)),\n ),\n );\n\n return sql`COALESCE(${journal.baseServerVersion}, ${predecessor}, ${syncedFallback})::text`;\n}\n\n/**\n * One table's send-eligible journal rows as a builder select with the shared {@link PendingBatchRow}\n * projection — the aliases ARE the row keys (raw seam), `tableKey` rides as a bound param, and the\n * resolved Base server version (ADR-0015) is the typed COALESCE fragment above.\n */\nfunction buildPendingRowsProjection(context: TableContext) {\n const journal = context.tables.journal;\n return {\n tableKey: sql<string>`${context.key}`.as(\"tableKey\"),\n mutationId: sql<string>`${journal.mutationId}`.as(\"mutationId\"),\n entityKeyJson: sql<string>`${journal.entityKeyJson}`.as(\"entityKeyJson\"),\n mutationSeq: sql<number>`${journal.mutationSeq}`.as(\"mutationSeq\"),\n mutationKind: sql<MutationKind>`${journal.mutationKind}`.as(\"mutationKind\"),\n status: journal.status,\n payloadJson: sql<string>`${journal.payloadJson}`.as(\"payloadJson\"),\n attemptCount: sql<number>`${journal.attemptCount}`.as(\"attemptCount\"),\n lastHttpStatus: sql<number | null>`${journal.lastHttpStatus}`.as(\"lastHttpStatus\"),\n lastError: sql<string | null>`${journal.lastError}`.as(\"lastError\"),\n conflictReason: sql<string | null>`${journal.conflictReason}`.as(\"conflictReason\"),\n nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as(\"nextRetryAtUs\"),\n serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as(\"serverUpdatedAtUs\"),\n baseServerVersion: buildResolvedBaseServerVersion(context).as(\"baseServerVersion\"),\n enqueuedAtUs: sql<string>`${journal.enqueuedAtUs}::text`.as(\"enqueuedAtUs\"),\n };\n}\n\nasync function readPendingBatchRows(db: MutationDb, contexts: TableContext[], nowUs: string, batchSize: number) {\n if (contexts.length === 0) {\n return [] as PendingBatchRow[];\n }\n\n const branches = contexts.map((context) => {\n const journal = context.tables.journal;\n const earlier = alias(journal, \"earlier\");\n return queryBuilder\n .select(buildPendingRowsProjection(context))\n .from(journal)\n .where(\n and(\n inArray(journal.status, [\"pending\", \"failed\"]),\n // ADR-0022: pessimistic rows are flushed by the authoritative unit path (flushUnit), never the\n // optimistic batch — exclude them here so a tagged write is never optimistically sent. The\n // `NOT LIKE 'pessimistic%'` also excludes a `pessimistic-blind` row (ADR-0022 addendum), which\n // belongs to its unit's foreground flush too.\n sql`COALESCE(${journal.writeMode}, '') NOT LIKE 'pessimistic%'`,\n sql`COALESCE(${journal.nextRetryAtUs}, 0) <= ${nowUs}::bigint`,\n notExists(\n queryBuilder\n .select({ one: sql`1` })\n .from(earlier)\n .where(\n and(\n eq(earlier.entityKeyJson, journal.entityKeyJson),\n lt(earlier.mutationSeq, journal.mutationSeq),\n // A still-unresolved earlier mutation blocks later same-entity ones so the\n // server applies them in author order. The quarantined status is included: a\n // later mutation must not flush past a prerequisite the server permanently\n // rejected (it would itself fail); resolving the quarantine unblocks the queue.\n inArray(earlier.status, [\"pending\", \"failed\", \"sending\", \"quarantined\"]),\n ),\n ),\n ),\n ),\n );\n });\n\n // The union rides inside a derived table because the outer ORDER BY casts the (text) output\n // columns — a set operation's own ORDER BY may only name plain output columns. The `pending`\n // alias and its two quoted output-column names are fixed by the projection above, not data.\n const query = queryDialect.sqlToQuery(\n sql`SELECT * FROM (${sql.join(branches, sql` UNION ALL `)}) AS pending ORDER BY pending.\"enqueuedAtUs\"::bigint ASC, pending.\"mutationSeq\" ASC LIMIT ${batchSize}`,\n );\n const result = await db.query<PendingBatchRow>(query.sql, query.params as unknown[]);\n\n return result.rows;\n}\n\n/**\n * Read one pessimistic write-unit's send-eligible rows (ADR-0022) across every table, ordered by author\n * sequence. Unlike {@link readPendingBatchRows} it has no per-entity ordering gate: a unit is enqueued and\n * sent atomically, so its members go together.\n */\nasync function readUnitPendingRows(\n db: MutationDb,\n contexts: TableContext[],\n unitId: string,\n): Promise<PendingBatchRow[]> {\n if (contexts.length === 0) {\n return [];\n }\n\n const branches = contexts.map((context) => {\n const journal = context.tables.journal;\n return queryBuilder\n .select(buildPendingRowsProjection(context))\n .from(journal)\n .where(and(eq(journal.writeUnit, unitId), inArray(journal.status, [\"pending\", \"failed\"])));\n });\n\n const query = queryDialect.sqlToQuery(\n sql`SELECT * FROM (${sql.join(branches, sql` UNION ALL `)}) AS unit ORDER BY unit.\"mutationSeq\" ASC`,\n );\n const result = await db.query<PendingBatchRow>(query.sql, query.params as unknown[]);\n\n return result.rows;\n}\n\nasync function flushBatch(\n db: MutationDb,\n tableContexts: Record<string, TableContext>,\n batchWriteUrl: string,\n maxAttempts: number,\n batchSize: number,\n tableFilter?: string,\n getAuthToken?: () => Promise<string | undefined>,\n requestHeaders?: Record<string, string>,\n): Promise<FlushBatchResult> {\n const contexts = filterContexts(tableContexts, tableFilter);\n const nowUs = nowMicroseconds();\n const quarantinedMutationIds: string[] = [];\n const conflictedMutationIds: string[] = [];\n\n // Collect send-eligible mutations across all target tables.\n const pendingRows = await readPendingBatchRows(db, contexts, nowUs, batchSize);\n const pending: PreparedBatchRow[] = [];\n const pendingByTable = new Map<string, PreparedBatchRow[]>();\n\n for (const row of pendingRows) {\n const context = tableContexts[row.tableKey];\n\n if (!context) {\n continue;\n }\n\n const entityKey = JSON.parse(row.entityKeyJson) as Record<string, string>;\n const rawPayload = JSON.parse(row.payloadJson) as Record<string, unknown>;\n const preparedRow: PreparedBatchRow = {\n ...row,\n context,\n entityKey,\n envelopePayload:\n row.mutationKind === \"delete\"\n ? entityKey\n : toSqlColumnPayload(\n context,\n stripManagedFields(\n context,\n (rawPayload[\"value\"] ?? rawPayload[\"patch\"] ?? rawPayload) as Record<string, unknown>,\n row.mutationKind as \"create\" | \"update\",\n ),\n ),\n sqlTableName: context.entry.shape?.tableName ?? context.key,\n };\n\n pending.push(preparedRow);\n\n const existingTableRows = pendingByTable.get(context.key);\n\n if (existingTableRows) {\n existingTableRows.push(preparedRow);\n } else {\n pendingByTable.set(context.key, [preparedRow]);\n }\n }\n\n if (pending.length === 0) {\n // If a write just enqueued and requested a pass, but this flush sees nothing, the pass raced the\n // journal commit (or everything is already in-flight/backed-off) — the write then waits for a\n // later pass. Worth seeing explicitly when chasing flush latency.\n syncDebug(\"flushBatch: no send-eligible mutations this pass\");\n return {\n processedCount: 0,\n affectedContexts: [],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n }\n\n syncDebug(\"flushBatch sending to board-write\", { count: pending.length });\n\n // Mark all as sending.\n const sentAtUs = nowMicroseconds();\n\n for (const rows of pendingByTable.values()) {\n await applyMutationStatusUpdates(\n db,\n rows[0]!.context,\n rows.map((row) => ({\n mutationId: row.mutationId,\n status: \"sending\",\n attemptCount: row.attemptCount + 1,\n updatedAtUs: sentAtUs,\n sentAtUs,\n replaceSentAtUs: true,\n // Persist the resolved Base server version (ADR-0015) so a chained write's flush-resolved\n // base is durable and matches exactly what the envelope carries to the server.\n baseServerVersion: row.baseServerVersion,\n replaceBaseServerVersion: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: null,\n conflictReason: null,\n })),\n );\n }\n\n const mutations = pending.map((row) => {\n return {\n tableName: row.sqlTableName,\n entityKey: row.entityKey,\n mutationId: row.mutationId,\n mutationSeq: row.mutationSeq,\n kind: row.mutationKind as \"create\" | \"update\" | \"delete\",\n payload: row.envelopePayload,\n clientTimestampUs: sentAtUs,\n // ADR-0015: carry the resolved Base server version so the applier can detect a stale write.\n // Omitted for a create / a table that predates the policy (null) — then no stale check runs.\n ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),\n };\n });\n\n let responseOk = false;\n let acksByMutationId: Map<string, BatchMutationAck[\"acks\"][number]> = new Map();\n const batchMutationUrl = resolveBatchMutationUrl(batchWriteUrl);\n\n try {\n // Resolve the auth token and the network round-trip separately: in the board, `getAuthToken` calls\n // `supabase.auth.getSession()` per send, which can itself stall (token refresh) and would otherwise\n // be invisibly folded into \"the write was slow\".\n const authStart = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n const authToken = await getAuthToken?.();\n const fetchStart = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n syncDebug(\"board-write auth token resolved\", { ms: Math.round(fetchStart - authStart) });\n\n let response = await fetch(batchMutationUrl, {\n method: \"POST\",\n headers: buildRequestHeaders(authToken, requestHeaders),\n body: jsonStringifyPayload({ mutations }),\n });\n\n if ([401, 403].includes(response.status) && getAuthToken) {\n response = await fetch(batchMutationUrl, {\n method: \"POST\",\n headers: buildRequestHeaders(await getAuthToken(), requestHeaders),\n body: jsonStringifyPayload({ mutations }),\n });\n }\n\n const fetchEnd = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n syncDebug(\"board-write responded\", { status: response.status, ms: Math.round(fetchEnd - fetchStart) });\n\n if (response.ok) {\n const responseJson = (await response.json()) as BatchMutationAck;\n responseOk = true;\n acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));\n syncDebug(\"board-write acks\", {\n acks: responseJson.acks.map((ack) => `${ack.mutationId.slice(0, 8)}:${ack.status}`),\n });\n } else {\n const text = await response.text();\n throw new MutationRequestError(\n text.length > 0 ? text : `Bulk write responded with ${response.status}`,\n response.status,\n parseBatchRejections(text),\n );\n }\n } catch (error) {\n const failedAtUs = nowMicroseconds();\n const httpStatus = error instanceof MutationRequestError ? error.status : null;\n const errorMessage = error instanceof Error ? error.message : \"Unknown batch write failure\";\n // The server attributed the failure to specific mutations (a structural validation\n // rejection of an atomic batch). When present, we quarantine exactly those and leave the\n // innocent siblings immediately retryable; absent (transport / 5xx / auth / malformed\n // envelope), the whole batch stays retryable under the shared attempt cap.\n const rejectionById =\n error instanceof MutationRequestError && error.rejections\n ? new Map(error.rejections.map((rejection) => [rejection.mutationId, rejection]))\n : null;\n\n for (const rows of pendingByTable.values()) {\n await applyMutationStatusUpdates(\n db,\n rows[0]!.context,\n rows.map((row) => {\n const attemptCount = row.attemptCount + 1;\n\n if (rejectionById) {\n const rejection = rejectionById.get(row.mutationId);\n\n if (rejection) {\n // Named as the cause: terminal quarantine (it will never succeed unchanged).\n quarantinedMutationIds.push(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"quarantined\" as const,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: rejection.reason,\n nextRetryAtUs: null,\n lastHttpStatus: httpStatus,\n conflictReason: rejection.reason,\n };\n }\n\n // Innocent sibling: nothing was applied (atomic batch), so make it immediately\n // retryable — no backoff (the fault was the now-quarantined mutation, not\n // congestion) — and the next flush proceeds without the poison.\n return {\n mutationId: row.mutationId,\n status: \"failed\" as const,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: \"Batch rejected due to a sibling mutation; retrying without it\",\n nextRetryAtUs: null,\n lastHttpStatus: httpStatus,\n conflictReason: null,\n };\n }\n\n // Unattributed batch-level failure: stays retryable with jittered backoff; only the\n // hard attempt cap escalates to terminal quarantined. A structural 4xx is NOT\n // quarantined here (a stray 404/413/malformed envelope would otherwise permanently\n // kill unrelated valid writes).\n const outcome = resolveBatchFailureOutcome(attemptCount, maxAttempts, failedAtUs);\n\n if (outcome.status === \"quarantined\") {\n quarantinedMutationIds.push(row.mutationId);\n }\n\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: errorMessage,\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: httpStatus,\n conflictReason: null,\n };\n }),\n );\n }\n\n return {\n processedCount: pending.length,\n affectedContexts: [...new Set(pending.map((row) => row.context))],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n }\n\n if (!responseOk) {\n return {\n processedCount: pending.length,\n affectedContexts: [...new Set(pending.map((row) => row.context))],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n }\n\n // Apply per-mutation ack results.\n const ackedAtUs = nowMicroseconds();\n const failedAtUs = nowMicroseconds();\n\n for (const rows of pendingByTable.values()) {\n await applyMutationStatusUpdates(\n db,\n rows[0]!.context,\n rows.map((row) => {\n const ack = acksByMutationId.get(row.mutationId);\n\n if (ack && ack.status === \"conflicted\") {\n // ADR-0015: a stale write the reject-if-stale policy declined. Move to the terminal\n // `conflicted` status — NOT a failure (never retried as-is, the base is still stale) — and\n // KEEP the optimistic Overlay (reconcile only clears acked rows, so the user's edit stays\n // visible). The server's current Server version rides on the journal row for the diff UI.\n conflictedMutationIds.push(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"conflicted\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: failedAtUs,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n nextRetryAtUs: null,\n lastHttpStatus: ack.httpStatus ?? 409,\n conflictReason: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n };\n }\n\n if (!ack || ack.status !== \"acked\") {\n const attemptCount = row.attemptCount + 1;\n const httpStatus = ack?.httpStatus ?? null;\n const outcome = resolveFailureOutcome(httpStatus, attemptCount, maxAttempts, failedAtUs);\n\n if (outcome.status === \"quarantined\") {\n quarantinedMutationIds.push(row.mutationId);\n }\n\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: ack?.conflictReason ?? \"Batch mutation not acknowledged\",\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: httpStatus,\n conflictReason: ack?.conflictReason ?? null,\n };\n }\n\n if (row.mutationKind === \"delete\") {\n return {\n mutationId: row.mutationId,\n status: \"acked\",\n attemptCount: row.attemptCount + 1,\n updatedAtUs: ackedAtUs,\n ackedAtUs,\n replaceAckedAtUs: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: 204,\n conflictReason: null,\n };\n }\n\n return {\n mutationId: row.mutationId,\n status: \"acked\",\n attemptCount: row.attemptCount + 1,\n updatedAtUs: ackedAtUs,\n ackedAtUs,\n replaceAckedAtUs: true,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: 200,\n conflictReason: null,\n };\n }),\n );\n }\n\n return {\n processedCount: pending.length,\n affectedContexts: [...new Set(pending.map((row) => row.context))],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n}\n\n/**\n * Resolve a flush failure into the durable journal outcome (ADR-0006). A structural\n * rejection ({@link classifyFailureStatus}) or hitting the hard attempt cap ends the\n * retry loop with a terminal `quarantined` (no `next_retry_at_us`); otherwise the\n * mutation stays `failed` with a jittered backoff (ADR-0005 congestion policy).\n */\nfunction resolveFailureOutcome(\n httpStatus: number | null,\n attemptCount: number,\n maxAttempts: number,\n failedAtUs: string,\n): { status: \"failed\" | \"quarantined\"; nextRetryAtUs: string | null } {\n if (classifyFailureStatus(httpStatus) === \"quarantined\" || attemptCount >= maxAttempts) {\n return { status: \"quarantined\", nextRetryAtUs: null };\n }\n\n return { status: \"failed\", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };\n}\n\n/**\n * Resolve a *batch-level* failure — the whole POST failed (transport error, 5xx, auth, or a\n * non-2xx the server did not attribute to a specific mutation). Unlike a per-mutation ack\n * rejection, the fault cannot be pinned on any one mutation, so a structural 4xx must NOT\n * quarantine the batch (a stray 404/413/malformed envelope would permanently kill unrelated\n * valid offline writes). These failures stay retryable `failed` with jittered backoff; only\n * the hard attempt cap escalates to terminal `quarantined`.\n */\nfunction resolveBatchFailureOutcome(\n attemptCount: number,\n maxAttempts: number,\n failedAtUs: string,\n): { status: \"failed\" | \"quarantined\"; nextRetryAtUs: string | null } {\n if (attemptCount >= maxAttempts) {\n return { status: \"quarantined\", nextRetryAtUs: null };\n }\n\n return { status: \"failed\", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };\n}\n\nfunction resolveBatchMutationUrl(batchWriteUrl: string): string {\n const trimmed = batchWriteUrl.replace(/\\/+$/, \"\");\n\n if (trimmed.endsWith(\"/mutations\")) {\n return trimmed;\n }\n\n return `${trimmed}/mutations`;\n}\n\n/** The authoritative (pessimistic) write endpoint (ADR-0022): the batch URL with `/unit` appended. */\nfunction resolveAuthoritativeMutationUrl(batchWriteUrl: string): string {\n return `${resolveBatchMutationUrl(batchWriteUrl)}/unit`;\n}\n\nfunction stripManagedFields(\n context: TableContext,\n payload: Record<string, unknown>,\n operation: \"create\" | \"update\",\n): Record<string, unknown> {\n const managedColumns = new Set<string>();\n\n for (const mf of context.entry.governance?.managedFields ?? []) {\n if (mf.applyOn.includes(operation)) {\n managedColumns.add(mf.column);\n }\n }\n\n if (managedColumns.size === 0) return payload;\n\n return Object.fromEntries(Object.entries(payload).filter(([key]) => !managedColumns.has(key)));\n}\n\nfunction toSqlColumnPayload(context: TableContext, payload: Record<string, unknown>): Record<string, unknown> {\n const normalized: Record<string, unknown> = {};\n\n for (const { propertyKey, column } of context.columns) {\n const columnName = column.name;\n\n if (Object.prototype.hasOwnProperty.call(payload, columnName)) {\n normalized[columnName] = payload[columnName];\n continue;\n }\n\n if (Object.prototype.hasOwnProperty.call(payload, propertyKey)) {\n normalized[columnName] = payload[propertyKey];\n }\n }\n\n return normalized;\n}\n\n/**\n * Discard a terminal-state entity: clear its journal rows in the given terminal status\n * (`conflicted` — ADR-0015; or `quarantined` — ADR-0006) and its kept optimistic Overlay row, so the\n * Read model falls back to the synced (server) value. The overlay is removed only when no OTHER journal\n * row still owes the entity (a pending/sending/failed/acked write), mirroring reconcileTable's\n * overlay-clear guard — so a discard never strips an overlay another un-resolved write still depends\n * on. Both public discards (`discardConflict`, `discardQuarantined`) are this one body parameterized by\n * the terminal status they retire; owning its own transaction (like reconcileTable), it is not wrapped.\n */\nasync function discardTerminalEntity(\n db: MutationDb,\n context: TableContext,\n entityKey: Record<string, string>,\n entityKeyJson: string,\n terminalStatus: \"conflicted\" | \"quarantined\",\n) {\n await db.exec(\"BEGIN\");\n\n try {\n const journal = context.tables.journal;\n const clearQuery = queryBuilder\n .delete(journal)\n .where(and(eq(journal.status, terminalStatus), eq(journal.entityKeyJson, entityKeyJson)))\n .toSQL();\n await db.query(clearQuery.sql, clearQuery.params as unknown[]);\n\n // Clear the kept overlay only when no journal row still owes this entity — so a discard never\n // strips an overlay another un-resolved write (e.g. a resolution already enqueued) depends on.\n const overlayQuery = buildOverlayDiscardQuery(context, entityKey, entityKeyJson);\n await db.query(overlayQuery.sql, overlayQuery.params as unknown[]);\n\n await db.exec(\"COMMIT\");\n } catch (error) {\n await db.exec(\"ROLLBACK\");\n throw error;\n }\n}\n\n/**\n * The shared overlay-discard statement: delete the entity's overlay row unless a journal row still\n * owes the entity — `owedStatuses` narrows which journal rows count as \"owed\" (all of them for a\n * conflict discard; only the un-sent pending/sending/failed set for a settled-unit discard).\n */\nfunction buildOverlayDiscardQuery(\n context: TableContext,\n entityKey: Record<string, string>,\n entityKeyJson: string,\n owedStatuses?: MutationStatus[],\n) {\n const overlay = context.tables.overlay;\n const journal = context.tables.journal;\n const owed = queryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(\n owedStatuses\n ? and(eq(journal.entityKeyJson, entityKeyJson), inArray(journal.status, owedStatuses))\n : eq(journal.entityKeyJson, entityKeyJson),\n );\n\n return queryBuilder\n .delete(overlay)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.overlayPkColumns[index]!, entityKey[columnName]),\n ),\n notExists(owed),\n ),\n )\n .toSQL();\n}\n\n/**\n * Auto-discard the optimistic overlay for an entity whose pessimistic write-unit the authoritative endpoint\n * `rejected` (ADR-0022 §4). Unlike {@link discardTerminalEntity} this KEEPS the terminal `rejected` journal\n * row (for diagnostics + `onReject`); it only clears the overlay, and only when no still-owed\n * (`pending`/`sending`/`failed`) journal row depends on it — so a later un-sent write never loses its overlay.\n */\nasync function discardOverlayForSettledEntity(\n db: MutationDb,\n context: TableContext,\n entityKey: Record<string, string>,\n entityKeyJson: string,\n) {\n const query = buildOverlayDiscardQuery(context, entityKey, entityKeyJson, [\"pending\", \"sending\", \"failed\"]);\n await db.query(query.sql, query.params as unknown[]);\n}\n\nasync function reconcileTable(db: MutationDb, context: TableContext) {\n // Idle fast-path. Reconcile only retires/clears journal rows in a terminal-clearable state — 'acked'\n // (clear the overlay once the echo lands) or 'conflicted' (retire once a later write resolved it). When\n // none exist — the steady state of an idle entity set — all three statements below are no-ops, so skip\n // the whole transaction. This matters because the convergence driver runs reconcile for EVERY writable\n // table on its interval (default 1.5s), and each CTE pays full PGlite plan+execute cost even against an\n // empty journal: left unguarded it is the dominant idle-CPU cost. The real-time cleanup path is the\n // <table>_reconcile_on_sync trigger; this bulk pass is a fallback, so skipping it when there is nothing\n // to clear changes no outcome. The guard is a single existence probe over the (small, usually empty)\n // journal.\n const journal = context.tables.journal;\n const overlay = context.tables.overlay;\n const synced = context.tables.synced;\n // This is the idle-CPU hot statement (it runs for every writable table on every convergence\n // tick), so the rendered text+params are memoized per context — each tick pays only a plain\n // `db.query` of a cached string, and it stays OUTSIDE any transaction (no BEGIN on the idle path).\n let idleProbe = context.reconcileIdleProbe;\n if (!idleProbe) {\n const probeQuery = queryDialect.sqlToQuery(\n sql`SELECT ${exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(inArray(journal.status, [\"acked\", \"conflicted\"])),\n )} AS \"hasWork\"`,\n );\n idleProbe = { sql: probeQuery.sql, params: probeQuery.params as unknown[] };\n context.reconcileIdleProbe = idleProbe;\n }\n const work = await db.query<{ hasWork: boolean }>(idleProbe.sql, idleProbe.params);\n if (work.rows[0]?.hasWork !== true) {\n return;\n }\n\n // The Convergence barrier (ADR-0010) gates the acked-row clearing below; the synced-table trigger\n // handles real-time cleanup, and this is the bulk recovery/fallback path that runs after every flush.\n await db.exec(\"BEGIN\");\n\n try {\n // ADR-0015: retire a terminal `conflicted` row once the user has RESOLVED it — i.e. a LATER write\n // on the same entity has been acked (resolution is an ordinary new mutation). Without this, the old\n // conflicted row lingers forever: `<table>_sync_state.conflict_state` keeps surfacing the resolved\n // conflict and `diagnostics().conflictedCount` never drops. Run before the acked-clear below so the\n // resolving row is still present to supersede it. (`discardConflict` is the explicit throw-away path.)\n // Drizzle DELETE has no USING; the resolver leg is the equivalent EXISTS semi-join.\n const resolver = alias(journal, \"resolver\");\n const retireQuery = queryBuilder\n .delete(journal)\n .where(\n and(\n eq(journal.status, \"conflicted\"),\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(resolver)\n .where(\n and(\n eq(resolver.entityKeyJson, journal.entityKeyJson),\n gt(resolver.mutationSeq, journal.mutationSeq),\n eq(resolver.status, \"acked\"),\n ),\n ),\n ),\n ),\n )\n .toSQL();\n await db.query(retireQuery.sql, retireQuery.params as unknown[]);\n\n // ADR-0022 addendum — retire an acked `pessimistic-blind` row with NO echo barrier. A blind update's\n // write target is excluded from this actor's read shape, so no synced echo will ever land for it and no\n // overlay was ever planned: the standard acked-clear below (gated on a synced row reaching the acked\n // version) would keep it forever. Nothing local converges for these rows, so once the authoritative unit\n // acked them there is nothing left to do but drop the journal row. Crash-safe: any later reconcile tick\n // clears a blind row the foreground flushUnit didn't survive to reconcile.\n const blindRetireQuery = queryBuilder\n .delete(journal)\n .where(and(eq(journal.status, \"acked\"), eq(journal.writeMode, \"pessimistic-blind\")))\n .toSQL();\n await db.query(blindRetireQuery.sql, blindRetireQuery.params as unknown[]);\n\n // Clear acknowledged non-delete mutations + matching overlays. ADR-0010: gated by the\n // Convergence barrier (same predicate as the trigger) — the acked write clears only once the\n // synced echo's Server version has reached its acked version. Joining the synced table makes\n // the comparison possible (and means an un-synced acked write is held until its echo lands).\n // Drizzle authoring: DELETE..USING becomes the equivalent EXISTS semi-join, chained through a\n // data-modifying CTE (both sub-statements see the same statement-start snapshot, exactly like\n // the USING form). The barrier predicate stays the shared contracts helper (single authority\n // with the trigger); it renders against the tables' own names, which is how drizzle references\n // their columns here (no aliases on a DELETE target).\n const barrier = sql.raw(\n buildOverlayResolutionBarrier(context.entry, {\n journalAlias: quoteIdentifier(getTableConfig(journal).name),\n syncedAlias: quoteIdentifier(getTableConfig(synced).name),\n }),\n );\n const clearedJournal = queryBuilder.$with(\"cleared_journal\").as(\n queryBuilder\n .delete(journal)\n .where(\n and(\n eq(journal.status, \"acked\"),\n isNotNull(journal.serverUpdatedAtUs),\n ne(journal.mutationKind, \"delete\"),\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(synced)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.syncedPkColumns[index]!, journal[columnName]!),\n ),\n barrier,\n ),\n ),\n ),\n ),\n )\n .returning(\n Object.fromEntries([\n [\"entity_key_json\", journal.entityKeyJson],\n ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]!]),\n ]),\n ),\n );\n const clearedJournalColumns = clearedJournal as unknown as Record<string, PgColumn>;\n const ackedClearQuery = queryBuilder\n .with(clearedJournal)\n .delete(overlay)\n .where(\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(clearedJournal)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.overlayPkColumns[index]!, clearedJournalColumns[columnName]!),\n ),\n notExists(\n queryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(\n and(\n eq(journal.entityKeyJson, clearedJournalColumns[\"entity_key_json\"]!),\n inArray(journal.status, [\"pending\", \"sending\", \"failed\"]),\n ),\n ),\n ),\n ),\n ),\n ),\n )\n .toSQL();\n await db.query(ackedClearQuery.sql, ackedClearQuery.params as unknown[]);\n\n // Clear acknowledged delete mutations where synced row is absent\n // Single compound CTE — PGlite does not support multi-statement query().\n const clearableEntities = queryBuilder.$with(\"clearable_entities\").as(\n queryBuilder\n .selectDistinct(\n Object.fromEntries([\n [\"entity_key_json\", journal.entityKeyJson],\n ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]!]),\n ]),\n )\n .from(journal)\n .leftJoin(\n synced,\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.syncedPkColumns[index]!, journal[columnName]!),\n ),\n ),\n )\n .where(\n and(eq(journal.status, \"acked\"), eq(journal.mutationKind, \"delete\"), isNull(context.syncedPkColumns[0]!)),\n ),\n );\n const clearableEntityColumns = clearableEntities as unknown as Record<string, PgColumn>;\n const deletedOverlay = queryBuilder.$with(\"deleted_overlay\").as(\n queryBuilder.delete(overlay).where(\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(clearableEntities)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.overlayPkColumns[index]!, clearableEntityColumns[columnName]!),\n ),\n ),\n ),\n ),\n ),\n );\n const deleteClearQuery = queryBuilder\n .with(clearableEntities, deletedOverlay)\n .delete(journal)\n .where(\n and(\n eq(journal.status, \"acked\"),\n eq(journal.mutationKind, \"delete\"),\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(clearableEntities)\n .where(\n and(\n ...context.pkColumnNames.map((columnName) =>\n eq(journal[columnName]!, clearableEntityColumns[columnName]!),\n ),\n ),\n ),\n ),\n ),\n )\n .toSQL();\n await db.query(deleteClearQuery.sql, deleteClearQuery.params as unknown[]);\n await db.exec(\"COMMIT\");\n } catch (error) {\n await db.exec(\"ROLLBACK\");\n throw error;\n }\n}\n\nfunction buildRequestHeaders(bearerToken?: string, requestHeaders?: Record<string, string>): Record<string, string> {\n // Static headers first so the toolkit-owned Content-Type/Authorization always win.\n return {\n ...(requestHeaders ?? {}),\n \"Content-Type\": \"application/json\",\n ...(bearerToken ? { Authorization: `Bearer ${bearerToken}` } : {}),\n };\n}\n\nasync function applyMutationStatusUpdates(db: MutationDb, context: TableContext, updates: MutationStatusUpdate[]) {\n if (updates.length === 0) {\n return;\n }\n\n // Tier ②: `update().from(<VALUES>)`. Every value is a bound param with the same cast as before;\n // the `updates` alias and its column list are fixed by this function (not derived from data), so\n // the alias-qualified references in SET/WHERE are fixed template text, while the journal side of\n // each CASE interpolates the column objects.\n const journal = context.tables.journal;\n const tuples = updates.map(\n (update) =>\n sql`(${update.mutationId}, ${update.status}, ${update.attemptCount}::int, ${update.updatedAtUs}::bigint, ${\n update.sentAtUs ?? null\n }::bigint, ${update.replaceSentAtUs ?? false}::boolean, ${update.ackedAtUs ?? null}::bigint, ${\n update.replaceAckedAtUs ?? false\n }::boolean, ${update.serverUpdatedAtUs ?? null}::bigint, ${update.replaceServerUpdatedAtUs ?? false}::boolean, ${\n update.baseServerVersion ?? null\n }::bigint, ${update.replaceBaseServerVersion ?? false}::boolean, ${update.lastError ?? null}, ${\n update.nextRetryAtUs ?? null\n }::bigint, ${update.lastHttpStatus ?? null}::int, ${update.conflictReason ?? null})`,\n );\n const updatesTable = sql`(VALUES ${sql.join(\n tuples,\n sql`, `,\n )}) AS updates (mutation_id, status, attempt_count, updated_at_us, sent_at_us, replace_sent_at_us, acked_at_us, replace_acked_at_us, server_updated_at_us, replace_server_updated_at_us, base_server_version, replace_base_server_version, last_error, next_retry_at_us, last_http_status, conflict_reason)`;\n\n const query = queryBuilder\n .update(journal)\n .set({\n status: sql`updates.status`,\n attemptCount: sql`updates.attempt_count`,\n updatedAtUs: sql`updates.updated_at_us::bigint`,\n sentAtUs: sql`CASE WHEN updates.replace_sent_at_us THEN updates.sent_at_us::bigint ELSE ${journal.sentAtUs} END`,\n ackedAtUs: sql`CASE WHEN updates.replace_acked_at_us THEN updates.acked_at_us::bigint ELSE ${journal.ackedAtUs} END`,\n serverUpdatedAtUs: sql`CASE WHEN updates.replace_server_updated_at_us THEN updates.server_updated_at_us::bigint ELSE ${journal.serverUpdatedAtUs} END`,\n baseServerVersion: sql`CASE WHEN updates.replace_base_server_version THEN updates.base_server_version::bigint ELSE ${journal.baseServerVersion} END`,\n lastError: sql`updates.last_error`,\n nextRetryAtUs: sql`updates.next_retry_at_us::bigint`,\n lastHttpStatus: sql`updates.last_http_status`,\n conflictReason: sql`updates.conflict_reason`,\n })\n .from(updatesTable)\n .where(eq(journal.mutationId, sql`updates.mutation_id::uuid`))\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\nfunction qualifyLocalIdentifier(schemaName: string, tableName: string) {\n if (schemaName === \"public\") {\n // Quote-when-needed: a reserved-word or mixed-case table name (e.g. `group`)\n // MUST be quoted or the generated SQL fails to parse (ADR-0004). Normal names\n // stay bare, so existing generated SQL is unchanged.\n return maybeQuoteIdentifier(tableName);\n }\n\n return `${quoteIdentifier(schemaName)}.${quoteIdentifier(tableName)}`;\n}\n\nfunction buildJournalSequenceName(journalTable: string) {\n return `${journalTable}_mutation_seq`;\n}\n\nfunction hasProperty(context: TableContext, propertyKey: string) {\n return context.columns.some((column) => column.propertyKey === propertyKey);\n}\n\nfunction ensureRecord(value: unknown) {\n if (!isRecord(value)) {\n throw new Error(\"Mutation runtime expected a record payload\");\n }\n\n return value;\n}\n\nfunction extractRecordFromState(context: TableContext, state: CurrentRecordStateRow | BatchCurrentRecordStateRow) {\n return Object.fromEntries(context.columns.map(({ propertyKey }) => [propertyKey, state[propertyKey] ?? null]));\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nclass MutationRequestError extends Error {\n readonly status: number;\n /** Per-mutation attribution the server returned for a structural rejection, or null. */\n readonly rejections: MutationRejection[] | null;\n\n constructor(message: string, status: number, rejections: MutationRejection[] | null = null) {\n super(message);\n this.name = \"MutationRequestError\";\n this.status = status;\n this.rejections = rejections;\n }\n}\n\n/**\n * Extract per-mutation attribution from a non-2xx batch-write body. The server names the\n * offending mutations on a structural (validation) rejection; an absent, non-JSON, or\n * empty-`rejections` body yields null, so the failure is treated as non-attributable\n * (whole batch stays retryable).\n */\nfunction parseBatchRejections(body: string): MutationRejection[] | null {\n if (body.length === 0) {\n return null;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return null;\n }\n\n const result = batchMutationErrorSchema.safeParse(parsed);\n const rejections = result.success ? result.data.rejections : undefined;\n return rejections && rejections.length > 0 ? rejections : null;\n}\n",
132
139
  "import type { ExternalHeadersRecord, ShapeStreamOptions } from \"@electric-sql/client\";\n\n/** The per-shape error handler shape Electric expects (`ShapeStreamOptions.onError`). */\ntype ShapeStreamErrorHandler = NonNullable<ShapeStreamOptions[\"onError\"]>;\n\n/**\n * Read-path identity (ADR-0013). The two ingress points must share **one** token lifecycle: the\n * write path already calls `getAuthToken` fresh on every flush, so the read path must too — never\n * freezing a JWT at boot, which wedges a long-lived offline-first session the instant the token\n * expires.\n *\n * `buildAuthShapeHeaders` returns the read-path `Authorization` header as an **async function**.\n * Electric resolves header-value functions on every request *and every retry*\n * (`ExternalHeadersRecord` allows `string | (() => string | Promise<string>)`), so each shape fetch\n * presents a fresh token. This is the client mirror of ADR-0003's server-side one-identity decision.\n *\n * The provider contract (documented in `docs/architecture.md`): `getAuthToken` is now called per\n * request by both paths and **must be refresh-deduping** — return the cached valid token and refresh\n * single-flight, so an N-shape consistency group does not trigger N refreshes.\n */\n/**\n * Build the read-path shape headers: the optional async `Authorization` (per ADR-0013) **plus** any\n * caller-supplied static `requestHeaders`. The static headers are spread first so the toolkit-owned\n * `Authorization` always wins; they exist for deployment-gateway credentials the toolkit is otherwise\n * agnostic about — e.g. a Supabase `apikey` header the platform function gateway expects. Emitted\n * whenever *either* a token provider or static headers are present, so a credential-only consumer\n * (no per-request token) still sends its headers.\n */\nexport function buildShapeHeaders(input: {\n getAuthToken?: () => Promise<string | undefined>;\n requestHeaders?: Record<string, string>;\n}): ExternalHeadersRecord {\n const headers: ExternalHeadersRecord = { ...(input.requestHeaders ?? {}) };\n const getAuthToken = input.getAuthToken;\n if (getAuthToken) {\n // Resolved per request: a fresh token each time, never one captured at boot. An absent token\n // yields an empty value (unauthenticated) rather than the literal string `Bearer undefined`.\n headers[\"Authorization\"] = async () => {\n const token = await getAuthToken();\n return token ? `Bearer ${token}` : \"\";\n };\n }\n return headers;\n}\n\n/** Token-only convenience over {@link buildShapeHeaders}; retained for callers that pass a provider. */\nexport function buildAuthShapeHeaders(\n getAuthToken: () => Promise<string | undefined>,\n requestHeaders?: Record<string, string>,\n): ExternalHeadersRecord {\n return buildShapeHeaders({ getAuthToken, ...(requestHeaders ? { requestHeaders } : {}) });\n}\n\n/** HTTP statuses that mean \"the credential is the problem\" — re-auth, never give up (ADR-0013). */\nconst AUTH_ERROR_STATUSES = new Set([401, 403]);\n\n/** Read the duck-typed numeric `status` off an Electric `FetchError`, or `undefined` for a plain error. */\nfunction readErrorStatus(error: unknown): number | undefined {\n if (typeof error !== \"object\" || error === null || !(\"status\" in error)) {\n return undefined;\n }\n const status = (error as { status: unknown }).status;\n return typeof status === \"number\" ? status : undefined;\n}\n\n/**\n * True when the error is an auth failure (Electric's `FetchError` with a 401/403 `status`). We read\n * the documented `status` field rather than `instanceof FetchError`: the experimental and client\n * packages can resolve to *different* `@electric-sql/client` copies, so an `instanceof` against one\n * copy can miss a `FetchError` thrown from the other. A duck-typed numeric `status` is robust and\n * carries no false positives — a plain network/`Error` has no numeric `status`.\n */\nfunction isAuthError(error: unknown): boolean {\n const status = readErrorStatus(error);\n return status !== undefined && AUTH_ERROR_STATUSES.has(status);\n}\n\n/**\n * Whether a non-auth read-stream error is worth retrying (#4): a transient transport fault — a 5xx,\n * a 429 rate-limit, or a network error with no HTTP status. A genuine non-auth 4xx (400/404/409/…)\n * is structural: retrying re-fails, so we stop. (401/403 are handled separately as auth.)\n */\nfunction isRetryableStreamError(error: unknown): boolean {\n const status = readErrorStatus(error);\n if (status === undefined) {\n return true; // network/transport error — retry with Electric's backoff\n }\n return status >= 500 || status === 429;\n}\n\n/**\n * The per-shape `ShapeStreamOptions.onError` handler for the read path. It is the only place that can\n * request a retry (the `MultiShapeStream.subscribe` `onError` is notification-only), so it owns BOTH\n * read-path identity (ADR-0013) and read-stream error surfacing (#4):\n *\n * - **auth (401/403)** → `onAuthError` + return `{}` (retry): Electric re-issues the request,\n * re-resolving the async Authorization header ({@link buildAuthShapeHeaders}) for a *fresh* token.\n * Never return `void` here — that stops the stream permanently, wrong for offline-first: a dead\n * session must keep retrying (jittered backoff bounds the cost) so sync resumes the instant re-auth\n * makes the token valid again. The optional `onAuthError` surfaces a distinct \"re-login\" status.\n * - **any other error** → `onReadStreamError` (so the runtime can move to a `degraded` status instead\n * of silently believing the read path is live), then retry transient faults ({@link\n * isRetryableStreamError}: 5xx/429/network → `{}`) or stop a structural 4xx (return `undefined`). A\n * later successful fetch (`onSyncActivity`) clears the degraded status back to live.\n */\nexport function createShapeErrorHandler(\n options: { onAuthError?: () => void; onReadStreamError?: (error: Error) => void } = {},\n): ShapeStreamErrorHandler {\n return (error: Error) => {\n if (isAuthError(error)) {\n options.onAuthError?.();\n return {}; // retry → re-resolves the async Authorization header for a fresh token\n }\n options.onReadStreamError?.(error);\n return isRetryableStreamError(error) ? {} : undefined;\n };\n}\n",
133
- "import type { ExternalHeadersRecord } from \"@electric-sql/client\";\nimport type { PGliteInterface } from \"@electric-sql/pglite\";\n\nimport {\n type Retention,\n type SubscriptionTiming,\n type SyncConfigInput,\n type SyncTableRegistry,\n type TableSpecInput,\n} from \"@pgxsinkit/contracts\";\n\nimport type { SyncNamespaceObj } from \"./sync\";\nimport { createShapeErrorHandler } from \"./sync-auth\";\n\nexport interface ShapeSyncSpec {\n electricUrl: string;\n tableName: string;\n schema?: string;\n shapeKey: string;\n primaryKey: string[];\n electricTable?: string;\n /**\n * Consistency group (ADR-0009 decision 2). Specs sharing a group sync on one `MultiShapeStream`\n * and commit atomically. Absent → the table is its own singleton group keyed by its `shapeKey`.\n */\n consistencyGroup?: string;\n /**\n * Subscription timing (ADR-0021). Absent → `eager`. A `lazy` spec's group is held out of the eager\n * boot set and started on demand via {@link StartConfiguredSyncResult.ensureGroupStarted}. A group's\n * members all agree (registry-validated), so the group's timing is any member's.\n */\n subscription?: SubscriptionTiming;\n /**\n * Retention (ADR-0021). Absent → `persistent`. Only a `persistent` `lazy` group is promoted to the\n * eager set on activation (its activation is permanent across boots); an `ephemeral` group's activation\n * is session-scoped by construction, so it is never promoted/persisted.\n */\n retention?: Retention;\n}\n\nexport interface ConfiguredShapeSyncSpec extends ShapeSyncSpec {\n key: string;\n}\n\nexport interface StartConfiguredSyncOptions {\n syncConfig: SyncConfigInput;\n /**\n * The sync registry (ADR-0029 D1): the engine's sole per-table spec source. Each shape's `tableKey`\n * (its `syncConfig` table key) resolves against it for the local table, PKs, apply strategy, and\n * column types — no table-scoped fact is threaded from `syncConfig` into the engine.\n */\n registry: SyncTableRegistry;\n /**\n * Shape request headers shared by every member shape. Values may be async functions resolved per\n * request (ADR-0013) — the read-path `Authorization` token is one such function.\n */\n shapeHeaders?: ExternalHeadersRecord;\n onInitialSync?: () => void;\n onTableInitialSync?: (tableKey: string) => void;\n /**\n * Fresh-store prefetch overlap (ADR-0032 S4). When present, every EAGER group starts its shape streams\n * and buffers their catch-up into the memory inbox immediately, gating all commits until this promise\n * resolves — so the network catch-up overlaps the local boot phases (schema/journal/reconcile) instead\n * of running after them. Set ONLY by `createSyncClient` on a provably-fresh store (its `freshStore`\n * hint); absent → the sequential path. Passed straight through to the engine's `syncShapesToTables`.\n */\n dbReady?: Promise<void>;\n /** Commit-level error surfacing (ADR-0009 decision 5): a sync commit exhausted its retries. */\n onSyncError?: (error: Error) => void;\n /**\n * Notified when a shape hits an auth error (401/403) and the read path is retrying for a fresh\n * token (ADR-0013 Phase 3). The runtime surfaces a distinct `auth-needed` status from this.\n */\n onAuthError?: () => void;\n /**\n * Notified when a shape hits a NON-auth stream error (#4): a transient 5xx/429/network (retried) or\n * a structural 4xx (stops the stream). The runtime surfaces a `degraded` status from this so it\n * never silently believes the read path is live while it has actually stalled.\n */\n onReadStreamError?: (error: Error) => void;\n /**\n * Notified when a shape successfully delivers a batch — i.e. a fetch just succeeded (ADR-0013\n * Phase 3). The runtime uses this to clear an `auth-needed`/`degraded` status once sync resumes.\n */\n onSyncActivity?: () => void;\n /**\n * Consistency-group keys of `lazy` groups that were activated on a previous boot and persisted their\n * activation flag (ADR-0021 §2 — `lazy + persistent` promotion). These join the eager boot set as if\n * they were declared `eager`, so a once-activated durable lazy group resumes without re-evaluation.\n * Computed by the caller from the local meta table (the sync engine does no DB read of its own).\n */\n promotedGroups?: ReadonlySet<string>;\n /**\n * Invoked when a `persistent` `lazy` group is activated on demand (not promoted at boot), so the\n * caller can persist its activation flag for the next boot (ADR-0021 §2). Never fired for an\n * `ephemeral` group (its activation is session-scoped and leaves no durable trace).\n */\n onLazyActivated?: (groupKey: string) => void;\n /**\n * Invoked exactly once per consistency group the moment it becomes up-to-date (ADR-0032 decision 6 —\n * per-group readiness). Fires for eager, promoted, and on-demand `lazy` groups alike, so a client can\n * surface progressive per-group paint (and the worker bridge can fan a `groupReady` event to tabs)\n * without the all-eager-groups `onInitialSync` gate. The matching promise is {@link StartConfiguredSyncResult.groupReady}.\n */\n onGroupReady?: (groupKey: string) => void;\n}\n\n// The engine is reached through the `electric` namespace the client attaches post-create (ADR-0032 S1) —\n// a plain property carrying the sync entry points, no longer a create-time PGlite extension.\ntype SyncEnginePGlite = PGliteInterface & { electric: SyncNamespaceObj };\n\nexport interface ShapeSyncResult {\n unsubscribe: () => void;\n readonly isUpToDate: boolean;\n}\n\nexport interface StartConfiguredSyncResult {\n unsubscribe: () => void;\n tables: Record<string, ShapeSyncResult>;\n /**\n * Start a `lazy` consistency group (ADR-0021) held out of the eager boot set. Idempotent and\n * single-flight: concurrent calls share one start; a started, unknown, or eager group resolves\n * immediately. Resolves once the group's initial sync completes — the seam the live-query layer\n * calls on first reference to a lazy table. After it resolves, the group's member `tables` entries\n * report `isUpToDate` live.\n */\n ensureGroupStarted: (groupKey: string) => Promise<void>;\n /**\n * Stop a group's stream and return it to dormant (ADR-0021 §2): tear down its live subscription and\n * clear the runtime so {@link isTableStarted} reports false again and a later {@link ensureGroupStarted}\n * re-subscribes from scratch — the inverse of an on-demand activation. Used by the client's `desync`\n * to halt a lazy group before truncating its read cache. A no-op for an unknown or never-started group.\n * The temp cluster of an `ephemeral` group is NOT dropped here (that is the deferred idle-eviction); the\n * cluster simply stops being fed.\n */\n stopGroup: (groupKey: string) => void;\n /** The consistency-group key a table belongs to — maps a queried table to its {@link ensureGroupStarted}. */\n groupKeyForTable: (tableKey: string) => string | undefined;\n /**\n * Whether a table's consistency group has started and completed its initial sync, so its reads are\n * hydrated (ADR-0021). False for a `lazy` group still held out of the boot set. Drives the read-path\n * tripwire — a lazy relation read while this is false would return empty/stale rows.\n */\n isTableStarted: (tableKey: string) => boolean;\n /**\n * A promise that resolves the moment the given consistency group is up-to-date (ADR-0032 decision 6).\n * Resolves immediately for an already-ready group; stays pending for a `lazy` group until it is\n * activated (via {@link ensureGroupStarted}) and catches up. An unknown group resolves immediately\n * (nothing to await). Per-group readiness the client re-exposes as `client.groupReady(table)`.\n */\n groupReady: (groupKey: string) => Promise<void>;\n /** Whether the given consistency group has completed its initial sync (synchronous peek at {@link groupReady}). */\n isGroupReady: (groupKey: string) => boolean;\n /** Every consistency-group key this config declares — the domain of {@link groupReady}/{@link isGroupReady}. */\n groupKeys: () => string[];\n}\n\nexport function buildShapeUrl(electricUrl: string, table: string) {\n const url = new URL(electricUrl);\n url.searchParams.set(\"table\", table);\n return url.toString();\n}\n\nexport function buildShapeConfig(input: ShapeSyncSpec) {\n return {\n shape: {\n // The ingress `table` param carries the unique `shapeKey` — the proxy resolves the shape by it and\n // maps it to the physical Electric table on egress (so a read projection and its owner, which share\n // a physical table, stay distinguishable). `table` below is the LOCAL PGlite apply target.\n url: buildShapeUrl(input.electricUrl, input.shapeKey),\n },\n table: input.tableName,\n ...(input.schema !== undefined ? { schema: input.schema } : {}),\n primaryKey: [...input.primaryKey],\n shapeKey: input.shapeKey,\n };\n}\n\nexport function buildConfiguredShapeSpecs(input: SyncConfigInput): ConfiguredShapeSyncSpec[] {\n return Object.entries(input.tables)\n .filter(([, table]) => table.mode !== \"writeonly\")\n .map(([key, table]) => buildConfiguredShapeSpec(input.electricUrl, input.localSchema, key, table));\n}\n\n/**\n * One consistency group's runtime: its specs, the subscription timing its members agree on, and its\n * live stream once started (`null` while a `lazy` group is still held). `startPromise` makes start\n * single-flight so concurrent on-demand triggers share one subscription.\n */\ninterface GroupRuntime {\n groupKey: string;\n specs: ConfiguredShapeSyncSpec[];\n subscription: SubscriptionTiming;\n retention: Retention;\n result: ShapeSyncResult | null;\n startPromise: Promise<void> | null;\n}\n\nexport async function startConfiguredSync(\n pg: SyncEnginePGlite,\n input: StartConfiguredSyncOptions,\n): Promise<StartConfiguredSyncResult> {\n const specs = buildConfiguredShapeSpecs(input.syncConfig);\n\n // Bucket specs into consistency groups (ADR-0009 decision 2). Each group is one MultiShapeStream\n // committed atomically; an ungrouped table is its own singleton group keyed by its shapeKey. A group\n // carries the subscription timing its members agree on (ADR-0021; registry validation guarantees\n // agreement, so the first member's value is the group's): `eager` groups start at boot, `lazy` groups\n // are held until ensureGroupStarted (the on-demand / live-query interception seam).\n const groups = new Map<string, GroupRuntime>();\n const groupKeyByTable = new Map<string, string>();\n for (const spec of specs) {\n const groupKey = groupSubscriptionKey(spec);\n groupKeyByTable.set(spec.key, groupKey);\n const existing = groups.get(groupKey);\n if (existing) {\n existing.specs.push(spec);\n } else {\n groups.set(groupKey, {\n groupKey,\n specs: [spec],\n subscription: spec.subscription ?? \"eager\",\n retention: spec.retention ?? \"persistent\",\n result: null,\n startPromise: null,\n });\n }\n }\n\n // Per-group readiness (ADR-0032 decision 6): one deferred per group, created up front so a caller can\n // await ANY group — eager or still-dormant lazy — before it has started. Resolved once (idempotent) the\n // moment the group reports up-to-date; a never-activated lazy group's promise simply stays pending.\n interface GroupReadyDeferred {\n promise: Promise<void>;\n resolve: () => void;\n ready: boolean;\n }\n const groupReadyState = new Map<string, GroupReadyDeferred>();\n for (const groupKey of groups.keys()) {\n let resolve!: () => void;\n const promise = new Promise<void>((r) => {\n resolve = r;\n });\n groupReadyState.set(groupKey, { promise, resolve, ready: false });\n }\n const markGroupReady = (groupKey: string) => {\n const state = groupReadyState.get(groupKey);\n if (!state || state.ready) return;\n state.ready = true;\n state.resolve();\n input.onGroupReady?.(groupKey);\n };\n\n // A `lazy` group activated on a previous boot (ADR-0021 §2 `lazy + persistent` promotion) is treated\n // as eager this boot: its activation is permanent, so it joins the boot set and resumes like any durable\n // table — no per-session re-evaluation, no half-lazy.\n const promotedGroups = input.promotedGroups ?? new Set<string>();\n const isEagerAtBoot = (group: GroupRuntime) => group.subscription !== \"lazy\" || promotedGroups.has(group.groupKey);\n\n // Boot readiness (`onInitialSync`) waits only for the boot (eager + promoted) groups to catch up; a lazy\n // group started later via ensureGroupStarted signals its members' `onTableInitialSync` but never the gate.\n const eagerGroups = [...groups.values()].filter(isEagerAtBoot);\n let pendingBootGroups = eagerGroups.length;\n let bootSignalled = false;\n const signalBootIfReady = () => {\n if (!bootSignalled && pendingBootGroups <= 0) {\n bootSignalled = true;\n input.onInitialSync?.();\n }\n };\n\n // Start one group's stream, single-flight: a started group resolves immediately; an in-flight start\n // is shared. `countsTowardBoot` is true only for the eager boot starts.\n const startGroup = (group: GroupRuntime, countsTowardBoot: boolean): Promise<void> => {\n if (group.result) {\n return Promise.resolve();\n }\n if (group.startPromise) {\n return group.startPromise;\n }\n group.startPromise = startGroupSync(pg, {\n groupKey: group.groupKey,\n specs: group.specs,\n registry: input.registry,\n // The prefetch overlap (ADR-0032 S4) applies ONLY to the eager BOOT starts: a fresh store's eager\n // groups are genuinely new, so buffering their catch-up behind the commit gate is safe. An on-demand\n // `lazy` start happens post-boot on an already-provisioned store (which may even be RESUMING persisted\n // subscription state), so it must take the exact sequential path — never the fresh-store overlap.\n ...(countsTowardBoot && input.dbReady ? { dbReady: input.dbReady } : {}),\n ...(input.shapeHeaders ? { headers: input.shapeHeaders } : {}),\n ...(input.onSyncError ? { onSyncError: input.onSyncError } : {}),\n ...(input.onAuthError ? { onAuthError: input.onAuthError } : {}),\n ...(input.onReadStreamError ? { onReadStreamError: input.onReadStreamError } : {}),\n ...(input.onSyncActivity ? { onSyncActivity: input.onSyncActivity } : {}),\n onGroupInitialSync: () => {\n // The group is up-to-date as a unit; signal each member table, mark the group ready (per-group\n // readiness, ADR-0032 decision 6), then (for an eager group only) advance the boot gate once\n // every eager group is caught up.\n for (const spec of group.specs) {\n input.onTableInitialSync?.(spec.key);\n }\n markGroupReady(group.groupKey);\n if (countsTowardBoot) {\n pendingBootGroups -= 1;\n signalBootIfReady();\n }\n },\n }).then((result) => {\n group.result = result;\n // A `persistent` `lazy` group activated on demand (not a boot start) persists its activation, so the\n // next boot promotes it to eager (ADR-0021 §2). `ephemeral` activation is session-scoped — never persisted.\n if (!countsTowardBoot && group.subscription === \"lazy\" && group.retention === \"persistent\") {\n input.onLazyActivated?.(group.groupKey);\n }\n });\n return group.startPromise;\n };\n\n // Each member table exposes a per-table view backed by its group's runtime: up-to-date exactly when\n // the group is (false until a lazy group is started), and unsubscribing it tears down the group.\n const tables: Record<string, ShapeSyncResult> = {};\n for (const [tableKey, groupKey] of groupKeyByTable) {\n const group = groups.get(groupKey)!;\n tables[tableKey] = {\n unsubscribe: () => group.result?.unsubscribe(),\n get isUpToDate() {\n return group.result?.isUpToDate ?? false;\n },\n };\n }\n\n // Start the eager groups at boot; lazy groups wait for ensureGroupStarted. `signalBootIfReady` after\n // the await covers a config with no eager groups (boot is trivially complete).\n await Promise.all(eagerGroups.map((group) => startGroup(group, true)));\n signalBootIfReady();\n\n return {\n unsubscribe: () => {\n // Unsubscribe per group (not per table) so a multi-table group's stream is torn down once.\n for (const group of groups.values()) {\n group.result?.unsubscribe();\n }\n },\n tables,\n ensureGroupStarted: (groupKey) => {\n const group = groups.get(groupKey);\n return group ? startGroup(group, false) : Promise.resolve();\n },\n stopGroup: (groupKey) => {\n const group = groups.get(groupKey);\n if (!group) return;\n // Tear down the live stream and clear the runtime so the group is dormant again: `isTableStarted`\n // reports false and `ensureGroupStarted` re-runs `startGroupSync` (its `group.result`/`startPromise`\n // short-circuits no longer apply) on the next reference.\n group.result?.unsubscribe();\n group.result = null;\n group.startPromise = null;\n // Return the group's readiness to pending: a stopped group is dormant again, so `groupReady` for a\n // later re-activation must re-await its fresh catch-up rather than resolve on the stale deferred.\n if (groupReadyState.get(groupKey)?.ready) {\n let resolve!: () => void;\n const promise = new Promise<void>((r) => {\n resolve = r;\n });\n groupReadyState.set(groupKey, { promise, resolve, ready: false });\n }\n },\n groupKeyForTable: (tableKey) => groupKeyByTable.get(tableKey),\n isTableStarted: (tableKey) => {\n const groupKey = groupKeyByTable.get(tableKey);\n if (groupKey == null) return false;\n return groups.get(groupKey)?.result != null;\n },\n // An unknown group key has nothing to await, so its readiness resolves immediately (never blocks).\n groupReady: (groupKey) => groupReadyState.get(groupKey)?.promise ?? Promise.resolve(),\n isGroupReady: (groupKey) => groupReadyState.get(groupKey)?.ready ?? true,\n groupKeys: () => [...groups.keys()],\n };\n}\n\ninterface StartGroupSyncOptions {\n groupKey: string;\n specs: ConfiguredShapeSyncSpec[];\n registry: SyncTableRegistry;\n headers?: ExternalHeadersRecord;\n /** Fresh-store prefetch overlap gate (ADR-0032 S4) — forwarded to the engine's `syncShapesToTables`. */\n dbReady?: Promise<void>;\n onGroupInitialSync?: () => void;\n onSyncError?: (error: Error) => void;\n onAuthError?: () => void;\n onReadStreamError?: (error: Error) => void;\n onSyncActivity?: () => void;\n}\n\n/**\n * Sync one consistency group on a single `MultiShapeStream` (ADR-0009 decision 2). All member\n * shapes share the group's subscription key and commit atomically at a shared LSN frontier; each\n * shape keeps its own apply strategy and column types (resolved per-shape inside the engine).\n */\nexport async function startGroupSync(pg: SyncEnginePGlite, input: StartGroupSyncOptions) {\n const shapeHeaders = input.headers && Object.keys(input.headers).length > 0 ? input.headers : undefined;\n\n // The per-shape onError owns read-path auth recovery (ADR-0013 Phase 2: a 401/403 retries with a\n // fresh token) AND read-stream error surfacing (#4: a non-auth error moves the runtime to\n // `degraded`, retrying transient 5xx/429/network and stopping a structural 4xx).\n const onError = createShapeErrorHandler({\n ...(input.onAuthError ? { onAuthError: input.onAuthError } : {}),\n ...(input.onReadStreamError ? { onReadStreamError: input.onReadStreamError } : {}),\n });\n\n const shapes = Object.fromEntries(\n input.specs.map((spec) => [\n spec.key,\n {\n shape: {\n // Ingress `table` = the unique `shapeKey` (proxy maps it to the physical table on egress).\n url: buildShapeUrl(spec.electricUrl, spec.shapeKey),\n ...(shapeHeaders ? { headers: shapeHeaders } : {}),\n onError,\n },\n // ADR-0029 D1: the registry table key is the engine's sole per-table spec — the local apply\n // target, PKs, strategy, and column types all derive from `(registry, tableKey)`. The\n // `syncConfig` table key IS the registry key, so the spec's `key` is the `tableKey`.\n tableKey: spec.key,\n },\n ]),\n );\n\n return getElectricNamespace(pg).syncShapesToTables({\n key: input.groupKey,\n registry: input.registry,\n shapes,\n ...(input.dbReady ? { dbReady: input.dbReady } : {}),\n ...(input.onGroupInitialSync ? { onInitialSync: input.onGroupInitialSync } : {}),\n ...(input.onSyncError ? { onSyncError: input.onSyncError } : {}),\n ...(input.onSyncActivity ? { onSyncActivity: input.onSyncActivity } : {}),\n });\n}\n\nfunction getElectricNamespace(pg: SyncEnginePGlite) {\n return pg.electric;\n}\n\nfunction buildConfiguredShapeSpec(\n electricUrl: string,\n localSchema: string | undefined,\n key: string,\n table: TableSpecInput,\n): ConfiguredShapeSyncSpec {\n if (table.shape === undefined) {\n throw new Error(`shape is required for synced table ${key}`);\n }\n\n return {\n key,\n electricUrl,\n tableName: table.clientProjection?.syncedTable ?? table.shape.tableName,\n // ADR-0021 §3: an ephemeral table's cluster is `TEMP` (bare names in `pg_temp`), so the row-applier\n // must target the unqualified name (resolved via search_path) — omit the schema for it.\n ...(localSchema && table.retention !== \"ephemeral\" ? { schema: localSchema } : {}),\n shapeKey: table.shape.shapeKey,\n primaryKey: [...(table.clientProjection?.localPrimaryKey?.columns ?? table.primaryKey.columns)],\n electricTable: table.shape.electricTable ?? table.shape.tableName,\n ...(table.consistencyGroup ? { consistencyGroup: table.consistencyGroup } : {}),\n ...(table.subscription ? { subscription: table.subscription } : {}),\n ...(table.retention ? { retention: table.retention } : {}),\n };\n}\n\n/**\n * The subscription key for a spec's consistency group (ADR-0009 decision 2): the explicit\n * `consistencyGroup` when set, else the table's own `shapeKey` (a singleton group). One persisted\n * subscription-state row exists per group key, so subscription reset enumerates these.\n */\nexport function groupSubscriptionKey(spec: Pick<ConfiguredShapeSyncSpec, \"consistencyGroup\" | \"shapeKey\">): string {\n return spec.consistencyGroup ?? spec.shapeKey;\n}\n",
134
- "// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\nimport type { EventMessage, MovePattern, Row } from \"@electric-sql/client\";\nimport { isChangeMessage, isControlMessage } from \"@electric-sql/client\";\nimport type { ChangeMessage, ShapeStreamOptions } from \"@electric-sql/client\";\nimport { MultiShapeStream } from \"@electric-sql/experimental\";\nimport type { PGliteInterface } from \"@electric-sql/pglite\";\nimport { sql } from \"drizzle-orm\";\nimport { getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport { type ApplyStrategy, classifyTableApplyStrategy } from \"@pgxsinkit/contracts\";\n\nimport { instrumentShapeFetch, syncDebug } from \"../debug\";\nimport { type ApplyTarget, resolveApplyTarget } from \"../local-tables\";\nimport { computeRetryDelayMs } from \"../mutation\";\nimport {\n applyBulkDeletesToTable,\n applyBulkUpdatesToTable,\n applyInsertsToTable,\n applyMessagesToTableWithCopy,\n applyMessagesToTableWithJson,\n applyUpsertsToTable,\n} from \"./apply\";\nimport { drizzleOverPg } from \"./drizzle-executor\";\nimport {\n NUDGE_HOLD_GRACE_MS,\n NUDGE_MAX_ROUNDS,\n NUDGE_ROUND_GRACE_MS,\n NUDGE_ROUND_WAIT_MS,\n withNudgeBuster,\n} from \"./nudge\";\nimport { foldChangeBatch, ShapeInbox } from \"./shape-inbox\";\nimport {\n deleteSubscriptionState,\n getSubscriptionState,\n migrateSubscriptionMetadataTables,\n type SubscriptionState,\n updateSubscriptionState,\n} from \"./subscription-state\";\nimport {\n addShapeRowTags,\n applyShapeMoveOut,\n applyShapeTagSync,\n assertValidMetadataSchema,\n clearShapeTags,\n DEFAULT_METADATA_SCHEMA,\n shapeTableId,\n} from \"./tags\";\nimport {\n DEFAULT_MAX_COMMIT_RETRIES,\n type ElectricSyncOptions,\n type InitialInsertMethod,\n type InsertChangeMessage,\n type Lsn,\n type SyncShapesToTablesOptions,\n type SyncShapesToTablesResult,\n type SyncShapeToTableOptions,\n type SyncShapeToTableResult,\n} from \"./types\";\n\nexport * from \"./types\";\n\n/**\n * Replication-stream headers Electric attaches to change messages but does not\n * declare on its `Header` type: `lsn` orders changes within the stream and\n * `last` marks the final change of an LSN. Single choke point for these\n * protocol assumptions.\n */\n/**\n * Maps the statically-resolved {@link ApplyStrategy} (ADR-0009 decision 3) onto the engine's\n * initial-backfill apply path. Undefined (no registry-supplied strategy) defaults to `copy`:\n * the COPY TEXT serializer round-trips every built-in type, so it is the safe no-brainer bootstrap.\n */\nfunction applyStrategyToInsertMethod(strategy: ApplyStrategy | undefined): InitialInsertMethod {\n switch (strategy) {\n case \"json\":\n return \"json\";\n case \"insert\":\n return \"insert\";\n default:\n return \"copy\";\n }\n}\n\nfunction readReplicationHeaders(headers: ChangeMessage[\"headers\"]): { lsn: bigint; isLastOfLsn: boolean } {\n const rawLsn: unknown = headers[\"lsn\"];\n\n return {\n lsn: typeof rawLsn === \"string\" ? BigInt(rawLsn) : BigInt(0),\n isLastOfLsn: headers[\"last\"] === true,\n };\n}\n\n/**\n * Electric's tagged-subquery `EventMessage` (ADR-0023) — `headers.event` is `move-out` | `move-in`,\n * carrying `patterns`. It is neither a change nor a control message, so `@electric-sql/client` exposes\n * no guard; we detect it by the `event` header. `MultiShapeStream` adds `.shape` like every message.\n */\ntype ShapeEventMessage = EventMessage & { shape: string };\n\nfunction isEventMessage(message: unknown): message is ShapeEventMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n typeof (message as { headers?: { event?: unknown } }).headers?.event === \"string\"\n );\n}\n\n/**\n * Construct the pgxsinkit sync engine over an ALREADY-created PGlite instance (ADR-0032 S1). The engine\n * is a plain module — not a create-time PGlite extension — so it demands only the minimal surface it\n * actually uses: a {@link PGliteInterface} (it runs its metadata DDL + apply commits through `pg.transaction`\n * / `pg.query` / `pg.exec`; it does NOT touch the `live` extension). It returns the `namespace` object (the\n * local-bookkeeping + shape-sync entry points the client attaches as `pg.electric`) plus an explicit\n * `close()` — the teardown the former extension's `close` hook ran when PGlite closed, now invoked\n * explicitly by the owner at the same moment (see `createSyncClient`'s `stop`/`destroy`).\n */\nexport async function createSyncEngine(pg: PGliteInterface, options?: ElectricSyncOptions) {\n const debug = options?.debug ?? false;\n // pgxsinkit-owned metadata namespace (ADR-0009 decision 6): this is our local bookkeeping (the\n // subscription-state table) and the sync-origin GUC (`<schema>.syncing`), not Electric's — so it\n // lives under our own schema, renamed from the upstream `electric` default.\n const metadataSchema = options?.metadataSchema ?? DEFAULT_METADATA_SCHEMA;\n // The schema name reaches raw GUC + DDL identifier positions below (no quoted-identifier form exists\n // there), so validate it at construction rather than trust caller input in those raw spots.\n assertValidMetadataSchema(metadataSchema);\n const streams: Array<{\n stream: MultiShapeStream<Record<string, Row<unknown>>>;\n aborter: AbortController;\n }> = [];\n\n const getShapeOptions = (shapes: SyncShapesToTablesOptions[\"shapes\"], shapeName: string) => {\n const shape = shapes[shapeName];\n if (!shape) {\n throw new Error(`Missing shape options for ${shapeName}`);\n }\n return shape;\n };\n\n const shapePerTableLock = new Map<string, void>();\n\n // Memoize the metadata DDL as a PROMISE, not a boolean: concurrent eager groups (`shape-sync.ts`\n // starts them with `Promise.all`) both call `initMetadataTables`, and a boolean set BEFORE the async\n // migration completed let the second caller return early and query the metadata tables before the DDL\n // had run. Storing the in-flight promise makes every concurrent caller await the same single migration.\n // Cleared on rejection so a transient DDL failure can be retried by a later start rather than caching a\n // rejected promise forever.\n let initMetadataTablesPromise: Promise<void> | undefined;\n const initMetadataTables = (): Promise<void> => {\n if (!initMetadataTablesPromise) {\n initMetadataTablesPromise = migrateSubscriptionMetadataTables({\n pg,\n metadataSchema,\n }).catch((error: unknown) => {\n initMetadataTablesPromise = undefined;\n throw error;\n });\n }\n return initMetadataTablesPromise;\n };\n\n const syncShapesToTables = async ({\n key,\n registry,\n shapes,\n initialInsertMethod,\n onInitialSync,\n onError,\n onSyncError,\n onSyncActivity,\n dbReady,\n maxCommitRetries = DEFAULT_MAX_COMMIT_RETRIES,\n commitRetryDelayMs = computeRetryDelayMs,\n }: SyncShapesToTablesOptions): Promise<SyncShapesToTablesResult> => {\n let unsubscribed = false;\n // Fresh-store prefetch overlap (ADR-0032 S4): the caller proved the store fresh and handed a `dbReady`\n // gate, so start the streams and buffer their catch-up into the memory inbox NOW — before the local\n // store's schema/journal/reconcile finish — and defer every DB touch (metadata DDL, the first commit)\n // until the gate lifts. Without it, the exact sequential path: init the metadata tables up front.\n const overlap = dbReady != null;\n if (!overlap) {\n await initMetadataTables();\n }\n\n // Resolve each shape's apply target ONCE at subscribe time (ADR-0029 D1/D2): the real projected\n // synced table, its columns, PKs, and model-derived types — the engine's per-message work is then a\n // pure builder over these resolved objects, never a per-message re-derivation or catalog probe.\n const targets = new Map<string, ApplyTarget>(\n Object.entries(shapes).map(([shapeName, shapeOptions]) => [\n shapeName,\n resolveApplyTarget(registry, shapeOptions.tableKey),\n ]),\n );\n const getTarget = (shapeName: string): ApplyTarget => {\n const target = targets.get(shapeName);\n if (!target) {\n throw new Error(`Missing apply target for ${shapeName}`);\n }\n return target;\n };\n // The synced table's physical identity — the per-table lock key and the tag-store `shape_table` key.\n const tableIdentity = (target: ApplyTarget) => {\n const { name, schema } = getTableConfig(target.table);\n return shapeTableId(schema, name);\n };\n\n Object.entries(shapes)\n .filter(([, shape]) => !shape.onMustRefetch)\n .forEach(([, shape]) => {\n if (shapePerTableLock.has(shape.tableKey)) {\n throw new Error(\"Already syncing shape for table \" + shape.tableKey);\n }\n shapePerTableLock.set(shape.tableKey);\n });\n\n let subState: SubscriptionState | null = null;\n\n // On the overlap path the store is provably fresh (the `freshStore` gate), so it carries no persisted\n // subscription state — AND its metadata tables do not exist yet (their DDL is deferred to the gate).\n // Skip the read entirely: `subState` stays null, so the group is (correctly) a new subscription.\n if (key !== null && !overlap) {\n subState = await getSubscriptionState({\n pg,\n metadataSchema,\n subscriptionKey: key,\n });\n if (debug && subState) {\n console.log(\"resuming from subscription state\", subState);\n }\n }\n\n const isNewSubscription = subState === null;\n\n // Each shape resolves its own apply method (ADR-0009 decisions 2 + 3 / ADR-0029 D1): an explicit\n // per-shape `initialInsertMethod` override wins, else the group-level default, else the registry's\n // build-time classification of the entry. So a consistency group with mixed column profiles applies\n // each table on its correct path.\n const shapeInsertMethod = new Map<string, InitialInsertMethod>(\n Object.entries(shapes).map(([shapeName, shapeOptions]) => {\n // Strategy precedence (ADR-0009 decisions 2+3 / ADR-0029 D1): an explicit per-shape override,\n // then the group-level default, then the registry's build-time classification of the entry.\n const entry = registry[shapeOptions.tableKey]!;\n const method =\n shapeOptions.initialInsertMethod ??\n initialInsertMethod ??\n applyStrategyToInsertMethod(classifyTableApplyStrategy(entry));\n return [shapeName, method];\n }),\n );\n\n // `useInsert` is per-shape, not shared: in a multi-shape group, one shape finishing its bulk\n // backfill must not flip every other shape onto plain `INSERT`. A shape uses its bulk path only\n // on a fresh subscription with a non-`insert` method; a resume starts already in insert mode.\n const useInsert = new Map<string, boolean>(\n Object.keys(shapes).map((shapeName) => [\n shapeName,\n !isNewSubscription || shapeInsertMethod.get(shapeName) === \"insert\",\n ]),\n );\n let onInitialSyncCalled = false;\n\n const maybeSignalInitialSync = () => {\n if (onInitialSync && !onInitialSyncCalled && multiShapeStream.isUpToDate) {\n onInitialSync();\n onInitialSyncCalled = true;\n }\n };\n\n // The Shape inbox (ADR-0014 / ISS-06): the pure, in-memory buffer + complete-LSN frontier for\n // this group's shapes. The engine keeps the commit queue, the apply, and the truncate set.\n const inbox = new ShapeInbox(Object.keys(shapes));\n\n // Live-tail sibling nudge (ADR-0031): a per-shape one-shot cache-buster token. The watchdog (below)\n // sets a token just before nudging a lagging sibling; `withNudgeBuster` (wrapping each shape's\n // fetchClient) consumes it on the sibling's next non-live catch-up so a CDN HIT cannot return the same\n // stale watermark and defeat the nudge. Empty on the steady path → the wrapper is a straight passthrough.\n const nudgeBusters = new Map<string, string>();\n\n const truncateNeeded = new Set<string>();\n // The committed frontier is a *running* variable, advanced after each successful commit — not\n // the boot-time `const` the upstream engine never advanced (which forced redundant empty\n // re-commits). `degraded` latches once commits exhaust their retries (ADR-0009 decision 5).\n let committedLsn: Lsn = subState?.last_lsn ?? BigInt(-1);\n let degraded = false;\n // Single-flight commit queue: at most one commit runs at a time; messages buffered while one\n // is in flight coalesce into the next run (re-armed via `commitRerun`).\n let commitInFlight: Promise<void> | null = null;\n let commitRerun = false;\n\n const aborter = new AbortController();\n Object.values(shapes)\n .filter((shapeOptions) => !!shapeOptions.shape.signal)\n .forEach((shapeOptions) => {\n shapeOptions.shape.signal!.addEventListener(\"abort\", () => aborter.abort(), {\n once: true,\n });\n });\n\n const multiShapeOptions: Record<string, ShapeStreamOptions<Row<unknown>>> = {};\n for (const [shapeName, shapeOptions] of Object.entries(shapes)) {\n const shapeMetadata = subState?.shape_metadata[shapeName];\n const streamOptions: ShapeStreamOptions<Row<unknown>> = {\n ...shapeOptions.shape,\n signal: aborter.signal,\n // Instrument every ShapeStream HTTP request (the read-path long-poll/catch-up) when debug is on;\n // a passthrough otherwise (see instrumentShapeFetch). Wraps any existing fetchClient rather than\n // replacing it, so auth/header injection on the shape's own fetchClient still runs. `withNudgeBuster`\n // is the OUTER wrapper (ADR-0031 live-tail nudge): it stamps the cache-buster onto the URL BEFORE\n // instrumentation runs, so the debug rail logs the busted URL (`BUSTED`) that actually hits the wire.\n fetchClient: withNudgeBuster(instrumentShapeFetch(shapeOptions.shape.fetchClient), nudgeBusters, shapeName),\n };\n\n if (shapeMetadata) {\n streamOptions.offset = shapeMetadata.offset;\n streamOptions.handle = shapeMetadata.handle;\n }\n\n multiShapeOptions[shapeName] = streamOptions;\n }\n\n const multiShapeStream = new MultiShapeStream<Record<string, Row<unknown>>>({\n shapes: multiShapeOptions,\n });\n\n // The commit gate (ADR-0032 S4). Open immediately on the sequential path; held closed on the overlap\n // path until `dbReady` resolves, so NOTHING writes to PGlite before the local schema exists. The inbox\n // is pure memory, so buffering catch-up behind this closed gate is safe — the only DB-bound work\n // (metadata DDL, then commits) waits for the gate.\n let dbGateOpen = !overlap;\n if (overlap) {\n // The streams' network side is starting now (subscribe below triggers the first fetch), overlapping\n // the caller's local boot phases. Name the shapes so the overlap is measurable on the boot rail.\n syncDebug(\"boot shape prefetch start\", { shapes: Object.keys(shapes) });\n }\n\n const getShapeStream = (shapeName: string) => {\n const stream = multiShapeStream.shapes[shapeName];\n if (!stream) {\n throw new Error(`Missing stream for ${shapeName}`);\n }\n return stream;\n };\n\n const insertMethods = {\n json: applyMessagesToTableWithJson,\n copy: applyMessagesToTableWithCopy,\n insert: applyInsertsToTable,\n } as const;\n\n // Apply everything buffered up to `targetLsn` in a single transaction, retrying with jittered\n // backoff on failure. Returns `true` once applied (and advances the running committed frontier);\n // returns `false` without advancing if the engine unsubscribed mid-flight or the commit\n // exhausted its retries (→ `degraded` + `onSyncError`, ADR-0009 decision 5). The drained\n // messages and the truncate snapshot are held across retries so a transient failure loses\n // nothing; the read cache never advances past an unapplied commit.\n const commitUpToLsn = async (targetLsn: Lsn): Promise<boolean> => {\n // PEEK (not drain) the buffered batch: it stays in the inbox until the transaction below actually\n // succeeds, and is only then ACKed (removed). A commit that exhausts its retries (→ `degraded`)\n // therefore HOLDS the drained batch in the buffer instead of losing it (ADR-0009 decision 5) — and\n // `enqueueCommit` refuses to run any newer commit while degraded, so a later LSN can never apply\n // over this held, unapplied batch. Recovery is a restart/refetch: the persisted offset was not\n // advanced, so the held batch re-streams from the same frontier.\n const messagesToCommit = inbox.peekUpTo(targetLsn);\n\n // Record every shape's reset epoch AT PEEK TIME (synchronously with the peeks, before the async\n // transaction). If a must-refetch + re-snapshot bumps a shape's epoch mid-commit, the acks below\n // skip that shape so its post-reset rebuild survives rather than being deleted/spliced away — see\n // ShapeInbox.ackUpTo / ackMoveOuts / ackMoveIns.\n const epochsAtPeek = inbox.snapshotEpochs();\n\n // Capture, per shape, whether it is still accepting snapshot (LSN-0) rows AT PEEK TIME. A shape in\n // snapshot acceptance (post-reset re-snapshot, or a brand-new shape before its first real lsn) can\n // have the SAME snapshot rows double-delivered by the racing recovery fetch loops — possibly across\n // separate commits — so its inserts are applied idempotently (upsert) rather than as plain\n // collision-surfacing inserts. Once a real lsn re-arms the dedup, this is false and the live-tail\n // plain-INSERT invariant (a genuine PK collision must surface, ADR-0014) is back in force.\n const snapshotModeAtPeek = new Map<string, boolean>(\n Object.keys(shapes).map((shapeName) => [shapeName, inbox.acceptsSnapshotRowsFor(shapeName)]),\n );\n\n // Snapshot the truncate set so a retried transaction still truncates; the per-shape flag is\n // cleared only once the commit has succeeded.\n const shapesToTruncate = new Set(truncateNeeded);\n\n // Peek the buffered tagged-subquery move-outs (ADR-0023) the same way: held in the buffer so a\n // retried/degraded commit still has them, ACKed only on success (by the exact peeked count, so a\n // move-out that arrived during a coalescing commit is not dropped).\n const moveOutsToCommit = new Map<string, MovePattern[][]>();\n // Peek the buffered tagged-subquery move-ins (ADR-0024) identically: a move-in snapshot row carries\n // no LSN; it is applied idempotently in the commit transaction and ACKed only on success.\n const moveInsToCommit = new Map<string, ChangeMessage<Row<unknown>>[]>();\n for (const shapeName of Object.keys(shapes)) {\n const pendingOut = inbox.peekMoveOuts(shapeName);\n if (pendingOut.length > 0) {\n moveOutsToCommit.set(shapeName, pendingOut);\n }\n const pendingIn = inbox.peekMoveIns(shapeName);\n if (pendingIn.length > 0) {\n moveInsToCommit.set(shapeName, pendingIn);\n }\n }\n\n const runCommit = () =>\n pg.transaction(async (tx) => {\n if (debug) {\n console.time(\"commit\");\n }\n\n // Tier ③ (ADR-0028 allow-list): a `SET LOCAL` GUC — the sync-origin `<schema>.syncing` flag\n // the apply trigger reads to distinguish streamed server truth from local writes. GUCs have\n // no tier-①/② builder form; the schema identifier is fixed at engine construction.\n await tx.exec(`SET LOCAL ${metadataSchema}.syncing = true;`);\n\n for (const [shapeName, initialMessages] of messagesToCommit.entries()) {\n const shape = getShapeOptions(shapes, shapeName);\n const target = getTarget(shapeName);\n const shapeMethod = shapeInsertMethod.get(shapeName)!;\n let messages = initialMessages;\n\n // ADR-0023: the shape's tag store key (synced table, schema-qualified).\n const shapeTable = tableIdentity(target);\n\n if (shapesToTruncate.has(shapeName)) {\n if (debug) {\n console.log(\"truncating table\", shapeTable);\n }\n if (shape.onMustRefetch) {\n await shape.onMustRefetch(drizzleOverPg(tx));\n } else {\n // ADR-0029 D4: a must-refetch wipe is engine cache maintenance, not server truth — so it\n // TRUNCATEs (tier ②; `TRUNCATE` has no Drizzle builder, the table object is interpolated)\n // rather than reacting via the per-row reconcile trigger. Correctness rides the reconcile\n // loop; TRUNCATE is O(1) and the re-snapshot inserts still fire the trigger.\n await drizzleOverPg(tx).execute(sql`TRUNCATE ${target.table}`);\n }\n // The re-snapshot rebuilds tags from scratch, so drop this shape's stale tag-set too\n // (ADR-0023 Slice 2: a must-refetch/​rebuild must not leave orphan tags).\n await clearShapeTags({ pg: tx, metadataSchema, shapeTable });\n }\n\n // ADR-0024: this shape's buffered move-in snapshot rows (a row ENTERING the shape). Their\n // tags are UNIONED first (a move-in adds a reason, it must not clear an independent grant's\n // tag) — and a regular change for the same row in this batch then authoritatively replaces\n // below, so union-then-replace converges either way.\n const moveInMessages = moveInsToCommit.get(shapeName) ?? [];\n if (moveInMessages.length > 0) {\n await addShapeRowTags({\n pg: tx,\n metadataSchema,\n shapeTable,\n messages: moveInMessages,\n primaryKey: target.primaryKey,\n });\n }\n\n // Maintain the tag-set from the RAW drained batch (ADR-0023) — before the data apply and\n // the move-out eviction, so an add-then-remove within one commit resolves correctly. Uses\n // `initialMessages` (the full batch) since the insert/​fold split below reduces `messages`.\n await applyShapeTagSync({\n pg: tx,\n metadataSchema,\n shapeTable,\n messages: initialMessages,\n primaryKey: target.primaryKey,\n });\n\n // ADR-0024: apply the move-in rows idempotently BEFORE the change fold, so a same-commit\n // update to a just-moved-in row lands on a present row. Upsert (not plain INSERT) because the\n // row may already be present via another grant or be re-delivered on a resume.\n if (moveInMessages.length > 0) {\n await applyUpsertsToTable({\n pg: tx,\n target,\n messages: moveInMessages,\n debug,\n });\n }\n\n if (!useInsert.get(shapeName)) {\n const initialInserts: InsertChangeMessage[] = [];\n const remainingMessages: ChangeMessage<Row<unknown>>[] = [];\n let foundNonInsert = false;\n for (const message of messages) {\n if (!foundNonInsert && message.headers.operation === \"insert\") {\n initialInserts.push(message as InsertChangeMessage);\n } else {\n foundNonInsert = true;\n remainingMessages.push(message);\n }\n }\n if (initialInserts.length > 0 && shapeMethod === \"copy\") {\n remainingMessages.unshift(initialInserts.pop()!);\n }\n messages = remainingMessages;\n\n if (initialInserts.length > 0) {\n await insertMethods[shapeMethod]({\n pg: tx,\n target,\n messages: initialInserts,\n debug,\n });\n\n useInsert.set(shapeName, true);\n }\n }\n\n // ADR-0014 Phase 3: fold this shape's drained batch to one net op per PK, then apply\n // three bulk statements in the order DELETE → INSERT → UPDATE. A re-created PK's delete\n // must precede its insert; every other PK lands in exactly one statement, so the rest of\n // the order is irrelevant within the (atomic) commit. The fold collapses same-PK runs, so\n // no bulk statement ever holds two rows for one PK — closing the `UPDATE … FROM` /\n // `json_to_recordset` join hazard (which would use one arbitrary matching row) by\n // construction. This replaces the previous one-SQL-statement-per-row steady-state loop.\n if (messages.length > 0) {\n const folded = foldChangeBatch(messages);\n\n if (folded.deletes.length > 0) {\n await applyBulkDeletesToTable({\n pg: tx,\n target,\n messages: folded.deletes,\n debug,\n });\n }\n if (folded.inserts.length > 0) {\n if (snapshotModeAtPeek.get(shapeName)) {\n // Snapshot-acceptance mode (post-reset re-snapshot / pre-first-lsn): the racing recovery\n // loops can re-deliver these exact snapshot rows, possibly in a later commit after this\n // shape's TRUNCATE flag has been consumed — so apply them idempotently (upsert), the same\n // posture as a move-in, rather than failing the commit on a PK collision.\n await applyUpsertsToTable({\n pg: tx,\n target,\n messages: folded.inserts,\n debug,\n });\n } else {\n await applyInsertsToTable({\n pg: tx,\n target,\n messages: folded.inserts,\n debug,\n });\n }\n }\n if (folded.updates.length > 0) {\n await applyBulkUpdatesToTable({\n pg: tx,\n target,\n messages: folded.updates,\n debug,\n });\n }\n }\n\n // ADR-0023: after the data + tag state is current, apply this shape's buffered move-outs —\n // withdraw the revoked tag and evict any row left with no tag (via the bulk-delete path, so\n // the reconcile trigger fires and the read model converges).\n const patternSets = moveOutsToCommit.get(shapeName);\n if (patternSets) {\n await applyShapeMoveOut({\n pg: tx,\n metadataSchema,\n shapeTable,\n target,\n patternSets,\n debug,\n });\n }\n }\n\n if (key) {\n await updateSubscriptionState({\n pg: tx,\n metadataSchema,\n subscriptionKey: key,\n shapeMetadata: Object.fromEntries(\n Object.keys(shapes).map((shapeName) => {\n const stream = getShapeStream(shapeName);\n return [\n shapeName,\n {\n handle: stream.shapeHandle!,\n offset: stream.lastOffset,\n },\n ];\n }),\n ),\n lastLsn: targetLsn,\n debug,\n });\n }\n\n // If we unsubscribed while this commit was in flight, discard it rather than persist\n // work during teardown. PGlite's `transaction()` skips its COMMIT once `tx.rollback()`\n // has closed the tx, so this rolls back both the applied rows and the subscription-state\n // advance; the (un-advanced) persisted offset means a later resume re-streams this batch.\n if (unsubscribed) {\n await tx.rollback();\n }\n });\n\n for (let attempt = 1; ; attempt++) {\n if (unsubscribed) {\n return false;\n }\n try {\n await runCommit();\n if (unsubscribed) {\n // The commit rolled itself back on unsubscribe (see runCommit); do not advance the\n // committed frontier, ACK the peeked buffer, or clear truncate flags for discarded work.\n return false;\n }\n committedLsn = targetLsn;\n // The transaction committed — now (and only now) remove the peeked batch from the inbox, passing\n // the peek-time epochs so a shape reset mid-commit is skipped (its rebuild survives). Move-outs/\n // move-ins are ACKed by the exact peeked count so anything that arrived during a coalescing\n // commit survives for the next run.\n inbox.ackUpTo(targetLsn, epochsAtPeek);\n for (const [shapeName, patternSets] of moveOutsToCommit) {\n inbox.ackMoveOuts(shapeName, patternSets.length, epochsAtPeek.get(shapeName) ?? inbox.epochFor(shapeName));\n }\n for (const [shapeName, moveInMessages] of moveInsToCommit) {\n inbox.ackMoveIns(\n shapeName,\n moveInMessages.length,\n epochsAtPeek.get(shapeName) ?? inbox.epochFor(shapeName),\n );\n }\n for (const shapeName of shapesToTruncate) {\n truncateNeeded.delete(shapeName);\n }\n if (debug) console.timeEnd(\"commit\");\n maybeSignalInitialSync();\n return true;\n } catch (error) {\n if (unsubscribed) {\n return false;\n }\n if (attempt >= maxCommitRetries) {\n degraded = true;\n onSyncError?.(error instanceof Error ? error : new Error(String(error)));\n return false;\n }\n await new Promise((resolve) => setTimeout(resolve, commitRetryDelayMs(attempt)));\n }\n }\n };\n\n const lowestCompleteLsn = (): Lsn => inbox.lowestCompleteLsn();\n\n // ─── Live-tail sibling nudge (ADR-0031 live-tail completion) ──────────────────────────────────────\n // The catch-up alignment (ADR-0031 in shape-inbox.ts) fixed this class of stall at BOOT: quiet shapes'\n // stale cached watermarks no longer hold a busy shape's backfill. On the LIVE tail the same shape holds\n // recur — a change batch lands on a busy shape at LSN L, but the group commits only at the min effective\n // frontier, so the batch stays buffered until every quiet sibling's PARKED long-poll returns a fresh\n // `global_last_seen_lsn` (~41s on Electric Cloud). This watchdog closes that live-tail gap: when a batch\n // is gated (its `batchMaxLsn > committedLsn`), it nudges each lagging sibling — aborting its parked poll\n // and forcing an immediate NON-live catch-up (`forceDisconnectAndRefresh`), which returns a fresh\n // watermark in ~sub-second. The group frontier then reaches L and the normal commit path (driven by the\n // up-to-date arrivals, NOT by this watchdog) fires. Atomicity is untouched: commits still happen only at\n // the group min frontier. The one-shot cache-buster (`nudgeBusters` + `withNudgeBuster`) defends each\n // nudged catch-up against a CDN HIT that would echo the stale watermark. Bounded to NUDGE_MAX_ROUNDS so a\n // genuinely-dead or still-legitimately-polling sibling degrades to the old wait-out-the-poll behavior\n // rather than a refresh storm.\n const nudgeInFlight = new Map<string, Promise<void>>();\n let nudgeTargetLsn: Lsn = BigInt(-1);\n let nudgeWatchdogRunning = false;\n\n // Void-called from the subscribe callback (never awaited — it must not backpressure the stream). Raises\n // the shared target and, if not already running, runs bounded rounds until the frontier reaches it, the\n // group tears down / degrades / re-closes its gate, or the rounds exhaust. Single-flight: a concurrent\n // gated batch just raises `nudgeTargetLsn` and returns. Wrapped so it can never throw unhandled.\n const runNudgeWatchdog = async (targetLsn: Lsn): Promise<void> => {\n if (targetLsn > nudgeTargetLsn) {\n nudgeTargetLsn = targetLsn;\n }\n if (nudgeWatchdogRunning) {\n return;\n }\n nudgeWatchdogRunning = true;\n try {\n // Pre-alignment (boot catch-up, before ADR-0031 lays the commit floors) the nudge is pure noise:\n // the alignment itself will commit the gated backfill the moment every shape reports, and firing\n // busted catch-ups mid-boot only contends with the boot requests. The floors survive later resets,\n // so this gate closes exactly once — the live tail is always past it.\n if (inbox.alignedFloor() < BigInt(0)) {\n return;\n }\n // Resolved / torn-down / gated-shut → nothing to nudge; the up-to-date arrival itself runs the\n // commit, so the watchdog never commits.\n const resolvedOrStopped = (): boolean =>\n unsubscribed || degraded || !dbGateOpen || lowestCompleteLsn() >= nudgeTargetLsn;\n\n // Hold-persistence grace: a cross-shape transaction's sibling halves arrive milliseconds apart,\n // so EVERY grouped commit passes through a transient held instant — nudging on it would abort\n // the sibling poll that is about to deliver the other half (the sync-e2e regression). Only a\n // hold that survives this grace is a real quiet-sibling park worth nudging.\n for (let waited = 0; waited < NUDGE_HOLD_GRACE_MS; waited += NUDGE_ROUND_GRACE_MS) {\n await new Promise((resolve) => setTimeout(resolve, NUDGE_ROUND_GRACE_MS));\n if (resolvedOrStopped()) {\n return;\n }\n }\n\n for (let round = 1; round <= NUDGE_MAX_ROUNDS; round++) {\n if (resolvedOrStopped()) {\n return;\n }\n for (const shapeName of Object.keys(shapes)) {\n // A shape still catching up advances on its own — only nudge one already in its live tail.\n if (!inbox.hasReportedUpToDate(shapeName)) continue;\n if (inbox.effectiveLsnFor(shapeName) >= nudgeTargetLsn) continue;\n if (nudgeInFlight.has(shapeName)) continue;\n // `forceDisconnectAndRefresh` is declared on the real ShapeStream, but a mocked/typed surface may\n // omit it — reach it structurally and skip (with a rail line) when absent.\n const stream = getShapeStream(shapeName) as { forceDisconnectAndRefresh?: () => Promise<void> };\n if (typeof stream.forceDisconnectAndRefresh !== \"function\") {\n syncDebug(\"live-tail sibling nudge unavailable\", { shape: shapeName });\n continue;\n }\n // Arm the one-shot cache-buster BEFORE the refresh so the forced catch-up carries it.\n nudgeBusters.set(shapeName, crypto.randomUUID());\n syncDebug(\"live-tail sibling nudge\", { shape: shapeName, target: String(nudgeTargetLsn), round });\n const refresh = stream\n .forceDisconnectAndRefresh()\n .catch((err: unknown) =>\n syncDebug(\"live-tail sibling nudge failed\", { shape: shapeName, error: String(err) }),\n )\n .finally(() => {\n nudgeInFlight.delete(shapeName);\n });\n nudgeInFlight.set(shapeName, refresh);\n }\n // Nothing to nudge and nothing in flight → exit QUIETLY (no exhaustion line). This is the routine\n // pre-alignment case: a gated batch during catch-up has siblings that have not yet reported\n // up-to-date, and those advance on their own — spinning the remaining rounds would only delay-loop\n // and print a misleading \"exhausted\" line on every boot rail. The \"held by group frontier\" line\n // already told the story.\n if (nudgeInFlight.size === 0) {\n return;\n }\n // Wait for this round's forced catch-ups to actually land and advance the frontier. The refresh\n // promises settle before the refreshed response does (measured), so awaiting them alone would\n // re-nudge into still-in-flight requests — poll the frontier instead, bounded per round, and\n // break out the moment the target is reached.\n await Promise.all([...nudgeInFlight.values()]);\n for (let waited = 0; waited < NUDGE_ROUND_WAIT_MS; waited += NUDGE_ROUND_GRACE_MS) {\n await new Promise((resolve) => setTimeout(resolve, NUDGE_ROUND_GRACE_MS));\n if (resolvedOrStopped()) {\n return;\n }\n }\n }\n // Rounds exhausted and the frontier is still short: a sibling is dead or genuinely mid-poll. Degrade\n // to the old behavior (wait out its live long-poll) rather than nudge forever.\n syncDebug(\"live-tail nudge exhausted; waiting on sibling live polls\", {\n target: String(nudgeTargetLsn),\n frontier: String(lowestCompleteLsn()),\n });\n } catch (err) {\n syncDebug(\"live-tail nudge watchdog error\", { error: String(err) });\n } finally {\n nudgeWatchdogRunning = false;\n }\n };\n\n // Drain buffered changes up to the current complete frontier, one commit at a time, looping\n // while fresh messages keep arriving (so commits coalesce). Returns early on `degraded` — a held\n // commit is not retried here; recovery is a later message/refetch or a restart.\n const runCommitLoop = async (): Promise<void> => {\n do {\n commitRerun = false;\n const target = lowestCompleteLsn();\n const isCommitNeeded = target > committedLsn;\n const isMustRefetchAndCatchingUp = target >= committedLsn && truncateNeeded.size > 0;\n // A buffered move-out (ADR-0023) or move-in (ADR-0024) must be committed even if no change\n // advanced the frontier — the revocation/grant has to land. Their `up-to-date` normally advances\n // `target`, but don't rely on that (move/event messages carry no LSN).\n const hasPendingMoves = target >= committedLsn && (inbox.hasPendingMoveOuts() || inbox.hasPendingMoveIns());\n // ADR-0031: a LATE-arriving change at or below an already-committed target must still commit. The\n // aligned commit floor lets `ingestChange` accept a change below the floor (its dedup frontier is\n // the raw `completeLsns`, unmoved by the floor), so such a change can land AFTER the group frontier\n // has already reached — or passed — its LSN, where no frontier advance would trigger a commit for\n // it. Committing at `target === committedLsn` is safe: it mirrors the moves path, which already\n // calls `commitUpToLsn(target)` with no frontier advance. (At `target > committedLsn` this overlaps\n // `isCommitNeeded` — harmless; the expression stays simple.)\n const hasLateArrivals = target >= committedLsn && inbox.hasBufferedChangesAtOrBelow(target);\n if (isCommitNeeded || isMustRefetchAndCatchingUp || hasPendingMoves || hasLateArrivals) {\n const applied = await commitUpToLsn(target);\n if (!applied) {\n return;\n }\n } else {\n maybeSignalInitialSync();\n }\n } while (commitRerun);\n };\n\n // Single-flight: at most one commit loop runs. A message arriving while one is running buffers\n // synchronously (above) and re-arms the loop via `commitRerun`; `commitInFlight` is cleared\n // inside the same async body — before its promise resolves — so an enqueue can never observe a\n // stale in-flight handle and resolve without committing its messages.\n const enqueueCommit = (): Promise<void> => {\n // ADR-0009 decision 5: once a commit exhausts its retries the engine latches `degraded` and\n // REFUSES to run any further commit. `commitUpToLsn` peeks (never drains) the buffer, so the\n // unapplied batch is still held; refusing later commits guarantees a newer LSN can never apply\n // over that held batch (the divergence the destructive drain allowed). The buffer keeps\n // accumulating incoming messages harmlessly; recovery is a restart/refetch, which re-streams the\n // held frontier because the persisted offset was never advanced. Note the commit-await backpressure\n // is intentionally absent while degraded — the inbox grows at the stream's rate until recovery,\n // which is the accepted cost of ADR-0009's documented \"hold the buffer\" posture.\n if (degraded) {\n return commitInFlight ?? Promise.resolve();\n }\n if (commitInFlight) {\n commitRerun = true;\n return commitInFlight;\n }\n commitInFlight = (async () => {\n try {\n await runCommitLoop();\n } finally {\n commitInFlight = null;\n }\n })();\n return commitInFlight;\n };\n\n multiShapeStream.subscribe(async (messages) => {\n if (unsubscribed) {\n return;\n }\n // A delivered batch means a fetch just succeeded — the read path is alive (ADR-0013 Phase 3),\n // so the runtime can clear an auth-needed status once a fresh token starts working again.\n onSyncActivity?.();\n if (debug) {\n console.log(\"received messages\", messages.length);\n }\n // Receive-path latency probe: a batch carrying real change rows is the moment Electric delivered\n // a write to this subscriber (the writer's own echo, or another browser's edit fanning in). The\n // gap from here to the commit finishing is the local apply cost.\n const changeCount = messages.reduce((n, message) => (isChangeMessage(message) ? n + 1 : n), 0);\n if (changeCount > 0) {\n syncDebug(\"sync received change batch from Electric\", { changes: changeCount });\n }\n const commitStartedAt = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n\n // The max LSN over the change rows this batch COMPLETED (routed to `ingestChange` with `isLastOfLsn`;\n // move-in rows carry no lsn and are excluded). It is what the batch needs the group frontier to reach\n // to actually commit — the truth test for the \"applied\" vs \"held\" rail line below. -1 if none.\n let batchMaxLsn: Lsn = BigInt(-1);\n\n messages.forEach((message) => {\n if (isChangeMessage(message)) {\n // A tagged-subquery MOVE-IN row (ADR-0024): an existing row ENTERING the shape because a grant\n // was added. Electric delivers it as a snapshot insert flagged `is_move_in` with NO `lsn`/`last`\n // (it is not a replication-stream change), so the `ingestChange` dedup — which floors a missing\n // lsn to 0 — would treat it as already-seen and drop it once the frontier passed 0. Route it to\n // its own buffer, applied idempotently at the next commit (the trailing `up-to-date`).\n if (message.headers[\"is_move_in\"] === true) {\n inbox.ingestMoveIn(message.shape, message);\n } else {\n const { lsn, isLastOfLsn } = readReplicationHeaders(message.headers);\n inbox.ingestChange(message.shape, message, lsn, isLastOfLsn);\n if (isLastOfLsn && lsn > batchMaxLsn) {\n batchMaxLsn = lsn;\n }\n }\n } else if (isControlMessage(message)) {\n switch (message.headers.control) {\n case \"up-to-date\": {\n if (debug) {\n console.log(\"received up-to-date\", message);\n }\n if (typeof message.headers.global_last_seen_lsn !== \"string\") {\n throw new Error(\"global_last_seen_lsn is not a string\");\n }\n // ADR-0031: `ingestUpToDate` returns true ONLY on the transition where this control message\n // completed the group (every shape has now reported up-to-date) and the inbox aligned the\n // commit floors. Surface that single moment on the debug rail so a \"stale board at load that\n // rearranges itself\" symptom is diagnosable — the floor it aligned to is the group head.\n if (inbox.ingestUpToDate(message.shape, BigInt(message.headers.global_last_seen_lsn))) {\n syncDebug(\"catch-up watermark aligned\", { floor: String(inbox.alignedFloor()) });\n }\n break;\n }\n case \"must-refetch\": {\n if (debug) {\n console.log(\"received must-refetch\", message);\n }\n // Surface the expired-handle / rewind event on the syncDebug rail too (the legacy `debug`\n // option only console.logs it): must-refetch is the trigger for the truncate + re-snapshot\n // recovery, so it must be visible when diagnosing a convergence loss in a live app.\n syncDebug(\"must-refetch received\", { shape: message.shape });\n inbox.resetShape(message.shape);\n truncateNeeded.add(message.shape);\n break;\n }\n }\n } else if (isEventMessage(message)) {\n // ADR-0023: a tagged-subquery move-out — a grant was revoked, so the rows it kept in the shape\n // must be evicted. Buffer the patterns; the eviction runs in the next commit (decision 3).\n // `MultiShapeStream`'s callback type does not declare `EventMessage` (the prior guards narrow\n // `message` to `never` here), so reach the runtime-present event through an explicit cast.\n const eventMessage = message as unknown as ShapeEventMessage;\n if (eventMessage.headers.event === \"move-out\") {\n if (debug) {\n console.log(\"received move-out\", eventMessage);\n }\n inbox.ingestMoveOut(eventMessage.shape, eventMessage.headers.patterns);\n }\n // A `move-in` EventMessage (ADR-0024) needs no action here: its newly-matched rows arrive in the\n // same batch as snapshot inserts flagged `is_move_in`, which the change branch routes to the\n // move-in buffer. The event's `patterns` are redundant with those inserts' `tags`.\n }\n });\n\n // Buffering above is synchronous. On the overlap path, while the commit gate is still closed the\n // batch stays in the memory inbox (its LSN frontier + catch-up watermarks still advance from the\n // ingest above) and the callback returns WITHOUT awaiting a commit — so the stream keeps fetching\n // catch-up and does not stall behind the local boot phases. Once the gate lifts, the deferred commit\n // train (below) drains everything buffered. On the sequential path the gate is already open, so this\n // is the unchanged path: enqueue the single-flight commit and await it (the natural backpressure that\n // bounds the buffer — replacing the old fire-and-forget commit + `setTimeout(0)` race).\n if (dbGateOpen) {\n await enqueueCommit();\n if (changeCount > 0) {\n // Truthful rail (ADR-0031): the \"applied\" line only fires when this batch's completed changes\n // actually landed (its `batchMaxLsn` is at or below the advanced `committedLsn`). Otherwise the\n // group frontier had not reached them — the batch is BUFFERED behind a quiet sibling's watermark —\n // so say so, and kick the live-tail sibling nudge to shorten that hold (void: never backpressure\n // the stream).\n if (batchMaxLsn <= committedLsn) {\n const elapsed = (typeof performance !== \"undefined\" ? performance.now() : Date.now()) - commitStartedAt;\n syncDebug(\"sync applied change batch to local store\", { changes: changeCount, ms: Math.round(elapsed) });\n } else {\n syncDebug(\"sync change batch held by group frontier\", {\n changes: changeCount,\n heldLsn: String(batchMaxLsn),\n frontier: String(lowestCompleteLsn()),\n });\n void runNudgeWatchdog(batchMaxLsn);\n }\n }\n }\n }, onError);\n\n // Fresh-store prefetch overlap (ADR-0032 S4): the moment the caller signals the local store is ready\n // (schema exec + journal recovery + store-version reconcile done), run the deferred metadata DDL, open\n // the commit gate, and drain everything the streams buffered during the window in one commit train. The\n // ADR-0031 catch-up watermarks were aligned by the ingests above as the up-to-dates arrived, so this\n // drain commits to the aligned floor and `onInitialSync` fires exactly as on the sequential path.\n if (overlap) {\n void dbReady!.then(async () => {\n if (unsubscribed) {\n return;\n }\n // The metadata tables' DDL was deferred past the gate (the store had no schema when the streams\n // started); create them now, before the first commit needs the subscription-state table.\n await initMetadataTables();\n dbGateOpen = true;\n syncDebug(\"boot commits opened\");\n await enqueueCommit();\n });\n }\n\n streams.push({\n stream: multiShapeStream,\n aborter,\n });\n\n const unsubscribe = () => {\n if (debug) {\n console.log(\"unsubscribing\");\n }\n unsubscribed = true;\n multiShapeStream.unsubscribeAll();\n aborter.abort();\n for (const shape of Object.values(shapes)) {\n shapePerTableLock.delete(shape.tableKey);\n }\n };\n\n return {\n unsubscribe,\n get isUpToDate() {\n // Never report up-to-date while a commit is pending or after going degraded (ADR-0009\n // decision 5): the read cache must not claim to match the server on an unapplied commit. Nor while\n // the overlap commit gate is still closed (ADR-0032 S4): the stream may already be `isUpToDate` on\n // the network side while its catch-up is still buffered, unapplied, in the memory inbox.\n return dbGateOpen && !degraded && commitInFlight === null && multiShapeStream.isUpToDate;\n },\n streams: Object.fromEntries(\n Object.keys(shapes).map((shapeName) => [shapeName, getShapeStream(shapeName)]),\n ) as SyncShapesToTablesResult[\"streams\"],\n };\n };\n\n const syncShapeToTable = async (options: SyncShapeToTableOptions): Promise<SyncShapeToTableResult> => {\n // ADR-0029 D6: thin sugar over the group form, forwarding the same entry-based options. The\n // per-shape `initialInsertMethod` (if any) rides through; the group form resolves the backfill\n // strategy from the registry entry when it is absent.\n const multiShapeSub = await syncShapesToTables({\n registry: options.registry,\n shapes: {\n shape: {\n shape: options.shape,\n tableKey: options.tableKey,\n onMustRefetch: options.onMustRefetch,\n ...(options.initialInsertMethod ? { initialInsertMethod: options.initialInsertMethod } : {}),\n },\n },\n key: options.shapeKey,\n onInitialSync: options.onInitialSync,\n onError: options.onError,\n onSyncError: options.onSyncError,\n maxCommitRetries: options.maxCommitRetries,\n commitRetryDelayMs: options.commitRetryDelayMs,\n });\n\n return {\n unsubscribe: multiShapeSub.unsubscribe,\n get isUpToDate() {\n return multiShapeSub.isUpToDate;\n },\n stream: (() => {\n const stream = multiShapeSub.streams[\"shape\"];\n if (!stream) {\n throw new Error(\"Missing stream for shape\");\n }\n return stream;\n })() as SyncShapeToTableResult[\"stream\"],\n };\n };\n\n const deleteSubscription = async (key: string) => {\n await deleteSubscriptionState({\n pg,\n metadataSchema,\n subscriptionKey: key,\n });\n };\n\n const namespaceObj = {\n initMetadataTables,\n syncShapesToTables,\n syncShapeToTable,\n deleteSubscription,\n };\n\n const close = async () => {\n for (const { stream, aborter } of streams) {\n stream.unsubscribeAll();\n aborter.abort();\n }\n };\n\n return {\n namespace: namespaceObj,\n close,\n };\n}\n\n/**\n * The pgxsinkit sync engine handle: the {@link SyncNamespaceObj} the client attaches as `pg.electric`,\n * plus the explicit `close()` teardown. Derived from {@link createSyncEngine}'s real return so the type\n * follows the object.\n */\nexport type SyncEngine = Awaited<ReturnType<typeof createSyncEngine>>;\nexport type SyncNamespaceObj = SyncEngine[\"namespace\"];\n\nexport type PGliteWithSync = PGliteInterface & {\n sync: SyncNamespaceObj;\n};\n",
140
+ "import type { ExternalHeadersRecord } from \"@electric-sql/client\";\nimport type { PGliteInterface } from \"@electric-sql/pglite\";\n\nimport {\n type Retention,\n type SubscriptionTiming,\n type SyncConfigInput,\n type SyncTableRegistry,\n type TableSpecInput,\n} from \"@pgxsinkit/contracts\";\n\nimport type { BootStampCollector, GroupBootStamp } from \"./boot-report\";\nimport type { SyncNamespaceObj } from \"./sync\";\nimport { createShapeErrorHandler } from \"./sync-auth\";\n\nexport interface ShapeSyncSpec {\n electricUrl: string;\n tableName: string;\n schema?: string;\n shapeKey: string;\n primaryKey: string[];\n electricTable?: string;\n /**\n * Consistency group (ADR-0009 decision 2). Specs sharing a group sync on one `MultiShapeStream`\n * and commit atomically. Absent → the table is its own singleton group keyed by its `shapeKey`.\n */\n consistencyGroup?: string;\n /**\n * Subscription timing (ADR-0021). Absent → `eager`. A `lazy` spec's group is held out of the eager\n * boot set and started on demand via {@link StartConfiguredSyncResult.ensureGroupStarted}. A group's\n * members all agree (registry-validated), so the group's timing is any member's.\n */\n subscription?: SubscriptionTiming;\n /**\n * Retention (ADR-0021). Absent → `persistent`. Only a `persistent` `lazy` group is promoted to the\n * eager set on activation (its activation is permanent across boots); an `ephemeral` group's activation\n * is session-scoped by construction, so it is never promoted/persisted.\n */\n retention?: Retention;\n}\n\nexport interface ConfiguredShapeSyncSpec extends ShapeSyncSpec {\n key: string;\n}\n\nexport interface StartConfiguredSyncOptions {\n syncConfig: SyncConfigInput;\n /**\n * The sync registry (ADR-0029 D1): the engine's sole per-table spec source. Each shape's `tableKey`\n * (its `syncConfig` table key) resolves against it for the local table, PKs, apply strategy, and\n * column types — no table-scoped fact is threaded from `syncConfig` into the engine.\n */\n registry: SyncTableRegistry;\n /**\n * Shape request headers shared by every member shape. Values may be async functions resolved per\n * request (ADR-0013) — the read-path `Authorization` token is one such function.\n */\n shapeHeaders?: ExternalHeadersRecord;\n onInitialSync?: () => void;\n onTableInitialSync?: (tableKey: string) => void;\n /**\n * Fresh-store prefetch overlap (ADR-0032 S4). When present, every EAGER group starts its shape streams\n * and buffers their catch-up into the memory inbox immediately, gating all commits until this promise\n * resolves — so the network catch-up overlaps the local boot phases (schema/journal/reconcile) instead\n * of running after them. Set ONLY by `createSyncClient` on a provably-fresh store (its `freshStore`\n * hint); absent → the sequential path. Passed straight through to the engine's `syncShapesToTables`.\n */\n dbReady?: Promise<void>;\n /** Commit-level error surfacing (ADR-0009 decision 5): a sync commit exhausted its retries. */\n onSyncError?: (error: Error) => void;\n /**\n * Notified when a shape hits an auth error (401/403) and the read path is retrying for a fresh\n * token (ADR-0013 Phase 3). The runtime surfaces a distinct `auth-needed` status from this.\n */\n onAuthError?: () => void;\n /**\n * Notified when a shape hits a NON-auth stream error (#4): a transient 5xx/429/network (retried) or\n * a structural 4xx (stops the stream). The runtime surfaces a `degraded` status from this so it\n * never silently believes the read path is live while it has actually stalled.\n */\n onReadStreamError?: (error: Error) => void;\n /**\n * Notified when a shape successfully delivers a batch — i.e. a fetch just succeeded (ADR-0013\n * Phase 3). The runtime uses this to clear an `auth-needed`/`degraded` status once sync resumes.\n */\n onSyncActivity?: () => void;\n /**\n * Consistency-group keys of `lazy` groups that were activated on a previous boot and persisted their\n * activation flag (ADR-0021 §2 — `lazy + persistent` promotion). These join the eager boot set as if\n * they were declared `eager`, so a once-activated durable lazy group resumes without re-evaluation.\n * Computed by the caller from the local meta table (the sync engine does no DB read of its own).\n */\n promotedGroups?: ReadonlySet<string>;\n /**\n * Invoked when a `persistent` `lazy` group is activated on demand (not promoted at boot), so the\n * caller can persist its activation flag for the next boot (ADR-0021 §2). Never fired for an\n * `ephemeral` group (its activation is session-scoped and leaves no durable trace).\n */\n onLazyActivated?: (groupKey: string) => void;\n /**\n * Invoked exactly once per consistency group the moment it becomes up-to-date (ADR-0032 decision 6 —\n * per-group readiness). Fires for eager, promoted, and on-demand `lazy` groups alike, so a client can\n * surface progressive per-group paint (and the worker bridge can fan a `groupReady` event to tabs)\n * without the all-eager-groups `onInitialSync` gate. The matching promise is {@link StartConfiguredSyncResult.groupReady}.\n */\n onGroupReady?: (groupKey: string) => void;\n /**\n * Boot observability (ADR-0034): opens a per-group accumulator (rows/requests/fetch/apply wall) for each\n * EAGER + PROMOTED boot group, stamped by the engine as the group's stream chain delivers and applies. A\n * lazy on-demand start gets none — so a lazily-activated-later group never enters (or mutates) the report.\n * Absent → no boot instrumentation.\n */\n bootCollector?: BootStampCollector;\n}\n\n// The engine is reached through the `electric` namespace the client attaches post-create (ADR-0032 S1) —\n// a plain property carrying the sync entry points, no longer a create-time PGlite extension.\ntype SyncEnginePGlite = PGliteInterface & { electric: SyncNamespaceObj };\n\nexport interface ShapeSyncResult {\n unsubscribe: () => void;\n readonly isUpToDate: boolean;\n}\n\nexport interface StartConfiguredSyncResult {\n unsubscribe: () => void;\n tables: Record<string, ShapeSyncResult>;\n /**\n * Start a `lazy` consistency group (ADR-0021) held out of the eager boot set. Idempotent and\n * single-flight: concurrent calls share one start; a started, unknown, or eager group resolves\n * immediately. Resolves once the group's initial sync completes — the seam the live-query layer\n * calls on first reference to a lazy table. After it resolves, the group's member `tables` entries\n * report `isUpToDate` live.\n */\n ensureGroupStarted: (groupKey: string) => Promise<void>;\n /**\n * Stop a group's stream and return it to dormant (ADR-0021 §2): tear down its live subscription and\n * clear the runtime so {@link isTableStarted} reports false again and a later {@link ensureGroupStarted}\n * re-subscribes from scratch — the inverse of an on-demand activation. Used by the client's `desync`\n * to halt a lazy group before truncating its read cache. A no-op for an unknown or never-started group.\n * The temp cluster of an `ephemeral` group is NOT dropped here (that is the deferred idle-eviction); the\n * cluster simply stops being fed.\n */\n stopGroup: (groupKey: string) => void;\n /** The consistency-group key a table belongs to — maps a queried table to its {@link ensureGroupStarted}. */\n groupKeyForTable: (tableKey: string) => string | undefined;\n /**\n * Whether a table's consistency group has started and completed its initial sync, so its reads are\n * hydrated (ADR-0021). False for a `lazy` group still held out of the boot set. Drives the read-path\n * tripwire — a lazy relation read while this is false would return empty/stale rows.\n */\n isTableStarted: (tableKey: string) => boolean;\n /**\n * A promise that resolves the moment the given consistency group is up-to-date (ADR-0032 decision 6).\n * Resolves immediately for an already-ready group; stays pending for a `lazy` group until it is\n * activated (via {@link ensureGroupStarted}) and catches up. An unknown group resolves immediately\n * (nothing to await). Per-group readiness the client re-exposes as `client.groupReady(table)`.\n */\n groupReady: (groupKey: string) => Promise<void>;\n /** Whether the given consistency group has completed its initial sync (synchronous peek at {@link groupReady}). */\n isGroupReady: (groupKey: string) => boolean;\n /** Every consistency-group key this config declares — the domain of {@link groupReady}/{@link isGroupReady}. */\n groupKeys: () => string[];\n}\n\nexport function buildShapeUrl(electricUrl: string, table: string) {\n const url = new URL(electricUrl);\n url.searchParams.set(\"table\", table);\n return url.toString();\n}\n\nexport function buildShapeConfig(input: ShapeSyncSpec) {\n return {\n shape: {\n // The ingress `table` param carries the unique `shapeKey` — the proxy resolves the shape by it and\n // maps it to the physical Electric table on egress (so a read projection and its owner, which share\n // a physical table, stay distinguishable). `table` below is the LOCAL PGlite apply target.\n url: buildShapeUrl(input.electricUrl, input.shapeKey),\n },\n table: input.tableName,\n ...(input.schema !== undefined ? { schema: input.schema } : {}),\n primaryKey: [...input.primaryKey],\n shapeKey: input.shapeKey,\n };\n}\n\nexport function buildConfiguredShapeSpecs(input: SyncConfigInput): ConfiguredShapeSyncSpec[] {\n return Object.entries(input.tables)\n .filter(([, table]) => table.mode !== \"writeonly\")\n .map(([key, table]) => buildConfiguredShapeSpec(input.electricUrl, input.localSchema, key, table));\n}\n\n/**\n * One consistency group's runtime: its specs, the subscription timing its members agree on, and its\n * live stream once started (`null` while a `lazy` group is still held). `startPromise` makes start\n * single-flight so concurrent on-demand triggers share one subscription.\n */\ninterface GroupRuntime {\n groupKey: string;\n specs: ConfiguredShapeSyncSpec[];\n subscription: SubscriptionTiming;\n retention: Retention;\n result: ShapeSyncResult | null;\n startPromise: Promise<void> | null;\n}\n\nexport async function startConfiguredSync(\n pg: SyncEnginePGlite,\n input: StartConfiguredSyncOptions,\n): Promise<StartConfiguredSyncResult> {\n const specs = buildConfiguredShapeSpecs(input.syncConfig);\n\n // Bucket specs into consistency groups (ADR-0009 decision 2). Each group is one MultiShapeStream\n // committed atomically; an ungrouped table is its own singleton group keyed by its shapeKey. A group\n // carries the subscription timing its members agree on (ADR-0021; registry validation guarantees\n // agreement, so the first member's value is the group's): `eager` groups start at boot, `lazy` groups\n // are held until ensureGroupStarted (the on-demand / live-query interception seam).\n const groups = new Map<string, GroupRuntime>();\n const groupKeyByTable = new Map<string, string>();\n for (const spec of specs) {\n const groupKey = groupSubscriptionKey(spec);\n groupKeyByTable.set(spec.key, groupKey);\n const existing = groups.get(groupKey);\n if (existing) {\n existing.specs.push(spec);\n } else {\n groups.set(groupKey, {\n groupKey,\n specs: [spec],\n subscription: spec.subscription ?? \"eager\",\n retention: spec.retention ?? \"persistent\",\n result: null,\n startPromise: null,\n });\n }\n }\n\n // Per-group readiness (ADR-0032 decision 6): one deferred per group, created up front so a caller can\n // await ANY group — eager or still-dormant lazy — before it has started. Resolved once (idempotent) the\n // moment the group reports up-to-date; a never-activated lazy group's promise simply stays pending.\n interface GroupReadyDeferred {\n promise: Promise<void>;\n resolve: () => void;\n ready: boolean;\n }\n const groupReadyState = new Map<string, GroupReadyDeferred>();\n for (const groupKey of groups.keys()) {\n let resolve!: () => void;\n const promise = new Promise<void>((r) => {\n resolve = r;\n });\n groupReadyState.set(groupKey, { promise, resolve, ready: false });\n }\n const markGroupReady = (groupKey: string) => {\n const state = groupReadyState.get(groupKey);\n if (!state || state.ready) return;\n state.ready = true;\n state.resolve();\n input.onGroupReady?.(groupKey);\n };\n\n // A `lazy` group activated on a previous boot (ADR-0021 §2 `lazy + persistent` promotion) is treated\n // as eager this boot: its activation is permanent, so it joins the boot set and resumes like any durable\n // table — no per-session re-evaluation, no half-lazy.\n const promotedGroups = input.promotedGroups ?? new Set<string>();\n const isEagerAtBoot = (group: GroupRuntime) => group.subscription !== \"lazy\" || promotedGroups.has(group.groupKey);\n\n // Boot readiness (`onInitialSync`) waits only for the boot (eager + promoted) groups to catch up; a lazy\n // group started later via ensureGroupStarted signals its members' `onTableInitialSync` but never the gate.\n const eagerGroups = [...groups.values()].filter(isEagerAtBoot);\n let pendingBootGroups = eagerGroups.length;\n let bootSignalled = false;\n const signalBootIfReady = () => {\n if (!bootSignalled && pendingBootGroups <= 0) {\n bootSignalled = true;\n input.onInitialSync?.();\n }\n };\n\n // Start one group's stream, single-flight: a started group resolves immediately; an in-flight start\n // is shared. `countsTowardBoot` is true only for the eager boot starts.\n const startGroup = (group: GroupRuntime, countsTowardBoot: boolean): Promise<void> => {\n if (group.result) {\n return Promise.resolve();\n }\n if (group.startPromise) {\n return group.startPromise;\n }\n // Boot observability (ADR-0034): open an accumulator for a BOOT group only (eager + promoted); an\n // on-demand lazy start (`countsTowardBoot === false`) gets none, so it never enters the report.\n const bootStamp: GroupBootStamp | undefined =\n countsTowardBoot && input.bootCollector\n ? input.bootCollector.beginGroup(group.groupKey, group.specs.length)\n : undefined;\n group.startPromise = startGroupSync(pg, {\n groupKey: group.groupKey,\n specs: group.specs,\n registry: input.registry,\n ...(bootStamp ? { bootStamp } : {}),\n // The prefetch overlap (ADR-0032 S4) applies ONLY to the eager BOOT starts: a fresh store's eager\n // groups are genuinely new, so buffering their catch-up behind the commit gate is safe. An on-demand\n // `lazy` start happens post-boot on an already-provisioned store (which may even be RESUMING persisted\n // subscription state), so it must take the exact sequential path — never the fresh-store overlap.\n ...(countsTowardBoot && input.dbReady ? { dbReady: input.dbReady } : {}),\n ...(input.shapeHeaders ? { headers: input.shapeHeaders } : {}),\n ...(input.onSyncError ? { onSyncError: input.onSyncError } : {}),\n ...(input.onAuthError ? { onAuthError: input.onAuthError } : {}),\n ...(input.onReadStreamError ? { onReadStreamError: input.onReadStreamError } : {}),\n ...(input.onSyncActivity ? { onSyncActivity: input.onSyncActivity } : {}),\n onGroupInitialSync: () => {\n // The group is up-to-date as a unit; signal each member table, mark the group ready (per-group\n // readiness, ADR-0032 decision 6), then (for an eager group only) advance the boot gate once\n // every eager group is caught up.\n for (const spec of group.specs) {\n input.onTableInitialSync?.(spec.key);\n }\n // Boot observability (ADR-0034): stamp readyAtMs and freeze the accumulator at the group's ready edge,\n // so later live traffic never mutates a finalized report.\n bootStamp?.markReady();\n markGroupReady(group.groupKey);\n if (countsTowardBoot) {\n pendingBootGroups -= 1;\n signalBootIfReady();\n }\n },\n }).then((result) => {\n group.result = result;\n // A `persistent` `lazy` group activated on demand (not a boot start) persists its activation, so the\n // next boot promotes it to eager (ADR-0021 §2). `ephemeral` activation is session-scoped — never persisted.\n if (!countsTowardBoot && group.subscription === \"lazy\" && group.retention === \"persistent\") {\n input.onLazyActivated?.(group.groupKey);\n }\n });\n return group.startPromise;\n };\n\n // Each member table exposes a per-table view backed by its group's runtime: up-to-date exactly when\n // the group is (false until a lazy group is started), and unsubscribing it tears down the group.\n const tables: Record<string, ShapeSyncResult> = {};\n for (const [tableKey, groupKey] of groupKeyByTable) {\n const group = groups.get(groupKey)!;\n tables[tableKey] = {\n unsubscribe: () => group.result?.unsubscribe(),\n get isUpToDate() {\n return group.result?.isUpToDate ?? false;\n },\n };\n }\n\n // Start the eager groups at boot; lazy groups wait for ensureGroupStarted. `signalBootIfReady` after\n // the await covers a config with no eager groups (boot is trivially complete).\n await Promise.all(eagerGroups.map((group) => startGroup(group, true)));\n signalBootIfReady();\n\n return {\n unsubscribe: () => {\n // Unsubscribe per group (not per table) so a multi-table group's stream is torn down once.\n for (const group of groups.values()) {\n group.result?.unsubscribe();\n }\n },\n tables,\n ensureGroupStarted: (groupKey) => {\n const group = groups.get(groupKey);\n return group ? startGroup(group, false) : Promise.resolve();\n },\n stopGroup: (groupKey) => {\n const group = groups.get(groupKey);\n if (!group) return;\n // Tear down the live stream and clear the runtime so the group is dormant again: `isTableStarted`\n // reports false and `ensureGroupStarted` re-runs `startGroupSync` (its `group.result`/`startPromise`\n // short-circuits no longer apply) on the next reference.\n group.result?.unsubscribe();\n group.result = null;\n group.startPromise = null;\n // Return the group's readiness to pending: a stopped group is dormant again, so `groupReady` for a\n // later re-activation must re-await its fresh catch-up rather than resolve on the stale deferred.\n if (groupReadyState.get(groupKey)?.ready) {\n let resolve!: () => void;\n const promise = new Promise<void>((r) => {\n resolve = r;\n });\n groupReadyState.set(groupKey, { promise, resolve, ready: false });\n }\n },\n groupKeyForTable: (tableKey) => groupKeyByTable.get(tableKey),\n isTableStarted: (tableKey) => {\n const groupKey = groupKeyByTable.get(tableKey);\n if (groupKey == null) return false;\n return groups.get(groupKey)?.result != null;\n },\n // An unknown group key has nothing to await, so its readiness resolves immediately (never blocks).\n groupReady: (groupKey) => groupReadyState.get(groupKey)?.promise ?? Promise.resolve(),\n isGroupReady: (groupKey) => groupReadyState.get(groupKey)?.ready ?? true,\n groupKeys: () => [...groups.keys()],\n };\n}\n\ninterface StartGroupSyncOptions {\n groupKey: string;\n specs: ConfiguredShapeSyncSpec[];\n registry: SyncTableRegistry;\n headers?: ExternalHeadersRecord;\n /** Fresh-store prefetch overlap gate (ADR-0032 S4) — forwarded to the engine's `syncShapesToTables`. */\n dbReady?: Promise<void>;\n /** Boot observability (ADR-0034): the group's accumulator, stamped by the engine on delivery/apply. */\n bootStamp?: GroupBootStamp;\n onGroupInitialSync?: () => void;\n onSyncError?: (error: Error) => void;\n onAuthError?: () => void;\n onReadStreamError?: (error: Error) => void;\n onSyncActivity?: () => void;\n}\n\n/**\n * Sync one consistency group on a single `MultiShapeStream` (ADR-0009 decision 2). All member\n * shapes share the group's subscription key and commit atomically at a shared LSN frontier; each\n * shape keeps its own apply strategy and column types (resolved per-shape inside the engine).\n */\nexport async function startGroupSync(pg: SyncEnginePGlite, input: StartGroupSyncOptions) {\n const shapeHeaders = input.headers && Object.keys(input.headers).length > 0 ? input.headers : undefined;\n\n // The per-shape onError owns read-path auth recovery (ADR-0013 Phase 2: a 401/403 retries with a\n // fresh token) AND read-stream error surfacing (#4: a non-auth error moves the runtime to\n // `degraded`, retrying transient 5xx/429/network and stopping a structural 4xx).\n const onError = createShapeErrorHandler({\n ...(input.onAuthError ? { onAuthError: input.onAuthError } : {}),\n ...(input.onReadStreamError ? { onReadStreamError: input.onReadStreamError } : {}),\n });\n\n const shapes = Object.fromEntries(\n input.specs.map((spec) => [\n spec.key,\n {\n shape: {\n // Ingress `table` = the unique `shapeKey` (proxy maps it to the physical table on egress).\n url: buildShapeUrl(spec.electricUrl, spec.shapeKey),\n ...(shapeHeaders ? { headers: shapeHeaders } : {}),\n onError,\n },\n // ADR-0029 D1: the registry table key is the engine's sole per-table spec — the local apply\n // target, PKs, strategy, and column types all derive from `(registry, tableKey)`. The\n // `syncConfig` table key IS the registry key, so the spec's `key` is the `tableKey`.\n tableKey: spec.key,\n },\n ]),\n );\n\n return getElectricNamespace(pg).syncShapesToTables({\n key: input.groupKey,\n registry: input.registry,\n shapes,\n ...(input.dbReady ? { dbReady: input.dbReady } : {}),\n ...(input.bootStamp ? { bootStamp: input.bootStamp } : {}),\n ...(input.onGroupInitialSync ? { onInitialSync: input.onGroupInitialSync } : {}),\n ...(input.onSyncError ? { onSyncError: input.onSyncError } : {}),\n ...(input.onSyncActivity ? { onSyncActivity: input.onSyncActivity } : {}),\n });\n}\n\nfunction getElectricNamespace(pg: SyncEnginePGlite) {\n return pg.electric;\n}\n\nfunction buildConfiguredShapeSpec(\n electricUrl: string,\n localSchema: string | undefined,\n key: string,\n table: TableSpecInput,\n): ConfiguredShapeSyncSpec {\n if (table.shape === undefined) {\n throw new Error(`shape is required for synced table ${key}`);\n }\n\n return {\n key,\n electricUrl,\n tableName: table.clientProjection?.syncedTable ?? table.shape.tableName,\n // ADR-0021 §3: an ephemeral table's cluster is `TEMP` (bare names in `pg_temp`), so the row-applier\n // must target the unqualified name (resolved via search_path) — omit the schema for it.\n ...(localSchema && table.retention !== \"ephemeral\" ? { schema: localSchema } : {}),\n shapeKey: table.shape.shapeKey,\n primaryKey: [...(table.clientProjection?.localPrimaryKey?.columns ?? table.primaryKey.columns)],\n electricTable: table.shape.electricTable ?? table.shape.tableName,\n ...(table.consistencyGroup ? { consistencyGroup: table.consistencyGroup } : {}),\n ...(table.subscription ? { subscription: table.subscription } : {}),\n ...(table.retention ? { retention: table.retention } : {}),\n };\n}\n\n/**\n * The subscription key for a spec's consistency group (ADR-0009 decision 2): the explicit\n * `consistencyGroup` when set, else the table's own `shapeKey` (a singleton group). One persisted\n * subscription-state row exists per group key, so subscription reset enumerates these.\n */\nexport function groupSubscriptionKey(spec: Pick<ConfiguredShapeSyncSpec, \"consistencyGroup\" | \"shapeKey\">): string {\n return spec.consistencyGroup ?? spec.shapeKey;\n}\n",
141
+ "// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\nimport type { EventMessage, MovePattern, Row } from \"@electric-sql/client\";\nimport { isChangeMessage, isControlMessage } from \"@electric-sql/client\";\nimport type { ChangeMessage, ShapeStreamOptions } from \"@electric-sql/client\";\nimport { MultiShapeStream } from \"@electric-sql/experimental\";\nimport type { PGliteInterface } from \"@electric-sql/pglite\";\nimport { sql } from \"drizzle-orm\";\nimport { getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport { type ApplyStrategy, classifyTableApplyStrategy } from \"@pgxsinkit/contracts\";\n\nimport { instrumentShapeFetch, syncDebug } from \"../debug\";\nimport { type ApplyTarget, resolveApplyTarget } from \"../local-tables\";\nimport { computeRetryDelayMs } from \"../mutation\";\nimport {\n applyBulkDeletesToTable,\n applyBulkUpdatesToTable,\n applyInsertsToTable,\n applyMessagesToTableWithCopy,\n applyMessagesToTableWithJson,\n applyUpsertsToTable,\n} from \"./apply\";\nimport { drizzleOverPg } from \"./drizzle-executor\";\nimport {\n NUDGE_HOLD_GRACE_MS,\n NUDGE_MAX_ROUNDS,\n NUDGE_ROUND_GRACE_MS,\n NUDGE_ROUND_WAIT_MS,\n withNudgeBuster,\n} from \"./nudge\";\nimport { foldChangeBatch, ShapeInbox } from \"./shape-inbox\";\nimport {\n deleteSubscriptionState,\n getSubscriptionState,\n migrateSubscriptionMetadataTables,\n type SubscriptionState,\n updateSubscriptionState,\n} from \"./subscription-state\";\nimport {\n addShapeRowTags,\n applyShapeMoveOut,\n applyShapeTagSync,\n assertValidMetadataSchema,\n clearShapeTags,\n DEFAULT_METADATA_SCHEMA,\n shapeTableId,\n} from \"./tags\";\nimport {\n DEFAULT_MAX_COMMIT_RETRIES,\n type ElectricSyncOptions,\n type InitialInsertMethod,\n type InsertChangeMessage,\n type Lsn,\n type SyncShapesToTablesOptions,\n type SyncShapesToTablesResult,\n type SyncShapeToTableOptions,\n type SyncShapeToTableResult,\n} from \"./types\";\n\nexport * from \"./types\";\n\n/**\n * Replication-stream headers Electric attaches to change messages but does not\n * declare on its `Header` type: `lsn` orders changes within the stream and\n * `last` marks the final change of an LSN. Single choke point for these\n * protocol assumptions.\n */\n/**\n * Maps the statically-resolved {@link ApplyStrategy} (ADR-0009 decision 3) onto the engine's\n * initial-backfill apply path. Undefined (no registry-supplied strategy) defaults to `copy`:\n * the COPY TEXT serializer round-trips every built-in type, so it is the safe no-brainer bootstrap.\n */\nfunction applyStrategyToInsertMethod(strategy: ApplyStrategy | undefined): InitialInsertMethod {\n switch (strategy) {\n case \"json\":\n return \"json\";\n case \"insert\":\n return \"insert\";\n default:\n return \"copy\";\n }\n}\n\nfunction readReplicationHeaders(headers: ChangeMessage[\"headers\"]): { lsn: bigint; isLastOfLsn: boolean } {\n const rawLsn: unknown = headers[\"lsn\"];\n\n return {\n lsn: typeof rawLsn === \"string\" ? BigInt(rawLsn) : BigInt(0),\n isLastOfLsn: headers[\"last\"] === true,\n };\n}\n\n/**\n * Electric's tagged-subquery `EventMessage` (ADR-0023) — `headers.event` is `move-out` | `move-in`,\n * carrying `patterns`. It is neither a change nor a control message, so `@electric-sql/client` exposes\n * no guard; we detect it by the `event` header. `MultiShapeStream` adds `.shape` like every message.\n */\ntype ShapeEventMessage = EventMessage & { shape: string };\n\nfunction isEventMessage(message: unknown): message is ShapeEventMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n typeof (message as { headers?: { event?: unknown } }).headers?.event === \"string\"\n );\n}\n\n/**\n * Construct the pgxsinkit sync engine over an ALREADY-created PGlite instance (ADR-0032 S1). The engine\n * is a plain module — not a create-time PGlite extension — so it demands only the minimal surface it\n * actually uses: a {@link PGliteInterface} (it runs its metadata DDL + apply commits through `pg.transaction`\n * / `pg.query` / `pg.exec`; it does NOT touch the `live` extension). It returns the `namespace` object (the\n * local-bookkeeping + shape-sync entry points the client attaches as `pg.electric`) plus an explicit\n * `close()` — the teardown the former extension's `close` hook ran when PGlite closed, now invoked\n * explicitly by the owner at the same moment (see `createSyncClient`'s `stop`/`destroy`).\n */\nexport async function createSyncEngine(pg: PGliteInterface, options?: ElectricSyncOptions) {\n const debug = options?.debug ?? false;\n // pgxsinkit-owned metadata namespace (ADR-0009 decision 6): this is our local bookkeeping (the\n // subscription-state table) and the sync-origin GUC (`<schema>.syncing`), not Electric's — so it\n // lives under our own schema, renamed from the upstream `electric` default.\n const metadataSchema = options?.metadataSchema ?? DEFAULT_METADATA_SCHEMA;\n // The schema name reaches raw GUC + DDL identifier positions below (no quoted-identifier form exists\n // there), so validate it at construction rather than trust caller input in those raw spots.\n assertValidMetadataSchema(metadataSchema);\n const streams: Array<{\n stream: MultiShapeStream<Record<string, Row<unknown>>>;\n aborter: AbortController;\n }> = [];\n\n const getShapeOptions = (shapes: SyncShapesToTablesOptions[\"shapes\"], shapeName: string) => {\n const shape = shapes[shapeName];\n if (!shape) {\n throw new Error(`Missing shape options for ${shapeName}`);\n }\n return shape;\n };\n\n const shapePerTableLock = new Map<string, void>();\n\n // Memoize the metadata DDL as a PROMISE, not a boolean: concurrent eager groups (`shape-sync.ts`\n // starts them with `Promise.all`) both call `initMetadataTables`, and a boolean set BEFORE the async\n // migration completed let the second caller return early and query the metadata tables before the DDL\n // had run. Storing the in-flight promise makes every concurrent caller await the same single migration.\n // Cleared on rejection so a transient DDL failure can be retried by a later start rather than caching a\n // rejected promise forever.\n let initMetadataTablesPromise: Promise<void> | undefined;\n const initMetadataTables = (): Promise<void> => {\n if (!initMetadataTablesPromise) {\n initMetadataTablesPromise = migrateSubscriptionMetadataTables({\n pg,\n metadataSchema,\n }).catch((error: unknown) => {\n initMetadataTablesPromise = undefined;\n throw error;\n });\n }\n return initMetadataTablesPromise;\n };\n\n const syncShapesToTables = async ({\n key,\n registry,\n shapes,\n initialInsertMethod,\n onInitialSync,\n onError,\n onSyncError,\n onSyncActivity,\n dbReady,\n bootStamp,\n maxCommitRetries = DEFAULT_MAX_COMMIT_RETRIES,\n commitRetryDelayMs = computeRetryDelayMs,\n }: SyncShapesToTablesOptions): Promise<SyncShapesToTablesResult> => {\n let unsubscribed = false;\n // Fresh-store prefetch overlap (ADR-0032 S4): the caller proved the store fresh and handed a `dbReady`\n // gate, so start the streams and buffer their catch-up into the memory inbox NOW — before the local\n // store's schema/journal/reconcile finish — and defer every DB touch (metadata DDL, the first commit)\n // until the gate lifts. Without it, the exact sequential path: init the metadata tables up front.\n const overlap = dbReady != null;\n if (!overlap) {\n await initMetadataTables();\n }\n\n // Resolve each shape's apply target ONCE at subscribe time (ADR-0029 D1/D2): the real projected\n // synced table, its columns, PKs, and model-derived types — the engine's per-message work is then a\n // pure builder over these resolved objects, never a per-message re-derivation or catalog probe.\n const targets = new Map<string, ApplyTarget>(\n Object.entries(shapes).map(([shapeName, shapeOptions]) => [\n shapeName,\n resolveApplyTarget(registry, shapeOptions.tableKey),\n ]),\n );\n const getTarget = (shapeName: string): ApplyTarget => {\n const target = targets.get(shapeName);\n if (!target) {\n throw new Error(`Missing apply target for ${shapeName}`);\n }\n return target;\n };\n // The synced table's physical identity — the per-table lock key and the tag-store `shape_table` key.\n const tableIdentity = (target: ApplyTarget) => {\n const { name, schema } = getTableConfig(target.table);\n return shapeTableId(schema, name);\n };\n\n Object.entries(shapes)\n .filter(([, shape]) => !shape.onMustRefetch)\n .forEach(([, shape]) => {\n if (shapePerTableLock.has(shape.tableKey)) {\n throw new Error(\"Already syncing shape for table \" + shape.tableKey);\n }\n shapePerTableLock.set(shape.tableKey);\n });\n\n let subState: SubscriptionState | null = null;\n\n // On the overlap path the store is provably fresh (the `freshStore` gate), so it carries no persisted\n // subscription state — AND its metadata tables do not exist yet (their DDL is deferred to the gate).\n // Skip the read entirely: `subState` stays null, so the group is (correctly) a new subscription.\n if (key !== null && !overlap) {\n subState = await getSubscriptionState({\n pg,\n metadataSchema,\n subscriptionKey: key,\n });\n if (debug && subState) {\n console.log(\"resuming from subscription state\", subState);\n }\n }\n\n const isNewSubscription = subState === null;\n\n // Each shape resolves its own apply method (ADR-0009 decisions 2 + 3 / ADR-0029 D1): an explicit\n // per-shape `initialInsertMethod` override wins, else the group-level default, else the registry's\n // build-time classification of the entry. So a consistency group with mixed column profiles applies\n // each table on its correct path.\n const shapeInsertMethod = new Map<string, InitialInsertMethod>(\n Object.entries(shapes).map(([shapeName, shapeOptions]) => {\n // Strategy precedence (ADR-0009 decisions 2+3 / ADR-0029 D1): an explicit per-shape override,\n // then the group-level default, then the registry's build-time classification of the entry.\n const entry = registry[shapeOptions.tableKey]!;\n const method =\n shapeOptions.initialInsertMethod ??\n initialInsertMethod ??\n applyStrategyToInsertMethod(classifyTableApplyStrategy(entry));\n return [shapeName, method];\n }),\n );\n\n // `useInsert` is per-shape, not shared: in a multi-shape group, one shape finishing its bulk\n // backfill must not flip every other shape onto plain `INSERT`. A shape uses its bulk path only\n // on a fresh subscription with a non-`insert` method; a resume starts already in insert mode.\n const useInsert = new Map<string, boolean>(\n Object.keys(shapes).map((shapeName) => [\n shapeName,\n !isNewSubscription || shapeInsertMethod.get(shapeName) === \"insert\",\n ]),\n );\n let onInitialSyncCalled = false;\n\n const maybeSignalInitialSync = () => {\n if (onInitialSync && !onInitialSyncCalled && multiShapeStream.isUpToDate) {\n onInitialSync();\n onInitialSyncCalled = true;\n }\n };\n\n // The Shape inbox (ADR-0014 / ISS-06): the pure, in-memory buffer + complete-LSN frontier for\n // this group's shapes. The engine keeps the commit queue, the apply, and the truncate set.\n const inbox = new ShapeInbox(Object.keys(shapes));\n\n // Live-tail sibling nudge (ADR-0031): a per-shape one-shot cache-buster token. The watchdog (below)\n // sets a token just before nudging a lagging sibling; `withNudgeBuster` (wrapping each shape's\n // fetchClient) consumes it on the sibling's next non-live catch-up so a CDN HIT cannot return the same\n // stale watermark and defeat the nudge. Empty on the steady path → the wrapper is a straight passthrough.\n const nudgeBusters = new Map<string, string>();\n\n const truncateNeeded = new Set<string>();\n // The committed frontier is a *running* variable, advanced after each successful commit — not\n // the boot-time `const` the upstream engine never advanced (which forced redundant empty\n // re-commits). `degraded` latches once commits exhaust their retries (ADR-0009 decision 5).\n let committedLsn: Lsn = subState?.last_lsn ?? BigInt(-1);\n let degraded = false;\n // Single-flight commit queue: at most one commit runs at a time; messages buffered while one\n // is in flight coalesce into the next run (re-armed via `commitRerun`).\n let commitInFlight: Promise<void> | null = null;\n let commitRerun = false;\n\n const aborter = new AbortController();\n Object.values(shapes)\n .filter((shapeOptions) => !!shapeOptions.shape.signal)\n .forEach((shapeOptions) => {\n shapeOptions.shape.signal!.addEventListener(\"abort\", () => aborter.abort(), {\n once: true,\n });\n });\n\n const multiShapeOptions: Record<string, ShapeStreamOptions<Row<unknown>>> = {};\n for (const [shapeName, shapeOptions] of Object.entries(shapes)) {\n const shapeMetadata = subState?.shape_metadata[shapeName];\n const streamOptions: ShapeStreamOptions<Row<unknown>> = {\n ...shapeOptions.shape,\n signal: aborter.signal,\n // Instrument every ShapeStream HTTP request (the read-path long-poll/catch-up) when debug is on;\n // a passthrough otherwise (see instrumentShapeFetch). Wraps any existing fetchClient rather than\n // replacing it, so auth/header injection on the shape's own fetchClient still runs. `withNudgeBuster`\n // is the OUTER wrapper (ADR-0031 live-tail nudge): it stamps the cache-buster onto the URL BEFORE\n // instrumentation runs, so the debug rail logs the busted URL (`BUSTED`) that actually hits the wire.\n fetchClient: withNudgeBuster(instrumentShapeFetch(shapeOptions.shape.fetchClient), nudgeBusters, shapeName),\n };\n\n if (shapeMetadata) {\n streamOptions.offset = shapeMetadata.offset;\n streamOptions.handle = shapeMetadata.handle;\n }\n\n multiShapeOptions[shapeName] = streamOptions;\n }\n\n const multiShapeStream = new MultiShapeStream<Record<string, Row<unknown>>>({\n shapes: multiShapeOptions,\n });\n\n // The commit gate (ADR-0032 S4). Open immediately on the sequential path; held closed on the overlap\n // path until `dbReady` resolves, so NOTHING writes to PGlite before the local schema exists. The inbox\n // is pure memory, so buffering catch-up behind this closed gate is safe — the only DB-bound work\n // (metadata DDL, then commits) waits for the gate.\n let dbGateOpen = !overlap;\n if (overlap) {\n // The streams' network side is starting now (subscribe below triggers the first fetch), overlapping\n // the caller's local boot phases. Name the shapes so the overlap is measurable on the boot rail.\n syncDebug(\"boot shape prefetch start\", { shapes: Object.keys(shapes) });\n }\n\n const getShapeStream = (shapeName: string) => {\n const stream = multiShapeStream.shapes[shapeName];\n if (!stream) {\n throw new Error(`Missing stream for ${shapeName}`);\n }\n return stream;\n };\n\n const insertMethods = {\n json: applyMessagesToTableWithJson,\n copy: applyMessagesToTableWithCopy,\n insert: applyInsertsToTable,\n } as const;\n\n // Apply everything buffered up to `targetLsn` in a single transaction, retrying with jittered\n // backoff on failure. Returns `true` once applied (and advances the running committed frontier);\n // returns `false` without advancing if the engine unsubscribed mid-flight or the commit\n // exhausted its retries (→ `degraded` + `onSyncError`, ADR-0009 decision 5). The drained\n // messages and the truncate snapshot are held across retries so a transient failure loses\n // nothing; the read cache never advances past an unapplied commit.\n const commitUpToLsn = async (targetLsn: Lsn): Promise<boolean> => {\n // PEEK (not drain) the buffered batch: it stays in the inbox until the transaction below actually\n // succeeds, and is only then ACKed (removed). A commit that exhausts its retries (→ `degraded`)\n // therefore HOLDS the drained batch in the buffer instead of losing it (ADR-0009 decision 5) — and\n // `enqueueCommit` refuses to run any newer commit while degraded, so a later LSN can never apply\n // over this held, unapplied batch. Recovery is a restart/refetch: the persisted offset was not\n // advanced, so the held batch re-streams from the same frontier.\n const messagesToCommit = inbox.peekUpTo(targetLsn);\n\n // Record every shape's reset epoch AT PEEK TIME (synchronously with the peeks, before the async\n // transaction). If a must-refetch + re-snapshot bumps a shape's epoch mid-commit, the acks below\n // skip that shape so its post-reset rebuild survives rather than being deleted/spliced away — see\n // ShapeInbox.ackUpTo / ackMoveOuts / ackMoveIns.\n const epochsAtPeek = inbox.snapshotEpochs();\n\n // Capture, per shape, whether it is still accepting snapshot (LSN-0) rows AT PEEK TIME. A shape in\n // snapshot acceptance (post-reset re-snapshot, or a brand-new shape before its first real lsn) can\n // have the SAME snapshot rows double-delivered by the racing recovery fetch loops — possibly across\n // separate commits — so its inserts are applied idempotently (upsert) rather than as plain\n // collision-surfacing inserts. Once a real lsn re-arms the dedup, this is false and the live-tail\n // plain-INSERT invariant (a genuine PK collision must surface, ADR-0014) is back in force.\n const snapshotModeAtPeek = new Map<string, boolean>(\n Object.keys(shapes).map((shapeName) => [shapeName, inbox.acceptsSnapshotRowsFor(shapeName)]),\n );\n\n // Snapshot the truncate set so a retried transaction still truncates; the per-shape flag is\n // cleared only once the commit has succeeded.\n const shapesToTruncate = new Set(truncateNeeded);\n\n // Peek the buffered tagged-subquery move-outs (ADR-0023) the same way: held in the buffer so a\n // retried/degraded commit still has them, ACKed only on success (by the exact peeked count, so a\n // move-out that arrived during a coalescing commit is not dropped).\n const moveOutsToCommit = new Map<string, MovePattern[][]>();\n // Peek the buffered tagged-subquery move-ins (ADR-0024) identically: a move-in snapshot row carries\n // no LSN; it is applied idempotently in the commit transaction and ACKed only on success.\n const moveInsToCommit = new Map<string, ChangeMessage<Row<unknown>>[]>();\n for (const shapeName of Object.keys(shapes)) {\n const pendingOut = inbox.peekMoveOuts(shapeName);\n if (pendingOut.length > 0) {\n moveOutsToCommit.set(shapeName, pendingOut);\n }\n const pendingIn = inbox.peekMoveIns(shapeName);\n if (pendingIn.length > 0) {\n moveInsToCommit.set(shapeName, pendingIn);\n }\n }\n\n const runCommit = () =>\n pg.transaction(async (tx) => {\n if (debug) {\n console.time(\"commit\");\n }\n\n // Tier ③ (ADR-0028 allow-list): a `SET LOCAL` GUC — the sync-origin `<schema>.syncing` flag\n // the apply trigger reads to distinguish streamed server truth from local writes. GUCs have\n // no tier-①/② builder form; the schema identifier is fixed at engine construction.\n await tx.exec(`SET LOCAL ${metadataSchema}.syncing = true;`);\n\n for (const [shapeName, initialMessages] of messagesToCommit.entries()) {\n const shape = getShapeOptions(shapes, shapeName);\n const target = getTarget(shapeName);\n const shapeMethod = shapeInsertMethod.get(shapeName)!;\n let messages = initialMessages;\n\n // ADR-0023: the shape's tag store key (synced table, schema-qualified).\n const shapeTable = tableIdentity(target);\n\n if (shapesToTruncate.has(shapeName)) {\n if (debug) {\n console.log(\"truncating table\", shapeTable);\n }\n if (shape.onMustRefetch) {\n await shape.onMustRefetch(drizzleOverPg(tx));\n } else {\n // ADR-0029 D4: a must-refetch wipe is engine cache maintenance, not server truth — so it\n // TRUNCATEs (tier ②; `TRUNCATE` has no Drizzle builder, the table object is interpolated)\n // rather than reacting via the per-row reconcile trigger. Correctness rides the reconcile\n // loop; TRUNCATE is O(1) and the re-snapshot inserts still fire the trigger.\n await drizzleOverPg(tx).execute(sql`TRUNCATE ${target.table}`);\n }\n // The re-snapshot rebuilds tags from scratch, so drop this shape's stale tag-set too\n // (ADR-0023 Slice 2: a must-refetch/​rebuild must not leave orphan tags).\n await clearShapeTags({ pg: tx, metadataSchema, shapeTable });\n }\n\n // ADR-0024: this shape's buffered move-in snapshot rows (a row ENTERING the shape). Their\n // tags are UNIONED first (a move-in adds a reason, it must not clear an independent grant's\n // tag) — and a regular change for the same row in this batch then authoritatively replaces\n // below, so union-then-replace converges either way.\n const moveInMessages = moveInsToCommit.get(shapeName) ?? [];\n if (moveInMessages.length > 0) {\n await addShapeRowTags({\n pg: tx,\n metadataSchema,\n shapeTable,\n messages: moveInMessages,\n primaryKey: target.primaryKey,\n });\n }\n\n // Maintain the tag-set from the RAW drained batch (ADR-0023) — before the data apply and\n // the move-out eviction, so an add-then-remove within one commit resolves correctly. Uses\n // `initialMessages` (the full batch) since the insert/​fold split below reduces `messages`.\n await applyShapeTagSync({\n pg: tx,\n metadataSchema,\n shapeTable,\n messages: initialMessages,\n primaryKey: target.primaryKey,\n });\n\n // ADR-0024: apply the move-in rows idempotently BEFORE the change fold, so a same-commit\n // update to a just-moved-in row lands on a present row. Upsert (not plain INSERT) because the\n // row may already be present via another grant or be re-delivered on a resume.\n if (moveInMessages.length > 0) {\n await applyUpsertsToTable({\n pg: tx,\n target,\n messages: moveInMessages,\n debug,\n });\n }\n\n if (!useInsert.get(shapeName)) {\n const initialInserts: InsertChangeMessage[] = [];\n const remainingMessages: ChangeMessage<Row<unknown>>[] = [];\n let foundNonInsert = false;\n for (const message of messages) {\n if (!foundNonInsert && message.headers.operation === \"insert\") {\n initialInserts.push(message as InsertChangeMessage);\n } else {\n foundNonInsert = true;\n remainingMessages.push(message);\n }\n }\n if (initialInserts.length > 0 && shapeMethod === \"copy\") {\n remainingMessages.unshift(initialInserts.pop()!);\n }\n messages = remainingMessages;\n\n if (initialInserts.length > 0) {\n await insertMethods[shapeMethod]({\n pg: tx,\n target,\n messages: initialInserts,\n debug,\n });\n\n useInsert.set(shapeName, true);\n }\n }\n\n // ADR-0014 Phase 3: fold this shape's drained batch to one net op per PK, then apply\n // three bulk statements in the order DELETE → INSERT → UPDATE. A re-created PK's delete\n // must precede its insert; every other PK lands in exactly one statement, so the rest of\n // the order is irrelevant within the (atomic) commit. The fold collapses same-PK runs, so\n // no bulk statement ever holds two rows for one PK — closing the `UPDATE … FROM` /\n // `json_to_recordset` join hazard (which would use one arbitrary matching row) by\n // construction. This replaces the previous one-SQL-statement-per-row steady-state loop.\n if (messages.length > 0) {\n const folded = foldChangeBatch(messages);\n\n if (folded.deletes.length > 0) {\n await applyBulkDeletesToTable({\n pg: tx,\n target,\n messages: folded.deletes,\n debug,\n });\n }\n if (folded.inserts.length > 0) {\n if (snapshotModeAtPeek.get(shapeName)) {\n // Snapshot-acceptance mode (post-reset re-snapshot / pre-first-lsn): the racing recovery\n // loops can re-deliver these exact snapshot rows, possibly in a later commit after this\n // shape's TRUNCATE flag has been consumed — so apply them idempotently (upsert), the same\n // posture as a move-in, rather than failing the commit on a PK collision.\n await applyUpsertsToTable({\n pg: tx,\n target,\n messages: folded.inserts,\n debug,\n });\n } else {\n await applyInsertsToTable({\n pg: tx,\n target,\n messages: folded.inserts,\n debug,\n });\n }\n }\n if (folded.updates.length > 0) {\n await applyBulkUpdatesToTable({\n pg: tx,\n target,\n messages: folded.updates,\n debug,\n });\n }\n }\n\n // ADR-0023: after the data + tag state is current, apply this shape's buffered move-outs —\n // withdraw the revoked tag and evict any row left with no tag (via the bulk-delete path, so\n // the reconcile trigger fires and the read model converges).\n const patternSets = moveOutsToCommit.get(shapeName);\n if (patternSets) {\n await applyShapeMoveOut({\n pg: tx,\n metadataSchema,\n shapeTable,\n target,\n patternSets,\n debug,\n });\n }\n }\n\n if (key) {\n await updateSubscriptionState({\n pg: tx,\n metadataSchema,\n subscriptionKey: key,\n shapeMetadata: Object.fromEntries(\n Object.keys(shapes).map((shapeName) => {\n const stream = getShapeStream(shapeName);\n return [\n shapeName,\n {\n handle: stream.shapeHandle!,\n offset: stream.lastOffset,\n },\n ];\n }),\n ),\n lastLsn: targetLsn,\n debug,\n });\n }\n\n // If we unsubscribed while this commit was in flight, discard it rather than persist\n // work during teardown. PGlite's `transaction()` skips its COMMIT once `tx.rollback()`\n // has closed the tx, so this rolls back both the applied rows and the subscription-state\n // advance; the (un-advanced) persisted offset means a later resume re-streams this batch.\n if (unsubscribed) {\n await tx.rollback();\n }\n });\n\n for (let attempt = 1; ; attempt++) {\n if (unsubscribed) {\n return false;\n }\n try {\n await runCommit();\n if (unsubscribed) {\n // The commit rolled itself back on unsubscribe (see runCommit); do not advance the\n // committed frontier, ACK the peeked buffer, or clear truncate flags for discarded work.\n return false;\n }\n committedLsn = targetLsn;\n // The transaction committed — now (and only now) remove the peeked batch from the inbox, passing\n // the peek-time epochs so a shape reset mid-commit is skipped (its rebuild survives). Move-outs/\n // move-ins are ACKed by the exact peeked count so anything that arrived during a coalescing\n // commit survives for the next run.\n inbox.ackUpTo(targetLsn, epochsAtPeek);\n for (const [shapeName, patternSets] of moveOutsToCommit) {\n inbox.ackMoveOuts(shapeName, patternSets.length, epochsAtPeek.get(shapeName) ?? inbox.epochFor(shapeName));\n }\n for (const [shapeName, moveInMessages] of moveInsToCommit) {\n inbox.ackMoveIns(\n shapeName,\n moveInMessages.length,\n epochsAtPeek.get(shapeName) ?? inbox.epochFor(shapeName),\n );\n }\n for (const shapeName of shapesToTruncate) {\n truncateNeeded.delete(shapeName);\n }\n if (debug) console.timeEnd(\"commit\");\n maybeSignalInitialSync();\n return true;\n } catch (error) {\n if (unsubscribed) {\n return false;\n }\n if (attempt >= maxCommitRetries) {\n degraded = true;\n onSyncError?.(error instanceof Error ? error : new Error(String(error)));\n return false;\n }\n await new Promise((resolve) => setTimeout(resolve, commitRetryDelayMs(attempt)));\n }\n }\n };\n\n const lowestCompleteLsn = (): Lsn => inbox.lowestCompleteLsn();\n\n // ─── Live-tail sibling nudge (ADR-0031 live-tail completion) ──────────────────────────────────────\n // The catch-up alignment (ADR-0031 in shape-inbox.ts) fixed this class of stall at BOOT: quiet shapes'\n // stale cached watermarks no longer hold a busy shape's backfill. On the LIVE tail the same shape holds\n // recur — a change batch lands on a busy shape at LSN L, but the group commits only at the min effective\n // frontier, so the batch stays buffered until every quiet sibling's PARKED long-poll returns a fresh\n // `global_last_seen_lsn` (~41s on Electric Cloud). This watchdog closes that live-tail gap: when a batch\n // is gated (its `batchMaxLsn > committedLsn`), it nudges each lagging sibling — aborting its parked poll\n // and forcing an immediate NON-live catch-up (`forceDisconnectAndRefresh`), which returns a fresh\n // watermark in ~sub-second. The group frontier then reaches L and the normal commit path (driven by the\n // up-to-date arrivals, NOT by this watchdog) fires. Atomicity is untouched: commits still happen only at\n // the group min frontier. The one-shot cache-buster (`nudgeBusters` + `withNudgeBuster`) defends each\n // nudged catch-up against a CDN HIT that would echo the stale watermark. Bounded to NUDGE_MAX_ROUNDS so a\n // genuinely-dead or still-legitimately-polling sibling degrades to the old wait-out-the-poll behavior\n // rather than a refresh storm.\n const nudgeInFlight = new Map<string, Promise<void>>();\n let nudgeTargetLsn: Lsn = BigInt(-1);\n let nudgeWatchdogRunning = false;\n\n // Void-called from the subscribe callback (never awaited — it must not backpressure the stream). Raises\n // the shared target and, if not already running, runs bounded rounds until the frontier reaches it, the\n // group tears down / degrades / re-closes its gate, or the rounds exhaust. Single-flight: a concurrent\n // gated batch just raises `nudgeTargetLsn` and returns. Wrapped so it can never throw unhandled.\n const runNudgeWatchdog = async (targetLsn: Lsn): Promise<void> => {\n if (targetLsn > nudgeTargetLsn) {\n nudgeTargetLsn = targetLsn;\n }\n if (nudgeWatchdogRunning) {\n return;\n }\n nudgeWatchdogRunning = true;\n try {\n // Pre-alignment (boot catch-up, before ADR-0031 lays the commit floors) the nudge is pure noise:\n // the alignment itself will commit the gated backfill the moment every shape reports, and firing\n // busted catch-ups mid-boot only contends with the boot requests. The floors survive later resets,\n // so this gate closes exactly once — the live tail is always past it.\n if (inbox.alignedFloor() < BigInt(0)) {\n return;\n }\n // Resolved / torn-down / gated-shut → nothing to nudge; the up-to-date arrival itself runs the\n // commit, so the watchdog never commits.\n const resolvedOrStopped = (): boolean =>\n unsubscribed || degraded || !dbGateOpen || lowestCompleteLsn() >= nudgeTargetLsn;\n\n // Hold-persistence grace: a cross-shape transaction's sibling halves arrive milliseconds apart,\n // so EVERY grouped commit passes through a transient held instant — nudging on it would abort\n // the sibling poll that is about to deliver the other half (the sync-e2e regression). Only a\n // hold that survives this grace is a real quiet-sibling park worth nudging.\n for (let waited = 0; waited < NUDGE_HOLD_GRACE_MS; waited += NUDGE_ROUND_GRACE_MS) {\n await new Promise((resolve) => setTimeout(resolve, NUDGE_ROUND_GRACE_MS));\n if (resolvedOrStopped()) {\n return;\n }\n }\n\n for (let round = 1; round <= NUDGE_MAX_ROUNDS; round++) {\n if (resolvedOrStopped()) {\n return;\n }\n for (const shapeName of Object.keys(shapes)) {\n // A shape still catching up advances on its own — only nudge one already in its live tail.\n if (!inbox.hasReportedUpToDate(shapeName)) continue;\n if (inbox.effectiveLsnFor(shapeName) >= nudgeTargetLsn) continue;\n if (nudgeInFlight.has(shapeName)) continue;\n // `forceDisconnectAndRefresh` is declared on the real ShapeStream, but a mocked/typed surface may\n // omit it — reach it structurally and skip (with a rail line) when absent.\n const stream = getShapeStream(shapeName) as { forceDisconnectAndRefresh?: () => Promise<void> };\n if (typeof stream.forceDisconnectAndRefresh !== \"function\") {\n syncDebug(\"live-tail sibling nudge unavailable\", { shape: shapeName });\n continue;\n }\n // Arm the one-shot cache-buster BEFORE the refresh so the forced catch-up carries it.\n nudgeBusters.set(shapeName, crypto.randomUUID());\n syncDebug(\"live-tail sibling nudge\", { shape: shapeName, target: String(nudgeTargetLsn), round });\n const refresh = stream\n .forceDisconnectAndRefresh()\n .catch((err: unknown) =>\n syncDebug(\"live-tail sibling nudge failed\", { shape: shapeName, error: String(err) }),\n )\n .finally(() => {\n nudgeInFlight.delete(shapeName);\n });\n nudgeInFlight.set(shapeName, refresh);\n }\n // Nothing to nudge and nothing in flight → exit QUIETLY (no exhaustion line). This is the routine\n // pre-alignment case: a gated batch during catch-up has siblings that have not yet reported\n // up-to-date, and those advance on their own — spinning the remaining rounds would only delay-loop\n // and print a misleading \"exhausted\" line on every boot rail. The \"held by group frontier\" line\n // already told the story.\n if (nudgeInFlight.size === 0) {\n return;\n }\n // Wait for this round's forced catch-ups to actually land and advance the frontier. The refresh\n // promises settle before the refreshed response does (measured), so awaiting them alone would\n // re-nudge into still-in-flight requests — poll the frontier instead, bounded per round, and\n // break out the moment the target is reached.\n await Promise.all([...nudgeInFlight.values()]);\n for (let waited = 0; waited < NUDGE_ROUND_WAIT_MS; waited += NUDGE_ROUND_GRACE_MS) {\n await new Promise((resolve) => setTimeout(resolve, NUDGE_ROUND_GRACE_MS));\n if (resolvedOrStopped()) {\n return;\n }\n }\n }\n // Rounds exhausted and the frontier is still short: a sibling is dead or genuinely mid-poll. Degrade\n // to the old behavior (wait out its live long-poll) rather than nudge forever.\n syncDebug(\"live-tail nudge exhausted; waiting on sibling live polls\", {\n target: String(nudgeTargetLsn),\n frontier: String(lowestCompleteLsn()),\n });\n } catch (err) {\n syncDebug(\"live-tail nudge watchdog error\", { error: String(err) });\n } finally {\n nudgeWatchdogRunning = false;\n }\n };\n\n // Drain buffered changes up to the current complete frontier, one commit at a time, looping\n // while fresh messages keep arriving (so commits coalesce). Returns early on `degraded` — a held\n // commit is not retried here; recovery is a later message/refetch or a restart.\n const runCommitLoop = async (): Promise<void> => {\n do {\n commitRerun = false;\n const target = lowestCompleteLsn();\n const isCommitNeeded = target > committedLsn;\n const isMustRefetchAndCatchingUp = target >= committedLsn && truncateNeeded.size > 0;\n // A buffered move-out (ADR-0023) or move-in (ADR-0024) must be committed even if no change\n // advanced the frontier — the revocation/grant has to land. Their `up-to-date` normally advances\n // `target`, but don't rely on that (move/event messages carry no LSN).\n const hasPendingMoves = target >= committedLsn && (inbox.hasPendingMoveOuts() || inbox.hasPendingMoveIns());\n // ADR-0031: a LATE-arriving change at or below an already-committed target must still commit. The\n // aligned commit floor lets `ingestChange` accept a change below the floor (its dedup frontier is\n // the raw `completeLsns`, unmoved by the floor), so such a change can land AFTER the group frontier\n // has already reached — or passed — its LSN, where no frontier advance would trigger a commit for\n // it. Committing at `target === committedLsn` is safe: it mirrors the moves path, which already\n // calls `commitUpToLsn(target)` with no frontier advance. (At `target > committedLsn` this overlaps\n // `isCommitNeeded` — harmless; the expression stays simple.)\n const hasLateArrivals = target >= committedLsn && inbox.hasBufferedChangesAtOrBelow(target);\n if (isCommitNeeded || isMustRefetchAndCatchingUp || hasPendingMoves || hasLateArrivals) {\n const applied = await commitUpToLsn(target);\n if (!applied) {\n return;\n }\n } else {\n maybeSignalInitialSync();\n }\n } while (commitRerun);\n };\n\n // Single-flight: at most one commit loop runs. A message arriving while one is running buffers\n // synchronously (above) and re-arms the loop via `commitRerun`; `commitInFlight` is cleared\n // inside the same async body — before its promise resolves — so an enqueue can never observe a\n // stale in-flight handle and resolve without committing its messages.\n const enqueueCommit = (): Promise<void> => {\n // ADR-0009 decision 5: once a commit exhausts its retries the engine latches `degraded` and\n // REFUSES to run any further commit. `commitUpToLsn` peeks (never drains) the buffer, so the\n // unapplied batch is still held; refusing later commits guarantees a newer LSN can never apply\n // over that held batch (the divergence the destructive drain allowed). The buffer keeps\n // accumulating incoming messages harmlessly; recovery is a restart/refetch, which re-streams the\n // held frontier because the persisted offset was never advanced. Note the commit-await backpressure\n // is intentionally absent while degraded — the inbox grows at the stream's rate until recovery,\n // which is the accepted cost of ADR-0009's documented \"hold the buffer\" posture.\n if (degraded) {\n return commitInFlight ?? Promise.resolve();\n }\n if (commitInFlight) {\n commitRerun = true;\n return commitInFlight;\n }\n commitInFlight = (async () => {\n try {\n await runCommitLoop();\n } finally {\n commitInFlight = null;\n }\n })();\n return commitInFlight;\n };\n\n multiShapeStream.subscribe(async (messages) => {\n if (unsubscribed) {\n return;\n }\n // A delivered batch means a fetch just succeeded — the read path is alive (ADR-0013 Phase 3),\n // so the runtime can clear an auth-needed status once a fresh token starts working again.\n onSyncActivity?.();\n if (debug) {\n console.log(\"received messages\", messages.length);\n }\n // Receive-path latency probe: a batch carrying real change rows is the moment Electric delivered\n // a write to this subscriber (the writer's own echo, or another browser's edit fanning in). The\n // gap from here to the commit finishing is the local apply cost.\n const changeCount = messages.reduce((n, message) => (isChangeMessage(message) ? n + 1 : n), 0);\n if (changeCount > 0) {\n syncDebug(\"sync received change batch from Electric\", { changes: changeCount });\n }\n // Boot observability (ADR-0034): one delivery = one shape-stream response. Records the fetch (network)\n // gap since the last settle plus this batch's request + change-row counts. No-op post-ready (frozen).\n bootStamp?.onBatchDelivered(changeCount);\n const commitStartedAt = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n\n // The max LSN over the change rows this batch COMPLETED (routed to `ingestChange` with `isLastOfLsn`;\n // move-in rows carry no lsn and are excluded). It is what the batch needs the group frontier to reach\n // to actually commit — the truth test for the \"applied\" vs \"held\" rail line below. -1 if none.\n let batchMaxLsn: Lsn = BigInt(-1);\n\n messages.forEach((message) => {\n if (isChangeMessage(message)) {\n // A tagged-subquery MOVE-IN row (ADR-0024): an existing row ENTERING the shape because a grant\n // was added. Electric delivers it as a snapshot insert flagged `is_move_in` with NO `lsn`/`last`\n // (it is not a replication-stream change), so the `ingestChange` dedup — which floors a missing\n // lsn to 0 — would treat it as already-seen and drop it once the frontier passed 0. Route it to\n // its own buffer, applied idempotently at the next commit (the trailing `up-to-date`).\n if (message.headers[\"is_move_in\"] === true) {\n inbox.ingestMoveIn(message.shape, message);\n } else {\n const { lsn, isLastOfLsn } = readReplicationHeaders(message.headers);\n inbox.ingestChange(message.shape, message, lsn, isLastOfLsn);\n if (isLastOfLsn && lsn > batchMaxLsn) {\n batchMaxLsn = lsn;\n }\n }\n } else if (isControlMessage(message)) {\n switch (message.headers.control) {\n case \"up-to-date\": {\n if (debug) {\n console.log(\"received up-to-date\", message);\n }\n if (typeof message.headers.global_last_seen_lsn !== \"string\") {\n throw new Error(\"global_last_seen_lsn is not a string\");\n }\n // ADR-0031: `ingestUpToDate` returns true ONLY on the transition where this control message\n // completed the group (every shape has now reported up-to-date) and the inbox aligned the\n // commit floors. Surface that single moment on the debug rail so a \"stale board at load that\n // rearranges itself\" symptom is diagnosable — the floor it aligned to is the group head.\n if (inbox.ingestUpToDate(message.shape, BigInt(message.headers.global_last_seen_lsn))) {\n syncDebug(\"catch-up watermark aligned\", { floor: String(inbox.alignedFloor()) });\n }\n break;\n }\n case \"must-refetch\": {\n if (debug) {\n console.log(\"received must-refetch\", message);\n }\n // Surface the expired-handle / rewind event on the syncDebug rail too (the legacy `debug`\n // option only console.logs it): must-refetch is the trigger for the truncate + re-snapshot\n // recovery, so it must be visible when diagnosing a convergence loss in a live app.\n syncDebug(\"must-refetch received\", { shape: message.shape });\n inbox.resetShape(message.shape);\n truncateNeeded.add(message.shape);\n break;\n }\n }\n } else if (isEventMessage(message)) {\n // ADR-0023: a tagged-subquery move-out — a grant was revoked, so the rows it kept in the shape\n // must be evicted. Buffer the patterns; the eviction runs in the next commit (decision 3).\n // `MultiShapeStream`'s callback type does not declare `EventMessage` (the prior guards narrow\n // `message` to `never` here), so reach the runtime-present event through an explicit cast.\n const eventMessage = message as unknown as ShapeEventMessage;\n if (eventMessage.headers.event === \"move-out\") {\n if (debug) {\n console.log(\"received move-out\", eventMessage);\n }\n inbox.ingestMoveOut(eventMessage.shape, eventMessage.headers.patterns);\n }\n // A `move-in` EventMessage (ADR-0024) needs no action here: its newly-matched rows arrive in the\n // same batch as snapshot inserts flagged `is_move_in`, which the change branch routes to the\n // move-in buffer. The event's `patterns` are redundant with those inserts' `tags`.\n }\n });\n\n // Buffering above is synchronous. On the overlap path, while the commit gate is still closed the\n // batch stays in the memory inbox (its LSN frontier + catch-up watermarks still advance from the\n // ingest above) and the callback returns WITHOUT awaiting a commit — so the stream keeps fetching\n // catch-up and does not stall behind the local boot phases. Once the gate lifts, the deferred commit\n // train (below) drains everything buffered. On the sequential path the gate is already open, so this\n // is the unchanged path: enqueue the single-flight commit and await it (the natural backpressure that\n // bounds the buffer — replacing the old fire-and-forget commit + `setTimeout(0)` race).\n if (dbGateOpen) {\n const applyStartedAt = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n await enqueueCommit();\n // Boot observability (ADR-0034): the apply (commit-into-PGlite) wall for this delivery.\n bootStamp?.onApply((typeof performance !== \"undefined\" ? performance.now() : Date.now()) - applyStartedAt);\n if (changeCount > 0) {\n // Truthful rail (ADR-0031): the \"applied\" line only fires when this batch's completed changes\n // actually landed (its `batchMaxLsn` is at or below the advanced `committedLsn`). Otherwise the\n // group frontier had not reached them — the batch is BUFFERED behind a quiet sibling's watermark —\n // so say so, and kick the live-tail sibling nudge to shorten that hold (void: never backpressure\n // the stream).\n if (batchMaxLsn <= committedLsn) {\n const elapsed = (typeof performance !== \"undefined\" ? performance.now() : Date.now()) - commitStartedAt;\n syncDebug(\"sync applied change batch to local store\", { changes: changeCount, ms: Math.round(elapsed) });\n } else {\n syncDebug(\"sync change batch held by group frontier\", {\n changes: changeCount,\n heldLsn: String(batchMaxLsn),\n frontier: String(lowestCompleteLsn()),\n });\n void runNudgeWatchdog(batchMaxLsn);\n }\n }\n }\n }, onError);\n\n // Fresh-store prefetch overlap (ADR-0032 S4): the moment the caller signals the local store is ready\n // (schema exec + journal recovery + store-version reconcile done), run the deferred metadata DDL, open\n // the commit gate, and drain everything the streams buffered during the window in one commit train. The\n // ADR-0031 catch-up watermarks were aligned by the ingests above as the up-to-dates arrived, so this\n // drain commits to the aligned floor and `onInitialSync` fires exactly as on the sequential path.\n if (overlap) {\n void dbReady!.then(async () => {\n if (unsubscribed) {\n return;\n }\n // The metadata tables' DDL was deferred past the gate (the store had no schema when the streams\n // started); create them now, before the first commit needs the subscription-state table.\n await initMetadataTables();\n dbGateOpen = true;\n syncDebug(\"boot commits opened\");\n // Boot observability (ADR-0034): on the overlap path the buffered catch-up drains here (not in a\n // subscribe callback), so stamp the drain's apply wall into the group's accumulator.\n const drainStartedAt = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n await enqueueCommit();\n bootStamp?.onApply((typeof performance !== \"undefined\" ? performance.now() : Date.now()) - drainStartedAt);\n });\n }\n\n streams.push({\n stream: multiShapeStream,\n aborter,\n });\n\n const unsubscribe = () => {\n if (debug) {\n console.log(\"unsubscribing\");\n }\n unsubscribed = true;\n multiShapeStream.unsubscribeAll();\n aborter.abort();\n for (const shape of Object.values(shapes)) {\n shapePerTableLock.delete(shape.tableKey);\n }\n };\n\n return {\n unsubscribe,\n get isUpToDate() {\n // Never report up-to-date while a commit is pending or after going degraded (ADR-0009\n // decision 5): the read cache must not claim to match the server on an unapplied commit. Nor while\n // the overlap commit gate is still closed (ADR-0032 S4): the stream may already be `isUpToDate` on\n // the network side while its catch-up is still buffered, unapplied, in the memory inbox.\n return dbGateOpen && !degraded && commitInFlight === null && multiShapeStream.isUpToDate;\n },\n streams: Object.fromEntries(\n Object.keys(shapes).map((shapeName) => [shapeName, getShapeStream(shapeName)]),\n ) as SyncShapesToTablesResult[\"streams\"],\n };\n };\n\n const syncShapeToTable = async (options: SyncShapeToTableOptions): Promise<SyncShapeToTableResult> => {\n // ADR-0029 D6: thin sugar over the group form, forwarding the same entry-based options. The\n // per-shape `initialInsertMethod` (if any) rides through; the group form resolves the backfill\n // strategy from the registry entry when it is absent.\n const multiShapeSub = await syncShapesToTables({\n registry: options.registry,\n shapes: {\n shape: {\n shape: options.shape,\n tableKey: options.tableKey,\n onMustRefetch: options.onMustRefetch,\n ...(options.initialInsertMethod ? { initialInsertMethod: options.initialInsertMethod } : {}),\n },\n },\n key: options.shapeKey,\n onInitialSync: options.onInitialSync,\n onError: options.onError,\n onSyncError: options.onSyncError,\n maxCommitRetries: options.maxCommitRetries,\n commitRetryDelayMs: options.commitRetryDelayMs,\n });\n\n return {\n unsubscribe: multiShapeSub.unsubscribe,\n get isUpToDate() {\n return multiShapeSub.isUpToDate;\n },\n stream: (() => {\n const stream = multiShapeSub.streams[\"shape\"];\n if (!stream) {\n throw new Error(\"Missing stream for shape\");\n }\n return stream;\n })() as SyncShapeToTableResult[\"stream\"],\n };\n };\n\n const deleteSubscription = async (key: string) => {\n await deleteSubscriptionState({\n pg,\n metadataSchema,\n subscriptionKey: key,\n });\n };\n\n const namespaceObj = {\n initMetadataTables,\n syncShapesToTables,\n syncShapeToTable,\n deleteSubscription,\n };\n\n const close = async () => {\n for (const { stream, aborter } of streams) {\n stream.unsubscribeAll();\n aborter.abort();\n }\n };\n\n return {\n namespace: namespaceObj,\n close,\n };\n}\n\n/**\n * The pgxsinkit sync engine handle: the {@link SyncNamespaceObj} the client attaches as `pg.electric`,\n * plus the explicit `close()` teardown. Derived from {@link createSyncEngine}'s real return so the type\n * follows the object.\n */\nexport type SyncEngine = Awaited<ReturnType<typeof createSyncEngine>>;\nexport type SyncNamespaceObj = SyncEngine[\"namespace\"];\n\nexport type PGliteWithSync = PGliteInterface & {\n sync: SyncNamespaceObj;\n};\n",
135
142
  "// Live-tail sibling nudge (ADR-0031 live-tail completion). The engine commits a consistency group\n// atomically at the group's lowest effective frontier (the MIN over per-shape `max(rawFrontier,\n// commitFloor)`; see shape-inbox.ts). On the LIVE tail, when a change batch arrives on a busy shape at\n// LSN L, a quiet sibling shape's frontier only advances when its parked long-poll returns — up to ~41s on\n// Electric Cloud — so the busy shape's batch stays buffered, unapplied, for that whole hold. The nudge\n// aborts those parked polls and forces an immediate NON-live catch-up on each lagging sibling, which\n// returns a fresh `global_last_seen_lsn` in ~sub-second; the group frontier then reaches L and the batch\n// commits. Commit atomicity is untouched — commits still fire only at the group min frontier — this only\n// shortens how long a gated batch waits for its siblings' watermarks.\n//\n// This module holds the two pieces that are pure and side-effect-free (so a plain unit test can exercise\n// them without dragging PGlite/Electric in through the engine module): the bounded-round constants and the\n// one-shot cache-buster fetch wrapper. The stateful, per-group watchdog itself lives in the engine's\n// per-group scope (index.ts), where it can read the inbox frontiers and reach the live shape streams.\n\n/**\n * How long a hold must PERSIST before the first nudge round fires. A cross-shape transaction's halves\n * arrive milliseconds apart even on a healthy stack, so every grouped commit passes through a\n * transient \"held\" instant — nudging on it immediately ABORTS the sibling's long-poll that was about\n * to deliver the other half, turning a millisecond hold into an abort/refetch disruption loop\n * (regression caught by the sync-e2e integration lane on local Electric). A hold that outlives this\n * grace is the real thing: a quiet sibling parked in a multi-second poll. On Electric Cloud this adds\n * ~1s to a path that saves ~40s; on local stacks it means the nudge simply never fires.\n */\nexport const NUDGE_HOLD_GRACE_MS = 1_000;\n\n/**\n * Max nudge rounds before a dead / genuinely-still-polling sibling degrades back to the old behavior\n * (wait out its live long-poll) instead of being nudged forever — so a stuck sibling never becomes a\n * refresh storm.\n */\nexport const NUDGE_MAX_ROUNDS = 3;\n\n/**\n * Polling step while waiting for a nudge round's forced catch-ups to advance the group frontier. The\n * `forceDisconnectAndRefresh()` promise settles BEFORE the refreshed catch-up response lands (field\n * measurement: round 2 fired ~750ms into round 1's still-in-flight requests when the wait keyed off that\n * promise alone), so the watchdog instead polls the frontier at this step, up to\n * {@link NUDGE_ROUND_WAIT_MS} per round, breaking out the moment the target is reached.\n */\nexport const NUDGE_ROUND_GRACE_MS = 100;\n\n/**\n * Max wait per nudge round for the forced catch-ups to return and advance the frontier. A nudged\n * catch-up measures ~0.9–1.4s through a warm deployed edge proxy but >3.5s against a cold one — and\n * a next round's refresh ABORTS a still-in-flight round (the abort-and-reconnect is the mechanism),\n * so an early re-nudge throws away an almost-done response. The wait therefore covers the cold-edge\n * tail; worst case to exhaustion stays NUDGE_MAX_ROUNDS × this ≈ 12s, still far under a ~41s hold.\n */\nexport const NUDGE_ROUND_WAIT_MS = 4_000;\n\n/** The request URL of a `fetch` first argument, in any of its accepted forms; undefined if unreadable. */\nfunction requestUrl(input: Parameters<typeof fetch>[0]): string | undefined {\n if (typeof input === \"string\") return input;\n if (input instanceof URL) return input.toString();\n if (typeof input === \"object\" && input !== null && \"url\" in input) {\n return (input as { url: string }).url;\n }\n return undefined;\n}\n\n/**\n * Wrap a `fetchClient` so a pending one-shot nudge token defeats the CDN on the nudged sibling's catch-up.\n *\n * A nudge's `forceDisconnectAndRefresh` issues a NON-live catch-up (Electric sets `canLongPoll: false`),\n * which is CDN-cacheable — a HIT would return the SAME stale watermark that made the sibling lag, defeating\n * the nudge. So the watchdog drops a per-shape token into `nudgeBusters` just before it nudges; this wrapper\n * consumes that token on the sibling's next NON-live request, appending `cache-buster=<token>` to force a\n * CDN miss. It is one-shot (the token is deleted on use) and skips LIVE (`live=true`) long-polls — the token\n * is meant for the catch-up that follows the aborted poll, not the poll itself, which is left to be retained\n * for that catch-up. An already-present `cache-buster` param is overwritten. When no token is pending this is\n * a straight passthrough, so the off-path pays only this closure.\n *\n * Exported for unit testing; composed in the engine as the OUTER wrapper around `instrumentShapeFetch`, so\n * the buster stamps the URL BEFORE instrumentation logs it (the debug rail then shows `BUSTED`).\n */\nexport function withNudgeBuster(\n fetchClient: typeof fetch,\n nudgeBusters: Map<string, string>,\n shapeName: string,\n): typeof fetch {\n const wrapped = (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]): Promise<Response> => {\n const token = nudgeBusters.get(shapeName);\n if (token === undefined) {\n return fetchClient(input, init);\n }\n const raw = requestUrl(input);\n if (raw === undefined) {\n return fetchClient(input, init);\n }\n const url = new URL(raw);\n // A live long-poll is the parked request the nudge aborts, not the catch-up that carries the fresh\n // watermark — leave it (and the token) untouched so the token lands on the following catch-up.\n if (url.searchParams.get(\"live\") === \"true\") {\n return fetchClient(input, init);\n }\n // One-shot: consume the token and stamp this catch-up URL (set overwrites any existing param).\n nudgeBusters.delete(shapeName);\n url.searchParams.set(\"cache-buster\", token);\n const busted = url.toString();\n if (typeof input === \"string\" || input instanceof URL) {\n return fetchClient(busted, init);\n }\n // A Request carries method/headers/body that must survive the URL swap — rebuild from it.\n return fetchClient(new Request(busted, input), init);\n };\n // `typeof fetch` (Bun's global) carries a `preconnect` member the wrapper neither has nor needs — the\n // ShapeStream only ever invokes fetchClient as a plain fetch — so the shape-compatible cast is safe.\n return wrapped as typeof fetch;\n}\n",
136
143
  "import type { ChangeMessage, MovePattern, Row } from \"@electric-sql/client\";\n\nimport type { InsertChangeMessage, Lsn } from \"./types\";\n\n/**\n * The Shape inbox (ADR-0014 / ISS-06): the pure, in-memory staging buffer between a shape's\n * Electric subscription and the Sync applier. It buffers each shape's change messages keyed by\n * LSN, tracks each shape's complete-LSN frontier, and drains everything up to a target LSN for the\n * applier to write. No database I/O lives here — that is exactly what makes it (and the ADR-0014\n * per-PK fold that will live here) property-testable against an ordered per-row apply oracle.\n *\n * One inbox owns all shapes in a consistency group; the group commits atomically at the lowest\n * complete frontier across its shapes ({@link lowestCompleteLsn}). `must-refetch` truncation stays\n * with the applier (the inbox only drops the affected shape's buffer via {@link resetShape}).\n *\n * COMMIT WATERMARK vs DEDUP FRONTIER (ADR-0031) — the load-bearing separation. Two per-shape LSNs live\n * here and they are deliberately NOT the same number:\n *\n * - {@link completeLsns} — the SOLE dedup threshold. {@link ingestChange} drops any change at or below\n * it as already-seen. Nothing else may narrow what the inbox accepts; a change below a shape's floor\n * (below) but above its raw frontier is still buffered, never dropped.\n * - {@link commitFloors} — a per-shape COMMIT watermark laid down once per catch-up completion (see\n * {@link ingestUpToDate}'s alignment). It only ever RAISES a shape's effective commit frontier in\n * {@link lowestCompleteLsn}; it never gates ingestion.\n *\n * Why the two must be separate: Electric's catch-up (non-live) shape responses are CDN-cacheable\n * (`s-maxage`, `stale-while-revalidate`), and the `up-to-date` control message — with its\n * `global_last_seen_lsn` watermark — rides INSIDE that cached body. So a quiet shape's cached catch-up\n * can assert a STALE watermark (captured before a busy sibling shape's newer writes), which drags the\n * group min-frontier below changes already delivered on the busy shape, holding them buffered until the\n * quiet shape's first LIVE long-poll returns a fresh watermark (~tens of seconds on Electric Cloud). The\n * alignment lifts the commit floors to the freshest ASSERTED global head so those changes commit at\n * catch-up completion — while the dedup frontier stays put, so a late sub-floor change from a shape whose\n * cached catch-up omitted it is still ingested and committed rather than dropped.\n */\nexport class ShapeInbox {\n // Per shape: buffered change messages keyed by their LSN, kept in arrival order within an LSN.\n private readonly changes = new Map<string, Map<Lsn, ChangeMessage<Row<unknown>>[]>>();\n // Per shape: the highest LSN known complete (every change at or below it has been received).\n private readonly completeLsns = new Map<string, Lsn>();\n // Per shape: buffered `move-out` events (ADR-0023), one pattern set per event. The event carries no\n // LSN, so it cannot key `changes`; it is drained and applied at the next commit (the `up-to-date`\n // that follows it), in the same transaction as that frontier's changes.\n private readonly moveOuts = new Map<string, MovePattern[][]>();\n // Per shape: buffered `move-in` snapshot rows (ADR-0024). A move-in row (`is_move_in`) is a row\n // ENTERING the shape; Electric delivers it as a snapshot insert with NO `lsn`/`last`, so it cannot\n // key `changes` either (and the change dedup, which floors a missing lsn to 0, would drop it once the\n // frontier passed 0). Drained and applied — idempotently — at the next commit, like the move-outs.\n private readonly moveIns = new Map<string, ChangeMessage<Row<unknown>>[]>();\n // Per shape: a reset epoch, bumped every time {@link resetShape} rewinds a shape (must-refetch). The\n // commit path records each shape's epoch at PEEK time and passes it back to the acks; an ack no-ops for\n // any shape whose epoch has since changed. This closes the mid-commit-reset hole: if a must-refetch +\n // re-snapshot arrives for shape B WHILE a commit that peeked B is in flight, B's frontier is rewound and\n // its buffers replaced with post-reset content; without the epoch guard the succeeding commit's\n // `ackUpTo`/`ackMove*` would delete/splice that never-peeked post-reset content, leaving B truncated-empty.\n private readonly epochs = new Map<string, number>();\n // Per shape: whether a snapshot (LSN-0) row is currently accepted PAST the dedup frontier. Set on\n // registration and every {@link resetShape} (must-refetch); re-armed (cleared) the first time a change\n // with a REAL lsn (> 0) is ingested for the shape. Invariant: after a reset — and on a brand-new shape\n // before any real replication LSN has been seen — a re-snapshot's rows are floored to LSN 0, yet the\n // frontier may already sit at a large LSN (a racing bare `up-to-date` advanced it before the rows\n // landed). The LSN-0 dedup ({@link ingestChange}) would then drop the whole re-snapshot. So while this\n // flag is set, LSN-0 rows bypass the dedup; the first real lsn (> 0) proves the stream has moved past\n // the snapshot into the live tail, and re-arms the dedup. The re-snapshot's rows reaching the applier\n // is what keeps the reconcile loop — the completeness guarantee (ADR-0029 D4) — whole.\n private readonly snapshotAccepted = new Map<string, boolean>();\n // Per shape: whether this shape has reported `up-to-date` at least once since registration / its last\n // {@link resetShape}. Set true in {@link ingestUpToDate} even when the reported watermark does NOT\n // advance the frontier (a stale cached watermark still means \"this shape has completed a catch-up and\n // asserted a global head\"). The catch-up alignment (ADR-0031) fires only once EVERY shape in the group\n // has reported up-to-date — i.e. once the whole group has a first asserted global head to align to.\n private readonly upToDateSeen = new Map<string, boolean>();\n // Per shape: the watermark (`global_last_seen_lsn`) this shape MOST RECENTLY reported via\n // {@link ingestUpToDate}, recorded unconditionally — even a stale cached watermark that does not\n // advance {@link completeLsns}. This is the input to the group-max alignment: the freshest asserted\n // global head across the group is `max` over these REPORTED watermarks (NOT over the frontiers — a\n // frontier can sit ahead of every reported watermark mid-live-batch; see {@link ingestUpToDate}).\n private readonly lastUpToDateLsn = new Map<string, Lsn>();\n // Per shape: the COMMIT floor (ADR-0031) — a watermark that only ever RAISES this shape's effective\n // commit frontier in {@link lowestCompleteLsn}, never its dedup threshold. Laid down once per catch-up\n // completion by the alignment in {@link ingestUpToDate}. Deliberately NOT reset by {@link resetShape}:\n // floors are monotonic, so a reset shape keeps its old floor (its buffer is empty anyway) until the\n // next group-wide realignment lifts it. Default -1 = no floor.\n private readonly commitFloors = new Map<string, Lsn>();\n // Whether the one-time catch-up commit-floor alignment (ADR-0031) has already run for the current\n // registration/reset generation. False at construction; set true when the alignment lays down floors in\n // {@link ingestUpToDate}; reset to false by {@link resetShape} so a must-refetch re-catch-up realigns\n // the group once every shape has completed again (a reset shape re-streams a fresh — possibly cached —\n // catch-up, so the group needs a fresh asserted global head to align to).\n private aligned = false;\n // The freshest asserted global head the last alignment aligned to (`max` over reported watermarks) —\n // surfaced on the debug rail by the caller as the `floor` of the `catch-up watermark aligned` line.\n private lastAlignedFloor: Lsn = BigInt(-1);\n\n constructor(shapeNames: Iterable<string>) {\n for (const shapeName of shapeNames) {\n this.changes.set(shapeName, new Map());\n this.completeLsns.set(shapeName, BigInt(-1));\n this.moveOuts.set(shapeName, []);\n this.moveIns.set(shapeName, []);\n this.epochs.set(shapeName, 0);\n this.snapshotAccepted.set(shapeName, true);\n this.upToDateSeen.set(shapeName, false);\n this.lastUpToDateLsn.set(shapeName, BigInt(-1));\n this.commitFloors.set(shapeName, BigInt(-1));\n }\n }\n\n /**\n * Whether the shape is still accepting snapshot (LSN-0) rows past the dedup frontier — true from\n * registration / the last {@link resetShape} until the first real-lsn change re-armed the dedup. The\n * commit path reads this to apply such rows idempotently (the racing recovery loops can double-deliver\n * them), consistent with the move-in upsert path, rather than as a plain collision-surfacing insert.\n */\n acceptsSnapshotRowsFor(shapeName: string): boolean {\n return this.snapshotAccepted.get(shapeName) === true;\n }\n\n /** The complete-LSN frontier for one shape (the already-seen dedup threshold). */\n completeLsnFor(shapeName: string): Lsn {\n return this.completeLsns.get(shapeName) ?? BigInt(-1);\n }\n\n /**\n * The shape's current reset epoch. The commit path snapshots this for every peeked shape and passes it\n * back to the acks, which no-op for any shape whose epoch changed (a mid-commit {@link resetShape}) so\n * the reset's own truncate+rebuild path owns that shape's post-reset state.\n */\n epochFor(shapeName: string): number {\n return this.epochs.get(shapeName) ?? 0;\n }\n\n /**\n * Buffer a change message. A message at or below the shape's current complete frontier is\n * already-seen and dropped. `isLastOfLsn` advances the frontier to this LSN.\n */\n ingestChange(shapeName: string, message: ChangeMessage<Row<unknown>>, lsn: Lsn, isLastOfLsn: boolean): void {\n // A real replication lsn (> 0) proves the stream has moved past the snapshot into the live tail:\n // re-arm the LSN-0 dedup for this shape (see {@link snapshotAccepted}).\n if (lsn > BigInt(0)) {\n this.snapshotAccepted.set(shapeName, false);\n }\n // A snapshot (LSN-0) row while snapshot acceptance is open bypasses the dedup even if the frontier\n // has advanced past 0 — otherwise a re-snapshot delivered AFTER a racing `up-to-date` (which pushed\n // the frontier to a large LSN) would be dropped wholesale, truncating the shape to empty. It still\n // buffers at LSN 0 (and does not advance the frontier), so drains/acks/truncate are unchanged.\n const acceptSnapshotRow = lsn === BigInt(0) && this.acceptsSnapshotRowsFor(shapeName);\n if (!acceptSnapshotRow && lsn <= this.completeLsnFor(shapeName)) {\n return;\n }\n\n const shapeChanges = this.changes.get(shapeName);\n if (!shapeChanges) {\n return;\n }\n\n let lsnMessages = shapeChanges.get(lsn);\n if (!lsnMessages) {\n lsnMessages = [];\n shapeChanges.set(lsn, lsnMessages);\n }\n lsnMessages.push(message);\n\n if (isLastOfLsn) {\n this.completeLsns.set(shapeName, lsn);\n }\n }\n\n /** The commit floor (ADR-0031) for one shape — the aligned watermark; -1 when no floor has been laid. */\n commitFloorFor(shapeName: string): Lsn {\n return this.commitFloors.get(shapeName) ?? BigInt(-1);\n }\n\n /**\n * A shape's EFFECTIVE complete frontier (ADR-0031): `max(completeLsnFor(shape), commitFloorFor(shape))` —\n * the raw dedup frontier raised by any aligned commit floor. This is the exact per-shape quantity\n * {@link lowestCompleteLsn} minimizes over (both go through here, so the two definitions cannot drift),\n * and the input the live-tail sibling nudge reads to decide which siblings still lag a target LSN.\n */\n effectiveLsnFor(shapeName: string): Lsn {\n const raw = this.completeLsnFor(shapeName);\n const floor = this.commitFloorFor(shapeName);\n return raw > floor ? raw : floor;\n }\n\n /**\n * Whether this shape has reported `up-to-date` at least once since registration / its last\n * {@link resetShape} — the {@link upToDateSeen} flag. The live-tail sibling nudge (ADR-0031) reads this:\n * a shape still catching up advances on its own, so only a shape already in its live tail is ever nudged.\n */\n hasReportedUpToDate(shapeName: string): boolean {\n return this.upToDateSeen.get(shapeName) === true;\n }\n\n /** The freshest asserted global head the last catch-up alignment aligned to (ADR-0031); -1 if never aligned. */\n alignedFloor(): Lsn {\n return this.lastAlignedFloor;\n }\n\n /**\n * Advance the frontier on an `up-to-date` control message (carries no buffered change) AND run the\n * one-time catch-up commit-floor alignment (ADR-0031) once the whole group has reported up-to-date.\n *\n * Returns `true` iff THIS call performed the alignment (the caller emits a single diagnostic line on\n * that transition); `false` on every other call.\n */\n ingestUpToDate(shapeName: string, globalLastSeenLsn: Lsn): boolean {\n // Record the report unconditionally: this shape has now completed a catch-up and asserted a global\n // head, and this is the watermark to align to — even if it is stale (below the frontier) and so does\n // NOT advance the dedup frontier below. Both facts feed the alignment; neither is the frontier.\n this.upToDateSeen.set(shapeName, true);\n this.lastUpToDateLsn.set(shapeName, globalLastSeenLsn);\n\n // The existing conditional frontier advance is UNCHANGED: a watermark only advances the dedup frontier\n // when it is strictly ahead of it. A stale cached watermark leaves the frontier where it was.\n if (globalLastSeenLsn > this.completeLsnFor(shapeName)) {\n this.completeLsns.set(shapeName, globalLastSeenLsn);\n }\n\n // Catch-up commit-floor alignment (ADR-0031), one-time per registration/reset generation: once EVERY\n // shape in the group has reported up-to-date, lift each shape's commit floor to the freshest asserted\n // global head. That is `max` over the REPORTED watermarks ({@link lastUpToDateLsn}) — deliberately NOT\n // over the frontiers ({@link completeLsns}). A frontier can be ahead of every reported watermark when a\n // live change batch is in flight and its sibling shapes' halves have not arrived yet; aligning floors\n // to such a frontier would commit one shape's half of a cross-shape transaction ahead of the other's\n // (a torn write). The freshest asserted global head is a watermark every shape has been told is\n // complete, so aligning to it can never tear a transaction that is still assembling above it.\n if (!this.aligned) {\n let everySeen = true;\n for (const seen of this.upToDateSeen.values()) {\n if (!seen) {\n everySeen = false;\n break;\n }\n }\n if (everySeen) {\n let groupMax: Lsn = BigInt(-1);\n for (const reported of this.lastUpToDateLsn.values()) {\n if (reported > groupMax) {\n groupMax = reported;\n }\n }\n for (const shape of this.commitFloors.keys()) {\n const existing = this.commitFloorFor(shape);\n this.commitFloors.set(shape, groupMax > existing ? groupMax : existing);\n }\n this.aligned = true;\n this.lastAlignedFloor = groupMax;\n return true;\n }\n }\n return false;\n }\n\n /** Buffer a `move-out` event's patterns for a shape (ADR-0023); applied at the next commit. */\n ingestMoveOut(shapeName: string, patterns: MovePattern[]): void {\n this.moveOuts.get(shapeName)?.push(patterns);\n }\n\n /** Remove and return a shape's buffered `move-out` pattern sets (one per event), in arrival order. */\n drainMoveOuts(shapeName: string): MovePattern[][] {\n const pending = this.moveOuts.get(shapeName) ?? [];\n this.moveOuts.set(shapeName, []);\n return pending;\n }\n\n /**\n * Peek — WITHOUT removing — a shape's buffered `move-out` pattern sets (a copy, arrival order). Pairs\n * with {@link ackMoveOuts}: the commit path peeks, applies inside its transaction, and acks (removes)\n * only after the transaction succeeds — so a failed/degraded commit (ADR-0009 decision 5) leaves the\n * revocations buffered rather than silently losing them.\n */\n peekMoveOuts(shapeName: string): MovePattern[][] {\n return [...(this.moveOuts.get(shapeName) ?? [])];\n }\n\n /**\n * Remove the first `count` buffered `move-out` pattern sets for a shape (call only after the commit\n * that consumed a matching {@link peekMoveOuts} of that many entries succeeded). Removing exactly the\n * peeked count — not clear-all — keeps any move-out that arrived DURING the commit (coalescing path)\n * buffered for the next run. `epochAtPeek` is the shape's {@link epochFor} captured at peek time: if a\n * {@link resetShape} bumped it since, the peeked entries no longer exist (the array was replaced), so\n * this no-ops rather than splicing the post-reset replacement.\n */\n ackMoveOuts(shapeName: string, count: number, epochAtPeek: number): void {\n if (this.epochFor(shapeName) !== epochAtPeek) {\n return;\n }\n this.moveOuts.get(shapeName)?.splice(0, count);\n }\n\n /** Whether any shape has a buffered `move-out` awaiting a commit. */\n hasPendingMoveOuts(): boolean {\n for (const pending of this.moveOuts.values()) {\n if (pending.length > 0) return true;\n }\n return false;\n }\n\n /** Buffer a `move-in` snapshot row for a shape (ADR-0024); applied idempotently at the next commit. */\n ingestMoveIn(shapeName: string, message: ChangeMessage<Row<unknown>>): void {\n this.moveIns.get(shapeName)?.push(message);\n }\n\n /** Remove and return a shape's buffered `move-in` snapshot rows, in arrival order. */\n drainMoveIns(shapeName: string): ChangeMessage<Row<unknown>>[] {\n const pending = this.moveIns.get(shapeName) ?? [];\n this.moveIns.set(shapeName, []);\n return pending;\n }\n\n /** Peek — WITHOUT removing — a shape's buffered `move-in` snapshot rows (a copy, arrival order). See {@link peekMoveOuts}. */\n peekMoveIns(shapeName: string): ChangeMessage<Row<unknown>>[] {\n return [...(this.moveIns.get(shapeName) ?? [])];\n }\n\n /**\n * Remove the first `count` buffered `move-in` snapshot rows for a shape (post-commit ack; see\n * {@link ackMoveOuts}). No-ops if `epochAtPeek` no longer matches the shape's current epoch (a\n * mid-commit {@link resetShape}), so the post-reset replacement rows survive.\n */\n ackMoveIns(shapeName: string, count: number, epochAtPeek: number): void {\n if (this.epochFor(shapeName) !== epochAtPeek) {\n return;\n }\n this.moveIns.get(shapeName)?.splice(0, count);\n }\n\n /** Whether any shape has a buffered `move-in` awaiting a commit. */\n hasPendingMoveIns(): boolean {\n for (const pending of this.moveIns.values()) {\n if (pending.length > 0) return true;\n }\n return false;\n }\n\n /** Reset a shape on `must-refetch`: drop its buffer and rewind its frontier (the applier truncates). */\n resetShape(shapeName: string): void {\n this.changes.get(shapeName)?.clear();\n this.completeLsns.set(shapeName, BigInt(-1));\n this.moveOuts.set(shapeName, []);\n this.moveIns.set(shapeName, []);\n // Re-open snapshot acceptance: the re-snapshot's LSN-0 rows must survive the dedup even if a racing\n // `up-to-date` advances the rewound frontier again before they arrive (see {@link snapshotAccepted}).\n this.snapshotAccepted.set(shapeName, true);\n // ADR-0031: this shape must re-report up-to-date before it counts toward the group again, and its\n // last reported watermark is void (it re-streams a fresh — possibly cached — catch-up). Clear the\n // group's aligned flag so the whole group realigns once every shape has completed again. The commit\n // floor is NOT cleared: floors are monotonic (the buffer is empty post-reset anyway), so the shape\n // keeps its old floor until realignment lifts it.\n this.upToDateSeen.set(shapeName, false);\n this.lastUpToDateLsn.set(shapeName, BigInt(-1));\n this.aligned = false;\n // Bump the epoch so any in-flight commit that peeked this shape BEFORE the reset skips its acks — the\n // post-reset buffers just installed above must survive to be committed on the follow-up pass.\n this.epochs.set(shapeName, this.epochFor(shapeName) + 1);\n }\n\n /**\n * The lowest EFFECTIVE complete frontier across all shapes — the atomic group commit target. A shape's\n * effective frontier is `max(completeLsnFor(shape), commitFloorFor(shape))` (ADR-0031): the raw dedup\n * frontier, raised by any aligned commit floor. Aligning the floors up to the freshest asserted global\n * head lets a group whose quiet shapes reported a STALE cached catch-up watermark still commit a busy\n * shape's delivered changes at catch-up completion, instead of holding them until the quiet shapes'\n * first live long-poll. The floor never narrows what {@link ingestChange} accepts (that remains the raw\n * {@link completeLsns}), so a late sub-floor change is still ingested and then committed.\n */\n lowestCompleteLsn(): Lsn {\n let minimum: Lsn | null = null;\n for (const shapeName of this.completeLsns.keys()) {\n const effective = this.effectiveLsnFor(shapeName);\n if (minimum === null || effective < minimum) {\n minimum = effective;\n }\n }\n return minimum ?? BigInt(-1);\n }\n\n /**\n * Whether any shape has a buffered change entry at an LSN at or below `targetLsn` (ADR-0031). The commit\n * loop uses this to fire a commit for a LATE-arriving change that lands at or below an already-committed\n * target — possible exactly because the aligned commit floor lets {@link ingestChange} accept a change\n * below the floor while the group frontier already sits at (or above) it, so no new frontier advance\n * would otherwise trigger a commit for it.\n */\n hasBufferedChangesAtOrBelow(targetLsn: Lsn): boolean {\n for (const shapeChanges of this.changes.values()) {\n for (const lsn of shapeChanges.keys()) {\n if (lsn <= targetLsn) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Peek — WITHOUT removing — every buffered change at or below `targetLsn`, per shape, in buffered-LSN\n * order. The returned map has an entry for every shape (an empty array where nothing peeked). Pairs\n * with {@link ackUpTo}: the commit path peeks, writes the batch inside its transaction, and acks\n * (removes) only after the transaction succeeds — so a failed/degraded commit (ADR-0009 decision 5)\n * holds the batch in the buffer rather than dropping it, and a newer LSN can never land over it.\n */\n peekUpTo(targetLsn: Lsn): Map<string, ChangeMessage<Row<unknown>>[]> {\n const peeked = new Map<string, ChangeMessage<Row<unknown>>[]>();\n\n for (const [shapeName, shapeChanges] of this.changes.entries()) {\n const messages: ChangeMessage<Row<unknown>>[] = [];\n for (const lsn of [...shapeChanges.keys()]) {\n if (lsn <= targetLsn) {\n for (const message of shapeChanges.get(lsn)!) {\n messages.push(message);\n }\n }\n }\n peeked.set(shapeName, messages);\n }\n\n return peeked;\n }\n\n /**\n * Remove every buffered change at or below `targetLsn` (call only after the commit that consumed a\n * matching {@link peekUpTo} succeeded). `epochsAtPeek` maps each shape to its {@link epochFor} captured\n * at peek time; a shape whose epoch has since changed is **skipped entirely**.\n *\n * The epoch guard is load-bearing under a frontier REWIND. In the steady state, the frontier only\n * advances, so nothing new at or below `targetLsn` can be buffered between peek and ack. But a mid-commit\n * {@link resetShape} (must-refetch) rewinds a shape's frontier to -1 and lets its re-snapshot buffer at\n * LSN 0 — content that was NOT in this commit's peek. Deleting it here (LSN 0 ≤ `targetLsn`) would drop\n * the rebuild; the epoch bump makes this no-op for that shape so the reset's own rebuild path owns it.\n */\n ackUpTo(targetLsn: Lsn, epochsAtPeek: Map<string, number>): void {\n for (const [shapeName, shapeChanges] of this.changes.entries()) {\n const peekEpoch = epochsAtPeek.get(shapeName);\n if (peekEpoch !== undefined && this.epochFor(shapeName) !== peekEpoch) {\n continue;\n }\n for (const lsn of [...shapeChanges.keys()]) {\n if (lsn <= targetLsn) {\n shapeChanges.delete(lsn);\n }\n }\n }\n }\n\n /** Snapshot every shape's current {@link epochFor} — captured at peek time and passed to the acks. */\n snapshotEpochs(): Map<string, number> {\n return new Map([...this.epochs.keys()].map((shapeName) => [shapeName, this.epochFor(shapeName)]));\n }\n\n /**\n * Remove and return every buffered change at or below `targetLsn`, per shape, in buffered-LSN order\n * ({@link peekUpTo} then {@link ackUpTo}). The returned map has an entry for every shape (an empty\n * array where nothing drained).\n */\n drainUpTo(targetLsn: Lsn): Map<string, ChangeMessage<Row<unknown>>[]> {\n const epochsAtPeek = this.snapshotEpochs();\n const drained = this.peekUpTo(targetLsn);\n this.ackUpTo(targetLsn, epochsAtPeek);\n return drained;\n }\n}\n\ntype Operation = \"insert\" | \"update\" | \"delete\";\n\n/**\n * A drained shape batch folded to **one net operation per primary key** (ADR-0014 decision 1).\n * Each PK appears in at most one of `inserts`/`updates`, and at most once in `deletes` — except a\n * *re-created* PK (`[delete, insert]`), which appears in both `deletes` and `inserts` so the bulk\n * apply clears the pre-existing row before inserting the new one. The Sync applier therefore runs\n * three bulk statements **in the order `deletes → inserts → updates`** (Phase 3): that ordering is\n * what makes a re-create safe, and every other PK is touched by exactly one statement, so the rest\n * of the order is irrelevant within the atomic commit.\n */\nexport interface FoldedShapeBatch {\n /** PKs to delete — net-`delete` keys, plus the clearing delete of each re-created key. */\n deletes: ChangeMessage<Row<unknown>>[];\n /** Full rows to insert — net-`insert` keys, plus each re-created key's new row (merged values). */\n inserts: InsertChangeMessage[];\n /** Merged partial updates — net-`update` keys (carry the PK plus the union of updated columns). */\n updates: ChangeMessage<Row<unknown>>[];\n}\n\n/** Clone a representative message, overriding its row value and operation (headers like LSN are kept). */\nfunction withValue(\n template: ChangeMessage<Row<unknown>>,\n value: Row<unknown>,\n operation: Operation,\n): ChangeMessage<Row<unknown>> {\n return { ...template, value, headers: { ...template.headers, operation } };\n}\n\n/** Shallow-merge the row values of an ordered op segment, last-write-wins per column. */\nfunction mergeValues(segment: ChangeMessage<Row<unknown>>[]): Row<unknown> {\n return Object.assign({}, ...segment.map((message) => message.value)) as Row<unknown>;\n}\n\n/**\n * Fold a drained shape batch (ordered by LSN, one shape) to one net operation per primary key\n * (ADR-0014 decision 1), so the read path can bulk-apply without the `UPDATE … FROM` / `INSERT …\n * SELECT json_to_recordset(…)` same-PK join hazard (those use **one arbitrary** matching row when\n * the source holds duplicate PKs). Each PK's ops are replayed in LSN order down to:\n *\n * - **trailing `delete`** ⇒ a single DELETE;\n * - **`insert` with no preceding delete**, then any updates ⇒ a single INSERT with merged values\n * (a *plain* insert — a genuine PK collision still surfaces, never a silent upsert, commit `de12bb6`);\n * - **only `update`s** ⇒ a single UPDATE with merged values;\n * - **re-created** (`[delete, … , insert, …]`, no trailing delete) ⇒ DELETE **and** INSERT, so the\n * pre-existing row is cleared first (faithful to the per-row `DELETE`-then-`INSERT`; a plain INSERT\n * would collide with the row the dropped delete was meant to remove);\n * - **`update` after a delete** (`[delete, update]` and kin) is malformed for a faithful stream\n * (an update asserts the row exists) ⇒ throw, surfacing stream corruption rather than silently\n * dropping it.\n *\n * Pure and dependency-free by design (ADR-0014 / ISS-06): property-tested against the oracle\n * *fold-then-bulk ≡ ordered per-row apply* over random same-PK sequences and random initial state.\n */\nexport function foldChangeBatch(messages: ChangeMessage<Row<unknown>>[]): FoldedShapeBatch {\n const groups = new Map<string, ChangeMessage<Row<unknown>>[]>();\n for (const message of messages) {\n let group = groups.get(message.key);\n if (!group) {\n group = [];\n groups.set(message.key, group);\n }\n group.push(message);\n }\n\n const folded: FoldedShapeBatch = { deletes: [], inserts: [], updates: [] };\n for (const [key, ops] of groups) {\n foldKey(key, ops, folded);\n }\n return folded;\n}\n\nfunction foldKey(key: string, ops: ChangeMessage<Row<unknown>>[], folded: FoldedShapeBatch): void {\n const lastDeleteIndex = ops.findLastIndex((message) => message.headers.operation === \"delete\");\n\n // A trailing delete is the net effect regardless of anything before it; emit one DELETE.\n if (lastDeleteIndex === ops.length - 1) {\n folded.deletes.push(ops[lastDeleteIndex]!);\n return;\n }\n\n // The net is decided by the segment after the last delete (or the whole sequence if none).\n const segment = ops.slice(lastDeleteIndex + 1);\n const merged = mergeValues(segment);\n const template = segment[segment.length - 1]!;\n const startsWithInsert = segment[0]!.headers.operation === \"insert\";\n const hadDelete = lastDeleteIndex >= 0;\n\n if (startsWithInsert) {\n if (hadDelete) {\n // Re-created: clear the pre-existing row, then insert the new one (DELETE before INSERT).\n folded.deletes.push(ops[lastDeleteIndex]!);\n }\n folded.inserts.push(withValue(template, merged, \"insert\") as InsertChangeMessage);\n return;\n }\n\n if (hadDelete) {\n throw new Error(`foldChangeBatch: malformed batch — update after delete for key ${JSON.stringify(key)}`);\n }\n folded.updates.push(withValue(template, merged, \"update\"));\n}\n",
137
144
  "// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\nimport type { Offset } from \"@electric-sql/client\";\nimport type { PGliteInterface, Transaction } from \"@electric-sql/pglite\";\nimport { eq } from \"drizzle-orm\";\n\nimport { quoteIdentifier } from \"@pgxsinkit/contracts\";\n\nimport { renderCreateTableSql } from \"../schema\";\nimport { drizzleOverPg } from \"./drizzle-executor\";\nimport { getMetadataTables } from \"./metadata-tables\";\nimport { type Lsn, type SubscriptionKey } from \"./types\";\n\nexport interface SubscriptionState {\n key: SubscriptionKey;\n shape_metadata: Record<string, ShapeSubscriptionState>;\n last_lsn: Lsn;\n}\n\nexport interface ShapeSubscriptionState {\n handle: string;\n offset: Offset;\n}\n\nexport interface GetSubscriptionStateOptions {\n readonly pg: PGliteInterface | Transaction;\n readonly metadataSchema: string;\n readonly subscriptionKey: SubscriptionKey;\n}\n\nexport async function getSubscriptionState({\n pg,\n metadataSchema,\n subscriptionKey,\n}: GetSubscriptionStateOptions): Promise<SubscriptionState | null> {\n const { subscriptionsMetadata } = getMetadataTables(metadataSchema);\n const rows = await drizzleOverPg(pg)\n .select()\n .from(subscriptionsMetadata)\n .where(eq(subscriptionsMetadata.key, subscriptionKey));\n\n if (rows.length === 0) {\n return null;\n }\n if (rows.length > 1) {\n throw new Error(`Multiple subscriptions found for key: ${subscriptionKey}`);\n }\n\n const row = rows[0];\n if (!row) {\n throw new Error(`Subscription row missing for key: ${subscriptionKey}`);\n }\n if (typeof row.key !== \"string\") {\n throw new Error(`Invalid key type: ${typeof row.key}`);\n }\n if (!row.shape_metadata || typeof row.shape_metadata !== \"object\") {\n throw new Error(\"Invalid shape_metadata payload\");\n }\n if (typeof row.last_lsn !== \"string\") {\n throw new Error(`Invalid last_lsn type: ${typeof row.last_lsn}`);\n }\n\n return {\n key: row.key,\n shape_metadata: row.shape_metadata,\n last_lsn: BigInt(row.last_lsn),\n };\n}\n\nexport interface UpdateSubscriptionStateOptions {\n pg: PGliteInterface | Transaction;\n metadataSchema: string;\n subscriptionKey: SubscriptionKey;\n shapeMetadata: Record<string, ShapeSubscriptionState>;\n lastLsn: Lsn;\n debug?: boolean;\n}\n\nexport async function updateSubscriptionState({\n pg,\n metadataSchema,\n subscriptionKey,\n shapeMetadata,\n lastLsn,\n debug,\n}: UpdateSubscriptionStateOptions) {\n if (debug) {\n console.log(\"updating subscription state\", subscriptionKey, shapeMetadata, lastLsn);\n }\n\n const { subscriptionsMetadata } = getMetadataTables(metadataSchema);\n const lastLsnText = lastLsn.toString();\n await drizzleOverPg(pg)\n .insert(subscriptionsMetadata)\n .values({ key: subscriptionKey, shape_metadata: shapeMetadata, last_lsn: lastLsnText })\n .onConflictDoUpdate({\n target: subscriptionsMetadata.key,\n set: { shape_metadata: shapeMetadata, last_lsn: lastLsnText },\n });\n}\n\nexport interface DeleteSubscriptionStateOptions {\n pg: PGliteInterface | Transaction;\n metadataSchema: string;\n subscriptionKey: SubscriptionKey;\n}\n\nexport async function deleteSubscriptionState({ pg, metadataSchema, subscriptionKey }: DeleteSubscriptionStateOptions) {\n const { subscriptionsMetadata } = getMetadataTables(metadataSchema);\n await drizzleOverPg(pg).delete(subscriptionsMetadata).where(eq(subscriptionsMetadata.key, subscriptionKey));\n}\n\nexport interface MigrateSubscriptionMetadataTablesOptions {\n pg: PGliteInterface | Transaction;\n metadataSchema: string;\n}\n\nexport async function migrateSubscriptionMetadataTables({\n pg,\n metadataSchema,\n}: MigrateSubscriptionMetadataTablesOptions) {\n // ADR-0029 D3: the metadata relations are RENDERED from the `metadata-tables.ts` pgTables through the\n // in-house schema renderer (`renderCreateTableSql`), so the pgTable is the single source and the old\n // DDL/pgTable drift can no longer exist. The CREATE SCHEMA + `SET` GUC default remain tier-③-by-nature\n // (schema identifier assembled at construction; the GUC has no tier-①/② form). Executed together as\n // one batch, exactly as before — same relations, same IF NOT EXISTS idempotence, same GUC default.\n const { subscriptionsMetadata, shapeRowTags } = getMetadataTables(metadataSchema);\n const statements = [\n `SET ${metadataSchema}.syncing = false;`,\n `CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(metadataSchema)};`,\n ...renderCreateTableSql(subscriptionsMetadata),\n ...renderCreateTableSql(shapeRowTags),\n ];\n await pg.exec(statements.join(\"\\n\"));\n}\n",
138
- "// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\nimport type { ChangeMessage, FetchError, Row, ShapeStreamInterface, ShapeStreamOptions } from \"@electric-sql/client\";\nimport type { PgliteDatabase } from \"drizzle-orm/pglite\";\n\nimport type { SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\n// Re-exported so in-repo tests (e.g. tests/unit/sync-engine.test.ts) can name these Electric types\n// via this engine module — they resolve here, inside @pgxsinkit/client's dependency scope, without\n// the root workspace needing a direct dependency on the Electric client packages.\nexport type { Row, ShapeStreamOptions } from \"@electric-sql/client\";\nexport type { MultiShapeMessages } from \"@electric-sql/experimental\";\n\nexport type Lsn = bigint;\n\nexport type SubscriptionKey = string;\nexport type InitialInsertMethod = \"insert\" | \"copy\" | \"json\";\n\n/** Default hard cap on commit-transaction attempts before the engine goes degraded (ADR-0009). */\nexport const DEFAULT_MAX_COMMIT_RETRIES = 5;\n\n/**\n * Per-shape options for the group form (ADR-0029 D1). Every table-scoped fact — local table identity,\n * projection, primary keys, apply strategy, column types — is derived by the engine from the\n * group-level `registry` and this shape's `tableKey`; none is passed here. Only the Electric shape\n * stream, an optional per-shape backfill override, and the must-refetch hook remain.\n */\nexport interface ShapeToTableOptions {\n shape: ShapeStreamOptions<Row<unknown>>;\n /** The registry table key this shape applies into — the engine's sole per-table spec (ADR-0029 D1). */\n tableKey: string;\n /**\n * Must-refetch override: replaces the default `TRUNCATE` cache wipe (ADR-0029 D4). Receives a Drizzle\n * handle bound to the commit transaction (`drizzleOverPg(tx)`), so a scoped clear authors tier-①\n * (`db.delete(table).where(…)`).\n */\n onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;\n /**\n * Per-shape initial-backfill apply strategy override (ADR-0009 decisions 2 + 3). In a consistency\n * group each shape resolves its own apply path, so one shape's backfill never forces the rest onto\n * plain `INSERT`. When set it wins over the registry-classified strategy; otherwise the strategy is\n * derived from the entry and mapped, else the group-level default applies.\n */\n initialInsertMethod?: InitialInsertMethod | undefined;\n}\n\nexport interface SyncShapesToTablesOptions {\n key: string | null;\n /** The engine's per-table spec source (ADR-0029 D1): every shape's `tableKey` resolves against it. */\n registry: SyncTableRegistry;\n shapes: Record<string, ShapeToTableOptions>;\n initialInsertMethod?: InitialInsertMethod | undefined;\n onInitialSync?: (() => void) | undefined;\n /**\n * Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003). When present, the group is on a\n * PROVABLY-FRESH store (a claimed schemaless spare — the caller's `freshStore` hint), so the engine\n * starts the shape streams and BUFFERS their catch-up into the memory inbox immediately — WITHOUT the\n * two DB touches the sequential path takes first (`initMetadataTables`, `getSubscriptionState`) — and\n * gates every commit (the first write to PGlite) until this promise resolves. The owner resolves it\n * once the local store is ready (schema exec + journal recovery + store-version reconcile complete), so\n * the network catch-up overlaps those local phases instead of running strictly after them. Absent → the\n * exact sequential path (warm stores, and every non-overlap caller). Because a fresh store has no prior\n * subscription state, the overlap treats the group as a new subscription (`subState === null`), which the\n * `freshStore` gate guarantees.\n */\n dbReady?: Promise<void> | undefined;\n /** Stream-level (network / fetch) error from Electric, forwarded to `MultiShapeStream.subscribe`. */\n onError?: ((error: FetchError | Error) => void) | undefined;\n /**\n * Commit-level error surfacing (ADR-0009 decision 5). Fired when a sync commit transaction\n * still fails after `maxCommitRetries` jittered-backoff attempts. The engine then holds its\n * buffer and committed frontier (never advancing `isUpToDate` on an unapplied commit) so the\n * read cache cannot silently diverge; recovery is a later commit or a restart/refetch.\n */\n onSyncError?: ((error: Error) => void) | undefined;\n /**\n * Fired whenever the stream delivers a batch — i.e. a fetch just succeeded (ADR-0013 Phase 3).\n * The runtime uses this as the read path's \"alive again\" signal to clear an `auth-needed` status\n * once sync resumes after re-authentication.\n */\n onSyncActivity?: (() => void) | undefined;\n /** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */\n maxCommitRetries?: number | undefined;\n /**\n * Backoff before re-attempting a failed commit, as a function of the attempt number. Defaults to\n * the runtime's jittered backoff (`computeRetryDelayMs`). A test seam — pass `() => 0` for an\n * immediate retry instead of sleeping the real backoff.\n */\n commitRetryDelayMs?: ((attempt: number) => number) | undefined;\n}\n\nexport interface SyncShapesToTablesResult {\n unsubscribe: () => void;\n readonly isUpToDate: boolean;\n streams: Record<string, ShapeStreamInterface<Row<unknown>>>;\n}\n\n/**\n * Single-shape options (ADR-0029 D6): thin sugar over the group form, taking the same entry-based\n * fields plus a `shapeKey`. Every table-scoped fact is derived from `(registry, tableKey)`.\n */\nexport interface SyncShapeToTableOptions {\n shape: ShapeStreamOptions<Row<unknown>>;\n registry: SyncTableRegistry;\n tableKey: string;\n shapeKey: string | null;\n initialInsertMethod?: InitialInsertMethod | undefined;\n onInitialSync?: (() => void) | undefined;\n onError?: ((error: FetchError | Error) => void) | undefined;\n /** Commit-level error surfacing (ADR-0009 decision 5); see {@link SyncShapesToTablesOptions.onSyncError}. */\n onSyncError?: ((error: Error) => void) | undefined;\n /** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */\n maxCommitRetries?: number | undefined;\n /** Backoff before re-attempting a failed commit; see {@link SyncShapesToTablesOptions.commitRetryDelayMs}. */\n commitRetryDelayMs?: ((attempt: number) => number) | undefined;\n onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;\n}\n\nexport interface SyncShapeToTableResult {\n unsubscribe: () => void;\n readonly isUpToDate: boolean;\n stream: ShapeStreamInterface<Row<unknown>>;\n}\n\nexport interface ElectricSyncOptions {\n debug?: boolean;\n metadataSchema?: string;\n}\n\nexport type InsertChangeMessage = ChangeMessage<Row<unknown>> & {\n headers: { operation: \"insert\" };\n};\n",
145
+ "// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\nimport type { ChangeMessage, FetchError, Row, ShapeStreamInterface, ShapeStreamOptions } from \"@electric-sql/client\";\nimport type { PgliteDatabase } from \"drizzle-orm/pglite\";\n\nimport type { SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport type { GroupBootStamp } from \"../boot-report\";\n\n// Re-exported so in-repo tests (e.g. tests/unit/sync-engine.test.ts) can name these Electric types\n// via this engine module — they resolve here, inside @pgxsinkit/client's dependency scope, without\n// the root workspace needing a direct dependency on the Electric client packages.\nexport type { Row, ShapeStreamOptions } from \"@electric-sql/client\";\nexport type { MultiShapeMessages } from \"@electric-sql/experimental\";\n\nexport type Lsn = bigint;\n\nexport type SubscriptionKey = string;\nexport type InitialInsertMethod = \"insert\" | \"copy\" | \"json\";\n\n/** Default hard cap on commit-transaction attempts before the engine goes degraded (ADR-0009). */\nexport const DEFAULT_MAX_COMMIT_RETRIES = 5;\n\n/**\n * Per-shape options for the group form (ADR-0029 D1). Every table-scoped fact — local table identity,\n * projection, primary keys, apply strategy, column types — is derived by the engine from the\n * group-level `registry` and this shape's `tableKey`; none is passed here. Only the Electric shape\n * stream, an optional per-shape backfill override, and the must-refetch hook remain.\n */\nexport interface ShapeToTableOptions {\n shape: ShapeStreamOptions<Row<unknown>>;\n /** The registry table key this shape applies into — the engine's sole per-table spec (ADR-0029 D1). */\n tableKey: string;\n /**\n * Must-refetch override: replaces the default `TRUNCATE` cache wipe (ADR-0029 D4). Receives a Drizzle\n * handle bound to the commit transaction (`drizzleOverPg(tx)`), so a scoped clear authors tier-①\n * (`db.delete(table).where(…)`).\n */\n onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;\n /**\n * Per-shape initial-backfill apply strategy override (ADR-0009 decisions 2 + 3). In a consistency\n * group each shape resolves its own apply path, so one shape's backfill never forces the rest onto\n * plain `INSERT`. When set it wins over the registry-classified strategy; otherwise the strategy is\n * derived from the entry and mapped, else the group-level default applies.\n */\n initialInsertMethod?: InitialInsertMethod | undefined;\n}\n\nexport interface SyncShapesToTablesOptions {\n key: string | null;\n /** The engine's per-table spec source (ADR-0029 D1): every shape's `tableKey` resolves against it. */\n registry: SyncTableRegistry;\n shapes: Record<string, ShapeToTableOptions>;\n initialInsertMethod?: InitialInsertMethod | undefined;\n onInitialSync?: (() => void) | undefined;\n /**\n * Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003). When present, the group is on a\n * PROVABLY-FRESH store (a claimed schemaless spare — the caller's `freshStore` hint), so the engine\n * starts the shape streams and BUFFERS their catch-up into the memory inbox immediately — WITHOUT the\n * two DB touches the sequential path takes first (`initMetadataTables`, `getSubscriptionState`) — and\n * gates every commit (the first write to PGlite) until this promise resolves. The owner resolves it\n * once the local store is ready (schema exec + journal recovery + store-version reconcile complete), so\n * the network catch-up overlaps those local phases instead of running strictly after them. Absent → the\n * exact sequential path (warm stores, and every non-overlap caller). Because a fresh store has no prior\n * subscription state, the overlap treats the group as a new subscription (`subState === null`), which the\n * `freshStore` gate guarantees.\n */\n dbReady?: Promise<void> | undefined;\n /** Stream-level (network / fetch) error from Electric, forwarded to `MultiShapeStream.subscribe`. */\n onError?: ((error: FetchError | Error) => void) | undefined;\n /**\n * Commit-level error surfacing (ADR-0009 decision 5). Fired when a sync commit transaction\n * still fails after `maxCommitRetries` jittered-backoff attempts. The engine then holds its\n * buffer and committed frontier (never advancing `isUpToDate` on an unapplied commit) so the\n * read cache cannot silently diverge; recovery is a later commit or a restart/refetch.\n */\n onSyncError?: ((error: Error) => void) | undefined;\n /**\n * Fired whenever the stream delivers a batch — i.e. a fetch just succeeded (ADR-0013 Phase 3).\n * The runtime uses this as the read path's \"alive again\" signal to clear an `auth-needed` status\n * once sync resumes after re-authentication.\n */\n onSyncActivity?: (() => void) | undefined;\n /** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */\n maxCommitRetries?: number | undefined;\n /**\n * Backoff before re-attempting a failed commit, as a function of the attempt number. Defaults to\n * the runtime's jittered backoff (`computeRetryDelayMs`). A test seam — pass `() => 0` for an\n * immediate retry instead of sleeping the real backoff.\n */\n commitRetryDelayMs?: ((attempt: number) => number) | undefined;\n /**\n * Boot observability (ADR-0034): a per-group accumulator, stamped as this group's stream chain delivers\n * batches (`onBatchDelivered`), applies commits into PGlite (`onApply`), and reaches initial sync\n * (`markReady`). Present only for eager + promoted BOOT groups; absent for on-demand lazy starts and any\n * boot without report instrumentation.\n */\n bootStamp?: GroupBootStamp | undefined;\n}\n\nexport interface SyncShapesToTablesResult {\n unsubscribe: () => void;\n readonly isUpToDate: boolean;\n streams: Record<string, ShapeStreamInterface<Row<unknown>>>;\n}\n\n/**\n * Single-shape options (ADR-0029 D6): thin sugar over the group form, taking the same entry-based\n * fields plus a `shapeKey`. Every table-scoped fact is derived from `(registry, tableKey)`.\n */\nexport interface SyncShapeToTableOptions {\n shape: ShapeStreamOptions<Row<unknown>>;\n registry: SyncTableRegistry;\n tableKey: string;\n shapeKey: string | null;\n initialInsertMethod?: InitialInsertMethod | undefined;\n onInitialSync?: (() => void) | undefined;\n onError?: ((error: FetchError | Error) => void) | undefined;\n /** Commit-level error surfacing (ADR-0009 decision 5); see {@link SyncShapesToTablesOptions.onSyncError}. */\n onSyncError?: ((error: Error) => void) | undefined;\n /** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */\n maxCommitRetries?: number | undefined;\n /** Backoff before re-attempting a failed commit; see {@link SyncShapesToTablesOptions.commitRetryDelayMs}. */\n commitRetryDelayMs?: ((attempt: number) => number) | undefined;\n onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;\n}\n\nexport interface SyncShapeToTableResult {\n unsubscribe: () => void;\n readonly isUpToDate: boolean;\n stream: ShapeStreamInterface<Row<unknown>>;\n}\n\nexport interface ElectricSyncOptions {\n debug?: boolean;\n metadataSchema?: string;\n}\n\nexport type InsertChangeMessage = ChangeMessage<Row<unknown>> & {\n headers: { operation: \"insert\" };\n};\n",
139
146
  "// The live-query DIFF machinery (ADR-0032 S2 §4). Two pure pieces sit either side of the bridge:\n// - {@link computeLiveDiff} (worker-side): turn a fresh ordered result-set into a {added, changed, removed}\n// diff against the previously-sent one, keyed by the query's PK — so only deltas cross the wire.\n// - {@link LiveRowsMaterializer} (tab-side): fold each diff back into an ordered array while preserving\n// row-object identity for unchanged rows (React memo bails on `===`).\n// Both are transport-free and worker-free, so they unit-test directly.\n\nimport type { LiveDiffPayload } from \"./protocol\";\n\n// A NUL separator — never a legitimate character inside a PK text value, so composite keys can't collide.\nconst KEY_SEP = String.fromCharCode(0);\n\n/**\n * The stable key for a result row (§4). With `pkColumns`, join their values (composite-safe) — this is the\n * diff-keying identity, so a row whose PK is unchanged is the SAME logical row even if other columns moved.\n * Without `pkColumns` (a keyless query) fall back to the whole-row JSON value: still diff-shaped (never a\n * full resend), but an update surfaces as remove+add rather than a `changed` — the documented keyless\n * fallback. Duplicate identical keyless rows collapse under this scheme (accepted for the fallback).\n */\nexport function rowKey(row: Record<string, unknown>, pkColumns: readonly string[] | undefined): string {\n if (pkColumns && pkColumns.length > 0) {\n return pkColumns.map((col) => String(row[col])).join(KEY_SEP);\n }\n return JSON.stringify(row);\n}\n\n/** A shallow value-equality over a row's own enumerable keys — decides `changed` vs unchanged in a diff. */\nfunction rowsEqual(a: Record<string, unknown>, b: Record<string, unknown>): boolean {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) {\n if (!Object.is(a[key], b[key])) return false;\n }\n return true;\n}\n\n/** The worker's per-subscription memory: the last delivered rows keyed by {@link rowKey}, in delivered order. */\nexport interface LiveDiffState {\n pkColumns?: readonly string[];\n /** key → the exact row body last sent, so the next diff can detect `changed` and skip unchanged rows. */\n previous: Map<string, Record<string, unknown>>;\n}\n\n/** Seed the diff state from the initial snapshot (which the worker sends verbatim, not as a diff). */\nexport function seedLiveDiffState(\n rows: readonly Record<string, unknown>[],\n pkColumns: readonly string[] | undefined,\n): LiveDiffState {\n const previous = new Map<string, Record<string, unknown>>();\n for (const row of rows) previous.set(rowKey(row, pkColumns), row);\n return { ...(pkColumns ? { pkColumns } : {}), previous };\n}\n\n/**\n * Diff a fresh ordered result set against the state's previous set, MUTATING the state to the new set and\n * returning the wire diff (§4). `order` is every key in the new ORDER BY order (keys only — cheap); `added`/\n * `changed` carry the delta row BODIES; `removed` carries dropped keys. Never emits the full result set: a\n * single-row change yields one `changed` and the (key-only) `order`.\n */\nexport function computeLiveDiff(\n state: LiveDiffState,\n nextRows: readonly Record<string, unknown>[],\n): Omit<LiveDiffPayload, \"queryId\"> {\n const order: string[] = [];\n const added: { key: string; row: Record<string, unknown> }[] = [];\n const changed: { key: string; row: Record<string, unknown> }[] = [];\n const nextKeys = new Set<string>();\n const nextMap = new Map<string, Record<string, unknown>>();\n\n for (const row of nextRows) {\n const key = rowKey(row, state.pkColumns);\n // A duplicate key within one result set (composite PK not actually unique, or a keyless collision):\n // keep the first, so `order`/diff stay a faithful set. Rare; the read projections are PK-unique.\n if (nextKeys.has(key)) continue;\n nextKeys.add(key);\n nextMap.set(key, row);\n order.push(key);\n\n const prior = state.previous.get(key);\n if (prior === undefined) {\n added.push({ key, row });\n } else if (!rowsEqual(prior, row)) {\n changed.push({ key, row });\n }\n }\n\n const removed: string[] = [];\n for (const key of state.previous.keys()) {\n if (!nextKeys.has(key)) removed.push(key);\n }\n\n state.previous = nextMap;\n return { order, added, changed, removed };\n}\n\n/**\n * The tab-side fold of live diffs into an ordered row array with STABLE object identity (§4). The initial\n * snapshot seeds the cache; each diff rebuilds the array from `diff.order`, reusing the cached object for\n * any key not in `added`/`changed` (so an unchanged row keeps `===` and a memoized React row skips its\n * re-render), and installing a fresh object for added/changed keys. Order is exactly `diff.order` — the\n * query's ORDER BY as delivered by the worker.\n */\nexport class LiveRowsMaterializer<TRow extends Record<string, unknown> = Record<string, unknown>> {\n private byKey = new Map<string, TRow>();\n private rows: TRow[] = [];\n private readonly pkColumns: readonly string[] | undefined;\n\n constructor(pkColumns: readonly string[] | undefined) {\n this.pkColumns = pkColumns;\n }\n\n /** Seed from the initial snapshot; returns the initial ordered rows (each a distinct cached object). */\n seed(initialRows: readonly TRow[]): TRow[] {\n this.byKey = new Map();\n this.rows = [];\n for (const row of initialRows) {\n const key = rowKey(row, this.pkColumns);\n this.byKey.set(key, row);\n this.rows.push(row);\n }\n return this.rows;\n }\n\n /** Apply a diff; returns the new ordered array (a fresh array, but unchanged rows keep their object identity). */\n apply(diff: Omit<LiveDiffPayload, \"queryId\">): TRow[] {\n for (const key of diff.removed) this.byKey.delete(key);\n for (const { key, row } of diff.added) this.byKey.set(key, row as TRow);\n for (const { key, row } of diff.changed) this.byKey.set(key, row as TRow);\n // Rebuild strictly from the delivered order, reusing whatever object each key now maps to. Added/changed\n // keys already point at fresh objects (set above); every other key keeps its prior object (=== holds).\n this.rows = diff.order.map((key) => this.byKey.get(key)!).filter((row): row is TRow => row !== undefined);\n return this.rows;\n }\n\n /** The current ordered rows (identity-stable across `apply` calls for unchanged rows). */\n current(): TRow[] {\n return this.rows;\n }\n}\n",
140
- "// The bridge protocol (ADR-0032 S2). Everything that crosses between a tab and the shared sync engine\n// travels as a typed {@link BridgeEnvelope} over a minimal {@link BridgePort} (a MessagePort-shaped\n// transport). The router only ever inspects the envelope's `type`/`id`; its `payload` is OPAQUE to the\n// router and always passes through a {@link BridgeCodec}, so a later columnar/transferable codec can be\n// swapped in WITHOUT any protocol change (see BridgeCodec's doc).\n//\n// Deliberately transport-agnostic: `defineSyncWorker` and `attachSyncClient` both talk to a `BridgePort`,\n// never a real `Worker`/`SharedWorker` directly — which is exactly why the whole bridge is unit-testable\n// over bun's `MessageChannel` with no worker at all.\n\nimport type { SyncRuntimeStatus } from \"@pgxsinkit/contracts\";\n\nexport const BRIDGE_CHANNEL = \"pgxsinkit-bridge\" as const;\nexport const BRIDGE_PROTOCOL_VERSION = 1 as const;\n\n/**\n * A structured-clone transferable (an `ArrayBuffer`, a `MessagePort`, …). The library carries no DOM lib\n * dependency (like the convergence triggers), so this is the toolkit's own name for the type a future\n * columnar codec would hand to `postMessage`'s transfer list. v1's identity codec never produces one.\n */\nexport type BridgeTransferable = unknown;\n\n/**\n * The minimal MessagePort-shaped transport the bridge needs — the intersection of a real `MessagePort`,\n * a `SharedWorker` port, and a dedicated `Worker`/`self`. Injected everywhere so the protocol layer is\n * exercised with a plain `MessageChannel` (no Worker) in tests. `start()` is optional (MessagePort needs\n * it, `Worker`/`self` do not); `close()` is optional (a dedicated `self` cannot be closed by the tab).\n */\nexport interface BridgePort {\n postMessage: (message: unknown, transfer?: BridgeTransferable[]) => void;\n addEventListener: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n removeEventListener: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n start?: () => void;\n close?: () => void;\n}\n\n/**\n * The wire envelope. `payload` is the codec-encoded body — opaque to the router, which only routes on\n * `type` and correlates on `id`. Keeping the body opaque is what lets a future codec return a columnar\n * buffer (a transferable) in `payload` without any change to routing.\n */\nexport interface BridgeEnvelope {\n ch: typeof BRIDGE_CHANNEL;\n v: typeof BRIDGE_PROTOCOL_VERSION;\n type: BridgeMessageType;\n /** Correlation id for request/response pairs (rpc, subscribe, token pull). Absent for fire-and-forget fanout. */\n id?: string;\n /** Codec-encoded body — opaque to the router; decode with the same {@link BridgeCodec}. */\n payload: unknown;\n}\n\nexport type BridgeMessageType =\n // tab → worker\n | \"provision\"\n | \"attach\"\n | \"detach\"\n | \"token-push\"\n | \"token-response\"\n | \"rpc\"\n | \"subscribe\"\n | \"unsubscribe\"\n | \"wake\"\n | \"set-online\"\n // worker → tab\n | \"provision-ack\"\n | \"attach-ack\"\n | \"token-request\"\n | \"rpc-result\"\n | \"live-initial\"\n | \"live-diff\"\n | \"event\";\n\n// ─── Payload shapes ───────────────────────────────────────────────────────────\n\n/** A single auth token snapshot the tab owns and pushes to the worker (ADR-0032 decision 3). */\nexport interface AuthTokenSnapshot {\n accessToken: string;\n /** Absolute expiry in epoch milliseconds (`Date.now()`-comparable), so the worker can apply an expiry margin. */\n expiresAt: number;\n}\n\n/**\n * tab → worker: pre-spawn the store WITHOUT booting the engine (ADR-0032 decision 5). Sent at the\n * login screen against the freshly-named spare worker: the worker only runs PGlite `create`/initdb\n * (off every thread that matters) and holds the raw store idle — no schema, no shape streams, no token\n * — until the real {@link AttachPayload} arrives (with config + token) and adopts the provisioned store.\n * Role-agnostic on purpose: the spare is minted before the user (and role) is known, so provisioning\n * carries no registry — the schema is applied at attach with the role-resolved registry.\n */\nexport interface ProvisionPayload {\n /** The bound store id (informational; naming is done tab-side via the SharedWorker name). */\n storeId?: string;\n /** The PGlite data dir to `create` ahead of attach (`idb://…` in a browser, `memory://…` in tests). */\n dataDir?: string;\n}\n\n/** worker → tab: the provision completed (or failed). Lets the login screen confirm the spare is warm. */\nexport interface ProvisionAckPayload {\n ok: boolean;\n storeId?: string;\n /** Present when `!ok` — the initdb/create failed; the worker falls back to a fresh create at attach. */\n error?: { message: string };\n}\n\n/** tab → worker: the attach handshake. The first attach boots the engine; later attaches join it. */\nexport interface AttachPayload {\n /** The bound store id (SharedWorker naming resolves it tab-side before attach — ADR-0032 decision 5). */\n storeId?: string;\n /** Explicit PGlite data dir if the worker should create its own store; `memory://…` in tests. */\n dataDir?: string;\n /** The tab's current auth token at attach time, or null when unauthenticated. */\n token: AuthTokenSnapshot | null;\n /**\n * Serializable per-attach config overrides (kept minimal; the urls are baked into the worker). `role`\n * selects which baked registry the worker boots (ADR-0032 S3): the spare is minted role-agnostic, so\n * the role is only known at claim/attach — a single worker file bakes BOTH registries and picks here.\n * `freshStore` is the fresh-store prefetch-overlap hint (ADR-0032 S4): the tab's claim path knows a\n * claimed spare is schemaless (fresh) while a mapped/returning store never is, and forwards that here so\n * the worker's `createSyncClient` can overlap the shape catch-up with the local boot phases.\n */\n config?: { syncEnabled?: boolean; role?: string; freshStore?: boolean };\n}\n\n/**\n * tab → worker: gate the worker's outbound convergence (the board's Offline toggle, ADR-0032 S3). In\n * in-process mode the toggle gates the local `autoSync` trigger; the worker owns convergence instead, so\n * the tab forwards the flag and the worker suppresses/resumes its flush passes. Going back online fires\n * one immediate pass so queued writes flush without waiting for the next interval tick.\n */\nexport interface SetOnlinePayload {\n online: boolean;\n}\n\n/** worker → tab: attach acknowledged. `alreadyBooted` is false for the attach that booted the engine. */\nexport interface AttachAckPayload {\n alreadyBooted: boolean;\n /**\n * True when the engine's initial sync had ALREADY fired by the time this attach was acked (a late\n * attach, ADR-0032 FIX 3). `ready` is monotonic in-process — once it resolves it stays resolved even if\n * the phase later degrades — so a tab attaching after that moment must resolve `ready` immediately from\n * the ack, rather than wait for a phase-\"ready\" status that may never come again.\n */\n engineReady?: boolean;\n /**\n * Present when the engine boot REJECTED for this attach: the tab rejects `attachSyncClient` with this\n * message instead of hanging forever on the ack (ADR-0032 FIX 1). A later attach retries the boot.\n */\n error?: { message: string; detail?: unknown };\n}\n\n/** worker → tab: a broadcast pull-request — any attached tab may answer, first response wins (ADR-0032 decision 3). */\nexport interface TokenRequestPayload {\n requestId: string;\n}\n\n/** tab → worker: the answer to a {@link TokenRequestPayload}. `token: null` = the tab has none. */\nexport interface TokenResponsePayload {\n requestId: string;\n token: AuthTokenSnapshot | null;\n}\n\n/**\n * The RPC ops the attach facade proxies to the worker's booted client — the write API (mirrors\n * `client.mutate`/flush), mutation-state reads, and the one-shot raw inspection reads (`rawQuery`/`rawExec`).\n */\nexport type RpcOp =\n | \"create\"\n | \"update\"\n | \"delete\"\n | \"batch\"\n | \"transaction\"\n | \"flush\"\n | \"reconcile\"\n | \"retryFailed\"\n | \"recoverSending\"\n | \"discardConflict\"\n | \"discardQuarantined\"\n | \"readMutationDetails\"\n | \"diagnostics\"\n | \"rawQuery\"\n | \"rawExec\";\n\n/** tab → worker: a write/read-of-mutation-state RPC. `id` correlates the matching {@link RpcResultPayload}. */\nexport interface RpcPayload {\n op: RpcOp;\n args: unknown[];\n}\n\n/** worker → tab: an RPC outcome, mirroring today's in-process resolve/reject semantics. */\nexport interface RpcResultPayload {\n ok: boolean;\n /** The resolved value (present when `ok`). */\n value?: unknown;\n /** The rejection message + optional structured detail (present when `!ok`). */\n error?: { message: string; detail?: unknown };\n}\n\n/** tab → worker: register a live query. `id` correlates the initial snapshot; `queryId` keys subsequent diffs. */\nexport interface SubscribePayload {\n queryId: string;\n sql: string;\n params: unknown[];\n /**\n * The result's primary-key columns, driving diff keying (§4). One column → the incremental path\n * (`live.incrementalQuery`); many → worker-side diff by composite PK; empty/absent → value-identity\n * fallback for a keyless query.\n */\n pkColumns?: string[];\n /** Lazy relations to activate before the query runs (ADR-0021), forwarded to the worker's `prepareQuery`. */\n use?: string[];\n}\n\n/** worker → tab: the initial ordered snapshot for a subscription. `id` correlates the `subscribe` request. */\nexport interface LiveInitialPayload {\n queryId: string;\n rows: Record<string, unknown>[];\n}\n\n/**\n * worker → tab: a DIFF update for a subscription (§4). Never a full result-set resend after the initial\n * snapshot. `order` is the full ordered list of row keys (cheap — keys only, no row bodies); `added`/\n * `changed` carry only the delta row bodies; `removed` carries only the dropped keys. The tab materializer\n * rebuilds the ordered array from `order`, reusing cached row objects for keys not in `added`/`changed` so\n * an unchanged row keeps its object identity (React memo bails on `===`).\n */\nexport interface LiveDiffPayload {\n queryId: string;\n /** Every result key in ORDER BY order (the query's delivered order). */\n order: string[];\n added: { key: string; row: Record<string, unknown> }[];\n changed: { key: string; row: Record<string, unknown> }[];\n removed: string[];\n}\n\n/** worker → tab: the single broadcast event stream (ADR-0032 decision 7), re-exposed as today's callbacks. */\nexport type BridgeEvent =\n | { kind: \"status\"; status: SyncRuntimeStatus }\n | { kind: \"groupReady\"; groupKey: string }\n | { kind: \"conflict\"; details: unknown }\n | { kind: \"quarantine\"; details: unknown }\n | { kind: \"reject\"; details: unknown }\n | { kind: \"schema-change\"; event: unknown }\n | { kind: \"sync-error\"; message: string }\n | { kind: \"timing\"; label: string; ms: number; data?: Record<string, unknown> }\n // The debug rail (ADR-0032 decision 7): stamped with the WORKER's monotonic clock and origin-tagged so a\n // tab can re-print it as `[pgxsinkit·w <stamp>ms] <line>` — a SharedWorker's own console is invisible.\n | { kind: \"debug\"; stamp: number; line: string; data?: Record<string, unknown> };\n\n/** tab → worker: an app-driven wake (online/visibilitychange), treated as a convergence pass request. */\nexport interface WakePayload {\n reason: \"online\" | \"visibility\" | \"manual\";\n}\n\n// ─── Codec seam ─────────────────────────────────────────────────────────────\n\n/**\n * The codec every bridge payload crosses through (owner-mandated seam, ADR-0032 S2 §1). v1 ships exactly\n * ONE codec — {@link identityCodec}, which relies on the transport's own structured clone. The seam exists\n * so a columnar/transferable codec (e.g. one that packs live-diff rows into a shared `ArrayBuffer` and\n * returns it as a transferable) can be swapped in later WITHOUT any protocol change: the router already\n * treats `BridgeEnvelope.payload` as opaque, and `encode` may return `{ payload, transfer }` so the sender\n * hands transferables to `postMessage`. Keep encode/decode inverse and side-effect free.\n */\nexport interface BridgeCodec {\n /** Encode a raw payload into the envelope body. May declare transferables for a future zero-copy codec. */\n encode: (payload: unknown) => { payload: unknown; transfer?: BridgeTransferable[] };\n /** Decode an envelope body back into the raw payload. Inverse of {@link encode}. */\n decode: (payload: unknown) => unknown;\n}\n\n/**\n * The v1 identity codec: the body IS the payload, and the transport's structured clone does the real\n * copying. No transferables. The only codec shipped in S2 — swapping in a columnar codec later touches\n * only this object, never the message types or the router.\n */\nexport const identityCodec: BridgeCodec = {\n encode: (payload) => ({ payload }),\n decode: (payload) => payload,\n};\n\n// ─── Envelope helpers ─────────────────────────────────────────────────────────\n\n/** Build a wire envelope, running the payload through the codec. Returns the envelope + any transferables. */\nexport function encodeEnvelope(\n codec: BridgeCodec,\n type: BridgeMessageType,\n payload: unknown,\n id?: string,\n): { envelope: BridgeEnvelope; transfer?: BridgeTransferable[] } {\n const encoded = codec.encode(payload);\n const envelope: BridgeEnvelope = {\n ch: BRIDGE_CHANNEL,\n v: BRIDGE_PROTOCOL_VERSION,\n type,\n payload: encoded.payload,\n ...(id !== undefined ? { id } : {}),\n };\n return { envelope, ...(encoded.transfer ? { transfer: encoded.transfer } : {}) };\n}\n\n/** Type-guard a received message as a bridge envelope of the current protocol version (ignore foreign traffic). */\nexport function isBridgeEnvelope(data: unknown): data is BridgeEnvelope {\n return (\n typeof data === \"object\" &&\n data !== null &&\n (data as { ch?: unknown }).ch === BRIDGE_CHANNEL &&\n (data as { v?: unknown }).v === BRIDGE_PROTOCOL_VERSION\n );\n}\n\n/** Send a typed message over a port: encode → post (with any transferables). The one write choke point. */\nexport function postBridgeMessage(\n port: BridgePort,\n codec: BridgeCodec,\n type: BridgeMessageType,\n payload: unknown,\n id?: string,\n): void {\n const { envelope, transfer } = encodeEnvelope(codec, type, payload, id);\n if (transfer && transfer.length > 0) {\n port.postMessage(envelope, transfer);\n } else {\n port.postMessage(envelope);\n }\n}\n",
141
- "// The tab facade (ADR-0032 S2, decisions 3/4/6/7). `attachSyncClient` returns the SAME client shape as\n// `createSyncClient` wherever semantics allow — the write API (RPC-backed), per-group readiness, the\n// live-rows seam, `ready`/`status`/`stop` — transparently proxied to the one shared worker engine. The tab\n// stays the single auth owner: it pushes its token at attach and on `notifyAuthChanged`, and answers the\n// worker's expiry pull-requests via `getToken`.\n//\n// One-shot Drizzle reads (`query`/`queryRaw`/…), local `pglite`/`ensureSynced`/`destroy` are NOT proxied in\n// S2 (the mandated attach surface is the write API + live rows + readiness) — they throw a clear\n// not-supported error. Query BUILDING still works on the tab: `drizzle`/`views` are the same build-only\n// handles `createSyncClient` exposes, compiled to SQL here and executed in the worker.\n\nimport type { Results } from \"@electric-sql/pglite\";\n\nimport type {\n MutationDiagnostics,\n SyncRuntimeStatus,\n SyncTableName,\n SyncTableRegistry,\n WriteMode,\n} from \"@pgxsinkit/contracts\";\n\nimport {\n buildRegistryReadHandles,\n type LiveRowsSubscription,\n type MutationBatchItem,\n type MutationDetail,\n type SubscribeLiveRowsInput,\n type SyncClient,\n type SyncTransaction,\n type SyncTransactionResult,\n} from \"../index\";\nimport type { LocalStoreVersionEvent } from \"../local-store\";\nimport { LiveRowsMaterializer } from \"./live-diff\";\nimport {\n type AttachAckPayload,\n type AttachPayload,\n type AuthTokenSnapshot,\n type BridgeCodec,\n type BridgeEvent,\n type BridgePort,\n type BridgeTransferable,\n identityCodec,\n isBridgeEnvelope,\n type LiveDiffPayload,\n type LiveInitialPayload,\n postBridgeMessage,\n type ProvisionAckPayload,\n type RpcOp,\n type RpcResultPayload,\n type TokenRequestPayload,\n} from \"./protocol\";\n\n/** A `Worker`/`SharedWorker`-shaped handle: a dedicated `Worker` IS the port; a `SharedWorker` carries `.port`. */\ninterface WorkerLike {\n port?: BridgePort;\n postMessage?: (message: unknown, transfer?: BridgeTransferable[]) => void;\n addEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n removeEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n}\n\nexport interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {\n registry: TRegistry;\n /** A native `Worker` or `SharedWorker` (or anything port-shaped). Provide this OR {@link port}. */\n worker?: WorkerLike;\n /** A raw transport port (a `MessageChannel` port in tests, a `SharedWorker.port` in a browser). */\n port?: BridgePort;\n /**\n * The tab's token provider (ADR-0032 decision 3). Richer than `createSyncClient`'s string form: the\n * worker needs the EXPIRY to apply its pull margin, so this yields `{accessToken, expiresAt}` (or null\n * when unauthenticated). Pushed at attach and answered on every worker pull-request.\n */\n getToken?: () => Promise<AuthTokenSnapshot | null>;\n /** The bound store id (resolved tab-side before attach — SharedWorker naming, ADR-0032 decision 5). */\n storeId?: string;\n dataDir?: string;\n syncEnabled?: boolean;\n /**\n * Which baked registry the worker boots (ADR-0032 S3) — forwarded in the attach `config.role`. A worker\n * file that bakes multiple role variants (the board's admin/member) picks by this; single-registry\n * workers ignore it.\n */\n role?: string;\n /**\n * Fresh-store prefetch-overlap hint (ADR-0032 S4), forwarded in the attach `config.freshStore`. Set true\n * ONLY when the tab knows the store is a claimed schemaless spare (never for a mapped/returning store);\n * the worker's `createSyncClient` then overlaps the shape catch-up with its local boot phases.\n */\n freshStore?: boolean;\n codec?: BridgeCodec;\n onStatusChange?: (status: SyncRuntimeStatus) => void;\n onConflict?: (details: MutationDetail[]) => void;\n onQuarantine?: (details: MutationDetail[]) => void;\n onReject?: (details: MutationDetail[]) => void;\n onSchemaChange?: (event: LocalStoreVersionEvent) => void;\n onSyncError?: (error: Error) => void;\n}\n\n/**\n * The worker-attached client: `SyncClient`'s shape, worker-proxied, plus `notifyAuthChanged` (re-push the\n * token after an app auth-state change, ADR-0032 decision 3). The unsupported one-shot-read members throw.\n */\nexport type AttachedSyncClient<TRegistry extends SyncTableRegistry> = SyncClient<TRegistry> & {\n notifyAuthChanged: () => void;\n /**\n * Forward the app's Offline toggle to the worker (ADR-0032 S3). The worker owns convergence, so the\n * tab cannot gate a local trigger; this sends `set-online`, which suppresses/resumes the worker's flush\n * passes (resuming fires one immediate pass). The in-process client gates its own `autoSync` instead.\n */\n setOnline: (online: boolean) => void;\n};\n\nexport async function attachSyncClient<const TRegistry extends SyncTableRegistry>(\n options: AttachSyncClientOptions<TRegistry>,\n): Promise<AttachedSyncClient<TRegistry>> {\n const codec = options.codec ?? identityCodec;\n const port = resolvePort(options);\n\n // ─── Correlation + subscription bookkeeping ──────────────────────────────────────────────────────\n let nextId = 0;\n const newId = (prefix: string) => `${prefix}-${++nextId}`;\n const rpcPending = new Map<string, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();\n const initialPending = new Map<\n string,\n { resolve: (payload: LiveInitialPayload) => void; reject: (error: Error) => void }\n >();\n const diffHandlers = new Map<string, (diff: Omit<LiveDiffPayload, \"queryId\">) => void>();\n\n // ─── Status + readiness ──────────────────────────────────────────────────────────────────────────\n const status: SyncRuntimeStatus = { phase: \"booting\", isRunning: false };\n let resolveReady!: () => void;\n const ready = new Promise<void>((resolve) => {\n resolveReady = resolve;\n });\n let readyResolved = false;\n const readyGroups = new Set<string>();\n const groupWaiters = new Map<string, Array<() => void>>();\n\n // ─── Auth: push at attach + on notifyAuthChanged, answer pull-requests ────────────────────────────\n const pushToken = async () => {\n const token = options.getToken ? await options.getToken() : null;\n postBridgeMessage(port, codec, \"token-push\", token);\n };\n const answerPull = async (requestId: string) => {\n const token = options.getToken ? await options.getToken() : null;\n postBridgeMessage(port, codec, \"token-response\", { requestId, token });\n };\n\n // ─── Inbound message routing ─────────────────────────────────────────────────────────────────────\n const markReady = () => {\n if (readyResolved) return;\n readyResolved = true;\n resolveReady();\n };\n // Record a group as ready and settle any waiters — shared by the discrete `groupReady` edge and the\n // status snapshot's `status.groups` merge (ADR-0032 FIX 4), so a tab attaching after the edge fired\n // still resolves `client.groupReady(table)` off the snapshot it gets at attach.\n const markGroupReady = (groupKey: string) => {\n readyGroups.add(groupKey);\n const waiters = groupWaiters.get(groupKey);\n if (waiters) {\n groupWaiters.delete(groupKey);\n for (const resolve of waiters) resolve();\n }\n };\n const onEvent = (event: BridgeEvent) => {\n switch (event.kind) {\n case \"status\": {\n Object.assign(status, event.status);\n options.onStatusChange?.(event.status);\n // Match the in-process contract EXACTLY (ADR-0032 FIX 3): `ready` resolves ONLY from phase\n // \"ready\" (all eager groups caught up, or the syncEnabled:false path). `auth-needed`/`degraded`\n // do NOT resolve it — an engine stuck retrying auth keeps `ready` pending, as in-process.\n if (event.status.phase === \"ready\") markReady();\n // Late-attach group merge (ADR-0032 FIX 4): fold every already-ready group from the snapshot.\n for (const [groupKey, ready] of Object.entries(event.status.groups ?? {})) {\n if (ready) markGroupReady(groupKey);\n }\n break;\n }\n case \"groupReady\": {\n markGroupReady(event.groupKey);\n break;\n }\n case \"conflict\":\n options.onConflict?.(event.details as MutationDetail[]);\n break;\n case \"quarantine\":\n options.onQuarantine?.(event.details as MutationDetail[]);\n break;\n case \"reject\":\n options.onReject?.(event.details as MutationDetail[]);\n break;\n case \"schema-change\":\n options.onSchemaChange?.(event.event as LocalStoreVersionEvent);\n break;\n case \"sync-error\":\n options.onSyncError?.(new Error(event.message));\n break;\n case \"debug\": {\n // Re-print the worker's rail line gated on THIS tab's own flag, origin-tagged with the worker's\n // monotonic stamp (ADR-0032 decision 7) — a SharedWorker's own console is otherwise invisible.\n if ((globalThis as { __pgxsinkitDebug?: boolean }).__pgxsinkitDebug === true) {\n const line = `[pgxsinkit·w ${event.stamp.toFixed(0)}ms] ${event.line}`;\n if (event.data) console.debug(line, event.data);\n else console.debug(line);\n }\n break;\n }\n case \"timing\":\n break;\n default:\n break;\n }\n };\n\n const listener = (message: { data: unknown }) => {\n if (!isBridgeEnvelope(message.data)) return;\n const envelope = message.data;\n const payload = codec.decode(envelope.payload);\n switch (envelope.type) {\n case \"attach-ack\": {\n const ack = payload as AttachAckPayload;\n // A boot failure crosses in the ack's `error` (ADR-0032 FIX 1): reject the handshake so\n // `attachSyncClient` rejects instead of hanging forever. On success, the engine exists and the\n // status event that follows drives `ready`; `engineReady` covers a LATE attach whose engine already\n // fired its monotonic `ready` before this ack (FIX 3), so resolve `ready` straight away.\n if (ack.error) {\n attachAckReject?.(rebuildError(ack.error));\n } else {\n if (ack.engineReady) markReady();\n attachAckResolve?.(ack);\n }\n break;\n }\n case \"token-request\":\n void answerPull((payload as TokenRequestPayload).requestId);\n break;\n case \"rpc-result\": {\n const id = envelope.id;\n if (id == null) break;\n const result = payload as RpcResultPayload;\n const pending = rpcPending.get(id);\n if (pending) {\n rpcPending.delete(id);\n if (result.ok) pending.resolve(result.value);\n else pending.reject(rebuildError(result.error));\n break;\n }\n // A failed `subscribe` is reported as an `rpc-result` correlated by the subscribe's envelope id\n // (the worker has no client to hand an initial snapshot), so route the miss to the initial waiter\n // (ADR-0032 FIX 2). A successful subscribe never lands here — it resolves via `live-initial`.\n const initial = initialPending.get(id);\n if (initial && !result.ok) {\n initialPending.delete(id);\n initial.reject(rebuildError(result.error));\n }\n break;\n }\n case \"live-initial\": {\n const id = envelope.id;\n const initial = payload as LiveInitialPayload;\n if (id != null) {\n const pending = initialPending.get(id);\n if (pending) {\n initialPending.delete(id);\n pending.resolve(initial);\n }\n }\n break;\n }\n case \"live-diff\": {\n const diff = payload as LiveDiffPayload;\n diffHandlers.get(diff.queryId)?.(diff);\n break;\n }\n case \"event\":\n onEvent(payload as BridgeEvent);\n break;\n default:\n break;\n }\n };\n port.addEventListener(\"message\", listener);\n port.start?.();\n\n // ─── RPC helper ──────────────────────────────────────────────────────────────────────────────────\n const rpc = <T>(op: RpcOp, args: unknown[]): Promise<T> => {\n const id = newId(\"rpc\");\n return new Promise<T>((resolve, reject) => {\n rpcPending.set(id, { resolve: resolve as (value: unknown) => void, reject });\n postBridgeMessage(port, codec, \"rpc\", { op, args }, id);\n });\n };\n\n // ─── Attach handshake ────────────────────────────────────────────────────────────────────────────\n let attachAckResolve: ((ack: AttachAckPayload) => void) | null = null;\n let attachAckReject: ((error: Error) => void) | null = null;\n const attachAck = new Promise<AttachAckPayload>((resolve, reject) => {\n attachAckResolve = resolve;\n attachAckReject = reject;\n });\n const initialToken = options.getToken ? await options.getToken() : null;\n const attachPayload: AttachPayload = {\n token: initialToken,\n ...(options.storeId ? { storeId: options.storeId } : {}),\n ...(options.dataDir ? { dataDir: options.dataDir } : {}),\n ...(options.syncEnabled != null || options.role != null || options.freshStore != null\n ? {\n config: {\n ...(options.syncEnabled != null ? { syncEnabled: options.syncEnabled } : {}),\n ...(options.role != null ? { role: options.role } : {}),\n ...(options.freshStore != null ? { freshStore: options.freshStore } : {}),\n },\n }\n : {}),\n };\n postBridgeMessage(port, codec, \"attach\", attachPayload);\n try {\n await attachAck;\n } catch (error) {\n // The worker's engine boot failed (ADR-0032 FIX 1): tear down this tab's listener so no port handler\n // leaks, then let the boot error propagate out of `attachSyncClient`.\n port.removeEventListener(\"message\", listener);\n throw error;\n }\n status.isRunning = true;\n\n // ─── Live-rows seam (ADR-0032 S2 §4) ─────────────────────────────────────────────────────────────\n const subscribeLiveRows = async <TRow extends Record<string, unknown>>(\n input: SubscribeLiveRowsInput,\n onRows: (rows: TRow[]) => void,\n ): Promise<LiveRowsSubscription<TRow>> => {\n const queryId = newId(\"live\");\n const id = newId(\"sub\");\n const materializer = new LiveRowsMaterializer<TRow>(input.pkColumns);\n diffHandlers.set(queryId, (diff) => {\n onRows(materializer.apply(diff));\n });\n let initial: LiveInitialPayload;\n try {\n initial = await new Promise<LiveInitialPayload>((resolve, reject) => {\n initialPending.set(id, { resolve, reject });\n postBridgeMessage(\n port,\n codec,\n \"subscribe\",\n {\n queryId,\n sql: input.sql,\n params: [...input.params],\n ...(input.pkColumns ? { pkColumns: [...input.pkColumns] } : {}),\n ...(input.use ? { use: [...input.use] } : {}),\n },\n id,\n );\n });\n } catch (error) {\n // The worker rejected the subscribe (invalid SQL, etc.); the initial-payload waiter rejected via the\n // `rpc-result` route (ADR-0032 FIX 2). Drop the pre-registered diff handler so no orphan survives.\n diffHandlers.delete(queryId);\n throw error;\n }\n const initialRows = materializer.seed(initial.rows as TRow[]);\n return {\n initialRows,\n unsubscribe: () => {\n diffHandlers.delete(queryId);\n postBridgeMessage(port, codec, \"unsubscribe\", { queryId });\n },\n };\n };\n\n // ─── Assembled client ────────────────────────────────────────────────────────────────────────────\n const { drizzle, views } = buildRegistryReadHandles(options.registry);\n const notSupported = (name: string) => (): never => {\n throw new Error(\n `[pgxsinkit] ${name} is not available on a worker-attached client (ADR-0032 S2). Use the live-rows hooks / subscribeLiveRows for reads, the write API for mutations.`,\n );\n };\n\n const groupKeyForTable = (table: SyncTableName<TRegistry>): string | undefined => {\n const entry = options.registry[table];\n return entry?.consistencyGroup ?? entry?.shape?.shapeKey;\n };\n\n const client: AttachedSyncClient<TRegistry> = {\n drizzle,\n views,\n // The tab has no local PGlite; reads go through the live-rows bridge. Touching `.pglite` is a misuse.\n pglite: new Proxy(\n {},\n {\n get: notSupported(\"client.pglite\"),\n },\n ) as never,\n tables: Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n key: tableKey,\n mode: options.registry[tableKey as SyncTableName<TRegistry>]!.mode,\n create: (input: unknown) => rpc<void>(\"create\", [tableKey, input]),\n update: (entityKey: Record<string, string>, patch: unknown) =>\n rpc<void>(\"update\", [tableKey, entityKey, patch]),\n delete: (entityKey: Record<string, string>) => rpc<void>(\"delete\", [tableKey, entityKey]),\n },\n ]),\n ) as SyncClient<TRegistry>[\"tables\"],\n ready,\n status,\n start: async () => {\n await ready;\n },\n stop: async () => {\n // Detach THIS tab; the worker engine keeps running for other tabs (ADR-0032 decision 2).\n status.isRunning = false;\n for (const queryId of diffHandlers.keys()) postBridgeMessage(port, codec, \"unsubscribe\", { queryId });\n diffHandlers.clear();\n postBridgeMessage(port, codec, \"detach\", null);\n port.removeEventListener(\"message\", listener);\n port.close?.();\n },\n destroy: notSupported(\"client.destroy\"),\n dropReadCache: notSupported(\"client.dropReadCache\"),\n flush: (table) => rpc<void>(\"flush\", [table]),\n reconcile: (table) => rpc<void>(\"reconcile\", [table]),\n retryFailed: (table) => rpc<void>(\"retryFailed\", [table]),\n recoverSending: (table) => rpc<void>(\"recoverSending\", [table]),\n readMutationDetails: (table) => rpc<MutationDetail[]>(\"readMutationDetails\", [table]),\n // Inspection reads run in the worker (ADR-0032 S2) — the same surface as the in-process client. `pglite`\n // itself stays blocked (below); these route the raw statement over the RPC round-trip instead.\n rawQuery: (sql, params, options) => rpc<Results>(\"rawQuery\", [sql, params, options]),\n rawExec: (sql, options) => rpc<Results[]>(\"rawExec\", [sql, options]),\n mutate: {\n create: (table, input) => rpc<void>(\"create\", [table, input]),\n update: (table, entityKey, patch) => rpc<void>(\"update\", [table, entityKey, patch]),\n delete: (table, entityKey) => rpc<void>(\"delete\", [table, entityKey]),\n batch: (items) => rpc<void>(\"batch\", [items]),\n },\n discardConflict: (table, entityKey) => rpc<void>(\"discardConflict\", [table, entityKey]),\n discardQuarantined: (table, entityKey) => rpc<void>(\"discardQuarantined\", [table, entityKey]),\n diagnostics: (table) => rpc<{ mutation: MutationDiagnostics }>(\"diagnostics\", [table]),\n query: notSupported(\"client.query\"),\n queryRow: notSupported(\"client.queryRow\"),\n queryRaw: notSupported(\"client.queryRaw\"),\n queryRawRow: notSupported(\"client.queryRawRow\"),\n ensureSynced: notSupported(\"client.ensureSynced\"),\n isSynced: notSupported(\"client.isSynced\"),\n desync: notSupported(\"client.desync\"),\n // The worker activates lazy relations inside its `subscribe` handler (via the `use` hint), so the tab's\n // `prepareQuery` is a no-op — the live-rows subscription is already guarded worker-side (ADR-0021).\n prepareQuery: async () => undefined,\n transaction: async ({ mode }: { mode: WriteMode }, run) => {\n // Collect the unit's mutations tab-side (the run callback cannot cross the wire), then RPC the\n // serialized items + mode; the worker replays them into a real `client.transaction` (matching acks).\n const collected: MutationBatchItem<TRegistry>[] = [];\n const txTables = Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n create: (input: unknown) => {\n collected.push({ table: tableKey, kind: \"create\", input } as MutationBatchItem<TRegistry>);\n },\n update: (entityKey: Record<string, string>, patch: unknown) => {\n collected.push({ table: tableKey, kind: \"update\", entityKey, patch } as MutationBatchItem<TRegistry>);\n },\n updateBlind: (entityKey: Record<string, string>, patch: unknown) => {\n // ADR-0022 addendum: the `blind` flag rides the serialized item across the wire; the worker\n // replays it through `client.transaction`'s `updateBlind`, identical to the in-process client.\n collected.push({\n table: tableKey,\n kind: \"update\",\n entityKey,\n patch,\n blind: true,\n } as MutationBatchItem<TRegistry>);\n },\n delete: (entityKey: Record<string, string>) => {\n collected.push({ table: tableKey, kind: \"delete\", entityKey } as MutationBatchItem<TRegistry>);\n },\n },\n ]),\n ) as SyncTransaction<TRegistry>[\"tables\"];\n await run({ tables: txTables });\n if (collected.length === 0) return { acks: [] };\n return rpc<SyncTransactionResult>(\"transaction\", [{ mode, items: collected }]);\n },\n groupReady: async (table) => {\n const groupKey = groupKeyForTable(table);\n if (groupKey == null || readyGroups.has(groupKey)) return;\n await new Promise<void>((resolve) => {\n const waiters = groupWaiters.get(groupKey) ?? [];\n waiters.push(resolve);\n groupWaiters.set(groupKey, waiters);\n });\n },\n subscribeLiveRows,\n notifyAuthChanged: () => {\n void pushToken();\n },\n setOnline: (online: boolean) => {\n postBridgeMessage(port, codec, \"set-online\", { online });\n },\n };\n\n return client;\n}\n\n/**\n * Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen\n * against a freshly-named spare `SharedWorker`: the worker runs PGlite `create`/initdb only and holds the\n * raw store idle until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the\n * provision (its initdb settled); rejects only if the worker reports the create failed — the caller treats\n * either outcome as best-effort, since attach falls back to a fresh create regardless.\n */\nexport function provisionSyncWorker<TRegistry extends SyncTableRegistry>(\n options: Pick<AttachSyncClientOptions<TRegistry>, \"worker\" | \"port\" | \"storeId\" | \"dataDir\" | \"codec\">,\n): Promise<void> {\n const codec = options.codec ?? identityCodec;\n const port = resolvePort(options);\n return new Promise<void>((resolve, reject) => {\n const listener = (message: { data: unknown }) => {\n if (!isBridgeEnvelope(message.data)) return;\n if (message.data.type !== \"provision-ack\") return;\n port.removeEventListener(\"message\", listener);\n const ack = codec.decode(message.data.payload) as ProvisionAckPayload;\n if (ack.ok) resolve();\n else reject(new Error(ack.error?.message ?? \"worker provision failed\"));\n };\n port.addEventListener(\"message\", listener);\n port.start?.();\n postBridgeMessage(port, codec, \"provision\", {\n ...(options.storeId ? { storeId: options.storeId } : {}),\n ...(options.dataDir ? { dataDir: options.dataDir } : {}),\n });\n });\n}\n\n/** Resolve the transport port from the options: an explicit port, a SharedWorker's `.port`, or a Worker itself. */\nfunction resolvePort(options: { port?: BridgePort; worker?: WorkerLike }): BridgePort {\n if (options.port) return options.port;\n const worker = options.worker;\n if (!worker) throw new Error(\"attachSyncClient: provide a `worker` or a `port`.\");\n if (worker.port) return worker.port;\n if (worker.postMessage && worker.addEventListener && worker.removeEventListener) {\n return worker as BridgePort;\n }\n throw new Error(\"attachSyncClient: the provided `worker` is neither a Worker nor a SharedWorker port.\");\n}\n\n/** Rebuild an Error from the bridge's serialized `{message, detail}` shape, carrying `detail` through. */\nfunction rebuildError(error: RpcResultPayload[\"error\"]): Error {\n const rebuilt = new Error(error?.message ?? \"worker rpc failed\");\n if (error && \"detail\" in error && error.detail !== undefined) {\n (rebuilt as Error & { detail?: unknown }).detail = error.detail;\n }\n return rebuilt;\n}\n",
147
+ "// The bridge protocol (ADR-0032 S2). Everything that crosses between a tab and the shared sync engine\n// travels as a typed {@link BridgeEnvelope} over a minimal {@link BridgePort} (a MessagePort-shaped\n// transport). The router only ever inspects the envelope's `type`/`id`; its `payload` is OPAQUE to the\n// router and always passes through a {@link BridgeCodec}, so a later columnar/transferable codec can be\n// swapped in WITHOUT any protocol change (see BridgeCodec's doc).\n//\n// Deliberately transport-agnostic: `defineSyncWorker` and `attachSyncClient` both talk to a `BridgePort`,\n// never a real `Worker`/`SharedWorker` directly — which is exactly why the whole bridge is unit-testable\n// over bun's `MessageChannel` with no worker at all.\n\nimport type { SyncRuntimeStatus } from \"@pgxsinkit/contracts\";\n\nimport type { BootReport } from \"../boot-report\";\nimport type { ExportReport } from \"../export-store\";\n\nexport const BRIDGE_CHANNEL = \"pgxsinkit-bridge\" as const;\nexport const BRIDGE_PROTOCOL_VERSION = 1 as const;\n\n/**\n * A structured-clone transferable (an `ArrayBuffer`, a `MessagePort`, …). The library carries no DOM lib\n * dependency (like the convergence triggers), so this is the toolkit's own name for the type a future\n * columnar codec would hand to `postMessage`'s transfer list. v1's identity codec never produces one.\n */\nexport type BridgeTransferable = unknown;\n\n/**\n * The minimal MessagePort-shaped transport the bridge needs — the intersection of a real `MessagePort`,\n * a `SharedWorker` port, and a dedicated `Worker`/`self`. Injected everywhere so the protocol layer is\n * exercised with a plain `MessageChannel` (no Worker) in tests. `start()` is optional (MessagePort needs\n * it, `Worker`/`self` do not); `close()` is optional (a dedicated `self` cannot be closed by the tab).\n */\nexport interface BridgePort {\n postMessage: (message: unknown, transfer?: BridgeTransferable[]) => void;\n addEventListener: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n removeEventListener: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n start?: () => void;\n close?: () => void;\n}\n\n/**\n * The wire envelope. `payload` is the codec-encoded body — opaque to the router, which only routes on\n * `type` and correlates on `id`. Keeping the body opaque is what lets a future codec return a columnar\n * buffer (a transferable) in `payload` without any change to routing.\n */\nexport interface BridgeEnvelope {\n ch: typeof BRIDGE_CHANNEL;\n v: typeof BRIDGE_PROTOCOL_VERSION;\n type: BridgeMessageType;\n /** Correlation id for request/response pairs (rpc, subscribe, token pull). Absent for fire-and-forget fanout. */\n id?: string;\n /** Codec-encoded body — opaque to the router; decode with the same {@link BridgeCodec}. */\n payload: unknown;\n}\n\nexport type BridgeMessageType =\n // tab → worker\n | \"provision\"\n | \"attach\"\n | \"detach\"\n | \"token-push\"\n | \"token-response\"\n | \"rpc\"\n | \"subscribe\"\n | \"unsubscribe\"\n | \"wake\"\n | \"set-online\"\n // worker → tab\n | \"provision-ack\"\n | \"attach-ack\"\n | \"token-request\"\n | \"rpc-result\"\n | \"live-initial\"\n | \"live-diff\"\n | \"event\";\n\n// ─── Payload shapes ───────────────────────────────────────────────────────────\n\n/** A single auth token snapshot the tab owns and pushes to the worker (ADR-0032 decision 3). */\nexport interface AuthTokenSnapshot {\n accessToken: string;\n /** Absolute expiry in epoch milliseconds (`Date.now()`-comparable), so the worker can apply an expiry margin. */\n expiresAt: number;\n}\n\n/**\n * tab → worker: pre-spawn the store WITHOUT booting the engine (ADR-0032 decision 5). Sent at the\n * login screen against the freshly-named spare worker: the worker only runs PGlite `create`/initdb\n * (off every thread that matters) and holds the raw store idle — no schema, no shape streams, no token\n * — until the real {@link AttachPayload} arrives (with config + token) and adopts the provisioned store.\n * Role-agnostic on purpose: the spare is minted before the user (and role) is known, so provisioning\n * carries no registry — the schema is applied at attach with the role-resolved registry.\n */\nexport interface ProvisionPayload {\n /** The bound store id (informational; naming is done tab-side via the SharedWorker name). */\n storeId?: string;\n /**\n * The plain store PATH (ADR-0036) to `create` ahead of attach — a name, not a storage URL; the worker\n * derives the backend (IndexedDB in a browser worker). When omitted, `storeId`/the worker default is used.\n */\n storePath?: string;\n /**\n * @internal INTERNAL WIRE FIELD (not consumer config, ADR-0036). Carries the testing memory-backend\n * override across the bridge, because a symbol-keyed marker does NOT survive `postMessage` structured\n * clone — so the worker's memory-store selection travels as this explicit field. Set only by the test\n * lane (via the attaching helper); a browser worker never sends it.\n */\n testStoreBackend?: \"memory\";\n}\n\n/** worker → tab: the provision completed (or failed). Lets the login screen confirm the spare is warm. */\nexport interface ProvisionAckPayload {\n ok: boolean;\n storeId?: string;\n /** Present when `!ok` — the initdb/create failed; the worker falls back to a fresh create at attach. */\n error?: { message: string };\n}\n\n/**\n * tab → worker: a store-backup tarball to restore from, carried on the boot {@link AttachPayload}\n * (ADR-0035 decision 6). The mirror image of {@link ExportArtefactWire}: a `File`/`Blob` cannot cross the\n * bridge as a transferable, so it is decomposed into its zero-copy `ArrayBuffer` (listed on `postMessage`'s\n * transfer list) plus the metadata to rebuild it, and the worker reassembles a `Blob` from\n * `buffer`/`mimeType` to hand `createSyncClient` as `restoreFrom`.\n */\nexport interface RestoreArtefactWire {\n /** The backup tarball bytes — transferred, not copied. */\n buffer: ArrayBuffer;\n /** The backup file name (informational; PGlite's `loadDataDir` reads the bytes, not the name). */\n fileName: string;\n /** The backup MIME type (`application/x-gzip` / `application/x-tar`), used to rebuild the `Blob`. */\n mimeType: string;\n}\n\n/** tab → worker: the attach handshake. The first attach boots the engine; later attaches join it. */\nexport interface AttachPayload {\n /** The bound store id (SharedWorker naming resolves it tab-side before attach — ADR-0032 decision 5). */\n storeId?: string;\n /**\n * Explicit plain store PATH (ADR-0036) if the worker should create its own store — a name, not a storage\n * URL; the worker derives the backend. When omitted, `storeId`/the worker default is used.\n */\n storePath?: string;\n /**\n * @internal INTERNAL WIRE FIELD (not consumer config, ADR-0036). Carries the testing memory-backend\n * override across the bridge — a symbol-keyed marker does not survive structured clone, so the worker's\n * memory-store selection travels as this explicit field. Set only by the test lane; never by a browser tab.\n */\n testStoreBackend?: \"memory\";\n /**\n * Restore the store from a backup on THIS attach (ADR-0035 decision 6) — the worker-mode carrier of\n * `createSyncClient`'s `restoreFrom`. Restore rides the FIRST attach (the boot attach): a `File`/`Blob`\n * cannot cross `postMessage` as a transferable, so the tab decomposes it into a transferred `ArrayBuffer`\n * plus its name/mime — the {@link ExportArtefactWire} pattern in reverse — and the worker recomposes it\n * into a `Blob` and hands it to `createSyncClient`. Absent on every ordinary attach. An attach that carries\n * this AFTER the engine has already booted is REFUSED (you cannot restore into a running store).\n */\n restore?: RestoreArtefactWire;\n /** The tab's current auth token at attach time, or null when unauthenticated. */\n token: AuthTokenSnapshot | null;\n /**\n * Serializable per-attach config overrides (kept minimal; the urls are baked into the worker). `role`\n * selects which baked registry the worker boots (ADR-0032 S3): the spare is minted role-agnostic, so\n * the role is only known at claim/attach — a single worker file bakes BOTH registries and picks here.\n * `freshStore` is the fresh-store prefetch-overlap hint (ADR-0032 S4): the tab's claim path knows a\n * claimed spare is schemaless (fresh) while a mapped/returning store never is, and forwards that here so\n * the worker's `createSyncClient` can overlap the shape catch-up with the local boot phases.\n */\n config?: { syncEnabled?: boolean; role?: string; freshStore?: boolean };\n}\n\n/**\n * tab → worker: gate the worker's outbound convergence (the board's Offline toggle, ADR-0032 S3). In\n * in-process mode the toggle gates the local `autoSync` trigger; the worker owns convergence instead, so\n * the tab forwards the flag and the worker suppresses/resumes its flush passes. Going back online fires\n * one immediate pass so queued writes flush without waiting for the next interval tick.\n */\nexport interface SetOnlinePayload {\n online: boolean;\n}\n\n/** worker → tab: attach acknowledged. `alreadyBooted` is false for the attach that booted the engine. */\nexport interface AttachAckPayload {\n alreadyBooted: boolean;\n /**\n * True when the engine's initial sync had ALREADY fired by the time this attach was acked (a late\n * attach, ADR-0032 FIX 3). `ready` is monotonic in-process — once it resolves it stays resolved even if\n * the phase later degrades — so a tab attaching after that moment must resolve `ready` immediately from\n * the ack, rather than wait for a phase-\"ready\" status that may never come again.\n */\n engineReady?: boolean;\n /**\n * Present when the engine boot REJECTED for this attach: the tab rejects `attachSyncClient` with this\n * message instead of hanging forever on the ack (ADR-0032 FIX 1). A later attach retries the boot.\n */\n error?: { message: string; detail?: unknown };\n}\n\n/** worker → tab: a broadcast pull-request — any attached tab may answer, first response wins (ADR-0032 decision 3). */\nexport interface TokenRequestPayload {\n requestId: string;\n}\n\n/** tab → worker: the answer to a {@link TokenRequestPayload}. `token: null` = the tab has none. */\nexport interface TokenResponsePayload {\n requestId: string;\n token: AuthTokenSnapshot | null;\n}\n\n/**\n * The RPC ops the attach facade proxies to the worker's booted client — the write API (mirrors\n * `client.mutate`/flush), mutation-state reads, and the one-shot raw inspection reads (`rawQuery`/`rawExec`).\n */\nexport type RpcOp =\n | \"create\"\n | \"update\"\n | \"delete\"\n | \"batch\"\n | \"transaction\"\n | \"flush\"\n | \"reconcile\"\n | \"retryFailed\"\n | \"recoverSending\"\n | \"discardConflict\"\n | \"discardQuarantined\"\n | \"desync\"\n | \"discardEphemeral\"\n | \"readMutationDetails\"\n | \"diagnostics\"\n | \"rawQuery\"\n | \"rawExec\"\n // Boot observability (ADR-0034): pull the worker engine's most recent completed boot report. Returns the\n // stored report (or null) regardless of when this tab attached, so a late tab reads a boot predating it.\n | \"bootReport\"\n // Store backup (ADR-0035): the worker runs the live `exportStore` on its owned client; the dump crosses\n // back as a transferred `ArrayBuffer` ({@link ExportArtefactWire}), rebuilt into a `File` tab-side.\n | \"exportStore\"\n // Diagnostic dump (ADR-0035): the worker runs `exportDiagnostics` on its owned client (live datadir dump\n // → memory throwaway clone → `pg_dump`); the SQL crosses back as the same transferred `ArrayBuffer` wire.\n | \"exportDiagnostics\"\n // Data export (ADR-0035): the worker runs `exportData` on its owned client (drain the journal → throwaway\n // clone → `pg_dump -t` per synced table); the portable SQL crosses back as the same transferred wire.\n | \"exportData\";\n\n/** tab → worker: a write/read-of-mutation-state RPC. `id` correlates the matching {@link RpcResultPayload}. */\nexport interface RpcPayload {\n op: RpcOp;\n args: unknown[];\n}\n\n/**\n * worker → tab: the wire form of ANY local-store export (ADR-0035) — the store backup's tarball OR the\n * diagnostic dump's SQL — carried as the `value` of an {@link RpcResultPayload}. The artefact crosses as a\n * transferred `ArrayBuffer` (zero-copy — the sender lists `buffer` in `postMessage`'s transfer list) plus\n * the metadata to rebuild it; the tab reconstructs a `File` from `buffer`/`fileName`/`mimeType`. A `File`\n * cannot itself be transferred, so it is decomposed here and reassembled tab-side, exactly the pattern the\n * codec's transferable seam anticipates for a zero-copy live-diff payload. `report` is the discriminated\n * {@link ExportReport} union, so the tab knows which export it round-tripped.\n */\nexport interface ExportArtefactWire {\n /** The artefact bytes (tarball or SQL) — transferred, not copied. */\n buffer: ArrayBuffer;\n /** The generated (or caller-supplied) artefact file name. */\n fileName: string;\n /** The artefact MIME type (`application/x-gzip` / `application/x-tar` for a backup, `application/sql` for a dump). */\n mimeType: string;\n /** The export report (ADR-0035), structured-cloned as a plain object — the `kind`-discriminated union. */\n report: ExportReport;\n}\n\n/** worker → tab: an RPC outcome, mirroring today's in-process resolve/reject semantics. */\nexport interface RpcResultPayload {\n ok: boolean;\n /** The resolved value (present when `ok`). */\n value?: unknown;\n /** The rejection message + optional structured detail (present when `!ok`). */\n error?: { message: string; detail?: unknown };\n}\n\n/** tab → worker: register a live query. `id` correlates the initial snapshot; `queryId` keys subsequent diffs. */\nexport interface SubscribePayload {\n queryId: string;\n sql: string;\n params: unknown[];\n /**\n * The unique output aliases the worker wraps the query's columns under so it is safe to MATERIALISE\n * (one per output column, in the compiled SQL's column order). ADDITIVE and backward-compatible: an\n * older tab omits it and the worker leaves the SQL untouched (name-keyed rows, as before); a newer tab\n * supplies it for a JOIN with same-named columns, which `live.query`/`live.incrementalQuery` otherwise\n * refuse to materialise (`column \"title\" specified more than once`). When present, result columns are\n * the aliases, so {@link pkColumns} must name a PK by its alias.\n */\n fields?: string[];\n /**\n * The result's primary-key columns, driving diff keying (§4). One column → the incremental path\n * (`live.incrementalQuery`); many → worker-side diff by composite PK; empty/absent → value-identity\n * fallback for a keyless query. When {@link fields} is supplied these name the ALIASED result columns.\n */\n pkColumns?: string[];\n /** Lazy relations to activate before the query runs (ADR-0021), forwarded to the worker's `prepareQuery`. */\n use?: string[];\n}\n\n/** worker → tab: the initial ordered snapshot for a subscription. `id` correlates the `subscribe` request. */\nexport interface LiveInitialPayload {\n queryId: string;\n rows: Record<string, unknown>[];\n}\n\n/**\n * worker → tab: a DIFF update for a subscription (§4). Never a full result-set resend after the initial\n * snapshot. `order` is the full ordered list of row keys (cheap — keys only, no row bodies); `added`/\n * `changed` carry only the delta row bodies; `removed` carries only the dropped keys. The tab materializer\n * rebuilds the ordered array from `order`, reusing cached row objects for keys not in `added`/`changed` so\n * an unchanged row keeps its object identity (React memo bails on `===`).\n */\nexport interface LiveDiffPayload {\n queryId: string;\n /** Every result key in ORDER BY order (the query's delivered order). */\n order: string[];\n added: { key: string; row: Record<string, unknown> }[];\n changed: { key: string; row: Record<string, unknown> }[];\n removed: string[];\n}\n\n/** worker → tab: the single broadcast event stream (ADR-0032 decision 7), re-exposed as today's callbacks. */\nexport type BridgeEvent =\n | { kind: \"status\"; status: SyncRuntimeStatus }\n | { kind: \"groupReady\"; groupKey: string }\n | { kind: \"conflict\"; details: unknown }\n | { kind: \"quarantine\"; details: unknown }\n | { kind: \"reject\"; details: unknown }\n | { kind: \"schema-change\"; event: unknown }\n | { kind: \"sync-error\"; message: string }\n | { kind: \"timing\"; label: string; ms: number; data?: Record<string, unknown> }\n // Boot observability (ADR-0034): the one-shot boot report, broadcast to currently-attached ports when the\n // engine's boot finalizes (the push counterpart of the `bootReport` pull). Later tabs read it via the pull.\n | { kind: \"boot-report\"; report: BootReport }\n // The debug rail (ADR-0032 decision 7): stamped with the WORKER's monotonic clock and origin-tagged so a\n // tab can re-print it as `[pgxsinkit·w <stamp>ms] <line>` — a SharedWorker's own console is invisible.\n | { kind: \"debug\"; stamp: number; line: string; data?: Record<string, unknown> };\n\n/** tab → worker: an app-driven wake (online/visibilitychange), treated as a convergence pass request. */\nexport interface WakePayload {\n reason: \"online\" | \"visibility\" | \"manual\";\n}\n\n// ─── Codec seam ─────────────────────────────────────────────────────────────\n\n/**\n * The codec every bridge payload crosses through (owner-mandated seam, ADR-0032 S2 §1). v1 ships exactly\n * ONE codec — {@link identityCodec}, which relies on the transport's own structured clone. The seam exists\n * so a columnar/transferable codec (e.g. one that packs live-diff rows into a shared `ArrayBuffer` and\n * returns it as a transferable) can be swapped in later WITHOUT any protocol change: the router already\n * treats `BridgeEnvelope.payload` as opaque, and `encode` may return `{ payload, transfer }` so the sender\n * hands transferables to `postMessage`. Keep encode/decode inverse and side-effect free.\n */\nexport interface BridgeCodec {\n /** Encode a raw payload into the envelope body. May declare transferables for a future zero-copy codec. */\n encode: (payload: unknown) => { payload: unknown; transfer?: BridgeTransferable[] };\n /** Decode an envelope body back into the raw payload. Inverse of {@link encode}. */\n decode: (payload: unknown) => unknown;\n}\n\n/**\n * The v1 identity codec: the body IS the payload, and the transport's structured clone does the real\n * copying. No transferables. The only codec shipped in S2 — swapping in a columnar codec later touches\n * only this object, never the message types or the router.\n */\nexport const identityCodec: BridgeCodec = {\n encode: (payload) => ({ payload }),\n decode: (payload) => payload,\n};\n\n// ─── Envelope helpers ─────────────────────────────────────────────────────────\n\n/** Build a wire envelope, running the payload through the codec. Returns the envelope + any transferables. */\nexport function encodeEnvelope(\n codec: BridgeCodec,\n type: BridgeMessageType,\n payload: unknown,\n id?: string,\n): { envelope: BridgeEnvelope; transfer?: BridgeTransferable[] } {\n const encoded = codec.encode(payload);\n const envelope: BridgeEnvelope = {\n ch: BRIDGE_CHANNEL,\n v: BRIDGE_PROTOCOL_VERSION,\n type,\n payload: encoded.payload,\n ...(id !== undefined ? { id } : {}),\n };\n return { envelope, ...(encoded.transfer ? { transfer: encoded.transfer } : {}) };\n}\n\n/** Type-guard a received message as a bridge envelope of the current protocol version (ignore foreign traffic). */\nexport function isBridgeEnvelope(data: unknown): data is BridgeEnvelope {\n return (\n typeof data === \"object\" &&\n data !== null &&\n (data as { ch?: unknown }).ch === BRIDGE_CHANNEL &&\n (data as { v?: unknown }).v === BRIDGE_PROTOCOL_VERSION\n );\n}\n\n/**\n * Send a typed message over a port: encode → post (with any transferables). The one write choke point.\n * `transfer` lets a caller declare payload-specific transferables (e.g. a store-backup's `ArrayBuffer`,\n * ADR-0035) WITHOUT teaching the shared codec about that op — they are merged after any the codec itself\n * produces, so both the codec's future zero-copy path and per-message transfers coexist.\n */\nexport function postBridgeMessage(\n port: BridgePort,\n codec: BridgeCodec,\n type: BridgeMessageType,\n payload: unknown,\n id?: string,\n transfer?: BridgeTransferable[],\n): void {\n const { envelope, transfer: codecTransfer } = encodeEnvelope(codec, type, payload, id);\n const allTransfer = [...(codecTransfer ?? []), ...(transfer ?? [])];\n if (allTransfer.length > 0) {\n port.postMessage(envelope, allTransfer);\n } else {\n port.postMessage(envelope);\n }\n}\n",
148
+ "// The tab facade (ADR-0032 S2, decisions 3/4/6/7). `attachSyncClient` returns the SAME client shape as\n// `createSyncClient` wherever semantics allow — the write API (RPC-backed), per-group readiness, the\n// live-rows seam, `ready`/`status`/`stop` — transparently proxied to the one shared worker engine. The tab\n// stays the single auth owner: it pushes its token at attach and on `notifyAuthChanged`, and answers the\n// worker's expiry pull-requests via `getToken`.\n//\n// One-shot Drizzle reads (`query`/`queryRaw`/…), local `pglite`/`ensureSynced`/`destroy` are NOT proxied in\n// S2 (the mandated attach surface is the write API + live rows + readiness) — they throw a clear\n// not-supported error. Query BUILDING still works on the tab: `drizzle`/`views` are the same build-only\n// handles `createSyncClient` exposes, compiled to SQL here and executed in the worker.\n\nimport type { Results } from \"@electric-sql/pglite\";\n\nimport type {\n MutationDiagnostics,\n SyncRuntimeStatus,\n SyncTableName,\n SyncTableRegistry,\n WriteMode,\n} from \"@pgxsinkit/contracts\";\n\nimport type { BootReport } from \"../boot-report\";\nimport type { DataExportOptions, DataExportResult } from \"../export-data\";\nimport type { DiagnosticExportOptions, DiagnosticExportResult } from \"../export-dump\";\nimport type { StoreExportOptions, StoreExportResult } from \"../export-store\";\nimport {\n buildRegistryReadHandles,\n type LiveRowsSubscription,\n type MutationBatchItem,\n type MutationDetail,\n type SubscribeLiveRowsInput,\n type SyncClient,\n type SyncTransaction,\n type SyncTransactionResult,\n} from \"../index\";\nimport type { LocalStoreVersionEvent } from \"../local-store\";\nimport { readTestStoreMarker } from \"../store-path\";\nimport { LiveRowsMaterializer } from \"./live-diff\";\nimport {\n type AttachAckPayload,\n type AttachPayload,\n type AuthTokenSnapshot,\n type BridgeCodec,\n type BridgeEvent,\n type BridgePort,\n type BridgeTransferable,\n type ExportArtefactWire,\n identityCodec,\n isBridgeEnvelope,\n type LiveDiffPayload,\n type LiveInitialPayload,\n postBridgeMessage,\n type ProvisionAckPayload,\n type RestoreArtefactWire,\n type RpcOp,\n type RpcResultPayload,\n type TokenRequestPayload,\n} from \"./protocol\";\n\n/** A `Worker`/`SharedWorker`-shaped handle: a dedicated `Worker` IS the port; a `SharedWorker` carries `.port`. */\ninterface WorkerLike {\n port?: BridgePort;\n postMessage?: (message: unknown, transfer?: BridgeTransferable[]) => void;\n addEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n removeEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n}\n\nexport interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {\n registry: TRegistry;\n /** A native `Worker` or `SharedWorker` (or anything port-shaped). Provide this OR {@link port}. */\n worker?: WorkerLike;\n /** A raw transport port (a `MessageChannel` port in tests, a `SharedWorker.port` in a browser). */\n port?: BridgePort;\n /**\n * The tab's token provider (ADR-0032 decision 3). Richer than `createSyncClient`'s string form: the\n * worker needs the EXPIRY to apply its pull margin, so this yields `{accessToken, expiresAt}` (or null\n * when unauthenticated). Pushed at attach and answered on every worker pull-request.\n */\n getToken?: () => Promise<AuthTokenSnapshot | null>;\n /** The bound store id (resolved tab-side before attach — SharedWorker naming, ADR-0032 decision 5). */\n storeId?: string;\n /**\n * The plain store PATH (ADR-0036) the worker opens if it must create its own store — a name, not a\n * storage URL. Spread `memoryStoreForTests(...)` from `@pgxsinkit/client/testing` here for a memory store\n * in tests (it also carries the internal marker forwarded to the worker as the memory-backend override).\n */\n storePath?: string;\n syncEnabled?: boolean;\n /**\n * Which baked registry the worker boots (ADR-0032 S3) — forwarded in the attach `config.role`. A worker\n * file that bakes multiple role variants (the board's admin/member) picks by this; single-registry\n * workers ignore it.\n */\n role?: string;\n /**\n * Fresh-store prefetch-overlap hint (ADR-0032 S4), forwarded in the attach `config.freshStore`. Set true\n * ONLY when the tab knows the store is a claimed schemaless spare (never for a mapped/returning store);\n * the worker's `createSyncClient` then overlaps the shape catch-up with its local boot phases.\n */\n freshStore?: boolean;\n /**\n * Restore the worker's store from a backup on attach (ADR-0035 decision 6) — the worker-mode `restoreFrom`.\n * A `File`/`Blob` as produced by {@link SyncClient.exportStore}; the facade decomposes it into a transferred\n * `ArrayBuffer` + name/mime ({@link RestoreArtefactWire}) and the worker recomposes it for `createSyncClient`.\n * Restore rides the FIRST (boot) attach: passing it when the worker's engine has ALREADY booted rejects the\n * attach with a typed error (you cannot restore into a running store). The restored engine boots offline and\n * its recovered journal is quarantined, exactly as in-process — see `restoreFrom` on `createSyncClient`.\n */\n restoreFrom?: File | Blob;\n codec?: BridgeCodec;\n onStatusChange?: (status: SyncRuntimeStatus) => void;\n onConflict?: (details: MutationDetail[]) => void;\n onQuarantine?: (details: MutationDetail[]) => void;\n onReject?: (details: MutationDetail[]) => void;\n onSchemaChange?: (event: LocalStoreVersionEvent) => void;\n onSyncError?: (error: Error) => void;\n /**\n * Boot observability (ADR-0034): invoked once with the worker engine's finalized {@link BootReport} if the\n * engine's boot finalizes WHILE this tab is attached (the one-shot `boot-report` broadcast). A tab that\n * attaches AFTER the boot never receives the push — it reads the report via {@link SyncClient.bootReport}.\n */\n onBootReport?: (report: BootReport) => void;\n}\n\n/**\n * The worker-attached client: `SyncClient`'s shape, worker-proxied, plus `notifyAuthChanged` (re-push the\n * token after an app auth-state change, ADR-0032 decision 3). The unsupported one-shot-read members throw.\n */\nexport type AttachedSyncClient<TRegistry extends SyncTableRegistry> = SyncClient<TRegistry> & {\n notifyAuthChanged: () => void;\n /**\n * Forward the app's Offline toggle to the worker (ADR-0032 S3). The worker owns convergence, so the\n * tab cannot gate a local trigger; this sends `set-online`, which suppresses/resumes the worker's flush\n * passes (resuming fires one immediate pass). The in-process client gates its own `autoSync` instead.\n */\n setOnline: (online: boolean) => void;\n};\n\nexport async function attachSyncClient<const TRegistry extends SyncTableRegistry>(\n options: AttachSyncClientOptions<TRegistry>,\n): Promise<AttachedSyncClient<TRegistry>> {\n const codec = options.codec ?? identityCodec;\n const port = resolvePort(options);\n\n // ─── Correlation + subscription bookkeeping ──────────────────────────────────────────────────────\n let nextId = 0;\n const newId = (prefix: string) => `${prefix}-${++nextId}`;\n const rpcPending = new Map<string, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();\n const initialPending = new Map<\n string,\n { resolve: (payload: LiveInitialPayload) => void; reject: (error: Error) => void }\n >();\n const diffHandlers = new Map<string, (diff: Omit<LiveDiffPayload, \"queryId\">) => void>();\n\n // ─── Status + readiness ──────────────────────────────────────────────────────────────────────────\n const status: SyncRuntimeStatus = { phase: \"booting\", isRunning: false };\n let resolveReady!: () => void;\n const ready = new Promise<void>((resolve) => {\n resolveReady = resolve;\n });\n let readyResolved = false;\n const readyGroups = new Set<string>();\n const groupWaiters = new Map<string, Array<() => void>>();\n\n // ─── Auth: push at attach + on notifyAuthChanged, answer pull-requests ────────────────────────────\n const pushToken = async () => {\n const token = options.getToken ? await options.getToken() : null;\n postBridgeMessage(port, codec, \"token-push\", token);\n };\n const answerPull = async (requestId: string) => {\n const token = options.getToken ? await options.getToken() : null;\n postBridgeMessage(port, codec, \"token-response\", { requestId, token });\n };\n\n // ─── Inbound message routing ─────────────────────────────────────────────────────────────────────\n const markReady = () => {\n if (readyResolved) return;\n readyResolved = true;\n resolveReady();\n };\n // Record a group as ready and settle any waiters — shared by the discrete `groupReady` edge and the\n // status snapshot's `status.groups` merge (ADR-0032 FIX 4), so a tab attaching after the edge fired\n // still resolves `client.groupReady(table)` off the snapshot it gets at attach.\n const markGroupReady = (groupKey: string) => {\n readyGroups.add(groupKey);\n const waiters = groupWaiters.get(groupKey);\n if (waiters) {\n groupWaiters.delete(groupKey);\n for (const resolve of waiters) resolve();\n }\n };\n const onEvent = (event: BridgeEvent) => {\n switch (event.kind) {\n case \"status\": {\n Object.assign(status, event.status);\n options.onStatusChange?.(event.status);\n // Match the in-process contract EXACTLY (ADR-0032 FIX 3): `ready` resolves ONLY from phase\n // \"ready\" (all eager groups caught up, or the syncEnabled:false path). `auth-needed`/`degraded`\n // do NOT resolve it — an engine stuck retrying auth keeps `ready` pending, as in-process.\n if (event.status.phase === \"ready\") markReady();\n // Late-attach group merge (ADR-0032 FIX 4): fold every already-ready group from the snapshot.\n for (const [groupKey, ready] of Object.entries(event.status.groups ?? {})) {\n if (ready) markGroupReady(groupKey);\n }\n break;\n }\n case \"groupReady\": {\n markGroupReady(event.groupKey);\n break;\n }\n case \"conflict\":\n options.onConflict?.(event.details as MutationDetail[]);\n break;\n case \"quarantine\":\n options.onQuarantine?.(event.details as MutationDetail[]);\n break;\n case \"reject\":\n options.onReject?.(event.details as MutationDetail[]);\n break;\n case \"schema-change\":\n options.onSchemaChange?.(event.event as LocalStoreVersionEvent);\n break;\n case \"sync-error\":\n options.onSyncError?.(new Error(event.message));\n break;\n case \"boot-report\":\n // Boot observability (ADR-0034): the one-shot push for a tab attached at finalize. A late tab never\n // gets this event and pulls the report via `client.bootReport()` instead.\n options.onBootReport?.(event.report);\n break;\n case \"debug\": {\n // Re-print the worker's rail line gated on THIS tab's own flag, origin-tagged with the worker's\n // monotonic stamp (ADR-0032 decision 7) — a SharedWorker's own console is otherwise invisible.\n if ((globalThis as { __pgxsinkitDebug?: boolean }).__pgxsinkitDebug === true) {\n const line = `[pgxsinkit·w ${event.stamp.toFixed(0)}ms] ${event.line}`;\n if (event.data) console.debug(line, event.data);\n else console.debug(line);\n }\n break;\n }\n case \"timing\":\n break;\n default:\n break;\n }\n };\n\n const listener = (message: { data: unknown }) => {\n if (!isBridgeEnvelope(message.data)) return;\n const envelope = message.data;\n const payload = codec.decode(envelope.payload);\n switch (envelope.type) {\n case \"attach-ack\": {\n const ack = payload as AttachAckPayload;\n // A boot failure crosses in the ack's `error` (ADR-0032 FIX 1): reject the handshake so\n // `attachSyncClient` rejects instead of hanging forever. On success, the engine exists and the\n // status event that follows drives `ready`; `engineReady` covers a LATE attach whose engine already\n // fired its monotonic `ready` before this ack (FIX 3), so resolve `ready` straight away.\n if (ack.error) {\n attachAckReject?.(rebuildError(ack.error));\n } else {\n if (ack.engineReady) markReady();\n attachAckResolve?.(ack);\n }\n break;\n }\n case \"token-request\":\n void answerPull((payload as TokenRequestPayload).requestId);\n break;\n case \"rpc-result\": {\n const id = envelope.id;\n if (id == null) break;\n const result = payload as RpcResultPayload;\n const pending = rpcPending.get(id);\n if (pending) {\n rpcPending.delete(id);\n if (result.ok) pending.resolve(result.value);\n else pending.reject(rebuildError(result.error));\n break;\n }\n // A failed `subscribe` is reported as an `rpc-result` correlated by the subscribe's envelope id\n // (the worker has no client to hand an initial snapshot), so route the miss to the initial waiter\n // (ADR-0032 FIX 2). A successful subscribe never lands here — it resolves via `live-initial`.\n const initial = initialPending.get(id);\n if (initial && !result.ok) {\n initialPending.delete(id);\n initial.reject(rebuildError(result.error));\n }\n break;\n }\n case \"live-initial\": {\n const id = envelope.id;\n const initial = payload as LiveInitialPayload;\n if (id != null) {\n const pending = initialPending.get(id);\n if (pending) {\n initialPending.delete(id);\n pending.resolve(initial);\n }\n }\n break;\n }\n case \"live-diff\": {\n const diff = payload as LiveDiffPayload;\n diffHandlers.get(diff.queryId)?.(diff);\n break;\n }\n case \"event\":\n onEvent(payload as BridgeEvent);\n break;\n default:\n break;\n }\n };\n port.addEventListener(\"message\", listener);\n port.start?.();\n\n // ─── RPC helper ──────────────────────────────────────────────────────────────────────────────────\n const rpc = <T>(op: RpcOp, args: unknown[]): Promise<T> => {\n const id = newId(\"rpc\");\n return new Promise<T>((resolve, reject) => {\n rpcPending.set(id, { resolve: resolve as (value: unknown) => void, reject });\n postBridgeMessage(port, codec, \"rpc\", { op, args }, id);\n });\n };\n\n // ─── Attach handshake ────────────────────────────────────────────────────────────────────────────\n let attachAckResolve: ((ack: AttachAckPayload) => void) | null = null;\n let attachAckReject: ((error: Error) => void) | null = null;\n const attachAck = new Promise<AttachAckPayload>((resolve, reject) => {\n attachAckResolve = resolve;\n attachAckReject = reject;\n });\n const initialToken = options.getToken ? await options.getToken() : null;\n // The testing memory-backend override travels as an explicit wire field, not the symbol marker — a symbol\n // does not survive `postMessage` structured clone (ADR-0036). Read it off the spread helper's options here.\n const memoryOverride = readTestStoreMarker(options) === \"memory\";\n // Restore (ADR-0035 decision 6): a `File`/`Blob` cannot cross as a transferable, so decompose it into a\n // zero-copy `ArrayBuffer` + name/mime (the `ExportArtefactWire` pattern in reverse) and list the buffer on\n // the attach `postMessage`'s transfer list. Read the bytes BEFORE building the payload (async).\n const restoreWire: RestoreArtefactWire | undefined = options.restoreFrom\n ? {\n buffer: await options.restoreFrom.arrayBuffer(),\n fileName: options.restoreFrom instanceof File ? options.restoreFrom.name : \"restore.pgdata.tar\",\n mimeType: options.restoreFrom.type || \"application/octet-stream\",\n }\n : undefined;\n const attachPayload: AttachPayload = {\n token: initialToken,\n ...(options.storeId ? { storeId: options.storeId } : {}),\n ...(options.storePath ? { storePath: options.storePath } : {}),\n ...(memoryOverride ? { testStoreBackend: \"memory\" as const } : {}),\n ...(restoreWire ? { restore: restoreWire } : {}),\n ...(options.syncEnabled != null || options.role != null || options.freshStore != null\n ? {\n config: {\n ...(options.syncEnabled != null ? { syncEnabled: options.syncEnabled } : {}),\n ...(options.role != null ? { role: options.role } : {}),\n ...(options.freshStore != null ? { freshStore: options.freshStore } : {}),\n },\n }\n : {}),\n };\n postBridgeMessage(port, codec, \"attach\", attachPayload, undefined, restoreWire ? [restoreWire.buffer] : undefined);\n try {\n await attachAck;\n } catch (error) {\n // The worker's engine boot failed (ADR-0032 FIX 1): tear down this tab's listener so no port handler\n // leaks, then let the boot error propagate out of `attachSyncClient`.\n port.removeEventListener(\"message\", listener);\n throw error;\n }\n status.isRunning = true;\n\n // ─── Live-rows seam (ADR-0032 S2 §4) ─────────────────────────────────────────────────────────────\n const subscribeLiveRows = async <TRow extends Record<string, unknown>>(\n input: SubscribeLiveRowsInput,\n onRows: (rows: TRow[]) => void,\n ): Promise<LiveRowsSubscription<TRow>> => {\n const queryId = newId(\"live\");\n const id = newId(\"sub\");\n const materializer = new LiveRowsMaterializer<TRow>(input.pkColumns);\n diffHandlers.set(queryId, (diff) => {\n onRows(materializer.apply(diff));\n });\n let initial: LiveInitialPayload;\n try {\n initial = await new Promise<LiveInitialPayload>((resolve, reject) => {\n initialPending.set(id, { resolve, reject });\n postBridgeMessage(\n port,\n codec,\n \"subscribe\",\n {\n queryId,\n sql: input.sql,\n params: [...input.params],\n ...(input.fields ? { fields: [...input.fields] } : {}),\n ...(input.pkColumns ? { pkColumns: [...input.pkColumns] } : {}),\n ...(input.use ? { use: [...input.use] } : {}),\n },\n id,\n );\n });\n } catch (error) {\n // The worker rejected the subscribe (invalid SQL, etc.); the initial-payload waiter rejected via the\n // `rpc-result` route (ADR-0032 FIX 2). Drop the pre-registered diff handler so no orphan survives.\n diffHandlers.delete(queryId);\n throw error;\n }\n const initialRows = materializer.seed(initial.rows as TRow[]);\n return {\n initialRows,\n unsubscribe: () => {\n diffHandlers.delete(queryId);\n postBridgeMessage(port, codec, \"unsubscribe\", { queryId });\n },\n };\n };\n\n // ─── Assembled client ────────────────────────────────────────────────────────────────────────────\n const { drizzle, views } = buildRegistryReadHandles(options.registry);\n const notSupported = (name: string) => (): never => {\n throw new Error(\n `[pgxsinkit] ${name} is not available on a worker-attached client (ADR-0032 S2). Use the live-rows hooks / subscribeLiveRows for reads, the write API for mutations.`,\n );\n };\n\n const groupKeyForTable = (table: SyncTableName<TRegistry>): string | undefined => {\n const entry = options.registry[table];\n return entry?.consistencyGroup ?? entry?.shape?.shapeKey;\n };\n\n const client: AttachedSyncClient<TRegistry> = {\n drizzle,\n views,\n // The tab has no local PGlite; reads go through the live-rows bridge. Touching `.pglite` is a misuse.\n pglite: new Proxy(\n {},\n {\n get: notSupported(\"client.pglite\"),\n },\n ) as never,\n tables: Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n key: tableKey,\n mode: options.registry[tableKey as SyncTableName<TRegistry>]!.mode,\n create: (input: unknown) => rpc<void>(\"create\", [tableKey, input]),\n update: (entityKey: Record<string, string>, patch: unknown) =>\n rpc<void>(\"update\", [tableKey, entityKey, patch]),\n delete: (entityKey: Record<string, string>) => rpc<void>(\"delete\", [tableKey, entityKey]),\n },\n ]),\n ) as SyncClient<TRegistry>[\"tables\"],\n ready,\n status,\n start: async () => {\n await ready;\n },\n stop: async () => {\n // Detach THIS tab; the worker engine keeps running for other tabs (ADR-0032 decision 2).\n status.isRunning = false;\n for (const queryId of diffHandlers.keys()) postBridgeMessage(port, codec, \"unsubscribe\", { queryId });\n diffHandlers.clear();\n postBridgeMessage(port, codec, \"detach\", null);\n port.removeEventListener(\"message\", listener);\n port.close?.();\n },\n destroy: notSupported(\"client.destroy\"),\n dropReadCache: notSupported(\"client.dropReadCache\"),\n flush: (table) => rpc<void>(\"flush\", [table]),\n reconcile: (table) => rpc<void>(\"reconcile\", [table]),\n retryFailed: (table) => rpc<void>(\"retryFailed\", [table]),\n recoverSending: (table) => rpc<void>(\"recoverSending\", [table]),\n readMutationDetails: (table) => rpc<MutationDetail[]>(\"readMutationDetails\", [table]),\n // Inspection reads run in the worker (ADR-0032 S2) — the same surface as the in-process client. `pglite`\n // itself stays blocked (below); these route the raw statement over the RPC round-trip instead.\n rawQuery: (sql, params, options) => rpc<Results>(\"rawQuery\", [sql, params, options]),\n rawExec: (sql, options) => rpc<Results[]>(\"rawExec\", [sql, options]),\n mutate: {\n create: (table, input) => rpc<void>(\"create\", [table, input]),\n update: (table, entityKey, patch) => rpc<void>(\"update\", [table, entityKey, patch]),\n delete: (table, entityKey) => rpc<void>(\"delete\", [table, entityKey]),\n batch: (items) => rpc<void>(\"batch\", [items]),\n },\n discardConflict: (table, entityKey) => rpc<void>(\"discardConflict\", [table, entityKey]),\n discardQuarantined: (table, entityKey) => rpc<void>(\"discardQuarantined\", [table, entityKey]),\n diagnostics: (table) => rpc<{ mutation: MutationDiagnostics }>(\"diagnostics\", [table]),\n query: notSupported(\"client.query\"),\n queryRow: notSupported(\"client.queryRow\"),\n queryRaw: notSupported(\"client.queryRaw\"),\n queryRawRow: notSupported(\"client.queryRawRow\"),\n ensureSynced: notSupported(\"client.ensureSynced\"),\n isSynced: notSupported(\"client.isSynced\"),\n // In SharedWorker mode the engine is SHARED, so a desync from one tab reverts the consistency group for\n // EVERY attached tab — inherent to desync's group-wide semantics (that footgun is why the narrower\n // `discardEphemeral` exists). The RPC runs the worker's real `desync` (same refusals as in-process).\n desync: (key) => rpc<void>(\"desync\", [key]),\n // Scoped, multi-tab-safe finalize (ADR-0021): drops an ephemeral relation's local rows and reverts it to\n // dormant. Safe under a shared engine because an ephemeral window is per-delivery-session and inherently\n // single-consumer; the RPC runs the worker's real `discardEphemeral` (refuses persistent members).\n discardEphemeral: (key) => rpc<void>(\"discardEphemeral\", [key]),\n // The worker activates lazy relations inside its `subscribe` handler (via the `use` hint), so the tab's\n // `prepareQuery` is a no-op — the live-rows subscription is already guarded worker-side (ADR-0021).\n prepareQuery: async () => undefined,\n transaction: async ({ mode }: { mode: WriteMode }, run) => {\n // Collect the unit's mutations tab-side (the run callback cannot cross the wire), then RPC the\n // serialized items + mode; the worker replays them into a real `client.transaction` (matching acks).\n const collected: MutationBatchItem<TRegistry>[] = [];\n const txTables = Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n create: (input: unknown) => {\n collected.push({ table: tableKey, kind: \"create\", input } as MutationBatchItem<TRegistry>);\n },\n update: (entityKey: Record<string, string>, patch: unknown) => {\n collected.push({ table: tableKey, kind: \"update\", entityKey, patch } as MutationBatchItem<TRegistry>);\n },\n updateBlind: (entityKey: Record<string, string>, patch: unknown) => {\n // ADR-0022 addendum: the `blind` flag rides the serialized item across the wire; the worker\n // replays it through `client.transaction`'s `updateBlind`, identical to the in-process client.\n collected.push({\n table: tableKey,\n kind: \"update\",\n entityKey,\n patch,\n blind: true,\n } as MutationBatchItem<TRegistry>);\n },\n delete: (entityKey: Record<string, string>) => {\n collected.push({ table: tableKey, kind: \"delete\", entityKey } as MutationBatchItem<TRegistry>);\n },\n },\n ]),\n ) as SyncTransaction<TRegistry>[\"tables\"];\n await run({ tables: txTables });\n if (collected.length === 0) return { acks: [] };\n return rpc<SyncTransactionResult>(\"transaction\", [{ mode, items: collected }]);\n },\n groupReady: async (table) => {\n const groupKey = groupKeyForTable(table);\n if (groupKey == null || readyGroups.has(groupKey)) return;\n await new Promise<void>((resolve) => {\n const waiters = groupWaiters.get(groupKey) ?? [];\n waiters.push(resolve);\n groupWaiters.set(groupKey, waiters);\n });\n },\n subscribeLiveRows,\n // Boot observability (ADR-0034): pull the worker engine's stored boot report over the bridge — returns\n // the same report regardless of when this tab attached (a late tab reads a boot that predates it).\n bootReport: () => rpc<BootReport | null>(\"bootReport\", []),\n // Store backup (ADR-0035): the worker runs the live export on its owned client (its lifecycle slot\n // serialises it against every tab). The dump crosses back as a transferred `ArrayBuffer`; rebuild the\n // `File` tab-side from the wire form — NOT in the notSupported set (unlike the local `pglite` reads).\n exportStore: async (exportOptions?: StoreExportOptions): Promise<StoreExportResult> => {\n const wire = await rpc<ExportArtefactWire>(\"exportStore\", [exportOptions]);\n return {\n file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),\n // The wire carries the discriminated union; `exportStore` always round-trips a store-backup report.\n report: wire.report as StoreExportResult[\"report\"],\n };\n },\n // Diagnostic dump (ADR-0035): the worker runs the throwaway-clone dump on its owned client (same\n // lifecycle slot as every tab). The SQL crosses back as the same transferred `ArrayBuffer`; rebuild the\n // `File` tab-side. NOT in the notSupported set (unlike the local `pglite` reads).\n exportDiagnostics: async (exportOptions?: DiagnosticExportOptions): Promise<DiagnosticExportResult> => {\n const wire = await rpc<ExportArtefactWire>(\"exportDiagnostics\", [exportOptions]);\n return {\n file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),\n // The wire carries the discriminated union; `exportDiagnostics` always round-trips a diagnostic-dump report.\n report: wire.report as DiagnosticExportResult[\"report\"],\n };\n },\n // Data export (ADR-0035): the worker runs the drain-guarded `pg_dump -t` export on its owned client (same\n // lifecycle slot as every tab). The portable SQL crosses back as the same transferred `ArrayBuffer`;\n // rebuild the `File` tab-side. A `DataExportDrainError` surfaces as the rejected RPC (deserialised tab-side).\n exportData: async (exportOptions?: DataExportOptions): Promise<DataExportResult> => {\n const wire = await rpc<ExportArtefactWire>(\"exportData\", [exportOptions]);\n return {\n file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),\n // The wire carries the discriminated union; `exportData` always round-trips a data-export report.\n report: wire.report as DataExportResult[\"report\"],\n };\n },\n notifyAuthChanged: () => {\n void pushToken();\n },\n setOnline: (online: boolean) => {\n postBridgeMessage(port, codec, \"set-online\", { online });\n },\n };\n\n return client;\n}\n\n/**\n * Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen\n * against a freshly-named spare `SharedWorker`: the worker runs PGlite `create`/initdb only and holds the\n * raw store idle until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the\n * provision (its initdb settled); rejects only if the worker reports the create failed — the caller treats\n * either outcome as best-effort, since attach falls back to a fresh create regardless.\n */\nexport function provisionSyncWorker<TRegistry extends SyncTableRegistry>(\n options: Pick<AttachSyncClientOptions<TRegistry>, \"worker\" | \"port\" | \"storeId\" | \"storePath\" | \"codec\">,\n): Promise<void> {\n const codec = options.codec ?? identityCodec;\n const port = resolvePort(options);\n // The testing memory-backend override travels as an explicit wire field (a symbol does not survive\n // structured clone, ADR-0036) — read it off the spread helper's options and forward it to the worker.\n const memoryOverride = readTestStoreMarker(options) === \"memory\";\n return new Promise<void>((resolve, reject) => {\n const listener = (message: { data: unknown }) => {\n if (!isBridgeEnvelope(message.data)) return;\n if (message.data.type !== \"provision-ack\") return;\n port.removeEventListener(\"message\", listener);\n const ack = codec.decode(message.data.payload) as ProvisionAckPayload;\n if (ack.ok) resolve();\n else reject(new Error(ack.error?.message ?? \"worker provision failed\"));\n };\n port.addEventListener(\"message\", listener);\n port.start?.();\n postBridgeMessage(port, codec, \"provision\", {\n ...(options.storeId ? { storeId: options.storeId } : {}),\n ...(options.storePath ? { storePath: options.storePath } : {}),\n ...(memoryOverride ? { testStoreBackend: \"memory\" as const } : {}),\n });\n });\n}\n\n/** Resolve the transport port from the options: an explicit port, a SharedWorker's `.port`, or a Worker itself. */\nfunction resolvePort(options: { port?: BridgePort; worker?: WorkerLike }): BridgePort {\n if (options.port) return options.port;\n const worker = options.worker;\n if (!worker) throw new Error(\"attachSyncClient: provide a `worker` or a `port`.\");\n if (worker.port) return worker.port;\n if (worker.postMessage && worker.addEventListener && worker.removeEventListener) {\n return worker as BridgePort;\n }\n throw new Error(\"attachSyncClient: the provided `worker` is neither a Worker nor a SharedWorker port.\");\n}\n\n/** Rebuild an Error from the bridge's serialized `{message, detail}` shape, carrying `detail` through. */\nfunction rebuildError(error: RpcResultPayload[\"error\"]): Error {\n const rebuilt = new Error(error?.message ?? \"worker rpc failed\");\n if (error && \"detail\" in error && error.detail !== undefined) {\n (rebuilt as Error & { detail?: unknown }).detail = error.detail;\n }\n return rebuilt;\n}\n",
142
149
  "// The worker's single auth token cache + pull mechanism (ADR-0032 decision 3). The worker holds exactly\n// ONE token and NEVER refreshes it — the tab layer is the sole auth owner (exactly one refresher exists, so\n// GoTrue refresh-token reuse detection can never trip). A read/write that finds the cache within the expiry\n// margin triggers ONE pull broadcast; concurrent needs dedupe onto that single in-flight pull; the first\n// tab answer wins. Factored out of `defineSyncWorker` so this mechanism is unit-tested in isolation.\n\nimport type { AuthTokenSnapshot } from \"./protocol\";\n\nexport interface WorkerTokenCache {\n /**\n * Resolve the access token for a shape/flush request. Returns the cached token when it is comfortably\n * ahead of expiry; otherwise broadcasts ONE pull (deduped across concurrent callers) and resolves when a\n * tab answers. Falls back to the (stale) cached token if a pull yields nothing.\n */\n getToken: () => Promise<string | undefined>;\n /** The tab pushed a fresh token (auth state change or the initial attach) — cache it and satisfy any pull. */\n push: (token: AuthTokenSnapshot | null) => void;\n /**\n * Seed the cache from a LATER attach's token, but only if it is strictly fresher than what is cached\n * (ADR-0032 FIX 5). Attach seeding must never CLOBBER a fresher cached token with an older/null one —\n * only the explicit `push` path (the tab as auth owner saying \"this is current\") may overwrite\n * unconditionally, including null on logout.\n */\n pushIfFresher: (token: AuthTokenSnapshot | null) => void;\n /** A tab answered a pull-request. First matching answer wins; later duplicates are ignored. */\n respond: (requestId: string, token: AuthTokenSnapshot | null) => void;\n}\n\nexport function createWorkerTokenCache(options: {\n marginMs: number;\n broadcastRequest: (requestId: string) => void;\n now?: () => number;\n}): WorkerTokenCache {\n const now = options.now ?? (() => Date.now());\n let cached: AuthTokenSnapshot | null = null;\n let inFlight: Promise<AuthTokenSnapshot | null> | null = null;\n let resolveInFlight: ((token: AuthTokenSnapshot | null) => void) | null = null;\n let currentRequestId: string | null = null;\n let requestCounter = 0;\n\n const settle = (token: AuthTokenSnapshot | null) => {\n if (token) cached = token;\n const resolve = resolveInFlight;\n inFlight = null;\n resolveInFlight = null;\n currentRequestId = null;\n resolve?.(token);\n };\n\n return {\n getToken: async () => {\n if (cached && cached.expiresAt - now() > options.marginMs) {\n return cached.accessToken;\n }\n if (!inFlight) {\n currentRequestId = `pull-${++requestCounter}`;\n inFlight = new Promise<AuthTokenSnapshot | null>((resolve) => {\n resolveInFlight = resolve;\n });\n // Exactly one broadcast per pull; concurrent getToken calls below await the same `inFlight`.\n options.broadcastRequest(currentRequestId);\n }\n const answered = await inFlight;\n return answered?.accessToken ?? cached?.accessToken;\n },\n push: (token) => {\n cached = token;\n // A push satisfies an outstanding pull too (the tab volunteered before answering the request).\n if (inFlight) settle(token);\n },\n pushIfFresher: (token) => {\n if (!token) return;\n if (cached && cached.expiresAt >= token.expiresAt) return;\n // Strictly fresher than the cache (or the cache is empty) → adopt it via `push`, which also settles\n // any in-flight pull.\n cached = token;\n if (inFlight) settle(token);\n },\n respond: (requestId, token) => {\n // First response for the CURRENT pull wins; a stale/duplicate requestId (or no pull) is ignored.\n if (inFlight && requestId === currentRequestId) settle(token);\n },\n };\n}\n",
143
- "// The worker entry factory (ADR-0032 S2, decisions 3/4/6/7). `defineSyncWorker` boots ONE sync engine and\n// fans it out to N attached tabs over the bridge. The first attach boots the engine by calling the\n// unchanged `createSyncClient` (the strongest form of \"reuse createSyncClient internals\" — the in-process\n// boot pipeline runs verbatim, so the unit suite stays its equivalence proof); later attaches join it.\n//\n// It serves BOTH a native `SharedWorker` (`onconnect`, many ports) and a dedicated `Worker` (one implicit\n// port) behind {@link SyncWorkerHost.connect} — the same entry a test drives with a plain `MessageChannel`\n// port, so no real Worker is needed to exercise the whole protocol.\n\nimport type { SyncRuntimeStatus, SyncTableName, SyncTableRegistry, WriteMode } from \"@pgxsinkit/contracts\";\n\nimport { type ConvergenceTrigger, createIntervalConvergenceTrigger } from \"../convergence\";\nimport { setSyncDebugSink, syncDebug } from \"../debug\";\nimport {\n type ClientPGlite,\n createClientPGlite,\n type CreateSyncClientOptions,\n createSyncClient,\n type MutationBatchItem,\n type RawQueryOptions,\n type SyncClient,\n} from \"../index\";\nimport type { LocalStoreVersionEvent } from \"../local-store\";\nimport { computeLiveDiff, seedLiveDiffState } from \"./live-diff\";\nimport {\n type AttachPayload,\n type BridgeCodec,\n type BridgeEnvelope,\n type BridgeEvent,\n type BridgePort,\n identityCodec,\n isBridgeEnvelope,\n postBridgeMessage,\n type ProvisionPayload,\n type RpcOp,\n type RpcPayload,\n type SetOnlinePayload,\n type SubscribePayload,\n type TokenResponsePayload,\n} from \"./protocol\";\nimport { createWorkerTokenCache } from \"./token-cache\";\n\nexport interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {\n /**\n * The sync registry — imported as CODE by the worker file, never cloned into it (ADR-0032 decision 4).\n * When {@link resolveRegistry} is also given this is the DEFAULT (used when the attach carries no role\n * or an unknown one).\n */\n registry: TRegistry;\n /**\n * Resolve the registry to boot from the attach's `config.role` (ADR-0032 S3). A single worker file can\n * bake BOTH role variants (e.g. the board's admin/member registries — same TS shape, different write\n * capability) and pick per-attach, which the spare flow needs: the spare is provisioned role-agnostic\n * (before the user is known) and the role is only settled at claim/attach. Returns `undefined` to fall\n * back to {@link registry}.\n */\n resolveRegistry?: (role: string | undefined) => TRegistry | undefined;\n /**\n * How the worker creates its raw PGlite store (provision + fresh-attach paths). Defaults to\n * {@link createClientPGlite}, which loads PGlite's own boot assets — in a browser worker those hit the\n * same-origin HTTP cache the tab's login-screen warm already primed (ADR-0032 S3). Injected in tests.\n */\n createPglite?: (dataDir: string) => Promise<ClientPGlite>;\n electricUrl: string;\n writeUrl: string;\n /** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */\n requestHeaders?: Record<string, string>;\n /** Write-only headers merged over {@link requestHeaders} (e.g. region/DB-affinity). See `createSyncClient`. */\n writeRequestHeaders?: Record<string, string>;\n /** Default PGlite store id if the first attach carries none (`memory://…` in tests, `idb://…` in a browser). */\n dataDir?: string;\n maxMutationAttempts?: number;\n syncEnabled?: boolean;\n /**\n * How close to expiry (ms) a cached token may be before a read/write that needs it triggers a pull\n * broadcast (ADR-0032 decision 3). Default 30s — comfortably ahead of a long-poll cycle.\n */\n tokenExpiryMarginMs?: number;\n /**\n * The worker's own convergence cadence (ms) — the interval trigger FALLBACK only. Local writes\n * flush immediately via the event-driven `requestPass` seam and tab `wake` signals, so this\n * interval exists purely for retry/recovery sweeps; each idle pass still costs real worker CPU\n * (`flush` + `reconcile` queries). Default 15000.\n */\n convergenceIntervalMs?: number;\n /** Injected transport binder. Defaults to auto-detecting the SharedWorker/dedicated-worker global scope. */\n installGlobal?: boolean;\n /** Injected codec (ADR-0032 S2 §1). Defaults to the v1 identity codec. */\n codec?: BridgeCodec;\n /**\n * A raw PGlite the worker uses instead of creating its own (forwarded to `createSyncClient`'s\n * {@link CreateSyncClientOptions.precreatedPglite}) — the client still applies schema/reconcile. In a\n * browser worker the store is minted internally (`dataDir`); this is the seam for a prepopulated store in\n * tests, and the future spare-worker claim (ADR-0032 decision 5).\n */\n precreatedPglite?: CreateSyncClientOptions<TRegistry>[\"precreatedPglite\"];\n /** A fully-provisioned PGlite (forwarded to {@link CreateSyncClientOptions.pgliteInstance}; caller owns schema). */\n pgliteInstance?: CreateSyncClientOptions<TRegistry>[\"pgliteInstance\"];\n}\n\n/** The worker-side host: attach ports, await the boot, and (for tests) tear down. */\nexport interface SyncWorkerHost<TRegistry extends SyncTableRegistry> {\n /** Bind a transport port (a SharedWorker connection, the dedicated-worker `self`, or a test channel port). */\n connect: (port: BridgePort) => void;\n /** Resolves with the booted in-process engine once the first attach's `createSyncClient` completes. */\n whenBooted: () => Promise<SyncClient<TRegistry>>;\n /** Detach every port and stop the underlying client — for tests and dedicated-worker teardown. */\n close: () => Promise<void>;\n}\n\ninterface LiveSub {\n unsubscribe: () => void;\n port: BridgePort;\n}\n\n/**\n * Build a worker host over the given engine config. In a real worker file the consumer calls this at module\n * top level and it auto-binds the global scope; a test constructs it and drives {@link SyncWorkerHost.connect}.\n */\nexport function defineSyncWorker<const TRegistry extends SyncTableRegistry>(\n options: DefineSyncWorkerOptions<TRegistry>,\n): SyncWorkerHost<TRegistry> {\n const codec = options.codec ?? identityCodec;\n const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30_000;\n const convergenceIntervalMs = options.convergenceIntervalMs ?? 15_000;\n const createPglite = options.createPglite ?? ((dataDir: string) => createClientPGlite(dataDir));\n\n const ports = new Set<BridgePort>();\n const liveSubs = new Map<string, LiveSub>();\n\n // ─── Pre-spawned (schemaless) store — the spare flow (ADR-0032 decision 5) ────────────────────────\n // A `provision` mints the raw PGlite (initdb only) and holds it idle here; the first real `attach`\n // adopts it as `precreatedPglite` (the client still runs schema/journal recovery/reconcile). Provision\n // is role-agnostic — the registry is chosen at attach — so the same warmed store serves either role.\n let provisioned: { dataDir: string; pglite: Promise<ClientPGlite> } | null = null;\n\n // ─── Outbound-convergence gate — the tab's Offline toggle over the bridge (ADR-0032 S3) ───────────\n // The worker owns convergence; the tab forwards its Offline flag as `set-online`. When suppressed the\n // interval trigger's `shouldConverge` returns false (writes stage in the journal, unsent) and a `wake`\n // is ignored; resuming fires one immediate pass so the queue flushes at once.\n let convergenceSuppressed = false;\n let fireConvergence: (() => void) | null = null;\n const baseTrigger = createIntervalConvergenceTrigger(convergenceIntervalMs);\n const gatedTrigger: ConvergenceTrigger = {\n subscribe: (onSignal) => {\n fireConvergence = onSignal;\n const unsubscribe = baseTrigger.subscribe(onSignal);\n return () => {\n fireConvergence = null;\n unsubscribe();\n };\n },\n shouldConverge: () => !convergenceSuppressed && baseTrigger.shouldConverge(),\n };\n\n // ─── The single auth token cache + pull mechanism (ADR-0032 decision 3) ──────────────────────────\n const tokenCache = createWorkerTokenCache({\n marginMs: tokenExpiryMarginMs,\n broadcastRequest: (requestId) => {\n syncDebug(\"worker token pull broadcast\", { requestId, tabs: ports.size });\n broadcast(\"token-request\", { requestId });\n },\n });\n const getWorkerAuthToken = () => tokenCache.getToken();\n\n // ─── The broadcast event channel (ADR-0032 decision 7) ───────────────────────────────────────────\n const seenReadyGroups = new Set<string>();\n const broadcast = (type: BridgeEnvelope[\"type\"], payload: unknown) => {\n for (const port of ports) postBridgeMessage(port, codec, type, payload);\n };\n const broadcastEvent = (event: BridgeEvent) => broadcast(\"event\", event);\n\n const emitStatus = (status: SyncRuntimeStatus) => {\n broadcastEvent({ kind: \"status\", status });\n // Derive a per-group `groupReady` event for each group that newly reached ready, so a tab gets both the\n // status snapshot (`status.groups`) and a discrete edge to await (ADR-0032 decision 6/7).\n for (const [groupKey, ready] of Object.entries(status.groups ?? {})) {\n if (ready && !seenReadyGroups.has(groupKey)) {\n seenReadyGroups.add(groupKey);\n broadcastEvent({ kind: \"groupReady\", groupKey });\n }\n }\n };\n\n // ─── Engine boot — reuse createSyncClient verbatim (ADR-0032 decision 1/4) ────────────────────────\n let client: SyncClient<TRegistry> | null = null;\n let bootPromise: Promise<SyncClient<TRegistry>> | null = null;\n // The role the engine actually booted with (from the FIRST attach's config). Later attaches compare\n // their requested role against this and get a warning on mismatch (ADR-0032 FIX 5) — never a reject.\n let bootedRole: string | undefined;\n // The engine's `ready` is monotonic: once its initial sync lands it stays resolved even if the phase\n // later degrades. A tab attaching AFTER that moment must still get a resolved `ready`, so track whether\n // it has fired and tell the ack (ADR-0032 FIX 3).\n let engineReadyFired = false;\n let resolveBooted!: (client: SyncClient<TRegistry>) => void;\n const bootedPromise = new Promise<SyncClient<TRegistry>>((resolve) => {\n resolveBooted = resolve;\n });\n\n const boot = (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {\n if (bootPromise) return bootPromise;\n // The tab is the auth owner: seed the cache with the token it presented at attach (decision 3).\n tokenCache.push(attach.token);\n bootedRole = attach.config?.role;\n // Forward the debug rail to tabs, stamped with the WORKER's monotonic clock (decision 7). Installed\n // before boot so the boot rail itself crosses the bridge.\n setSyncDebugSink((line, stamp, data) => {\n broadcastEvent({ kind: \"debug\", stamp, line, ...(data ? { data } : {}) });\n });\n // Resolve the registry from the attach's role (ADR-0032 S3): a single worker file bakes both variants\n // and the claim/attach settles which one boots — the spare was provisioned before the role was known.\n const registry = options.resolveRegistry?.(attach.config?.role) ?? options.registry;\n // dataDir-first, matching the `provision` handler's resolution (below): the board sends BOTH a bare\n // `storeId` (SharedWorker naming, tab-side) AND the real `dataDir` (`idb://pgxsinkit-board-<id>`), and\n // the PGlite store lives at `dataDir` — so the provisioned store's dataDir must be what we adopt on.\n // `storeId` is only a last-ditch fallback for a caller that passes it as the store path.\n const dataDir = attach.dataDir ?? attach.storeId ?? options.dataDir ?? \"idb://pgxsinkit-overlay-v1\";\n // Adopt a matching pre-provisioned store (its initdb already ran off-thread) as `precreatedPglite`;\n // createSyncClient falls back to a fresh `dataDir` create if that promise rejects — a pure accelerator.\n const precreatedPglite =\n provisioned && provisioned.dataDir === dataDir ? provisioned.pglite : options.precreatedPglite;\n if (precreatedPglite === provisioned?.pglite) {\n syncDebug(\"worker adopting provisioned store\", { dataDir });\n }\n bootPromise = createSyncClient<TRegistry>({\n registry,\n electricUrl: options.electricUrl,\n writeUrl: options.writeUrl,\n dataDir,\n ...(precreatedPglite ? { precreatedPglite } : {}),\n ...(options.pgliteInstance ? { pgliteInstance: options.pgliteInstance } : {}),\n // Fresh-store prefetch overlap (ADR-0032 S4): the tab's claim path proved this store a schemaless\n // spare and forwarded the hint in the attach config, so the shape catch-up overlaps schema exec +\n // journal recovery + reconcile. Never inferred from \"adopting a provisioned store\": the board\n // provisions a worker even for a MAPPED (returning) user, whose idb is NOT fresh — only the claim\n // path's explicit hint distinguishes them.\n ...(attach.config?.freshStore === true ? { freshStore: true } : {}),\n getAuthToken: getWorkerAuthToken,\n // The worker owns convergence via the interval trigger, GATED by the tab's Offline toggle\n // (`set-online`); tabs additionally forward online/visibility as `wake` pass requests (below).\n autoSync: gatedTrigger,\n syncEnabled: attach.config?.syncEnabled ?? options.syncEnabled ?? true,\n ...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),\n ...(options.writeRequestHeaders ? { writeRequestHeaders: options.writeRequestHeaders } : {}),\n ...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),\n onStatusChange: (status) => emitStatus(status),\n onConflict: (details) => broadcastEvent({ kind: \"conflict\", details }),\n onQuarantine: (details) => broadcastEvent({ kind: \"quarantine\", details }),\n onReject: (details) => broadcastEvent({ kind: \"reject\", details }),\n onSchemaChange: (event: LocalStoreVersionEvent) => broadcastEvent({ kind: \"schema-change\", event }),\n onSyncError: (error) => broadcastEvent({ kind: \"sync-error\", message: error.message }),\n });\n return bootPromise;\n };\n\n const whenBooted = () => bootedPromise;\n\n // ─── Write / mutation-state RPC dispatch ─────────────────────────────────────────────────────────\n const dispatchRpc = async (active: SyncClient<TRegistry>, op: RpcOp, args: unknown[]): Promise<unknown> => {\n type TableKey = SyncTableName<TRegistry>;\n switch (op) {\n case \"create\":\n return active.mutate.create(args[0] as TableKey, args[1] as never);\n case \"update\":\n return active.mutate.update(args[0] as TableKey, args[1] as Record<string, string>, args[2] as never);\n case \"delete\":\n return active.mutate.delete(args[0] as TableKey, args[1] as Record<string, string>);\n case \"batch\":\n return active.mutate.batch(args[0] as ReadonlyArray<MutationBatchItem<TRegistry>>);\n case \"transaction\": {\n // The tab collected the unit's mutations (the run callback can't cross the wire); the worker replays\n // the serialized items into a real `client.transaction` so pessimistic acks / optimistic flush match\n // the in-process semantics exactly.\n const { mode, items } = args[0] as { mode: WriteMode; items: MutationBatchItem<TRegistry>[] };\n return active.transaction({ mode }, (tx) => {\n for (const item of items) {\n const handle = tx.tables[item.table];\n if (item.kind === \"create\") {\n handle.create(item.input as never);\n } else if (item.kind === \"update\") {\n // ADR-0022 addendum: a `blind` update replays through `updateBlind` (journal-only, no overlay).\n if (item.blind) handle.updateBlind(item.entityKey, item.patch as never);\n else handle.update(item.entityKey, item.patch as never);\n } else {\n handle.delete(item.entityKey);\n }\n }\n });\n }\n case \"flush\":\n return active.flush(args[0] as TableKey | undefined);\n case \"reconcile\":\n return active.reconcile(args[0] as TableKey | undefined);\n case \"retryFailed\":\n return active.retryFailed(args[0] as TableKey | undefined);\n case \"recoverSending\":\n return active.recoverSending(args[0] as TableKey | undefined);\n case \"discardConflict\":\n return active.discardConflict(args[0] as TableKey, args[1] as Record<string, string>);\n case \"discardQuarantined\":\n return active.discardQuarantined(args[0] as TableKey, args[1] as Record<string, string>);\n case \"readMutationDetails\":\n return active.readMutationDetails(args[0] as TableKey | undefined);\n case \"diagnostics\":\n return active.diagnostics(args[0] as TableKey | undefined);\n case \"rawQuery\":\n // Inspection read (ADR-0032 S2): run straight against the worker's own store — `active.pglite`\n // exists worker-side (it's the in-process client). `Results` rows/fields structured-clone across\n // the wire (Dates survive postMessage), so the tab receives the same shape it would in-process.\n // The options arg is the clonable RawQueryOptions subset (rowMode) — the REPL's array mode.\n return active.rawQuery(args[0] as string, args[1] as unknown[] | undefined, args[2] as RawQueryOptions);\n case \"rawExec\":\n return active.rawExec(args[0] as string, args[1] as RawQueryOptions);\n default: {\n const exhaustive: never = op;\n throw new Error(`unknown rpc op ${String(exhaustive)}`);\n }\n }\n };\n\n // ─── Live-query bridge (ADR-0032 S2 §4) ──────────────────────────────────────────────────────────\n const handleSubscribe = async (port: BridgePort, id: string | undefined, payload: SubscribePayload) => {\n const active = client ?? (await bootPromise);\n if (!active) throw new Error(\"subscribe before attach\");\n const { queryId, sql, params, pkColumns, use } = payload;\n // Activate any lazy relations the query reads BEFORE registering the live query (ADR-0021) — the worker\n // owns the real client, so its `prepareQuery` does the real work; the tab's `prepareQuery` is a no-op.\n await active.prepareQuery({ sql, ...(use ? { use: use as SyncTableName<TRegistry>[] } : {}) });\n\n const live = active.pglite.live;\n // Single-column PK → PGlite's incremental machinery (`live.incrementalQuery`): it maintains the ordered\n // result via an internal `__after__` linked list and only recomputes changed rows. Composite/keyless →\n // `live.query` (full ordered result each fire) and we diff worker-side. Either way the CROSS-WIRE shape\n // is a diff computed by `computeLiveDiff` — neither live API emits an ordered, identity-friendly delta.\n const registered =\n pkColumns && pkColumns.length === 1\n ? await live.incrementalQuery<Record<string, unknown>>(sql, params as unknown[], pkColumns[0]!)\n : await live.query<Record<string, unknown>>(sql, params as unknown[]);\n\n const state = seedLiveDiffState(registered.initialResults.rows, pkColumns);\n // Initial snapshot verbatim (not a diff), correlated to the subscribe request so the tab resolves.\n postBridgeMessage(port, codec, \"live-initial\", { queryId, rows: registered.initialResults.rows }, id);\n\n const listener = (results: { rows: Record<string, unknown>[] }) => {\n // `subscribe` fires only on a real change (never the initial), so every fire yields a genuine delta.\n const diff = computeLiveDiff(state, results.rows);\n postBridgeMessage(port, codec, \"live-diff\", { queryId, ...diff });\n };\n registered.subscribe(listener);\n liveSubs.set(queryId, {\n port,\n unsubscribe: () => void registered.unsubscribe(listener),\n });\n };\n\n // ─── Per-port message routing ────────────────────────────────────────────────────────────────────\n const onPortMessage = (port: BridgePort, data: unknown) => {\n if (!isBridgeEnvelope(data)) return;\n const envelope = data;\n const payload = codec.decode(envelope.payload);\n switch (envelope.type) {\n case \"provision\": {\n // Pre-spawn the raw store (initdb only), idle and schemaless, for the first attach to adopt\n // (ADR-0032 decision 5). A no-op once the engine has booted or a store is already provisioned.\n const provision = payload as ProvisionPayload;\n const dataDir = provision.dataDir ?? provision.storeId ?? options.dataDir ?? \"idb://pgxsinkit-overlay-v1\";\n if (bootPromise != null || provisioned != null) {\n postBridgeMessage(port, codec, \"provision-ack\", {\n ok: true,\n ...(provision.storeId ? { storeId: provision.storeId } : {}),\n });\n break;\n }\n const pglite = createPglite(dataDir);\n provisioned = { dataDir, pglite };\n // Guard an unobserved rejection when no attach ever adopts it (the page navigated away).\n void pglite.catch(() => undefined);\n syncDebug(\"worker store provisioned\", { dataDir });\n void pglite.then(\n () =>\n postBridgeMessage(port, codec, \"provision-ack\", {\n ok: true,\n ...(provision.storeId ? { storeId: provision.storeId } : {}),\n }),\n (error: unknown) =>\n postBridgeMessage(port, codec, \"provision-ack\", {\n ok: false,\n error: serializeError(error),\n ...(provision.storeId ? { storeId: provision.storeId } : {}),\n }),\n );\n break;\n }\n case \"set-online\": {\n // The tab's Offline toggle over the bridge (ADR-0032 S3). Suppress/resume the worker's outbound\n // convergence; resuming fires one immediate pass so queued writes flush at once.\n const { online } = payload as SetOnlinePayload;\n convergenceSuppressed = !online;\n syncDebug(\"worker convergence gate\", { online });\n if (online) fireConvergence?.();\n break;\n }\n case \"attach\": {\n const attach = payload as AttachPayload;\n const alreadyBooted = bootPromise !== null;\n if (alreadyBooted) {\n // A later attach seeds auth WITHOUT clobbering a fresher cached token (ADR-0032 FIX 5) — the\n // first-boot `push` already ran, and only an explicit `token-push` (auth owner) may overwrite.\n tokenCache.pushIfFresher(attach.token);\n // Role is a property of the (user, store) the engine already booted for: the worker is\n // one-engine-per-(user,store) by ADR-0032 decision 2 and is NOT keyed by role. A mismatch is an\n // app-layer bug to surface, not a supported topology — warn, keep the booted registry.\n const requested = attach.config?.role;\n if (requested !== bootedRole) {\n syncDebug(\"worker attach role mismatch — engine keeps its booted registry\", {\n booted: bootedRole,\n requested,\n });\n }\n }\n void boot(attach).then(\n (booted) => {\n client = booted;\n resolveBooted(booted);\n // Track the engine's monotonic `ready` edge exactly once, so a LATER attach acked after the\n // initial sync landed can resolve its `ready` straight from the ack (ADR-0032 FIX 3).\n if (!engineReadyFired) {\n void booted.ready.then(() => {\n engineReadyFired = true;\n });\n }\n // Ack AFTER the engine exists so the tab's subsequent traffic (rpc/subscribe) has a client to\n // hit; include current status + per-group readiness for a late-joining tab (decisions 4/6).\n postBridgeMessage(port, codec, \"attach-ack\", {\n alreadyBooted,\n ...(engineReadyFired ? { engineReady: true } : {}),\n });\n postBridgeMessage(port, codec, \"event\", { kind: \"status\", status: booted.status });\n },\n (error: unknown) => {\n // The engine boot rejected: tell THIS attaching tab so it rejects `attachSyncClient` instead of\n // hanging on the ack (ADR-0032 FIX 1), and clear `bootPromise` so a later attach retries the\n // boot. Do NOT clear `provisioned`: a resolved provisioned PGlite holds the only open handle on\n // that store, so a retry must adopt it (createSyncClient falls back internally if it rejected).\n bootPromise = null;\n postBridgeMessage(port, codec, \"attach-ack\", {\n alreadyBooted,\n error: serializeError(error),\n });\n },\n );\n break;\n }\n case \"token-push\": {\n // The tab pushed a fresh token (auth state change) — update the cache and satisfy any in-flight pull.\n tokenCache.push(payload as AttachPayload[\"token\"]);\n break;\n }\n case \"token-response\": {\n const response = payload as TokenResponsePayload;\n // First response for the current pull wins; a stale/duplicate requestId is ignored.\n tokenCache.respond(response.requestId, response.token);\n break;\n }\n case \"rpc\": {\n const { op, args } = payload as RpcPayload;\n const id = envelope.id;\n void (async () => {\n try {\n const active = client ?? (await bootPromise);\n if (!active) throw new Error(\"rpc before attach\");\n const value = await dispatchRpc(active, op, args);\n postBridgeMessage(port, codec, \"rpc-result\", { ok: true, value }, id);\n } catch (error) {\n postBridgeMessage(port, codec, \"rpc-result\", { ok: false, error: serializeError(error) }, id);\n }\n })();\n break;\n }\n case \"subscribe\": {\n const id = envelope.id;\n void handleSubscribe(port, id, payload as SubscribePayload).catch((error) => {\n postBridgeMessage(port, codec, \"rpc-result\", { ok: false, error: serializeError(error) }, id);\n });\n break;\n }\n case \"unsubscribe\": {\n const { queryId } = payload as { queryId: string };\n const sub = liveSubs.get(queryId);\n if (sub) {\n sub.unsubscribe();\n liveSubs.delete(queryId);\n }\n break;\n }\n case \"wake\": {\n // A tab forwarded online/visibilitychange (or a manual nudge): treat it as a convergence pass request\n // so a write flushes promptly without waiting for the worker's interval tick (decision 5 seam).\n // Suppressed while the Offline toggle is off — a wake must not flush a simulated-offline board.\n if (!convergenceSuppressed) void bootPromise?.then((active) => void active.flush());\n break;\n }\n default:\n break;\n }\n };\n\n const detachPort = (port: BridgePort) => {\n ports.delete(port);\n for (const [queryId, sub] of liveSubs) {\n if (sub.port === port) {\n sub.unsubscribe();\n liveSubs.delete(queryId);\n }\n }\n };\n\n const connect = (port: BridgePort) => {\n ports.add(port);\n const listener = (event: { data: unknown }) => {\n if (isBridgeEnvelope(event.data) && event.data.type === \"detach\") {\n detachPort(port);\n port.removeEventListener(\"message\", listener);\n return;\n }\n onPortMessage(port, event.data);\n };\n port.addEventListener(\"message\", listener);\n port.start?.();\n };\n\n // ─── Global-scope auto-binding (real worker only; tests inject ports via connect) ─────────────────\n if (options.installGlobal !== false) bindGlobalScope(connect);\n\n return {\n connect,\n whenBooted,\n close: async () => {\n for (const sub of liveSubs.values()) sub.unsubscribe();\n liveSubs.clear();\n ports.clear();\n setSyncDebugSink(undefined);\n const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);\n await active?.stop();\n },\n };\n}\n\n/** Serialize a thrown value into the bridge's `{message, detail}` error shape (detail only when structured). */\nfunction serializeError(error: unknown): { message: string; detail?: unknown } {\n if (error instanceof Error) {\n const detail = (error as Error & { detail?: unknown }).detail;\n return { message: error.message, ...(detail !== undefined ? { detail } : {}) };\n }\n return { message: String(error) };\n}\n\ninterface SharedWorkerConnectEvent {\n ports: BridgePort[];\n}\ninterface WorkerGlobalScopeLike {\n onconnect?: (event: SharedWorkerConnectEvent) => void;\n postMessage?: (message: unknown) => void;\n addEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n removeEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n}\n\n/**\n * Bind the running global scope to `connect`. A `SharedWorkerGlobalScope` exposes `onconnect` (one event per\n * tab, each carrying a port); a dedicated `DedicatedWorkerGlobalScope` has no `onconnect` but IS itself the\n * single implicit port (`self.postMessage`/`addEventListener`). Neither exists in a plain test/Node context,\n * where the host is driven via {@link SyncWorkerHost.connect} directly — so this is a no-op there.\n */\nfunction bindGlobalScope(connect: (port: BridgePort) => void): void {\n const scope = globalThis as unknown as WorkerGlobalScopeLike;\n const hasSharedWorkerScope =\n typeof (globalThis as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope !== \"undefined\";\n const hasDedicatedWorkerScope =\n typeof (globalThis as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !== \"undefined\";\n\n if (hasSharedWorkerScope) {\n scope.onconnect = (event: SharedWorkerConnectEvent) => {\n const port = event.ports[0];\n if (port) connect(port);\n };\n return;\n }\n if (hasDedicatedWorkerScope && scope.postMessage && scope.addEventListener && scope.removeEventListener) {\n // The dedicated worker's own global scope IS the single port.\n connect({\n postMessage: (message: unknown) => scope.postMessage!(message),\n addEventListener: (type, listener) => scope.addEventListener!(type, listener),\n removeEventListener: (type, listener) => scope.removeEventListener!(type, listener),\n });\n }\n}\n"
150
+ "// The worker entry factory (ADR-0032 S2, decisions 3/4/6/7). `defineSyncWorker` boots ONE sync engine and\n// fans it out to N attached tabs over the bridge. The first attach boots the engine by calling the\n// unchanged `createSyncClient` (the strongest form of \"reuse createSyncClient internals\" — the in-process\n// boot pipeline runs verbatim, so the unit suite stays its equivalence proof); later attaches join it.\n//\n// It serves BOTH a native `SharedWorker` (`onconnect`, many ports) and a dedicated `Worker` (one implicit\n// port) behind {@link SyncWorkerHost.connect} — the same entry a test drives with a plain `MessageChannel`\n// port, so no real Worker is needed to exercise the whole protocol.\n\nimport type { SyncRuntimeStatus, SyncTableName, SyncTableRegistry, WriteMode } from \"@pgxsinkit/contracts\";\n\nimport { type ConvergenceTrigger, createIntervalConvergenceTrigger } from \"../convergence\";\nimport { setSyncDebugSink, syncDebug } from \"../debug\";\nimport {\n type ClientPGlite,\n createClientPGlite,\n type CreateSyncClientOptions,\n createSyncClient,\n type DataExportOptions,\n type DiagnosticExportOptions,\n type MutationBatchItem,\n type RawQueryOptions,\n type StoreExportOptions,\n type SyncClient,\n} from \"../index\";\nimport { wrapLiveQueryForMaterialization } from \"../live-rows-sql\";\nimport type { LocalStoreVersionEvent } from \"../local-store\";\nimport { readTestStoreMarker, TEST_STORE_BACKEND, type TestStoreMarker } from \"../store-path\";\nimport { computeLiveDiff, seedLiveDiffState } from \"./live-diff\";\nimport {\n type AttachPayload,\n type BridgeCodec,\n type BridgeEnvelope,\n type BridgeEvent,\n type BridgePort,\n type ExportArtefactWire,\n identityCodec,\n isBridgeEnvelope,\n postBridgeMessage,\n type ProvisionPayload,\n type RpcOp,\n type RpcPayload,\n type SetOnlinePayload,\n type SubscribePayload,\n type TokenResponsePayload,\n} from \"./protocol\";\nimport { createWorkerTokenCache } from \"./token-cache\";\n\nexport interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {\n /**\n * The sync registry — imported as CODE by the worker file, never cloned into it (ADR-0032 decision 4).\n * When {@link resolveRegistry} is also given this is the DEFAULT (used when the attach carries no role\n * or an unknown one).\n */\n registry: TRegistry;\n /**\n * Resolve the registry to boot from the attach's `config.role` (ADR-0032 S3). A single worker file can\n * bake BOTH role variants (e.g. the board's admin/member registries — same TS shape, different write\n * capability) and pick per-attach, which the spare flow needs: the spare is provisioned role-agnostic\n * (before the user is known) and the role is only settled at claim/attach. Returns `undefined` to fall\n * back to {@link registry}.\n */\n resolveRegistry?: (role: string | undefined) => TRegistry | undefined;\n /**\n * How the worker creates its raw PGlite store (provision + fresh-attach paths). Defaults to\n * {@link createClientPGlite}, which loads PGlite's own boot assets — in a browser worker those hit the\n * same-origin HTTP cache the tab's login-screen warm already primed (ADR-0032 S3). Injected in tests.\n * Takes a plain store PATH (ADR-0036); the internal `backendOverride` is the test lane's memory selection.\n */\n createPglite?: (storePath: string, backendOverride?: \"memory\") => Promise<ClientPGlite>;\n electricUrl: string;\n writeUrl: string;\n /** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */\n requestHeaders?: Record<string, string>;\n /** Write-only headers merged over {@link requestHeaders} (e.g. region/DB-affinity). See `createSyncClient`. */\n writeRequestHeaders?: Record<string, string>;\n /** Default plain store PATH (ADR-0036) if the first attach carries none — a name, not a storage URL. */\n storePath?: string;\n maxMutationAttempts?: number;\n syncEnabled?: boolean;\n /**\n * How close to expiry (ms) a cached token may be before a read/write that needs it triggers a pull\n * broadcast (ADR-0032 decision 3). Default 30s — comfortably ahead of a long-poll cycle.\n */\n tokenExpiryMarginMs?: number;\n /**\n * The worker's own convergence cadence (ms) — the interval trigger FALLBACK only. Local writes\n * flush immediately via the event-driven `requestPass` seam and tab `wake` signals, so this\n * interval exists purely for retry/recovery sweeps; each idle pass still costs real worker CPU\n * (`flush` + `reconcile` queries). Default 15000.\n */\n convergenceIntervalMs?: number;\n /** Injected transport binder. Defaults to auto-detecting the SharedWorker/dedicated-worker global scope. */\n installGlobal?: boolean;\n /** Injected codec (ADR-0032 S2 §1). Defaults to the v1 identity codec. */\n codec?: BridgeCodec;\n /**\n * A raw PGlite the worker uses instead of creating its own (forwarded to `createSyncClient`'s\n * {@link CreateSyncClientOptions.precreatedPglite}) — the client still applies schema/reconcile. In a\n * browser worker the store is minted internally (`storePath`); this is the seam for a prepopulated store in\n * tests, and the future spare-worker claim (ADR-0032 decision 5).\n */\n precreatedPglite?: CreateSyncClientOptions<TRegistry>[\"precreatedPglite\"];\n /** A fully-provisioned PGlite (forwarded to {@link CreateSyncClientOptions.pgliteInstance}; caller owns schema). */\n pgliteInstance?: CreateSyncClientOptions<TRegistry>[\"pgliteInstance\"];\n}\n\n/** The worker-side host: attach ports, await the boot, and (for tests) tear down. */\nexport interface SyncWorkerHost<TRegistry extends SyncTableRegistry> {\n /** Bind a transport port (a SharedWorker connection, the dedicated-worker `self`, or a test channel port). */\n connect: (port: BridgePort) => void;\n /** Resolves with the booted in-process engine once the first attach's `createSyncClient` completes. */\n whenBooted: () => Promise<SyncClient<TRegistry>>;\n /** Detach every port and stop the underlying client — for tests and dedicated-worker teardown. */\n close: () => Promise<void>;\n}\n\ninterface LiveSub {\n unsubscribe: () => void;\n port: BridgePort;\n}\n\n/**\n * Build a worker host over the given engine config. In a real worker file the consumer calls this at module\n * top level and it auto-binds the global scope; a test constructs it and drives {@link SyncWorkerHost.connect}.\n */\nexport function defineSyncWorker<const TRegistry extends SyncTableRegistry>(\n options: DefineSyncWorkerOptions<TRegistry>,\n): SyncWorkerHost<TRegistry> {\n const codec = options.codec ?? identityCodec;\n const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30_000;\n const convergenceIntervalMs = options.convergenceIntervalMs ?? 15_000;\n const createPglite =\n options.createPglite ??\n ((storePath: string, backendOverride?: \"memory\") =>\n createClientPGlite(storePath, backendOverride ? { backendOverride } : undefined));\n // A testing acknowledgment (ADR-0036) spread into THIS worker's options — needed when a test injects a\n // non-persistent BYO store (`precreatedPglite` / `pgliteInstance` / a memory-returning `createPglite`),\n // which `createSyncClient` would otherwise refuse. Forwarded to the boot below. A browser worker never\n // sets it; a memory selection carried on the attach wire wins over it.\n const workerTestMarker = readTestStoreMarker(options);\n\n const ports = new Set<BridgePort>();\n const liveSubs = new Map<string, LiveSub>();\n\n // ─── Pre-spawned (schemaless) store — the spare flow (ADR-0032 decision 5) ────────────────────────\n // A `provision` mints the raw PGlite (initdb only) and holds it idle here; the first real `attach`\n // adopts it as `precreatedPglite` (the client still runs schema/journal recovery/reconcile). Provision\n // is role-agnostic — the registry is chosen at attach — so the same warmed store serves either role.\n // `stamp` carries the spare's create timing (ADR-0034): a boot adopting this store reports the initdb cost\n // as `BootReport.provision` (with `phases.pgliteCreateMs = null`) instead of timing a create it never ran.\n let provisioned: {\n storePath: string;\n pglite: Promise<ClientPGlite>;\n stamp: Promise<{ initdbMs: number; provisionReadyAt: number }>;\n } | null = null;\n\n // ─── Outbound-convergence gate — the tab's Offline toggle over the bridge (ADR-0032 S3) ───────────\n // The worker owns convergence; the tab forwards its Offline flag as `set-online`. When suppressed the\n // interval trigger's `shouldConverge` returns false (writes stage in the journal, unsent) and a `wake`\n // is ignored; resuming fires one immediate pass so the queue flushes at once.\n let convergenceSuppressed = false;\n let fireConvergence: (() => void) | null = null;\n const baseTrigger = createIntervalConvergenceTrigger(convergenceIntervalMs);\n const gatedTrigger: ConvergenceTrigger = {\n subscribe: (onSignal) => {\n fireConvergence = onSignal;\n const unsubscribe = baseTrigger.subscribe(onSignal);\n return () => {\n fireConvergence = null;\n unsubscribe();\n };\n },\n shouldConverge: () => !convergenceSuppressed && baseTrigger.shouldConverge(),\n };\n\n // ─── The single auth token cache + pull mechanism (ADR-0032 decision 3) ──────────────────────────\n const tokenCache = createWorkerTokenCache({\n marginMs: tokenExpiryMarginMs,\n broadcastRequest: (requestId) => {\n syncDebug(\"worker token pull broadcast\", { requestId, tabs: ports.size });\n broadcast(\"token-request\", { requestId });\n },\n });\n const getWorkerAuthToken = () => tokenCache.getToken();\n\n // ─── The broadcast event channel (ADR-0032 decision 7) ───────────────────────────────────────────\n const seenReadyGroups = new Set<string>();\n const broadcast = (type: BridgeEnvelope[\"type\"], payload: unknown) => {\n for (const port of ports) postBridgeMessage(port, codec, type, payload);\n };\n const broadcastEvent = (event: BridgeEvent) => broadcast(\"event\", event);\n\n // ─── Debug-rail buffer + replay (ADR-0034) ───────────────────────────────────────────────────────\n // The engine boots on the first ATTACH, but the front half of boot (provision, and the boot rail's\n // schema/journal/reconcile lines) can be emitted before any debug-enabled tab is listening — so they\n // vanished. Install the sink at construction (not at boot) into a bounded ring buffer, so the whole boot\n // is captured from worker start; the buffer is REPLAYED (marked `[replay]`) to the first attach, while the\n // back half streams live over the bridge. Bounded so a long-lived worker never grows the buffer unbounded.\n const RAIL_BUFFER_MAX = 500;\n const railBuffer: Array<{ stamp: number; line: string; data?: Record<string, unknown> }> = [];\n let railReplayed = false;\n setSyncDebugSink((line, stamp, data) => {\n if (railBuffer.length >= RAIL_BUFFER_MAX) railBuffer.shift();\n railBuffer.push({ stamp, line, ...(data ? { data } : {}) });\n broadcastEvent({ kind: \"debug\", stamp, line, ...(data ? { data } : {}) });\n });\n const nowStamp = () => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n // Replay the pre-attach rail buffer to the first attaching port. Taken as a snapshot BEFORE this attach's\n // boot runs, so the boot's own lines (which stream live to this now-connected port) are never doubled.\n const replayRailBufferTo = (port: BridgePort) => {\n if (railReplayed) return;\n railReplayed = true;\n const buffered = [...railBuffer];\n postBridgeMessage(port, codec, \"event\", {\n kind: \"debug\",\n stamp: nowStamp(),\n line: `[replay] replaying ${buffered.length} buffered rail line(s)`,\n } satisfies BridgeEvent);\n for (const entry of buffered) {\n postBridgeMessage(port, codec, \"event\", {\n kind: \"debug\",\n stamp: entry.stamp,\n line: `[replay] ${entry.line}`,\n ...(entry.data ? { data: entry.data } : {}),\n } satisfies BridgeEvent);\n }\n };\n\n const emitStatus = (status: SyncRuntimeStatus) => {\n broadcastEvent({ kind: \"status\", status });\n // Derive a per-group `groupReady` event for each group that newly reached ready, so a tab gets both the\n // status snapshot (`status.groups`) and a discrete edge to await (ADR-0032 decision 6/7).\n for (const [groupKey, ready] of Object.entries(status.groups ?? {})) {\n if (ready && !seenReadyGroups.has(groupKey)) {\n seenReadyGroups.add(groupKey);\n broadcastEvent({ kind: \"groupReady\", groupKey });\n }\n }\n };\n\n // ─── Engine boot — reuse createSyncClient verbatim (ADR-0032 decision 1/4) ────────────────────────\n let client: SyncClient<TRegistry> | null = null;\n let bootPromise: Promise<SyncClient<TRegistry>> | null = null;\n // The role the engine actually booted with (from the FIRST attach's config). Later attaches compare\n // their requested role against this and get a warning on mismatch (ADR-0032 FIX 5) — never a reject.\n let bootedRole: string | undefined;\n // The engine's `ready` is monotonic: once its initial sync lands it stays resolved even if the phase\n // later degrades. A tab attaching AFTER that moment must still get a resolved `ready`, so track whether\n // it has fired and tell the ack (ADR-0032 FIX 3).\n let engineReadyFired = false;\n let resolveBooted!: (client: SyncClient<TRegistry>) => void;\n const bootedPromise = new Promise<SyncClient<TRegistry>>((resolve) => {\n resolveBooted = resolve;\n });\n\n const boot = (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {\n if (bootPromise) return bootPromise;\n // The tab is the auth owner: seed the cache with the token it presented at attach (decision 3).\n tokenCache.push(attach.token);\n bootedRole = attach.config?.role;\n // The debug-rail sink is installed at construction (ADR-0034) so it buffers from worker start and\n // forwards live to tabs, stamped with the WORKER's monotonic clock (decision 7) — see above.\n // Resolve the registry from the attach's role (ADR-0032 S3): a single worker file bakes both variants\n // and the claim/attach settles which one boots — the spare was provisioned before the role was known.\n const registry = options.resolveRegistry?.(attach.config?.role) ?? options.registry;\n // storePath-first, matching the `provision` handler's resolution (below): the board sends BOTH a bare\n // `storeId` (SharedWorker naming, tab-side) AND the real `storePath` (`pgxsinkit-board-<id>`), and the\n // PGlite store lives at `storePath` — so the provisioned store's path must be what we adopt on.\n // `storeId` is only a last-ditch fallback for a caller that passes it as the store path.\n const storePath = attach.storePath ?? attach.storeId ?? options.storePath ?? \"pgxsinkit-overlay-v1\";\n // The testing memory-backend override rides as an explicit wire field (a symbol does not survive\n // structured clone, ADR-0036); re-stamp it as the internal marker on the createSyncClient options below.\n // A memory selection on the attach wins over the worker's own acknowledgment (memory implies acknowledged).\n const backendOverride = attach.testStoreBackend;\n const testMarker: TestStoreMarker | undefined = backendOverride === \"memory\" ? \"memory\" : workerTestMarker;\n // Restore (ADR-0035 decision 6): the tab decomposed the backup into a transferred `ArrayBuffer` + mime\n // (`RestoreArtefactWire`); recompose a `Blob` to hand `createSyncClient` as `restoreFrom`. Restore OWNS the\n // store's creation (a `loadDataDir` seed), so it is mutually exclusive with adopting a pre-provisioned or\n // caller-supplied instance — when restoring, we suppress the adopt paths below rather than let\n // createSyncClient throw the exclusion error.\n const restoreFrom = attach.restore\n ? new Blob([attach.restore.buffer], { type: attach.restore.mimeType })\n : undefined;\n // Adopt a matching pre-provisioned store (its initdb already ran off-thread) as `precreatedPglite`;\n // createSyncClient falls back to a fresh `storePath` create if that promise rejects — a pure accelerator.\n // Never adopt when restoring (restore boots a brand-new store from the backup, not the provisioned one).\n const adoptingProvisioned = restoreFrom == null && provisioned != null && provisioned.storePath === storePath;\n const precreatedPglite = adoptingProvisioned\n ? provisioned!.pglite\n : restoreFrom\n ? undefined\n : options.precreatedPglite;\n // The adopted spare's create timing feeds `BootReport.provision` (ADR-0034); absent otherwise.\n const provisionStamp = adoptingProvisioned ? provisioned!.stamp : undefined;\n if (adoptingProvisioned) {\n syncDebug(\"worker adopting provisioned store\", { storePath });\n }\n if (restoreFrom) {\n syncDebug(\"worker restoring store from backup\", { storePath, byteLength: attach.restore!.buffer.byteLength });\n }\n bootPromise = createSyncClient<TRegistry>({\n registry,\n electricUrl: options.electricUrl,\n writeUrl: options.writeUrl,\n storePath,\n // Re-stamp the internal testing marker (ADR-0036) so `createSyncClient`'s option handling selects the\n // memory backend on its fallback create and/or bypasses the BYO refusal for an injected test store —\n // the wire field / worker acknowledgment are the cross-clone carriers for it.\n ...(testMarker ? { [TEST_STORE_BACKEND]: testMarker } : {}),\n // Restore rides the boot attach (ADR-0035 decision 6): createSyncClient seeds the fresh store via\n // `loadDataDir`, boots offline, and quarantines the recovered journal.\n ...(restoreFrom ? { restoreFrom } : {}),\n // Boot observability (ADR-0034): label the report `worker`, and forward the provision stamp so an\n // adopted spare's initdb cost is reported rather than a create this boot never ran.\n bootMode: \"worker\",\n ...(provisionStamp ? { provisionStamp } : {}),\n ...(precreatedPglite ? { precreatedPglite } : {}),\n ...(options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {}),\n // Fresh-store prefetch overlap (ADR-0032 S4): the tab's claim path proved this store a schemaless\n // spare and forwarded the hint in the attach config, so the shape catch-up overlaps schema exec +\n // journal recovery + reconcile. Never inferred from \"adopting a provisioned store\": the board\n // provisions a worker even for a MAPPED (returning) user, whose idb is NOT fresh — only the claim\n // path's explicit hint distinguishes them.\n ...(attach.config?.freshStore === true ? { freshStore: true } : {}),\n getAuthToken: getWorkerAuthToken,\n // The worker owns convergence via the interval trigger, GATED by the tab's Offline toggle\n // (`set-online`); tabs additionally forward online/visibility as `wake` pass requests (below).\n autoSync: gatedTrigger,\n syncEnabled: attach.config?.syncEnabled ?? options.syncEnabled ?? true,\n ...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),\n ...(options.writeRequestHeaders ? { writeRequestHeaders: options.writeRequestHeaders } : {}),\n ...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),\n onStatusChange: (status) => emitStatus(status),\n onConflict: (details) => broadcastEvent({ kind: \"conflict\", details }),\n onQuarantine: (details) => broadcastEvent({ kind: \"quarantine\", details }),\n onReject: (details) => broadcastEvent({ kind: \"reject\", details }),\n onSchemaChange: (event: LocalStoreVersionEvent) => broadcastEvent({ kind: \"schema-change\", event }),\n onSyncError: (error) => broadcastEvent({ kind: \"sync-error\", message: error.message }),\n // Boot observability (ADR-0034): broadcast the finalized report to currently-attached ports (one-shot\n // push). Later tabs read the same report via the `bootReport` pull RPC — there is no replay event.\n onBootReport: (report) => broadcastEvent({ kind: \"boot-report\", report }),\n });\n return bootPromise;\n };\n\n const whenBooted = () => bootedPromise;\n\n // ─── Write / mutation-state RPC dispatch ─────────────────────────────────────────────────────────\n const dispatchRpc = async (active: SyncClient<TRegistry>, op: RpcOp, args: unknown[]): Promise<unknown> => {\n type TableKey = SyncTableName<TRegistry>;\n switch (op) {\n case \"create\":\n return active.mutate.create(args[0] as TableKey, args[1] as never);\n case \"update\":\n return active.mutate.update(args[0] as TableKey, args[1] as Record<string, string>, args[2] as never);\n case \"delete\":\n return active.mutate.delete(args[0] as TableKey, args[1] as Record<string, string>);\n case \"batch\":\n return active.mutate.batch(args[0] as ReadonlyArray<MutationBatchItem<TRegistry>>);\n case \"transaction\": {\n // The tab collected the unit's mutations (the run callback can't cross the wire); the worker replays\n // the serialized items into a real `client.transaction` so pessimistic acks / optimistic flush match\n // the in-process semantics exactly.\n const { mode, items } = args[0] as { mode: WriteMode; items: MutationBatchItem<TRegistry>[] };\n return active.transaction({ mode }, (tx) => {\n for (const item of items) {\n const handle = tx.tables[item.table];\n if (item.kind === \"create\") {\n handle.create(item.input as never);\n } else if (item.kind === \"update\") {\n // ADR-0022 addendum: a `blind` update replays through `updateBlind` (journal-only, no overlay).\n if (item.blind) handle.updateBlind(item.entityKey, item.patch as never);\n else handle.update(item.entityKey, item.patch as never);\n } else {\n handle.delete(item.entityKey);\n }\n }\n });\n }\n case \"flush\":\n return active.flush(args[0] as TableKey | undefined);\n case \"reconcile\":\n return active.reconcile(args[0] as TableKey | undefined);\n case \"retryFailed\":\n return active.retryFailed(args[0] as TableKey | undefined);\n case \"recoverSending\":\n return active.recoverSending(args[0] as TableKey | undefined);\n case \"discardConflict\":\n return active.discardConflict(args[0] as TableKey, args[1] as Record<string, string>);\n case \"discardQuarantined\":\n return active.discardQuarantined(args[0] as TableKey, args[1] as Record<string, string>);\n case \"desync\":\n return active.desync(args[0] as TableKey);\n case \"discardEphemeral\":\n return active.discardEphemeral(args[0] as TableKey);\n case \"readMutationDetails\":\n return active.readMutationDetails(args[0] as TableKey | undefined);\n case \"diagnostics\":\n return active.diagnostics(args[0] as TableKey | undefined);\n case \"rawQuery\":\n // Inspection read (ADR-0032 S2): run straight against the worker's own store — `active.pglite`\n // exists worker-side (it's the in-process client). `Results` rows/fields structured-clone across\n // the wire (Dates survive postMessage), so the tab receives the same shape it would in-process.\n // The options arg is the clonable RawQueryOptions subset (rowMode) — the REPL's array mode.\n return active.rawQuery(args[0] as string, args[1] as unknown[] | undefined, args[2] as RawQueryOptions);\n case \"rawExec\":\n return active.rawExec(args[0] as string, args[1] as RawQueryOptions);\n case \"bootReport\":\n // Boot observability (ADR-0034): the worker engine's stored report (or null). Pull, so a late tab\n // reads a boot predating it; the report structured-clones across the bridge as a plain object.\n return active.bootReport();\n case \"exportStore\": {\n // Store backup (ADR-0035): run the live export on the worker's OWN client (its lifecycle slot\n // serialises it against every tab's export). A `File` cannot cross the bridge as a transferable, so\n // decompose it into an `ExportArtefactWire` — the `ArrayBuffer` is listed on `postMessage`'s transfer\n // list in the `rpc` handler and rebuilt into a `File` tab-side.\n const { file, report } = await active.exportStore(args[0] as StoreExportOptions | undefined);\n const buffer = await file.arrayBuffer();\n return { buffer, fileName: file.name, mimeType: file.type, report } satisfies ExportArtefactWire;\n }\n case \"exportDiagnostics\": {\n // Diagnostic dump (ADR-0035): identical bridge shape to the store backup — the worker runs the live\n // datadir dump → memory throwaway clone → `pg_dump` on its OWN client (same lifecycle slot), and the\n // SQL crosses back as the same transferred-`ArrayBuffer` `ExportArtefactWire`.\n const { file, report } = await active.exportDiagnostics(args[0] as DiagnosticExportOptions | undefined);\n const buffer = await file.arrayBuffer();\n return { buffer, fileName: file.name, mimeType: file.type, report } satisfies ExportArtefactWire;\n }\n case \"exportData\": {\n // Data export (ADR-0035): identical bridge shape — the worker runs the drain-guarded `pg_dump -t`\n // per-synced-table export on its OWN client (same lifecycle slot), and the portable SQL crosses back\n // as the same transferred-`ArrayBuffer` `ExportArtefactWire`. A DataExportDrainError rejects the RPC\n // like any other failure (serialised back to the tab).\n const { file, report } = await active.exportData(args[0] as DataExportOptions | undefined);\n const buffer = await file.arrayBuffer();\n return { buffer, fileName: file.name, mimeType: file.type, report } satisfies ExportArtefactWire;\n }\n default: {\n const exhaustive: never = op;\n throw new Error(`unknown rpc op ${String(exhaustive)}`);\n }\n }\n };\n\n // ─── Live-query bridge (ADR-0032 S2 §4) ──────────────────────────────────────────────────────────\n const handleSubscribe = async (port: BridgePort, id: string | undefined, payload: SubscribePayload) => {\n const active = client ?? (await bootPromise);\n if (!active) throw new Error(\"subscribe before attach\");\n const { queryId, sql, params, pkColumns, use, fields } = payload;\n // Activate any lazy relations the query reads BEFORE registering the live query (ADR-0021) — the worker\n // owns the real client, so its `prepareQuery` does the real work; the tab's `prepareQuery` is a no-op.\n // Scan the ORIGINAL sql (the wrap only adds an outer `SELECT * FROM (...)`; table refs are inside).\n await active.prepareQuery({ sql, ...(use ? { use: use as SyncTableName<TRegistry>[] } : {}) });\n\n const live = active.pglite.live;\n // Render the query safe to materialise: a JOIN with same-named columns fails BOTH live APIs' temp-view\n // creation (`column \"title\" specified more than once`) unless every output column has a unique alias.\n // No `fields` → SQL unchanged (backward-compatible name-keyed rows; the aliased path keys by alias).\n const materialSql = wrapLiveQueryForMaterialization(sql, fields);\n // Single-column PK → PGlite's incremental machinery (`live.incrementalQuery`): it maintains the ordered\n // result via an internal `__after__` linked list and only recomputes changed rows. Composite/keyless →\n // `live.query` (full ordered result each fire) and we diff worker-side. Either way the CROSS-WIRE shape\n // is a diff computed by `computeLiveDiff` — neither live API emits an ordered, identity-friendly delta.\n const registered =\n pkColumns && pkColumns.length === 1\n ? await live.incrementalQuery<Record<string, unknown>>(materialSql, params as unknown[], pkColumns[0]!)\n : await live.query<Record<string, unknown>>(materialSql, params as unknown[]);\n\n const state = seedLiveDiffState(registered.initialResults.rows, pkColumns);\n // Initial snapshot verbatim (not a diff), correlated to the subscribe request so the tab resolves.\n postBridgeMessage(port, codec, \"live-initial\", { queryId, rows: registered.initialResults.rows }, id);\n\n const listener = (results: { rows: Record<string, unknown>[] }) => {\n // `subscribe` fires only on a real change (never the initial), so every fire yields a genuine delta.\n const diff = computeLiveDiff(state, results.rows);\n postBridgeMessage(port, codec, \"live-diff\", { queryId, ...diff });\n };\n registered.subscribe(listener);\n liveSubs.set(queryId, {\n port,\n unsubscribe: () => void registered.unsubscribe(listener),\n });\n };\n\n // ─── Per-port message routing ────────────────────────────────────────────────────────────────────\n const onPortMessage = (port: BridgePort, data: unknown) => {\n if (!isBridgeEnvelope(data)) return;\n const envelope = data;\n const payload = codec.decode(envelope.payload);\n switch (envelope.type) {\n case \"provision\": {\n // Pre-spawn the raw store (initdb only), idle and schemaless, for the first attach to adopt\n // (ADR-0032 decision 5). A no-op once the engine has booted or a store is already provisioned.\n const provision = payload as ProvisionPayload;\n const storePath = provision.storePath ?? provision.storeId ?? options.storePath ?? \"pgxsinkit-overlay-v1\";\n // The testing memory-backend override rides as an explicit wire field (ADR-0036) — a symbol does not\n // survive structured clone, so the store's backend selection travels here and is passed to createPglite.\n const backendOverride = provision.testStoreBackend;\n if (bootPromise != null || provisioned != null) {\n postBridgeMessage(port, codec, \"provision-ack\", {\n ok: true,\n ...(provision.storeId ? { storeId: provision.storeId } : {}),\n });\n break;\n }\n // Stamp the spare's create timing (ADR-0034): initdb cost + the monotonic instant it became ready,\n // so an adopting boot can compute how long it sat idle before adoption.\n const provisionStartedAt = nowStamp();\n const pglite = createPglite(storePath, backendOverride);\n const stamp = pglite.then(() => {\n const readyAt = nowStamp();\n return { initdbMs: readyAt - provisionStartedAt, provisionReadyAt: readyAt };\n });\n provisioned = { storePath, pglite, stamp };\n // Guard an unobserved rejection when no attach ever adopts it (the page navigated away).\n void pglite.catch(() => undefined);\n void stamp.catch(() => undefined);\n syncDebug(\"worker store provisioned\", { storePath });\n void pglite.then(\n () =>\n postBridgeMessage(port, codec, \"provision-ack\", {\n ok: true,\n ...(provision.storeId ? { storeId: provision.storeId } : {}),\n }),\n (error: unknown) =>\n postBridgeMessage(port, codec, \"provision-ack\", {\n ok: false,\n error: serializeError(error),\n ...(provision.storeId ? { storeId: provision.storeId } : {}),\n }),\n );\n break;\n }\n case \"set-online\": {\n // The tab's Offline toggle over the bridge (ADR-0032 S3). Suppress/resume the worker's outbound\n // convergence; resuming fires one immediate pass so queued writes flush at once.\n const { online } = payload as SetOnlinePayload;\n convergenceSuppressed = !online;\n syncDebug(\"worker convergence gate\", { online });\n if (online) fireConvergence?.();\n break;\n }\n case \"attach\": {\n const attach = payload as AttachPayload;\n // Boot observability (ADR-0034): replay the pre-attach rail buffer (provision + any early lines) to\n // the FIRST attaching tab, so the front half of boot is no longer invisible. Snapshotted before this\n // attach's boot runs, so the boot's own lines (streamed live) are not doubled.\n replayRailBufferTo(port);\n const alreadyBooted = bootPromise !== null;\n // Restore rides the FIRST (boot) attach only (ADR-0035 decision 6): a restore attach that arrives once\n // the engine has already booted CANNOT be honoured — `loadDataDir` is a create-time seed and the store\n // is already live. Reject THIS attach with a typed error rather than silently ignoring the backup, so\n // the caller learns their restore did not happen (the engine keeps running its existing store).\n if (alreadyBooted && attach.restore != null) {\n postBridgeMessage(port, codec, \"attach-ack\", {\n alreadyBooted,\n error: {\n message:\n \"[pgxsinkit] cannot restore into a running store: the worker engine has already booted, and a store backup can only seed a brand-new store on the FIRST attach (ADR-0035 decision 6). Restore into a fresh worker instead.\",\n },\n });\n break;\n }\n if (alreadyBooted) {\n // A later attach seeds auth WITHOUT clobbering a fresher cached token (ADR-0032 FIX 5) — the\n // first-boot `push` already ran, and only an explicit `token-push` (auth owner) may overwrite.\n tokenCache.pushIfFresher(attach.token);\n // Role is a property of the (user, store) the engine already booted for: the worker is\n // one-engine-per-(user,store) by ADR-0032 decision 2 and is NOT keyed by role. A mismatch is an\n // app-layer bug to surface, not a supported topology — warn, keep the booted registry.\n const requested = attach.config?.role;\n if (requested !== bootedRole) {\n syncDebug(\"worker attach role mismatch — engine keeps its booted registry\", {\n booted: bootedRole,\n requested,\n });\n }\n }\n void boot(attach).then(\n (booted) => {\n client = booted;\n resolveBooted(booted);\n // Track the engine's monotonic `ready` edge exactly once, so a LATER attach acked after the\n // initial sync landed can resolve its `ready` straight from the ack (ADR-0032 FIX 3).\n if (!engineReadyFired) {\n void booted.ready.then(() => {\n engineReadyFired = true;\n });\n }\n // Ack AFTER the engine exists so the tab's subsequent traffic (rpc/subscribe) has a client to\n // hit; include current status + per-group readiness for a late-joining tab (decisions 4/6).\n postBridgeMessage(port, codec, \"attach-ack\", {\n alreadyBooted,\n ...(engineReadyFired ? { engineReady: true } : {}),\n });\n postBridgeMessage(port, codec, \"event\", { kind: \"status\", status: booted.status });\n },\n (error: unknown) => {\n // The engine boot rejected: tell THIS attaching tab so it rejects `attachSyncClient` instead of\n // hanging on the ack (ADR-0032 FIX 1), and clear `bootPromise` so a later attach retries the\n // boot. Do NOT clear `provisioned`: a resolved provisioned PGlite holds the only open handle on\n // that store, so a retry must adopt it (createSyncClient falls back internally if it rejected).\n bootPromise = null;\n postBridgeMessage(port, codec, \"attach-ack\", {\n alreadyBooted,\n error: serializeError(error),\n });\n },\n );\n break;\n }\n case \"token-push\": {\n // The tab pushed a fresh token (auth state change) — update the cache and satisfy any in-flight pull.\n tokenCache.push(payload as AttachPayload[\"token\"]);\n break;\n }\n case \"token-response\": {\n const response = payload as TokenResponsePayload;\n // First response for the current pull wins; a stale/duplicate requestId is ignored.\n tokenCache.respond(response.requestId, response.token);\n break;\n }\n case \"rpc\": {\n const { op, args } = payload as RpcPayload;\n const id = envelope.id;\n void (async () => {\n try {\n const active = client ?? (await bootPromise);\n if (!active) throw new Error(\"rpc before attach\");\n const value = await dispatchRpc(active, op, args);\n // An export artefact (backup tarball or diagnostic SQL) crosses zero-copy: transfer its\n // `ArrayBuffer` (rebuilt into a `File` tab-side, ADR-0035). Every other op's value\n // structured-clones in place with no transfer list.\n const transfer =\n op === \"exportStore\" || op === \"exportDiagnostics\" || op === \"exportData\"\n ? [(value as ExportArtefactWire).buffer]\n : undefined;\n postBridgeMessage(port, codec, \"rpc-result\", { ok: true, value }, id, transfer);\n } catch (error) {\n postBridgeMessage(port, codec, \"rpc-result\", { ok: false, error: serializeError(error) }, id);\n }\n })();\n break;\n }\n case \"subscribe\": {\n const id = envelope.id;\n void handleSubscribe(port, id, payload as SubscribePayload).catch((error) => {\n postBridgeMessage(port, codec, \"rpc-result\", { ok: false, error: serializeError(error) }, id);\n });\n break;\n }\n case \"unsubscribe\": {\n const { queryId } = payload as { queryId: string };\n const sub = liveSubs.get(queryId);\n if (sub) {\n sub.unsubscribe();\n liveSubs.delete(queryId);\n }\n break;\n }\n case \"wake\": {\n // A tab forwarded online/visibilitychange (or a manual nudge): treat it as a convergence pass request\n // so a write flushes promptly without waiting for the worker's interval tick (decision 5 seam).\n // Suppressed while the Offline toggle is off — a wake must not flush a simulated-offline board.\n if (!convergenceSuppressed) void bootPromise?.then((active) => void active.flush());\n break;\n }\n default:\n break;\n }\n };\n\n const detachPort = (port: BridgePort) => {\n ports.delete(port);\n for (const [queryId, sub] of liveSubs) {\n if (sub.port === port) {\n sub.unsubscribe();\n liveSubs.delete(queryId);\n }\n }\n };\n\n const connect = (port: BridgePort) => {\n ports.add(port);\n const listener = (event: { data: unknown }) => {\n if (isBridgeEnvelope(event.data) && event.data.type === \"detach\") {\n detachPort(port);\n port.removeEventListener(\"message\", listener);\n return;\n }\n onPortMessage(port, event.data);\n };\n port.addEventListener(\"message\", listener);\n port.start?.();\n };\n\n // ─── Global-scope auto-binding (real worker only; tests inject ports via connect) ─────────────────\n if (options.installGlobal !== false) bindGlobalScope(connect);\n\n return {\n connect,\n whenBooted,\n close: async () => {\n for (const sub of liveSubs.values()) sub.unsubscribe();\n liveSubs.clear();\n ports.clear();\n setSyncDebugSink(undefined);\n const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);\n await active?.stop();\n },\n };\n}\n\n/** Serialize a thrown value into the bridge's `{message, detail}` error shape (detail only when structured). */\nfunction serializeError(error: unknown): { message: string; detail?: unknown } {\n if (error instanceof Error) {\n const detail = (error as Error & { detail?: unknown }).detail;\n return { message: error.message, ...(detail !== undefined ? { detail } : {}) };\n }\n return { message: String(error) };\n}\n\ninterface SharedWorkerConnectEvent {\n ports: BridgePort[];\n}\ninterface WorkerGlobalScopeLike {\n onconnect?: (event: SharedWorkerConnectEvent) => void;\n postMessage?: (message: unknown) => void;\n addEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n removeEventListener?: (type: \"message\", listener: (event: { data: unknown }) => void) => void;\n}\n\n/**\n * Bind the running global scope to `connect`. A `SharedWorkerGlobalScope` exposes `onconnect` (one event per\n * tab, each carrying a port); a dedicated `DedicatedWorkerGlobalScope` has no `onconnect` but IS itself the\n * single implicit port (`self.postMessage`/`addEventListener`). Neither exists in a plain test/Node context,\n * where the host is driven via {@link SyncWorkerHost.connect} directly — so this is a no-op there.\n */\nfunction bindGlobalScope(connect: (port: BridgePort) => void): void {\n const scope = globalThis as unknown as WorkerGlobalScopeLike;\n const hasSharedWorkerScope =\n typeof (globalThis as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope !== \"undefined\";\n const hasDedicatedWorkerScope =\n typeof (globalThis as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !== \"undefined\";\n\n if (hasSharedWorkerScope) {\n scope.onconnect = (event: SharedWorkerConnectEvent) => {\n const port = event.ports[0];\n if (port) connect(port);\n };\n return;\n }\n if (hasDedicatedWorkerScope && scope.postMessage && scope.addEventListener && scope.removeEventListener) {\n // The dedicated worker's own global scope IS the single port.\n connect({\n postMessage: (message: unknown) => scope.postMessage!(message),\n addEventListener: (type, listener) => scope.addEventListener!(type, listener),\n removeEventListener: (type, listener) => scope.removeEventListener!(type, listener),\n });\n }\n}\n"
144
151
  ],
145
- "mappings": ";;AAA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