@neetru/sdk 1.2.0 → 2.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +284 -244
  2. package/README.md +194 -194
  3. package/dist/auth.cjs +3740 -345
  4. package/dist/auth.cjs.map +1 -1
  5. package/dist/auth.d.cts +5 -1
  6. package/dist/auth.d.ts +5 -1
  7. package/dist/auth.mjs +3740 -345
  8. package/dist/auth.mjs.map +1 -1
  9. package/dist/catalog.cjs.map +1 -1
  10. package/dist/catalog.d.cts +5 -1
  11. package/dist/catalog.d.ts +5 -1
  12. package/dist/catalog.mjs.map +1 -1
  13. package/dist/checkout.cjs.map +1 -1
  14. package/dist/checkout.d.cts +5 -1
  15. package/dist/checkout.d.ts +5 -1
  16. package/dist/checkout.mjs.map +1 -1
  17. package/dist/collection-ref-BBvTTXoG.d.cts +423 -0
  18. package/dist/collection-ref-BBvTTXoG.d.ts +423 -0
  19. package/dist/db-react.cjs +136 -0
  20. package/dist/db-react.cjs.map +1 -0
  21. package/dist/db-react.d.cts +99 -0
  22. package/dist/db-react.d.ts +99 -0
  23. package/dist/db-react.mjs +112 -0
  24. package/dist/db-react.mjs.map +1 -0
  25. package/dist/db.cjs +3599 -131
  26. package/dist/db.cjs.map +1 -1
  27. package/dist/db.d.cts +5 -8
  28. package/dist/db.d.ts +5 -8
  29. package/dist/db.mjs +3596 -131
  30. package/dist/db.mjs.map +1 -1
  31. package/dist/entitlements.cjs.map +1 -1
  32. package/dist/entitlements.d.cts +5 -1
  33. package/dist/entitlements.d.ts +5 -1
  34. package/dist/entitlements.mjs.map +1 -1
  35. package/dist/errors.cjs.map +1 -1
  36. package/dist/errors.mjs.map +1 -1
  37. package/dist/index.cjs +3957 -342
  38. package/dist/index.cjs.map +1 -1
  39. package/dist/index.d.cts +13 -6
  40. package/dist/index.d.ts +13 -6
  41. package/dist/index.mjs +3877 -263
  42. package/dist/index.mjs.map +1 -1
  43. package/dist/mocks.cjs +183 -7
  44. package/dist/mocks.cjs.map +1 -1
  45. package/dist/mocks.d.cts +18 -5
  46. package/dist/mocks.d.ts +18 -5
  47. package/dist/mocks.mjs +183 -7
  48. package/dist/mocks.mjs.map +1 -1
  49. package/dist/notifications.cjs.map +1 -1
  50. package/dist/notifications.d.cts +5 -1
  51. package/dist/notifications.d.ts +5 -1
  52. package/dist/notifications.mjs.map +1 -1
  53. package/dist/react.cjs.map +1 -1
  54. package/dist/react.d.cts +5 -1
  55. package/dist/react.d.ts +5 -1
  56. package/dist/react.mjs.map +1 -1
  57. package/dist/support.cjs.map +1 -1
  58. package/dist/support.d.cts +5 -1
  59. package/dist/support.d.ts +5 -1
  60. package/dist/support.mjs.map +1 -1
  61. package/dist/telemetry.cjs.map +1 -1
  62. package/dist/telemetry.d.cts +5 -1
  63. package/dist/telemetry.d.ts +5 -1
  64. package/dist/telemetry.mjs.map +1 -1
  65. package/dist/types-B1jylbMC.d.ts +1364 -0
  66. package/dist/types-Kmt4y1FQ.d.cts +1364 -0
  67. package/dist/usage.cjs.map +1 -1
  68. package/dist/usage.d.cts +5 -1
  69. package/dist/usage.d.ts +5 -1
  70. package/dist/usage.mjs.map +1 -1
  71. package/dist/webhooks.cjs.map +1 -1
  72. package/dist/webhooks.d.cts +5 -1
  73. package/dist/webhooks.d.ts +5 -1
  74. package/dist/webhooks.mjs.map +1 -1
  75. package/package.json +133 -111
  76. package/dist/types-CQAfwqUS.d.cts +0 -654
  77. package/dist/types-CQAfwqUS.d.ts +0 -654
package/dist/db.cjs CHANGED
@@ -1,27 +1,48 @@
1
1
  'use strict';
2
2
 
3
+ var idb = require('idb');
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
13
+ var __esm = (fn, res) => function __init() {
14
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
15
+ };
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+
3
21
  // src/errors.ts
4
- var NeetruError = class _NeetruError extends Error {
5
- code;
6
- status;
7
- requestId;
8
- constructor(code, message, status, requestId) {
9
- super(message);
10
- this.name = "NeetruError";
11
- this.code = code;
12
- this.status = status;
13
- this.requestId = requestId;
14
- Object.setPrototypeOf(this, _NeetruError.prototype);
22
+ var NeetruError;
23
+ var init_errors = __esm({
24
+ "src/errors.ts"() {
25
+ NeetruError = class _NeetruError extends Error {
26
+ code;
27
+ status;
28
+ requestId;
29
+ constructor(code, message, status, requestId) {
30
+ super(message);
31
+ this.name = "NeetruError";
32
+ this.code = code;
33
+ this.status = status;
34
+ this.requestId = requestId;
35
+ Object.setPrototypeOf(this, _NeetruError.prototype);
36
+ }
37
+ };
15
38
  }
16
- };
39
+ });
17
40
 
18
41
  // src/http.ts
19
- var DEFAULT_RETRIES = 2;
20
- var RETRYABLE_CODES = /* @__PURE__ */ new Set([
21
- "rate_limited",
22
- "server_error",
23
- "network_error"
24
- ]);
42
+ var http_exports = {};
43
+ __export(http_exports, {
44
+ httpRequest: () => httpRequest
45
+ });
25
46
  function backoffMs(attempt) {
26
47
  const base = 200 * Math.pow(4, attempt);
27
48
  const jitter = base * 0.2 * (Math.random() * 2 - 1);
@@ -128,7 +149,7 @@ async function httpRequest(config, opts) {
128
149
  }
129
150
  const err = new NeetruError(code, message, res.status, requestId);
130
151
  lastError = err;
131
- const isRetryable = RETRYABLE_CODES.has(code);
152
+ const isRetryable = RETRYABLE_CODES2.has(code);
132
153
  if (isRetryable && attempt < maxRetries) {
133
154
  const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
134
155
  const delay = retryAfter ?? backoffMs(attempt);
@@ -139,139 +160,3586 @@ async function httpRequest(config, opts) {
139
160
  }
140
161
  throw lastError ?? new NeetruError("unknown", "unexpected httpRequest exit");
141
162
  }
163
+ var DEFAULT_RETRIES, RETRYABLE_CODES2;
164
+ var init_http = __esm({
165
+ "src/http.ts"() {
166
+ init_errors();
167
+ DEFAULT_RETRIES = 2;
168
+ RETRYABLE_CODES2 = /* @__PURE__ */ new Set([
169
+ "rate_limited",
170
+ "server_error",
171
+ "network_error"
172
+ ]);
173
+ }
174
+ });
142
175
 
143
- // src/db.ts
144
- var COLL_RE = /^[a-z0-9][a-z0-9_-]{0,62}$/;
145
- function assertValidCollection(name) {
146
- if (!COLL_RE.test(name)) {
147
- throw new NeetruError(
148
- "validation_failed",
149
- `Invalid collection name: "${name}". Must match ${COLL_RE}.`
150
- );
176
+ // src/db-errors.ts
177
+ init_errors();
178
+ var RETRYABLE_CODES = /* @__PURE__ */ new Set([
179
+ "db_unavailable",
180
+ "db_conflict",
181
+ "db_timeout"
182
+ ]);
183
+ var NeetruDbError = class _NeetruDbError extends NeetruError {
184
+ /** Código de erro fechado — específico de DB. */
185
+ code;
186
+ /**
187
+ * `true` para erros transientes que o produto pode tentar novamente.
188
+ * São retryable: `db_unavailable`, `db_conflict`, `db_timeout`.
189
+ */
190
+ retryable;
191
+ /**
192
+ * ID opaco do banco lógico — só para correlação com logs do Core.
193
+ * Nunca deve ser exibido ao usuário final.
194
+ */
195
+ dbId;
196
+ constructor(code, message, dbId) {
197
+ super(code, message);
198
+ this.name = "NeetruDbError";
199
+ this.code = code;
200
+ this.retryable = RETRYABLE_CODES.has(code);
201
+ this.dbId = dbId;
202
+ Object.setPrototypeOf(this, _NeetruDbError.prototype);
151
203
  }
204
+ };
205
+
206
+ // src/db/offline/query-engine.ts
207
+ function typeRank(v) {
208
+ if (v === null || v === void 0) return 0;
209
+ if (typeof v === "number") return 1;
210
+ if (typeof v === "string") return 2;
211
+ if (typeof v === "boolean") return 3;
212
+ return 4;
152
213
  }
153
- function serializeWhere(filter) {
154
- const { field, op, value } = filter;
155
- if (op === "in") {
156
- if (!Array.isArray(value)) {
157
- throw new NeetruError(
158
- "validation_failed",
159
- `where op="in" requer value array (recebido: ${typeof value})`
214
+ function compareValues(a, b) {
215
+ const ra = typeRank(a);
216
+ const rb = typeRank(b);
217
+ if (ra !== rb) return ra - rb;
218
+ if (a === null || a === void 0) return 0;
219
+ if (typeof a === "number" && typeof b === "number") return a - b;
220
+ if (typeof a === "string" && typeof b === "string") return a < b ? -1 : a > b ? 1 : 0;
221
+ if (typeof a === "boolean" && typeof b === "boolean") return a === b ? 0 : a ? 1 : -1;
222
+ const sa = String(a);
223
+ const sb = String(b);
224
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
225
+ }
226
+ function getField(data, field) {
227
+ const parts = field.split(".");
228
+ let current = data;
229
+ for (const part of parts) {
230
+ if (current === null || current === void 0 || typeof current !== "object") {
231
+ return void 0;
232
+ }
233
+ current = current[part];
234
+ }
235
+ return current;
236
+ }
237
+ function evaluateFilter(data, filter) {
238
+ const fieldValue = getField(data, filter.field);
239
+ if (fieldValue === void 0) return false;
240
+ const { op, value } = filter;
241
+ switch (op) {
242
+ case "==":
243
+ return fieldValue === value;
244
+ case "!=":
245
+ return fieldValue !== value;
246
+ case "<":
247
+ return compareValues(fieldValue, value) < 0;
248
+ case "<=":
249
+ return compareValues(fieldValue, value) <= 0;
250
+ case ">":
251
+ return compareValues(fieldValue, value) > 0;
252
+ case ">=":
253
+ return compareValues(fieldValue, value) >= 0;
254
+ case "array-contains":
255
+ return Array.isArray(fieldValue) && fieldValue.includes(value);
256
+ case "in":
257
+ if (!Array.isArray(value)) return false;
258
+ return value.includes(fieldValue);
259
+ case "not-in":
260
+ if (!Array.isArray(value)) return true;
261
+ return !value.includes(fieldValue);
262
+ default:
263
+ return false;
264
+ }
265
+ }
266
+ function matchesAllFilters(data, filters) {
267
+ return filters.every((f) => evaluateFilter(data, f));
268
+ }
269
+ function buildComparator(orderBy) {
270
+ return (a, b) => {
271
+ if (orderBy) {
272
+ const aVal = getField(a.data, orderBy.field);
273
+ const bVal = getField(b.data, orderBy.field);
274
+ const cmp = compareValues(aVal, bVal);
275
+ if (cmp !== 0) {
276
+ return orderBy.direction === "desc" ? -cmp : cmp;
277
+ }
278
+ }
279
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
280
+ };
281
+ }
282
+ function applyCursor(sorted, cursor) {
283
+ const idx = sorted.findIndex((d) => d.id === cursor.docId);
284
+ if (idx === -1) {
285
+ return sorted;
286
+ }
287
+ if (cursor.type === "startAfter") {
288
+ return sorted.slice(idx + 1);
289
+ } else {
290
+ return sorted.slice(0, idx);
291
+ }
292
+ }
293
+ var QueryEngine = class _QueryEngine {
294
+ /**
295
+ * Avalia um `QueryDescriptor` contra um array de `OfflineDoc`.
296
+ *
297
+ * Pipeline (I3 §5.3):
298
+ * 1. Filtra docs com `deleted:false`.
299
+ * 2. Aplica `where` (AND de todos os filtros).
300
+ * 3. Ordena por `orderBy` + tie-break por docId.
301
+ * 4. Aplica cursor (`startAfter` / `endBefore`).
302
+ * 5. Corta em `limit`.
303
+ */
304
+ evaluate(docs, query) {
305
+ let filtered = docs.filter((d) => !d.meta.deleted);
306
+ const filters = query.where ?? [];
307
+ if (filters.length > 0) {
308
+ filtered = filtered.filter(
309
+ (d) => matchesAllFilters(d.data, filters)
160
310
  );
161
311
  }
162
- return `${field}:in:${value.map((v) => String(v)).join(",")}`;
312
+ const comparator = buildComparator(query.orderBy);
313
+ const sorted = [...filtered].sort(comparator);
314
+ const afterCursor = query.cursor ? applyCursor(sorted, query.cursor) : sorted;
315
+ const limitN = Math.min(query.limit ?? 20, 500);
316
+ const limited = afterCursor.slice(0, limitN);
317
+ return {
318
+ docs: limited.map((d) => ({ id: d.id, data: d.data })),
319
+ // `incomplete` é sempre true aqui — o QueryEngine não sabe se o cache
320
+ // tem todos os docs da coleção. É responsabilidade do chamador (LocalStore)
321
+ // injetar o flag de completude baseado nos metadados do query_cache.
322
+ incomplete: true
323
+ };
324
+ }
325
+ // ─── Static helper ─────────────────────────────────────────────────────────
326
+ /**
327
+ * Helper estático para uso sem instanciar a classe.
328
+ * Equivalente a `new QueryEngine().evaluate(docs, query)`.
329
+ */
330
+ static evaluate(docs, query) {
331
+ return new _QueryEngine().evaluate(docs, query);
332
+ }
333
+ };
334
+
335
+ // src/db/offline/local-store.ts
336
+ var SCHEMA_VERSION = 1;
337
+ var STORE_DOCUMENTS = "documents";
338
+ var STORE_MUTATIONS = "mutations";
339
+ var STORE_QUERY_CACHE = "query_cache";
340
+ var STORE_SYNC_META = "sync_meta";
341
+ var STORE_CONFLICT_LOG = "conflict_log";
342
+ var LocalStore = class {
343
+ db = null;
344
+ dbName;
345
+ constructor(dbName) {
346
+ this.dbName = dbName;
347
+ }
348
+ // ─── Ciclo de vida ──────────────────────────────────────────────────────────
349
+ /**
350
+ * Abre (ou reabre) o banco IndexedDB e executa o upgrade de schema se necessário.
351
+ * Idempotente — chamadas subsequentes são no-ops se o banco já está aberto.
352
+ */
353
+ async open() {
354
+ if (this.db !== null) return;
355
+ this.db = await idb.openDB(this.dbName, SCHEMA_VERSION, {
356
+ upgrade(db) {
357
+ if (!db.objectStoreNames.contains(STORE_DOCUMENTS)) {
358
+ const docsStore = db.createObjectStore(STORE_DOCUMENTS, {
359
+ keyPath: ["collection", "id"]
360
+ });
361
+ docsStore.createIndex("by_collection", "collection");
362
+ docsStore.createIndex("by_collection_state", ["collection", "meta.state"]);
363
+ docsStore.createIndex("by_updatedAtServer", "meta.updatedAtServer");
364
+ }
365
+ if (!db.objectStoreNames.contains(STORE_MUTATIONS)) {
366
+ const mutStore = db.createObjectStore(STORE_MUTATIONS, {
367
+ keyPath: "mutationId"
368
+ });
369
+ mutStore.createIndex("by_seq", "seq");
370
+ mutStore.createIndex("by_status", "status");
371
+ mutStore.createIndex("by_doc", ["collection", "docId"]);
372
+ mutStore.createIndex("by_batch", "batchId");
373
+ }
374
+ if (!db.objectStoreNames.contains(STORE_QUERY_CACHE)) {
375
+ db.createObjectStore(STORE_QUERY_CACHE, { keyPath: "queryHash" });
376
+ }
377
+ if (!db.objectStoreNames.contains(STORE_SYNC_META)) {
378
+ db.createObjectStore(STORE_SYNC_META, { keyPath: "key" });
379
+ }
380
+ if (!db.objectStoreNames.contains(STORE_CONFLICT_LOG)) {
381
+ const conflictStore = db.createObjectStore(STORE_CONFLICT_LOG, {
382
+ keyPath: "id",
383
+ autoIncrement: true
384
+ });
385
+ conflictStore.createIndex("by_delivered", "delivered");
386
+ conflictStore.createIndex("by_doc", ["collection", "docId"]);
387
+ }
388
+ }
389
+ });
390
+ }
391
+ /** Fecha o banco IndexedDB. */
392
+ async close() {
393
+ this.db?.close();
394
+ this.db = null;
395
+ }
396
+ assertOpen() {
397
+ if (this.db === null) {
398
+ throw new Error("LocalStore: banco n\xE3o est\xE1 aberto. Chame open() primeiro.");
399
+ }
400
+ return this.db;
401
+ }
402
+ // ─── Documents ──────────────────────────────────────────────────────────────
403
+ /**
404
+ * Retorna um documento pelo [collection, id], ou `null` se não existir.
405
+ * Retorna tombstones (deleted: true) — o chamador decide se deve mostrá-los.
406
+ */
407
+ async getDoc(collection, id) {
408
+ const db = this.assertOpen();
409
+ const result = await db.get(STORE_DOCUMENTS, [collection, id]);
410
+ return result ?? null;
411
+ }
412
+ /**
413
+ * Insere ou atualiza um documento na store `documents`.
414
+ * O documento é identificado pelo keyPath composto `[collection, id]`.
415
+ */
416
+ async putDoc(doc) {
417
+ const db = this.assertOpen();
418
+ await db.put(STORE_DOCUMENTS, doc);
419
+ }
420
+ /**
421
+ * Marca um documento como tombstone (`deleted: true`).
422
+ * Não remove fisicamente — o tombstone é necessário para reconciliação.
423
+ * No-op se o documento não existir.
424
+ */
425
+ async deleteDoc(collection, id) {
426
+ const db = this.assertOpen();
427
+ const existing = await db.get(STORE_DOCUMENTS, [collection, id]);
428
+ if (!existing) return;
429
+ await db.put(STORE_DOCUMENTS, {
430
+ ...existing,
431
+ meta: {
432
+ ...existing.meta,
433
+ deleted: true,
434
+ updatedAtLocal: Date.now()
435
+ }
436
+ });
437
+ }
438
+ /**
439
+ * Lista documentos de uma coleção, aplicando o QueryDescriptor via QueryEngine.
440
+ *
441
+ * I3 §5.3: a listagem lê todos os docs da coleção pelo índice `by_collection`
442
+ * e delega a filtragem/ordenação/paginação ao QueryEngine (que opera em memória).
443
+ */
444
+ async listDocs(collection, query) {
445
+ const db = this.assertOpen();
446
+ const rawDocs = await db.getAllFromIndex(STORE_DOCUMENTS, "by_collection", collection);
447
+ return QueryEngine.evaluate(rawDocs, query);
448
+ }
449
+ // ─── Sync meta (key-value) ──────────────────────────────────────────────────
450
+ /**
451
+ * Retorna o valor de uma chave da store `sync_meta`, ou `null` se não existir.
452
+ *
453
+ * Chaves conhecidas (I3 §3.3):
454
+ * 'lastSyncWatermark', 'resumeToken:<col>', 'schemaVersion',
455
+ * 'lastFullResyncAt', 'leaderTabId'.
456
+ */
457
+ async getMeta(key) {
458
+ const db = this.assertOpen();
459
+ const entry = await db.get(STORE_SYNC_META, key);
460
+ if (!entry) return null;
461
+ return entry.value;
462
+ }
463
+ /**
464
+ * Armazena ou atualiza um valor na store `sync_meta`.
465
+ */
466
+ async setMeta(key, value) {
467
+ const db = this.assertOpen();
468
+ await db.put(STORE_SYNC_META, { key, value });
469
+ }
470
+ // ─── Conflict log ───────────────────────────────────────────────────────────
471
+ /**
472
+ * Adiciona um registro de conflito ao `conflict_log`.
473
+ * O `id` é autoIncrement — não deve ser fornecido pelo chamador.
474
+ */
475
+ async appendConflict(record) {
476
+ const db = this.assertOpen();
477
+ const id = await db.add(STORE_CONFLICT_LOG, record);
478
+ return { ...record, id };
479
+ }
480
+ /**
481
+ * Lista registros do `conflict_log`.
482
+ * Filtra por `delivered` se a opção for fornecida.
483
+ */
484
+ async listConflicts(options) {
485
+ const db = this.assertOpen();
486
+ const all = await db.getAll(STORE_CONFLICT_LOG);
487
+ if (options?.delivered !== void 0) {
488
+ return all.filter((r) => r.delivered === options.delivered);
489
+ }
490
+ return all;
491
+ }
492
+ /**
493
+ * Marca um registro do `conflict_log` como entregue ao produto.
494
+ */
495
+ async markConflictDelivered(id) {
496
+ const db = this.assertOpen();
497
+ const existing = await db.get(STORE_CONFLICT_LOG, id);
498
+ if (!existing) return;
499
+ await db.put(STORE_CONFLICT_LOG, { ...existing, delivered: true });
500
+ }
501
+ // ─── Mutations (acessores usados pelo MutationQueue) ────────────────────────
502
+ /**
503
+ * Insere ou atualiza uma mutação na store `mutations`.
504
+ * Key: `mutationId`.
505
+ */
506
+ async putMutation(mutation) {
507
+ const db = this.assertOpen();
508
+ await db.put(STORE_MUTATIONS, mutation);
509
+ }
510
+ /**
511
+ * Retorna uma mutação pelo `mutationId`, ou `null` se não existir.
512
+ */
513
+ async getMutation(mutationId) {
514
+ const db = this.assertOpen();
515
+ const result = await db.get(STORE_MUTATIONS, mutationId);
516
+ return result ?? null;
517
+ }
518
+ /**
519
+ * Lista mutações com filtros opcionais.
520
+ * Resultado ordenado por `seq` crescente.
521
+ */
522
+ async listMutations(options) {
523
+ const db = this.assertOpen();
524
+ let mutations;
525
+ if (options?.status !== void 0) {
526
+ mutations = await db.getAllFromIndex(STORE_MUTATIONS, "by_status", options.status);
527
+ } else if (options?.collection !== void 0 && options.docId !== void 0) {
528
+ mutations = await db.getAllFromIndex(STORE_MUTATIONS, "by_doc", [options.collection, options.docId]);
529
+ } else {
530
+ mutations = await db.getAllFromIndex(STORE_MUTATIONS, "by_seq");
531
+ }
532
+ return mutations.sort((a, b) => a.seq - b.seq);
533
+ }
534
+ /**
535
+ * Remove uma mutação pelo `mutationId`.
536
+ * No-op se não existir.
537
+ */
538
+ async deleteMutation(mutationId) {
539
+ const db = this.assertOpen();
540
+ await db.delete(STORE_MUTATIONS, mutationId);
541
+ }
542
+ // ─── Collection discovery ────────────────────────────────────────────────────
543
+ /**
544
+ * Retorna a lista de coleções únicas presentes na store `documents`.
545
+ *
546
+ * Usado pelo SyncEngine no full resync para descobrir coleções cujos docs
547
+ * precisam ser verificados contra a resposta do servidor (tombstone detection).
548
+ *
549
+ * Implementação: itera o índice `by_collection` com `openKeyCursor` para
550
+ * coletar os valores únicos de forma eficiente (sem carregar os docs completos).
551
+ */
552
+ async listCollections() {
553
+ const db = this.assertOpen();
554
+ const allDocs = await db.getAllFromIndex(STORE_DOCUMENTS, "by_collection");
555
+ const collections = /* @__PURE__ */ new Set();
556
+ for (const doc of allDocs) {
557
+ collections.add(doc.collection);
558
+ }
559
+ return Array.from(collections);
560
+ }
561
+ // ─── Query cache ─────────────────────────────────────────────────────────────
562
+ /**
563
+ * Retorna a entrada de `query_cache` para um hash de query, ou `null`.
564
+ */
565
+ async getQueryCache(queryHash) {
566
+ const db = this.assertOpen();
567
+ const result = await db.get(STORE_QUERY_CACHE, queryHash);
568
+ return result ?? null;
163
569
  }
164
- return `${field}:${op}:${String(value)}`;
570
+ /**
571
+ * Insere ou atualiza uma entrada de `query_cache`.
572
+ */
573
+ async putQueryCache(entry) {
574
+ const db = this.assertOpen();
575
+ await db.put(STORE_QUERY_CACHE, entry);
576
+ }
577
+ /**
578
+ * Remove uma entrada de `query_cache` pelo queryHash.
579
+ */
580
+ async deleteQueryCache(queryHash) {
581
+ const db = this.assertOpen();
582
+ await db.delete(STORE_QUERY_CACHE, queryHash);
583
+ }
584
+ };
585
+
586
+ // src/db/offline/mutation-queue.ts
587
+ function generateUUIDv4() {
588
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
589
+ return crypto.randomUUID();
590
+ }
591
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
592
+ const r = Math.random() * 16 | 0;
593
+ const v = c === "x" ? r : r & 3 | 8;
594
+ return v.toString(16);
595
+ });
165
596
  }
166
- function createDbNamespace(config) {
167
- return {
168
- collection(name) {
169
- assertValidCollection(name);
170
- const headers = {};
171
- if (config.tenantId) headers["x-neetru-tenant"] = config.tenantId;
597
+ var MutationQueue = class {
598
+ store;
599
+ /**
600
+ * Ponteiro de sequência local.
601
+ * Inicializado com 0 — o primeiro enqueue sincroniza o valor real do banco
602
+ * (`_syncSeq`), garantindo que nunca sobreponha um seq existente.
603
+ */
604
+ seqCounter = 0;
605
+ seqSynced = false;
606
+ constructor(store) {
607
+ this.store = store;
608
+ }
609
+ // ─── Seq management ─────────────────────────────────────────────────────────
610
+ /**
611
+ * Sincroniza o ponteiro de seq com o maior seq existente no banco.
612
+ * Chamado lazy no primeiro enqueue.
613
+ */
614
+ async syncSeq() {
615
+ if (this.seqSynced) return;
616
+ const all = await this.store.listMutations();
617
+ if (all.length > 0) {
618
+ const maxSeq = Math.max(...all.map((m) => m.seq));
619
+ this.seqCounter = maxSeq;
620
+ }
621
+ this.seqSynced = true;
622
+ }
623
+ nextSeq() {
624
+ this.seqCounter += 1;
625
+ return this.seqCounter;
626
+ }
627
+ // ─── Coalescing ─────────────────────────────────────────────────────────────
628
+ /**
629
+ * Tenta coalescir `newOp`/`newPayload` com a mutação existente `existing`.
630
+ *
631
+ * Regras de coalescing (I3 §4.4):
632
+ * - update + update → update com merge dos campos (segundo vence nos conflitos)
633
+ * - add + update → add com campos mesclados
634
+ * - add + remove → nada (remove a mutação existente, retorna null para remove)
635
+ * - set + update → set com campos mesclados
636
+ * - any + remove (base servidor) → remove
637
+ *
638
+ * Retorna:
639
+ * - `{ coalesced: Mutation }` — substitui a mutação existente (update in-place)
640
+ * - `{ removed: true }` — a mutação existente deve ser deletada (add+remove)
641
+ * - `null` — não é possível coalescir
642
+ */
643
+ tryCoalesce(existing, newOp, newPayload, newBatchId) {
644
+ if (existing.batchId !== newBatchId) return null;
645
+ if (existing.status === "inflight") return null;
646
+ const existingOp = existing.op;
647
+ if (existingOp === "add" && newOp === "remove") {
648
+ return { removed: true };
649
+ }
650
+ if (existingOp === "update" && newOp === "update") {
172
651
  return {
173
- async list(opts) {
174
- let path = `/api/sdk/v1/datastore/${name}`;
175
- const params = new URLSearchParams();
176
- if (opts?.limit !== void 0) params.set("limit", String(opts.limit));
177
- if (opts?.where && opts.where.length > 0) {
178
- for (const f of opts.where) {
179
- params.append("where", serializeWhere(f));
180
- }
181
- }
182
- if (config.tenantId) params.set("tenantId", config.tenantId);
183
- const qs = params.toString();
184
- if (qs) path += `?${qs}`;
185
- const raw = await httpRequest(config, {
186
- method: "GET",
187
- path,
188
- requireAuth: true,
189
- headers
190
- });
191
- if (!raw || !Array.isArray(raw.items)) {
192
- throw new NeetruError(
193
- "invalid_response",
194
- "datastore.list missing items[]"
195
- );
196
- }
197
- return raw.items;
198
- },
199
- async get(id) {
200
- if (!id || typeof id !== "string") {
201
- throw new NeetruError("validation_failed", "id required");
652
+ coalesced: {
653
+ ...existing,
654
+ payload: { ...existing.payload ?? {}, ...newPayload ?? {} }
655
+ }
656
+ };
657
+ }
658
+ if (existingOp === "add" && newOp === "update") {
659
+ return {
660
+ coalesced: {
661
+ ...existing,
662
+ op: "add",
663
+ payload: { ...existing.payload ?? {}, ...newPayload ?? {} }
664
+ }
665
+ };
666
+ }
667
+ if (existingOp === "set" && newOp === "update") {
668
+ return {
669
+ coalesced: {
670
+ ...existing,
671
+ op: "set",
672
+ payload: { ...existing.payload ?? {}, ...newPayload ?? {} }
673
+ }
674
+ };
675
+ }
676
+ if (newOp === "remove") {
677
+ return {
678
+ coalesced: {
679
+ ...existing,
680
+ op: "remove",
681
+ payload: null
682
+ }
683
+ };
684
+ }
685
+ return null;
686
+ }
687
+ // ─── Enqueue ─────────────────────────────────────────────────────────────────
688
+ /**
689
+ * Enfileira uma nova mutação.
690
+ *
691
+ * Processo (I3 §4.1):
692
+ * 1. Gera docId se op=add e não fornecido.
693
+ * 2. Sincroniza seq (lazy).
694
+ * 3. Tenta coalescir com a última mutação queued do mesmo [collection, docId].
695
+ * 4. Se coalescing:
696
+ * - `removed` → deleta mutação existente; retorna sem enfileirar nova.
697
+ * - `coalesced` → substitui a mutação existente (mesmo seq, mesmo mutationId).
698
+ * 5. Se não coalesce → enfileira nova mutação (novo seq, novo mutationId).
699
+ *
700
+ * Atômico: a persistência final é uma única operação putMutation.
701
+ */
702
+ async enqueue(params) {
703
+ const { collection, op, payload, baseVersion, batchId } = params;
704
+ const docId = params.docId ?? (op === "add" ? generateUUIDv4() : "");
705
+ await this.syncSeq();
706
+ const existingMutations = await this.store.listMutations({ collection, docId });
707
+ const lastQueued = existingMutations.filter((m) => m.status === "queued").sort((a, b) => b.seq - a.seq)[0];
708
+ if (lastQueued !== void 0) {
709
+ const coalesceResult = this.tryCoalesce(lastQueued, op, payload, batchId);
710
+ if (coalesceResult !== null) {
711
+ if ("removed" in coalesceResult) {
712
+ await this.store.deleteMutation(lastQueued.mutationId);
713
+ const phantomMut = {
714
+ seq: lastQueued.seq,
715
+ mutationId: generateUUIDv4(),
716
+ collection,
717
+ docId,
718
+ op: "remove",
719
+ payload: null,
720
+ baseVersion,
721
+ enqueuedAt: Date.now(),
722
+ attempts: 0,
723
+ lastError: null,
724
+ status: "queued",
725
+ batchId
726
+ };
727
+ return phantomMut;
728
+ }
729
+ const { coalesced } = coalesceResult;
730
+ await this.store.putMutation(coalesced);
731
+ return coalesced;
732
+ }
733
+ }
734
+ const seq = this.nextSeq();
735
+ const mutation = {
736
+ seq,
737
+ mutationId: generateUUIDv4(),
738
+ collection,
739
+ docId,
740
+ op,
741
+ payload,
742
+ baseVersion,
743
+ enqueuedAt: Date.now(),
744
+ attempts: 0,
745
+ lastError: null,
746
+ status: "queued",
747
+ batchId
748
+ };
749
+ await this.store.putMutation(mutation);
750
+ return mutation;
751
+ }
752
+ // ─── Leitura da fila ─────────────────────────────────────────────────────────
753
+ /**
754
+ * Retorna a primeira mutação com status `queued` (menor seq), ou `null`.
755
+ */
756
+ async peek() {
757
+ const pending = await this.listPending();
758
+ return pending[0] ?? null;
759
+ }
760
+ /**
761
+ * Retorna todas as mutações com status `queued`, ordenadas por seq crescente.
762
+ */
763
+ async listPending() {
764
+ return this.store.listMutations({ status: "queued" });
765
+ }
766
+ /**
767
+ * Retorna TODAS as mutações (qualquer status), ordenadas por seq crescente.
768
+ * Útil para inspeção e testes.
769
+ */
770
+ async listAll() {
771
+ return this.store.listMutations();
772
+ }
773
+ /**
774
+ * Conta o número de mutações com status `queued`.
775
+ */
776
+ async countPending() {
777
+ const pending = await this.listPending();
778
+ return pending.length;
779
+ }
780
+ /**
781
+ * Retorna um lote de mutações `queued` para drenagem (I3 §6.2 FASE 1).
782
+ * Ordena por seq crescente. O SyncEngine chama drain(), itera, e marca
783
+ * cada mutação como applied/failed.
784
+ */
785
+ async drain(options) {
786
+ const pending = await this.listPending();
787
+ if (options?.maxBatch !== void 0 && options.maxBatch > 0) {
788
+ return pending.slice(0, options.maxBatch);
789
+ }
790
+ return pending;
791
+ }
792
+ // ─── Ciclo de vida de mutações ────────────────────────────────────────────────
793
+ /**
794
+ * Marca uma mutação como `inflight` (está sendo enviada ao Core).
795
+ * Chamado pelo SyncEngine antes de enviar o request.
796
+ */
797
+ async markInflight(mutationId) {
798
+ const mut = await this.store.getMutation(mutationId);
799
+ if (!mut) return;
800
+ await this.store.putMutation({ ...mut, status: "inflight" });
801
+ }
802
+ /**
803
+ * Remove a mutação da fila (sucesso de replay).
804
+ * Chamado pelo SyncEngine ao receber confirmação do Core.
805
+ */
806
+ async markApplied(mutationId) {
807
+ await this.store.deleteMutation(mutationId);
808
+ }
809
+ /**
810
+ * Marca uma mutação como `failed` e registra o erro.
811
+ * Incrementa `attempts`. Chamado pelo SyncEngine em falha permanente.
812
+ */
813
+ async markFailed(mutationId, error) {
814
+ const mut = await this.store.getMutation(mutationId);
815
+ if (!mut) return;
816
+ await this.store.putMutation({
817
+ ...mut,
818
+ status: "failed",
819
+ lastError: error,
820
+ attempts: mut.attempts + 1
821
+ });
822
+ }
823
+ /**
824
+ * Incrementa `attempts` e volta para `queued` (falha transiente com backoff).
825
+ * Chamado pelo SyncEngine em falha transiente (5xx, timeout).
826
+ */
827
+ async markRetry(mutationId, error) {
828
+ const mut = await this.store.getMutation(mutationId);
829
+ if (!mut) return;
830
+ await this.store.putMutation({
831
+ ...mut,
832
+ status: "queued",
833
+ lastError: error,
834
+ attempts: mut.attempts + 1
835
+ });
836
+ }
837
+ };
838
+
839
+ // src/db/offline/sync-engine.ts
840
+ var SyncEngine = class {
841
+ _store;
842
+ _queue;
843
+ _resolver;
844
+ _bus;
845
+ _transport;
846
+ _tabCoordinator;
847
+ _connectivity;
848
+ /** `true` se um sync está atualmente em progresso — guarda re-entrância. */
849
+ _syncing = false;
850
+ /** `true` se destroy() foi chamado. */
851
+ _destroyed = false;
852
+ /**
853
+ * Conjunto de coleções "conhecidas" pelo engine.
854
+ * Populado ao aplicar docs do servidor (Fase 1 e 2) e ao ler do cache.
855
+ * Persiste em sync_meta['activeCollections'] para sobreviver a reloads.
856
+ */
857
+ _activeCollections = /* @__PURE__ */ new Set();
858
+ /** Estado de sync atual (fonte de verdade em RAM). */
859
+ _state;
860
+ /** Listeners de mudança de SyncState. */
861
+ _stateListeners = /* @__PURE__ */ new Set();
862
+ /** Cleanup functions dos listeners externos. */
863
+ _cleanups = [];
864
+ /** Timer de resync periódico. */
865
+ _periodicTimer = null;
866
+ constructor(opts) {
867
+ this._store = opts.store;
868
+ this._queue = opts.queue;
869
+ this._resolver = opts.resolver;
870
+ this._bus = opts.bus;
871
+ this._transport = opts.transport;
872
+ this._tabCoordinator = opts.tabCoordinator;
873
+ this._connectivity = opts.connectivity;
874
+ this._state = this._buildInitialState();
875
+ this._wireListeners();
876
+ const intervalMs = opts.periodicSyncIntervalMs ?? 5 * 60 * 1e3;
877
+ if (intervalMs > 0) {
878
+ this._periodicTimer = setInterval(() => {
879
+ this._triggerSync("periodic");
880
+ }, intervalMs);
881
+ }
882
+ }
883
+ // ─── API pública ─────────────────────────────────────────────────────────────
884
+ /**
885
+ * Expõe o transporte de sync para acesso direto por `DbCollectionRefImpl`.
886
+ * Necessário para que `onSnapshot` possa chamar `subscribeCollection` no
887
+ * transport nosql-vm (HIGH-1 fix — realtime deltas).
888
+ */
889
+ get transport() {
890
+ return this._transport;
891
+ }
892
+ /**
893
+ * Retorna o estado de sync atual (snapshot síncrono).
894
+ * Equivale a `client.db.syncState` na API pública do SDK (I3 §10.3).
895
+ *
896
+ * `pendingWrites` reflete o valor mais recente calculado de forma assíncrona.
897
+ * Para garantir o valor mais atualizado, aguarde `refreshPendingWrites()` antes.
898
+ */
899
+ getSyncState() {
900
+ return { ...this._state };
901
+ }
902
+ /**
903
+ * Força a atualização de `pendingWrites` e retorna o estado atualizado.
904
+ * Útil quando o chamador precisa do pendingWrites fresco sem aguardar um sync.
905
+ */
906
+ async refreshPendingWrites() {
907
+ await this._refreshPendingWrites();
908
+ return { ...this._state };
909
+ }
910
+ /**
911
+ * Registra um listener de mudanças no SyncState.
912
+ * Retorna uma função de unsubscribe.
913
+ */
914
+ onSyncStateChange(cb) {
915
+ this._stateListeners.add(cb);
916
+ return () => {
917
+ this._stateListeners.delete(cb);
918
+ };
919
+ }
920
+ /**
921
+ * Força um sync imediato (I3 §10.3 `flush()`).
922
+ * Resolve quando a fila esvazia OU rejeita se o engine estiver destruído.
923
+ */
924
+ async flush() {
925
+ if (this._destroyed) return;
926
+ await this.sync();
927
+ }
928
+ /**
929
+ * Executa as 3 fases de sincronização.
930
+ *
931
+ * Guarda re-entrância: se já está em progresso, retorna imediatamente.
932
+ * NÃO executa se esta aba não é líder ou se está offline.
933
+ */
934
+ async sync() {
935
+ if (this._destroyed) return;
936
+ if (!this._tabCoordinator.isLeader()) return;
937
+ if (!this._connectivity.isOnline) return;
938
+ if (this._syncing) return;
939
+ this._syncing = true;
940
+ this._updateState({ status: "syncing" });
941
+ try {
942
+ const phase1Ok = await this._phase1Push();
943
+ if (!phase1Ok) {
944
+ this._updateState({ status: "idle" });
945
+ this._syncing = false;
946
+ return;
947
+ }
948
+ await this._phase2Pull();
949
+ this._phase3Realtime();
950
+ this._updateState({ status: "idle", lastSyncedAt: Date.now() });
951
+ } catch (err) {
952
+ this._updateState({ status: "idle" });
953
+ } finally {
954
+ this._syncing = false;
955
+ }
956
+ }
957
+ /**
958
+ * Teardown: para timers, remove listeners, marca como destroyed.
959
+ */
960
+ destroy() {
961
+ if (this._destroyed) return;
962
+ this._destroyed = true;
963
+ if (this._periodicTimer !== null) {
964
+ clearInterval(this._periodicTimer);
965
+ this._periodicTimer = null;
966
+ }
967
+ for (const cleanup of this._cleanups) {
968
+ try {
969
+ cleanup();
970
+ } catch {
971
+ }
972
+ }
973
+ this._cleanups.length = 0;
974
+ this._stateListeners.clear();
975
+ }
976
+ // ─── FASE 1 — push (drenar a fila) ───────────────────────────────────────────
977
+ /**
978
+ * Drena a MutationQueue, enviando mutações em ordem de seq.
979
+ *
980
+ * Retorna `true` se a fase completou sem falhas transientes.
981
+ * Retorna `false` se houve falha transiente (ciclo deve ser abortado).
982
+ */
983
+ async _phase1Push() {
984
+ const mutations = await this._queue.drain();
985
+ if (mutations.length === 0) return true;
986
+ for (const mut of mutations) {
987
+ await this._queue.markInflight(mut.mutationId);
988
+ }
989
+ let result;
990
+ try {
991
+ result = await this._transport.pushMutations(mutations);
992
+ } catch (err) {
993
+ for (const mut of mutations) {
994
+ const errMsg = err instanceof Error ? err.message : String(err);
995
+ await this._queue.markRetry(mut.mutationId, errMsg);
996
+ }
997
+ return false;
998
+ }
999
+ const busChanges = [];
1000
+ for (const res of result.results) {
1001
+ const mut = mutations.find((m) => m.mutationId === res.mutationId);
1002
+ if (!mut) continue;
1003
+ if (res.outcome === "confirmed") {
1004
+ await this._queue.markApplied(mut.mutationId);
1005
+ await this._applySyncedDoc(
1006
+ mut.collection,
1007
+ mut.docId,
1008
+ res.serverVersion,
1009
+ res.serverTimestamp,
1010
+ mut,
1011
+ busChanges
1012
+ );
1013
+ } else if (res.outcome === "superseded") {
1014
+ await this._queue.markApplied(mut.mutationId);
1015
+ await this._applySuperseded(mut, res, busChanges);
1016
+ } else if (res.outcome === "rejected") {
1017
+ await this._queue.markApplied(mut.mutationId);
1018
+ await this._applyRejected(mut, res, busChanges);
1019
+ }
1020
+ }
1021
+ if (busChanges.length > 0) {
1022
+ this._bus.emit(busChanges);
1023
+ }
1024
+ return true;
1025
+ }
1026
+ /** Atualiza o cache após confirmação de escrita (outcome=confirmed). */
1027
+ async _applySyncedDoc(collection, docId, serverVersion, serverTimestamp, mut, busChanges) {
1028
+ const existing = await this._store.getDoc(collection, docId);
1029
+ if (mut.op === "remove") {
1030
+ if (existing) {
1031
+ await this._store.putDoc({
1032
+ ...existing,
1033
+ meta: {
1034
+ ...existing.meta,
1035
+ serverVersion,
1036
+ updatedAtServer: serverTimestamp,
1037
+ updatedAtLocal: Date.now(),
1038
+ state: "synced",
1039
+ deleted: true,
1040
+ pendingMutationIds: []
202
1041
  }
203
- try {
204
- const raw = await httpRequest(config, {
205
- method: "GET",
206
- path: `/api/sdk/v1/datastore/${name}/${encodeURIComponent(id)}`,
207
- requireAuth: true,
208
- headers
1042
+ });
1043
+ busChanges.push({ type: "removed", collection, doc: { id: docId, data: existing.data } });
1044
+ }
1045
+ return;
1046
+ }
1047
+ const newData = mut.payload ?? (existing?.data ?? {});
1048
+ const updatedDoc = {
1049
+ collection,
1050
+ id: docId,
1051
+ data: mut.op === "update" ? { ...existing?.data ?? {}, ...newData } : newData,
1052
+ meta: {
1053
+ serverVersion,
1054
+ updatedAtServer: serverTimestamp,
1055
+ updatedAtLocal: Date.now(),
1056
+ state: "synced",
1057
+ pendingMutationIds: [],
1058
+ deleted: false,
1059
+ ownerId: existing?.meta.ownerId ?? null
1060
+ }
1061
+ };
1062
+ await this._store.putDoc(updatedDoc);
1063
+ busChanges.push({
1064
+ type: existing ? "modified" : "added",
1065
+ collection,
1066
+ doc: { id: docId, data: updatedDoc.data }
1067
+ });
1068
+ }
1069
+ /** Processa resultado 'superseded' (LWW: servidor venceu). */
1070
+ async _applySuperseded(mut, res, busChanges) {
1071
+ const localDoc = await this._store.getDoc(mut.collection, mut.docId);
1072
+ const serverDocEnvelope = {
1073
+ collection: mut.collection,
1074
+ id: mut.docId,
1075
+ data: res.serverData,
1076
+ meta: {
1077
+ serverVersion: res.serverVersion,
1078
+ updatedAtServer: res.serverTimestamp,
1079
+ updatedAtLocal: Date.now(),
1080
+ state: "synced",
1081
+ pendingMutationIds: [],
1082
+ deleted: false,
1083
+ ownerId: localDoc?.meta.ownerId ?? null
1084
+ }
1085
+ };
1086
+ const localDocForResolver = localDoc ?? {
1087
+ collection: mut.collection,
1088
+ id: mut.docId,
1089
+ data: mut.payload ?? {},
1090
+ meta: {
1091
+ serverVersion: mut.baseVersion,
1092
+ updatedAtServer: res.serverTimestamp - 1,
1093
+ // garante server é mais novo
1094
+ updatedAtLocal: mut.enqueuedAt,
1095
+ state: "pending",
1096
+ pendingMutationIds: [mut.mutationId],
1097
+ deleted: false,
1098
+ ownerId: null
1099
+ }
1100
+ };
1101
+ const resolveResult = this._resolver.resolve(
1102
+ localDocForResolver,
1103
+ serverDocEnvelope,
1104
+ mut
1105
+ );
1106
+ const conflictRecord = resolveResult.conflictRecord ?? {
1107
+ collection: mut.collection,
1108
+ docId: mut.docId,
1109
+ mutationId: mut.mutationId,
1110
+ losingData: mut.payload ?? {},
1111
+ winningData: res.serverData,
1112
+ reason: "lww_server_newer",
1113
+ detectedAt: Date.now(),
1114
+ delivered: false
1115
+ };
1116
+ await this._store.appendConflict(conflictRecord);
1117
+ const updatedDoc = {
1118
+ collection: mut.collection,
1119
+ id: mut.docId,
1120
+ data: res.serverData,
1121
+ meta: {
1122
+ serverVersion: res.serverVersion,
1123
+ updatedAtServer: res.serverTimestamp,
1124
+ updatedAtLocal: Date.now(),
1125
+ state: "synced",
1126
+ pendingMutationIds: [],
1127
+ deleted: false,
1128
+ ownerId: localDoc?.meta.ownerId ?? null
1129
+ }
1130
+ };
1131
+ await this._store.putDoc(updatedDoc);
1132
+ busChanges.push({
1133
+ type: localDoc ? "modified" : "added",
1134
+ collection: mut.collection,
1135
+ doc: { id: mut.docId, data: res.serverData }
1136
+ });
1137
+ }
1138
+ /** Processa resultado 'rejected' (permissão/validação negada). */
1139
+ async _applyRejected(mut, res, busChanges) {
1140
+ const storedDoc = await this._store.getDoc(mut.collection, mut.docId);
1141
+ const localDoc = storedDoc ?? {
1142
+ collection: mut.collection,
1143
+ id: mut.docId,
1144
+ data: mut.payload ?? {},
1145
+ meta: {
1146
+ serverVersion: mut.baseVersion,
1147
+ updatedAtServer: null,
1148
+ updatedAtLocal: mut.enqueuedAt,
1149
+ state: "pending",
1150
+ pendingMutationIds: [mut.mutationId],
1151
+ deleted: false,
1152
+ ownerId: null
1153
+ }
1154
+ };
1155
+ const serverDocEnvelope = res.serverData ? {
1156
+ ...localDoc,
1157
+ data: res.serverData,
1158
+ meta: {
1159
+ ...localDoc.meta,
1160
+ serverVersion: res.serverVersion ?? localDoc.meta.serverVersion
1161
+ }
1162
+ } : null;
1163
+ const resolveResult = this._resolver.resolveRejected(
1164
+ localDoc,
1165
+ serverDocEnvelope,
1166
+ mut,
1167
+ res.reason
1168
+ );
1169
+ const conflictRecord = resolveResult.conflictRecord ?? {
1170
+ collection: mut.collection,
1171
+ docId: mut.docId,
1172
+ mutationId: mut.mutationId,
1173
+ losingData: mut.payload ?? {},
1174
+ winningData: res.serverData ?? {},
1175
+ reason: res.reason,
1176
+ detectedAt: Date.now(),
1177
+ delivered: false
1178
+ };
1179
+ await this._store.appendConflict(conflictRecord);
1180
+ if (res.serverData) {
1181
+ await this._store.putDoc({
1182
+ ...localDoc,
1183
+ data: res.serverData,
1184
+ meta: {
1185
+ ...localDoc.meta,
1186
+ state: "synced",
1187
+ pendingMutationIds: []
1188
+ }
1189
+ });
1190
+ busChanges.push({
1191
+ type: "modified",
1192
+ collection: mut.collection,
1193
+ doc: { id: mut.docId, data: res.serverData }
1194
+ });
1195
+ } else {
1196
+ await this._store.putDoc({
1197
+ ...localDoc,
1198
+ meta: {
1199
+ ...localDoc.meta,
1200
+ state: "synced",
1201
+ pendingMutationIds: []
1202
+ }
1203
+ });
1204
+ }
1205
+ }
1206
+ // ─── FASE 2 — pull (reconciliar o cache) ─────────────────────────────────────
1207
+ /**
1208
+ * Busca mudanças do servidor e aplica ao cache via ConflictResolver.
1209
+ *
1210
+ * Se `resyncRequired === true`, faz full resync em vez de pull incremental.
1211
+ */
1212
+ async _phase2Pull() {
1213
+ const watermark = await this._store.getMeta("lastSyncWatermark");
1214
+ const resumeToken = await this._store.getMeta("lastResumeToken");
1215
+ let pullResult;
1216
+ try {
1217
+ pullResult = await this._transport.pullChanges(watermark, resumeToken);
1218
+ } catch {
1219
+ return;
1220
+ }
1221
+ if (pullResult.resyncRequired) {
1222
+ await this._phase2FullResync();
1223
+ return;
1224
+ }
1225
+ const busChanges = [];
1226
+ await this._applyServerDocs(pullResult.docs, busChanges, false);
1227
+ if (pullResult.newWatermark !== null) {
1228
+ await this._store.setMeta("lastSyncWatermark", pullResult.newWatermark);
1229
+ }
1230
+ if (busChanges.length > 0) {
1231
+ this._bus.emit(busChanges);
1232
+ }
1233
+ }
1234
+ /** Full resync: lista completa + detecta deleções por ausência. */
1235
+ async _phase2FullResync() {
1236
+ const collections = await this._getActiveCollections();
1237
+ let resyncResult;
1238
+ try {
1239
+ resyncResult = await this._transport.fullResync(collections);
1240
+ } catch {
1241
+ return;
1242
+ }
1243
+ const busChanges = [];
1244
+ await this._applyServerDocs(resyncResult.docs, busChanges, true);
1245
+ const returnedKeys = new Set(
1246
+ resyncResult.docs.map((d) => `${d.collection}::${d.id}`)
1247
+ );
1248
+ for (const col of collections) {
1249
+ const queryResult = await this._store.listDocs(col, {});
1250
+ for (const { id } of queryResult.docs) {
1251
+ const key = `${col}::${id}`;
1252
+ if (!returnedKeys.has(key)) {
1253
+ const fullDoc = await this._store.getDoc(col, id);
1254
+ if (fullDoc && !fullDoc.meta.deleted) {
1255
+ await this._store.putDoc({
1256
+ ...fullDoc,
1257
+ meta: {
1258
+ ...fullDoc.meta,
1259
+ deleted: true,
1260
+ updatedAtLocal: Date.now(),
1261
+ state: "synced"
1262
+ }
1263
+ });
1264
+ busChanges.push({
1265
+ type: "removed",
1266
+ collection: col,
1267
+ doc: { id, data: fullDoc.data }
209
1268
  });
210
- return raw?.item ?? null;
211
- } catch (err) {
212
- if (err instanceof NeetruError && err.code === "not_found") return null;
213
- throw err;
214
- }
215
- },
216
- async add(data) {
217
- if (!data || typeof data !== "object") {
218
- throw new NeetruError("validation_failed", "data object required");
219
1269
  }
220
- const raw = await httpRequest(config, {
221
- method: "POST",
222
- path: `/api/sdk/v1/datastore/${name}`,
223
- body: { data },
224
- requireAuth: true,
225
- headers
1270
+ }
1271
+ }
1272
+ }
1273
+ if (resyncResult.newWatermark !== null) {
1274
+ await this._store.setMeta("lastSyncWatermark", resyncResult.newWatermark);
1275
+ }
1276
+ await this._store.setMeta("lastFullResyncAt", Date.now());
1277
+ if (busChanges.length > 0) {
1278
+ this._bus.emit(busChanges);
1279
+ }
1280
+ }
1281
+ /**
1282
+ * Aplica uma lista de ServerDoc ao cache local via ConflictResolver.
1283
+ *
1284
+ * `isFullResync = true` indica que o conjunto é completo — usamos isso para
1285
+ * otimizar a path (sempre sobrescreve docs synced; pending passam pelo LWW).
1286
+ */
1287
+ async _applyServerDocs(docs, busChanges, _isFullResync) {
1288
+ for (const serverDoc of docs) {
1289
+ const localDoc = await this._store.getDoc(serverDoc.collection, serverDoc.id);
1290
+ if (serverDoc.deleted) {
1291
+ if (localDoc && !localDoc.meta.deleted) {
1292
+ await this._store.putDoc({
1293
+ ...localDoc,
1294
+ meta: {
1295
+ ...localDoc.meta,
1296
+ deleted: true,
1297
+ serverVersion: serverDoc.serverVersion,
1298
+ updatedAtServer: serverDoc.serverTimestamp,
1299
+ updatedAtLocal: Date.now(),
1300
+ state: "synced"
1301
+ }
226
1302
  });
227
- if (!raw || typeof raw.id !== "string") {
228
- throw new NeetruError("invalid_response", "datastore.add missing id");
229
- }
230
- return { ok: true, id: raw.id };
231
- },
232
- async set(id, data) {
233
- if (!id || typeof id !== "string") {
234
- throw new NeetruError("validation_failed", "id required");
235
- }
236
- await httpRequest(config, {
237
- method: "PUT",
238
- path: `/api/sdk/v1/datastore/${name}/${encodeURIComponent(id)}`,
239
- body: { data },
240
- requireAuth: true,
241
- headers
1303
+ busChanges.push({
1304
+ type: "removed",
1305
+ collection: serverDoc.collection,
1306
+ doc: { id: serverDoc.id, data: localDoc.data }
242
1307
  });
243
- return { ok: true };
244
- },
245
- async update(id, data) {
246
- if (!id || typeof id !== "string") {
247
- throw new NeetruError("validation_failed", "id required");
1308
+ }
1309
+ continue;
1310
+ }
1311
+ if (localDoc && localDoc.meta.state === "pending") {
1312
+ const serverEnvelope = {
1313
+ collection: serverDoc.collection,
1314
+ id: serverDoc.id,
1315
+ data: serverDoc.data,
1316
+ meta: {
1317
+ serverVersion: serverDoc.serverVersion,
1318
+ updatedAtServer: serverDoc.serverTimestamp,
1319
+ updatedAtLocal: Date.now(),
1320
+ state: "synced",
1321
+ pendingMutationIds: [],
1322
+ deleted: false,
1323
+ ownerId: localDoc.meta.ownerId
248
1324
  }
249
- await httpRequest(config, {
250
- method: "PATCH",
251
- path: `/api/sdk/v1/datastore/${name}/${encodeURIComponent(id)}`,
252
- body: { data },
253
- requireAuth: true,
254
- headers
255
- });
256
- return { ok: true };
257
- },
258
- async remove(id) {
259
- if (!id || typeof id !== "string") {
260
- throw new NeetruError("validation_failed", "id required");
1325
+ };
1326
+ const pendingMuts = await this._queue.drain();
1327
+ const docMut = pendingMuts.find(
1328
+ (m) => m.collection === serverDoc.collection && m.docId === serverDoc.id
1329
+ );
1330
+ if (docMut) {
1331
+ const result = this._resolver.resolve(localDoc, serverEnvelope, docMut);
1332
+ if (result.conflictRecord) {
1333
+ await this._store.appendConflict(result.conflictRecord);
261
1334
  }
262
- await httpRequest(config, {
263
- method: "DELETE",
264
- path: `/api/sdk/v1/datastore/${name}/${encodeURIComponent(id)}`,
265
- requireAuth: true,
266
- headers
1335
+ await this._store.putDoc({
1336
+ ...localDoc,
1337
+ meta: { ...localDoc.meta, state: "conflict" }
1338
+ });
1339
+ continue;
1340
+ }
1341
+ }
1342
+ const isNew = !localDoc;
1343
+ const newDoc = {
1344
+ collection: serverDoc.collection,
1345
+ id: serverDoc.id,
1346
+ data: serverDoc.data,
1347
+ meta: {
1348
+ serverVersion: serverDoc.serverVersion,
1349
+ updatedAtServer: serverDoc.serverTimestamp,
1350
+ updatedAtLocal: Date.now(),
1351
+ state: "synced",
1352
+ pendingMutationIds: [],
1353
+ deleted: false,
1354
+ ownerId: localDoc?.meta.ownerId ?? null
1355
+ }
1356
+ };
1357
+ await this._store.putDoc(newDoc);
1358
+ busChanges.push({
1359
+ type: isNew ? "added" : "modified",
1360
+ collection: serverDoc.collection,
1361
+ doc: { id: serverDoc.id, data: serverDoc.data }
1362
+ });
1363
+ }
1364
+ }
1365
+ // ─── FASE 3 — reabre listeners (realtime) ─────────────────────────────────────
1366
+ /**
1367
+ * Fase 3: sinaliza que o cache está reconciliado.
1368
+ *
1369
+ * O transporte de tempo real (Firestore onSnapshot / WebSocket) é gerido
1370
+ * pela camada superior — aqui apenas garantimos que o SyncState reflita
1371
+ * o término do sync, o que notifica os listeners `onSyncStateChange` e
1372
+ * transitivamente os `onSnapshot` da UI.
1373
+ */
1374
+ _phase3Realtime() {
1375
+ }
1376
+ // ─── Helpers ──────────────────────────────────────────────────────────────────
1377
+ /**
1378
+ * Retorna a lista de coleções com documentos no cache local.
1379
+ * Usado pelo full resync para saber quais coleções checar.
1380
+ *
1381
+ * Combina:
1382
+ * 1. Set em memória `_activeCollections` (populado ao aplicar docs)
1383
+ * 2. Coleções de mutações pendentes
1384
+ * 3. Coleções de conflict_log
1385
+ * 4. Coleções persistas em sync_meta['activeCollections']
1386
+ */
1387
+ async _getActiveCollections() {
1388
+ const collectionSet = new Set(this._activeCollections);
1389
+ const mutations = await this._queue.listAll();
1390
+ for (const m of mutations) collectionSet.add(m.collection);
1391
+ const conflicts = await this._store.listConflicts();
1392
+ for (const c of conflicts) collectionSet.add(c.collection);
1393
+ const persistedRaw = await this._store.getMeta("activeCollections");
1394
+ if (persistedRaw) {
1395
+ for (const col of persistedRaw) collectionSet.add(col);
1396
+ }
1397
+ const storedCollections = await this._store.listCollections();
1398
+ for (const col of storedCollections) collectionSet.add(col);
1399
+ return Array.from(collectionSet);
1400
+ }
1401
+ /** Constrói o estado inicial com base no estado atual dos colaboradores. */
1402
+ _buildInitialState() {
1403
+ const isOnline = this._connectivity.isOnline;
1404
+ return {
1405
+ status: isOnline ? "idle" : "offline",
1406
+ pendingWrites: 0,
1407
+ lastSyncedAt: null,
1408
+ isLeaderTab: this._tabCoordinator.isLeader()
1409
+ };
1410
+ }
1411
+ /**
1412
+ * Atualiza o SyncState em RAM e notifica os listeners.
1413
+ * Só emite se algo realmente mudou.
1414
+ */
1415
+ _updateState(partial) {
1416
+ const prev = this._state;
1417
+ const next = { ...prev, ...partial };
1418
+ const changed = prev.status !== next.status || prev.pendingWrites !== next.pendingWrites || prev.lastSyncedAt !== next.lastSyncedAt || prev.isLeaderTab !== next.isLeaderTab;
1419
+ this._state = next;
1420
+ if (changed) {
1421
+ this._emitState(next);
1422
+ }
1423
+ }
1424
+ _emitState(state) {
1425
+ for (const listener of this._stateListeners) {
1426
+ try {
1427
+ listener({ ...state });
1428
+ } catch {
1429
+ }
1430
+ }
1431
+ }
1432
+ /**
1433
+ * Atualiza `pendingWrites` no estado.
1434
+ * Chamado de forma assíncrona quando necessário.
1435
+ */
1436
+ async _refreshPendingWrites() {
1437
+ if (this._destroyed) return;
1438
+ try {
1439
+ const count = await this._queue.countPending();
1440
+ if (count !== this._state.pendingWrites) {
1441
+ this._updateState({ pendingWrites: count });
1442
+ }
1443
+ } catch {
1444
+ }
1445
+ }
1446
+ /** Dispara um sync de forma fire-and-forget (para gatilhos externos). */
1447
+ _triggerSync(_reason) {
1448
+ if (this._destroyed) return;
1449
+ this._refreshPendingWrites().catch(() => {
1450
+ });
1451
+ this.sync().catch(() => {
1452
+ });
1453
+ }
1454
+ /** Carrega activeCollections do sync_meta e popula o Set em memória. */
1455
+ _loadActiveCollections() {
1456
+ this._store.getMeta("activeCollections").then((raw) => {
1457
+ const cols = raw;
1458
+ if (cols) {
1459
+ for (const c of cols) this._activeCollections.add(c);
1460
+ }
1461
+ }).catch(() => {
1462
+ });
1463
+ }
1464
+ /** Conecta os listeners de ConnectivityMonitor e TabCoordinator. */
1465
+ _wireListeners() {
1466
+ this._loadActiveCollections();
1467
+ const unsubConn = this._connectivity.subscribe((state) => {
1468
+ if (state === "offline") {
1469
+ this._updateState({ status: "offline" });
1470
+ } else {
1471
+ if (this._state.status === "offline") {
1472
+ this._updateState({ status: "idle" });
1473
+ }
1474
+ this._triggerSync("connectivity:online");
1475
+ }
1476
+ });
1477
+ this._cleanups.push(unsubConn);
1478
+ const unsubRole = this._tabCoordinator.onRoleChange((role) => {
1479
+ const isLeader = role === "leader";
1480
+ this._updateState({ isLeaderTab: isLeader });
1481
+ if (isLeader) {
1482
+ this._triggerSync("role:leader");
1483
+ }
1484
+ });
1485
+ this._cleanups.push(unsubRole);
1486
+ }
1487
+ };
1488
+
1489
+ // src/db/offline/conflict-resolver.ts
1490
+ function isServerNewer(localUpdatedAtServer, remoteUpdatedAtServer) {
1491
+ if (remoteUpdatedAtServer === null) return false;
1492
+ if (localUpdatedAtServer === null) return true;
1493
+ return remoteUpdatedAtServer > localUpdatedAtServer;
1494
+ }
1495
+ var ConflictResolver = class _ConflictResolver {
1496
+ /**
1497
+ * Resolve um conflito com base na operação da mutação (auto-dispatch).
1498
+ *
1499
+ * - `add` / `set` → `resolveDocLevel`
1500
+ * - `update` → `resolveFieldRestricted`
1501
+ * - `remove` → a remoção sempre vence (LWW: operação mais recente é a destruição)
1502
+ */
1503
+ resolve(localDoc, serverDoc, pendingMutation) {
1504
+ switch (pendingMutation.op) {
1505
+ case "remove":
1506
+ return this.resolveRemove(localDoc, serverDoc, pendingMutation);
1507
+ case "update":
1508
+ return this.resolveFieldRestricted(localDoc, serverDoc, pendingMutation);
1509
+ case "add":
1510
+ case "set":
1511
+ default:
1512
+ return this.resolveDocLevel(localDoc, serverDoc, pendingMutation);
1513
+ }
1514
+ }
1515
+ /**
1516
+ * LWW documento-nível (para `set` e `add`).
1517
+ *
1518
+ * O documento inteiro com o timestamp de servidor mais recente vence.
1519
+ * Se o servidor for mais novo, a escrita local é descartada e um
1520
+ * `ConflictRecord` é emitido.
1521
+ */
1522
+ resolveDocLevel(localDoc, serverDoc, pendingMutation) {
1523
+ if (serverDoc === null) {
1524
+ const data = pendingMutation.payload ?? {};
1525
+ return { outcome: "no_conflict", resolvedData: data, conflictRecord: null };
1526
+ }
1527
+ if (localDoc === null) {
1528
+ return {
1529
+ outcome: "server_wins",
1530
+ resolvedData: serverDoc.data,
1531
+ conflictRecord: null
1532
+ };
1533
+ }
1534
+ const serverNewer = isServerNewer(
1535
+ localDoc.meta.updatedAtServer,
1536
+ serverDoc.meta.updatedAtServer
1537
+ );
1538
+ if (!serverNewer) {
1539
+ return {
1540
+ outcome: "local_wins",
1541
+ resolvedData: localDoc.data,
1542
+ conflictRecord: null
1543
+ };
1544
+ }
1545
+ const conflictRecord = {
1546
+ collection: pendingMutation.collection,
1547
+ docId: pendingMutation.docId,
1548
+ mutationId: pendingMutation.mutationId,
1549
+ losingData: localDoc.data,
1550
+ winningData: serverDoc.data,
1551
+ reason: "lww_server_newer",
1552
+ detectedAt: Date.now(),
1553
+ delivered: false
1554
+ };
1555
+ return {
1556
+ outcome: "server_wins",
1557
+ resolvedData: serverDoc.data,
1558
+ conflictRecord
1559
+ };
1560
+ }
1561
+ /**
1562
+ * LWW campo-restrito (para `update`).
1563
+ *
1564
+ * Apenas os campos declarados no payload da mutação são comparados.
1565
+ * Campos não tocados pela mutação são preservados do estado do servidor
1566
+ * (se disponível) ou do estado local (I3 §7.2).
1567
+ *
1568
+ * Resultado:
1569
+ * - Se o servidor for mais novo nos campos conflitantes → `server_wins`
1570
+ * para esses campos; o doc resultante é uma mescla de server (campos
1571
+ * conflitantes) + estado antes da mutação para os demais.
1572
+ * - Se o local for mais recente → `local_wins`; os campos do update são
1573
+ * aplicados sobre o server.
1574
+ * - Campos do server não tocados pelo update sempre preservados → `merged`.
1575
+ */
1576
+ resolveFieldRestricted(localDoc, serverDoc, pendingMutation) {
1577
+ const mutatedFields = Object.keys(pendingMutation.payload ?? {});
1578
+ if (serverDoc === null) {
1579
+ const base = localDoc?.data ?? {};
1580
+ const resolved = { ...base, ...pendingMutation.payload ?? {} };
1581
+ return { outcome: "no_conflict", resolvedData: resolved, conflictRecord: null };
1582
+ }
1583
+ const serverData = serverDoc.data;
1584
+ if (localDoc === null) {
1585
+ const resolved = { ...serverData, ...pendingMutation.payload ?? {} };
1586
+ return { outcome: "no_conflict", resolvedData: resolved, conflictRecord: null };
1587
+ }
1588
+ const serverNewer = isServerNewer(
1589
+ localDoc.meta.updatedAtServer,
1590
+ serverDoc.meta.updatedAtServer
1591
+ );
1592
+ if (!serverNewer) {
1593
+ const resolved = { ...serverData, ...pendingMutation.payload ?? {} };
1594
+ return { outcome: "local_wins", resolvedData: resolved, conflictRecord: null };
1595
+ }
1596
+ const losingFields = {};
1597
+ for (const field of mutatedFields) {
1598
+ losingFields[field] = localDoc.data[field];
1599
+ }
1600
+ const conflictRecord = {
1601
+ collection: pendingMutation.collection,
1602
+ docId: pendingMutation.docId,
1603
+ mutationId: pendingMutation.mutationId,
1604
+ losingData: losingFields,
1605
+ winningData: serverData,
1606
+ reason: "lww_server_newer",
1607
+ detectedAt: Date.now(),
1608
+ delivered: false
1609
+ };
1610
+ return {
1611
+ outcome: "server_wins",
1612
+ resolvedData: serverData,
1613
+ conflictRecord
1614
+ };
1615
+ }
1616
+ /**
1617
+ * Resolve uma operação `remove`.
1618
+ *
1619
+ * A remoção sempre vence no LWW (I3 §7.4: "a última operação é a destruição").
1620
+ * Se o servidor modificou o doc depois que o cliente enfileirou o remove, a
1621
+ * remoção ainda prevalece — comportamento documentado.
1622
+ */
1623
+ resolveRemove(_localDoc, serverDoc, _pendingMutation) {
1624
+ const emptyDoc = {};
1625
+ if (serverDoc !== null && serverDoc.meta.updatedAtServer !== null) {
1626
+ const conflictRecord = {
1627
+ collection: _pendingMutation.collection,
1628
+ docId: _pendingMutation.docId,
1629
+ mutationId: _pendingMutation.mutationId,
1630
+ losingData: serverDoc.data,
1631
+ winningData: {},
1632
+ reason: "lww_server_newer",
1633
+ detectedAt: Date.now(),
1634
+ delivered: false
1635
+ };
1636
+ return { outcome: "local_wins", resolvedData: emptyDoc, conflictRecord };
1637
+ }
1638
+ return { outcome: "local_wins", resolvedData: emptyDoc, conflictRecord: null };
1639
+ }
1640
+ /**
1641
+ * Resolve conflito com razão de rejeição explícita (servidor retornou
1642
+ * `rejected_permission` ou `rejected_validation`).
1643
+ *
1644
+ * Usado pelo SyncEngine quando o Core rejeita o replay por motivo não-LWW.
1645
+ */
1646
+ resolveRejected(localDoc, serverDoc, pendingMutation, reason) {
1647
+ const winningData = serverDoc?.data ?? {};
1648
+ const conflictRecord = {
1649
+ collection: pendingMutation.collection,
1650
+ docId: pendingMutation.docId,
1651
+ mutationId: pendingMutation.mutationId,
1652
+ losingData: localDoc.data,
1653
+ winningData,
1654
+ reason,
1655
+ detectedAt: Date.now(),
1656
+ delivered: false
1657
+ };
1658
+ return {
1659
+ outcome: "server_wins",
1660
+ resolvedData: serverDoc?.data ?? localDoc.data,
1661
+ conflictRecord
1662
+ };
1663
+ }
1664
+ // ─── Static helpers ─────────────────────────────────────────────────────────
1665
+ static resolve(localDoc, serverDoc, pendingMutation) {
1666
+ return new _ConflictResolver().resolve(localDoc, serverDoc, pendingMutation);
1667
+ }
1668
+ };
1669
+
1670
+ // src/db/offline/change-bus.ts
1671
+ function dedupeKey(c) {
1672
+ return `${c.collection}::${c.doc.id}`;
1673
+ }
1674
+ var ChangeBus = class {
1675
+ /** Listeners filtrados por coleção. */
1676
+ _collectionListeners = /* @__PURE__ */ new Map();
1677
+ /** Listeners globais (todas as coleções). */
1678
+ _globalListeners = /* @__PURE__ */ new Set();
1679
+ /**
1680
+ * Subscreve a eventos de uma coleção específica.
1681
+ *
1682
+ * @param collection - Nome da coleção a filtrar.
1683
+ * @param listener - Callback que recebe os changes da coleção.
1684
+ * @returns Função de unsubscribe.
1685
+ */
1686
+ subscribe(collection, listener) {
1687
+ if (!this._collectionListeners.has(collection)) {
1688
+ this._collectionListeners.set(collection, /* @__PURE__ */ new Set());
1689
+ }
1690
+ this._collectionListeners.get(collection).add(listener);
1691
+ return () => {
1692
+ const set = this._collectionListeners.get(collection);
1693
+ if (set) {
1694
+ set.delete(listener);
1695
+ if (set.size === 0) {
1696
+ this._collectionListeners.delete(collection);
1697
+ }
1698
+ }
1699
+ };
1700
+ }
1701
+ /**
1702
+ * Subscreve a eventos de TODAS as coleções.
1703
+ *
1704
+ * @param listener - Callback que recebe todos os changes, de qualquer coleção.
1705
+ * @returns Função de unsubscribe.
1706
+ */
1707
+ subscribeAll(listener) {
1708
+ this._globalListeners.add(listener);
1709
+ return () => {
1710
+ this._globalListeners.delete(listener);
1711
+ };
1712
+ }
1713
+ /**
1714
+ * Emite um array de `Change` events para todos os listeners relevantes.
1715
+ *
1716
+ * Agrupa os changes por coleção antes de despachar, para que cada listener
1717
+ * receba apenas os events da sua coleção.
1718
+ *
1719
+ * Deduplicação: events com o mesmo `[collection, id]` dentro do mesmo `emit()`
1720
+ * são compactados: apenas o último do array é mantido (o mais recente vence).
1721
+ * Isso cobre o caso Fase 1 + Fase 2 do SyncEngine emitindo o mesmo doc.
1722
+ *
1723
+ * Erros em listeners individuais são capturados e não interrompem os demais.
1724
+ */
1725
+ emit(changes) {
1726
+ if (changes.length === 0) return;
1727
+ const deduped = /* @__PURE__ */ new Map();
1728
+ for (const c of changes) {
1729
+ deduped.set(dedupeKey(c), c);
1730
+ }
1731
+ const uniqueChanges = Array.from(deduped.values());
1732
+ const byCollection = /* @__PURE__ */ new Map();
1733
+ for (const c of uniqueChanges) {
1734
+ if (!byCollection.has(c.collection)) {
1735
+ byCollection.set(c.collection, []);
1736
+ }
1737
+ byCollection.get(c.collection).push(c);
1738
+ }
1739
+ for (const [collection, collChanges] of byCollection) {
1740
+ const listeners = this._collectionListeners.get(collection);
1741
+ if (listeners) {
1742
+ for (const listener of listeners) {
1743
+ this._safeCall(listener, collChanges);
1744
+ }
1745
+ }
1746
+ }
1747
+ for (const listener of this._globalListeners) {
1748
+ this._safeCall(listener, uniqueChanges);
1749
+ }
1750
+ }
1751
+ /**
1752
+ * Número de listeners ativos (útil em testes).
1753
+ */
1754
+ get listenerCount() {
1755
+ let count = this._globalListeners.size;
1756
+ for (const set of this._collectionListeners.values()) {
1757
+ count += set.size;
1758
+ }
1759
+ return count;
1760
+ }
1761
+ /**
1762
+ * Remove todos os listeners registrados.
1763
+ * Útil para teardown em testes ou no shutdown do SDK.
1764
+ */
1765
+ clear() {
1766
+ this._collectionListeners.clear();
1767
+ this._globalListeners.clear();
1768
+ }
1769
+ // ─── Privado ────────────────────────────────────────────────────────────────
1770
+ _safeCall(listener, changes) {
1771
+ try {
1772
+ listener(changes);
1773
+ } catch {
1774
+ }
1775
+ }
1776
+ };
1777
+
1778
+ // src/db/offline/connectivity-monitor.ts
1779
+ var ConnectivityMonitor = class {
1780
+ _state;
1781
+ _listeners = /* @__PURE__ */ new Set();
1782
+ _nav;
1783
+ _target;
1784
+ _debounceMs;
1785
+ _debounceTimer = null;
1786
+ _started = false;
1787
+ // Handlers bound para remoção correta em removeEventListener
1788
+ _onOnline;
1789
+ _onOffline;
1790
+ constructor(options = {}) {
1791
+ this._nav = options.navigator ?? (typeof navigator !== "undefined" ? navigator : void 0);
1792
+ this._target = options.eventTarget ?? (typeof window !== "undefined" ? window : void 0);
1793
+ this._debounceMs = options.debounceMs ?? 300;
1794
+ this._state = this._nav?.onLine === false ? "offline" : "online";
1795
+ this._onOnline = () => this._handleNativeEvent("online");
1796
+ this._onOffline = () => this._handleNativeEvent("offline");
1797
+ }
1798
+ // ─── Ciclo de vida ──────────────────────────────────────────────────────────
1799
+ /**
1800
+ * Inicia a escuta de eventos. Deve ser chamado após instanciar.
1801
+ * Sem efeito se já foi iniciado.
1802
+ */
1803
+ start() {
1804
+ if (this._started) return;
1805
+ this._started = true;
1806
+ this._target?.addEventListener("online", this._onOnline);
1807
+ this._target?.addEventListener("offline", this._onOffline);
1808
+ }
1809
+ /**
1810
+ * Para a escuta e remove todos os listeners.
1811
+ * Deve ser chamado no shutdown para evitar memory leaks.
1812
+ */
1813
+ destroy() {
1814
+ this._started = false;
1815
+ this._target?.removeEventListener("online", this._onOnline);
1816
+ this._target?.removeEventListener("offline", this._onOffline);
1817
+ if (this._debounceTimer !== null) {
1818
+ clearTimeout(this._debounceTimer);
1819
+ this._debounceTimer = null;
1820
+ }
1821
+ this._listeners.clear();
1822
+ }
1823
+ // ─── Estado atual ───────────────────────────────────────────────────────────
1824
+ /**
1825
+ * Retorna o estado de conectividade atual.
1826
+ */
1827
+ getState() {
1828
+ return this._state;
1829
+ }
1830
+ /**
1831
+ * True se o estado atual é `'online'`.
1832
+ */
1833
+ get isOnline() {
1834
+ return this._state === "online";
1835
+ }
1836
+ /**
1837
+ * True se o estado atual é `'offline'`.
1838
+ */
1839
+ get isOffline() {
1840
+ return this._state === "offline";
1841
+ }
1842
+ // ─── Subscrições ────────────────────────────────────────────────────────────
1843
+ /**
1844
+ * Subscreve a mudanças de estado de conectividade.
1845
+ *
1846
+ * @param listener - Callback chamado ao mudar o estado.
1847
+ * @returns Função de unsubscribe (sem memory leak).
1848
+ */
1849
+ subscribe(listener) {
1850
+ this._listeners.add(listener);
1851
+ return () => {
1852
+ this._listeners.delete(listener);
1853
+ };
1854
+ }
1855
+ /**
1856
+ * Número de listeners ativos (útil em testes).
1857
+ */
1858
+ get listenerCount() {
1859
+ return this._listeners.size;
1860
+ }
1861
+ // ─── Força de estado (para testes e heartbeat externo) ─────────────────────
1862
+ /**
1863
+ * Força o estado para um valor específico, ignorando eventos nativos.
1864
+ * Útil para o SyncEngine injetar o resultado de um heartbeat real ao Core.
1865
+ * Respeita o debounce.
1866
+ */
1867
+ forceState(state) {
1868
+ this._scheduleTransition(state);
1869
+ }
1870
+ // ─── Privado ────────────────────────────────────────────────────────────────
1871
+ _handleNativeEvent(type) {
1872
+ const newState = type === "online" ? "online" : "offline";
1873
+ this._scheduleTransition(newState);
1874
+ }
1875
+ _scheduleTransition(newState) {
1876
+ if (this._debounceTimer !== null) {
1877
+ clearTimeout(this._debounceTimer);
1878
+ this._debounceTimer = null;
1879
+ }
1880
+ if (this._debounceMs <= 0) {
1881
+ this._applyTransition(newState);
1882
+ return;
1883
+ }
1884
+ this._debounceTimer = setTimeout(() => {
1885
+ this._debounceTimer = null;
1886
+ this._applyTransition(newState);
1887
+ }, this._debounceMs);
1888
+ }
1889
+ _applyTransition(newState) {
1890
+ if (newState === this._state) return;
1891
+ this._state = newState;
1892
+ this._notifyListeners(newState);
1893
+ }
1894
+ _notifyListeners(state) {
1895
+ for (const listener of this._listeners) {
1896
+ try {
1897
+ listener(state);
1898
+ } catch {
1899
+ }
1900
+ }
1901
+ }
1902
+ };
1903
+
1904
+ // src/db/offline/tab-coordinator.ts
1905
+ var TabCoordinator = class {
1906
+ _lockName;
1907
+ _channelName;
1908
+ _lockManager;
1909
+ _channel;
1910
+ _channelFactory;
1911
+ /** ID único desta aba (para debug e `sync_state`). */
1912
+ _tabId;
1913
+ /** Estado de papel atual. */
1914
+ _role = "follower";
1915
+ /** Promise resolve que libera o lock perpétuo. */
1916
+ _releaseLock = null;
1917
+ /** `true` se destroy() já foi chamado. */
1918
+ _destroyed = false;
1919
+ /** `true` se start() já foi chamado. */
1920
+ _started = false;
1921
+ /** Listeners de mudança de papel. */
1922
+ _roleListeners = /* @__PURE__ */ new Set();
1923
+ /** Listeners de mensagem recebida. */
1924
+ _messageListeners = /* @__PURE__ */ new Set();
1925
+ constructor(options) {
1926
+ this._lockName = options.lockName;
1927
+ this._channelName = options.channelName;
1928
+ this._tabId = `tab-${Math.random().toString(36).slice(2, 10)}-${Date.now()}`;
1929
+ this._lockManager = options.lockManager !== void 0 ? options.lockManager : typeof navigator !== "undefined" && "locks" in navigator && navigator.locks != null ? navigator.locks : void 0;
1930
+ if (options.broadcastChannel !== void 0) {
1931
+ this._channel = options.broadcastChannel;
1932
+ } else if (typeof BroadcastChannel !== "undefined") {
1933
+ const channelName = this._channelName;
1934
+ this._channelFactory = () => {
1935
+ const bc = new BroadcastChannel(channelName);
1936
+ const wrapper = {
1937
+ get onmessage() {
1938
+ return bc.onmessage;
1939
+ },
1940
+ set onmessage(cb) {
1941
+ bc.onmessage = cb ? (event) => cb(event.data) : null;
1942
+ },
1943
+ postMessage: (msg) => bc.postMessage(msg),
1944
+ close: () => bc.close()
1945
+ };
1946
+ return wrapper;
1947
+ };
1948
+ }
1949
+ }
1950
+ // ─── Ciclo de vida ───────────────────────────────────────────────────────────
1951
+ /**
1952
+ * Inicia o processo de eleição de líder.
1953
+ * Idempotente: sem efeito se já foi chamado.
1954
+ */
1955
+ start() {
1956
+ if (this._started || this._destroyed) return;
1957
+ this._started = true;
1958
+ if (!this._channel && this._channelFactory) {
1959
+ this._channel = this._channelFactory();
1960
+ }
1961
+ if (this._channel) {
1962
+ this._channel.onmessage = (msg) => {
1963
+ this._handleIncomingMessage(msg);
1964
+ };
1965
+ }
1966
+ if (this._lockManager) {
1967
+ this._electWithLocks();
1968
+ } else {
1969
+ this._becomeLeader();
1970
+ }
1971
+ }
1972
+ /**
1973
+ * Para o TabCoordinator: libera o lock, fecha o canal.
1974
+ * Idempotente: pode ser chamado múltiplas vezes.
1975
+ */
1976
+ destroy() {
1977
+ if (this._destroyed) return;
1978
+ this._destroyed = true;
1979
+ this._started = false;
1980
+ if (this._releaseLock) {
1981
+ this._releaseLock();
1982
+ this._releaseLock = null;
1983
+ }
1984
+ if (this._channel) {
1985
+ this._channel.onmessage = null;
1986
+ this._channel.close();
1987
+ this._channel = void 0;
1988
+ }
1989
+ this._role = "follower";
1990
+ this._roleListeners.clear();
1991
+ this._messageListeners.clear();
1992
+ }
1993
+ // ─── Estado ──────────────────────────────────────────────────────────────────
1994
+ /**
1995
+ * Retorna `true` se esta aba é atualmente a líder.
1996
+ */
1997
+ isLeader() {
1998
+ return !this._destroyed && this._role === "leader";
1999
+ }
2000
+ /**
2001
+ * Retorna o papel atual desta aba.
2002
+ */
2003
+ getRole() {
2004
+ return this._destroyed ? "follower" : this._role;
2005
+ }
2006
+ /**
2007
+ * ID único desta aba (para diagnóstico).
2008
+ */
2009
+ get tabId() {
2010
+ return this._tabId;
2011
+ }
2012
+ // ─── Subscrições ─────────────────────────────────────────────────────────────
2013
+ /**
2014
+ * Registra um listener para mudanças de papel (`'leader'` | `'follower'`).
2015
+ *
2016
+ * @returns Função de unsubscribe.
2017
+ */
2018
+ onRoleChange(listener) {
2019
+ this._roleListeners.add(listener);
2020
+ return () => {
2021
+ this._roleListeners.delete(listener);
2022
+ };
2023
+ }
2024
+ /**
2025
+ * Registra um listener para mensagens recebidas de outras abas via
2026
+ * BroadcastChannel. O remetente NÃO recebe suas próprias mensagens.
2027
+ *
2028
+ * @returns Função de unsubscribe.
2029
+ */
2030
+ onMessage(listener) {
2031
+ this._messageListeners.add(listener);
2032
+ return () => {
2033
+ this._messageListeners.delete(listener);
2034
+ };
2035
+ }
2036
+ // ─── Comunicação ─────────────────────────────────────────────────────────────
2037
+ /**
2038
+ * Transmite uma mensagem para todas as outras abas via BroadcastChannel.
2039
+ * Sem efeito se o canal não estiver disponível ou o coordinator foi destroyed.
2040
+ */
2041
+ broadcast(msg) {
2042
+ if (this._destroyed) return;
2043
+ try {
2044
+ this._channel?.postMessage(msg);
2045
+ } catch {
2046
+ }
2047
+ }
2048
+ // ─── Privado — eleição ───────────────────────────────────────────────────────
2049
+ /**
2050
+ * Inicia a disputa pelo lock Web Locks.
2051
+ *
2052
+ * `navigator.locks.request` com uma Promise-interna que nunca resolve:
2053
+ * enquanto a aba vive e o lock está ativo, a callback não retorna.
2054
+ * Ao chamar `destroy()` a Promise interna resolve → lock liberado.
2055
+ */
2056
+ _electWithLocks() {
2057
+ const lockPromise = new Promise((resolve) => {
2058
+ this._releaseLock = resolve;
2059
+ });
2060
+ Promise.resolve().then(() => {
2061
+ if (!this._destroyed && this._role === "follower") {
2062
+ this._notifyRoleChange("follower");
2063
+ }
2064
+ });
2065
+ this._lockManager.request(this._lockName, (_lock) => {
2066
+ if (this._destroyed) {
2067
+ return Promise.resolve();
2068
+ }
2069
+ this._becomeLeader();
2070
+ return lockPromise;
2071
+ }).catch(() => {
2072
+ });
2073
+ }
2074
+ /**
2075
+ * Transição para o papel de líder.
2076
+ */
2077
+ _becomeLeader() {
2078
+ if (this._destroyed) return;
2079
+ this._setRole("leader");
2080
+ Promise.resolve().then(() => {
2081
+ if (!this._destroyed) this._broadcastSyncState();
2082
+ });
2083
+ }
2084
+ /**
2085
+ * Muda o papel e notifica os listeners.
2086
+ */
2087
+ _setRole(role) {
2088
+ const previous = this._role;
2089
+ this._role = role;
2090
+ if (previous !== role) {
2091
+ this._notifyRoleChange(role);
2092
+ }
2093
+ }
2094
+ /**
2095
+ * Transmite o estado de sync atual (chamado ao se tornar líder).
2096
+ */
2097
+ _broadcastSyncState() {
2098
+ this.broadcast({
2099
+ type: "sync_state",
2100
+ leaderTabId: this._tabId,
2101
+ syncing: false,
2102
+ pendingWrites: 0
2103
+ });
2104
+ }
2105
+ // ─── Privado — mensagens ─────────────────────────────────────────────────────
2106
+ /**
2107
+ * Processa mensagem recebida de outra aba.
2108
+ * Mensagens de tipo desconhecido são ignoradas silenciosamente.
2109
+ */
2110
+ _handleIncomingMessage(msg) {
2111
+ if (this._destroyed) return;
2112
+ if (!msg || typeof msg.type !== "string") return;
2113
+ for (const listener of this._messageListeners) {
2114
+ try {
2115
+ listener(msg);
2116
+ } catch {
2117
+ }
2118
+ }
2119
+ }
2120
+ // ─── Privado — notificações ───────────────────────────────────────────────────
2121
+ _notifyRoleChange(role) {
2122
+ for (const listener of this._roleListeners) {
2123
+ try {
2124
+ listener(role);
2125
+ } catch {
2126
+ }
2127
+ }
2128
+ }
2129
+ };
2130
+
2131
+ // src/db/collection-ref.ts
2132
+ var COLL_RE = /^[a-z0-9][a-z0-9_-]{0,62}$/;
2133
+ function assertValidCollection(name) {
2134
+ if (!COLL_RE.test(name)) {
2135
+ throw new NeetruDbError(
2136
+ "db_invalid_query",
2137
+ `Nome de cole\xE7\xE3o inv\xE1lido: "${name}". Deve seguir o padr\xE3o ${COLL_RE}.`
2138
+ );
2139
+ }
2140
+ }
2141
+ function assertValidId(id, label = "id") {
2142
+ if (!id || typeof id !== "string" || id.trim() === "") {
2143
+ throw new NeetruDbError(
2144
+ "db_invalid_query",
2145
+ `${label} \xE9 obrigat\xF3rio e deve ser uma string n\xE3o-vazia.`
2146
+ );
2147
+ }
2148
+ }
2149
+ function toQueryDescriptor(query) {
2150
+ const desc = {};
2151
+ if (query?.where) {
2152
+ desc.where = query.where.map((f) => ({
2153
+ field: f.field,
2154
+ op: f.op,
2155
+ value: f.value
2156
+ }));
2157
+ }
2158
+ if (query?.orderBy) {
2159
+ desc.orderBy = {
2160
+ field: query.orderBy.field,
2161
+ direction: query.orderBy.direction
2162
+ };
2163
+ }
2164
+ if (query?.limit !== void 0) {
2165
+ desc.limit = query.limit;
2166
+ }
2167
+ if (query?.cursor) {
2168
+ try {
2169
+ const cursorObj = JSON.parse(atob(query.cursor));
2170
+ desc.cursor = { type: cursorObj.type ?? "startAfter", docId: cursorObj.docId };
2171
+ } catch {
2172
+ }
2173
+ }
2174
+ return desc;
2175
+ }
2176
+ function buildNextCursor(docs, limit) {
2177
+ if (docs.length < limit) return null;
2178
+ const lastDoc = docs[docs.length - 1];
2179
+ if (!lastDoc) return null;
2180
+ return btoa(JSON.stringify({ type: "startAfter", docId: lastDoc.id }));
2181
+ }
2182
+ var DbCollectionRefImpl = class {
2183
+ constructor(_collection, _store, _queue, _bus, _engine, _connectivity) {
2184
+ this._collection = _collection;
2185
+ this._store = _store;
2186
+ this._queue = _queue;
2187
+ this._bus = _bus;
2188
+ this._engine = _engine;
2189
+ this._connectivity = _connectivity;
2190
+ }
2191
+ _collection;
2192
+ _store;
2193
+ _queue;
2194
+ _bus;
2195
+ _engine;
2196
+ _connectivity;
2197
+ // ── helpers ────────────────────────────────────────────────────────────────
2198
+ /** Verifica se há mutações pendentes para esta coleção. */
2199
+ async _hasPendingWrites() {
2200
+ const pending = await this._queue.listPending();
2201
+ return pending.some((m) => m.collection === this._collection);
2202
+ }
2203
+ /** Verifica se há mutações pendentes para um doc específico. */
2204
+ async _docHasPendingWrites(id) {
2205
+ const pending = await this._queue.listPending();
2206
+ return pending.some((m) => m.collection === this._collection && m.docId === id);
2207
+ }
2208
+ _isOnline() {
2209
+ return this._connectivity.isOnline;
2210
+ }
2211
+ /** Constrói um DbGetResult para um doc específico, ou null se tombstoned/ausente. */
2212
+ async _buildGetResult(id) {
2213
+ const doc = await this._store.getDoc(this._collection, id);
2214
+ if (!doc || doc.meta.deleted) return null;
2215
+ const hasPending = await this._docHasPendingWrites(id);
2216
+ const isOnline = this._isOnline();
2217
+ const syncState = this._engine.getSyncState();
2218
+ const staleGet = !isOnline || syncState.status === "offline";
2219
+ const fromCacheGet = hasPending || syncState.lastSyncedAt === null || staleGet;
2220
+ return {
2221
+ docs: [{ id: doc.id, data: doc.data }],
2222
+ fromCache: fromCacheGet,
2223
+ stale: staleGet,
2224
+ hasPendingWrites: hasPending,
2225
+ changes: []
2226
+ };
2227
+ }
2228
+ /** Constrói um DbListResult para a coleção com query opcional. */
2229
+ async _buildListResult(q) {
2230
+ const desc = toQueryDescriptor(q);
2231
+ const effectiveLimit = desc.limit ?? 20;
2232
+ const result = await this._store.listDocs(this._collection, desc);
2233
+ const hasPending = await this._hasPendingWrites();
2234
+ const isOnline = this._isOnline();
2235
+ const syncState = this._engine.getSyncState();
2236
+ const nextCursor = buildNextCursor(result.docs, effectiveLimit);
2237
+ const stale = !isOnline || syncState.status === "offline";
2238
+ const fromCache = hasPending || syncState.lastSyncedAt === null || stale;
2239
+ return {
2240
+ docs: result.docs.map((d) => ({ id: d.id, data: d.data })),
2241
+ nextCursor,
2242
+ fromCache,
2243
+ stale,
2244
+ hasPendingWrites: hasPending,
2245
+ changes: []
2246
+ };
2247
+ }
2248
+ // ── CRUD ────────────────────────────────────────────────────────────────────
2249
+ async get(id) {
2250
+ assertValidId(id);
2251
+ return this._buildGetResult(id);
2252
+ }
2253
+ async list(q) {
2254
+ return this._buildListResult(q);
2255
+ }
2256
+ async add(data) {
2257
+ const mutation = await this._queue.enqueue({
2258
+ collection: this._collection,
2259
+ op: "add",
2260
+ payload: data,
2261
+ baseVersion: null,
2262
+ batchId: null
2263
+ });
2264
+ const docId = mutation.docId;
2265
+ await this._store.putDoc({
2266
+ collection: this._collection,
2267
+ id: docId,
2268
+ data,
2269
+ meta: {
2270
+ serverVersion: null,
2271
+ updatedAtServer: null,
2272
+ updatedAtLocal: Date.now(),
2273
+ state: "pending",
2274
+ pendingMutationIds: [mutation.mutationId],
2275
+ deleted: false,
2276
+ ownerId: null
2277
+ }
2278
+ });
2279
+ this._bus.emit([{
2280
+ type: "added",
2281
+ collection: this._collection,
2282
+ doc: { id: docId, data }
2283
+ }]);
2284
+ return { ok: true, id: docId };
2285
+ }
2286
+ async set(id, data) {
2287
+ assertValidId(id);
2288
+ const existing = await this._store.getDoc(this._collection, id);
2289
+ const mutation = await this._queue.enqueue({
2290
+ collection: this._collection,
2291
+ docId: id,
2292
+ op: "set",
2293
+ payload: data,
2294
+ baseVersion: existing?.meta.serverVersion ?? null,
2295
+ batchId: null
2296
+ });
2297
+ await this._store.putDoc({
2298
+ collection: this._collection,
2299
+ id,
2300
+ data,
2301
+ meta: {
2302
+ serverVersion: existing?.meta.serverVersion ?? null,
2303
+ updatedAtServer: existing?.meta.updatedAtServer ?? null,
2304
+ updatedAtLocal: Date.now(),
2305
+ state: "pending",
2306
+ pendingMutationIds: [mutation.mutationId],
2307
+ deleted: false,
2308
+ ownerId: null
2309
+ }
2310
+ });
2311
+ this._bus.emit([{
2312
+ type: existing && !existing.meta.deleted ? "modified" : "added",
2313
+ collection: this._collection,
2314
+ doc: { id, data }
2315
+ }]);
2316
+ return { ok: true };
2317
+ }
2318
+ async update(id, data) {
2319
+ assertValidId(id);
2320
+ const existing = await this._store.getDoc(this._collection, id);
2321
+ const mergedData = existing?.meta.deleted ? { ...data } : { ...existing?.data ?? {}, ...data };
2322
+ const mutation = await this._queue.enqueue({
2323
+ collection: this._collection,
2324
+ docId: id,
2325
+ op: "update",
2326
+ payload: data,
2327
+ baseVersion: existing?.meta.serverVersion ?? null,
2328
+ batchId: null
2329
+ });
2330
+ await this._store.putDoc({
2331
+ collection: this._collection,
2332
+ id,
2333
+ data: mergedData,
2334
+ meta: {
2335
+ serverVersion: existing?.meta.serverVersion ?? null,
2336
+ updatedAtServer: existing?.meta.updatedAtServer ?? null,
2337
+ updatedAtLocal: Date.now(),
2338
+ state: "pending",
2339
+ pendingMutationIds: [
2340
+ ...existing?.meta.pendingMutationIds ?? [],
2341
+ mutation.mutationId
2342
+ ],
2343
+ deleted: false,
2344
+ ownerId: existing?.meta.ownerId ?? null
2345
+ }
2346
+ });
2347
+ this._bus.emit([{
2348
+ type: "modified",
2349
+ collection: this._collection,
2350
+ doc: { id, data: mergedData }
2351
+ }]);
2352
+ return { ok: true };
2353
+ }
2354
+ async remove(id) {
2355
+ assertValidId(id);
2356
+ const existing = await this._store.getDoc(this._collection, id);
2357
+ if (!existing || existing.meta.deleted) ;
2358
+ await this._queue.enqueue({
2359
+ collection: this._collection,
2360
+ docId: id,
2361
+ op: "remove",
2362
+ payload: null,
2363
+ baseVersion: existing?.meta.serverVersion ?? null,
2364
+ batchId: null
2365
+ });
2366
+ await this._store.deleteDoc(this._collection, id);
2367
+ if (existing && !existing.meta.deleted) {
2368
+ this._bus.emit([{
2369
+ type: "removed",
2370
+ collection: this._collection,
2371
+ doc: { id, data: existing.data }
2372
+ }]);
2373
+ }
2374
+ return { ok: true };
2375
+ }
2376
+ async batch(ops) {
2377
+ const batchId = `batch-${Date.now()}-${Math.random().toString(36).slice(2)}`;
2378
+ const busChanges = [];
2379
+ for (const op of ops) {
2380
+ const id = op.id ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
2381
+ const data = op.data ?? {};
2382
+ const collection = op.collection;
2383
+ if (op.op === "add") {
2384
+ const mutation = await this._queue.enqueue({
2385
+ collection,
2386
+ op: "add",
2387
+ payload: data,
2388
+ baseVersion: null,
2389
+ batchId
2390
+ });
2391
+ const docId = mutation.docId;
2392
+ await this._store.putDoc({
2393
+ collection,
2394
+ id: docId,
2395
+ data,
2396
+ meta: {
2397
+ serverVersion: null,
2398
+ updatedAtServer: null,
2399
+ updatedAtLocal: Date.now(),
2400
+ state: "pending",
2401
+ pendingMutationIds: [mutation.mutationId],
2402
+ deleted: false,
2403
+ ownerId: null
2404
+ }
2405
+ });
2406
+ busChanges.push({ type: "added", collection, doc: { id: docId, data } });
2407
+ } else if (op.op === "set") {
2408
+ const existing = await this._store.getDoc(collection, id);
2409
+ const mutation = await this._queue.enqueue({
2410
+ collection,
2411
+ docId: id,
2412
+ op: "set",
2413
+ payload: data,
2414
+ baseVersion: existing?.meta.serverVersion ?? null,
2415
+ batchId
2416
+ });
2417
+ await this._store.putDoc({
2418
+ collection,
2419
+ id,
2420
+ data,
2421
+ meta: {
2422
+ serverVersion: existing?.meta.serverVersion ?? null,
2423
+ updatedAtServer: existing?.meta.updatedAtServer ?? null,
2424
+ updatedAtLocal: Date.now(),
2425
+ state: "pending",
2426
+ pendingMutationIds: [mutation.mutationId],
2427
+ deleted: false,
2428
+ ownerId: null
2429
+ }
2430
+ });
2431
+ busChanges.push({
2432
+ type: existing && !existing.meta.deleted ? "modified" : "added",
2433
+ collection,
2434
+ doc: { id, data }
2435
+ });
2436
+ } else if (op.op === "update") {
2437
+ const existing = await this._store.getDoc(collection, id);
2438
+ const merged = { ...existing?.data ?? {}, ...data };
2439
+ const mutation = await this._queue.enqueue({
2440
+ collection,
2441
+ docId: id,
2442
+ op: "update",
2443
+ payload: data,
2444
+ baseVersion: existing?.meta.serverVersion ?? null,
2445
+ batchId
2446
+ });
2447
+ await this._store.putDoc({
2448
+ collection,
2449
+ id,
2450
+ data: merged,
2451
+ meta: {
2452
+ serverVersion: existing?.meta.serverVersion ?? null,
2453
+ updatedAtServer: existing?.meta.updatedAtServer ?? null,
2454
+ updatedAtLocal: Date.now(),
2455
+ state: "pending",
2456
+ pendingMutationIds: [
2457
+ ...existing?.meta.pendingMutationIds ?? [],
2458
+ mutation.mutationId
2459
+ ],
2460
+ deleted: false,
2461
+ ownerId: existing?.meta.ownerId ?? null
2462
+ }
2463
+ });
2464
+ busChanges.push({ type: "modified", collection, doc: { id, data: merged } });
2465
+ } else if (op.op === "remove") {
2466
+ const existing = await this._store.getDoc(collection, id);
2467
+ await this._queue.enqueue({
2468
+ collection,
2469
+ docId: id,
2470
+ op: "remove",
2471
+ payload: null,
2472
+ baseVersion: existing?.meta.serverVersion ?? null,
2473
+ batchId
2474
+ });
2475
+ await this._store.deleteDoc(collection, id);
2476
+ if (existing && !existing.meta.deleted) {
2477
+ busChanges.push({ type: "removed", collection, doc: { id, data: existing.data } });
2478
+ }
2479
+ }
2480
+ }
2481
+ if (busChanges.length > 0) {
2482
+ this._bus.emit(busChanges);
2483
+ }
2484
+ return { ok: true };
2485
+ }
2486
+ // ── Realtime ─────────────────────────────────────────────────────────────────
2487
+ onDoc(id, cb) {
2488
+ assertValidId(id);
2489
+ this._buildGetResult(id).then((r) => {
2490
+ cb(r ? r.docs[0]?.data ?? null : null);
2491
+ }).catch(() => cb(null));
2492
+ return this._bus.subscribe(this._collection, (changes) => {
2493
+ const relevant = changes.find((c) => c.doc.id === id);
2494
+ if (!relevant) return;
2495
+ if (relevant.type === "removed") {
2496
+ cb(null);
2497
+ } else {
2498
+ cb(relevant.doc.data);
2499
+ }
2500
+ });
2501
+ }
2502
+ onSnapshot(q, cb) {
2503
+ this._buildListResult(q).then((snap) => cb(snap)).catch(() => {
2504
+ });
2505
+ const unsubBus = this._bus.subscribe(this._collection, async (_changes) => {
2506
+ try {
2507
+ const snap = await this._buildListResult(q);
2508
+ const delta = _changes.map((c) => ({
2509
+ type: c.type,
2510
+ doc: { id: c.doc.id, data: c.doc.data }
2511
+ }));
2512
+ cb({ ...snap, changes: delta });
2513
+ } catch {
2514
+ }
2515
+ });
2516
+ const unsubSync = this._engine.onSyncStateChange(async () => {
2517
+ try {
2518
+ const snap = await this._buildListResult(q);
2519
+ cb(snap);
2520
+ } catch {
2521
+ }
2522
+ });
2523
+ let unsubRealtime;
2524
+ if (typeof this._engine.transport.subscribeCollection === "function") {
2525
+ unsubRealtime = this._engine.transport.subscribeCollection(
2526
+ this._collection,
2527
+ async (remoteChanges, needsResync) => {
2528
+ if (needsResync) {
2529
+ return;
2530
+ }
2531
+ for (const rc of remoteChanges) {
2532
+ if (rc.type === "removed" || rc.data === null) {
2533
+ await this._store.deleteDoc(this._collection, rc.docId);
2534
+ this._bus.emit([{
2535
+ type: "removed",
2536
+ collection: this._collection,
2537
+ doc: { id: rc.docId, data: {} }
2538
+ }]);
2539
+ } else {
2540
+ await this._store.putDoc({
2541
+ collection: this._collection,
2542
+ id: rc.docId,
2543
+ data: rc.data,
2544
+ meta: {
2545
+ serverVersion: `rt_${Date.now()}`,
2546
+ updatedAtServer: Date.now(),
2547
+ updatedAtLocal: Date.now(),
2548
+ state: "synced",
2549
+ pendingMutationIds: [],
2550
+ deleted: false,
2551
+ ownerId: null
2552
+ }
2553
+ });
2554
+ this._bus.emit([{
2555
+ type: rc.type,
2556
+ collection: this._collection,
2557
+ doc: { id: rc.docId, data: rc.data }
2558
+ }]);
2559
+ }
2560
+ }
2561
+ }
2562
+ );
2563
+ }
2564
+ return () => {
2565
+ unsubBus();
2566
+ unsubSync();
2567
+ unsubRealtime?.();
2568
+ };
2569
+ }
2570
+ doc(id) {
2571
+ assertValidId(id);
2572
+ const self = this;
2573
+ return {
2574
+ async get() {
2575
+ return self._buildGetResult(id);
2576
+ },
2577
+ async set(data) {
2578
+ return self.set(id, data);
2579
+ },
2580
+ async update(data) {
2581
+ return self.update(id, data);
2582
+ },
2583
+ async remove() {
2584
+ return self.remove(id);
2585
+ },
2586
+ onSnapshot(cb) {
2587
+ self._buildGetResult(id).then((r) => cb(r)).catch(() => cb(null));
2588
+ const unsubBus = self._bus.subscribe(self._collection, async (changes) => {
2589
+ const relevant = changes.find((c) => c.doc.id === id);
2590
+ if (!relevant) return;
2591
+ try {
2592
+ if (relevant.type === "removed") {
2593
+ cb(null);
2594
+ } else {
2595
+ const result = await self._buildGetResult(id);
2596
+ cb(result);
2597
+ }
2598
+ } catch {
2599
+ cb(null);
2600
+ }
2601
+ });
2602
+ const unsubSync = self._engine.onSyncStateChange(async () => {
2603
+ try {
2604
+ const result = await self._buildGetResult(id);
2605
+ cb(result);
2606
+ } catch {
2607
+ cb(null);
2608
+ }
2609
+ });
2610
+ return () => {
2611
+ unsubBus();
2612
+ unsubSync();
2613
+ };
2614
+ }
2615
+ };
2616
+ }
2617
+ };
2618
+ var NeetruDbDocumentsImpl = class {
2619
+ _store;
2620
+ _queue;
2621
+ _bus;
2622
+ _engine;
2623
+ _connectivity;
2624
+ constructor(opts) {
2625
+ this._store = opts.store;
2626
+ this._queue = opts.queue;
2627
+ this._bus = opts.bus;
2628
+ this._engine = opts.engine;
2629
+ this._connectivity = opts.connectivity;
2630
+ }
2631
+ collection(name) {
2632
+ assertValidCollection(name);
2633
+ return new DbCollectionRefImpl(
2634
+ name,
2635
+ this._store,
2636
+ this._queue,
2637
+ this._bus,
2638
+ this._engine,
2639
+ this._connectivity
2640
+ );
2641
+ }
2642
+ get syncState() {
2643
+ return this._engine.getSyncState();
2644
+ }
2645
+ onSyncStateChanged(cb) {
2646
+ return this._engine.onSyncStateChange(cb);
2647
+ }
2648
+ async flush() {
2649
+ return this._engine.flush();
2650
+ }
2651
+ async clearCache() {
2652
+ await this._store.close();
2653
+ await this._store.open();
2654
+ }
2655
+ async getConflicts() {
2656
+ return this._store.listConflicts();
2657
+ }
2658
+ };
2659
+ async function createOfflineDocumentsNamespace(opts) {
2660
+ const store = new LocalStore(opts.dbName);
2661
+ await store.open();
2662
+ const queue = new MutationQueue(store);
2663
+ const resolver = new ConflictResolver();
2664
+ const bus = new ChangeBus();
2665
+ const connectivity = new ConnectivityMonitor({
2666
+ // Se startOnline=false, injeta um navigator falso
2667
+ navigator: opts.startOnline === false ? { onLine: false } : typeof navigator !== "undefined" ? navigator : void 0
2668
+ });
2669
+ const tabCoordinatorLike = opts.singleTab ? (
2670
+ // Fake tab coordinator para single-tab mode (sempre líder)
2671
+ {
2672
+ isLeader: () => true,
2673
+ onRoleChange: (_cb) => {
2674
+ return () => {
2675
+ };
2676
+ }
2677
+ }
2678
+ ) : new TabCoordinator({
2679
+ lockName: `neetru-offline:${opts.dbName}`,
2680
+ channelName: `neetru-offline:${opts.dbName}`
2681
+ });
2682
+ const engine = new SyncEngine({
2683
+ store,
2684
+ queue,
2685
+ resolver,
2686
+ bus,
2687
+ transport: opts.transport,
2688
+ tabCoordinator: tabCoordinatorLike,
2689
+ connectivity,
2690
+ periodicSyncIntervalMs: opts.periodicSyncIntervalMs ?? 5 * 60 * 1e3
2691
+ });
2692
+ return new NeetruDbDocumentsImpl({
2693
+ store,
2694
+ queue,
2695
+ bus,
2696
+ engine,
2697
+ connectivity
2698
+ });
2699
+ }
2700
+
2701
+ // src/db/sql/lease.ts
2702
+ var RENEWAL_THRESHOLD = 0.8;
2703
+ var MIN_RENEWAL_DELAY_MS = 3e4;
2704
+ var SqlLeaseManager = class {
2705
+ _lease;
2706
+ _pool;
2707
+ _orm;
2708
+ _renewalTimer = null;
2709
+ _closed = false;
2710
+ _deps;
2711
+ constructor(lease, pool, orm, deps) {
2712
+ this._lease = lease;
2713
+ this._pool = pool;
2714
+ this._orm = orm;
2715
+ this._deps = {
2716
+ ...deps,
2717
+ now: deps.now ?? (() => Date.now())
2718
+ };
2719
+ this._scheduleRenewal();
2720
+ }
2721
+ // ─── Superfície pública (NeetruSqlClient) ──────────────────────────────────
2722
+ get orm() {
2723
+ this._assertOpen();
2724
+ return this._orm;
2725
+ }
2726
+ async transaction(fn, opts) {
2727
+ this._assertOpen();
2728
+ try {
2729
+ if (opts?.isolationLevel) {
2730
+ return await this._orm.transaction(fn, {
2731
+ isolationLevel: opts.isolationLevel
2732
+ });
2733
+ }
2734
+ return await this._orm.transaction(fn);
2735
+ } catch (err) {
2736
+ throw mapPoolError(err);
2737
+ }
2738
+ }
2739
+ async close() {
2740
+ if (this._closed) return;
2741
+ this._closed = true;
2742
+ this._cancelRenewal();
2743
+ await this._pool.end().catch(() => {
2744
+ });
2745
+ }
2746
+ // ─── Renovação proativa ────────────────────────────────────────────────────
2747
+ /**
2748
+ * Calcula o delay de renovação: momento de ~80% do TTL restante.
2749
+ *
2750
+ * Fórmula: `renewAt = issuedAt + TTL * RENEWAL_THRESHOLD`
2751
+ * = `expiresAt - TTL * (1 - RENEWAL_THRESHOLD)`
2752
+ *
2753
+ * Se o lease já está além do ponto de renovação (ou TTL não calculável),
2754
+ * usa `MIN_RENEWAL_DELAY_MS` como fallback seguro.
2755
+ */
2756
+ _calcRenewalDelayMs() {
2757
+ const expiresAtMs = Date.parse(this._lease.expiresAt);
2758
+ if (!Number.isFinite(expiresAtMs)) return MIN_RENEWAL_DELAY_MS;
2759
+ const now = this._deps.now();
2760
+ const remainingMs = expiresAtMs - now;
2761
+ if (remainingMs <= 0) return MIN_RENEWAL_DELAY_MS;
2762
+ const renewInMs = remainingMs * (1 - RENEWAL_THRESHOLD);
2763
+ return Math.max(MIN_RENEWAL_DELAY_MS, Math.round(renewInMs));
2764
+ }
2765
+ _scheduleRenewal() {
2766
+ if (this._closed) return;
2767
+ const delayMs = this._calcRenewalDelayMs();
2768
+ this._renewalTimer = setTimeout(() => {
2769
+ void this._doRenew();
2770
+ }, delayMs);
2771
+ }
2772
+ _cancelRenewal() {
2773
+ if (this._renewalTimer !== null) {
2774
+ clearTimeout(this._renewalTimer);
2775
+ this._renewalTimer = null;
2776
+ }
2777
+ }
2778
+ async _doRenew() {
2779
+ if (this._closed) return;
2780
+ try {
2781
+ const renewOpts = {
2782
+ leaseId: this._lease.leaseId
2783
+ };
2784
+ if (this._deps.database !== void 0) {
2785
+ renewOpts.database = this._deps.database;
2786
+ }
2787
+ const newLease = await this._deps.fetchLease(renewOpts);
2788
+ await this._swapPool(newLease);
2789
+ } catch (err) {
2790
+ this._renewalTimer = setTimeout(() => {
2791
+ void this._doRenew();
2792
+ }, MIN_RENEWAL_DELAY_MS);
2793
+ if (process.env["NODE_ENV"] !== "production") {
2794
+ console.warn("[SqlLeaseManager] Lease renewal failed, will retry:", err);
2795
+ }
2796
+ return;
2797
+ }
2798
+ this._scheduleRenewal();
2799
+ }
2800
+ /**
2801
+ * Hot-swap do pool: cria pool novo, atualiza ponteiros, drena pool antigo.
2802
+ *
2803
+ * Exposto como método protegido para testes.
2804
+ */
2805
+ async _swapPool(newLease) {
2806
+ const credRotated = newLease.credentialVersion !== this._lease.credentialVersion;
2807
+ if (!credRotated && newLease.leaseId === this._lease.leaseId) {
2808
+ this._lease = newLease;
2809
+ return;
2810
+ }
2811
+ const newPool = this._deps.createPool(newLease);
2812
+ const newOrm = this._deps.createDrizzle(newPool, this._deps.schema);
2813
+ const oldPool = this._pool;
2814
+ this._lease = newLease;
2815
+ this._pool = newPool;
2816
+ this._orm = newOrm;
2817
+ void oldPool.end().catch(() => {
2818
+ });
2819
+ }
2820
+ // ─── Helpers ───────────────────────────────────────────────────────────────
2821
+ _assertOpen() {
2822
+ if (this._closed) {
2823
+ throw new NeetruDbError(
2824
+ "db_unavailable",
2825
+ "SqlLeaseManager foi fechado \u2014 chame close() apenas no shutdown."
2826
+ );
2827
+ }
2828
+ }
2829
+ };
2830
+ function mapPoolError(err) {
2831
+ if (err instanceof NeetruDbError) return err;
2832
+ const message = err instanceof Error ? err.message : String(err);
2833
+ const code = err instanceof Error ? err.code : void 0;
2834
+ if (typeof code === "string" && (code === "ECONNREFUSED" || code === "ENOTFOUND" || code === "ETIMEDOUT")) {
2835
+ return new NeetruDbError(
2836
+ "db_unavailable",
2837
+ `Pool connection failed (${code}): ${message}`
2838
+ );
2839
+ }
2840
+ if (message.includes("statement timeout") || message.includes("lock timeout")) {
2841
+ return new NeetruDbError("db_timeout", `Query timeout: ${message}`);
2842
+ }
2843
+ if (message.includes("40001") || message.includes("40P01") || message.includes("deadlock")) {
2844
+ return new NeetruDbError("db_conflict", `Transaction conflict: ${message}`);
2845
+ }
2846
+ if (message.includes("42501") || message.toLowerCase().includes("permission denied")) {
2847
+ return new NeetruDbError("db_permission_denied", `Permission denied: ${message}`);
2848
+ }
2849
+ return new NeetruDbError("db_unavailable", `Database error: ${message}`);
2850
+ }
2851
+
2852
+ // src/db/sql/sql-client.ts
2853
+ var LEASE_ENDPOINT = "/api/sdk/v1/db/lease";
2854
+ var LEASE_RENEW_ENDPOINT = "/api/sdk/v1/db/lease/renew";
2855
+ function mapEnvToCore(sdkEnv) {
2856
+ if (sdkEnv === "workspace") return "staging";
2857
+ if (sdkEnv === "prod") return "production";
2858
+ return "dev";
2859
+ }
2860
+ function createHttpLeaseFetcher(config) {
2861
+ return async (opts) => {
2862
+ const { httpRequest: httpRequest2 } = await Promise.resolve().then(() => (init_http(), http_exports));
2863
+ const isRenewal = Boolean(opts?.leaseId);
2864
+ const path = isRenewal ? LEASE_RENEW_ENDPOINT : LEASE_ENDPOINT;
2865
+ let body;
2866
+ if (isRenewal) {
2867
+ body = { leaseId: opts.leaseId };
2868
+ } else {
2869
+ body = {
2870
+ productId: config.productId ?? "",
2871
+ environment: mapEnvToCore(config.env ?? "prod")
2872
+ };
2873
+ if (opts?.database !== void 0) {
2874
+ body["database"] = opts.database;
2875
+ }
2876
+ }
2877
+ let raw;
2878
+ try {
2879
+ raw = await httpRequest2(config, {
2880
+ method: "POST",
2881
+ path,
2882
+ body,
2883
+ requireAuth: true,
2884
+ // Lease fetch é idempotente do ponto de vista de segurança — retries OK.
2885
+ retries: 2
2886
+ });
2887
+ } catch (err) {
2888
+ const msg = err instanceof Error ? err.message : String(err);
2889
+ throw new NeetruDbError(
2890
+ "db_unavailable",
2891
+ `Falha ao ${isRenewal ? "renovar" : "obter"} lease SQL: ${msg}`
2892
+ );
2893
+ }
2894
+ return parseLease(raw);
2895
+ };
2896
+ }
2897
+ function parseLease(raw) {
2898
+ if (!raw || typeof raw !== "object") {
2899
+ throw new NeetruDbError("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
2900
+ }
2901
+ const envelope = raw;
2902
+ const leaseObj = envelope["lease"];
2903
+ if (!leaseObj || typeof leaseObj !== "object") {
2904
+ throw new NeetruDbError(
2905
+ "db_unavailable",
2906
+ 'Resposta de lease inv\xE1lida: campo "lease" ausente ou n\xE3o \xE9 objeto. O Core retorna { kind, lease: { leaseId, host, ... } }.'
2907
+ );
2908
+ }
2909
+ const r = leaseObj;
2910
+ function req(field, type) {
2911
+ if (typeof r[field] !== type) {
2912
+ throw new NeetruDbError(
2913
+ "db_unavailable",
2914
+ `Campo obrigat\xF3rio "${field}" ausente ou tipo inv\xE1lido na resposta de lease.`
2915
+ );
2916
+ }
2917
+ return r[field];
2918
+ }
2919
+ return {
2920
+ leaseId: req("leaseId", "string"),
2921
+ host: req("host", "string"),
2922
+ port: typeof r["port"] === "number" ? r["port"] : 5433,
2923
+ dbName: req("dbName", "string"),
2924
+ user: req("user", "string"),
2925
+ password: req("password", "string"),
2926
+ sslca: typeof r["sslca"] === "string" ? r["sslca"] : null,
2927
+ clientCert: typeof r["clientCert"] === "string" ? r["clientCert"] : null,
2928
+ clientKey: typeof r["clientKey"] === "string" ? r["clientKey"] : null,
2929
+ credentialVersion: typeof r["credentialVersion"] === "number" ? r["credentialVersion"] : 1,
2930
+ expiresAt: req("expiresAt", "string")
2931
+ };
2932
+ }
2933
+ async function createSqlClientWithDeps(deps, options) {
2934
+ const depsWithDb = options?.database !== void 0 ? { ...deps, database: options.database } : deps;
2935
+ let lease;
2936
+ try {
2937
+ if (options?.database !== void 0) {
2938
+ lease = await depsWithDb.fetchLease({ database: options.database });
2939
+ } else {
2940
+ lease = await depsWithDb.fetchLease();
2941
+ }
2942
+ } catch (err) {
2943
+ if (err instanceof NeetruDbError) throw err;
2944
+ const msg = err instanceof Error ? err.message : String(err);
2945
+ throw new NeetruDbError("db_unavailable", `Falha ao obter lease inicial: ${msg}`);
2946
+ }
2947
+ let pool;
2948
+ try {
2949
+ pool = depsWithDb.createPool(lease);
2950
+ } catch (err) {
2951
+ const msg = err instanceof Error ? err.message : String(err);
2952
+ throw new NeetruDbError("db_unavailable", `Falha ao abrir pool: ${msg}`);
2953
+ }
2954
+ let orm;
2955
+ try {
2956
+ orm = depsWithDb.createDrizzle(pool, depsWithDb.schema);
2957
+ } catch (err) {
2958
+ await pool.end().catch(() => {
2959
+ });
2960
+ const msg = err instanceof Error ? err.message : String(err);
2961
+ throw new NeetruDbError("db_unavailable", `Falha ao criar handle Drizzle: ${msg}`);
2962
+ }
2963
+ return new SqlLeaseManager(lease, pool, orm, depsWithDb);
2964
+ }
2965
+ async function createSqlClientFromConfig(config, schema, options) {
2966
+ const fetchLease = createHttpLeaseFetcher(config);
2967
+ const createPool = (lease) => {
2968
+ const { Pool } = __require("pg");
2969
+ const ssl = lease.sslca ? {
2970
+ ca: lease.sslca,
2971
+ cert: lease.clientCert ?? void 0,
2972
+ key: lease.clientKey ?? void 0,
2973
+ rejectUnauthorized: true
2974
+ } : false;
2975
+ return new Pool({
2976
+ host: lease.host,
2977
+ port: lease.port,
2978
+ database: lease.dbName,
2979
+ user: lease.user,
2980
+ password: lease.password,
2981
+ ssl,
2982
+ max: 3,
2983
+ idleTimeoutMillis: 3e4,
2984
+ connectionTimeoutMillis: 1e4
2985
+ });
2986
+ };
2987
+ const createDrizzle = (pool, s) => {
2988
+ const { drizzle } = __require("drizzle-orm/node-postgres");
2989
+ return drizzle(pool, { schema: s });
2990
+ };
2991
+ return createSqlClientWithDeps(
2992
+ {
2993
+ fetchLease,
2994
+ createPool,
2995
+ createDrizzle,
2996
+ schema
2997
+ },
2998
+ options
2999
+ );
3000
+ }
3001
+
3002
+ // src/db/realtime/realtime-client.ts
3003
+ var WS_OPEN = 1;
3004
+ var WS_CLOSED = 3;
3005
+ var JITTER_MIN = 0.5;
3006
+ var JITTER_MAX = 1.5;
3007
+ var DEFAULT_BACKOFF_BASE_MS = 1e3;
3008
+ var DEFAULT_BACKOFF_MAX_MS = 3e4;
3009
+ var DEFAULT_HEARTBEAT_INTERVAL_MS = 25e3;
3010
+ var _idCounter = 0;
3011
+ function generateId() {
3012
+ if (typeof globalThis.crypto?.randomUUID === "function") {
3013
+ return globalThis.crypto.randomUUID();
3014
+ }
3015
+ return `nrt-sub-${Date.now()}-${++_idCounter}-${Math.random().toString(36).slice(2)}`;
3016
+ }
3017
+ var NeetruRealtimeClient = class {
3018
+ // ── configuração ──────────────────────────────────────────────────────────
3019
+ _gatewayUrl;
3020
+ _wsFactory;
3021
+ _setTimeout;
3022
+ _clearTimeout;
3023
+ _backoffBaseMs;
3024
+ _backoffMaxMs;
3025
+ _heartbeatIntervalMs;
3026
+ _ticketProvider;
3027
+ /** ID do banco lógico (BL-8) — embutido em query.filter._dbId de cada subscribe. */
3028
+ _dbId;
3029
+ /** Ticket atual — obtido antes de cada abertura de WS e embutido nos frames. */
3030
+ _currentTicket = null;
3031
+ // ── estado interno ────────────────────────────────────────────────────────
3032
+ /** Subscriptions ativas: id → entry */
3033
+ _subscriptions = /* @__PURE__ */ new Map();
3034
+ /** Listeners do estado da conexão. */
3035
+ _stateListeners = [];
3036
+ /** Estado atual da conexão. */
3037
+ _connectionState = "connecting";
3038
+ /** Socket atual (pode ser null entre tentativas). */
3039
+ _ws = null;
3040
+ /** Número da tentativa de reconexão corrente (reseta após conexão bem-sucedida). */
3041
+ _reconnectAttempt = 0;
3042
+ /** Handle do timer de backoff pendente. */
3043
+ _reconnectTimer = null;
3044
+ /** Handle do timer de heartbeat. */
3045
+ _heartbeatTimer = null;
3046
+ /** Indica que o cliente foi encerrado via `close()`. Não reconecta mais. */
3047
+ _closed = false;
3048
+ /**
3049
+ * Frames de subscribe que precisam ser enviados mas a socket ainda não
3050
+ * está aberta (estado CONNECTING). Drenados no onopen.
3051
+ */
3052
+ _pendingFrames = [];
3053
+ // ── construtor ────────────────────────────────────────────────────────────
3054
+ constructor(options) {
3055
+ this._gatewayUrl = options.gatewayUrl;
3056
+ this._wsFactory = options.webSocketFactory ?? defaultWebSocketFactory;
3057
+ this._setTimeout = options.setTimeoutFn ?? globalThis.setTimeout.bind(globalThis);
3058
+ this._clearTimeout = options.clearTimeoutFn ?? globalThis.clearTimeout.bind(globalThis);
3059
+ this._backoffBaseMs = options.backoffBaseMs ?? DEFAULT_BACKOFF_BASE_MS;
3060
+ this._backoffMaxMs = options.backoffMaxMs ?? DEFAULT_BACKOFF_MAX_MS;
3061
+ this._heartbeatIntervalMs = options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
3062
+ this._ticketProvider = options.ticketProvider;
3063
+ this._dbId = options.dbId;
3064
+ this._connect();
3065
+ }
3066
+ // ── API pública ───────────────────────────────────────────────────────────
3067
+ /**
3068
+ * Registra uma subscription em `collection` com `query` opcional.
3069
+ *
3070
+ * Envia um frame `subscribe` ao gateway (ou enfileira se o socket ainda
3071
+ * não está aberto). O `callback` é invocado com cada frame `delta`,
3072
+ * `resync`, `stale` ou `error` roteado para esta subscription.
3073
+ *
3074
+ * @returns O `subscriptionId` opaco — usar para cancelar via `unsubscribe()`.
3075
+ */
3076
+ subscribe(collection, query, callback) {
3077
+ if (this._closed) {
3078
+ return generateId();
3079
+ }
3080
+ const subscriptionId = generateId();
3081
+ this._subscriptions.set(subscriptionId, {
3082
+ subscriptionId,
3083
+ collection,
3084
+ query: Object.keys(query).length > 0 ? query : void 0,
3085
+ callback
3086
+ });
3087
+ const frame = {
3088
+ op: "subscribe",
3089
+ subscriptionId,
3090
+ collection,
3091
+ query: this._buildSubscribeQuery(query)
3092
+ };
3093
+ this._sendOrBuffer(frame);
3094
+ return subscriptionId;
3095
+ }
3096
+ /**
3097
+ * Cancela uma subscription.
3098
+ *
3099
+ * Envia um frame `unsubscribe` ao gateway e remove o listener local.
3100
+ * Frames subsequentes com este `subscriptionId` são silenciosamente descartados.
3101
+ */
3102
+ unsubscribe(subscriptionId) {
3103
+ if (!this._subscriptions.has(subscriptionId)) {
3104
+ return;
3105
+ }
3106
+ this._subscriptions.delete(subscriptionId);
3107
+ const frame = { op: "unsubscribe", subscriptionId };
3108
+ this._sendOrBuffer(frame);
3109
+ }
3110
+ /**
3111
+ * Registra um listener de mudanças no estado da conexão.
3112
+ *
3113
+ * O listener é invocado imediatamente com o estado atual e depois a cada
3114
+ * transição. Retorna uma função `unsubscribe`.
3115
+ */
3116
+ onConnectionState(listener) {
3117
+ this._stateListeners.push(listener);
3118
+ listener(this._connectionState);
3119
+ return () => {
3120
+ this._stateListeners = this._stateListeners.filter((l) => l !== listener);
3121
+ };
3122
+ }
3123
+ /**
3124
+ * Encerra o cliente definitivamente.
3125
+ *
3126
+ * Fecha o socket ativo, cancela timers pendentes e marca o cliente como
3127
+ * encerrado (sem mais reconexões).
3128
+ */
3129
+ close() {
3130
+ this._closed = true;
3131
+ this._cancelReconnectTimer();
3132
+ this._cancelHeartbeatTimer();
3133
+ if (this._ws) {
3134
+ this._detachHandlers(this._ws);
3135
+ if (this._ws.readyState !== WS_CLOSED) {
3136
+ this._ws.close(1e3, "client closed");
3137
+ }
3138
+ this._ws = null;
3139
+ }
3140
+ this._setState("disconnected");
3141
+ }
3142
+ // ── Conexão ───────────────────────────────────────────────────────────────
3143
+ /**
3144
+ * Busca um ticket de autenticação e, em seguida, cria um novo WebSocket e
3145
+ * instala os handlers de evento.
3146
+ *
3147
+ * A busca de ticket é obrigatória antes de abrir qualquer WS (primeira
3148
+ * conexão e reconexões). Se a busca falhar, a conexão é abortada com
3149
+ * estado `'connecting'` e o backoff reconectará em seguida.
3150
+ *
3151
+ * Fail-closed: o WebSocket NUNCA é aberto sem um ticket válido.
3152
+ */
3153
+ _connect() {
3154
+ if (this._closed) return;
3155
+ this._setState("connecting");
3156
+ void this._connectWithTicket();
3157
+ }
3158
+ /** Implementação assíncrona de _connect — busca ticket e abre WS. */
3159
+ async _connectWithTicket() {
3160
+ if (this._closed) return;
3161
+ let ticket;
3162
+ try {
3163
+ ticket = await this._ticketProvider();
3164
+ } catch (err) {
3165
+ if (this._closed) return;
3166
+ const delay = this._computeBackoffDelay(this._reconnectAttempt);
3167
+ this._reconnectAttempt++;
3168
+ this._reconnectTimer = this._setTimeout(() => {
3169
+ this._reconnectTimer = null;
3170
+ if (!this._closed) this._connect();
3171
+ }, delay);
3172
+ return;
3173
+ }
3174
+ if (this._closed) return;
3175
+ this._currentTicket = ticket;
3176
+ const ws = this._wsFactory(this._gatewayUrl);
3177
+ this._ws = ws;
3178
+ ws.onopen = this._handleOpen.bind(this);
3179
+ ws.onmessage = this._handleMessage.bind(this);
3180
+ ws.onclose = this._handleClose.bind(this);
3181
+ ws.onerror = this._handleError.bind(this);
3182
+ }
3183
+ // ── Handlers de WebSocket ─────────────────────────────────────────────────
3184
+ _handleOpen(_event) {
3185
+ if (this._closed) return;
3186
+ this._reconnectAttempt = 0;
3187
+ this._setState("connected");
3188
+ for (const frame of this._pendingFrames) {
3189
+ this._sendNow(frame);
3190
+ }
3191
+ this._pendingFrames = [];
3192
+ this._resubscribeAll();
3193
+ this._scheduleHeartbeat();
3194
+ }
3195
+ _handleMessage(event) {
3196
+ if (this._closed) return;
3197
+ let frame;
3198
+ try {
3199
+ frame = JSON.parse(event.data);
3200
+ } catch {
3201
+ return;
3202
+ }
3203
+ switch (frame.op) {
3204
+ case "delta":
3205
+ case "resync":
3206
+ case "stale":
3207
+ case "error":
3208
+ this._routeToSubscription(frame);
3209
+ break;
3210
+ case "pong":
3211
+ break;
3212
+ case "drain":
3213
+ this._handleDrain();
3214
+ break;
3215
+ }
3216
+ }
3217
+ _handleClose(_event) {
3218
+ if (this._closed) return;
3219
+ this._cancelHeartbeatTimer();
3220
+ this._ws = null;
3221
+ this._scheduleReconnect();
3222
+ }
3223
+ _handleError(_event) {
3224
+ if (this._closed) return;
3225
+ this._setState("connecting");
3226
+ }
3227
+ // ── Drain (graceful shutdown do gateway) ─────────────────────────────────
3228
+ _handleDrain() {
3229
+ if (this._closed) return;
3230
+ this._setState("draining");
3231
+ this._cancelHeartbeatTimer();
3232
+ if (this._ws) {
3233
+ this._detachHandlers(this._ws);
3234
+ if (this._ws.readyState !== WS_CLOSED) {
3235
+ this._ws.close(1001, "drain");
3236
+ }
3237
+ this._ws = null;
3238
+ }
3239
+ this._scheduleReconnect();
3240
+ }
3241
+ // ── Roteamento de frames ──────────────────────────────────────────────────
3242
+ _routeToSubscription(frame) {
3243
+ const entry = this._subscriptions.get(frame.subscriptionId);
3244
+ if (!entry) {
3245
+ return;
3246
+ }
3247
+ try {
3248
+ entry.callback(frame);
3249
+ } catch {
3250
+ }
3251
+ }
3252
+ // ── Resubscrição ──────────────────────────────────────────────────────────
3253
+ /**
3254
+ * Reenvía frames `subscribe` para todas as subscriptions ativas.
3255
+ * Chamado no `onopen` de reconexões para restaurar o estado remoto.
3256
+ *
3257
+ * Durante a PRIMEIRA conexão: _pendingFrames já foi drenado com os
3258
+ * subscribes iniciais acima. ResubscribeAll envia novamente — como a
3259
+ * lista de subscriptions foi populada pelos `subscribe()` calls anteriores
3260
+ * ao open, e os frames drenados também os incluem, teríamos duplicatas.
3261
+ *
3262
+ * Solução: resubscribeAll só é invocado após drenar _pendingFrames, e
3263
+ * como o gateway é idempotente para o mesmo subscriptionId (segundo o
3264
+ * design do componente #19), a duplicata é inócua. Em reconexões, onde
3265
+ * _pendingFrames está vazio, os frames são os únicos enviados.
3266
+ *
3267
+ * Para o caso do primeiro open com subscribes anteriores ao open, os
3268
+ * frames já foram drenados de _pendingFrames — não chamamos resubscribeAll
3269
+ * se era a primeira conexão (_reconnectAttempt era 0 antes de resetar).
3270
+ * Rastreamos isso com _hasConnectedOnce.
3271
+ */
3272
+ _hasConnectedOnce = false;
3273
+ _resubscribeAll() {
3274
+ if (!this._hasConnectedOnce) {
3275
+ this._hasConnectedOnce = true;
3276
+ return;
3277
+ }
3278
+ for (const entry of this._subscriptions.values()) {
3279
+ const frame = {
3280
+ op: "subscribe",
3281
+ subscriptionId: entry.subscriptionId,
3282
+ collection: entry.collection,
3283
+ query: this._buildSubscribeQuery(entry.query ?? {})
3284
+ };
3285
+ this._sendNow(frame);
3286
+ }
3287
+ }
3288
+ // ── Ticket embedding ──────────────────────────────────────────────────────
3289
+ /**
3290
+ * Constrói o descriptor `query` para um frame `subscribe`, embutindo o
3291
+ * `token` do ticket corrente em `query.filter._ticket` e o `_dbId` do
3292
+ * banco lógico em `query.filter._dbId` (BL-8 fix).
3293
+ *
3294
+ * O gateway extrai `filter._ticket` do primeiro frame `subscribe` e valida
3295
+ * contra `POST /api/sdk/v1/db/realtime/validate`. `filter._dbId` é exigido
3296
+ * pelo `@neetru/realtime-changestream._extractDbId` para rotear a
3297
+ * subscription ao banco correto — sem ele a subscription é rejeitada.
3298
+ *
3299
+ * Retorna `undefined` se a query seria vazia E não há ticket (estado
3300
+ * transitório antes do primeiro ticket — não deve ocorrer normalmente pois
3301
+ * `_connect` só abre o WS após obter o ticket).
3302
+ */
3303
+ _buildSubscribeQuery(query) {
3304
+ const ticket = this._currentTicket;
3305
+ const hasUserQuery = Object.keys(query).length > 0;
3306
+ if (!ticket) {
3307
+ return hasUserQuery ? query : void 0;
3308
+ }
3309
+ const mergedFilter = {
3310
+ ...query.filter ?? {},
3311
+ _ticket: ticket.token
3312
+ };
3313
+ if (this._dbId !== void 0) {
3314
+ mergedFilter["_dbId"] = this._dbId;
3315
+ }
3316
+ return {
3317
+ ...query,
3318
+ filter: mergedFilter
3319
+ };
3320
+ }
3321
+ // ── Backoff e reconexão ───────────────────────────────────────────────────
3322
+ /** Agenda uma tentativa de reconexão com backoff exponencial + jitter. */
3323
+ _scheduleReconnect() {
3324
+ if (this._closed) return;
3325
+ this._cancelReconnectTimer();
3326
+ this._setState("connecting");
3327
+ this._currentTicket = null;
3328
+ const delayMs = this._computeBackoffDelay(this._reconnectAttempt);
3329
+ this._reconnectAttempt++;
3330
+ this._reconnectTimer = this._setTimeout(() => {
3331
+ this._reconnectTimer = null;
3332
+ if (!this._closed) {
3333
+ this._connect();
3334
+ }
3335
+ }, delayMs);
3336
+ }
3337
+ /**
3338
+ * Calcula o delay de backoff para o attempt N.
3339
+ *
3340
+ * Fórmula: `min(baseMs * 2^N, maxMs) * jitter`
3341
+ * onde `jitter ∈ [JITTER_MIN, JITTER_MAX]` (±50%).
3342
+ */
3343
+ _computeBackoffDelay(attempt) {
3344
+ const exponential = this._backoffBaseMs * Math.pow(2, attempt);
3345
+ const capped = Math.min(exponential, this._backoffMaxMs);
3346
+ const jitter = JITTER_MIN + Math.random() * (JITTER_MAX - JITTER_MIN);
3347
+ return Math.round(capped * jitter);
3348
+ }
3349
+ _cancelReconnectTimer() {
3350
+ if (this._reconnectTimer !== null) {
3351
+ this._clearTimeout(this._reconnectTimer);
3352
+ this._reconnectTimer = null;
3353
+ }
3354
+ }
3355
+ // ── Heartbeat ─────────────────────────────────────────────────────────────
3356
+ /** Agenda o próximo ping. Não-operacional se heartbeatIntervalMs === 0. */
3357
+ _scheduleHeartbeat() {
3358
+ if (this._heartbeatIntervalMs === 0) return;
3359
+ this._cancelHeartbeatTimer();
3360
+ this._heartbeatTimer = this._setTimeout(() => {
3361
+ this._heartbeatTimer = null;
3362
+ this._sendPing();
3363
+ this._scheduleHeartbeat();
3364
+ }, this._heartbeatIntervalMs);
3365
+ }
3366
+ _cancelHeartbeatTimer() {
3367
+ if (this._heartbeatTimer !== null) {
3368
+ this._clearTimeout(this._heartbeatTimer);
3369
+ this._heartbeatTimer = null;
3370
+ }
3371
+ }
3372
+ _sendPing() {
3373
+ const frame = { op: "ping", subscriptionId: "" };
3374
+ this._sendOrBuffer(frame);
3375
+ }
3376
+ // ── Envio de frames ───────────────────────────────────────────────────────
3377
+ /**
3378
+ * Envia o frame imediatamente se o socket está aberto; caso contrário,
3379
+ * enfileira em `_pendingFrames` para envio no próximo `onopen`.
3380
+ */
3381
+ _sendOrBuffer(frame) {
3382
+ if (this._ws !== null && this._ws.readyState === WS_OPEN) {
3383
+ this._sendNow(frame);
3384
+ } else {
3385
+ if (frame.op !== "unsubscribe") {
3386
+ this._pendingFrames.push(frame);
3387
+ }
3388
+ }
3389
+ }
3390
+ /** Serializa e envia o frame imediatamente via WebSocket. */
3391
+ _sendNow(frame) {
3392
+ if (!this._ws || this._ws.readyState !== WS_OPEN) return;
3393
+ try {
3394
+ this._ws.send(JSON.stringify(frame));
3395
+ } catch {
3396
+ }
3397
+ }
3398
+ // ── Estado da conexão ─────────────────────────────────────────────────────
3399
+ _setState(state) {
3400
+ if (this._connectionState === state) return;
3401
+ this._connectionState = state;
3402
+ for (const listener of this._stateListeners) {
3403
+ try {
3404
+ listener(state);
3405
+ } catch {
3406
+ }
3407
+ }
3408
+ }
3409
+ // ── Desvinculação de handlers ─────────────────────────────────────────────
3410
+ /** Remove todos os handlers de um WebSocket (evita disparo após close()). */
3411
+ _detachHandlers(ws) {
3412
+ ws.onopen = null;
3413
+ ws.onmessage = null;
3414
+ ws.onclose = null;
3415
+ ws.onerror = null;
3416
+ }
3417
+ };
3418
+ var defaultWebSocketFactory = (url) => {
3419
+ if (typeof WebSocket === "undefined") {
3420
+ throw new Error(
3421
+ "[NeetruRealtimeClient] WebSocket n\xE3o dispon\xEDvel neste ambiente. Injete uma implementa\xE7\xE3o via `webSocketFactory` nas op\xE7\xF5es."
3422
+ );
3423
+ }
3424
+ return new WebSocket(url);
3425
+ };
3426
+
3427
+ // src/db/client-db.ts
3428
+ var DATASTORE_COLLECTION_ENDPOINT = (collection) => `/api/sdk/v1/datastore/${encodeURIComponent(collection)}`;
3429
+ var DATASTORE_DOC_ENDPOINT = (collection, docId) => `/api/sdk/v1/datastore/${encodeURIComponent(collection)}/${encodeURIComponent(docId)}`;
3430
+ function resolveTransport(engine, opts, config) {
3431
+ if (opts._transport) {
3432
+ return opts._transport;
3433
+ }
3434
+ if (engine === "firestore") {
3435
+ if (opts.firestoreTransport) {
3436
+ return opts.firestoreTransport;
3437
+ }
3438
+ }
3439
+ if (engine === "nosql-vm" && opts.realtimeGatewayUrl) {
3440
+ return createWebSocketSyncTransport(opts.realtimeGatewayUrl, config, opts);
3441
+ }
3442
+ return createRestSyncTransport(config);
3443
+ }
3444
+ function createRestSyncTransport(config) {
3445
+ return {
3446
+ async pushMutations(mutations) {
3447
+ if (!config) {
3448
+ throw new NeetruDbError(
3449
+ "db_unavailable",
3450
+ "[RestSyncTransport] config n\xE3o dispon\xEDvel \u2014 n\xE3o \xE9 poss\xEDvel enviar ao Core. Inicialize o transporte via createNeetruDb."
3451
+ );
3452
+ }
3453
+ const { httpRequest: httpRequest2 } = await Promise.resolve().then(() => (init_http(), http_exports));
3454
+ const results = [];
3455
+ const tenantScopeId = config.tenantId ?? config.productId;
3456
+ const tenantHeaders = tenantScopeId ? { "x-neetru-tenant": tenantScopeId } : void 0;
3457
+ for (const m of mutations) {
3458
+ try {
3459
+ let raw;
3460
+ if (m.op === "add") {
3461
+ raw = await httpRequest2(config, {
3462
+ method: "POST",
3463
+ path: DATASTORE_COLLECTION_ENDPOINT(m.collection),
3464
+ body: { data: m.payload ?? {} },
3465
+ requireAuth: true,
3466
+ retries: 0,
3467
+ headers: tenantHeaders
3468
+ });
3469
+ } else if (m.op === "set") {
3470
+ raw = await httpRequest2(config, {
3471
+ method: "PUT",
3472
+ path: DATASTORE_DOC_ENDPOINT(m.collection, m.docId),
3473
+ body: { data: m.payload ?? {} },
3474
+ requireAuth: true,
3475
+ retries: 2,
3476
+ headers: tenantHeaders
3477
+ });
3478
+ } else if (m.op === "update") {
3479
+ raw = await httpRequest2(config, {
3480
+ method: "PATCH",
3481
+ path: DATASTORE_DOC_ENDPOINT(m.collection, m.docId),
3482
+ body: { data: m.payload ?? {} },
3483
+ requireAuth: true,
3484
+ retries: 2,
3485
+ headers: tenantHeaders
3486
+ });
3487
+ } else {
3488
+ raw = await httpRequest2(config, {
3489
+ method: "DELETE",
3490
+ path: DATASTORE_DOC_ENDPOINT(m.collection, m.docId),
3491
+ requireAuth: true,
3492
+ retries: 2,
3493
+ headers: tenantHeaders
3494
+ });
3495
+ }
3496
+ const resp = raw;
3497
+ results.push({
3498
+ mutationId: m.mutationId,
3499
+ outcome: "confirmed",
3500
+ serverVersion: resp?.serverVersion ?? resp?.id ?? `rest_${Date.now()}`,
3501
+ serverTimestamp: Date.now()
3502
+ });
3503
+ } catch (err) {
3504
+ const msg = err instanceof Error ? err.message : String(err);
3505
+ throw new NeetruDbError("db_unavailable", `pushMutations falhou: ${msg}`);
3506
+ }
3507
+ }
3508
+ return { results };
3509
+ },
3510
+ async pullChanges(_watermark, _resumeToken) {
3511
+ if (!config) {
3512
+ return { docs: [], newWatermark: Date.now(), resyncRequired: false };
3513
+ }
3514
+ return { docs: [], newWatermark: Date.now(), resyncRequired: false };
3515
+ },
3516
+ async fullResync(_collections) {
3517
+ if (!config) {
3518
+ return { docs: [], newWatermark: Date.now() };
3519
+ }
3520
+ return { docs: [], newWatermark: Date.now() };
3521
+ }
3522
+ };
3523
+ }
3524
+ function createWebSocketSyncTransport(gatewayUrl, config, opts) {
3525
+ const restTransport = createRestSyncTransport(config);
3526
+ const realtimeClient = new NeetruRealtimeClient({
3527
+ gatewayUrl,
3528
+ ticketProvider: buildTicketProvider(config, opts),
3529
+ dbId: opts.dbId,
3530
+ webSocketFactory: opts._wsFactory
3531
+ });
3532
+ return {
3533
+ pushMutations: restTransport.pushMutations.bind(restTransport),
3534
+ pullChanges: restTransport.pullChanges.bind(restTransport),
3535
+ fullResync: restTransport.fullResync.bind(restTransport),
3536
+ // HIGH-1: subscribeCollection — chamado por DbCollectionRefImpl.onSnapshot
3537
+ // quando o engine é nosql-vm. Registra a subscription no NeetruRealtimeClient
3538
+ // e traduz os frames inbound para o contrato de `onChange`.
3539
+ subscribeCollection(collection, onChange) {
3540
+ const subId = realtimeClient.subscribe(collection, {}, (frame) => {
3541
+ if (frame.op === "resync") {
3542
+ onChange([], true);
3543
+ return;
3544
+ }
3545
+ if (frame.op === "stale") {
3546
+ onChange([], true);
3547
+ return;
3548
+ }
3549
+ if (frame.op === "delta" && frame.changes) {
3550
+ const changes = frame.changes.map((c) => ({
3551
+ type: c.type === "insert" ? "added" : c.type === "delete" ? "removed" : "modified",
3552
+ docId: c.documentId,
3553
+ data: c.data ?? null
3554
+ }));
3555
+ if (changes.length > 0) {
3556
+ onChange(changes, false);
3557
+ }
3558
+ }
3559
+ });
3560
+ return () => {
3561
+ realtimeClient.unsubscribe(subId);
3562
+ };
3563
+ }
3564
+ };
3565
+ }
3566
+ function buildTicketProvider(config, opts) {
3567
+ return async () => {
3568
+ const { httpRequest: httpRequest2 } = await Promise.resolve().then(() => (init_http(), http_exports));
3569
+ const ticket = await httpRequest2(config, {
3570
+ method: "POST",
3571
+ path: "/api/sdk/v1/db/realtime/ticket",
3572
+ body: {
3573
+ productId: config.productId ?? "",
3574
+ collections: opts.collections ?? ["*"]
3575
+ },
3576
+ requireAuth: true,
3577
+ retries: 1
3578
+ });
3579
+ return ticket;
3580
+ };
3581
+ }
3582
+ function getWebSocketRealtimeClient(gatewayUrl, ticketProvider, dbId, wsFactory) {
3583
+ return new NeetruRealtimeClient({ gatewayUrl, ticketProvider, dbId, webSocketFactory: wsFactory });
3584
+ }
3585
+ function createNeetruDb(config, dbOpts = {}) {
3586
+ const engine = dbOpts.engine ?? "rest";
3587
+ const transport = resolveTransport(engine, dbOpts, config);
3588
+ const dbId = dbOpts.dbId ?? "default";
3589
+ const dbName = dbOpts.dbName ?? `neetru-db__${config.productId ?? "sdk"}__${dbId}__${config.env}`;
3590
+ let _docsPromise = null;
3591
+ let _docsResolved = null;
3592
+ function getDocsPromise() {
3593
+ if (!_docsPromise) {
3594
+ _docsPromise = createOfflineDocumentsNamespace({
3595
+ dbName,
3596
+ transport,
3597
+ singleTab: dbOpts.singleTab ?? config.env !== "prod"
3598
+ }).then((docs) => {
3599
+ _docsResolved = docs;
3600
+ return docs;
3601
+ });
3602
+ }
3603
+ return _docsPromise;
3604
+ }
3605
+ return {
3606
+ collection(name) {
3607
+ if (_docsResolved) return _docsResolved.collection(name);
3608
+ return createLazyCollectionRef(name, getDocsPromise);
3609
+ },
3610
+ async sql(schema, options) {
3611
+ if (config.env === "dev") {
3612
+ throw new NeetruDbError(
3613
+ "db_unavailable",
3614
+ "[SDK] db.sql() n\xE3o dispon\xEDvel em NEETRU_ENV=dev. Use `neetru dev` para subir o container Postgres local."
3615
+ );
3616
+ }
3617
+ return createSqlClientFromConfig(config, schema, options);
3618
+ },
3619
+ get syncState() {
3620
+ return _docsResolved?.syncState ?? {
3621
+ status: "idle",
3622
+ pendingWrites: 0,
3623
+ lastSyncedAt: null,
3624
+ isLeaderTab: false
3625
+ };
3626
+ },
3627
+ onSyncStateChanged(cb) {
3628
+ if (_docsResolved) return _docsResolved.onSyncStateChanged(cb);
3629
+ let unsub = null;
3630
+ let cancelled = false;
3631
+ getDocsPromise().then((docs) => {
3632
+ if (!cancelled) {
3633
+ unsub = docs.onSyncStateChanged(cb);
3634
+ }
3635
+ });
3636
+ return () => {
3637
+ cancelled = true;
3638
+ unsub?.();
3639
+ };
3640
+ },
3641
+ async flush() {
3642
+ const docs = await getDocsPromise();
3643
+ return docs.flush();
3644
+ },
3645
+ async clearCache() {
3646
+ const docs = await getDocsPromise();
3647
+ return docs.clearCache();
3648
+ },
3649
+ async getConflicts() {
3650
+ const docs = await getDocsPromise();
3651
+ return docs.getConflicts();
3652
+ }
3653
+ };
3654
+ }
3655
+ function createLazyCollectionRef(name, getDocsPromise) {
3656
+ async function getRef() {
3657
+ const docs = await getDocsPromise();
3658
+ return docs.collection(name);
3659
+ }
3660
+ return {
3661
+ async get(id) {
3662
+ return (await getRef()).get(id);
3663
+ },
3664
+ async list(q) {
3665
+ return (await getRef()).list(q);
3666
+ },
3667
+ async add(data) {
3668
+ return (await getRef()).add(data);
3669
+ },
3670
+ async set(id, data) {
3671
+ return (await getRef()).set(id, data);
3672
+ },
3673
+ async update(id, data) {
3674
+ return (await getRef()).update(id, data);
3675
+ },
3676
+ async remove(id) {
3677
+ return (await getRef()).remove(id);
3678
+ },
3679
+ async batch(ops) {
3680
+ return (await getRef()).batch(ops);
3681
+ },
3682
+ onDoc(id, cb) {
3683
+ let unsub = null;
3684
+ let cancelled = false;
3685
+ getRef().then((ref) => {
3686
+ if (!cancelled) {
3687
+ unsub = ref.onDoc(id, cb);
3688
+ }
3689
+ });
3690
+ return () => {
3691
+ cancelled = true;
3692
+ unsub?.();
3693
+ };
3694
+ },
3695
+ onSnapshot(q, cb) {
3696
+ let unsub = null;
3697
+ let cancelled = false;
3698
+ getRef().then((ref) => {
3699
+ if (!cancelled) {
3700
+ unsub = ref.onSnapshot(q, cb);
3701
+ }
3702
+ });
3703
+ return () => {
3704
+ cancelled = true;
3705
+ unsub?.();
3706
+ };
3707
+ },
3708
+ doc(id) {
3709
+ return {
3710
+ async get() {
3711
+ return (await getRef()).doc(id).get();
3712
+ },
3713
+ async set(data) {
3714
+ return (await getRef()).doc(id).set(data);
3715
+ },
3716
+ async update(data) {
3717
+ return (await getRef()).doc(id).update(data);
3718
+ },
3719
+ async remove() {
3720
+ return (await getRef()).doc(id).remove();
3721
+ },
3722
+ onSnapshot(cb) {
3723
+ let unsub = null;
3724
+ let cancelled = false;
3725
+ getRef().then((ref) => {
3726
+ if (!cancelled) {
3727
+ unsub = ref.doc(id).onSnapshot(cb);
3728
+ }
267
3729
  });
268
- return { ok: true };
3730
+ return () => {
3731
+ cancelled = true;
3732
+ unsub?.();
3733
+ };
269
3734
  }
270
3735
  };
271
3736
  }
272
3737
  };
273
3738
  }
274
3739
 
275
- exports.createDbNamespace = createDbNamespace;
3740
+ exports.NeetruDbError = NeetruDbError;
3741
+ exports.createNeetruDb = createNeetruDb;
3742
+ exports.createRestSyncTransport = createRestSyncTransport;
3743
+ exports.getWebSocketRealtimeClient = getWebSocketRealtimeClient;
276
3744
  //# sourceMappingURL=db.cjs.map
277
3745
  //# sourceMappingURL=db.cjs.map