korajs 0.1.0

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.
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/config.ts
21
+ var config_exports = {};
22
+ __export(config_exports, {
23
+ defineConfig: () => defineConfig
24
+ });
25
+ module.exports = __toCommonJS(config_exports);
26
+ function defineConfig(config) {
27
+ return config;
28
+ }
29
+ // Annotate the CommonJS export names for ESM import in node:
30
+ 0 && (module.exports = {
31
+ defineConfig
32
+ });
33
+ //# sourceMappingURL=config.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config.ts"],"sourcesContent":["/**\n * Kora CLI/runtime configuration shape loaded from `kora.config.*`.\n */\nexport interface KoraUserConfig {\n\t/** Path to the schema file. Defaults to auto-detection in CLI. */\n\tschema?: string\n\tdev?: {\n\t\t/** Vite development server port. */\n\t\tport?: number\n\t\tsync?:\n\t\t\t| boolean\n\t\t\t| {\n\t\t\t\t/** Enable or disable sync server startup in `kora dev`. */\n\t\t\t\tenabled?: boolean\n\t\t\t\t/** Sync server port (also exposed as PORT/KORA_SYNC_PORT env). */\n\t\t\t\tport?: number\n\t\t\t\t/** Sync server store backend for managed mode (without server.ts). */\n\t\t\t\tstore?:\n\t\t\t\t\t| 'memory'\n\t\t\t\t\t| 'sqlite'\n\t\t\t\t\t| 'postgres'\n\t\t\t\t\t| {\n\t\t\t\t\t\ttype: 'memory'\n\t\t\t\t\t}\n\t\t\t\t\t| {\n\t\t\t\t\t\ttype: 'sqlite'\n\t\t\t\t\t\tfilename?: string\n\t\t\t\t\t}\n\t\t\t\t\t| {\n\t\t\t\t\t\ttype: 'postgres'\n\t\t\t\t\t\tconnectionString: string\n\t\t\t\t\t}\n\t\t\t}\n\t\twatch?:\n\t\t\t| boolean\n\t\t\t| {\n\t\t\t\t/** Enable or disable schema watching. */\n\t\t\t\tenabled?: boolean\n\t\t\t\t/** Debounce duration for schema regeneration. */\n\t\t\t\tdebounceMs?: number\n\t\t\t}\n\t}\n}\n\n/**\n * Defines a typed Kora config.\n */\nexport function defineConfig(config: KoraUserConfig): KoraUserConfig {\n\treturn config\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA+CO,SAAS,aAAa,QAAwC;AACpE,SAAO;AACR;","names":[]}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Kora CLI/runtime configuration shape loaded from `kora.config.*`.
3
+ */
4
+ interface KoraUserConfig {
5
+ /** Path to the schema file. Defaults to auto-detection in CLI. */
6
+ schema?: string;
7
+ dev?: {
8
+ /** Vite development server port. */
9
+ port?: number;
10
+ sync?: boolean | {
11
+ /** Enable or disable sync server startup in `kora dev`. */
12
+ enabled?: boolean;
13
+ /** Sync server port (also exposed as PORT/KORA_SYNC_PORT env). */
14
+ port?: number;
15
+ /** Sync server store backend for managed mode (without server.ts). */
16
+ store?: 'memory' | 'sqlite' | 'postgres' | {
17
+ type: 'memory';
18
+ } | {
19
+ type: 'sqlite';
20
+ filename?: string;
21
+ } | {
22
+ type: 'postgres';
23
+ connectionString: string;
24
+ };
25
+ };
26
+ watch?: boolean | {
27
+ /** Enable or disable schema watching. */
28
+ enabled?: boolean;
29
+ /** Debounce duration for schema regeneration. */
30
+ debounceMs?: number;
31
+ };
32
+ };
33
+ }
34
+ /**
35
+ * Defines a typed Kora config.
36
+ */
37
+ declare function defineConfig(config: KoraUserConfig): KoraUserConfig;
38
+
39
+ export { type KoraUserConfig, defineConfig };
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Kora CLI/runtime configuration shape loaded from `kora.config.*`.
3
+ */
4
+ interface KoraUserConfig {
5
+ /** Path to the schema file. Defaults to auto-detection in CLI. */
6
+ schema?: string;
7
+ dev?: {
8
+ /** Vite development server port. */
9
+ port?: number;
10
+ sync?: boolean | {
11
+ /** Enable or disable sync server startup in `kora dev`. */
12
+ enabled?: boolean;
13
+ /** Sync server port (also exposed as PORT/KORA_SYNC_PORT env). */
14
+ port?: number;
15
+ /** Sync server store backend for managed mode (without server.ts). */
16
+ store?: 'memory' | 'sqlite' | 'postgres' | {
17
+ type: 'memory';
18
+ } | {
19
+ type: 'sqlite';
20
+ filename?: string;
21
+ } | {
22
+ type: 'postgres';
23
+ connectionString: string;
24
+ };
25
+ };
26
+ watch?: boolean | {
27
+ /** Enable or disable schema watching. */
28
+ enabled?: boolean;
29
+ /** Debounce duration for schema regeneration. */
30
+ debounceMs?: number;
31
+ };
32
+ };
33
+ }
34
+ /**
35
+ * Defines a typed Kora config.
36
+ */
37
+ declare function defineConfig(config: KoraUserConfig): KoraUserConfig;
38
+
39
+ export { type KoraUserConfig, defineConfig };
package/dist/config.js ADDED
@@ -0,0 +1,8 @@
1
+ // src/config.ts
2
+ function defineConfig(config) {
3
+ return config;
4
+ }
5
+ export {
6
+ defineConfig
7
+ };
8
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config.ts"],"sourcesContent":["/**\n * Kora CLI/runtime configuration shape loaded from `kora.config.*`.\n */\nexport interface KoraUserConfig {\n\t/** Path to the schema file. Defaults to auto-detection in CLI. */\n\tschema?: string\n\tdev?: {\n\t\t/** Vite development server port. */\n\t\tport?: number\n\t\tsync?:\n\t\t\t| boolean\n\t\t\t| {\n\t\t\t\t/** Enable or disable sync server startup in `kora dev`. */\n\t\t\t\tenabled?: boolean\n\t\t\t\t/** Sync server port (also exposed as PORT/KORA_SYNC_PORT env). */\n\t\t\t\tport?: number\n\t\t\t\t/** Sync server store backend for managed mode (without server.ts). */\n\t\t\t\tstore?:\n\t\t\t\t\t| 'memory'\n\t\t\t\t\t| 'sqlite'\n\t\t\t\t\t| 'postgres'\n\t\t\t\t\t| {\n\t\t\t\t\t\ttype: 'memory'\n\t\t\t\t\t}\n\t\t\t\t\t| {\n\t\t\t\t\t\ttype: 'sqlite'\n\t\t\t\t\t\tfilename?: string\n\t\t\t\t\t}\n\t\t\t\t\t| {\n\t\t\t\t\t\ttype: 'postgres'\n\t\t\t\t\t\tconnectionString: string\n\t\t\t\t\t}\n\t\t\t}\n\t\twatch?:\n\t\t\t| boolean\n\t\t\t| {\n\t\t\t\t/** Enable or disable schema watching. */\n\t\t\t\tenabled?: boolean\n\t\t\t\t/** Debounce duration for schema regeneration. */\n\t\t\t\tdebounceMs?: number\n\t\t\t}\n\t}\n}\n\n/**\n * Defines a typed Kora config.\n */\nexport function defineConfig(config: KoraUserConfig): KoraUserConfig {\n\treturn config\n}\n"],"mappings":";AA+CO,SAAS,aAAa,QAAwC;AACpE,SAAO;AACR;","names":[]}
package/dist/index.cjs ADDED
@@ -0,0 +1,470 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ HybridLogicalClock: () => import_core2.HybridLogicalClock,
34
+ KoraError: () => import_core5.KoraError,
35
+ MergeEngine: () => import_merge2.MergeEngine,
36
+ Store: () => import_store2.Store,
37
+ SyncEngine: () => import_sync2.SyncEngine,
38
+ WebSocketTransport: () => import_sync2.WebSocketTransport,
39
+ createApp: () => createApp,
40
+ createOperation: () => import_core4.createOperation,
41
+ defineSchema: () => import_core.defineSchema,
42
+ generateUUIDv7: () => import_core3.generateUUIDv7,
43
+ t: () => import_core.t
44
+ });
45
+ module.exports = __toCommonJS(index_exports);
46
+
47
+ // src/create-app.ts
48
+ var import_internal = require("@korajs/core/internal");
49
+ var import_devtools = require("@korajs/devtools");
50
+ var import_merge = require("@korajs/merge");
51
+ var import_store = require("@korajs/store");
52
+ var import_sync = require("@korajs/sync");
53
+
54
+ // src/adapter-resolver.ts
55
+ function detectAdapterType() {
56
+ if (typeof process !== "undefined" && process.versions?.node) {
57
+ return "better-sqlite3";
58
+ }
59
+ if (typeof globalThis.navigator !== "undefined") {
60
+ if (typeof globalThis.FileSystemHandle !== "undefined") {
61
+ return "sqlite-wasm";
62
+ }
63
+ return "indexeddb";
64
+ }
65
+ return "better-sqlite3";
66
+ }
67
+ async function createAdapter(type, dbName) {
68
+ switch (type) {
69
+ case "better-sqlite3": {
70
+ const { BetterSqlite3Adapter } = await import("@korajs/store/better-sqlite3");
71
+ return new BetterSqlite3Adapter(dbName);
72
+ }
73
+ case "sqlite-wasm": {
74
+ const { SqliteWasmAdapter } = await import("@korajs/store/sqlite-wasm");
75
+ return new SqliteWasmAdapter({ dbName });
76
+ }
77
+ case "indexeddb": {
78
+ const { IndexedDbAdapter } = await import("@korajs/store/indexeddb");
79
+ return new IndexedDbAdapter({ dbName });
80
+ }
81
+ default: {
82
+ const _exhaustive = type;
83
+ throw new Error(`Unknown adapter type: ${_exhaustive}`);
84
+ }
85
+ }
86
+ }
87
+
88
+ // src/merge-aware-sync-store.ts
89
+ var MergeAwareSyncStore = class {
90
+ constructor(store, mergeEngine, emitter) {
91
+ this.store = store;
92
+ this.mergeEngine = mergeEngine;
93
+ this.emitter = emitter;
94
+ }
95
+ store;
96
+ mergeEngine;
97
+ emitter;
98
+ getVersionVector() {
99
+ return this.store.getVersionVector();
100
+ }
101
+ getNodeId() {
102
+ return this.store.getNodeId();
103
+ }
104
+ async getOperationRange(nodeId, fromSeq, toSeq) {
105
+ return this.store.getOperationRange(nodeId, fromSeq, toSeq);
106
+ }
107
+ async applyRemoteOperation(op) {
108
+ if (op.type !== "update" || !op.data || !op.previousData) {
109
+ return this.store.applyRemoteOperation(op);
110
+ }
111
+ const schema = this.store.getSchema();
112
+ const collectionDef = schema.collections[op.collection];
113
+ if (!collectionDef) {
114
+ return this.store.applyRemoteOperation(op);
115
+ }
116
+ const accessor = this.store.collection(op.collection);
117
+ const currentRecord = await accessor.findById(op.recordId);
118
+ if (!currentRecord) {
119
+ return this.store.applyRemoteOperation(op);
120
+ }
121
+ let hasConflict = false;
122
+ for (const field of Object.keys(op.data)) {
123
+ const expectedBase = op.previousData[field];
124
+ const currentLocal = currentRecord[field];
125
+ if (!deepEqual(expectedBase, currentLocal)) {
126
+ hasConflict = true;
127
+ break;
128
+ }
129
+ }
130
+ if (!hasConflict) {
131
+ return this.store.applyRemoteOperation(op);
132
+ }
133
+ this.emitter?.emit({
134
+ type: "merge:started",
135
+ operationA: op,
136
+ operationB: op
137
+ });
138
+ const baseState = { ...op.previousData };
139
+ const localOp = {
140
+ ...op,
141
+ // The "local" operation's data is the diff between base and current local state
142
+ data: buildLocalDiff(op.previousData, currentRecord, Object.keys(op.data)),
143
+ previousData: op.previousData,
144
+ nodeId: this.store.getNodeId()
145
+ };
146
+ const input = {
147
+ local: localOp,
148
+ remote: op,
149
+ baseState,
150
+ collectionDef
151
+ };
152
+ const result = this.mergeEngine.mergeFields(input);
153
+ for (const trace of result.traces) {
154
+ this.emitter?.emit({ type: "merge:conflict", trace });
155
+ }
156
+ const firstTrace = result.traces[0];
157
+ if (firstTrace) {
158
+ this.emitter?.emit({ type: "merge:completed", trace: firstTrace });
159
+ }
160
+ const mergedOp = {
161
+ ...op,
162
+ data: result.mergedData
163
+ };
164
+ return this.store.applyRemoteOperation(mergedOp);
165
+ }
166
+ };
167
+ function buildLocalDiff(baseState, currentRecord, fields) {
168
+ const diff = {};
169
+ for (const field of fields) {
170
+ diff[field] = currentRecord[field];
171
+ }
172
+ return diff;
173
+ }
174
+ function deepEqual(a, b) {
175
+ if (a === b) return true;
176
+ if (a === null || b === null) return false;
177
+ if (a === void 0 || b === void 0) return false;
178
+ if (typeof a !== typeof b) return false;
179
+ if (Array.isArray(a) && Array.isArray(b)) {
180
+ if (a.length !== b.length) return false;
181
+ return a.every((val, i) => deepEqual(val, b[i]));
182
+ }
183
+ if (typeof a === "object" && typeof b === "object") {
184
+ const keysA = Object.keys(a);
185
+ const keysB = Object.keys(b);
186
+ if (keysA.length !== keysB.length) return false;
187
+ return keysA.every(
188
+ (key) => deepEqual(a[key], b[key])
189
+ );
190
+ }
191
+ return false;
192
+ }
193
+
194
+ // src/create-app.ts
195
+ function createApp(config) {
196
+ const emitter = new import_internal.SimpleEventEmitter();
197
+ const mergeEngine = new import_merge.MergeEngine();
198
+ let store = null;
199
+ let syncEngine = null;
200
+ let unsubscribeSync = null;
201
+ let reconnectionManager = null;
202
+ let connectionMonitor = null;
203
+ let instrumenter = null;
204
+ let intentionalDisconnect = false;
205
+ let qualityInterval = null;
206
+ if (config.devtools) {
207
+ instrumenter = new import_devtools.Instrumenter(emitter, {
208
+ bridgeEnabled: typeof globalThis !== "undefined" && "window" in globalThis
209
+ });
210
+ }
211
+ const ready = initializeAsync(config, emitter, mergeEngine).then((result) => {
212
+ store = result.store;
213
+ syncEngine = result.syncEngine;
214
+ unsubscribeSync = result.unsubscribeSync;
215
+ if (config.sync && syncEngine) {
216
+ connectionMonitor = new import_sync.ConnectionMonitor();
217
+ reconnectionManager = new import_sync.ReconnectionManager({
218
+ initialDelay: config.sync.reconnectInterval,
219
+ maxDelay: config.sync.maxReconnectInterval
220
+ });
221
+ emitter.on("sync:sent", () => connectionMonitor?.recordActivity());
222
+ emitter.on("sync:received", () => connectionMonitor?.recordActivity());
223
+ emitter.on("sync:acknowledged", () => connectionMonitor?.recordActivity());
224
+ emitter.on("sync:connected", () => {
225
+ if (qualityInterval !== null) clearInterval(qualityInterval);
226
+ qualityInterval = setInterval(() => {
227
+ if (connectionMonitor) {
228
+ emitter.emit({ type: "connection:quality", quality: connectionMonitor.getQuality() });
229
+ }
230
+ }, 5e3);
231
+ });
232
+ emitter.on("sync:disconnected", () => {
233
+ connectionMonitor?.reset();
234
+ if (qualityInterval !== null) {
235
+ clearInterval(qualityInterval);
236
+ qualityInterval = null;
237
+ }
238
+ });
239
+ if (config.sync.autoReconnect !== false) {
240
+ const engine = syncEngine;
241
+ emitter.on("sync:disconnected", () => {
242
+ if (intentionalDisconnect) return;
243
+ reconnectionManager?.stop();
244
+ reconnectionManager?.start(async () => {
245
+ try {
246
+ await engine.start();
247
+ return true;
248
+ } catch {
249
+ return false;
250
+ }
251
+ });
252
+ });
253
+ }
254
+ }
255
+ });
256
+ const syncControl = config.sync ? {
257
+ async connect() {
258
+ await ready;
259
+ if (syncEngine) {
260
+ intentionalDisconnect = false;
261
+ reconnectionManager?.stop();
262
+ reconnectionManager?.reset();
263
+ await syncEngine.start();
264
+ }
265
+ },
266
+ async disconnect() {
267
+ await ready;
268
+ if (syncEngine) {
269
+ intentionalDisconnect = true;
270
+ reconnectionManager?.stop();
271
+ await syncEngine.stop();
272
+ }
273
+ },
274
+ getStatus() {
275
+ if (syncEngine) {
276
+ return syncEngine.getStatus();
277
+ }
278
+ return { status: "offline", pendingOperations: 0, lastSyncedAt: null };
279
+ }
280
+ } : null;
281
+ const app = {
282
+ ready,
283
+ events: emitter,
284
+ sync: syncControl,
285
+ getStore() {
286
+ if (!store) {
287
+ throw new Error("Store not initialized. Await app.ready before accessing the store.");
288
+ }
289
+ return store;
290
+ },
291
+ getSyncEngine() {
292
+ return syncEngine;
293
+ },
294
+ async close() {
295
+ await ready;
296
+ intentionalDisconnect = true;
297
+ if (qualityInterval !== null) {
298
+ clearInterval(qualityInterval);
299
+ qualityInterval = null;
300
+ }
301
+ reconnectionManager?.stop();
302
+ if (instrumenter) {
303
+ instrumenter.destroy();
304
+ instrumenter = null;
305
+ }
306
+ if (unsubscribeSync) {
307
+ unsubscribeSync();
308
+ unsubscribeSync = null;
309
+ }
310
+ if (syncEngine) {
311
+ await syncEngine.stop();
312
+ syncEngine = null;
313
+ }
314
+ if (store) {
315
+ await store.close();
316
+ store = null;
317
+ }
318
+ emitter.clear();
319
+ }
320
+ };
321
+ for (const collectionName of Object.keys(config.schema.collections)) {
322
+ Object.defineProperty(app, collectionName, {
323
+ get() {
324
+ return createCollectionAccessor(collectionName, () => store);
325
+ },
326
+ enumerable: true,
327
+ configurable: false
328
+ });
329
+ }
330
+ return app;
331
+ }
332
+ async function initializeAsync(config, emitter, mergeEngine) {
333
+ const adapterType = config.store?.adapter ?? detectAdapterType();
334
+ const dbName = config.store?.name ?? "kora-db";
335
+ const adapter = await createAdapter(adapterType, dbName);
336
+ const store = new import_store.Store({
337
+ schema: config.schema,
338
+ adapter,
339
+ emitter
340
+ });
341
+ await store.open();
342
+ let syncEngine = null;
343
+ let unsubscribeSync = null;
344
+ if (config.sync) {
345
+ const transport = new import_sync.WebSocketTransport();
346
+ const mergeAwareStore = new MergeAwareSyncStore(store, mergeEngine, emitter);
347
+ syncEngine = new import_sync.SyncEngine({
348
+ transport,
349
+ store: mergeAwareStore,
350
+ config: {
351
+ url: config.sync.url,
352
+ transport: config.sync.transport,
353
+ auth: config.sync.auth,
354
+ batchSize: config.sync.batchSize,
355
+ schemaVersion: config.sync.schemaVersion ?? config.schema.version
356
+ },
357
+ emitter
358
+ });
359
+ unsubscribeSync = emitter.on("operation:created", (event) => {
360
+ if (syncEngine) {
361
+ syncEngine.pushOperation(event.operation);
362
+ }
363
+ });
364
+ }
365
+ return { store, syncEngine, unsubscribeSync };
366
+ }
367
+ function createCollectionAccessor(collectionName, getStore) {
368
+ return {
369
+ async insert(data) {
370
+ const currentStore = getStore();
371
+ if (!currentStore) {
372
+ throw new Error(`Cannot mutate collection "${collectionName}" before app.ready resolves.`);
373
+ }
374
+ return currentStore.collection(collectionName).insert(data);
375
+ },
376
+ async findById(id) {
377
+ const currentStore = getStore();
378
+ if (!currentStore) return null;
379
+ return currentStore.collection(collectionName).findById(id);
380
+ },
381
+ async update(id, data) {
382
+ const currentStore = getStore();
383
+ if (!currentStore) {
384
+ throw new Error(`Cannot mutate collection "${collectionName}" before app.ready resolves.`);
385
+ }
386
+ return currentStore.collection(collectionName).update(id, data);
387
+ },
388
+ async delete(id) {
389
+ const currentStore = getStore();
390
+ if (!currentStore) {
391
+ throw new Error(`Cannot mutate collection "${collectionName}" before app.ready resolves.`);
392
+ }
393
+ return currentStore.collection(collectionName).delete(id);
394
+ },
395
+ where(conditions) {
396
+ const currentStore = getStore();
397
+ if (!currentStore) {
398
+ return createPendingQueryBuilder(conditions);
399
+ }
400
+ return currentStore.collection(collectionName).where(conditions);
401
+ }
402
+ };
403
+ }
404
+ function createPendingQueryBuilder(initialWhere) {
405
+ const descriptor = {
406
+ collection: "__pending__",
407
+ where: { ...initialWhere },
408
+ orderBy: [],
409
+ limit: void 0,
410
+ offset: void 0
411
+ };
412
+ const builder = {
413
+ where(conditions) {
414
+ descriptor.where = { ...descriptor.where, ...conditions };
415
+ return this;
416
+ },
417
+ orderBy(field, direction = "asc") {
418
+ descriptor.orderBy.push({ field, direction });
419
+ return this;
420
+ },
421
+ limit(n) {
422
+ descriptor.limit = n;
423
+ return this;
424
+ },
425
+ offset(n) {
426
+ descriptor.offset = n;
427
+ return this;
428
+ },
429
+ async exec() {
430
+ return [];
431
+ },
432
+ async count() {
433
+ return 0;
434
+ },
435
+ subscribe(callback) {
436
+ void callback([]);
437
+ return () => {
438
+ };
439
+ },
440
+ getDescriptor() {
441
+ return { ...descriptor, where: { ...descriptor.where }, orderBy: [...descriptor.orderBy] };
442
+ }
443
+ };
444
+ return builder;
445
+ }
446
+
447
+ // src/index.ts
448
+ var import_core = require("@korajs/core");
449
+ var import_core2 = require("@korajs/core");
450
+ var import_core3 = require("@korajs/core");
451
+ var import_core4 = require("@korajs/core");
452
+ var import_core5 = require("@korajs/core");
453
+ var import_store2 = require("@korajs/store");
454
+ var import_merge2 = require("@korajs/merge");
455
+ var import_sync2 = require("@korajs/sync");
456
+ // Annotate the CommonJS export names for ESM import in node:
457
+ 0 && (module.exports = {
458
+ HybridLogicalClock,
459
+ KoraError,
460
+ MergeEngine,
461
+ Store,
462
+ SyncEngine,
463
+ WebSocketTransport,
464
+ createApp,
465
+ createOperation,
466
+ defineSchema,
467
+ generateUUIDv7,
468
+ t
469
+ });
470
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/create-app.ts","../src/adapter-resolver.ts","../src/merge-aware-sync-store.ts"],"sourcesContent":["// kora — meta-package re-exporting core, store, merge, sync\n// This is the primary entry point for `import { createApp, defineSchema, t } from 'korajs'`\n\n// === createApp factory ===\nexport { createApp } from './create-app'\n\n// === App types ===\nexport type {\n\tAdapterType,\n\tKoraApp,\n\tKoraConfig,\n\tStoreOptions,\n\tSyncControl,\n\tSyncOptions,\n\tTypedCollectionAccessor,\n\tTypedKoraApp,\n\tTypedKoraConfig,\n} from './types'\n\n// === @korajs/core re-exports ===\nexport { defineSchema, t } from '@korajs/core'\nexport { HybridLogicalClock } from '@korajs/core'\nexport { generateUUIDv7 } from '@korajs/core'\nexport { createOperation } from '@korajs/core'\nexport { KoraError } from '@korajs/core'\nexport type {\n\tCollectionDefinition,\n\tConnectionQuality,\n\tConstraint,\n\tFieldDescriptor,\n\tFieldKindToType,\n\tHLCTimestamp,\n\tInferFieldType,\n\tInferInsertInput,\n\tInferRecord,\n\tInferUpdateInput,\n\tKoraEvent,\n\tKoraEventEmitter,\n\tKoraEventListener,\n\tKoraEventType,\n\tMergeStrategy,\n\tMergeTrace,\n\tOperation,\n\tSchemaDefinition,\n\tSchemaInput,\n\tTypedSchemaDefinition,\n\tVersionVector,\n} from '@korajs/core'\n\n// === @korajs/store re-exports ===\nexport { Store } from '@korajs/store'\nexport type {\n\tCollectionAccessor,\n\tCollectionRecord,\n\tStorageAdapter,\n\tStoreConfig,\n} from '@korajs/store'\n\n// === @korajs/merge re-exports ===\nexport { MergeEngine } from '@korajs/merge'\nexport type { MergeInput, MergeResult } from '@korajs/merge'\n\n// === @korajs/sync re-exports ===\nexport { SyncEngine, WebSocketTransport } from '@korajs/sync'\nexport type {\n\tSyncConfig,\n\tSyncState,\n\tSyncStatus,\n\tSyncStatusInfo,\n\tSyncStore,\n} from '@korajs/sync'\n","import type { KoraEventEmitter, Operation, SchemaInput } from '@korajs/core'\nimport { SimpleEventEmitter } from '@korajs/core/internal'\nimport { Instrumenter } from '@korajs/devtools'\nimport { MergeEngine } from '@korajs/merge'\nimport { Store } from '@korajs/store'\nimport type { CollectionAccessor, StorageAdapter } from '@korajs/store'\nimport type { QueryBuilder } from '@korajs/store'\nimport { ConnectionMonitor, ReconnectionManager, SyncEngine, WebSocketTransport } from '@korajs/sync'\nimport type { SyncStatusInfo } from '@korajs/sync'\nimport { createAdapter, detectAdapterType } from './adapter-resolver'\nimport { MergeAwareSyncStore } from './merge-aware-sync-store'\nimport type { KoraApp, KoraConfig, SyncControl, TypedKoraApp, TypedKoraConfig } from './types'\n\n/**\n * Creates a new Kora application instance.\n *\n * Wires together store, merge engine, event emitter, and optionally sync\n * into a single developer-facing `KoraApp` object. Collection accessors\n * (e.g. `app.todos`) are defined as properties for immediate use after `await app.ready`.\n *\n * @param config - Application configuration including schema and optional sync settings\n * @returns A KoraApp instance with reactive collections ready for use\n *\n * @example\n * ```typescript\n * const app = createApp({\n * schema: defineSchema({\n * version: 1,\n * collections: {\n * todos: {\n * fields: {\n * title: t.string(),\n * completed: t.boolean().default(false)\n * }\n * }\n * }\n * })\n * })\n *\n * await app.ready\n * const todo = await app.todos.insert({ title: 'Hello' })\n * ```\n */\n/**\n * Creates a new typed Kora application instance.\n * When the schema is created with `defineSchema()`, full type inference flows through\n * to collection accessors, providing autocomplete and type checking for all CRUD operations.\n */\nexport function createApp<const S extends SchemaInput>(config: TypedKoraConfig<S>): TypedKoraApp<S>\n/**\n * Creates a new Kora application instance (untyped fallback).\n */\nexport function createApp(config: KoraConfig): KoraApp\nexport function createApp(config: KoraConfig): KoraApp {\n\tconst emitter: KoraEventEmitter & { clear(): void } = new SimpleEventEmitter()\n\tconst mergeEngine = new MergeEngine()\n\n\tlet store: Store | null = null\n\tlet syncEngine: SyncEngine | null = null\n\tlet unsubscribeSync: (() => void) | null = null\n\tlet reconnectionManager: ReconnectionManager | null = null\n\tlet connectionMonitor: ConnectionMonitor | null = null\n\tlet instrumenter: Instrumenter | null = null\n\tlet intentionalDisconnect = false\n\tlet qualityInterval: ReturnType<typeof setInterval> | null = null\n\n\t// Wire DevTools instrumentation immediately (emitter exists synchronously)\n\tif (config.devtools) {\n\t\tinstrumenter = new Instrumenter(emitter, {\n\t\t\tbridgeEnabled: typeof globalThis !== 'undefined' && 'window' in globalThis,\n\t\t})\n\t}\n\n\t// Build the ready promise — resolves when the store is open and wired\n\tconst ready = initializeAsync(config, emitter, mergeEngine).then((result) => {\n\t\tstore = result.store\n\t\tsyncEngine = result.syncEngine\n\t\tunsubscribeSync = result.unsubscribeSync\n\n\t\t// Wire reconnection and connection quality after sync engine is ready\n\t\tif (config.sync && syncEngine) {\n\t\t\tconnectionMonitor = new ConnectionMonitor()\n\t\t\treconnectionManager = new ReconnectionManager({\n\t\t\t\tinitialDelay: config.sync.reconnectInterval,\n\t\t\t\tmaxDelay: config.sync.maxReconnectInterval,\n\t\t\t})\n\n\t\t\t// Track activity for connection quality\n\t\t\temitter.on('sync:sent', () => connectionMonitor?.recordActivity())\n\t\t\temitter.on('sync:received', () => connectionMonitor?.recordActivity())\n\t\t\temitter.on('sync:acknowledged', () => connectionMonitor?.recordActivity())\n\n\t\t\t// Emit quality on timer while connected\n\t\t\temitter.on('sync:connected', () => {\n\t\t\t\tif (qualityInterval !== null) clearInterval(qualityInterval)\n\t\t\t\tqualityInterval = setInterval(() => {\n\t\t\t\t\tif (connectionMonitor) {\n\t\t\t\t\t\temitter.emit({ type: 'connection:quality', quality: connectionMonitor.getQuality() })\n\t\t\t\t\t}\n\t\t\t\t}, 5000)\n\t\t\t})\n\n\t\t\t// Reset monitor and clear timer on disconnect\n\t\t\temitter.on('sync:disconnected', () => {\n\t\t\t\tconnectionMonitor?.reset()\n\t\t\t\tif (qualityInterval !== null) {\n\t\t\t\t\tclearInterval(qualityInterval)\n\t\t\t\t\tqualityInterval = null\n\t\t\t\t}\n\t\t\t})\n\n\t\t\t// Auto-reconnect on unexpected disconnect\n\t\t\tif (config.sync.autoReconnect !== false) {\n\t\t\t\tconst engine = syncEngine\n\t\t\t\temitter.on('sync:disconnected', () => {\n\t\t\t\t\tif (intentionalDisconnect) return\n\t\t\t\t\t// Guard: stop any in-progress reconnection before starting a new one\n\t\t\t\t\treconnectionManager?.stop()\n\t\t\t\t\treconnectionManager?.start(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait engine.start()\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\treturn false\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t})\n\n\t// Build sync control\n\tconst syncControl: SyncControl | null = config.sync\n\t\t? {\n\t\t\t\tasync connect(): Promise<void> {\n\t\t\t\t\tawait ready\n\t\t\t\t\tif (syncEngine) {\n\t\t\t\t\t\tintentionalDisconnect = false\n\t\t\t\t\t\treconnectionManager?.stop()\n\t\t\t\t\t\treconnectionManager?.reset()\n\t\t\t\t\t\tawait syncEngine.start()\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tasync disconnect(): Promise<void> {\n\t\t\t\t\tawait ready\n\t\t\t\t\tif (syncEngine) {\n\t\t\t\t\t\tintentionalDisconnect = true\n\t\t\t\t\t\treconnectionManager?.stop()\n\t\t\t\t\t\tawait syncEngine.stop()\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tgetStatus(): SyncStatusInfo {\n\t\t\t\t\tif (syncEngine) {\n\t\t\t\t\t\treturn syncEngine.getStatus()\n\t\t\t\t\t}\n\t\t\t\t\treturn { status: 'offline', pendingOperations: 0, lastSyncedAt: null }\n\t\t\t\t},\n\t\t\t}\n\t\t: null\n\n\t// Build the KoraApp object\n\tconst app: KoraApp = {\n\t\tready,\n\t\tevents: emitter,\n\t\tsync: syncControl,\n\t\tgetStore(): Store {\n\t\t\tif (!store) {\n\t\t\t\tthrow new Error('Store not initialized. Await app.ready before accessing the store.')\n\t\t\t}\n\t\t\treturn store\n\t\t},\n\t\tgetSyncEngine(): SyncEngine | null {\n\t\t\treturn syncEngine\n\t\t},\n\t\tasync close(): Promise<void> {\n\t\t\tawait ready\n\t\t\tintentionalDisconnect = true\n\t\t\tif (qualityInterval !== null) {\n\t\t\t\tclearInterval(qualityInterval)\n\t\t\t\tqualityInterval = null\n\t\t\t}\n\t\t\treconnectionManager?.stop()\n\t\t\tif (instrumenter) {\n\t\t\t\tinstrumenter.destroy()\n\t\t\t\tinstrumenter = null\n\t\t\t}\n\t\t\tif (unsubscribeSync) {\n\t\t\t\tunsubscribeSync()\n\t\t\t\tunsubscribeSync = null\n\t\t\t}\n\t\t\tif (syncEngine) {\n\t\t\t\tawait syncEngine.stop()\n\t\t\t\tsyncEngine = null\n\t\t\t}\n\t\t\tif (store) {\n\t\t\t\tawait store.close()\n\t\t\t\tstore = null\n\t\t\t}\n\t\t\temitter.clear()\n\t\t},\n\t}\n\n\t// Define collection accessors via Object.defineProperty.\n\t// Before ready resolves, query methods return empty results.\n\tfor (const collectionName of Object.keys(config.schema.collections)) {\n\t\tObject.defineProperty(app, collectionName, {\n\t\t\tget(): CollectionAccessor {\n\t\t\t\treturn createCollectionAccessor(collectionName, () => store)\n\t\t\t},\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t})\n\t}\n\n\treturn app\n}\n\n/**\n * Asynchronous initialization: create adapter, open store, wire sync.\n */\nasync function initializeAsync(\n\tconfig: KoraConfig,\n\temitter: KoraEventEmitter,\n\tmergeEngine: MergeEngine,\n): Promise<{\n\tstore: Store\n\tsyncEngine: SyncEngine | null\n\tunsubscribeSync: (() => void) | null\n}> {\n\t// Resolve adapter\n\tconst adapterType = config.store?.adapter ?? detectAdapterType()\n\tconst dbName = config.store?.name ?? 'kora-db'\n\tconst adapter: StorageAdapter = await createAdapter(adapterType, dbName)\n\n\t// Create and open the store\n\tconst store = new Store({\n\t\tschema: config.schema,\n\t\tadapter,\n\t\temitter,\n\t})\n\tawait store.open()\n\n\t// Wire sync if configured\n\tlet syncEngine: SyncEngine | null = null\n\tlet unsubscribeSync: (() => void) | null = null\n\n\tif (config.sync) {\n\t\tconst transport = new WebSocketTransport()\n\t\tconst mergeAwareStore = new MergeAwareSyncStore(store, mergeEngine, emitter)\n\n\t\tsyncEngine = new SyncEngine({\n\t\t\ttransport,\n\t\t\tstore: mergeAwareStore,\n\t\t\tconfig: {\n\t\t\t\turl: config.sync.url,\n\t\t\t\ttransport: config.sync.transport,\n\t\t\t\tauth: config.sync.auth,\n\t\t\t\tbatchSize: config.sync.batchSize,\n\t\t\t\tschemaVersion: config.sync.schemaVersion ?? config.schema.version,\n\t\t\t},\n\t\t\temitter,\n\t\t})\n\n\t\t// Wire local mutations → sync outbound queue\n\t\tunsubscribeSync = emitter.on('operation:created', (event) => {\n\t\t\tif (syncEngine) {\n\t\t\t\tsyncEngine.pushOperation(event.operation)\n\t\t\t}\n\t\t})\n\t}\n\n\treturn { store, syncEngine, unsubscribeSync }\n}\n\nfunction createCollectionAccessor(\n\tcollectionName: string,\n\tgetStore: () => Store | null,\n): CollectionAccessor {\n\treturn {\n\t\tasync insert(data: Record<string, unknown>) {\n\t\t\tconst currentStore = getStore()\n\t\t\tif (!currentStore) {\n\t\t\t\tthrow new Error(`Cannot mutate collection \"${collectionName}\" before app.ready resolves.`)\n\t\t\t}\n\t\t\treturn currentStore.collection(collectionName).insert(data)\n\t\t},\n\t\tasync findById(id: string) {\n\t\t\tconst currentStore = getStore()\n\t\t\tif (!currentStore) return null\n\t\t\treturn currentStore.collection(collectionName).findById(id)\n\t\t},\n\t\tasync update(id: string, data: Record<string, unknown>) {\n\t\t\tconst currentStore = getStore()\n\t\t\tif (!currentStore) {\n\t\t\t\tthrow new Error(`Cannot mutate collection \"${collectionName}\" before app.ready resolves.`)\n\t\t\t}\n\t\t\treturn currentStore.collection(collectionName).update(id, data)\n\t\t},\n\t\tasync delete(id: string) {\n\t\t\tconst currentStore = getStore()\n\t\t\tif (!currentStore) {\n\t\t\t\tthrow new Error(`Cannot mutate collection \"${collectionName}\" before app.ready resolves.`)\n\t\t\t}\n\t\t\treturn currentStore.collection(collectionName).delete(id)\n\t\t},\n\t\twhere(conditions: Record<string, unknown>) {\n\t\t\tconst currentStore = getStore()\n\t\t\tif (!currentStore) {\n\t\t\t\treturn createPendingQueryBuilder(conditions)\n\t\t\t}\n\t\t\treturn currentStore.collection(collectionName).where(conditions)\n\t\t},\n\t}\n}\n\nfunction createPendingQueryBuilder(initialWhere: Record<string, unknown>): QueryBuilder {\n\tconst descriptor = {\n\t\tcollection: '__pending__',\n\t\twhere: { ...initialWhere },\n\t\torderBy: [] as Array<{ field: string; direction: 'asc' | 'desc' }>,\n\t\tlimit: undefined as number | undefined,\n\t\toffset: undefined as number | undefined,\n\t}\n\n\tconst builder = {\n\t\twhere(conditions: Record<string, unknown>) {\n\t\t\tdescriptor.where = { ...descriptor.where, ...conditions }\n\t\t\treturn this\n\t\t},\n\t\torderBy(field: string, direction: 'asc' | 'desc' = 'asc') {\n\t\t\tdescriptor.orderBy.push({ field, direction })\n\t\t\treturn this\n\t\t},\n\t\tlimit(n: number) {\n\t\t\tdescriptor.limit = n\n\t\t\treturn this\n\t\t},\n\t\toffset(n: number) {\n\t\t\tdescriptor.offset = n\n\t\t\treturn this\n\t\t},\n\t\tasync exec() {\n\t\t\treturn []\n\t\t},\n\t\tasync count() {\n\t\t\treturn 0\n\t\t},\n\t\tsubscribe(callback: (results: Array<Record<string, unknown>>) => void) {\n\t\t\tvoid callback([])\n\t\t\treturn () => {}\n\t\t},\n\t\tgetDescriptor() {\n\t\t\treturn { ...descriptor, where: { ...descriptor.where }, orderBy: [...descriptor.orderBy] }\n\t\t},\n\t}\n\n\treturn builder as unknown as QueryBuilder\n}\n","import type { StorageAdapter } from '@korajs/store'\nimport type { AdapterType } from './types'\n\n/**\n * Detect the best storage adapter for the current environment.\n *\n * - Node.js: 'better-sqlite3'\n * - Browser with OPFS: 'sqlite-wasm'\n * - Browser without OPFS: 'indexeddb'\n */\nexport function detectAdapterType(): AdapterType {\n\t// Node.js environment\n\tif (typeof process !== 'undefined' && process.versions?.node) {\n\t\treturn 'better-sqlite3'\n\t}\n\n\t// Browser environment\n\tif (typeof globalThis.navigator !== 'undefined') {\n\t\t// Check for OPFS support (FileSystemHandle indicates OPFS availability)\n\t\tif (typeof (globalThis as Record<string, unknown>).FileSystemHandle !== 'undefined') {\n\t\t\treturn 'sqlite-wasm'\n\t\t}\n\t\treturn 'indexeddb'\n\t}\n\n\t// Default fallback (e.g., Deno, Bun, or other runtimes)\n\treturn 'better-sqlite3'\n}\n\n/**\n * Create a StorageAdapter for the given adapter type.\n * Uses dynamic imports so unused adapters are not bundled.\n *\n * @param type - The adapter type to create\n * @param dbName - Database name (used by all adapters)\n * @returns A configured StorageAdapter instance\n */\nexport async function createAdapter(type: AdapterType, dbName: string): Promise<StorageAdapter> {\n\tswitch (type) {\n\t\tcase 'better-sqlite3': {\n\t\t\tconst { BetterSqlite3Adapter } = await import('@korajs/store/better-sqlite3')\n\t\t\treturn new BetterSqlite3Adapter(dbName)\n\t\t}\n\t\tcase 'sqlite-wasm': {\n\t\t\tconst { SqliteWasmAdapter } = await import('@korajs/store/sqlite-wasm')\n\t\t\treturn new SqliteWasmAdapter({ dbName })\n\t\t}\n\t\tcase 'indexeddb': {\n\t\t\tconst { IndexedDbAdapter } = await import('@korajs/store/indexeddb')\n\t\t\treturn new IndexedDbAdapter({ dbName })\n\t\t}\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = type\n\t\t\tthrow new Error(`Unknown adapter type: ${_exhaustive}`)\n\t\t}\n\t}\n}\n","import type { KoraEventEmitter, Operation, VersionVector } from '@korajs/core'\nimport type { MergeEngine, MergeInput } from '@korajs/merge'\nimport type { Store } from '@korajs/store'\nimport type { ApplyResult, SyncStore } from '@korajs/sync'\n\n/**\n * Wraps a Store to interpose merge resolution before applying remote operations.\n *\n * For inserts and deletes, delegates directly to the underlying Store.\n * For updates, checks whether the remote operation's previousData conflicts\n * with the current local state. If so, runs MergeEngine to resolve and\n * applies the merged result instead.\n *\n * This keeps MergeEngine integration out of Store and SyncEngine internals.\n */\nexport class MergeAwareSyncStore implements SyncStore {\n\tconstructor(\n\t\tprivate readonly store: Store,\n\t\tprivate readonly mergeEngine: MergeEngine,\n\t\tprivate readonly emitter: KoraEventEmitter | null,\n\t) {}\n\n\tgetVersionVector(): VersionVector {\n\t\treturn this.store.getVersionVector()\n\t}\n\n\tgetNodeId(): string {\n\t\treturn this.store.getNodeId()\n\t}\n\n\tasync getOperationRange(nodeId: string, fromSeq: number, toSeq: number): Promise<Operation[]> {\n\t\treturn this.store.getOperationRange(nodeId, fromSeq, toSeq)\n\t}\n\n\tasync applyRemoteOperation(op: Operation): Promise<ApplyResult> {\n\t\t// Only intercept updates that have previousData (needed for 3-way merge)\n\t\tif (op.type !== 'update' || !op.data || !op.previousData) {\n\t\t\treturn this.store.applyRemoteOperation(op)\n\t\t}\n\n\t\t// Look up current local record to detect conflicts\n\t\tconst schema = this.store.getSchema()\n\t\tconst collectionDef = schema.collections[op.collection]\n\t\tif (!collectionDef) {\n\t\t\treturn this.store.applyRemoteOperation(op)\n\t\t}\n\n\t\tconst accessor = this.store.collection(op.collection)\n\t\tconst currentRecord = await accessor.findById(op.recordId)\n\n\t\t// If record doesn't exist locally, delegate directly\n\t\tif (!currentRecord) {\n\t\t\treturn this.store.applyRemoteOperation(op)\n\t\t}\n\n\t\t// Check for conflicts: do any of the remote op's changed fields differ\n\t\t// from what the remote op expected them to be (previousData)?\n\t\tlet hasConflict = false\n\t\tfor (const field of Object.keys(op.data)) {\n\t\t\tconst expectedBase = op.previousData[field]\n\t\t\tconst currentLocal = currentRecord[field]\n\n\t\t\t// If the local state doesn't match what the remote expected,\n\t\t\t// it means the local side also changed this field — conflict.\n\t\t\tif (!deepEqual(expectedBase, currentLocal)) {\n\t\t\t\thasConflict = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// No conflict: safe to apply directly\n\t\tif (!hasConflict) {\n\t\t\treturn this.store.applyRemoteOperation(op)\n\t\t}\n\n\t\t// Conflict detected — run merge engine\n\t\t// Build a synthetic \"local operation\" representing the current local state changes\n\t\t// relative to the same base the remote operation used.\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'merge:started',\n\t\t\toperationA: op,\n\t\t\toperationB: op,\n\t\t})\n\n\t\tconst baseState: Record<string, unknown> = { ...op.previousData }\n\t\tconst localOp: Operation = {\n\t\t\t...op,\n\t\t\t// The \"local\" operation's data is the diff between base and current local state\n\t\t\tdata: buildLocalDiff(op.previousData, currentRecord, Object.keys(op.data)),\n\t\t\tpreviousData: op.previousData,\n\t\t\tnodeId: this.store.getNodeId(),\n\t\t}\n\n\t\tconst input: MergeInput = {\n\t\t\tlocal: localOp,\n\t\t\tremote: op,\n\t\t\tbaseState,\n\t\t\tcollectionDef,\n\t\t}\n\n\t\tconst result = this.mergeEngine.mergeFields(input)\n\n\t\t// Emit merge traces\n\t\tfor (const trace of result.traces) {\n\t\t\tthis.emitter?.emit({ type: 'merge:conflict', trace })\n\t\t}\n\t\tconst firstTrace = result.traces[0]\n\t\tif (firstTrace) {\n\t\t\tthis.emitter?.emit({ type: 'merge:completed', trace: firstTrace })\n\t\t}\n\n\t\t// Create a modified operation with the merged data to apply\n\t\tconst mergedOp: Operation = {\n\t\t\t...op,\n\t\t\tdata: result.mergedData,\n\t\t}\n\n\t\treturn this.store.applyRemoteOperation(mergedOp)\n\t}\n}\n\n/**\n * Build the local diff: for each field the remote op changed,\n * extract the current local value (which may differ from both base and remote).\n */\nfunction buildLocalDiff(\n\tbaseState: Record<string, unknown>,\n\tcurrentRecord: Record<string, unknown>,\n\tfields: string[],\n): Record<string, unknown> {\n\tconst diff: Record<string, unknown> = {}\n\tfor (const field of fields) {\n\t\tdiff[field] = currentRecord[field]\n\t}\n\treturn diff\n}\n\n/**\n * Simple deep equality check for comparing field values.\n * Handles primitives, arrays, and plain objects.\n */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n\tif (a === b) return true\n\tif (a === null || b === null) return false\n\tif (a === undefined || b === undefined) return false\n\tif (typeof a !== typeof b) return false\n\n\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\tif (a.length !== b.length) return false\n\t\treturn a.every((val, i) => deepEqual(val, b[i]))\n\t}\n\n\tif (typeof a === 'object' && typeof b === 'object') {\n\t\tconst keysA = Object.keys(a as Record<string, unknown>)\n\t\tconst keysB = Object.keys(b as Record<string, unknown>)\n\t\tif (keysA.length !== keysB.length) return false\n\t\treturn keysA.every((key) =>\n\t\t\tdeepEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n\t\t)\n\t}\n\n\treturn false\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,sBAAmC;AACnC,sBAA6B;AAC7B,mBAA4B;AAC5B,mBAAsB;AAGtB,kBAAuF;;;ACGhF,SAAS,oBAAiC;AAEhD,MAAI,OAAO,YAAY,eAAe,QAAQ,UAAU,MAAM;AAC7D,WAAO;AAAA,EACR;AAGA,MAAI,OAAO,WAAW,cAAc,aAAa;AAEhD,QAAI,OAAQ,WAAuC,qBAAqB,aAAa;AACpF,aAAO;AAAA,IACR;AACA,WAAO;AAAA,EACR;AAGA,SAAO;AACR;AAUA,eAAsB,cAAc,MAAmB,QAAyC;AAC/F,UAAQ,MAAM;AAAA,IACb,KAAK,kBAAkB;AACtB,YAAM,EAAE,qBAAqB,IAAI,MAAM,OAAO,8BAA8B;AAC5E,aAAO,IAAI,qBAAqB,MAAM;AAAA,IACvC;AAAA,IACA,KAAK,eAAe;AACnB,YAAM,EAAE,kBAAkB,IAAI,MAAM,OAAO,2BAA2B;AACtE,aAAO,IAAI,kBAAkB,EAAE,OAAO,CAAC;AAAA,IACxC;AAAA,IACA,KAAK,aAAa;AACjB,YAAM,EAAE,iBAAiB,IAAI,MAAM,OAAO,yBAAyB;AACnE,aAAO,IAAI,iBAAiB,EAAE,OAAO,CAAC;AAAA,IACvC;AAAA,IACA,SAAS;AACR,YAAM,cAAqB;AAC3B,YAAM,IAA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