@pgxsinkit/react 0.1.41 → 0.1.48

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.
@@ -18,7 +18,15 @@ interface DrizzleSqlBuilder<TRows extends readonly unknown[]> extends PromiseLik
18
18
  readonly selectedFields?: SelectedFields;
19
19
  };
20
20
  }
21
- /** Reactive read result. `hydrating` is true while a lazy relation the query reads is being activated. */
21
+ /**
22
+ * Reactive read result. `hydrating` is true from mount until every consistency group the query reads —
23
+ * eager OR lazy — has completed its initial catch-up (`client.groupReady`) and the caught-up rows have
24
+ * been delivered to this subscription, not merely started its stream. Rows flow while it is true
25
+ * (local/cached rows paint immediately; catch-up rows stream in), so render an empty state only when
26
+ * `!loading && !hydrating` — zero rows before that means "not loaded yet", not "empty". A subscription
27
+ * whose groups are all already caught up at mount (the steady-state fast path) clears `hydrating` at the
28
+ * first snapshot with no extra work.
29
+ */
22
30
  interface LiveRowsState<TRows> {
23
31
  rows: TRows;
24
32
  loading: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"create-hooks.d.ts","sourceRoot":"","sources":["../src/create-hooks.tsx"],"names":[],"mappings":"AACA,OAAO,EAAiB,KAAK,cAAc,EAAE,KAAK,SAAS,EAA4C,MAAM,OAAO,CAAC;AAErH,OAAO,EAAE,KAAK,YAAY,EAA6B,KAAK,UAAU,EAAa,MAAM,mBAAmB,CAAC;AAC7G,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAE7E,OAAO,EAAuD,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAE5G;;;;;;GAMG;AACH,UAAU,iBAAiB,CAAC,KAAK,SAAS,SAAS,OAAO,EAAE,CAAE,SAAQ,WAAW,CAAC,KAAK,CAAC;IACtF,KAAK,IAAI;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,OAAO,EAAE,CAAA;KAAE,CAAC;IAC5C,QAAQ,CAA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K,EAAE,CAAC,MAAM,EAAE,UAAU,CAAC,SAAS,CAAC,KAAK,iBAAiB,CAAC,KAAK,CAAC,CAAC;QACnE,IAAI,CAAC,EAAE,cAAc,CAAC;QACtB,KAAK,CAAC,EAAE,OAAO,CAAC;KACjB,KAAG,aAAa,CAAC,KAAK,CAAC;yBAOI,KAAK,SAAS,SAAS,OAAO,EAAE,QAAQ;QAClE,GAAG,CAAC,EAAE,SAAS,aAAa,CAAC,SAAS,CAAC,EAAE,CAAC;QAC1C,KAAK,EAAE,CAAC,MAAM,EAAE,UAAU,CAAC,SAAS,CAAC,KAAK,iBAAiB,CAAC,KAAK,CAAC,CAAC;QACnE,IAAI,CAAC,EAAE,cAAc,CAAC;QACtB,KAAK,CAAC,EAAE,OAAO,CAAC;KACjB,KAAG;QAAE,GAAG,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;QAAC,OAAO,EAAE,OAAO,CAAC;QAAC,SAAS,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAA;KAAE;EAe7F"}
package/dist/index.js CHANGED
@@ -251,12 +251,6 @@ function createSyncClientHooks() {
251
251
  ...useList ? { use: useList } : {}
252
252
  }).then(() => {
253
253
  if (!active) return void 0;
254
- setState((prev) => ({
255
- rows: prev.rows,
256
- loading: true,
257
- hydrating: false,
258
- error: null
259
- }));
260
254
  return contextClient.subscribeLiveRows({
261
255
  sql: sql.sql,
262
256
  params: sql.params,
@@ -265,12 +259,12 @@ function createSyncClientHooks() {
265
259
  }, (rows) => {
266
260
  if (active) {
267
261
  syncDebug("live query updated → re-render", { rows: rows.length });
268
- setState({
262
+ setState((prev) => ({
269
263
  rows: mapRows(rows),
270
264
  loading: false,
271
- hydrating: false,
265
+ hydrating: prev.hydrating,
272
266
  error: null
273
- });
267
+ }));
274
268
  }
275
269
  }).then((registered) => {
276
270
  if (!active) {
@@ -278,11 +272,17 @@ function createSyncClientHooks() {
278
272
  return;
279
273
  }
280
274
  subscription = registered;
281
- setState({
275
+ setState((prev) => ({
282
276
  rows: mapRows(registered.initialRows),
283
277
  loading: false,
284
- hydrating: false,
278
+ hydrating: registered.hydrated != null ? prev.hydrating : false,
285
279
  error: null
280
+ }));
281
+ if (registered.hydrated) registered.hydrated.then(() => {
282
+ if (active) setState((prev) => ({
283
+ ...prev,
284
+ hydrating: false
285
+ }));
286
286
  });
287
287
  });
288
288
  }).catch((error) => {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/remap-live-row.ts","../src/create-hooks.tsx"],"sourcesContent":["import { Column, is, SQL } from \"drizzle-orm\";\n\n/** The `{ fieldKey: Column | SQL | nested }` map carried on a Drizzle select at `query._.selectedFields`. */\nexport type SelectedFields = Record<string, unknown>;\n\n/**\n * Map a raw PGlite live-query row onto a Drizzle select's field keys.\n *\n * `useLiveDrizzleRows` feeds the builder's `.toSQL()` straight into PGlite's `live.query`, which\n * returns rows keyed by the **underlying column names** (snake_case) — `select({ assigneeId })`\n * produces SQL `select \"assignee_id\"`, so the raw row is `{ assignee_id }`, not `{ assigneeId }`.\n * Drizzle's own execution would remap these by position; the live query bypasses that, so this does it\n * by name using the select's field metadata:\n *\n * - a {@link Column} carries its DB `name`, so the value is read from `row[column.name]`;\n * - an {@link SQL} / aliased expression is aliased to its key in the generated SQL, so read `row[key]`;\n * - a nested selection object recurses;\n * - with no field map (a raw query) the row is returned unchanged.\n */\nexport function remapLiveRow(\n selectedFields: SelectedFields | undefined,\n row: Record<string, unknown>,\n): Record<string, unknown> {\n if (selectedFields == null) return row;\n const out: Record<string, unknown> = {};\n for (const [key, field] of Object.entries(selectedFields)) {\n if (is(field, Column)) {\n out[key] = row[field.name];\n } else if (is(field, SQL) || is(field, SQL.Aliased)) {\n out[key] = row[key];\n } else if (field != null && typeof field === \"object\") {\n out[key] = remapLiveRow(field as SelectedFields, row);\n } else {\n out[key] = row[key];\n }\n }\n return out;\n}\n\n// ─── Materialization-safe live reads (JOINs with same-named columns) ─────────────────────────────────\n//\n// Reading by the underlying column NAME (as `remapLiveRow` does) is unsound when a JOIN's tables share a\n// column name — `select({ courseTitle: course.title, moduleTitle: module.title })` compiles to a SELECT\n// with two `title` output columns. PGlite's `live` extension MATERIALISES the query and fails hard\n// (`column \"title\" specified more than once`); even a plain query would silently collapse both `title`s\n// into one value. The seam (`client.subscribeLiveRows`) fixes this by wrapping the query with a POSITIONAL\n// column-alias-list when it is handed `fields` — the unique aliases below — so every output column is\n// renamed to a distinct name. Rows then come back keyed by THOSE aliases, and `remapAliasedLiveRow` maps\n// them onto the select's field keys positionally.\n\n/** The prefix for the positional output aliases the live-rows seam renames a materialised query's columns to. */\nconst LIVE_FIELD_ALIAS_PREFIX = \"__pgx_c\";\n\n/** Assign a positional alias to the `index`-th output column: `__pgx_c0`, `__pgx_c1`, … (unique by index). */\nfunction liveFieldAliasAt(index: number): string {\n return `${LIVE_FIELD_ALIAS_PREFIX}${index}`;\n}\n\n/**\n * Flatten a Drizzle select's `selectedFields` into the ordered list of UNIQUE output aliases needed to\n * make its live query safe to materialise. The walk order (depth-first over the field keys, recursing\n * into nested selection objects) matches Drizzle's column-emission order in the compiled SQL, so the\n * `index`-th leaf here is the `index`-th output column there — the invariant the positional\n * column-alias-list depends on. Returns `undefined` for a raw query (no field map): the seam then leaves\n * the SQL unwrapped and rows stay keyed by the underlying column names ({@link remapLiveRow}).\n */\nexport function liveFieldAliases(selectedFields: SelectedFields | undefined): string[] | undefined {\n if (selectedFields == null) return undefined;\n const aliases: string[] = [];\n const walk = (fields: SelectedFields): void => {\n for (const field of Object.values(fields)) {\n if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {\n aliases.push(liveFieldAliasAt(aliases.length));\n } else if (field != null && typeof field === \"object\") {\n walk(field as SelectedFields);\n } else {\n aliases.push(liveFieldAliasAt(aliases.length));\n }\n }\n };\n walk(selectedFields);\n return aliases.length > 0 ? aliases : undefined;\n}\n\n/**\n * Map a live row that came back from the ALIAS-WRAPPED query (keyed by the positional `__pgx_cN` aliases\n * {@link liveFieldAliases} produced) onto the Drizzle select's field keys. Walks `selectedFields` in the\n * same order, so the Nth leaf reads `row[__pgx_cN]`; nested selections recurse. The alias-space\n * counterpart to {@link remapLiveRow} — which keys by the underlying column name and cannot survive a\n * same-named-column collision. Returns the row unchanged when there is no field map (a raw query).\n */\nexport function remapAliasedLiveRow(\n selectedFields: SelectedFields | undefined,\n row: Record<string, unknown>,\n): Record<string, unknown> {\n if (selectedFields == null) return row;\n const cursor = { index: 0 };\n const walk = (fields: SelectedFields): Record<string, unknown> => {\n const out: Record<string, unknown> = {};\n for (const [key, field] of Object.entries(fields)) {\n if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {\n out[key] = row[liveFieldAliasAt(cursor.index)];\n cursor.index += 1;\n } else if (field != null && typeof field === \"object\") {\n out[key] = walk(field as SelectedFields);\n } else {\n out[key] = row[liveFieldAliasAt(cursor.index)];\n cursor.index += 1;\n }\n }\n return out;\n };\n return walk(selectedFields);\n}\n","import type { LiveQuery, LiveQueryResults } from \"@electric-sql/pglite/live\";\nimport { createContext, type DependencyList, type ReactNode, useContext, useEffect, useMemo, useState } from \"react\";\n\nimport { type ClientPGlite, type LiveRowsSubscription, type SyncClient, syncDebug } from \"@pgxsinkit/client\";\nimport type { SyncTableName, SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { liveFieldAliases, remapAliasedLiveRow, remapLiveRow, type SelectedFields } from \"./remap-live-row\";\n\n/**\n * Minimal interface satisfied by every Drizzle select/query builder.\n * Calling `.toSQL()` extracts the SQL string and positional params without\n * executing the query, so they can be fed into PGlite's live query API. `_.selectedFields` is the\n * select's field metadata, used to remap PGlite's snake_case rows back to the builder's field keys\n * ({@link remapLiveRow}) — without it the typed rows would carry the underlying column names.\n */\ninterface DrizzleSqlBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {\n toSQL(): { sql: string; params: unknown[] };\n readonly _?: { readonly selectedFields?: SelectedFields };\n}\n\n/** Reactive read result. `hydrating` is true while a lazy relation the query reads is being activated. */\ninterface LiveRowsState<TRows> {\n rows: TRows;\n loading: boolean;\n hydrating: boolean;\n error: Error | null;\n}\n\n/**\n * The raw direct-PGlite subscription used only by `useLiveRows`'s explicit-`pglite` override (tests/multi-db).\n * Wraps `pglite.live.query` into the client's {@link LiveRowsSubscription} shape so the hook body treats the\n * override and the seam identically. The normal path goes through `client.subscribeLiveRows`.\n */\nfunction subscribeRawPglite<TRow extends Record<string, unknown>>(\n pglite: ClientPGlite,\n query: string,\n params: unknown[],\n onRows: (rows: TRow[]) => void,\n): Promise<LiveRowsSubscription<TRow>> {\n return pglite.live.query<TRow>(query, params).then((registered: LiveQuery<TRow>) => {\n const listener = (results: LiveQueryResults<TRow>) => onRows(results.rows);\n registered.subscribe(listener);\n return {\n initialRows: registered.initialResults.rows,\n unsubscribe: () => void registered.unsubscribe(listener),\n };\n });\n}\n\n/**\n * Creates a set of React hooks and a context provider bound to a specific\n * `SyncTableRegistry` type. Call this once at the module level in your app:\n *\n * ```ts\n * export const { SyncClientProvider, useSyncClient, useLiveRows, useLiveDrizzleRows, useLiveQueryRaw } =\n * createSyncClientHooks<typeof mySyncRegistry>();\n * ```\n */\nexport function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {\n const SyncClientContext = createContext<SyncClient<TRegistry> | null>(null);\n\n // ─── Provider ────────────────────────────────────────────────────────────\n\n function SyncClientProvider({ client, children }: { client: SyncClient<TRegistry> | null; children: ReactNode }) {\n return <SyncClientContext.Provider value={client}>{children}</SyncClientContext.Provider>;\n }\n\n function useSyncClient(): SyncClient<TRegistry> {\n const client = useContext(SyncClientContext);\n if (client == null) {\n throw new Error(\"[pgxsinkit] useSyncClient must be called inside <SyncClientProvider>\");\n }\n return client;\n }\n\n // ─── Raw SQL live hooks ───────────────────────────────────────────────────\n\n /**\n * Reactive raw-SQL query. This is the **unguarded** escape hatch: it does not participate in the\n * lazy-relation safety net (ADR-0021) — a raw string is not parameterised/quoted predictably, so a\n * `lazy` relation referenced here will read empty/stale unless you `client.ensureSynced([...])` first.\n * Prefer {@link useLiveDrizzleRows} / {@link useLiveQueryRaw} for anything touching lazy relations.\n */\n function useLiveRows<TRow extends Record<string, unknown> = Record<string, unknown>>(\n query: string,\n options?: {\n params?: readonly unknown[];\n ready?: boolean;\n /** Explicit PGlite instance — overrides the context client. Useful in tests or multi-db scenarios. */\n pglite?: ClientPGlite;\n },\n ): { rows: TRow[]; loading: boolean; error: Error | null } {\n const contextClient = useContext(SyncClientContext);\n // An explicit `pglite` override keeps the raw direct-PGlite path (tests/multi-db); otherwise the query\n // runs through the client's live-rows seam, so this hook works against the worker-attached client too\n // (which has no local `pglite`) exactly as against the in-process client (ADR-0032 S2 §4).\n const overridePglite = options?.pglite;\n const ready = options?.ready ?? true;\n\n const paramsKey = JSON.stringify(options?.params ?? []);\n const stableParams = useMemo<unknown[]>(() => JSON.parse(paramsKey) as unknown[], [paramsKey]);\n\n const [state, setState] = useState<{ rows: TRow[]; loading: boolean; error: Error | null }>({\n rows: [],\n loading: ready,\n error: null,\n });\n\n useEffect(() => {\n const canRun = ready && (overridePglite != null || contextClient != null);\n if (!canRun) {\n setState({ rows: [], loading: ready, error: null });\n return;\n }\n\n let active = true;\n let subscription: LiveRowsSubscription<TRow> | undefined;\n\n setState((prev) => ({ rows: prev.rows, loading: true, error: null }));\n\n const onRows = (rows: TRow[]) => {\n if (active) {\n syncDebug(\"live query updated → re-render\", { rows: rows.length });\n setState({ rows, loading: false, error: null });\n }\n };\n\n // The raw-PGlite override subscribes directly (unchanged); the seam path is the SAME `pglite.live`\n // wrapper the in-process client exposes, so behaviour is identical when no override is given.\n const subscribe = overridePglite\n ? subscribeRawPglite<TRow>(overridePglite, query, stableParams, onRows)\n : contextClient!.subscribeLiveRows<Record<string, unknown>>({ sql: query, params: stableParams }, (rows) =>\n onRows(rows as TRow[]),\n );\n\n void subscribe\n .then((registered) => {\n if (!active) {\n registered.unsubscribe();\n return;\n }\n subscription = registered as LiveRowsSubscription<TRow>;\n setState({ rows: registered.initialRows as TRow[], loading: false, error: null });\n })\n .catch((error: unknown) => {\n if (active) {\n setState({ rows: [], loading: false, error: error instanceof Error ? error : new Error(String(error)) });\n }\n });\n\n return () => {\n active = false;\n subscription?.unsubscribe();\n };\n }, [contextClient, overridePglite, query, ready, stableParams]);\n\n return state;\n }\n\n function useLiveRow<TRow extends Record<string, unknown> = Record<string, unknown>>(\n query: string,\n options?: { params?: readonly unknown[]; ready?: boolean; pglite?: ClientPGlite },\n ): { row: TRow | null; loading: boolean; error: Error | null } {\n const { rows, loading, error } = useLiveRows<TRow>(query, options);\n return { row: rows[0] ?? null, loading, error };\n }\n\n // ─── Drizzle typed live hooks ─────────────────────────────────────────────\n\n /**\n * Shared implementation behind {@link useLiveDrizzleRows} and {@link useLiveQueryRaw}. Builds the query,\n * then `client.prepareQuery` scans the compiled SQL for the lazy relations it reads (∪ the optional\n * `use`), activates + hydrates them, and only then subscribes the live query — so it is never\n * registered against an un-hydrated lazy relation (ADR-0021).\n */\n function useGuardedDrizzleLive<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean; use?: readonly SyncTableName<TRegistry>[] },\n ): LiveRowsState<TRows> {\n const contextClient = useContext(SyncClientContext);\n const ready = options?.ready ?? true;\n const useList = options?.use;\n const useKey = useList != null ? JSON.stringify(useList) : \"\";\n\n const queryInfo = useMemo(\n () => {\n if (contextClient == null) return null;\n const query = buildQuery(contextClient);\n return { sql: query.toSQL(), selectedFields: query._?.selectedFields };\n },\n // buildQuery intentionally excluded; callers control reactivity via deps. Spread is valid and intentional.\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- intentional: callers own deps, spread is by design\n [contextClient, ...deps],\n );\n\n const sqlKey = queryInfo != null ? JSON.stringify(queryInfo.sql) : null;\n\n const [state, setState] = useState<LiveRowsState<TRows>>({\n rows: [] as unknown as TRows,\n loading: ready,\n hydrating: ready,\n error: null,\n });\n\n useEffect(() => {\n if (!ready || contextClient == null || queryInfo == null) {\n setState({ rows: [] as unknown as TRows, loading: ready, hydrating: false, error: null });\n return;\n }\n\n const { sql, selectedFields } = queryInfo;\n // Render the query safe to MATERIALISE: hand the seam the select's unique field aliases so it wraps a\n // JOIN with same-named columns (two `title`) under a positional column-alias-list — otherwise PGlite's\n // live query refuses it (`column \"title\" specified more than once`) and same-named columns collapse.\n // With `fields` the rows come back keyed by those aliases, so map by alias; without a field map (a raw\n // query) the seam leaves the SQL unwrapped and rows stay name-keyed (`remapLiveRow`).\n const fields = liveFieldAliases(selectedFields);\n const mapRows = (rows: readonly unknown[]): TRows =>\n rows.map((row) =>\n fields\n ? remapAliasedLiveRow(selectedFields, row as Record<string, unknown>)\n : remapLiveRow(selectedFields, row as Record<string, unknown>),\n ) as unknown as TRows;\n\n let active = true;\n let subscription: LiveRowsSubscription<Record<string, unknown>> | undefined;\n\n setState((prev) => ({ rows: prev.rows, loading: true, hydrating: true, error: null }));\n\n // Scan the compiled SQL for the lazy relations the query reads (∪ `use`), activate + hydrate them,\n // THEN subscribe via the client's live-rows seam — so a query is never registered against an\n // un-hydrated lazy relation (ADR-0021), and the same hook drives both the in-process client (seam over\n // `pglite.live`) and the worker-attached client (seam over the bridge, ADR-0032 S2 §4).\n void contextClient\n .prepareQuery({ sql: sql.sql, ...(useList ? { use: useList } : {}) })\n .then(() => {\n if (!active) return undefined;\n setState((prev) => ({ rows: prev.rows, loading: true, hydrating: false, error: null }));\n return contextClient\n .subscribeLiveRows<Record<string, unknown>>(\n { sql: sql.sql, params: sql.params, ...(fields ? { fields } : {}), ...(useList ? { use: useList } : {}) },\n (rows) => {\n if (active) {\n syncDebug(\"live query updated → re-render\", { rows: rows.length });\n setState({ rows: mapRows(rows), loading: false, hydrating: false, error: null });\n }\n },\n )\n .then((registered) => {\n if (!active) {\n registered.unsubscribe();\n return undefined;\n }\n subscription = registered;\n setState({ rows: mapRows(registered.initialRows), loading: false, hydrating: false, error: null });\n return undefined;\n });\n })\n .catch((error: unknown) => {\n if (active) {\n setState({\n rows: [] as unknown as TRows,\n loading: false,\n hydrating: false,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n });\n\n return () => {\n active = false;\n subscription?.unsubscribe();\n };\n // sqlKey/useKey are stable JSON snapshots; queryInfo is captured inside the effect.\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- sqlKey/useKey are the stable proxies for queryInfo\n }, [contextClient, sqlKey, useKey, ready]);\n\n return state;\n }\n\n /**\n * Reactive query using a Drizzle select builder. The builder is re-created\n * whenever `deps` changes (same contract as `useEffect`). pgxsinkit scans the compiled SQL and\n * auto-activates any `lazy` relation the query reads — anywhere it appears (FROM, JOIN, subquery,\n * WHERE) — before subscribing. `use` (see {@link useLiveQueryRaw}) is an optional pre-activation hint,\n * not a requirement (ADR-0021).\n *\n * ```ts\n * const { rows } = useLiveDrizzleRows(\n * (c) => c.drizzle.select().from(c.views.todos).orderBy(c.views.todos.createdAtUs),\n * [],\n * );\n * // rows is fully typed from the view definition — no casts needed\n * ```\n */\n function useLiveDrizzleRows<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean },\n ): LiveRowsState<TRows> {\n return useGuardedDrizzleLive(buildQuery, deps, options);\n }\n\n function useLiveDrizzleRow<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean },\n ): { row: TRows[number] | null; loading: boolean; hydrating: boolean; error: Error | null } {\n const { rows, loading, hydrating, error } = useGuardedDrizzleLive(buildQuery, deps, options);\n return { row: rows[0] ?? null, loading, hydrating, error };\n }\n\n /**\n * The reactive query for a builder that embeds a raw `sql` fragment (ADR-0021): `use` names the `lazy`\n * relations it reads that the compiled-SQL scan can't see (a bare identifier inside raw SQL), so they\n * are guaranteed activated before it subscribes. The non-live counterpart of\n * `client.queryRaw({ use, build })`. Pure-Drizzle reads use `useLiveDrizzleRows` / `client.query((c) => …)`,\n * which auto-detect every relation and need no `use`.\n *\n * ```ts\n * const { rows, hydrating } = useLiveQueryRaw({\n * use: [\"archive\"],\n * build: (c) => c.drizzle.select().from(archiveTable).where(inArray(archiveTable.id, recentIds)),\n * deps: [recentIds],\n * });\n * ```\n */\n function useLiveQueryRaw<TRows extends readonly unknown[]>(args: {\n use?: readonly SyncTableName<TRegistry>[];\n build: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>;\n deps?: DependencyList;\n ready?: boolean;\n }): LiveRowsState<TRows> {\n return useGuardedDrizzleLive(args.build, args.deps ?? [], {\n ...(args.ready != null ? { ready: args.ready } : {}),\n ...(args.use ? { use: args.use } : {}),\n });\n }\n\n function useLiveQueryRawRow<TRows extends readonly unknown[]>(args: {\n use?: readonly SyncTableName<TRegistry>[];\n build: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>;\n deps?: DependencyList;\n ready?: boolean;\n }): { row: TRows[number] | null; loading: boolean; hydrating: boolean; error: Error | null } {\n const { rows, loading, hydrating, error } = useLiveQueryRaw(args);\n return { row: rows[0] ?? null, loading, hydrating, error };\n }\n\n return {\n SyncClientProvider,\n useSyncClient,\n useLiveRows,\n useLiveRow,\n useLiveDrizzleRows,\n useLiveDrizzleRow,\n useLiveQueryRaw,\n useLiveQueryRawRow,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,aACd,gBACA,KACyB;CACzB,IAAI,kBAAkB,MAAM,OAAO;CACnC,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,cAAc,GACtD,IAAI,GAAG,OAAO,MAAM,GAClB,IAAI,OAAO,IAAI,MAAM;MAChB,IAAI,GAAG,OAAO,GAAG,KAAK,GAAG,OAAO,IAAI,OAAO,GAChD,I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["../src/remap-live-row.ts","../src/create-hooks.tsx"],"sourcesContent":["import { Column, is, SQL } from \"drizzle-orm\";\n\n/** The `{ fieldKey: Column | SQL | nested }` map carried on a Drizzle select at `query._.selectedFields`. */\nexport type SelectedFields = Record<string, unknown>;\n\n/**\n * Map a raw PGlite live-query row onto a Drizzle select's field keys.\n *\n * `useLiveDrizzleRows` feeds the builder's `.toSQL()` straight into PGlite's `live.query`, which\n * returns rows keyed by the **underlying column names** (snake_case) — `select({ assigneeId })`\n * produces SQL `select \"assignee_id\"`, so the raw row is `{ assignee_id }`, not `{ assigneeId }`.\n * Drizzle's own execution would remap these by position; the live query bypasses that, so this does it\n * by name using the select's field metadata:\n *\n * - a {@link Column} carries its DB `name`, so the value is read from `row[column.name]`;\n * - an {@link SQL} / aliased expression is aliased to its key in the generated SQL, so read `row[key]`;\n * - a nested selection object recurses;\n * - with no field map (a raw query) the row is returned unchanged.\n */\nexport function remapLiveRow(\n selectedFields: SelectedFields | undefined,\n row: Record<string, unknown>,\n): Record<string, unknown> {\n if (selectedFields == null) return row;\n const out: Record<string, unknown> = {};\n for (const [key, field] of Object.entries(selectedFields)) {\n if (is(field, Column)) {\n out[key] = row[field.name];\n } else if (is(field, SQL) || is(field, SQL.Aliased)) {\n out[key] = row[key];\n } else if (field != null && typeof field === \"object\") {\n out[key] = remapLiveRow(field as SelectedFields, row);\n } else {\n out[key] = row[key];\n }\n }\n return out;\n}\n\n// ─── Materialization-safe live reads (JOINs with same-named columns) ─────────────────────────────────\n//\n// Reading by the underlying column NAME (as `remapLiveRow` does) is unsound when a JOIN's tables share a\n// column name — `select({ courseTitle: course.title, moduleTitle: module.title })` compiles to a SELECT\n// with two `title` output columns. PGlite's `live` extension MATERIALISES the query and fails hard\n// (`column \"title\" specified more than once`); even a plain query would silently collapse both `title`s\n// into one value. The seam (`client.subscribeLiveRows`) fixes this by wrapping the query with a POSITIONAL\n// column-alias-list when it is handed `fields` — the unique aliases below — so every output column is\n// renamed to a distinct name. Rows then come back keyed by THOSE aliases, and `remapAliasedLiveRow` maps\n// them onto the select's field keys positionally.\n\n/** The prefix for the positional output aliases the live-rows seam renames a materialised query's columns to. */\nconst LIVE_FIELD_ALIAS_PREFIX = \"__pgx_c\";\n\n/** Assign a positional alias to the `index`-th output column: `__pgx_c0`, `__pgx_c1`, … (unique by index). */\nfunction liveFieldAliasAt(index: number): string {\n return `${LIVE_FIELD_ALIAS_PREFIX}${index}`;\n}\n\n/**\n * Flatten a Drizzle select's `selectedFields` into the ordered list of UNIQUE output aliases needed to\n * make its live query safe to materialise. The walk order (depth-first over the field keys, recursing\n * into nested selection objects) matches Drizzle's column-emission order in the compiled SQL, so the\n * `index`-th leaf here is the `index`-th output column there — the invariant the positional\n * column-alias-list depends on. Returns `undefined` for a raw query (no field map): the seam then leaves\n * the SQL unwrapped and rows stay keyed by the underlying column names ({@link remapLiveRow}).\n */\nexport function liveFieldAliases(selectedFields: SelectedFields | undefined): string[] | undefined {\n if (selectedFields == null) return undefined;\n const aliases: string[] = [];\n const walk = (fields: SelectedFields): void => {\n for (const field of Object.values(fields)) {\n if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {\n aliases.push(liveFieldAliasAt(aliases.length));\n } else if (field != null && typeof field === \"object\") {\n walk(field as SelectedFields);\n } else {\n aliases.push(liveFieldAliasAt(aliases.length));\n }\n }\n };\n walk(selectedFields);\n return aliases.length > 0 ? aliases : undefined;\n}\n\n/**\n * Map a live row that came back from the ALIAS-WRAPPED query (keyed by the positional `__pgx_cN` aliases\n * {@link liveFieldAliases} produced) onto the Drizzle select's field keys. Walks `selectedFields` in the\n * same order, so the Nth leaf reads `row[__pgx_cN]`; nested selections recurse. The alias-space\n * counterpart to {@link remapLiveRow} — which keys by the underlying column name and cannot survive a\n * same-named-column collision. Returns the row unchanged when there is no field map (a raw query).\n */\nexport function remapAliasedLiveRow(\n selectedFields: SelectedFields | undefined,\n row: Record<string, unknown>,\n): Record<string, unknown> {\n if (selectedFields == null) return row;\n const cursor = { index: 0 };\n const walk = (fields: SelectedFields): Record<string, unknown> => {\n const out: Record<string, unknown> = {};\n for (const [key, field] of Object.entries(fields)) {\n if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {\n out[key] = row[liveFieldAliasAt(cursor.index)];\n cursor.index += 1;\n } else if (field != null && typeof field === \"object\") {\n out[key] = walk(field as SelectedFields);\n } else {\n out[key] = row[liveFieldAliasAt(cursor.index)];\n cursor.index += 1;\n }\n }\n return out;\n };\n return walk(selectedFields);\n}\n","import type { LiveQuery, LiveQueryResults } from \"@electric-sql/pglite/live\";\nimport { createContext, type DependencyList, type ReactNode, useContext, useEffect, useMemo, useState } from \"react\";\n\nimport { type ClientPGlite, type LiveRowsSubscription, type SyncClient, syncDebug } from \"@pgxsinkit/client\";\nimport type { SyncTableName, SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { liveFieldAliases, remapAliasedLiveRow, remapLiveRow, type SelectedFields } from \"./remap-live-row\";\n\n/**\n * Minimal interface satisfied by every Drizzle select/query builder.\n * Calling `.toSQL()` extracts the SQL string and positional params without\n * executing the query, so they can be fed into PGlite's live query API. `_.selectedFields` is the\n * select's field metadata, used to remap PGlite's snake_case rows back to the builder's field keys\n * ({@link remapLiveRow}) — without it the typed rows would carry the underlying column names.\n */\ninterface DrizzleSqlBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {\n toSQL(): { sql: string; params: unknown[] };\n readonly _?: { readonly selectedFields?: SelectedFields };\n}\n\n/**\n * Reactive read result. `hydrating` is true from mount until every consistency group the query reads —\n * eager OR lazy — has completed its initial catch-up (`client.groupReady`) and the caught-up rows have\n * been delivered to this subscription, not merely started its stream. Rows flow while it is true\n * (local/cached rows paint immediately; catch-up rows stream in), so render an empty state only when\n * `!loading && !hydrating` — zero rows before that means \"not loaded yet\", not \"empty\". A subscription\n * whose groups are all already caught up at mount (the steady-state fast path) clears `hydrating` at the\n * first snapshot with no extra work.\n */\ninterface LiveRowsState<TRows> {\n rows: TRows;\n loading: boolean;\n hydrating: boolean;\n error: Error | null;\n}\n\n/**\n * The raw direct-PGlite subscription used only by `useLiveRows`'s explicit-`pglite` override (tests/multi-db).\n * Wraps `pglite.live.query` into the client's {@link LiveRowsSubscription} shape so the hook body treats the\n * override and the seam identically. The normal path goes through `client.subscribeLiveRows`.\n */\nfunction subscribeRawPglite<TRow extends Record<string, unknown>>(\n pglite: ClientPGlite,\n query: string,\n params: unknown[],\n onRows: (rows: TRow[]) => void,\n): Promise<LiveRowsSubscription<TRow>> {\n return pglite.live.query<TRow>(query, params).then((registered: LiveQuery<TRow>) => {\n const listener = (results: LiveQueryResults<TRow>) => onRows(results.rows);\n registered.subscribe(listener);\n return {\n initialRows: registered.initialResults.rows,\n unsubscribe: () => void registered.unsubscribe(listener),\n };\n });\n}\n\n/**\n * Creates a set of React hooks and a context provider bound to a specific\n * `SyncTableRegistry` type. Call this once at the module level in your app:\n *\n * ```ts\n * export const { SyncClientProvider, useSyncClient, useLiveRows, useLiveDrizzleRows, useLiveQueryRaw } =\n * createSyncClientHooks<typeof mySyncRegistry>();\n * ```\n */\nexport function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {\n const SyncClientContext = createContext<SyncClient<TRegistry> | null>(null);\n\n // ─── Provider ────────────────────────────────────────────────────────────\n\n function SyncClientProvider({ client, children }: { client: SyncClient<TRegistry> | null; children: ReactNode }) {\n return <SyncClientContext.Provider value={client}>{children}</SyncClientContext.Provider>;\n }\n\n function useSyncClient(): SyncClient<TRegistry> {\n const client = useContext(SyncClientContext);\n if (client == null) {\n throw new Error(\"[pgxsinkit] useSyncClient must be called inside <SyncClientProvider>\");\n }\n return client;\n }\n\n // ─── Raw SQL live hooks ───────────────────────────────────────────────────\n\n /**\n * Reactive raw-SQL query. This is the **unguarded** escape hatch: it does not participate in the\n * lazy-relation safety net (ADR-0021) — a raw string is not parameterised/quoted predictably, so a\n * `lazy` relation referenced here will read empty/stale unless you `client.ensureSynced([...])` first.\n * Prefer {@link useLiveDrizzleRows} / {@link useLiveQueryRaw} for anything touching lazy relations.\n */\n function useLiveRows<TRow extends Record<string, unknown> = Record<string, unknown>>(\n query: string,\n options?: {\n params?: readonly unknown[];\n ready?: boolean;\n /** Explicit PGlite instance — overrides the context client. Useful in tests or multi-db scenarios. */\n pglite?: ClientPGlite;\n },\n ): { rows: TRow[]; loading: boolean; error: Error | null } {\n const contextClient = useContext(SyncClientContext);\n // An explicit `pglite` override keeps the raw direct-PGlite path (tests/multi-db); otherwise the query\n // runs through the client's live-rows seam, so this hook works against the worker-attached client too\n // (which has no local `pglite`) exactly as against the in-process client (ADR-0032 S2 §4).\n const overridePglite = options?.pglite;\n const ready = options?.ready ?? true;\n\n const paramsKey = JSON.stringify(options?.params ?? []);\n const stableParams = useMemo<unknown[]>(() => JSON.parse(paramsKey) as unknown[], [paramsKey]);\n\n const [state, setState] = useState<{ rows: TRow[]; loading: boolean; error: Error | null }>({\n rows: [],\n loading: ready,\n error: null,\n });\n\n useEffect(() => {\n const canRun = ready && (overridePglite != null || contextClient != null);\n if (!canRun) {\n setState({ rows: [], loading: ready, error: null });\n return;\n }\n\n let active = true;\n let subscription: LiveRowsSubscription<TRow> | undefined;\n\n setState((prev) => ({ rows: prev.rows, loading: true, error: null }));\n\n const onRows = (rows: TRow[]) => {\n if (active) {\n syncDebug(\"live query updated → re-render\", { rows: rows.length });\n setState({ rows, loading: false, error: null });\n }\n };\n\n // The raw-PGlite override subscribes directly (unchanged); the seam path is the SAME `pglite.live`\n // wrapper the in-process client exposes, so behaviour is identical when no override is given.\n const subscribe = overridePglite\n ? subscribeRawPglite<TRow>(overridePglite, query, stableParams, onRows)\n : contextClient!.subscribeLiveRows<Record<string, unknown>>({ sql: query, params: stableParams }, (rows) =>\n onRows(rows as TRow[]),\n );\n\n void subscribe\n .then((registered) => {\n if (!active) {\n registered.unsubscribe();\n return;\n }\n subscription = registered as LiveRowsSubscription<TRow>;\n setState({ rows: registered.initialRows as TRow[], loading: false, error: null });\n })\n .catch((error: unknown) => {\n if (active) {\n setState({ rows: [], loading: false, error: error instanceof Error ? error : new Error(String(error)) });\n }\n });\n\n return () => {\n active = false;\n subscription?.unsubscribe();\n };\n }, [contextClient, overridePglite, query, ready, stableParams]);\n\n return state;\n }\n\n function useLiveRow<TRow extends Record<string, unknown> = Record<string, unknown>>(\n query: string,\n options?: { params?: readonly unknown[]; ready?: boolean; pglite?: ClientPGlite },\n ): { row: TRow | null; loading: boolean; error: Error | null } {\n const { rows, loading, error } = useLiveRows<TRow>(query, options);\n return { row: rows[0] ?? null, loading, error };\n }\n\n // ─── Drizzle typed live hooks ─────────────────────────────────────────────\n\n /**\n * Shared implementation behind {@link useLiveDrizzleRows} and {@link useLiveQueryRaw}. Builds the query,\n * then `client.prepareQuery` scans the compiled SQL for the lazy relations it reads (∪ the optional\n * `use`), activates + hydrates them, and only then subscribes the live query — so it is never\n * registered against an un-hydrated lazy relation (ADR-0021).\n */\n function useGuardedDrizzleLive<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean; use?: readonly SyncTableName<TRegistry>[] },\n ): LiveRowsState<TRows> {\n const contextClient = useContext(SyncClientContext);\n const ready = options?.ready ?? true;\n const useList = options?.use;\n const useKey = useList != null ? JSON.stringify(useList) : \"\";\n\n const queryInfo = useMemo(\n () => {\n if (contextClient == null) return null;\n const query = buildQuery(contextClient);\n return { sql: query.toSQL(), selectedFields: query._?.selectedFields };\n },\n // buildQuery intentionally excluded; callers control reactivity via deps. Spread is valid and intentional.\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- intentional: callers own deps, spread is by design\n [contextClient, ...deps],\n );\n\n const sqlKey = queryInfo != null ? JSON.stringify(queryInfo.sql) : null;\n\n const [state, setState] = useState<LiveRowsState<TRows>>({\n rows: [] as unknown as TRows,\n loading: ready,\n hydrating: ready,\n error: null,\n });\n\n useEffect(() => {\n if (!ready || contextClient == null || queryInfo == null) {\n setState({ rows: [] as unknown as TRows, loading: ready, hydrating: false, error: null });\n return;\n }\n\n const { sql, selectedFields } = queryInfo;\n // Render the query safe to MATERIALISE: hand the seam the select's unique field aliases so it wraps a\n // JOIN with same-named columns (two `title`) under a positional column-alias-list — otherwise PGlite's\n // live query refuses it (`column \"title\" specified more than once`) and same-named columns collapse.\n // With `fields` the rows come back keyed by those aliases, so map by alias; without a field map (a raw\n // query) the seam leaves the SQL unwrapped and rows stay name-keyed (`remapLiveRow`).\n const fields = liveFieldAliases(selectedFields);\n const mapRows = (rows: readonly unknown[]): TRows =>\n rows.map((row) =>\n fields\n ? remapAliasedLiveRow(selectedFields, row as Record<string, unknown>)\n : remapLiveRow(selectedFields, row as Record<string, unknown>),\n ) as unknown as TRows;\n\n let active = true;\n let subscription: LiveRowsSubscription<Record<string, unknown>> | undefined;\n\n setState((prev) => ({ rows: prev.rows, loading: true, hydrating: true, error: null }));\n\n // Scan the compiled SQL for the lazy relations the query reads (∪ `use`), ACTIVATE them (streams\n // started, tripwire satisfied), THEN subscribe via the client's live-rows seam — so a query is never\n // registered against a dormant lazy relation (ADR-0021), and the same hook drives both the in-process\n // client (seam over `pglite.live`) and the worker-attached client (seam over the bridge, ADR-0032 S2 §4).\n // Activation is NOT catch-up: the subscription registers immediately (local/cached rows paint, and an\n // offline client is never blocked behind the network), while `hydrating` stays true until the\n // subscription's `hydrated` promise resolves. That promise now spans EVERY referenced consistency\n // group (eager AND lazy) still catching up — not just the lazy ones — so a cold boot's eager catch-up\n // is covered too; when every referenced group is already ready at subscribe time the seam builds no\n // promise and `hydrating` clears at the first snapshot. The seam guarantees rows-before-signal (it\n // refreshes the live query against the caught-up store before resolving), so clearing `hydrating`\n // here can never present zero rows as \"empty\" while the catch-up rows are still in flight.\n void contextClient\n .prepareQuery({ sql: sql.sql, ...(useList ? { use: useList } : {}) })\n .then(() => {\n if (!active) return undefined;\n return contextClient\n .subscribeLiveRows<Record<string, unknown>>(\n { sql: sql.sql, params: sql.params, ...(fields ? { fields } : {}), ...(useList ? { use: useList } : {}) },\n (rows) => {\n if (active) {\n syncDebug(\"live query updated → re-render\", { rows: rows.length });\n setState((prev) => ({ rows: mapRows(rows), loading: false, hydrating: prev.hydrating, error: null }));\n }\n },\n )\n .then((registered) => {\n if (!active) {\n registered.unsubscribe();\n return undefined;\n }\n subscription = registered;\n setState((prev) => ({\n rows: mapRows(registered.initialRows),\n loading: false,\n hydrating: registered.hydrated != null ? prev.hydrating : false,\n error: null,\n }));\n if (registered.hydrated) {\n void registered.hydrated.then(() => {\n if (active) setState((prev) => ({ ...prev, hydrating: false }));\n });\n }\n return undefined;\n });\n })\n .catch((error: unknown) => {\n if (active) {\n setState({\n rows: [] as unknown as TRows,\n loading: false,\n hydrating: false,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n });\n\n return () => {\n active = false;\n subscription?.unsubscribe();\n };\n // sqlKey/useKey are stable JSON snapshots; queryInfo is captured inside the effect.\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- sqlKey/useKey are the stable proxies for queryInfo\n }, [contextClient, sqlKey, useKey, ready]);\n\n return state;\n }\n\n /**\n * Reactive query using a Drizzle select builder. The builder is re-created\n * whenever `deps` changes (same contract as `useEffect`). pgxsinkit scans the compiled SQL and\n * auto-activates any `lazy` relation the query reads — anywhere it appears (FROM, JOIN, subquery,\n * WHERE) — before subscribing. `use` (see {@link useLiveQueryRaw}) is an optional pre-activation hint,\n * not a requirement (ADR-0021).\n *\n * ```ts\n * const { rows } = useLiveDrizzleRows(\n * (c) => c.drizzle.select().from(c.views.todos).orderBy(c.views.todos.createdAtUs),\n * [],\n * );\n * // rows is fully typed from the view definition — no casts needed\n * ```\n */\n function useLiveDrizzleRows<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean },\n ): LiveRowsState<TRows> {\n return useGuardedDrizzleLive(buildQuery, deps, options);\n }\n\n function useLiveDrizzleRow<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean },\n ): { row: TRows[number] | null; loading: boolean; hydrating: boolean; error: Error | null } {\n const { rows, loading, hydrating, error } = useGuardedDrizzleLive(buildQuery, deps, options);\n return { row: rows[0] ?? null, loading, hydrating, error };\n }\n\n /**\n * The reactive query for a builder that embeds a raw `sql` fragment (ADR-0021): `use` names the `lazy`\n * relations it reads that the compiled-SQL scan can't see (a bare identifier inside raw SQL), so they\n * are guaranteed activated before it subscribes. The non-live counterpart of\n * `client.queryRaw({ use, build })`. Pure-Drizzle reads use `useLiveDrizzleRows` / `client.query((c) => …)`,\n * which auto-detect every relation and need no `use`.\n *\n * ```ts\n * const { rows, hydrating } = useLiveQueryRaw({\n * use: [\"archive\"],\n * build: (c) => c.drizzle.select().from(archiveTable).where(inArray(archiveTable.id, recentIds)),\n * deps: [recentIds],\n * });\n * ```\n */\n function useLiveQueryRaw<TRows extends readonly unknown[]>(args: {\n use?: readonly SyncTableName<TRegistry>[];\n build: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>;\n deps?: DependencyList;\n ready?: boolean;\n }): LiveRowsState<TRows> {\n return useGuardedDrizzleLive(args.build, args.deps ?? [], {\n ...(args.ready != null ? { ready: args.ready } : {}),\n ...(args.use ? { use: args.use } : {}),\n });\n }\n\n function useLiveQueryRawRow<TRows extends readonly unknown[]>(args: {\n use?: readonly SyncTableName<TRegistry>[];\n build: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>;\n deps?: DependencyList;\n ready?: boolean;\n }): { row: TRows[number] | null; loading: boolean; hydrating: boolean; error: Error | null } {\n const { rows, loading, hydrating, error } = useLiveQueryRaw(args);\n return { row: rows[0] ?? null, loading, hydrating, error };\n }\n\n return {\n SyncClientProvider,\n useSyncClient,\n useLiveRows,\n useLiveRow,\n useLiveDrizzleRows,\n useLiveDrizzleRow,\n useLiveQue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AO,KAAK,QAAQ,CAAC,GAAG;GACxD,GAAI,KAAK,SAAS,OAAO,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;GAClD,GAAI,KAAK,MAAM,EAAE,KAAK,KAAK,IAAI,IAAI,CAAC;EACtC,CAAC;CACH;CAEA,SAAS,mBAAqD,MAK+B;EAC3F,MAAM,EAAE,MAAM,SAAS,WAAW,UAAU,gBAAgB,IAAI;EAChE,OAAO;GAAE,KAAK,KAAK,MAAM;GAAM;GAAS;GAAW;EAAM;CAC3D;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pgxsinkit/react",
3
- "version": "0.1.41",
3
+ "version": "0.1.48",
4
4
  "keywords": [
5
5
  "tanstack-intent"
6
6
  ],
@@ -27,8 +27,8 @@
27
27
  "build": "bun --cwd ../.. run build:public-packages"
28
28
  },
29
29
  "dependencies": {
30
- "@pgxsinkit/client": "0.1.41",
31
- "@pgxsinkit/contracts": "0.1.41"
30
+ "@pgxsinkit/client": "0.1.48",
31
+ "@pgxsinkit/contracts": "0.1.48"
32
32
  },
33
33
  "peerDependencies": {
34
34
  "@electric-sql/pglite": "0.5.4",
@@ -5,14 +5,18 @@ description: >-
5
5
  (useLiveRows, useLiveRow, useLiveDrizzleRows, useLiveDrizzleRow) plus SyncClientProvider /
6
6
  useSyncClient. Teaches that live reads are event-driven off PGlite's live.query (they fire on commit,
7
7
  not on a poll), that useLiveDrizzleRows remaps snake_case columns back to the builder's field keys
8
- while raw useLiveRows returns underlying column names, the { rows, loading, error } contract, and that
9
- writes go through client.tables.<t> (not the hooks) and flush on enqueue. Load before building React
10
- components that read or write synced data.
8
+ while raw useLiveRows returns underlying column names, the { rows, loading, error } contract (the
9
+ Drizzle hooks add a hydrating flag that stays true until every referenced consistency group — eager or
10
+ lazy — has caught up and delivered its rows, so empty is distinguishable from still-synchronizing), that
11
+ authenticated lazy groups must be gated until claims exist (ordinary writes self-activate their group,
12
+ so gate the write on auth rather than mounting an activator), and that writes go through
13
+ client.tables.<t> (not the hooks) and flush on enqueue. Load before building React components that read
14
+ or write synced data.
11
15
  metadata:
12
16
  type: framework
13
17
  framework: react
14
18
  library: "@pgxsinkit/react"
15
- library_version: "0.1.41"
19
+ library_version: "0.1.48"
16
20
  source: https://pgxsinkit.github.io/
17
21
  requires:
18
22
  - react
@@ -40,6 +44,55 @@ query re-runs and the hook re-renders — **on commit, not on an interval**. Do
40
44
  Every read hook returns `{ rows, loading, error }` (singular variants return `{ row, ... }`). Pass
41
45
  `ready: false` to defer a query until a dependency is available.
42
46
 
47
+ ### `hydrating` — distinguish "still synchronizing" from "genuinely empty"
48
+
49
+ The Drizzle hooks (`useLiveDrizzleRows`/`useLiveDrizzleRow`/`useLiveQueryRaw`/`useLiveQueryRawRow`) add a
50
+ `hydrating` boolean. It is `true` from mount until **every** consistency group the query reads — eager
51
+ **or** lazy — has completed its initial catch-up and the caught-up rows have been delivered to the
52
+ subscription. Cached/local rows paint immediately while `hydrating` is `true` (the subscription registers
53
+ without waiting on the network), and the signal is rows-before-catch-up: it never flips to `false` before
54
+ the freshly caught-up rows have landed, so it can never flash a false "empty".
55
+
56
+ This is uniform across eager and lazy relations — an eager relation still catching up on a cold boot is
57
+ covered too, not just lazy relations. Steady-state subscriptions (every referenced group already caught up
58
+ at mount) are unaffected: `hydrating` clears at the first snapshot with no extra work. Render an empty
59
+ state only when `!loading && !hydrating` — zero rows before that means "not loaded yet", not "empty":
60
+
61
+ ```tsx
62
+ const { rows, loading, hydrating } = useLiveDrizzleRows((c) => c.drizzle.select().from(c.views.todos), []);
63
+ if (loading || hydrating) return <Spinner />;
64
+ if (rows.length === 0) return <EmptyState />;
65
+ ```
66
+
67
+ ## Gate authenticated lazy groups until the session exists
68
+
69
+ A live query that references one `subscription: "lazy"` relation activates its **whole consistency
70
+ group**. The first shape request uses the claims available at that moment. If the group's row filters
71
+ return `DENY_ALL` without a user claim, mounting the query while auth is unresolved starts an anonymous,
72
+ empty subscription; a later auth notification then has to rotate/refetch the shape.
73
+
74
+ Use the hook's `ready` option to make first activation coincide with the authenticated session:
75
+
76
+ ```tsx
77
+ const workflowView = registry.workflow.view!;
78
+
79
+ useLiveDrizzleRows((client) => client.drizzle.select({ id: workflowView.id }).from(workflowView), [], {
80
+ ready: session != null,
81
+ });
82
+ ```
83
+
84
+ You no longer need a separate activator component for writes. An ordinary optimistic create/update/delete
85
+ self-activates its target's lazy group at enqueue, so the Postgres commit echoes back through Electric and
86
+ retires the acknowledged journal row on its own. But that write-triggered activation still uses the claims
87
+ available at the time, so gate the **write** on auth the same way — do not write to an authenticated-only
88
+ group before the session exists. (`updateBlind` is different: it has no overlay, does not activate its
89
+ group, and deliberately retires on the authoritative ack without an echo.) Activating a claims-denied group
90
+ with no token — by read or by write — now logs a `console.warn` naming the group.
91
+
92
+ If anonymous access is valid, gate on **auth resolution** rather than `session != null`, then call
93
+ `client.notifyAuthChanged()` whenever the known session changes. The rule is not "always require a user";
94
+ it is "do not activate a claims-dependent lazy group with unresolved claims."
95
+
43
96
  ## Prefer `useLiveDrizzleRows` for typed, correctly-keyed rows
44
97
 
45
98
  PGlite returns rows keyed by the underlying **snake_case** column names. `useLiveDrizzleRows` takes a
@@ -70,5 +123,8 @@ cadence and the `globalThis.__pgxsinkitDebug` latency instrumentation.
70
123
  saturates the single WASM thread.
71
124
  - Mutating local tables directly instead of through `client.tables.<t>` (the one write path).
72
125
  - Reading before the client is ready instead of gating with `ready: false`.
126
+ - Reading OR writing an authenticated lazy group before auth resolves — it activates against anonymous
127
+ claims (now flagged by a console warning) and the shape stays empty until a later rotation/refetch. Gate
128
+ on the session, not on a manual activator (writes self-activate their group).
73
129
 
74
130
  Reference: <https://pgxsinkit.github.io/>.
@@ -18,7 +18,15 @@ interface DrizzleSqlBuilder<TRows extends readonly unknown[]> extends PromiseLik
18
18
  readonly _?: { readonly selectedFields?: SelectedFields };
19
19
  }
20
20
 
21
- /** Reactive read result. `hydrating` is true while a lazy relation the query reads is being activated. */
21
+ /**
22
+ * Reactive read result. `hydrating` is true from mount until every consistency group the query reads —
23
+ * eager OR lazy — has completed its initial catch-up (`client.groupReady`) and the caught-up rows have
24
+ * been delivered to this subscription, not merely started its stream. Rows flow while it is true
25
+ * (local/cached rows paint immediately; catch-up rows stream in), so render an empty state only when
26
+ * `!loading && !hydrating` — zero rows before that means "not loaded yet", not "empty". A subscription
27
+ * whose groups are all already caught up at mount (the steady-state fast path) clears `hydrating` at the
28
+ * first snapshot with no extra work.
29
+ */
22
30
  interface LiveRowsState<TRows> {
23
31
  rows: TRows;
24
32
  loading: boolean;
@@ -228,22 +236,29 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
228
236
 
229
237
  setState((prev) => ({ rows: prev.rows, loading: true, hydrating: true, error: null }));
230
238
 
231
- // Scan the compiled SQL for the lazy relations the query reads (∪ `use`), activate + hydrate them,
232
- // THEN subscribe via the client's live-rows seam — so a query is never registered against an
233
- // un-hydrated lazy relation (ADR-0021), and the same hook drives both the in-process client (seam over
234
- // `pglite.live`) and the worker-attached client (seam over the bridge, ADR-0032 S2 §4).
239
+ // Scan the compiled SQL for the lazy relations the query reads (∪ `use`), ACTIVATE them (streams
240
+ // started, tripwire satisfied), THEN subscribe via the client's live-rows seam — so a query is never
241
+ // registered against a dormant lazy relation (ADR-0021), and the same hook drives both the in-process
242
+ // client (seam over `pglite.live`) and the worker-attached client (seam over the bridge, ADR-0032 S2 §4).
243
+ // Activation is NOT catch-up: the subscription registers immediately (local/cached rows paint, and an
244
+ // offline client is never blocked behind the network), while `hydrating` stays true until the
245
+ // subscription's `hydrated` promise resolves. That promise now spans EVERY referenced consistency
246
+ // group (eager AND lazy) still catching up — not just the lazy ones — so a cold boot's eager catch-up
247
+ // is covered too; when every referenced group is already ready at subscribe time the seam builds no
248
+ // promise and `hydrating` clears at the first snapshot. The seam guarantees rows-before-signal (it
249
+ // refreshes the live query against the caught-up store before resolving), so clearing `hydrating`
250
+ // here can never present zero rows as "empty" while the catch-up rows are still in flight.
235
251
  void contextClient
236
252
  .prepareQuery({ sql: sql.sql, ...(useList ? { use: useList } : {}) })
237
253
  .then(() => {
238
254
  if (!active) return undefined;
239
- setState((prev) => ({ rows: prev.rows, loading: true, hydrating: false, error: null }));
240
255
  return contextClient
241
256
  .subscribeLiveRows<Record<string, unknown>>(
242
257
  { sql: sql.sql, params: sql.params, ...(fields ? { fields } : {}), ...(useList ? { use: useList } : {}) },
243
258
  (rows) => {
244
259
  if (active) {
245
260
  syncDebug("live query updated → re-render", { rows: rows.length });
246
- setState({ rows: mapRows(rows), loading: false, hydrating: false, error: null });
261
+ setState((prev) => ({ rows: mapRows(rows), loading: false, hydrating: prev.hydrating, error: null }));
247
262
  }
248
263
  },
249
264
  )
@@ -253,7 +268,17 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
253
268
  return undefined;
254
269
  }
255
270
  subscription = registered;
256
- setState({ rows: mapRows(registered.initialRows), loading: false, hydrating: false, error: null });
271
+ setState((prev) => ({
272
+ rows: mapRows(registered.initialRows),
273
+ loading: false,
274
+ hydrating: registered.hydrated != null ? prev.hydrating : false,
275
+ error: null,
276
+ }));
277
+ if (registered.hydrated) {
278
+ void registered.hydrated.then(() => {
279
+ if (active) setState((prev) => ({ ...prev, hydrating: false }));
280
+ });
281
+ }
257
282
  return undefined;
258
283
  });
259
284
  })