@livestore/livestore 0.4.0 → 0.5.0-dev.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.tsbuildinfo +1 -1
- package/dist/QueryCache.d.ts.map +1 -1
- package/dist/SqliteDbWrapper.d.ts +1 -1
- package/dist/SqliteDbWrapper.d.ts.map +1 -1
- package/dist/SqliteDbWrapper.js +9 -7
- package/dist/SqliteDbWrapper.js.map +1 -1
- package/dist/SqliteDbWrapper.test.js +22 -5
- package/dist/SqliteDbWrapper.test.js.map +1 -1
- package/dist/effect/LiveStore.d.ts +68 -16
- package/dist/effect/LiveStore.d.ts.map +1 -1
- package/dist/effect/LiveStore.js +22 -20
- package/dist/effect/LiveStore.js.map +1 -1
- package/dist/effect/LiveStore.test.js +7 -8
- package/dist/effect/LiveStore.test.js.map +1 -1
- package/dist/effect/mod.js +2 -2
- package/dist/internal/mod.js +2 -2
- package/dist/live-queries/base-class.d.ts +20 -3
- package/dist/live-queries/base-class.d.ts.map +1 -1
- package/dist/live-queries/base-class.js +30 -4
- package/dist/live-queries/base-class.js.map +1 -1
- package/dist/live-queries/client-document-get-query.d.ts.map +1 -1
- package/dist/live-queries/client-document-get-query.js +1 -1
- package/dist/live-queries/computed.d.ts +1 -1
- package/dist/live-queries/computed.d.ts.map +1 -1
- package/dist/live-queries/computed.js +5 -5
- package/dist/live-queries/computed.js.map +1 -1
- package/dist/live-queries/db-query.d.ts +3 -3
- package/dist/live-queries/db-query.d.ts.map +1 -1
- package/dist/live-queries/db-query.js +30 -21
- package/dist/live-queries/db-query.js.map +1 -1
- package/dist/live-queries/db-query.test.js +15 -15
- package/dist/live-queries/db-query.test.js.map +1 -1
- package/dist/live-queries/mod.js +4 -4
- package/dist/live-queries/signal.d.ts +1 -1
- package/dist/live-queries/signal.d.ts.map +1 -1
- package/dist/live-queries/signal.js +2 -2
- package/dist/live-queries/signal.js.map +1 -1
- package/dist/live-queries/signal.test.js +5 -5
- package/dist/live-queries/signal.test.js.map +1 -1
- package/dist/mod.js +8 -8
- package/dist/reactive.d.ts +1 -1
- package/dist/reactive.d.ts.map +1 -1
- package/dist/reactive.js +20 -1
- package/dist/reactive.js.map +1 -1
- package/dist/reactive.test.js +1 -1
- package/dist/store/StoreRegistry.d.ts +12 -12
- package/dist/store/StoreRegistry.d.ts.map +1 -1
- package/dist/store/StoreRegistry.js +25 -25
- package/dist/store/StoreRegistry.js.map +1 -1
- package/dist/store/StoreRegistry.test.js +65 -62
- package/dist/store/StoreRegistry.test.js.map +1 -1
- package/dist/store/create-store.d.ts +27 -16
- package/dist/store/create-store.d.ts.map +1 -1
- package/dist/store/create-store.js +55 -27
- package/dist/store/create-store.js.map +1 -1
- package/dist/store/create-store.test.d.ts +2 -0
- package/dist/store/create-store.test.d.ts.map +1 -0
- package/dist/store/create-store.test.js +28 -0
- package/dist/store/create-store.test.js.map +1 -0
- package/dist/store/devtools.d.ts +1 -2
- package/dist/store/devtools.d.ts.map +1 -1
- package/dist/store/devtools.js +6 -5
- package/dist/store/devtools.js.map +1 -1
- package/dist/store/store-commit.test.d.ts +2 -0
- package/dist/store/store-commit.test.d.ts.map +1 -0
- package/dist/store/store-commit.test.js +85 -0
- package/dist/store/store-commit.test.js.map +1 -0
- package/dist/store/store-eventstream.test.js +6 -6
- package/dist/store/store-eventstream.test.js.map +1 -1
- package/dist/store/store-types.d.ts +10 -28
- package/dist/store/store-types.d.ts.map +1 -1
- package/dist/store/store-types.js +2 -38
- package/dist/store/store-types.js.map +1 -1
- package/dist/store/store-types.test.js +4 -4
- package/dist/store/store.d.ts +15 -16
- package/dist/store/store.d.ts.map +1 -1
- package/dist/store/store.js +149 -91
- package/dist/store/store.js.map +1 -1
- package/dist/utils/data-structures.d.ts.map +1 -1
- package/dist/utils/dev.d.ts.map +1 -1
- package/dist/utils/dev.js +1 -1
- package/dist/utils/dev.js.map +1 -1
- package/dist/utils/function-string.d.ts +3 -3
- package/dist/utils/function-string.d.ts.map +1 -1
- package/dist/utils/stack-info.d.ts.map +1 -1
- package/dist/utils/stack-info.js +2 -1
- package/dist/utils/stack-info.js.map +1 -1
- package/dist/utils/stack-info.test.js +1 -1
- package/dist/utils/tests/fixture.d.ts +26 -34
- package/dist/utils/tests/fixture.d.ts.map +1 -1
- package/dist/utils/tests/fixture.js.map +1 -1
- package/dist/utils/tests/mod.js +3 -3
- package/dist/utils/tests/otel.d.ts +6 -6
- package/dist/utils/tests/otel.d.ts.map +1 -1
- package/package.json +40 -50
- package/src/SqliteDbWrapper.test.ts +25 -3
- package/src/SqliteDbWrapper.ts +13 -10
- package/src/effect/LiveStore.test.ts +16 -16
- package/src/effect/LiveStore.ts +83 -51
- package/src/live-queries/__snapshots__/db-query.test.ts.snap +303 -97
- package/src/live-queries/base-class.ts +39 -7
- package/src/live-queries/computed.ts +5 -5
- package/src/live-queries/db-query.test.ts +9 -9
- package/src/live-queries/db-query.ts +42 -30
- package/src/live-queries/signal.test.ts +2 -2
- package/src/live-queries/signal.ts +3 -3
- package/src/reactive.ts +45 -35
- package/src/store/StoreRegistry.test.ts +62 -59
- package/src/store/StoreRegistry.ts +49 -38
- package/src/store/create-store.test.ts +35 -0
- package/src/store/create-store.ts +110 -55
- package/src/store/devtools.ts +283 -283
- package/src/store/store-commit.test.ts +137 -0
- package/src/store/store-eventstream.test.ts +16 -7
- package/src/store/store-types.test.ts +1 -1
- package/src/store/store-types.ts +10 -56
- package/src/store/store.ts +184 -110
- package/src/utils/dev.ts +1 -1
- package/src/utils/stack-info.ts +4 -1
package/src/store/store.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import * as otel from '@opentelemetry/api'
|
|
2
|
+
|
|
1
3
|
import {
|
|
2
4
|
type Bindable,
|
|
3
5
|
type ClientSession,
|
|
@@ -11,10 +13,11 @@ import {
|
|
|
11
13
|
MaterializeError,
|
|
12
14
|
MaterializerHashMismatchError,
|
|
13
15
|
makeClientSessionSyncProcessor,
|
|
14
|
-
type PreparedBindValues,
|
|
15
16
|
prepareBindValues,
|
|
16
17
|
QueryBuilderAstSymbol,
|
|
17
|
-
|
|
18
|
+
resolveSessionIdSymbolInBindValues,
|
|
19
|
+
SqliteDbHelper,
|
|
20
|
+
StateHead,
|
|
18
21
|
type StorageMode,
|
|
19
22
|
type SyncState,
|
|
20
23
|
UnknownError,
|
|
@@ -23,8 +26,8 @@ import type { StreamEventsOptions } from '@livestore/common/leader-thread'
|
|
|
23
26
|
import type { LiveStoreSchema } from '@livestore/common/schema'
|
|
24
27
|
import { EventSequenceNumber, LiveStoreEvent, resolveEventDef, SystemTables } from '@livestore/common/schema'
|
|
25
28
|
import { assertNever, isDevEnv, objectToString, omitUndefineds, shouldNeverHappen } from '@livestore/utils'
|
|
26
|
-
import type { Scope } from '@livestore/utils/effect'
|
|
27
29
|
import {
|
|
30
|
+
type Scope,
|
|
28
31
|
Cause,
|
|
29
32
|
Effect,
|
|
30
33
|
Exit,
|
|
@@ -32,12 +35,12 @@ import {
|
|
|
32
35
|
Inspectable,
|
|
33
36
|
Option,
|
|
34
37
|
OtelTracer,
|
|
35
|
-
|
|
38
|
+
Queue,
|
|
39
|
+
Result,
|
|
36
40
|
Schema,
|
|
37
41
|
Stream,
|
|
38
42
|
} from '@livestore/utils/effect'
|
|
39
43
|
import { nanoid } from '@livestore/utils/nanoid'
|
|
40
|
-
import * as otel from '@opentelemetry/api'
|
|
41
44
|
|
|
42
45
|
import type { LiveQuery, ReactivityGraphContext, SignalDef } from '../live-queries/base-class.ts'
|
|
43
46
|
import { makeReactivityGraph } from '../live-queries/base-class.ts'
|
|
@@ -206,14 +209,15 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
206
209
|
this.storageMode = clientSession.leaderThread.initialState.storageMode
|
|
207
210
|
|
|
208
211
|
const reactivityGraph = makeReactivityGraph()
|
|
212
|
+
const stateHead = StateHead.make({ dbState: clientSession.sqliteDb })
|
|
209
213
|
|
|
210
214
|
const syncProcessor = makeClientSessionSyncProcessor({
|
|
211
215
|
schema,
|
|
212
216
|
clientSession,
|
|
213
217
|
materializeEvent: Effect.fn('client-session-sync-processor:materialize-event')(
|
|
214
|
-
(eventEncoded, {
|
|
218
|
+
(eventEncoded, { materializerHashLeader }) =>
|
|
215
219
|
// We need to use `Effect.gen` (even though we're using `Effect.fn`) so that we can pass `this` to the function
|
|
216
|
-
Effect.gen(this, function* () {
|
|
220
|
+
Effect.gen({ self: this }, function* () {
|
|
217
221
|
const resolution = yield* resolveEventDef(schema, {
|
|
218
222
|
operation: '@livestore/livestore:store:materializeEvent',
|
|
219
223
|
event: eventEncoded,
|
|
@@ -222,6 +226,7 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
222
226
|
if (resolution._tag === 'unknown') {
|
|
223
227
|
// Runtime schema doesn't know this event yet; skip materialization but
|
|
224
228
|
// keep the log entry so upgraded clients can replay it later.
|
|
229
|
+
yield* stateHead.set(eventEncoded.seqNum)
|
|
225
230
|
return {
|
|
226
231
|
writeTables: new Set<string>(),
|
|
227
232
|
sessionChangeset: { _tag: 'no-op' as const },
|
|
@@ -286,18 +291,14 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
286
291
|
}
|
|
287
292
|
}
|
|
288
293
|
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
| { _tag: 'no-op' }
|
|
292
|
-
| { _tag: 'unset' } = { _tag: 'unset' }
|
|
293
|
-
if (withChangeset === true) {
|
|
294
|
-
sessionChangeset = this[StoreInternalsSymbol].sqliteDbWrapper.withChangeset(exec).changeset
|
|
295
|
-
} else {
|
|
296
|
-
exec()
|
|
297
|
-
}
|
|
294
|
+
const sessionChangeset = this[StoreInternalsSymbol].sqliteDbWrapper.withChangeset(exec).changeset
|
|
295
|
+
yield* stateHead.set(eventEncoded.seqNum)
|
|
298
296
|
|
|
299
297
|
return { writeTables: writeTablesForEvent, sessionChangeset, materializerHash }
|
|
300
|
-
}).pipe(
|
|
298
|
+
}).pipe(
|
|
299
|
+
SqliteDbHelper.withSavepoint(clientSession.sqliteDb),
|
|
300
|
+
Effect.mapError((cause) => MaterializeError.make({ cause })),
|
|
301
|
+
),
|
|
301
302
|
),
|
|
302
303
|
rollback: (changeset) => {
|
|
303
304
|
this[StoreInternalsSymbol].sqliteDbWrapper.rollback(changeset)
|
|
@@ -315,12 +316,9 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
315
316
|
...omitUndefineds({
|
|
316
317
|
leaderPushBatchSize: params.leaderPushBatchSize,
|
|
317
318
|
}),
|
|
318
|
-
...(params.simulation?.clientSessionSyncProcessor !== undefined
|
|
319
|
-
? { simulation: params.simulation.clientSessionSyncProcessor }
|
|
320
|
-
: {}),
|
|
321
319
|
},
|
|
322
320
|
confirmUnsavedChanges,
|
|
323
|
-
}).pipe(
|
|
321
|
+
}).pipe(Effect.provideService(StateHead.StateHead, stateHead), Effect.runSyncWith(effectContext.services))
|
|
324
322
|
|
|
325
323
|
// TODO generalize the `tableRefs` concept to allow finer-grained refs
|
|
326
324
|
const tableRefs: { [key: string]: Ref<null, ReactivityGraphContext, RefreshReason> } = {}
|
|
@@ -370,7 +368,7 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
370
368
|
})
|
|
371
369
|
}
|
|
372
370
|
|
|
373
|
-
const boot = Effect.gen(this, function* () {
|
|
371
|
+
const boot = Effect.gen({ self: this }, function* () {
|
|
374
372
|
yield* Effect.addFinalizer(() =>
|
|
375
373
|
Effect.sync(() => {
|
|
376
374
|
// Remove all table refs from the reactivity graph
|
|
@@ -394,7 +392,7 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
394
392
|
|
|
395
393
|
// Initialize internals bag
|
|
396
394
|
this[StoreInternalsSymbol] = {
|
|
397
|
-
eventSchema: LiveStoreEvent.Client.makeSchemaMemo(schema) as Schema.
|
|
395
|
+
eventSchema: LiveStoreEvent.Client.makeSchemaMemo(schema) as Schema.Codec<
|
|
398
396
|
LiveStoreEvent.Client.Decoded,
|
|
399
397
|
LiveStoreEvent.Client.Encoded
|
|
400
398
|
>,
|
|
@@ -570,24 +568,111 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
570
568
|
): AsyncIterable<TResult> => {
|
|
571
569
|
this.checkShutdown('subscribe')
|
|
572
570
|
|
|
573
|
-
|
|
571
|
+
// This used to delegate to `Stream.toAsyncIterable(this.subscribeStream(...))`.
|
|
572
|
+
// With Effect v4, the callback-backed stream producer is forked during stream startup, so a caller could request
|
|
573
|
+
// `next()`, commit an update, and race the actual subscription registration. Register directly here so the first
|
|
574
|
+
// pending `next()` observes post-subscription updates. In the future, this should be refactored back toward a shared
|
|
575
|
+
// stream/async-iterable bridge if Effect exposes a primitive with that synchronous registration guarantee.
|
|
576
|
+
return {
|
|
577
|
+
[Symbol.asyncIterator]: () => {
|
|
578
|
+
const services = this[StoreInternalsSymbol].effectContext.services
|
|
579
|
+
const runSync = Effect.runSyncWith(services)
|
|
580
|
+
const runPromiseExit = Effect.runPromiseExitWith(services)
|
|
581
|
+
let queue: Queue.Queue<TResult, Cause.Done> | undefined
|
|
582
|
+
let isDone = false
|
|
583
|
+
let unsubscribe: Unsubscribe | undefined
|
|
584
|
+
|
|
585
|
+
const done = (): IteratorResult<TResult> => ({ done: true, value: undefined })
|
|
586
|
+
const isClosed = () => isDone
|
|
587
|
+
const isQueueDone = (cause: Cause.Cause<Cause.Done>) => {
|
|
588
|
+
const error = Cause.findError(cause)
|
|
589
|
+
return Result.isSuccess(error) && Cause.isDone(error.success)
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
const ensureQueue = () => {
|
|
593
|
+
// Lazily allocate the queue so creating an async iterator without consuming it has no subscription-side work.
|
|
594
|
+
queue ??= Queue.unbounded<TResult, Cause.Done>().pipe(runSync)
|
|
595
|
+
return queue
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
const emit = (value: TResult) => {
|
|
599
|
+
if (isDone === true) return
|
|
600
|
+
|
|
601
|
+
Queue.offerUnsafe(ensureQueue(), value)
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
const ensureSubscribed = () => {
|
|
605
|
+
// Subscribe from the first `next()` call so callers that request a value before
|
|
606
|
+
// committing updates don't race the asynchronous Stream-to-iterator startup path.
|
|
607
|
+
unsubscribe ??= this.subscribeWithCallback(query, emit, options)
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
const close = (): IteratorResult<TResult> => {
|
|
611
|
+
if (isDone === false) {
|
|
612
|
+
isDone = true
|
|
613
|
+
unsubscribe?.()
|
|
614
|
+
unsubscribe = undefined
|
|
615
|
+
|
|
616
|
+
if (queue !== undefined) {
|
|
617
|
+
// Wake any pending `next()` call and prevent later callback emissions from being buffered.
|
|
618
|
+
Queue.shutdown(queue).pipe(runSync)
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
return done()
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
return {
|
|
626
|
+
next: async () => {
|
|
627
|
+
if (isDone === true) {
|
|
628
|
+
return done()
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
ensureSubscribed()
|
|
632
|
+
|
|
633
|
+
// Delegate buffering and pending-consumer wakeups to Effect's queue implementation.
|
|
634
|
+
const exit = await runPromiseExit(Queue.take(ensureQueue()))
|
|
635
|
+
if (Exit.isSuccess(exit) === true) {
|
|
636
|
+
return { done: false, value: exit.value }
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
if (isClosed() === true || isQueueDone(exit.cause) === true) {
|
|
640
|
+
return done()
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
throw Cause.squash(exit.cause)
|
|
644
|
+
},
|
|
645
|
+
return: () => Promise.resolve(close()),
|
|
646
|
+
throw: (cause) => {
|
|
647
|
+
close()
|
|
648
|
+
return Promise.reject(cause)
|
|
649
|
+
},
|
|
650
|
+
}
|
|
651
|
+
},
|
|
652
|
+
}
|
|
574
653
|
}
|
|
575
654
|
|
|
576
655
|
subscribeStream = <TResult>(query: Queryable<TResult>, options?: SubscribeOptions<TResult>): Stream.Stream<TResult> =>
|
|
577
|
-
Stream.
|
|
578
|
-
Effect.gen(this, function* () {
|
|
656
|
+
Stream.callback<TResult>((emit) =>
|
|
657
|
+
Effect.gen({ self: this }, function* () {
|
|
579
658
|
const otelSpan = yield* OtelTracer.currentOtelSpan.pipe(
|
|
580
|
-
Effect.catchTag('
|
|
659
|
+
Effect.catchTag('NoSuchElementError', () => Effect.void),
|
|
581
660
|
)
|
|
582
661
|
const otelContext =
|
|
583
662
|
otelSpan !== undefined ? otel.trace.setSpan(otel.context.active(), otelSpan) : otel.context.active()
|
|
584
663
|
|
|
585
664
|
yield* Effect.acquireRelease(
|
|
586
665
|
Effect.sync(() =>
|
|
587
|
-
this.subscribe(
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
666
|
+
this.subscribe(
|
|
667
|
+
query,
|
|
668
|
+
(result) => {
|
|
669
|
+
Queue.offerUnsafe(emit, result)
|
|
670
|
+
},
|
|
671
|
+
{
|
|
672
|
+
...options,
|
|
673
|
+
otelContext,
|
|
674
|
+
},
|
|
675
|
+
),
|
|
591
676
|
),
|
|
592
677
|
(unsub) => Effect.sync(() => unsub()),
|
|
593
678
|
)
|
|
@@ -609,7 +694,7 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
609
694
|
* ```
|
|
610
695
|
*/
|
|
611
696
|
query = <TResult>(
|
|
612
|
-
query: Queryable<TResult> | { query: string; bindValues: Bindable; schema?: Schema.
|
|
697
|
+
query: Queryable<TResult> | { query: string; bindValues: Bindable; schema?: Schema.Decoder<TResult> },
|
|
613
698
|
options?: { otelContext?: otel.Context; debugRefreshReason?: RefreshReason },
|
|
614
699
|
): TResult => {
|
|
615
700
|
this.checkShutdown('query')
|
|
@@ -623,7 +708,7 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
623
708
|
},
|
|
624
709
|
) as any
|
|
625
710
|
if (query.schema !== undefined) {
|
|
626
|
-
return Schema.
|
|
711
|
+
return Schema.decodeUnknownSync(query.schema)(res)
|
|
627
712
|
}
|
|
628
713
|
return res
|
|
629
714
|
} else if (isQueryBuilder(query) === true) {
|
|
@@ -640,23 +725,25 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
640
725
|
const sqlRes = query.asSql()
|
|
641
726
|
const schema = getResultSchema(query)
|
|
642
727
|
|
|
643
|
-
//
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
728
|
+
// Query builders preserve SessionIdSymbol so client-document queries can be reused across sessions.
|
|
729
|
+
// SQLite bind values must be concrete primitives, so resolve the symbol only at execution time.
|
|
730
|
+
const resolvedBindValues =
|
|
731
|
+
sqlRes.bindValues === undefined
|
|
732
|
+
? undefined
|
|
733
|
+
: resolveSessionIdSymbolInBindValues(sqlRes.bindValues, this[StoreInternalsSymbol].clientSession.sessionId)
|
|
647
734
|
|
|
648
735
|
const rawRes = this[StoreInternalsSymbol].sqliteDbWrapper.cachedSelect(
|
|
649
736
|
sqlRes.query,
|
|
650
|
-
|
|
737
|
+
resolvedBindValues === undefined ? undefined : prepareBindValues(resolvedBindValues, sqlRes.query),
|
|
651
738
|
{
|
|
652
739
|
...omitUndefineds({ otelContext: options?.otelContext }),
|
|
653
740
|
queriedTables: new Set([query[QueryBuilderAstSymbol].tableDef.sqliteDef.name]),
|
|
654
741
|
},
|
|
655
742
|
)
|
|
656
743
|
|
|
657
|
-
const decodeResult = Schema.
|
|
658
|
-
if (decodeResult
|
|
659
|
-
return decodeResult.
|
|
744
|
+
const decodeResult = Schema.decodeResult(schema)(rawRes)
|
|
745
|
+
if (Result.isSuccess(decodeResult) === true) {
|
|
746
|
+
return decodeResult.success
|
|
660
747
|
} else {
|
|
661
748
|
return shouldNeverHappen(
|
|
662
749
|
'Failed to decode query result with for schema:',
|
|
@@ -664,7 +751,7 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
664
751
|
'raw result:',
|
|
665
752
|
rawRes,
|
|
666
753
|
'decode error:',
|
|
667
|
-
decodeResult.
|
|
754
|
+
decodeResult.failure,
|
|
668
755
|
)
|
|
669
756
|
}
|
|
670
757
|
} else if (query._tag === 'def') {
|
|
@@ -734,19 +821,16 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
734
821
|
* events.todoCompleted({ id: todoId }))
|
|
735
822
|
* ```
|
|
736
823
|
*
|
|
737
|
-
* For
|
|
738
|
-
*
|
|
739
|
-
* Under the hood this will simply collect all events and apply them in a single database transaction.
|
|
824
|
+
* For conditional batches, you can pass a synchronous function to `commit` which returns an array of events.
|
|
825
|
+
* LiveStore evaluates the function before applying the returned events in a single database transaction.
|
|
740
826
|
*
|
|
741
827
|
* @example
|
|
742
828
|
* ```ts
|
|
743
|
-
* store.commit((
|
|
829
|
+
* store.commit(() => {
|
|
744
830
|
* const todoId = nanoid()
|
|
745
|
-
*
|
|
746
|
-
*
|
|
747
|
-
*
|
|
748
|
-
* commit(events.todoCompleted({ id: todoId }))
|
|
749
|
-
* }
|
|
831
|
+
* return Math.random() > 0.5
|
|
832
|
+
* ? [events.todoCreated({ id: todoId, text: 'Make coffee' })]
|
|
833
|
+
* : [events.todoCompleted({ id: todoId })]
|
|
750
834
|
* })
|
|
751
835
|
* ```
|
|
752
836
|
*
|
|
@@ -768,49 +852,36 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
768
852
|
*/
|
|
769
853
|
commit: {
|
|
770
854
|
<const TCommitArg extends ReadonlyArray<LiveStoreEvent.Input.ForSchema<TSchema>>>(...list: TCommitArg): void
|
|
771
|
-
(
|
|
772
|
-
txn: <const TCommitArg extends ReadonlyArray<LiveStoreEvent.Input.ForSchema<TSchema>>>(
|
|
773
|
-
...list: TCommitArg
|
|
774
|
-
) => void,
|
|
775
|
-
): void
|
|
855
|
+
(buildEvents: CommitBatchBuilder<TSchema>): void
|
|
776
856
|
<const TCommitArg extends ReadonlyArray<LiveStoreEvent.Input.ForSchema<TSchema>>>(
|
|
777
857
|
options: StoreCommitOptions,
|
|
778
858
|
...list: TCommitArg
|
|
779
859
|
): void
|
|
780
|
-
(
|
|
781
|
-
|
|
782
|
-
txn: <const TCommitArg extends ReadonlyArray<LiveStoreEvent.Input.ForSchema<TSchema>>>(
|
|
783
|
-
...list: TCommitArg
|
|
784
|
-
) => void,
|
|
785
|
-
): void
|
|
786
|
-
} = (firstEventOrTxnFnOrOptions: any, ...restEvents: any[]) => {
|
|
860
|
+
(options: StoreCommitOptions, buildEvents: CommitBatchBuilder<TSchema>): void
|
|
861
|
+
} = (firstEventOrBatchBuilderOrOptions: any, ...restEvents: any[]) => {
|
|
787
862
|
this.checkShutdown('commit')
|
|
788
863
|
|
|
789
|
-
const { events, options } = this.getCommitArgs(
|
|
864
|
+
const { events, options } = this.getCommitArgs(firstEventOrBatchBuilderOrOptions, restEvents)
|
|
790
865
|
|
|
791
|
-
Effect.gen(this, function* () {
|
|
866
|
+
Effect.gen({ self: this }, function* () {
|
|
792
867
|
const commitsSpan = otel.trace.getSpan(this[StoreInternalsSymbol].otel.commitsSpanContext)
|
|
793
868
|
commitsSpan?.addEvent('commit')
|
|
794
869
|
const currentSpan = yield* OtelTracer.currentOtelSpan.pipe(Effect.orDie)
|
|
795
870
|
commitsSpan?.addLink({ context: currentSpan.spanContext() })
|
|
796
871
|
|
|
797
|
-
for (const event of events) {
|
|
798
|
-
replaceSessionIdSymbol(event.args, this[StoreInternalsSymbol].clientSession.sessionId)
|
|
799
|
-
}
|
|
800
|
-
|
|
801
872
|
if (events.length === 0) return
|
|
802
873
|
|
|
803
|
-
const
|
|
874
|
+
const localServices = yield* Effect.context()
|
|
804
875
|
|
|
805
876
|
const encodedEvents = yield* this[StoreInternalsSymbol].syncProcessor.encodeEvents(events)
|
|
806
877
|
|
|
807
878
|
const { writeTables } = yield* Effect.try({
|
|
808
879
|
try: () => {
|
|
809
880
|
const materialize = () =>
|
|
810
|
-
this[StoreInternalsSymbol].syncProcessor
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
881
|
+
this[StoreInternalsSymbol].syncProcessor
|
|
882
|
+
.materializeEvents(encodedEvents)
|
|
883
|
+
.pipe(Effect.runSyncWith(localServices))
|
|
884
|
+
return events.length > 1 ? this[StoreInternalsSymbol].sqliteDbWrapper.txn(materialize) : materialize()
|
|
814
885
|
},
|
|
815
886
|
catch: (cause) => UnknownError.make({ cause }),
|
|
816
887
|
})
|
|
@@ -854,9 +925,9 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
854
925
|
...(options?.spanLinks?.map(OtelTracer.makeSpanLink) ?? []),
|
|
855
926
|
],
|
|
856
927
|
}),
|
|
857
|
-
Effect.
|
|
858
|
-
Effect.
|
|
859
|
-
|
|
928
|
+
Effect.tapCause(Effect.logError),
|
|
929
|
+
Effect.catchCause((cause) => Effect.forkChild(this.shutdown(cause))),
|
|
930
|
+
Effect.runSyncWith(this[StoreInternalsSymbol].effectContext.services),
|
|
860
931
|
)
|
|
861
932
|
}
|
|
862
933
|
//#endregion commit
|
|
@@ -934,8 +1005,8 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
934
1005
|
}
|
|
935
1006
|
|
|
936
1007
|
return clientSession.leaderThread.events.stream(baseOptions).pipe(
|
|
937
|
-
Stream.
|
|
938
|
-
Stream.catchTag('
|
|
1008
|
+
Stream.mapEffect((event) => Schema.decodeEffect(eventSchema)(event)),
|
|
1009
|
+
Stream.catchTag('SchemaError', (cause) => Stream.fail(UnknownError.make({ cause }))),
|
|
939
1010
|
Stream.tapError((error) => Effect.logError('Error in eventsStream', error)),
|
|
940
1011
|
)
|
|
941
1012
|
}
|
|
@@ -1028,7 +1099,7 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
1028
1099
|
)
|
|
1029
1100
|
|
|
1030
1101
|
return () => {
|
|
1031
|
-
Fiber.interrupt(fiber).pipe(
|
|
1102
|
+
Fiber.interrupt(fiber).pipe(Effect.runForkWith(this[StoreInternalsSymbol].effectContext.services))
|
|
1032
1103
|
}
|
|
1033
1104
|
}
|
|
1034
1105
|
|
|
@@ -1102,7 +1173,7 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
1102
1173
|
*/
|
|
1103
1174
|
_dev = {
|
|
1104
1175
|
downloadDb: (source: 'local' | 'leader' = 'local') => {
|
|
1105
|
-
Effect.gen(this, function* () {
|
|
1176
|
+
Effect.gen({ self: this }, function* () {
|
|
1106
1177
|
const data =
|
|
1107
1178
|
source === 'local'
|
|
1108
1179
|
? this[StoreInternalsSymbol].sqliteDbWrapper.export()
|
|
@@ -1112,14 +1183,14 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
1112
1183
|
},
|
|
1113
1184
|
|
|
1114
1185
|
downloadEventlogDb: () => {
|
|
1115
|
-
Effect.gen(this, function* () {
|
|
1186
|
+
Effect.gen({ self: this }, function* () {
|
|
1116
1187
|
const data = yield* this[StoreInternalsSymbol].clientSession.leaderThread.getEventlogData
|
|
1117
1188
|
downloadBlob(data, `livestore-eventlog-${Date.now()}.db`)
|
|
1118
1189
|
}).pipe(this.runEffectFork)
|
|
1119
1190
|
},
|
|
1120
1191
|
|
|
1121
1192
|
hardReset: (mode: 'all-data' | 'only-app-db' = 'all-data') => {
|
|
1122
|
-
Effect.gen(this, function* () {
|
|
1193
|
+
Effect.gen({ self: this }, function* () {
|
|
1123
1194
|
const clientId = this[StoreInternalsSymbol].clientSession.clientId
|
|
1124
1195
|
yield* this[StoreInternalsSymbol].clientSession.leaderThread.sendDevtoolsMessage(
|
|
1125
1196
|
Devtools.Leader.ResetAllData.Request.make({ liveStoreVersion, mode, requestId: nanoid(), clientId }),
|
|
@@ -1143,14 +1214,14 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
1143
1214
|
|
|
1144
1215
|
// NOTE: Explicit return type needed to avoid TS2742 (inferred type references internal path)
|
|
1145
1216
|
syncStates: (): Promise<{ session: SyncState.SyncState; leader: SyncState.SyncState }> =>
|
|
1146
|
-
Effect.gen(this, function* () {
|
|
1217
|
+
Effect.gen({ self: this }, function* () {
|
|
1147
1218
|
const session = yield* this[StoreInternalsSymbol].syncProcessor.syncState
|
|
1148
1219
|
const leader = yield* this[StoreInternalsSymbol].clientSession.leaderThread.syncState
|
|
1149
1220
|
return { session, leader }
|
|
1150
1221
|
}).pipe(this.runEffectPromise),
|
|
1151
1222
|
|
|
1152
1223
|
printSyncStates: () => {
|
|
1153
|
-
Effect.gen(this, function* () {
|
|
1224
|
+
Effect.gen({ self: this }, function* () {
|
|
1154
1225
|
const session = yield* this[StoreInternalsSymbol].syncProcessor.syncState
|
|
1155
1226
|
yield* Effect.log(
|
|
1156
1227
|
`Session sync state: ${objectToString(session.localHead)} (upstream: ${objectToString(session.upstreamHead)})`,
|
|
@@ -1181,46 +1252,49 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
|
|
|
1181
1252
|
effect.pipe(
|
|
1182
1253
|
Effect.forkIn(this[StoreInternalsSymbol].effectContext.lifetimeScope),
|
|
1183
1254
|
Effect.tapCauseLogPretty,
|
|
1184
|
-
|
|
1255
|
+
Effect.runForkWith(this[StoreInternalsSymbol].effectContext.services),
|
|
1185
1256
|
)
|
|
1186
1257
|
|
|
1187
1258
|
private runEffectPromise = <A, E>(effect: Effect.Effect<A, E, Scope.Scope>) =>
|
|
1188
|
-
effect.pipe(Effect.tapCauseLogPretty,
|
|
1259
|
+
effect.pipe(Effect.tapCauseLogPretty, Effect.runPromiseWith(this[StoreInternalsSymbol].effectContext.services))
|
|
1189
1260
|
|
|
1190
1261
|
private getCommitArgs = (
|
|
1191
|
-
|
|
1262
|
+
firstEventOrBatchBuilderOrOptions: any,
|
|
1192
1263
|
restEvents: any[],
|
|
1193
1264
|
): {
|
|
1194
1265
|
events: LiveStoreEvent.Input.ForSchema<TSchema>[]
|
|
1195
1266
|
options: StoreCommitOptions | undefined
|
|
1196
1267
|
} => {
|
|
1197
|
-
let events: LiveStoreEvent.Input.ForSchema<TSchema>[]
|
|
1268
|
+
let events: LiveStoreEvent.Input.ForSchema<TSchema>[] = []
|
|
1198
1269
|
let options: StoreCommitOptions | undefined
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
firstEventOrTxnFnOrOptions?.spanLinks !== undefined
|
|
1270
|
+
let commitArgs = [firstEventOrBatchBuilderOrOptions, ...restEvents]
|
|
1271
|
+
|
|
1272
|
+
if (
|
|
1273
|
+
firstEventOrBatchBuilderOrOptions?.label !== undefined ||
|
|
1274
|
+
firstEventOrBatchBuilderOrOptions?.skipRefresh !== undefined ||
|
|
1275
|
+
firstEventOrBatchBuilderOrOptions?.otelContext !== undefined ||
|
|
1276
|
+
firstEventOrBatchBuilderOrOptions?.spanLinks !== undefined ||
|
|
1277
|
+
typeof restEvents[0] === 'function'
|
|
1208
1278
|
) {
|
|
1209
|
-
options =
|
|
1210
|
-
|
|
1211
|
-
} else if (firstEventOrTxnFnOrOptions === undefined) {
|
|
1212
|
-
// When `commit` is called with no arguments (which sometimes happens when dynamically filtering events)
|
|
1213
|
-
events = []
|
|
1214
|
-
} else {
|
|
1215
|
-
events = [firstEventOrTxnFnOrOptions, ...restEvents]
|
|
1279
|
+
options = firstEventOrBatchBuilderOrOptions
|
|
1280
|
+
commitArgs = restEvents
|
|
1216
1281
|
}
|
|
1217
1282
|
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1283
|
+
const firstEventOrBatchBuilder = commitArgs[0]
|
|
1284
|
+
if (typeof firstEventOrBatchBuilder === 'function') {
|
|
1285
|
+
const builtEvents: unknown = firstEventOrBatchBuilder()
|
|
1286
|
+
if (Array.isArray(builtEvents) === false) {
|
|
1287
|
+
throw new TypeError('store.commit callback must synchronously return an array of events')
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
// Copy the completed batch so callers cannot mutate the array while it enters the commit pipeline.
|
|
1291
|
+
events = [...builtEvents]
|
|
1292
|
+
} else if (firstEventOrBatchBuilder !== undefined) {
|
|
1293
|
+
events = commitArgs
|
|
1294
|
+
}
|
|
1223
1295
|
|
|
1224
1296
|
return { events, options }
|
|
1225
1297
|
}
|
|
1226
1298
|
}
|
|
1299
|
+
|
|
1300
|
+
type CommitBatchBuilder<TSchema extends LiveStoreSchema> = () => ReadonlyArray<LiveStoreEvent.Input.ForSchema<TSchema>>
|
package/src/utils/dev.ts
CHANGED
|
@@ -24,7 +24,7 @@ export const downloadURL = (data: string, fileName: string) => {
|
|
|
24
24
|
const a = document.createElement('a')
|
|
25
25
|
a.href = data
|
|
26
26
|
a.download = fileName
|
|
27
|
-
document.body.
|
|
27
|
+
document.body.appendChild(a)
|
|
28
28
|
a.style.display = 'none'
|
|
29
29
|
a.click()
|
|
30
30
|
a.remove()
|
package/src/utils/stack-info.ts
CHANGED
|
@@ -41,7 +41,10 @@ export const extractStackInfoFromStackTrace = (stackTrace: string): StackInfo =>
|
|
|
41
41
|
// console.debug(name, filePath)
|
|
42
42
|
|
|
43
43
|
// NOTE No idea where this `Module.` comes from - possibly a Vite thing?
|
|
44
|
-
if (
|
|
44
|
+
if (
|
|
45
|
+
(name.startsWith('use') === true || name.startsWith('Module.use') === true) &&
|
|
46
|
+
name.endsWith('QueryRef') === false
|
|
47
|
+
) {
|
|
45
48
|
hasReachedStart = true
|
|
46
49
|
// console.debug('hasReachedStart. adding one more frame.')
|
|
47
50
|
|