@lunora/replica 1.0.0-alpha.9 → 1.0.0-alpha.91
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +214 -0
- package/README.md +55 -10
- package/dist/adapters/better-sqlite3.d.mts +2 -1
- package/dist/adapters/better-sqlite3.d.ts +2 -1
- package/dist/adapters/better-sqlite3.mjs +1 -29
- package/dist/adapters/sqlite-wasm.d.mts +3 -9
- package/dist/adapters/sqlite-wasm.d.ts +3 -9
- package/dist/adapters/sqlite-wasm.mjs +1 -44
- package/dist/adapters/sqljs.d.mts +4 -2
- package/dist/adapters/sqljs.d.ts +4 -2
- package/dist/adapters/sqljs.mjs +1 -55
- package/dist/index.d.mts +158 -55
- package/dist/index.d.ts +158 -55
- package/dist/index.mjs +1 -20
- package/dist/packem_shared/EventEmitter-uo75adUL.mjs +1 -0
- package/dist/packem_shared/EventLog-SuC_BKwj.mjs +1 -0
- package/dist/packem_shared/EventLogDO-BgUx2GGL.mjs +1 -0
- package/dist/packem_shared/EventLogDOClient-DWerZ3_n.mjs +1 -0
- package/dist/packem_shared/EventSource-Bg6zNmRn.mjs +1 -0
- package/dist/packem_shared/EventsSync-B3wzXm-b.mjs +1 -0
- package/dist/packem_shared/InMemorySnapshotStore-C4taIG5K.mjs +1 -0
- package/dist/packem_shared/LocalMirror-Bn22hyEB.mjs +4 -0
- package/dist/packem_shared/MaterializerRuntime-DFXi-aqd.mjs +1 -0
- package/dist/packem_shared/SubscriptionManager-AhPw3lFc.mjs +1 -0
- package/dist/packem_shared/applyDiff-CZAqAC8Y.mjs +1 -0
- package/dist/packem_shared/applyDiffToDb-CK-Dcy17.mjs +1 -0
- package/dist/packem_shared/classifyChanges-BBc0-770.mjs +1 -0
- package/dist/packem_shared/defineEvents-DHo-VK7G.mjs +1 -0
- package/dist/packem_shared/eventsContext-Dxow9Y7S.mjs +1 -0
- package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
- package/dist/packem_shared/int64-CCVxepl4.mjs +1 -0
- package/dist/packem_shared/isClientSeq-D2Xm0_lj.mjs +1 -0
- package/dist/packem_shared/{local-mirror.d-DTavX_y0.d.mts → local-mirror.d-DzREvGNM.d.mts} +54 -22
- package/dist/packem_shared/{local-mirror.d-CyGOpUES.d.ts → local-mirror.d-wbGXkXaE.d.ts} +54 -22
- package/dist/packem_shared/subscribeToMirror-DSn8n1IR.mjs +1 -0
- package/dist/packem_shared/{types.d-CkMkSwLJ.d.mts → types.d-BuLTPLaQ.d.mts} +0 -2
- package/dist/packem_shared/{types.d-CkMkSwLJ.d.ts → types.d-BuLTPLaQ.d.ts} +0 -2
- package/dist/packem_shared/wire-key-DfMHAtqH.mjs +1 -0
- package/dist/react.d.mts +39 -29
- package/dist/react.d.ts +39 -29
- package/dist/react.mjs +1 -15
- package/package.json +1 -1
- package/dist/packem_shared/EventEmitter-CMZfct03.mjs +0 -92
- package/dist/packem_shared/EventLog-CnK-3Wge.mjs +0 -264
- package/dist/packem_shared/EventLogDO-DIJWdi7n.mjs +0 -382
- package/dist/packem_shared/EventLogDOClient-F4FO8Si4.mjs +0 -92
- package/dist/packem_shared/EventSource-D5yO9_aI.mjs +0 -221
- package/dist/packem_shared/EventsSync-BP36tC9O.mjs +0 -123
- package/dist/packem_shared/InMemorySnapshotStore-BHVAD-Bp.mjs +0 -24
- package/dist/packem_shared/LocalMirror-a-5jEqFN.mjs +0 -219
- package/dist/packem_shared/MaterializerRuntime-BoIrsMYB.mjs +0 -224
- package/dist/packem_shared/SubscriptionManager-C5xbw0pg.mjs +0 -75
- package/dist/packem_shared/applyDiff-Ctu04rYc.mjs +0 -88
- package/dist/packem_shared/applyDiffToDb-DQ1xZp5J.mjs +0 -58
- package/dist/packem_shared/classifyChanges-RcqLBpLs.mjs +0 -41
- package/dist/packem_shared/defineEvents-DiBkPTh_.mjs +0 -28
- package/dist/packem_shared/eventsContext-Bk_p48hj.mjs +0 -6
- package/dist/packem_shared/isClientSeq-C46BkzqJ.mjs +0 -5
- package/dist/packem_shared/subscribeToMirror-CiaM-nQ7.mjs +0 -45
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as SqliteAdapter } from "./types.d-
|
|
1
|
+
import { S as SqliteAdapter } from "./types.d-BuLTPLaQ.mjs";
|
|
2
2
|
/**
|
|
3
3
|
* Row-level change kind within a TableDiff.
|
|
4
4
|
*
|
|
@@ -31,13 +31,14 @@ interface TableDiff {
|
|
|
31
31
|
/**
|
|
32
32
|
* Optional stable identity for this diff, distinct from `timestamp`
|
|
33
33
|
* (multiple diffs can legitimately share a millisecond, so `timestamp`
|
|
34
|
-
* alone is not a unique diff identity).
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
34
|
+
* alone is not a unique diff identity). `createTableDiff` auto-generates
|
|
35
|
+
* one when omitted.
|
|
36
|
+
*
|
|
37
|
+
* **Nothing in the apply path reads it.** `deriveInsertId` (`apply-diff.ts`)
|
|
38
|
+
* keys an id-less insert off the ROW'S OWN content — hashing the diff id
|
|
39
|
+
* into it is what made `subscribeToMirror`'s per-frame re-emission mint a
|
|
40
|
+
* fresh row every second, so that derivation is gone. This field is
|
|
41
|
+
* carried for consumers that want to recognise a diff they have seen.
|
|
41
42
|
*/
|
|
42
43
|
readonly id?: string;
|
|
43
44
|
/** Logical table name (matches the schema table name). */
|
|
@@ -140,7 +141,7 @@ declare const isClientSeq: (seq: Seq) => seq is ClientSeq;
|
|
|
140
141
|
*
|
|
141
142
|
* ```ts
|
|
142
143
|
* const event = events.chat.messageSent({ channelId: "c1", text: "hello" });
|
|
143
|
-
* // event: InputEvent
|
|
144
|
+
* // event: InputEvent<"chat.messageSent", { channelId: string; text: string }>
|
|
144
145
|
* ```
|
|
145
146
|
* @experimental
|
|
146
147
|
*/
|
|
@@ -312,6 +313,11 @@ declare class EventLog {
|
|
|
312
313
|
getSince(sinceSeq: number): ReadonlyArray<EventLogEntry>;
|
|
313
314
|
/**
|
|
314
315
|
* Paginated read starting at `fromSeq`.
|
|
316
|
+
*
|
|
317
|
+
* `limit` must be a positive safe integer, validated like
|
|
318
|
+
* {@link EventLog#truncateBelow}'s floor and the constructor's `maxEntries`:
|
|
319
|
+
* a `limit` of `0` returned an empty page with `hasMore: true`, which spins a
|
|
320
|
+
* paginating caller forever on a page it can never advance past.
|
|
315
321
|
* @returns `{ entries, hasMore }` where `hasMore` is `true` when more
|
|
316
322
|
* entries exist beyond the requested page.
|
|
317
323
|
*/
|
|
@@ -381,15 +387,18 @@ interface LocalMirrorOptions {
|
|
|
381
387
|
/** Platform-specific SQLite adapter. */
|
|
382
388
|
readonly db: SqliteAdapter;
|
|
383
389
|
/**
|
|
384
|
-
* Cap the mirror's internal {@link EventLog} to this many entries
|
|
385
|
-
*
|
|
386
|
-
*
|
|
390
|
+
* Cap the mirror's internal {@link EventLog} to this many entries.
|
|
391
|
+
* Every applied diff is recorded in the log, so an uncapped log grows by
|
|
392
|
+
* one entry (holding every changed row) per diff for the life of the
|
|
393
|
+
* mirror — a leak by construction on a long-lived client.
|
|
387
394
|
*
|
|
388
|
-
*
|
|
389
|
-
*
|
|
390
|
-
*
|
|
391
|
-
*
|
|
392
|
-
* a
|
|
395
|
+
* Defaults to {@link DEFAULT_MAX_EVENT_LOG_ENTRIES}. On overflow the
|
|
396
|
+
* OLDEST entries are dropped; nothing in the mirror replays its own log,
|
|
397
|
+
* so a drop loses nothing the mirror needs. A consumer that does replay
|
|
398
|
+
* it (`eventLog.getSince(watermark)` from another tab / service worker)
|
|
399
|
+
* detects a gap when the first returned entry's `seq` is above its
|
|
400
|
+
* watermark, and should re-seed from the mirror's rows (`query`) instead
|
|
401
|
+
* of applying the partial window.
|
|
393
402
|
*/
|
|
394
403
|
readonly maxEventLogEntries?: number;
|
|
395
404
|
/**
|
|
@@ -402,6 +411,15 @@ interface LocalMirrorOptions {
|
|
|
402
411
|
*/
|
|
403
412
|
readonly tables?: Record<string, MirrorTableDef>;
|
|
404
413
|
}
|
|
414
|
+
/**
|
|
415
|
+
* Why the mirror changed: `"diff"` for the rows an {@link LocalMirror.applyDiff}
|
|
416
|
+
* wrote, `"clear"` for the wholesale {@link LocalMirror.clearData} sweep.
|
|
417
|
+
*
|
|
418
|
+
* A subscriber that caches what it believes the mirror holds has to tell the two
|
|
419
|
+
* apart: `"diff"` reports a change it usually made itself, while `"clear"` means
|
|
420
|
+
* every row it was tracking is gone regardless of who wrote it.
|
|
421
|
+
*/
|
|
422
|
+
type MirrorChangeReason = "clear" | "diff";
|
|
405
423
|
/**
|
|
406
424
|
* Local SQLite mirror that maintains a client-side replica of server
|
|
407
425
|
* tables by applying {@link TableDiff} deltas.
|
|
@@ -420,13 +438,13 @@ interface LocalMirrorOptions {
|
|
|
420
438
|
* mirror.applyDiff(someDiff);
|
|
421
439
|
*
|
|
422
440
|
* // Query locally:
|
|
423
|
-
* const rows = mirror.query
|
|
441
|
+
* const rows = mirror.query<{ id: string; name: string }>(
|
|
424
442
|
* "SELECT id, name FROM users WHERE name LIKE ?",
|
|
425
443
|
* ["alice%"],
|
|
426
444
|
* );
|
|
427
445
|
* ```
|
|
428
446
|
*/
|
|
429
|
-
type ChangeSubscriber = () => void;
|
|
447
|
+
type ChangeSubscriber = (reason: MirrorChangeReason) => void;
|
|
430
448
|
/**
|
|
431
449
|
* `LocalMirror` is part of the experimental `@lunora/replica` API and may change without a major version bump.
|
|
432
450
|
* @experimental
|
|
@@ -504,8 +522,17 @@ declare class LocalMirror {
|
|
|
504
522
|
*/
|
|
505
523
|
query<T = Record<string, unknown>>(sql: string, params?: ReadonlyArray<unknown>): T[];
|
|
506
524
|
/**
|
|
507
|
-
* Delete every row from
|
|
508
|
-
* and schema). Useful when re-syncing from scratch.
|
|
525
|
+
* Delete every row from every data table in the adapter's database
|
|
526
|
+
* (preserves the event log and schema). Useful when re-syncing from scratch.
|
|
527
|
+
*
|
|
528
|
+
* **The mirror owns its database.** The sweep is `sqlite_master` minus the
|
|
529
|
+
* reserved prefixes, NOT {@link LocalMirror.mirroredTables} — a table this
|
|
530
|
+
* mirror never registered is cleared too, and `#reconcileSchemaVersion`
|
|
531
|
+
* DROPs on the same list. It cannot be narrowed to the registered set: that
|
|
532
|
+
* runs from the constructor, before any `applyDiff` has re-registered the
|
|
533
|
+
* tables a previous session persisted, and those are exactly the
|
|
534
|
+
* stale-schema tables it exists to drop. So hand the adapter a database
|
|
535
|
+
* dedicated to the mirror, never one that also holds your own tables.
|
|
509
536
|
*
|
|
510
537
|
* Notifies `onChange` subscribers and bumps {@link LocalMirror.version}
|
|
511
538
|
* (REPLICA-09) even though nothing is appended to the event log — a
|
|
@@ -519,9 +546,14 @@ declare class LocalMirror {
|
|
|
519
546
|
close(): void;
|
|
520
547
|
/**
|
|
521
548
|
* Register a table schema so the mirror can create the table on
|
|
522
|
-
* first use.
|
|
549
|
+
* first use. Merges into any definition already registered for `name`
|
|
550
|
+
* (from the constructor's `tables` or an earlier call), so a helper that
|
|
551
|
+
* registers `{}` just to make the table known does not erase a
|
|
552
|
+
* user-supplied `primaryKey`.
|
|
523
553
|
*/
|
|
524
554
|
registerTable(name: string, definition: MirrorTableDef): void;
|
|
555
|
+
/** The primary-key column of a mirrored table (`"id"` unless registered otherwise). */
|
|
556
|
+
primaryKeyOf(table: string): string;
|
|
525
557
|
/**
|
|
526
558
|
* Return the list of mirrored table names.
|
|
527
559
|
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as SqliteAdapter } from "./types.d-
|
|
1
|
+
import { S as SqliteAdapter } from "./types.d-BuLTPLaQ.js";
|
|
2
2
|
/**
|
|
3
3
|
* Row-level change kind within a TableDiff.
|
|
4
4
|
*
|
|
@@ -31,13 +31,14 @@ interface TableDiff {
|
|
|
31
31
|
/**
|
|
32
32
|
* Optional stable identity for this diff, distinct from `timestamp`
|
|
33
33
|
* (multiple diffs can legitimately share a millisecond, so `timestamp`
|
|
34
|
-
* alone is not a unique diff identity).
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
34
|
+
* alone is not a unique diff identity). `createTableDiff` auto-generates
|
|
35
|
+
* one when omitted.
|
|
36
|
+
*
|
|
37
|
+
* **Nothing in the apply path reads it.** `deriveInsertId` (`apply-diff.ts`)
|
|
38
|
+
* keys an id-less insert off the ROW'S OWN content — hashing the diff id
|
|
39
|
+
* into it is what made `subscribeToMirror`'s per-frame re-emission mint a
|
|
40
|
+
* fresh row every second, so that derivation is gone. This field is
|
|
41
|
+
* carried for consumers that want to recognise a diff they have seen.
|
|
41
42
|
*/
|
|
42
43
|
readonly id?: string;
|
|
43
44
|
/** Logical table name (matches the schema table name). */
|
|
@@ -140,7 +141,7 @@ declare const isClientSeq: (seq: Seq) => seq is ClientSeq;
|
|
|
140
141
|
*
|
|
141
142
|
* ```ts
|
|
142
143
|
* const event = events.chat.messageSent({ channelId: "c1", text: "hello" });
|
|
143
|
-
* // event: InputEvent
|
|
144
|
+
* // event: InputEvent<"chat.messageSent", { channelId: string; text: string }>
|
|
144
145
|
* ```
|
|
145
146
|
* @experimental
|
|
146
147
|
*/
|
|
@@ -312,6 +313,11 @@ declare class EventLog {
|
|
|
312
313
|
getSince(sinceSeq: number): ReadonlyArray<EventLogEntry>;
|
|
313
314
|
/**
|
|
314
315
|
* Paginated read starting at `fromSeq`.
|
|
316
|
+
*
|
|
317
|
+
* `limit` must be a positive safe integer, validated like
|
|
318
|
+
* {@link EventLog#truncateBelow}'s floor and the constructor's `maxEntries`:
|
|
319
|
+
* a `limit` of `0` returned an empty page with `hasMore: true`, which spins a
|
|
320
|
+
* paginating caller forever on a page it can never advance past.
|
|
315
321
|
* @returns `{ entries, hasMore }` where `hasMore` is `true` when more
|
|
316
322
|
* entries exist beyond the requested page.
|
|
317
323
|
*/
|
|
@@ -381,15 +387,18 @@ interface LocalMirrorOptions {
|
|
|
381
387
|
/** Platform-specific SQLite adapter. */
|
|
382
388
|
readonly db: SqliteAdapter;
|
|
383
389
|
/**
|
|
384
|
-
* Cap the mirror's internal {@link EventLog} to this many entries
|
|
385
|
-
*
|
|
386
|
-
*
|
|
390
|
+
* Cap the mirror's internal {@link EventLog} to this many entries.
|
|
391
|
+
* Every applied diff is recorded in the log, so an uncapped log grows by
|
|
392
|
+
* one entry (holding every changed row) per diff for the life of the
|
|
393
|
+
* mirror — a leak by construction on a long-lived client.
|
|
387
394
|
*
|
|
388
|
-
*
|
|
389
|
-
*
|
|
390
|
-
*
|
|
391
|
-
*
|
|
392
|
-
* a
|
|
395
|
+
* Defaults to {@link DEFAULT_MAX_EVENT_LOG_ENTRIES}. On overflow the
|
|
396
|
+
* OLDEST entries are dropped; nothing in the mirror replays its own log,
|
|
397
|
+
* so a drop loses nothing the mirror needs. A consumer that does replay
|
|
398
|
+
* it (`eventLog.getSince(watermark)` from another tab / service worker)
|
|
399
|
+
* detects a gap when the first returned entry's `seq` is above its
|
|
400
|
+
* watermark, and should re-seed from the mirror's rows (`query`) instead
|
|
401
|
+
* of applying the partial window.
|
|
393
402
|
*/
|
|
394
403
|
readonly maxEventLogEntries?: number;
|
|
395
404
|
/**
|
|
@@ -402,6 +411,15 @@ interface LocalMirrorOptions {
|
|
|
402
411
|
*/
|
|
403
412
|
readonly tables?: Record<string, MirrorTableDef>;
|
|
404
413
|
}
|
|
414
|
+
/**
|
|
415
|
+
* Why the mirror changed: `"diff"` for the rows an {@link LocalMirror.applyDiff}
|
|
416
|
+
* wrote, `"clear"` for the wholesale {@link LocalMirror.clearData} sweep.
|
|
417
|
+
*
|
|
418
|
+
* A subscriber that caches what it believes the mirror holds has to tell the two
|
|
419
|
+
* apart: `"diff"` reports a change it usually made itself, while `"clear"` means
|
|
420
|
+
* every row it was tracking is gone regardless of who wrote it.
|
|
421
|
+
*/
|
|
422
|
+
type MirrorChangeReason = "clear" | "diff";
|
|
405
423
|
/**
|
|
406
424
|
* Local SQLite mirror that maintains a client-side replica of server
|
|
407
425
|
* tables by applying {@link TableDiff} deltas.
|
|
@@ -420,13 +438,13 @@ interface LocalMirrorOptions {
|
|
|
420
438
|
* mirror.applyDiff(someDiff);
|
|
421
439
|
*
|
|
422
440
|
* // Query locally:
|
|
423
|
-
* const rows = mirror.query
|
|
441
|
+
* const rows = mirror.query<{ id: string; name: string }>(
|
|
424
442
|
* "SELECT id, name FROM users WHERE name LIKE ?",
|
|
425
443
|
* ["alice%"],
|
|
426
444
|
* );
|
|
427
445
|
* ```
|
|
428
446
|
*/
|
|
429
|
-
type ChangeSubscriber = () => void;
|
|
447
|
+
type ChangeSubscriber = (reason: MirrorChangeReason) => void;
|
|
430
448
|
/**
|
|
431
449
|
* `LocalMirror` is part of the experimental `@lunora/replica` API and may change without a major version bump.
|
|
432
450
|
* @experimental
|
|
@@ -504,8 +522,17 @@ declare class LocalMirror {
|
|
|
504
522
|
*/
|
|
505
523
|
query<T = Record<string, unknown>>(sql: string, params?: ReadonlyArray<unknown>): T[];
|
|
506
524
|
/**
|
|
507
|
-
* Delete every row from
|
|
508
|
-
* and schema). Useful when re-syncing from scratch.
|
|
525
|
+
* Delete every row from every data table in the adapter's database
|
|
526
|
+
* (preserves the event log and schema). Useful when re-syncing from scratch.
|
|
527
|
+
*
|
|
528
|
+
* **The mirror owns its database.** The sweep is `sqlite_master` minus the
|
|
529
|
+
* reserved prefixes, NOT {@link LocalMirror.mirroredTables} — a table this
|
|
530
|
+
* mirror never registered is cleared too, and `#reconcileSchemaVersion`
|
|
531
|
+
* DROPs on the same list. It cannot be narrowed to the registered set: that
|
|
532
|
+
* runs from the constructor, before any `applyDiff` has re-registered the
|
|
533
|
+
* tables a previous session persisted, and those are exactly the
|
|
534
|
+
* stale-schema tables it exists to drop. So hand the adapter a database
|
|
535
|
+
* dedicated to the mirror, never one that also holds your own tables.
|
|
509
536
|
*
|
|
510
537
|
* Notifies `onChange` subscribers and bumps {@link LocalMirror.version}
|
|
511
538
|
* (REPLICA-09) even though nothing is appended to the event log — a
|
|
@@ -519,9 +546,14 @@ declare class LocalMirror {
|
|
|
519
546
|
close(): void;
|
|
520
547
|
/**
|
|
521
548
|
* Register a table schema so the mirror can create the table on
|
|
522
|
-
* first use.
|
|
549
|
+
* first use. Merges into any definition already registered for `name`
|
|
550
|
+
* (from the constructor's `tables` or an earlier call), so a helper that
|
|
551
|
+
* registers `{}` just to make the table known does not erase a
|
|
552
|
+
* user-supplied `primaryKey`.
|
|
523
553
|
*/
|
|
524
554
|
registerTable(name: string, definition: MirrorTableDef): void;
|
|
555
|
+
/** The primary-key column of a mirrored table (`"id"` unless registered otherwise). */
|
|
556
|
+
primaryKeyOf(table: string): string;
|
|
525
557
|
/**
|
|
526
558
|
* Return the list of mirrored table names.
|
|
527
559
|
*/
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{s as A}from"./wire-key-DfMHAtqH.mjs";const _=e=>`fn_${e.replaceAll(/[/:.]/g,"_")}`,k=e=>Array.isArray(e)?e:e!==null&&typeof e=="object"?[e]:[],x=(e,o,l,y,g)=>{const a=_(l.__lunoraRef);o.registerTable(a,{});const d=o.primaryKeyOf(a);let r=new Map,f=0;const w=o.onChange(p=>{p==="clear"&&(f+=1,r=new Map)}),h=e.subscribe(l,y,p=>{const M=f,c=new Map,b=new Map,s=[];for(const t of k(p)){const n=t,i=n[d];if(typeof i!="string"&&typeof i!="number"&&typeof i!="bigint"){s.push({type:"insert",data:n});continue}const u=String(i),m=A(n);c.set(u,m),b.set(u,n)}for(const[t,n]of c)r.get(t)!==n&&s.push({data:b.get(t),type:"insert"});for(const t of r.keys())c.has(t)||s.push({type:"delete",id:t});s.length>0&&o.applyDiff({table:a,changes:s,timestamp:Date.now()}),M===f&&(r=c)},{shardKey:g});return()=>{w(),h()}};export{x as subscribeToMirror};
|
|
@@ -11,8 +11,6 @@ interface SqliteAdapter {
|
|
|
11
11
|
close: () => void;
|
|
12
12
|
/** Execute a SQL statement (with optional bound params). */
|
|
13
13
|
exec: (sql: string, params?: ReadonlyArray<unknown>) => void;
|
|
14
|
-
/** Return the id of the last inserted row. */
|
|
15
|
-
lastInsertRowId: () => number;
|
|
16
14
|
/**
|
|
17
15
|
* Execute a SQL statement and return the result rows.
|
|
18
16
|
* Columns can be accessed by index or by name.
|
|
@@ -11,8 +11,6 @@ interface SqliteAdapter {
|
|
|
11
11
|
close: () => void;
|
|
12
12
|
/** Execute a SQL statement (with optional bound params). */
|
|
13
13
|
exec: (sql: string, params?: ReadonlyArray<unknown>) => void;
|
|
14
|
-
/** Return the id of the last inserted row. */
|
|
15
|
-
lastInsertRowId: () => number;
|
|
16
14
|
/**
|
|
17
15
|
* Execute a SQL statement and return the result rows.
|
|
18
16
|
* Columns can be accessed by index or by name.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const m=/["\\\u0000-\u001F\uD800-\uDFFF]/,d=r=>m.test(r)?JSON.stringify(r):`"${r}"`,b=r=>{if(r===void 0)return"null";if(typeof r=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof r=="number"){if(Number.isNaN(r))return"nan";if(r===1/0)return"inf";if(r===-1/0)return"-inf";if(Object.is(r,-0))return"-0"}if(typeof r=="string")return d(r);if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r)){let e="[";for(let i=0;i<r.length;i++)i>0&&(e+=","),e+=b(r[i]);return e+"]"}const n=Object.getPrototypeOf(r);if(n!==null&&n!==Object.prototype){const e=r.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${e} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const y=r,s=Object.keys(y).sort();let f="{",t=!0;for(const e of s){const i=y[e];i!==void 0&&(t?t=!1:f+=",",f+=d(e),f+=":",f+=b(i))}return f+"}"},u=r=>{let n="";for(let s=0;s<r.length;s+=32768)n+=String.fromCharCode(...r.subarray(s,s+32768));return btoa(n)},o="$lunora.wire$";const g="__proto__",w=r=>{if(r===null||typeof r!="object")return!1;const n=Object.getPrototypeOf(r);return n===null||n===Object.prototype},c=(r,n=0)=>{if(n>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(r===void 0)return[o,"undefined"];if(r===null)return null;const y=typeof r;if(y==="bigint")return[o,"bigint",r.toString()];if(y==="number"){const t=r;return Number.isNaN(t)?[o,"nan"]:t===1/0?[o,"inf"]:t===-1/0?[o,"-inf"]:t}if(y!=="object")return r;if(r instanceof Date)return[o,"date",c(r.getTime(),n+1)];if(r instanceof Error){const t=r,e={};for(const a of Object.keys(t)){if(t[a]===void 0)continue;const p=c(t[a],n+1);a===g?Object.defineProperty(e,a,{configurable:!0,enumerable:!0,value:p,writable:!0}):e[a]=p}const i=[o,"error",String(t.name),String(t.message),e];return t.cause!==void 0&&i.push(c(t.cause,n+1)),i}if(r instanceof URL)return[o,"url",r.href];if(r instanceof Map)return[o,"map",[...r.entries()].map(([t,e])=>[c(t,n+1),c(e,n+1)])];if(r instanceof Set)return[o,"set",[...r].map(t=>c(t,n+1))];if(r instanceof ArrayBuffer)return[o,"bytes",u(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const t=r,e=t.constructor.name,i=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return e==="Uint8Array"?[o,"bytes",u(i)]:[o,"bytes",u(i),e]}if(Array.isArray(r)){const t=r.map(e=>c(e,n+1));return t.length>0&&t[0]===o?[o,"arr",t]:t}if(!w(r)){const t=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${t} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const s=r,f={};for(const t of Object.keys(s)){const e=s[t];if(e===void 0)continue;const i=c(e,n+1);t===g?Object.defineProperty(f,t,{configurable:!0,enumerable:!0,value:i,writable:!0}):f[t]=i}return f},O=r=>b(c(r));export{O as s};
|
package/dist/react.d.mts
CHANGED
|
@@ -1,26 +1,36 @@
|
|
|
1
|
-
import { L as LocalMirror } from "./packem_shared/local-mirror.d-
|
|
2
|
-
import "./packem_shared/types.d-
|
|
1
|
+
import { L as LocalMirror } from "./packem_shared/local-mirror.d-DzREvGNM.mjs";
|
|
2
|
+
import "./packem_shared/types.d-BuLTPLaQ.mjs";
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
4
|
+
* Result of {@link useLocalQuery} — a discriminated union so callers get a
|
|
5
|
+
* typed error instead of a swallowed `undefined`.
|
|
5
6
|
* @experimental
|
|
6
7
|
*/
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
* argument.
|
|
15
|
-
*/
|
|
16
|
-
shardKey?: string;
|
|
17
|
-
}
|
|
8
|
+
type LocalQueryResult<T> = {
|
|
9
|
+
readonly data: T[];
|
|
10
|
+
readonly error?: undefined;
|
|
11
|
+
} | {
|
|
12
|
+
readonly data?: undefined;
|
|
13
|
+
readonly error: Error;
|
|
14
|
+
};
|
|
18
15
|
/**
|
|
19
16
|
* React hook that subscribes to a local SQLite query and returns
|
|
20
17
|
* live-updating results whenever the mirror applies a diff.
|
|
21
18
|
*
|
|
22
|
-
* Uses `useSyncExternalStore`
|
|
23
|
-
*
|
|
19
|
+
* Uses `useSyncExternalStore` with `getSnapshot` reading {@link LocalMirror.version}
|
|
20
|
+
* — a plain number, unconditionally `Object.is`-stable across calls with no
|
|
21
|
+
* mutation in between. The actual query runs in a `useMemo` keyed on
|
|
22
|
+
* `[mirror, version, sql, stableParamsKey(params)]`, so it only re-executes
|
|
23
|
+
* when the mirror actually advances (or `sql`/`params` change) — not on
|
|
24
|
+
* every unrelated re-render.
|
|
25
|
+
*
|
|
26
|
+
* This intentionally does NOT cache query results inside {@link LocalMirror}
|
|
27
|
+
* itself: an LRU-capped cache in the mirror core evicts still-mounted hooks'
|
|
28
|
+
* entries once more than the cap's worth of distinct live queries are open
|
|
29
|
+
* on one mirror, which makes `getSnapshot` return a fresh (non-identical)
|
|
30
|
+
* object on the next read — `useSyncExternalStore` then force-re-renders,
|
|
31
|
+
* re-inserts, evicts another entry, and so on without bound. Keying the
|
|
32
|
+
* external-store snapshot on the version primitive instead of a cached
|
|
33
|
+
* query result has no such cap, so it can't loop.
|
|
24
34
|
*
|
|
25
35
|
* The hook works with React 18+ concurrent features, Suspense, and
|
|
26
36
|
* server-side rendering. During SSR the same value is returned as on
|
|
@@ -32,28 +42,28 @@ interface UseLocalQueryOptions {
|
|
|
32
42
|
* engine without rewriting).
|
|
33
43
|
* @param params Optional positional bound parameters matching `?`
|
|
34
44
|
* placeholders in `sql`.
|
|
35
|
-
* @
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
* **Error handling**: The hook catches SQL errors internally and returns
|
|
43
|
-
* `undefined`. Use a try-catch around `mirror.query(...)` directly if you
|
|
44
|
-
* need finer-grained error diagnostics.
|
|
45
|
+
* @returns `{ data }` with the result rows typed via the generic parameter
|
|
46
|
+
* `T`, or `{ error }` when the query fails (e.g. malformed SQL, or the
|
|
47
|
+
* target table doesn't exist yet because no matching diff has been applied
|
|
48
|
+
* — that specific case surfaces as a "no such table" `Error`). Never
|
|
49
|
+
* collapses a failure to `undefined` — check `error` explicitly rather than
|
|
50
|
+
* treating a missing `data` as "still loading".
|
|
45
51
|
* @example
|
|
46
52
|
* ```tsx
|
|
47
53
|
* import { useLocalQuery } from "@lunora/replica/react";
|
|
48
54
|
* import { mirror } from "./mirror";
|
|
49
55
|
*
|
|
50
56
|
* function UserList() {
|
|
51
|
-
* const users = useLocalQuery<{ id: string; name: string }>(
|
|
57
|
+
* const { data: users, error } = useLocalQuery<{ id: string; name: string }>(
|
|
52
58
|
* mirror,
|
|
53
59
|
* "SELECT id, name FROM fn_todos_list WHERE name LIKE ?",
|
|
54
60
|
* ["%alice%"],
|
|
55
61
|
* );
|
|
56
62
|
*
|
|
63
|
+
* if (error) {
|
|
64
|
+
* return <p>Query failed: {error.message}</p>;
|
|
65
|
+
* }
|
|
66
|
+
*
|
|
57
67
|
* if (users === undefined) {
|
|
58
68
|
* return <p>Waiting for data…</p>;
|
|
59
69
|
* }
|
|
@@ -63,5 +73,5 @@ interface UseLocalQueryOptions {
|
|
|
63
73
|
* ```
|
|
64
74
|
* @experimental
|
|
65
75
|
*/
|
|
66
|
-
declare const useLocalQuery: <T = Record<string, unknown>>(mirror: LocalMirror, sql: string, params?: ReadonlyArray<unknown
|
|
67
|
-
export {
|
|
76
|
+
declare const useLocalQuery: <T = Record<string, unknown>>(mirror: LocalMirror, sql: string, params?: ReadonlyArray<unknown>) => LocalQueryResult<T>;
|
|
77
|
+
export { type LocalQueryResult, useLocalQuery };
|
package/dist/react.d.ts
CHANGED
|
@@ -1,26 +1,36 @@
|
|
|
1
|
-
import { L as LocalMirror } from "./packem_shared/local-mirror.d-
|
|
2
|
-
import "./packem_shared/types.d-
|
|
1
|
+
import { L as LocalMirror } from "./packem_shared/local-mirror.d-wbGXkXaE.js";
|
|
2
|
+
import "./packem_shared/types.d-BuLTPLaQ.js";
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
4
|
+
* Result of {@link useLocalQuery} — a discriminated union so callers get a
|
|
5
|
+
* typed error instead of a swallowed `undefined`.
|
|
5
6
|
* @experimental
|
|
6
7
|
*/
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
* argument.
|
|
15
|
-
*/
|
|
16
|
-
shardKey?: string;
|
|
17
|
-
}
|
|
8
|
+
type LocalQueryResult<T> = {
|
|
9
|
+
readonly data: T[];
|
|
10
|
+
readonly error?: undefined;
|
|
11
|
+
} | {
|
|
12
|
+
readonly data?: undefined;
|
|
13
|
+
readonly error: Error;
|
|
14
|
+
};
|
|
18
15
|
/**
|
|
19
16
|
* React hook that subscribes to a local SQLite query and returns
|
|
20
17
|
* live-updating results whenever the mirror applies a diff.
|
|
21
18
|
*
|
|
22
|
-
* Uses `useSyncExternalStore`
|
|
23
|
-
*
|
|
19
|
+
* Uses `useSyncExternalStore` with `getSnapshot` reading {@link LocalMirror.version}
|
|
20
|
+
* — a plain number, unconditionally `Object.is`-stable across calls with no
|
|
21
|
+
* mutation in between. The actual query runs in a `useMemo` keyed on
|
|
22
|
+
* `[mirror, version, sql, stableParamsKey(params)]`, so it only re-executes
|
|
23
|
+
* when the mirror actually advances (or `sql`/`params` change) — not on
|
|
24
|
+
* every unrelated re-render.
|
|
25
|
+
*
|
|
26
|
+
* This intentionally does NOT cache query results inside {@link LocalMirror}
|
|
27
|
+
* itself: an LRU-capped cache in the mirror core evicts still-mounted hooks'
|
|
28
|
+
* entries once more than the cap's worth of distinct live queries are open
|
|
29
|
+
* on one mirror, which makes `getSnapshot` return a fresh (non-identical)
|
|
30
|
+
* object on the next read — `useSyncExternalStore` then force-re-renders,
|
|
31
|
+
* re-inserts, evicts another entry, and so on without bound. Keying the
|
|
32
|
+
* external-store snapshot on the version primitive instead of a cached
|
|
33
|
+
* query result has no such cap, so it can't loop.
|
|
24
34
|
*
|
|
25
35
|
* The hook works with React 18+ concurrent features, Suspense, and
|
|
26
36
|
* server-side rendering. During SSR the same value is returned as on
|
|
@@ -32,28 +42,28 @@ interface UseLocalQueryOptions {
|
|
|
32
42
|
* engine without rewriting).
|
|
33
43
|
* @param params Optional positional bound parameters matching `?`
|
|
34
44
|
* placeholders in `sql`.
|
|
35
|
-
* @
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
* **Error handling**: The hook catches SQL errors internally and returns
|
|
43
|
-
* `undefined`. Use a try-catch around `mirror.query(...)` directly if you
|
|
44
|
-
* need finer-grained error diagnostics.
|
|
45
|
+
* @returns `{ data }` with the result rows typed via the generic parameter
|
|
46
|
+
* `T`, or `{ error }` when the query fails (e.g. malformed SQL, or the
|
|
47
|
+
* target table doesn't exist yet because no matching diff has been applied
|
|
48
|
+
* — that specific case surfaces as a "no such table" `Error`). Never
|
|
49
|
+
* collapses a failure to `undefined` — check `error` explicitly rather than
|
|
50
|
+
* treating a missing `data` as "still loading".
|
|
45
51
|
* @example
|
|
46
52
|
* ```tsx
|
|
47
53
|
* import { useLocalQuery } from "@lunora/replica/react";
|
|
48
54
|
* import { mirror } from "./mirror";
|
|
49
55
|
*
|
|
50
56
|
* function UserList() {
|
|
51
|
-
* const users = useLocalQuery<{ id: string; name: string }>(
|
|
57
|
+
* const { data: users, error } = useLocalQuery<{ id: string; name: string }>(
|
|
52
58
|
* mirror,
|
|
53
59
|
* "SELECT id, name FROM fn_todos_list WHERE name LIKE ?",
|
|
54
60
|
* ["%alice%"],
|
|
55
61
|
* );
|
|
56
62
|
*
|
|
63
|
+
* if (error) {
|
|
64
|
+
* return <p>Query failed: {error.message}</p>;
|
|
65
|
+
* }
|
|
66
|
+
*
|
|
57
67
|
* if (users === undefined) {
|
|
58
68
|
* return <p>Waiting for data…</p>;
|
|
59
69
|
* }
|
|
@@ -63,5 +73,5 @@ interface UseLocalQueryOptions {
|
|
|
63
73
|
* ```
|
|
64
74
|
* @experimental
|
|
65
75
|
*/
|
|
66
|
-
declare const useLocalQuery: <T = Record<string, unknown>>(mirror: LocalMirror, sql: string, params?: ReadonlyArray<unknown
|
|
67
|
-
export {
|
|
76
|
+
declare const useLocalQuery: <T = Record<string, unknown>>(mirror: LocalMirror, sql: string, params?: ReadonlyArray<unknown>) => LocalQueryResult<T>;
|
|
77
|
+
export { type LocalQueryResult, useLocalQuery };
|
package/dist/react.mjs
CHANGED
|
@@ -1,15 +1 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
const useLocalQuery = (mirror, sql, params, _options) => {
|
|
4
|
-
const subscribe = (onStoreChange) => mirror.onChange(onStoreChange);
|
|
5
|
-
const getSnapshot = () => mirror.version;
|
|
6
|
-
const getServerSnapshot = () => mirror.version;
|
|
7
|
-
useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
|
8
|
-
try {
|
|
9
|
-
return mirror.query(sql, params);
|
|
10
|
-
} catch {
|
|
11
|
-
return void 0;
|
|
12
|
-
}
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
export { useLocalQuery };
|
|
1
|
+
import{useSyncExternalStore as y,useMemo as i}from"react";const u=t=>JSON.stringify(t??[],(r,e)=>typeof e=="bigint"?`${e.toString()}n`:e),S=(t,r,e)=>{const s=n=>t.onChange(n),o=()=>t.version,c=y(s,o,o),a=u(e);return i(()=>{try{return{data:t.query(r,e)}}catch(n){return{error:n instanceof Error?n:new Error(String(n))}}},[t,c,r,a])};export{S as useLocalQuery};
|
package/package.json
CHANGED
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
class EventEmitter {
|
|
2
|
-
#listeners = /* @__PURE__ */ new Map();
|
|
3
|
-
#wildcardListeners = /* @__PURE__ */ new Set();
|
|
4
|
-
// ── Registration ──────────────────────────────────────────────────
|
|
5
|
-
/**
|
|
6
|
-
* Register a handler for a specific event type.
|
|
7
|
-
* @returns An unsubscribe function (equivalent to calling {@link off}).
|
|
8
|
-
*/
|
|
9
|
-
on(event, handler) {
|
|
10
|
-
let set = this.#listeners.get(event);
|
|
11
|
-
if (!set) {
|
|
12
|
-
set = /* @__PURE__ */ new Set();
|
|
13
|
-
this.#listeners.set(event, set);
|
|
14
|
-
}
|
|
15
|
-
set.add(handler);
|
|
16
|
-
return () => {
|
|
17
|
-
this.off(event, handler);
|
|
18
|
-
};
|
|
19
|
-
}
|
|
20
|
-
/**
|
|
21
|
-
* Remove a previously registered handler.
|
|
22
|
-
*/
|
|
23
|
-
off(event, handler) {
|
|
24
|
-
this.#listeners.get(event)?.delete(handler);
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* Register a wildcard handler that fires for **every** event type.
|
|
28
|
-
* @returns An unsubscribe function.
|
|
29
|
-
*/
|
|
30
|
-
onAny(handler) {
|
|
31
|
-
this.#wildcardListeners.add(handler);
|
|
32
|
-
return () => {
|
|
33
|
-
this.#wildcardListeners.delete(handler);
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
/**
|
|
37
|
-
* Remove a wildcard handler.
|
|
38
|
-
*/
|
|
39
|
-
offAny(handler) {
|
|
40
|
-
this.#wildcardListeners.delete(handler);
|
|
41
|
-
}
|
|
42
|
-
// ── Emission ──────────────────────────────────────────────────────
|
|
43
|
-
/**
|
|
44
|
-
* Emit an event. All registered handlers (typed + wildcard) are invoked
|
|
45
|
-
* synchronously. Exceptions from handlers are caught and silently
|
|
46
|
-
* swallowed — they **must not** break the emitter loop.
|
|
47
|
-
* @returns `true` if at least one handler was called.
|
|
48
|
-
*/
|
|
49
|
-
emit(event, payload) {
|
|
50
|
-
let called = false;
|
|
51
|
-
const typed = this.#listeners.get(event);
|
|
52
|
-
if (typed) {
|
|
53
|
-
for (const handler of typed) {
|
|
54
|
-
try {
|
|
55
|
-
handler(payload);
|
|
56
|
-
called = true;
|
|
57
|
-
} catch {
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
for (const handler of this.#wildcardListeners) {
|
|
62
|
-
try {
|
|
63
|
-
handler(event, payload);
|
|
64
|
-
called = true;
|
|
65
|
-
} catch {
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
return called;
|
|
69
|
-
}
|
|
70
|
-
// ── Introspection ─────────────────────────────────────────────────
|
|
71
|
-
/**
|
|
72
|
-
* Return `true` when at least one listener is registered for `event`.
|
|
73
|
-
*/
|
|
74
|
-
hasListeners(event) {
|
|
75
|
-
return (this.#listeners.get(event)?.size ?? 0) > 0 || this.#wildcardListeners.size > 0;
|
|
76
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* Return the number of typed listeners for a specific event.
|
|
79
|
-
*/
|
|
80
|
-
listenerCount(event) {
|
|
81
|
-
return this.#listeners.get(event)?.size ?? 0;
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* Remove all listeners.
|
|
85
|
-
*/
|
|
86
|
-
clear() {
|
|
87
|
-
this.#listeners.clear();
|
|
88
|
-
this.#wildcardListeners.clear();
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
export { EventEmitter };
|