@sqlite-sync/core 0.6.0 → 0.7.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/index.d.ts CHANGED
@@ -1,13 +1,63 @@
1
1
  import * as kysely from 'kysely';
2
2
  import { Kysely, SchemaModule } from 'kysely';
3
- import { S as SQLiteDbWrapper, L as Logger, T as TypedEvent, I as InternalSQLiteWrapper, a as StoredValue, C as CrdtStorage, E as ExecuteParams, b as ExecuteResult, Q as QueryBuilderOutput, K as KyselyQueryFactory, c as SQLiteTransactionWrapper, W as WorkerState, D as DeSyncDetectedReason } from './crdt-sync-remote-source-CJrVzW-B.js';
4
- export { R as CRDT_EVENT_NO_OP_PAYLOAD, U as CrdtEventOrigin, V as CrdtEventStatus, X as CrdtEventType, F as CrdtSyncRemoteSource, Y as CrdtUpdateLogItem, Z as CrdtUpdateLogPayload, g as DatabaseIntrospection, a5 as DeferredPromise, a6 as DistributiveOmit, J as EventsPullRequest, N as EventsPushRequest, O as EventsPushResponse, H as HLC, f as HLCCounter, a1 as KyselyStatementFactory, j as LogLevel, M as MigratableEvent, n as Migrations, o as MigrationsDb, P as PendingCrdtEvent, $ as PersistedCrdtEvent, a2 as PreparedStatement, p as SyncDbMigrator, w as SystemDbConfig, x as SystemMigration, y as SystemMigrationContext, h as TableMetadata, aa as TypedBroadcastChannel, ab as TypedEventTarget, ae as WorkerConfig, af as WorkerNotificationMessage, q as applyMemoryDbSchema, r as applyWorkerDbSchema, t as baseSystemMigrations, d as compareHLC, z as createCrdtApplyFunction, B as createCrdtStorage, G as createCrdtSyncRemoteSource, a3 as createDeferredPromise, l as createMigrations, m as createMigrator, A as createSQLiteCrdtApplyFunction, a0 as createStoredValue, u as createSystemDbConfig, a4 as createTypedEventTarget, e as deserializeHLC, a7 as generateId, i as introspectDb, _ as isNoOpCrdtEventPayload, a8 as jsonSafeParse, a9 as quoteId, v as runSystemMigrations, s as serializeHLC, k as startPerformanceLogger, ac as tryCatch, ad as tryCatchAsync } from './crdt-sync-remote-source-CJrVzW-B.js';
5
- import { S as SyncDbSchema, C as CrdtTableConfig } from './reset-state-Comk7IC0.js';
6
- export { a as CreateCrdtSchemaOptions, R as RESET_REQUEST_TTL_MS, b as ResetRequest, d as ResetStore, c as createSyncDbSchema } from './reset-state-Comk7IC0.js';
3
+ import { I as InternalSQLiteWrapper, S as StoredValue, E as ExecuteResult, C as CrdtStorage, a as CrdtTableConfig, b as SQLiteDbWrapper, L as Logger, T as TypedEvent, c as SyncSchemaTables, d as SyncDbSchema, A as AnyTableBuilder, e as TableBuilder, f as TableColumns, g as InferRow, R as ReadonlyTable, M as Migrations, N as NewCrdtEvent, h as ExecuteParams, Q as QueryBuilderOutput, K as KyselyQueryFactory, i as SQLiteTransactionWrapper, W as WorkerState, D as DeSyncDetectedReason } from './crdt-sync-remote-source-yXp-iMEd.js';
4
+ export { U as AnyColumnBuilder, ab as CRDT_EVENT_NO_OP_PAYLOAD, V as ColumnBuilder, X as ColumnKind, Y as ColumnMeta, m as ColumnMetadata, ac as CrdtEventOrigin, ad as CrdtEventStatus, ae as CrdtEventType, a6 as CrdtSyncRemoteSource, af as CrdtUpdateLogItem, ag as CrdtUpdateLogPayload, n as DatabaseIntrospection, ao as DeferredPromise, ap as DistributiveOmit, a8 as EventsPullRequest, a9 as EventsPushRequest, aa as EventsPushResponse, H as HLC, l as HLCCounter, ak as KyselyStatementFactory, q as LogLevel, v as MigratableEvent, w as MigrationsDb, a5 as OwnCrdtEvent, Z as PayloadValidationResult, a3 as PendingCrdtEvent, ai as PersistedCrdtEvent, al as PreparedStatement, _ as SqliteStorageType, x as SyncDbMigrator, J as SystemDbConfig, O as SystemMigration, P as SystemMigrationContext, p as TableMetadata, $ as TableOptions, at as TypedBroadcastChannel, au as TypedEventTarget, ax as WorkerConfig, ay as WorkerNotificationMessage, y as applyMemoryDbSchema, z as applyWorkerDbSchema, B as baseSystemMigrations, j as compareHLC, a1 as createCrdtApplyFunction, a4 as createCrdtStorage, a7 as createCrdtSyncRemoteSource, am as createDeferredPromise, t as createMigrations, u as createMigrator, a2 as createSQLiteCrdtApplyFunction, aj as createStoredValue, F as createSystemDbConfig, an as createTypedEventTarget, k as deserializeHLC, aq as generateId, o as introspectDb, ah as isNoOpCrdtEventPayload, ar as jsonSafeParse, as as quoteId, G as runSystemMigrations, s as serializeHLC, r as startPerformanceLogger, a0 as t, av as tryCatch, aw as tryCatchAsync } from './crdt-sync-remote-source-yXp-iMEd.js';
5
+ export { R as RESET_REQUEST_TTL_MS, a as ResetRequest, b as ResetStore } from './reset-state-D6UslXaj.js';
7
6
  import '@sqlite.org/sqlite-wasm';
8
7
 
9
8
  declare const dummyKysely: Kysely<any>;
10
9
 
10
+ type KvStoreItem = {
11
+ key: string;
12
+ value: string;
13
+ };
14
+ declare function createKvStoreTableQuery(schema: SchemaModule, tableName: string): kysely.CreateTableBuilder<string, "value" | "key">;
15
+ declare function createSQLiteKvStore({ db, metaTableName }: {
16
+ db: InternalSQLiteWrapper<any>;
17
+ metaTableName: string;
18
+ }): {
19
+ get: (key: string) => string | null;
20
+ set: (key: string, value: string) => void;
21
+ remove: (key: string) => void;
22
+ createStringStoredValue: (key: string, defaultValue: string) => StoredValue<string>;
23
+ createNumberStoredValue: (key: string, defaultValue: number) => StoredValue<number>;
24
+ };
25
+
26
+ /**
27
+ * A portable, schema-version-aware dump of every active entity in a synced DB.
28
+ * Unlike a raw SQLite snapshot, it carries no event history — just the current
29
+ * `tombstone = 0` rows, ready to be replayed as fresh create events on import.
30
+ */
31
+ type SyncedDbExport = {
32
+ schemaVersion: number;
33
+ exportedAt: string;
34
+ /** crdt table name -> active rows (each includes `id`, excludes `tombstone`). */
35
+ tables: Record<string, Array<Record<string, unknown>>>;
36
+ };
37
+ type ExportImportReactiveDb = {
38
+ db: {
39
+ execute<T>(sql: string, meta: {
40
+ loggerLevel: "system";
41
+ }): ExecuteResult<T>;
42
+ };
43
+ };
44
+ type CreateExportImportOptions = {
45
+ reactiveDb: ExportImportReactiveDb;
46
+ crdtStorage: CrdtStorage;
47
+ tablesConfig: CrdtTableConfig[];
48
+ schemaVersion: number;
49
+ };
50
+ declare function createExportImport({ reactiveDb, crdtStorage, tablesConfig, schemaVersion, }: CreateExportImportOptions): {
51
+ exportData: (opts?: {
52
+ tables?: string[];
53
+ }) => SyncedDbExport;
54
+ importData: (data: SyncedDbExport, opts?: {
55
+ validate?: boolean;
56
+ }) => {
57
+ imported: number;
58
+ };
59
+ };
60
+
11
61
  declare function ensureLoaded(): Promise<void>;
12
62
  declare function h64(input: string, seed?: bigint): bigint;
13
63
  declare const xxhash: {
@@ -90,21 +140,71 @@ declare class SQLiteReactiveDb<Database> {
90
140
  }
91
141
  declare function parametersAreEqual(a: readonly unknown[] | undefined, b: readonly unknown[] | undefined): boolean;
92
142
 
93
- type KvStoreItem = {
94
- key: string;
95
- value: string;
143
+ type Simplify<T> = {
144
+ [K in keyof T]: T[K];
145
+ } & {};
146
+ type RowOf<Table extends AnyTableBuilder> = Table extends TableBuilder<infer Cols extends TableColumns, any> ? InferRow<Cols> : never;
147
+ type BaseNameOf<CrdtName, Table extends AnyTableBuilder> = string extends Table["~baseName"] ? `_${CrdtName & string}` : [Table["~baseName"]] extends [string] ? Table["~baseName"] : `_${CrdtName & string}`;
148
+ type ClientSchemaOf<Tables extends SyncSchemaTables> = Simplify<{
149
+ [K in keyof Tables]: RowOf<Tables[K]>;
150
+ } & {
151
+ [K in keyof Tables as BaseNameOf<K, Tables[K]>]: ReadonlyTable<RowOf<Tables[K]>>;
152
+ }>;
153
+ type ServerSchemaOf<Tables extends SyncSchemaTables> = Simplify<{
154
+ [K in keyof Tables]: ReadonlyTable<RowOf<Tables[K]>>;
155
+ } & {
156
+ [K in keyof Tables as BaseNameOf<K, Tables[K]>]: ReadonlyTable<RowOf<Tables[K]>>;
157
+ }>;
158
+ type MutationsSchemaOf<Tables extends SyncSchemaTables> = Simplify<{
159
+ [K in keyof Tables as BaseNameOf<K, Tables[K]>]: RowOf<Tables[K]>;
160
+ }>;
161
+ interface DefinedSyncSchema<Tables extends SyncSchemaTables> extends SyncDbSchema<ClientSchemaOf<Tables>, ServerSchemaOf<Tables>, MutationsSchemaOf<Tables>> {
162
+ /** The table builders, for type extraction (`typeof schema.tables.item.$row`) and runtime metadata. */
163
+ tables: Tables;
164
+ }
165
+ type DefineSyncSchemaConfig<Tables extends SyncSchemaTables> = {
166
+ tables: Tables;
167
+ /** Full migration history (including the initial createTable version), built with `createMigrations`. */
168
+ migrations: Migrations;
96
169
  };
97
- declare function createKvStoreTableQuery(schema: SchemaModule, tableName: string): kysely.CreateTableBuilder<string, "key" | "value">;
98
- declare function createSQLiteKvStore({ db, metaTableName }: {
99
- db: InternalSQLiteWrapper<any>;
100
- metaTableName: string;
101
- }): {
102
- get: (key: string) => string | null;
103
- set: (key: string, value: string) => void;
104
- remove: (key: string) => void;
105
- createStringStoredValue: (key: string, defaultValue: string) => StoredValue<string>;
106
- createNumberStoredValue: (key: string, defaultValue: number) => StoredValue<number>;
170
+ /**
171
+ * Define a sync database schema from `t.table()` builders.
172
+ *
173
+ * Record keys are the crdt (view) table names; base table names default to the key
174
+ * prefixed with "_", overridable per table via `t.table(cols, { baseName })`.
175
+ */
176
+ declare function defineSyncSchema<Tables extends SyncSchemaTables>({ tables, migrations, }: DefineSyncSchemaConfig<Tables>): DefinedSyncSchema<Tables>;
177
+
178
+ type NewCrdtEventValidationResult = {
179
+ success: true;
180
+ event: NewCrdtEvent;
181
+ } | {
182
+ success: false;
183
+ errors: string[];
107
184
  };
185
+ declare class CrdtEventValidationError extends Error {
186
+ readonly errors: string[];
187
+ constructor(errors: string[]);
188
+ }
189
+ declare function validateNewCrdtEvent(schema: Pick<SyncDbSchema, "tables" | "tablesConfig">, input: unknown): NewCrdtEventValidationResult;
190
+
191
+ type SchemaVerificationIssue = {
192
+ table: string;
193
+ column?: string;
194
+ message: string;
195
+ };
196
+ /**
197
+ * Verify that replaying the full migration history on a fresh database produces
198
+ * exactly the declared table schema. Creates a throwaway in-memory SQLite db,
199
+ * applies all migrations, introspects the result, and diffs it against the
200
+ * `t.table()` declarations.
201
+ *
202
+ * Returns an empty array when migrations and schema agree. Intended for dev-time
203
+ * checks (`startDbWorker({ verifySchema: true })`) and tests:
204
+ * `expect(await verifySyncSchema(syncDbSchema)).toEqual([])`.
205
+ */
206
+ declare function verifySyncSchema(schema: SyncDbSchema): Promise<SchemaVerificationIssue[]>;
207
+ declare function formatSchemaVerificationIssues(issues: SchemaVerificationIssue[]): string;
108
208
 
109
209
  type CrdtStorageMutator<Database> = ReturnType<typeof createCrdtStorageMutator<Database>>;
110
210
  type CommitEventOptions<Database, Table extends keyof Database & string> = {
@@ -222,6 +322,14 @@ declare function createSyncedDb<Database, Props = undefined>(options: SyncedDbOp
222
322
  }[K]>) => void) => {
223
323
  unsubscribe: () => void;
224
324
  };
325
+ exportData: (opts?: {
326
+ tables?: string[];
327
+ }) => SyncedDbExport;
328
+ importData: (data: SyncedDbExport, opts?: {
329
+ validate?: boolean;
330
+ }) => {
331
+ imported: number;
332
+ };
225
333
  dispose: () => Promise<void>;
226
334
  _internal: {
227
335
  executeAsync: (query: ExecuteParams) => Promise<ExecuteResult<unknown>>;
@@ -238,4 +346,4 @@ declare function createSyncedDb<Database, Props = undefined>(options: SyncedDbOp
238
346
  }>;
239
347
  type SyncedDb<Database> = Awaited<ReturnType<typeof createSyncedDb<Database>>>;
240
348
 
241
- export { CrdtStorage, type CrdtStorageMutator, CrdtTableConfig, ExecuteParams, ExecuteResult, InternalSQLiteWrapper, type KvStoreItem, KyselyQueryFactory, Logger, QueryBuilderOutput, SQLiteDbWrapper, SQLiteReactiveDb, SQLiteTransactionWrapper, type SharedLiveQuery, type SharedLiveQuerySnapshot, StoredValue, SyncDbSchema, type SyncedDb, TypedEvent, WorkerState, createCrdtStorageMutator, createCrdtSyncProducer, createKvStoreTableQuery, createSQLiteKvStore, createSyncedDb, dummyKysely, makeCrdtTable, parametersAreEqual, xxhash };
349
+ export { AnyTableBuilder, CrdtEventValidationError, CrdtStorage, type CrdtStorageMutator, CrdtTableConfig, type DefineSyncSchemaConfig, type DefinedSyncSchema, ExecuteParams, ExecuteResult, InferRow, InternalSQLiteWrapper, type KvStoreItem, KyselyQueryFactory, Logger, Migrations, type NewCrdtEventValidationResult, QueryBuilderOutput, ReadonlyTable, SQLiteDbWrapper, SQLiteReactiveDb, SQLiteTransactionWrapper, type SchemaVerificationIssue, type SharedLiveQuery, type SharedLiveQuerySnapshot, StoredValue, SyncDbSchema, SyncSchemaTables, type SyncedDb, type SyncedDbExport, TableBuilder, TableColumns, TypedEvent, WorkerState, createCrdtStorageMutator, createCrdtSyncProducer, createExportImport, createKvStoreTableQuery, createSQLiteKvStore, createSyncedDb, defineSyncSchema, dummyKysely, formatSchemaVerificationIssues, makeCrdtTable, parametersAreEqual, validateNewCrdtEvent, verifySyncSchema, xxhash };