@pgxsinkit/client 0.1.32 → 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 (111) hide show
  1. package/README.md +11 -0
  2. package/dist/boot-report.d.ts +134 -0
  3. package/dist/boot-report.d.ts.map +1 -0
  4. package/dist/convergence.d.ts +76 -0
  5. package/dist/convergence.d.ts.map +1 -0
  6. package/dist/debug.d.ts +34 -0
  7. package/dist/debug.d.ts.map +1 -0
  8. package/dist/export-data.d.ts +100 -0
  9. package/dist/export-data.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts +92 -0
  11. package/dist/export-dump.d.ts.map +1 -0
  12. package/dist/export-store.d.ts +214 -0
  13. package/dist/export-store.d.ts.map +1 -0
  14. package/dist/index.d.ts +615 -8
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8083 -2286
  17. package/dist/index.js.map +81 -44
  18. package/dist/lazy-guard.d.ts +59 -0
  19. package/dist/lazy-guard.d.ts.map +1 -0
  20. package/dist/lifecycle-slot.d.ts +31 -0
  21. package/dist/lifecycle-slot.d.ts.map +1 -0
  22. package/dist/live-rows-sql.d.ts +21 -0
  23. package/dist/live-rows-sql.d.ts.map +1 -0
  24. package/dist/local-store.d.ts +56 -0
  25. package/dist/local-store.d.ts.map +1 -0
  26. package/dist/local-tables.d.ts +707 -0
  27. package/dist/local-tables.d.ts.map +1 -0
  28. package/dist/mutation-state.d.ts +69 -0
  29. package/dist/mutation-state.d.ts.map +1 -0
  30. package/dist/mutation.d.ts +129 -4
  31. package/dist/mutation.d.ts.map +1 -1
  32. package/dist/schema.d.ts +82 -0
  33. package/dist/schema.d.ts.map +1 -1
  34. package/dist/shape-sync.d.ts +190 -0
  35. package/dist/shape-sync.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +132 -0
  37. package/dist/store-path.d.ts.map +1 -0
  38. package/dist/sync/apply.d.ts +51 -0
  39. package/dist/sync/apply.d.ts.map +1 -0
  40. package/dist/sync/copy.d.ts +43 -0
  41. package/dist/sync/copy.d.ts.map +1 -0
  42. package/dist/sync/drizzle-executor.d.ts +5 -0
  43. package/dist/sync/drizzle-executor.d.ts.map +1 -0
  44. package/dist/sync/index.d.ts +32 -0
  45. package/dist/sync/index.d.ts.map +1 -0
  46. package/dist/sync/metadata-tables.d.ts +131 -0
  47. package/dist/sync/metadata-tables.d.ts.map +1 -0
  48. package/dist/sync/nudge.d.ts +49 -0
  49. package/dist/sync/nudge.d.ts.map +1 -0
  50. package/dist/sync/shape-inbox.d.ts +215 -0
  51. package/dist/sync/shape-inbox.d.ts.map +1 -0
  52. package/dist/sync/subscription-state.d.ts +39 -0
  53. package/dist/sync/subscription-state.d.ts.map +1 -0
  54. package/dist/sync/tags.d.ts +130 -0
  55. package/dist/sync/tags.d.ts.map +1 -0
  56. package/dist/sync/types.d.ts +126 -0
  57. package/dist/sync/types.d.ts.map +1 -0
  58. package/dist/sync-auth.d.ts +53 -0
  59. package/dist/sync-auth.d.ts.map +1 -0
  60. package/dist/testing.d.ts +27 -0
  61. package/dist/testing.d.ts.map +1 -0
  62. package/dist/testing.js +17 -0
  63. package/dist/testing.js.map +11 -0
  64. package/dist/worker/attach-sync-client.d.ts +96 -0
  65. package/dist/worker/attach-sync-client.d.ts.map +1 -0
  66. package/dist/worker/define-sync-worker.d.ts +76 -0
  67. package/dist/worker/define-sync-worker.d.ts.map +1 -0
  68. package/dist/worker/live-diff.d.ts +44 -0
  69. package/dist/worker/live-diff.d.ts.map +1 -0
  70. package/dist/worker/protocol.d.ts +341 -0
  71. package/dist/worker/protocol.d.ts.map +1 -0
  72. package/dist/worker/token-cache.d.ts +26 -0
  73. package/dist/worker/token-cache.d.ts.map +1 -0
  74. package/oxlint-plugin.js +143 -0
  75. package/package.json +20 -7
  76. package/skills/core/SKILL.md +210 -0
  77. package/skills/operating/SKILL.md +303 -0
  78. package/src/boot-report.ts +287 -0
  79. package/src/convergence.ts +197 -0
  80. package/src/debug.ts +151 -0
  81. package/src/export-data.ts +300 -0
  82. package/src/export-dump.ts +239 -0
  83. package/src/export-store.ts +309 -0
  84. package/src/index.ts +1652 -51
  85. package/src/lazy-guard.ts +135 -0
  86. package/src/lifecycle-slot.ts +66 -0
  87. package/src/live-rows-sql.ts +45 -0
  88. package/src/local-store.ts +193 -0
  89. package/src/local-tables.ts +546 -0
  90. package/src/mutation-state.ts +99 -0
  91. package/src/mutation.ts +1910 -562
  92. package/src/schema.ts +472 -28
  93. package/src/shape-sync.ts +498 -0
  94. package/src/store-path.ts +249 -0
  95. package/src/sync/apply.ts +530 -0
  96. package/src/sync/copy.ts +206 -0
  97. package/src/sync/drizzle-executor.ts +48 -0
  98. package/src/sync/index.ts +1087 -0
  99. package/src/sync/metadata-tables.ts +67 -0
  100. package/src/sync/nudge.ts +110 -0
  101. package/src/sync/shape-inbox.ts +566 -0
  102. package/src/sync/subscription-state.ts +135 -0
  103. package/src/sync/tags.ts +365 -0
  104. package/src/sync/types.ts +141 -0
  105. package/src/sync-auth.ts +117 -0
  106. package/src/testing.ts +53 -0
  107. package/src/worker/attach-sync-client.ts +653 -0
  108. package/src/worker/define-sync-worker.ts +762 -0
  109. package/src/worker/live-diff.ts +140 -0
  110. package/src/worker/protocol.ts +425 -0
  111. package/src/worker/token-cache.ts +84 -0
@@ -0,0 +1,117 @@
1
+ import type { ExternalHeadersRecord, ShapeStreamOptions } from "@electric-sql/client";
2
+
3
+ /** The per-shape error handler shape Electric expects (`ShapeStreamOptions.onError`). */
4
+ type ShapeStreamErrorHandler = NonNullable<ShapeStreamOptions["onError"]>;
5
+
6
+ /**
7
+ * Read-path identity (ADR-0013). The two ingress points must share **one** token lifecycle: the
8
+ * write path already calls `getAuthToken` fresh on every flush, so the read path must too — never
9
+ * freezing a JWT at boot, which wedges a long-lived offline-first session the instant the token
10
+ * expires.
11
+ *
12
+ * `buildAuthShapeHeaders` returns the read-path `Authorization` header as an **async function**.
13
+ * Electric resolves header-value functions on every request *and every retry*
14
+ * (`ExternalHeadersRecord` allows `string | (() => string | Promise<string>)`), so each shape fetch
15
+ * presents a fresh token. This is the client mirror of ADR-0003's server-side one-identity decision.
16
+ *
17
+ * The provider contract (documented in `docs/architecture.md`): `getAuthToken` is now called per
18
+ * request by both paths and **must be refresh-deduping** — return the cached valid token and refresh
19
+ * single-flight, so an N-shape consistency group does not trigger N refreshes.
20
+ */
21
+ /**
22
+ * Build the read-path shape headers: the optional async `Authorization` (per ADR-0013) **plus** any
23
+ * caller-supplied static `requestHeaders`. The static headers are spread first so the toolkit-owned
24
+ * `Authorization` always wins; they exist for deployment-gateway credentials the toolkit is otherwise
25
+ * agnostic about — e.g. a Supabase `apikey` header the platform function gateway expects. Emitted
26
+ * whenever *either* a token provider or static headers are present, so a credential-only consumer
27
+ * (no per-request token) still sends its headers.
28
+ */
29
+ export function buildShapeHeaders(input: {
30
+ getAuthToken?: () => Promise<string | undefined>;
31
+ requestHeaders?: Record<string, string>;
32
+ }): ExternalHeadersRecord {
33
+ const headers: ExternalHeadersRecord = { ...(input.requestHeaders ?? {}) };
34
+ const getAuthToken = input.getAuthToken;
35
+ if (getAuthToken) {
36
+ // Resolved per request: a fresh token each time, never one captured at boot. An absent token
37
+ // yields an empty value (unauthenticated) rather than the literal string `Bearer undefined`.
38
+ headers["Authorization"] = async () => {
39
+ const token = await getAuthToken();
40
+ return token ? `Bearer ${token}` : "";
41
+ };
42
+ }
43
+ return headers;
44
+ }
45
+
46
+ /** Token-only convenience over {@link buildShapeHeaders}; retained for callers that pass a provider. */
47
+ export function buildAuthShapeHeaders(
48
+ getAuthToken: () => Promise<string | undefined>,
49
+ requestHeaders?: Record<string, string>,
50
+ ): ExternalHeadersRecord {
51
+ return buildShapeHeaders({ getAuthToken, ...(requestHeaders ? { requestHeaders } : {}) });
52
+ }
53
+
54
+ /** HTTP statuses that mean "the credential is the problem" — re-auth, never give up (ADR-0013). */
55
+ const AUTH_ERROR_STATUSES = new Set([401, 403]);
56
+
57
+ /** Read the duck-typed numeric `status` off an Electric `FetchError`, or `undefined` for a plain error. */
58
+ function readErrorStatus(error: unknown): number | undefined {
59
+ if (typeof error !== "object" || error === null || !("status" in error)) {
60
+ return undefined;
61
+ }
62
+ const status = (error as { status: unknown }).status;
63
+ return typeof status === "number" ? status : undefined;
64
+ }
65
+
66
+ /**
67
+ * True when the error is an auth failure (Electric's `FetchError` with a 401/403 `status`). We read
68
+ * the documented `status` field rather than `instanceof FetchError`: the experimental and client
69
+ * packages can resolve to *different* `@electric-sql/client` copies, so an `instanceof` against one
70
+ * copy can miss a `FetchError` thrown from the other. A duck-typed numeric `status` is robust and
71
+ * carries no false positives — a plain network/`Error` has no numeric `status`.
72
+ */
73
+ function isAuthError(error: unknown): boolean {
74
+ const status = readErrorStatus(error);
75
+ return status !== undefined && AUTH_ERROR_STATUSES.has(status);
76
+ }
77
+
78
+ /**
79
+ * Whether a non-auth read-stream error is worth retrying (#4): a transient transport fault — a 5xx,
80
+ * a 429 rate-limit, or a network error with no HTTP status. A genuine non-auth 4xx (400/404/409/…)
81
+ * is structural: retrying re-fails, so we stop. (401/403 are handled separately as auth.)
82
+ */
83
+ function isRetryableStreamError(error: unknown): boolean {
84
+ const status = readErrorStatus(error);
85
+ if (status === undefined) {
86
+ return true; // network/transport error — retry with Electric's backoff
87
+ }
88
+ return status >= 500 || status === 429;
89
+ }
90
+
91
+ /**
92
+ * The per-shape `ShapeStreamOptions.onError` handler for the read path. It is the only place that can
93
+ * request a retry (the `MultiShapeStream.subscribe` `onError` is notification-only), so it owns BOTH
94
+ * read-path identity (ADR-0013) and read-stream error surfacing (#4):
95
+ *
96
+ * - **auth (401/403)** → `onAuthError` + return `{}` (retry): Electric re-issues the request,
97
+ * re-resolving the async Authorization header ({@link buildAuthShapeHeaders}) for a *fresh* token.
98
+ * Never return `void` here — that stops the stream permanently, wrong for offline-first: a dead
99
+ * session must keep retrying (jittered backoff bounds the cost) so sync resumes the instant re-auth
100
+ * makes the token valid again. The optional `onAuthError` surfaces a distinct "re-login" status.
101
+ * - **any other error** → `onReadStreamError` (so the runtime can move to a `degraded` status instead
102
+ * of silently believing the read path is live), then retry transient faults ({@link
103
+ * isRetryableStreamError}: 5xx/429/network → `{}`) or stop a structural 4xx (return `undefined`). A
104
+ * later successful fetch (`onSyncActivity`) clears the degraded status back to live.
105
+ */
106
+ export function createShapeErrorHandler(
107
+ options: { onAuthError?: () => void; onReadStreamError?: (error: Error) => void } = {},
108
+ ): ShapeStreamErrorHandler {
109
+ return (error: Error) => {
110
+ if (isAuthError(error)) {
111
+ options.onAuthError?.();
112
+ return {}; // retry → re-resolves the async Authorization header for a fresh token
113
+ }
114
+ options.onReadStreamError?.(error);
115
+ return isRetryableStreamError(error) ? {} : undefined;
116
+ };
117
+ }
package/src/testing.ts ADDED
@@ -0,0 +1,53 @@
1
+ // `@pgxsinkit/client/testing` — the ONLY sanctioned door to a memory-backed store (ADR-0036 decision 3).
2
+ //
3
+ // pgxsinkit's durability semantics assume a persisted store, so the production API surface cannot express a
4
+ // memory store: `createSyncClient`/`createClientPGlite` take a plain `storePath` whose backend is derived
5
+ // (IndexedDB / filesystem), and the BYO seam refuses a provably non-persistent instance. Genuine memory
6
+ // stores are needed in exactly two of OUR places — the unit-test lane (speed + isolation) and the export
7
+ // machinery's throwaway clone — and this subpath serves the first: an import whose NAME says what it is, so
8
+ // reaching a memory store is always a visible, deliberate act. App bundles never import it, so the whole
9
+ // module (and any mention of memory) tree-shakes away.
10
+ //
11
+ // The helpers mint plain options objects that ALSO carry the module-internal {@link TEST_STORE_BACKEND}
12
+ // marker at runtime — invisible in the public return type. Consumers SPREAD them into the client options:
13
+ //
14
+ // createSyncClient({ ...memoryStoreForTests("my-test"), registry, electricUrl, writeUrl })
15
+ // createSyncClient({ ...testStoreAcknowledgment(), pgliteInstance, registry, electricUrl, writeUrl })
16
+
17
+ import { TEST_STORE_BACKEND } from "./store-path";
18
+
19
+ /**
20
+ * The public shape of {@link memoryStoreForTests}'s output: just a `storePath`. The internal backend marker
21
+ * rides alongside at runtime but is deliberately absent from this type, so no production type mentions memory.
22
+ */
23
+ export interface MemoryStoreForTests {
24
+ storePath: string;
25
+ }
26
+
27
+ /**
28
+ * Mint client store options that resolve to a scheme-selected in-memory store — the unit-test / ephemeral
29
+ * lane (ADR-0036 decision 3). Spread the result into `createSyncClient` (or `defineSyncWorker` where its
30
+ * options accept `storePath`): the client reads the internal marker and selects the memory backend.
31
+ *
32
+ * DURABILITY CAVEAT: a memory store is session-scoped, so pgxsinkit's persistent-retention guarantee and the
33
+ * optimistic Mutation journal's durability window are BOTH void on it — everything is lost when the instance
34
+ * closes. Use it only for tests and throwaway/ephemeral flows, never for anything a user expects to persist.
35
+ */
36
+ export function memoryStoreForTests(storePath: string): MemoryStoreForTests {
37
+ // The marker is a symbol-keyed property, so it survives an object spread but is invisible to the public
38
+ // type and to `Object.keys`. Cast because the return TYPE deliberately hides it (ADR-0036 decision 3).
39
+ return { storePath, [TEST_STORE_BACKEND]: "memory" } as MemoryStoreForTests;
40
+ }
41
+
42
+ /**
43
+ * Mint an options fragment that ACKNOWLEDGES a caller-owned test store, bypassing the BYO refusal
44
+ * (ADR-0036 decision 4) WITHOUT selecting a backend — for when the test supplies its own non-persistent
45
+ * PGlite via `pgliteInstance` / `precreatedPglite`. Spread it alongside that option.
46
+ *
47
+ * Same DURABILITY CAVEAT as {@link memoryStoreForTests}: only for tests / throwaway flows; a non-persistent
48
+ * store voids the retention + journal durability guarantees.
49
+ */
50
+ export function testStoreAcknowledgment(): Record<never, never> {
51
+ // An empty public shape carrying only the internal marker — nothing for a consumer to configure.
52
+ return { [TEST_STORE_BACKEND]: "acknowledged" } as Record<never, never>;
53
+ }