@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/index.mjs CHANGED
@@ -1,28 +1,46 @@
1
- // src/errors.ts
2
- var NeetruError = class _NeetruError extends Error {
3
- code;
4
- status;
5
- requestId;
6
- constructor(code, message, status, requestId) {
7
- super(message);
8
- this.name = "NeetruError";
9
- this.code = code;
10
- this.status = status;
11
- this.requestId = requestId;
12
- Object.setPrototypeOf(this, _NeetruError.prototype);
13
- }
1
+ import { openDB } from 'idb';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
6
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
7
+ }) : x)(function(x) {
8
+ if (typeof require !== "undefined") return require.apply(this, arguments);
9
+ throw Error('Dynamic require of "' + x + '" is not supported');
10
+ });
11
+ var __esm = (fn, res) => function __init() {
12
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
13
+ };
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
14
17
  };
15
18
 
16
- // src/types.ts
17
- var DEFAULT_BASE_URL = "https://api.neetru.com";
19
+ // src/errors.ts
20
+ var NeetruError;
21
+ var init_errors = __esm({
22
+ "src/errors.ts"() {
23
+ NeetruError = class _NeetruError extends Error {
24
+ code;
25
+ status;
26
+ requestId;
27
+ constructor(code, message, status, requestId) {
28
+ super(message);
29
+ this.name = "NeetruError";
30
+ this.code = code;
31
+ this.status = status;
32
+ this.requestId = requestId;
33
+ Object.setPrototypeOf(this, _NeetruError.prototype);
34
+ }
35
+ };
36
+ }
37
+ });
18
38
 
19
39
  // src/http.ts
20
- var DEFAULT_RETRIES = 2;
21
- var RETRYABLE_CODES = /* @__PURE__ */ new Set([
22
- "rate_limited",
23
- "server_error",
24
- "network_error"
25
- ]);
40
+ var http_exports = {};
41
+ __export(http_exports, {
42
+ httpRequest: () => httpRequest
43
+ });
26
44
  function backoffMs(attempt) {
27
45
  const base = 200 * Math.pow(4, attempt);
28
46
  const jitter = base * 0.2 * (Math.random() * 2 - 1);
@@ -140,8 +158,28 @@ async function httpRequest(config, opts) {
140
158
  }
141
159
  throw lastError ?? new NeetruError("unknown", "unexpected httpRequest exit");
142
160
  }
161
+ var DEFAULT_RETRIES, RETRYABLE_CODES;
162
+ var init_http = __esm({
163
+ "src/http.ts"() {
164
+ init_errors();
165
+ DEFAULT_RETRIES = 2;
166
+ RETRYABLE_CODES = /* @__PURE__ */ new Set([
167
+ "rate_limited",
168
+ "server_error",
169
+ "network_error"
170
+ ]);
171
+ }
172
+ });
173
+
174
+ // src/auth.ts
175
+ init_errors();
176
+
177
+ // src/types.ts
178
+ var DEFAULT_BASE_URL = "https://api.neetru.com";
143
179
 
144
180
  // src/catalog.ts
181
+ init_errors();
182
+ init_http();
145
183
  function toProduct(raw) {
146
184
  if (!raw || typeof raw !== "object") {
147
185
  throw new NeetruError("invalid_response", "Catalog response item is not an object");
@@ -219,6 +257,8 @@ function createCatalogNamespace(config) {
219
257
  }
220
258
 
221
259
  // src/entitlements.ts
260
+ init_errors();
261
+ init_http();
222
262
  function toEntitlementCheck(raw) {
223
263
  if (!raw || typeof raw !== "object") {
224
264
  throw new NeetruError("invalid_response", "Entitlement response is not an object");
@@ -297,6 +337,8 @@ function createEntitlementsNamespace(config) {
297
337
  }
298
338
 
299
339
  // src/telemetry.ts
340
+ init_errors();
341
+ init_http();
300
342
  var VALID_LOG_LEVELS = ["debug", "info", "warn", "error", "fatal"];
301
343
  function consoleFor(level) {
302
344
  switch (level) {
@@ -492,6 +534,8 @@ function createTelemetryNamespace(config) {
492
534
  }
493
535
 
494
536
  // src/usage.ts
537
+ init_errors();
538
+ init_http();
495
539
  function toQuota(metric, raw) {
496
540
  if (!raw || typeof raw !== "object") {
497
541
  throw new NeetruError("invalid_response", "Quota response is not an object");
@@ -573,263 +617,3694 @@ function createUsageNamespace(config) {
573
617
  "tenantId required (pass to options or set on createNeetruClient)"
574
618
  );
575
619
  }
576
- const raw = await httpRequest(config, {
577
- method: "POST",
578
- path: "/sdk/v1/usage/record",
579
- body: { productId, tenantId, resource, qty: Math.floor(qty) },
580
- requireAuth: true
581
- });
582
- if (!raw || raw.ok !== true) {
583
- throw new NeetruError("invalid_response", "usage.report response missing ok");
620
+ const raw = await httpRequest(config, {
621
+ method: "POST",
622
+ path: "/sdk/v1/usage/record",
623
+ body: { productId, tenantId, resource, qty: Math.floor(qty) },
624
+ requireAuth: true
625
+ });
626
+ if (!raw || raw.ok !== true) {
627
+ throw new NeetruError("invalid_response", "usage.report response missing ok");
628
+ }
629
+ return {
630
+ ok: true,
631
+ counterId: raw.counterId,
632
+ value: raw.value,
633
+ limit: raw.limit,
634
+ remaining: raw.remaining,
635
+ status: raw.status
636
+ };
637
+ },
638
+ /**
639
+ * v0.3 — Verifica entitlement de um resource via GET /sdk/v1/entitlements.
640
+ */
641
+ async check(resource, options) {
642
+ if (!resource || typeof resource !== "string") {
643
+ throw new NeetruError("validation_failed", "resource is required");
644
+ }
645
+ const productId = options?.productId ?? config.productId;
646
+ const tenantId = options?.tenantId ?? config.tenantId;
647
+ if (!productId || !tenantId) {
648
+ throw new NeetruError(
649
+ "validation_failed",
650
+ "productId and tenantId required"
651
+ );
652
+ }
653
+ const raw = await httpRequest(config, {
654
+ method: "GET",
655
+ path: "/sdk/v1/entitlements",
656
+ query: { productId, tenantId, feature: resource },
657
+ requireAuth: true
658
+ });
659
+ if (!raw || typeof raw.allowed !== "boolean") {
660
+ throw new NeetruError("invalid_response", "usage.check response missing allowed");
661
+ }
662
+ return {
663
+ allowed: raw.allowed,
664
+ reason: raw.reason,
665
+ remaining: raw.remaining,
666
+ limit: raw.limit,
667
+ planId: raw.planId,
668
+ planFeatures: raw.planFeatures
669
+ };
670
+ }
671
+ };
672
+ }
673
+
674
+ // src/support.ts
675
+ init_errors();
676
+ init_http();
677
+ var VALID_SEVERITIES = ["low", "normal", "high", "urgent"];
678
+ var VALID_STATUSES = ["open", "pending", "resolved", "closed"];
679
+ function toTicket(raw) {
680
+ if (!raw || typeof raw !== "object") {
681
+ throw new NeetruError("invalid_response", "Ticket response is not an object");
682
+ }
683
+ const r = raw;
684
+ if (typeof r.id !== "string") {
685
+ throw new NeetruError("invalid_response", "Ticket missing id");
686
+ }
687
+ return {
688
+ id: r.id,
689
+ subject: typeof r.subject === "string" ? r.subject : "",
690
+ message: typeof r.message === "string" ? r.message : "",
691
+ severity: VALID_SEVERITIES.includes(r.severity) ? r.severity : "normal",
692
+ status: VALID_STATUSES.includes(r.status) ? r.status : "open",
693
+ createdAt: typeof r.createdAt === "string" ? r.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
694
+ updatedAt: typeof r.updatedAt === "string" ? r.updatedAt : void 0,
695
+ productSlug: typeof r.productSlug === "string" ? r.productSlug : void 0
696
+ };
697
+ }
698
+ function createSupportNamespace(config) {
699
+ return {
700
+ /**
701
+ * Cria um ticket de suporte. Requer Bearer auth. Se `productSlug` não é
702
+ * passado, o backend infere do escopo do token.
703
+ */
704
+ async createTicket(input) {
705
+ if (!input || typeof input !== "object") {
706
+ throw new NeetruError("validation_failed", "input is required");
707
+ }
708
+ if (!input.subject || typeof input.subject !== "string") {
709
+ throw new NeetruError("validation_failed", "subject is required");
710
+ }
711
+ if (input.subject.length > 200) {
712
+ throw new NeetruError("validation_failed", "subject max 200 chars");
713
+ }
714
+ if (!input.message || typeof input.message !== "string") {
715
+ throw new NeetruError("validation_failed", "message is required");
716
+ }
717
+ if (input.message.length > 1e4) {
718
+ throw new NeetruError("validation_failed", "message max 10000 chars");
719
+ }
720
+ if (input.severity && !VALID_SEVERITIES.includes(input.severity)) {
721
+ throw new NeetruError("validation_failed", `severity must be one of ${VALID_SEVERITIES.join(", ")}`);
722
+ }
723
+ const slug = input.productSlug ?? "_default";
724
+ const body = {
725
+ subject: input.subject,
726
+ message: input.message,
727
+ severity: input.severity ?? "normal"
728
+ };
729
+ const raw = await httpRequest(config, {
730
+ method: "POST",
731
+ path: `/api/v1/products/${encodeURIComponent(slug)}/tickets`,
732
+ body,
733
+ requireAuth: true
734
+ });
735
+ const candidate = raw && typeof raw === "object" && "ticket" in raw ? raw.ticket : raw;
736
+ return toTicket(candidate);
737
+ },
738
+ /**
739
+ * Lista tickets do customer no produto atual (escopo do token).
740
+ */
741
+ async listMyTickets() {
742
+ const raw = await httpRequest(config, {
743
+ method: "GET",
744
+ path: "/api/v1/products/_default/tickets",
745
+ requireAuth: true
746
+ });
747
+ const list = Array.isArray(raw) ? raw : raw && typeof raw === "object" && "tickets" in raw ? raw.tickets ?? [] : [];
748
+ return list.map(toTicket);
749
+ }
750
+ };
751
+ }
752
+
753
+ // src/db-errors.ts
754
+ init_errors();
755
+ var RETRYABLE_CODES2 = /* @__PURE__ */ new Set([
756
+ "db_unavailable",
757
+ "db_conflict",
758
+ "db_timeout"
759
+ ]);
760
+ var NeetruDbError = class _NeetruDbError extends NeetruError {
761
+ /** Código de erro fechado — específico de DB. */
762
+ code;
763
+ /**
764
+ * `true` para erros transientes que o produto pode tentar novamente.
765
+ * São retryable: `db_unavailable`, `db_conflict`, `db_timeout`.
766
+ */
767
+ retryable;
768
+ /**
769
+ * ID opaco do banco lógico — só para correlação com logs do Core.
770
+ * Nunca deve ser exibido ao usuário final.
771
+ */
772
+ dbId;
773
+ constructor(code, message, dbId) {
774
+ super(code, message);
775
+ this.name = "NeetruDbError";
776
+ this.code = code;
777
+ this.retryable = RETRYABLE_CODES2.has(code);
778
+ this.dbId = dbId;
779
+ Object.setPrototypeOf(this, _NeetruDbError.prototype);
780
+ }
781
+ };
782
+
783
+ // src/db/offline/query-engine.ts
784
+ function typeRank(v) {
785
+ if (v === null || v === void 0) return 0;
786
+ if (typeof v === "number") return 1;
787
+ if (typeof v === "string") return 2;
788
+ if (typeof v === "boolean") return 3;
789
+ return 4;
790
+ }
791
+ function compareValues(a, b) {
792
+ const ra = typeRank(a);
793
+ const rb = typeRank(b);
794
+ if (ra !== rb) return ra - rb;
795
+ if (a === null || a === void 0) return 0;
796
+ if (typeof a === "number" && typeof b === "number") return a - b;
797
+ if (typeof a === "string" && typeof b === "string") return a < b ? -1 : a > b ? 1 : 0;
798
+ if (typeof a === "boolean" && typeof b === "boolean") return a === b ? 0 : a ? 1 : -1;
799
+ const sa = String(a);
800
+ const sb = String(b);
801
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
802
+ }
803
+ function getField(data, field) {
804
+ const parts = field.split(".");
805
+ let current = data;
806
+ for (const part of parts) {
807
+ if (current === null || current === void 0 || typeof current !== "object") {
808
+ return void 0;
809
+ }
810
+ current = current[part];
811
+ }
812
+ return current;
813
+ }
814
+ function evaluateFilter(data, filter) {
815
+ const fieldValue = getField(data, filter.field);
816
+ if (fieldValue === void 0) return false;
817
+ const { op, value } = filter;
818
+ switch (op) {
819
+ case "==":
820
+ return fieldValue === value;
821
+ case "!=":
822
+ return fieldValue !== value;
823
+ case "<":
824
+ return compareValues(fieldValue, value) < 0;
825
+ case "<=":
826
+ return compareValues(fieldValue, value) <= 0;
827
+ case ">":
828
+ return compareValues(fieldValue, value) > 0;
829
+ case ">=":
830
+ return compareValues(fieldValue, value) >= 0;
831
+ case "array-contains":
832
+ return Array.isArray(fieldValue) && fieldValue.includes(value);
833
+ case "in":
834
+ if (!Array.isArray(value)) return false;
835
+ return value.includes(fieldValue);
836
+ case "not-in":
837
+ if (!Array.isArray(value)) return true;
838
+ return !value.includes(fieldValue);
839
+ default:
840
+ return false;
841
+ }
842
+ }
843
+ function matchesAllFilters(data, filters) {
844
+ return filters.every((f) => evaluateFilter(data, f));
845
+ }
846
+ function buildComparator(orderBy) {
847
+ return (a, b) => {
848
+ if (orderBy) {
849
+ const aVal = getField(a.data, orderBy.field);
850
+ const bVal = getField(b.data, orderBy.field);
851
+ const cmp = compareValues(aVal, bVal);
852
+ if (cmp !== 0) {
853
+ return orderBy.direction === "desc" ? -cmp : cmp;
854
+ }
855
+ }
856
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
857
+ };
858
+ }
859
+ function applyCursor(sorted, cursor) {
860
+ const idx = sorted.findIndex((d) => d.id === cursor.docId);
861
+ if (idx === -1) {
862
+ return sorted;
863
+ }
864
+ if (cursor.type === "startAfter") {
865
+ return sorted.slice(idx + 1);
866
+ } else {
867
+ return sorted.slice(0, idx);
868
+ }
869
+ }
870
+ var QueryEngine = class _QueryEngine {
871
+ /**
872
+ * Avalia um `QueryDescriptor` contra um array de `OfflineDoc`.
873
+ *
874
+ * Pipeline (I3 §5.3):
875
+ * 1. Filtra docs com `deleted:false`.
876
+ * 2. Aplica `where` (AND de todos os filtros).
877
+ * 3. Ordena por `orderBy` + tie-break por docId.
878
+ * 4. Aplica cursor (`startAfter` / `endBefore`).
879
+ * 5. Corta em `limit`.
880
+ */
881
+ evaluate(docs, query) {
882
+ let filtered = docs.filter((d) => !d.meta.deleted);
883
+ const filters = query.where ?? [];
884
+ if (filters.length > 0) {
885
+ filtered = filtered.filter(
886
+ (d) => matchesAllFilters(d.data, filters)
887
+ );
888
+ }
889
+ const comparator = buildComparator(query.orderBy);
890
+ const sorted = [...filtered].sort(comparator);
891
+ const afterCursor = query.cursor ? applyCursor(sorted, query.cursor) : sorted;
892
+ const limitN = Math.min(query.limit ?? 20, 500);
893
+ const limited = afterCursor.slice(0, limitN);
894
+ return {
895
+ docs: limited.map((d) => ({ id: d.id, data: d.data })),
896
+ // `incomplete` é sempre true aqui — o QueryEngine não sabe se o cache
897
+ // tem todos os docs da coleção. É responsabilidade do chamador (LocalStore)
898
+ // injetar o flag de completude baseado nos metadados do query_cache.
899
+ incomplete: true
900
+ };
901
+ }
902
+ // ─── Static helper ─────────────────────────────────────────────────────────
903
+ /**
904
+ * Helper estático para uso sem instanciar a classe.
905
+ * Equivalente a `new QueryEngine().evaluate(docs, query)`.
906
+ */
907
+ static evaluate(docs, query) {
908
+ return new _QueryEngine().evaluate(docs, query);
909
+ }
910
+ };
911
+
912
+ // src/db/offline/local-store.ts
913
+ var SCHEMA_VERSION = 1;
914
+ var STORE_DOCUMENTS = "documents";
915
+ var STORE_MUTATIONS = "mutations";
916
+ var STORE_QUERY_CACHE = "query_cache";
917
+ var STORE_SYNC_META = "sync_meta";
918
+ var STORE_CONFLICT_LOG = "conflict_log";
919
+ var LocalStore = class {
920
+ db = null;
921
+ dbName;
922
+ constructor(dbName) {
923
+ this.dbName = dbName;
924
+ }
925
+ // ─── Ciclo de vida ──────────────────────────────────────────────────────────
926
+ /**
927
+ * Abre (ou reabre) o banco IndexedDB e executa o upgrade de schema se necessário.
928
+ * Idempotente — chamadas subsequentes são no-ops se o banco já está aberto.
929
+ */
930
+ async open() {
931
+ if (this.db !== null) return;
932
+ this.db = await openDB(this.dbName, SCHEMA_VERSION, {
933
+ upgrade(db) {
934
+ if (!db.objectStoreNames.contains(STORE_DOCUMENTS)) {
935
+ const docsStore = db.createObjectStore(STORE_DOCUMENTS, {
936
+ keyPath: ["collection", "id"]
937
+ });
938
+ docsStore.createIndex("by_collection", "collection");
939
+ docsStore.createIndex("by_collection_state", ["collection", "meta.state"]);
940
+ docsStore.createIndex("by_updatedAtServer", "meta.updatedAtServer");
941
+ }
942
+ if (!db.objectStoreNames.contains(STORE_MUTATIONS)) {
943
+ const mutStore = db.createObjectStore(STORE_MUTATIONS, {
944
+ keyPath: "mutationId"
945
+ });
946
+ mutStore.createIndex("by_seq", "seq");
947
+ mutStore.createIndex("by_status", "status");
948
+ mutStore.createIndex("by_doc", ["collection", "docId"]);
949
+ mutStore.createIndex("by_batch", "batchId");
950
+ }
951
+ if (!db.objectStoreNames.contains(STORE_QUERY_CACHE)) {
952
+ db.createObjectStore(STORE_QUERY_CACHE, { keyPath: "queryHash" });
953
+ }
954
+ if (!db.objectStoreNames.contains(STORE_SYNC_META)) {
955
+ db.createObjectStore(STORE_SYNC_META, { keyPath: "key" });
956
+ }
957
+ if (!db.objectStoreNames.contains(STORE_CONFLICT_LOG)) {
958
+ const conflictStore = db.createObjectStore(STORE_CONFLICT_LOG, {
959
+ keyPath: "id",
960
+ autoIncrement: true
961
+ });
962
+ conflictStore.createIndex("by_delivered", "delivered");
963
+ conflictStore.createIndex("by_doc", ["collection", "docId"]);
964
+ }
965
+ }
966
+ });
967
+ }
968
+ /** Fecha o banco IndexedDB. */
969
+ async close() {
970
+ this.db?.close();
971
+ this.db = null;
972
+ }
973
+ assertOpen() {
974
+ if (this.db === null) {
975
+ throw new Error("LocalStore: banco n\xE3o est\xE1 aberto. Chame open() primeiro.");
976
+ }
977
+ return this.db;
978
+ }
979
+ // ─── Documents ──────────────────────────────────────────────────────────────
980
+ /**
981
+ * Retorna um documento pelo [collection, id], ou `null` se não existir.
982
+ * Retorna tombstones (deleted: true) — o chamador decide se deve mostrá-los.
983
+ */
984
+ async getDoc(collection, id) {
985
+ const db = this.assertOpen();
986
+ const result = await db.get(STORE_DOCUMENTS, [collection, id]);
987
+ return result ?? null;
988
+ }
989
+ /**
990
+ * Insere ou atualiza um documento na store `documents`.
991
+ * O documento é identificado pelo keyPath composto `[collection, id]`.
992
+ */
993
+ async putDoc(doc) {
994
+ const db = this.assertOpen();
995
+ await db.put(STORE_DOCUMENTS, doc);
996
+ }
997
+ /**
998
+ * Marca um documento como tombstone (`deleted: true`).
999
+ * Não remove fisicamente — o tombstone é necessário para reconciliação.
1000
+ * No-op se o documento não existir.
1001
+ */
1002
+ async deleteDoc(collection, id) {
1003
+ const db = this.assertOpen();
1004
+ const existing = await db.get(STORE_DOCUMENTS, [collection, id]);
1005
+ if (!existing) return;
1006
+ await db.put(STORE_DOCUMENTS, {
1007
+ ...existing,
1008
+ meta: {
1009
+ ...existing.meta,
1010
+ deleted: true,
1011
+ updatedAtLocal: Date.now()
1012
+ }
1013
+ });
1014
+ }
1015
+ /**
1016
+ * Lista documentos de uma coleção, aplicando o QueryDescriptor via QueryEngine.
1017
+ *
1018
+ * I3 §5.3: a listagem lê todos os docs da coleção pelo índice `by_collection`
1019
+ * e delega a filtragem/ordenação/paginação ao QueryEngine (que opera em memória).
1020
+ */
1021
+ async listDocs(collection, query) {
1022
+ const db = this.assertOpen();
1023
+ const rawDocs = await db.getAllFromIndex(STORE_DOCUMENTS, "by_collection", collection);
1024
+ return QueryEngine.evaluate(rawDocs, query);
1025
+ }
1026
+ // ─── Sync meta (key-value) ──────────────────────────────────────────────────
1027
+ /**
1028
+ * Retorna o valor de uma chave da store `sync_meta`, ou `null` se não existir.
1029
+ *
1030
+ * Chaves conhecidas (I3 §3.3):
1031
+ * 'lastSyncWatermark', 'resumeToken:<col>', 'schemaVersion',
1032
+ * 'lastFullResyncAt', 'leaderTabId'.
1033
+ */
1034
+ async getMeta(key) {
1035
+ const db = this.assertOpen();
1036
+ const entry = await db.get(STORE_SYNC_META, key);
1037
+ if (!entry) return null;
1038
+ return entry.value;
1039
+ }
1040
+ /**
1041
+ * Armazena ou atualiza um valor na store `sync_meta`.
1042
+ */
1043
+ async setMeta(key, value) {
1044
+ const db = this.assertOpen();
1045
+ await db.put(STORE_SYNC_META, { key, value });
1046
+ }
1047
+ // ─── Conflict log ───────────────────────────────────────────────────────────
1048
+ /**
1049
+ * Adiciona um registro de conflito ao `conflict_log`.
1050
+ * O `id` é autoIncrement — não deve ser fornecido pelo chamador.
1051
+ */
1052
+ async appendConflict(record) {
1053
+ const db = this.assertOpen();
1054
+ const id = await db.add(STORE_CONFLICT_LOG, record);
1055
+ return { ...record, id };
1056
+ }
1057
+ /**
1058
+ * Lista registros do `conflict_log`.
1059
+ * Filtra por `delivered` se a opção for fornecida.
1060
+ */
1061
+ async listConflicts(options) {
1062
+ const db = this.assertOpen();
1063
+ const all = await db.getAll(STORE_CONFLICT_LOG);
1064
+ if (options?.delivered !== void 0) {
1065
+ return all.filter((r) => r.delivered === options.delivered);
1066
+ }
1067
+ return all;
1068
+ }
1069
+ /**
1070
+ * Marca um registro do `conflict_log` como entregue ao produto.
1071
+ */
1072
+ async markConflictDelivered(id) {
1073
+ const db = this.assertOpen();
1074
+ const existing = await db.get(STORE_CONFLICT_LOG, id);
1075
+ if (!existing) return;
1076
+ await db.put(STORE_CONFLICT_LOG, { ...existing, delivered: true });
1077
+ }
1078
+ // ─── Mutations (acessores usados pelo MutationQueue) ────────────────────────
1079
+ /**
1080
+ * Insere ou atualiza uma mutação na store `mutations`.
1081
+ * Key: `mutationId`.
1082
+ */
1083
+ async putMutation(mutation) {
1084
+ const db = this.assertOpen();
1085
+ await db.put(STORE_MUTATIONS, mutation);
1086
+ }
1087
+ /**
1088
+ * Retorna uma mutação pelo `mutationId`, ou `null` se não existir.
1089
+ */
1090
+ async getMutation(mutationId) {
1091
+ const db = this.assertOpen();
1092
+ const result = await db.get(STORE_MUTATIONS, mutationId);
1093
+ return result ?? null;
1094
+ }
1095
+ /**
1096
+ * Lista mutações com filtros opcionais.
1097
+ * Resultado ordenado por `seq` crescente.
1098
+ */
1099
+ async listMutations(options) {
1100
+ const db = this.assertOpen();
1101
+ let mutations;
1102
+ if (options?.status !== void 0) {
1103
+ mutations = await db.getAllFromIndex(STORE_MUTATIONS, "by_status", options.status);
1104
+ } else if (options?.collection !== void 0 && options.docId !== void 0) {
1105
+ mutations = await db.getAllFromIndex(STORE_MUTATIONS, "by_doc", [options.collection, options.docId]);
1106
+ } else {
1107
+ mutations = await db.getAllFromIndex(STORE_MUTATIONS, "by_seq");
1108
+ }
1109
+ return mutations.sort((a, b) => a.seq - b.seq);
1110
+ }
1111
+ /**
1112
+ * Remove uma mutação pelo `mutationId`.
1113
+ * No-op se não existir.
1114
+ */
1115
+ async deleteMutation(mutationId) {
1116
+ const db = this.assertOpen();
1117
+ await db.delete(STORE_MUTATIONS, mutationId);
1118
+ }
1119
+ // ─── Collection discovery ────────────────────────────────────────────────────
1120
+ /**
1121
+ * Retorna a lista de coleções únicas presentes na store `documents`.
1122
+ *
1123
+ * Usado pelo SyncEngine no full resync para descobrir coleções cujos docs
1124
+ * precisam ser verificados contra a resposta do servidor (tombstone detection).
1125
+ *
1126
+ * Implementação: itera o índice `by_collection` com `openKeyCursor` para
1127
+ * coletar os valores únicos de forma eficiente (sem carregar os docs completos).
1128
+ */
1129
+ async listCollections() {
1130
+ const db = this.assertOpen();
1131
+ const allDocs = await db.getAllFromIndex(STORE_DOCUMENTS, "by_collection");
1132
+ const collections = /* @__PURE__ */ new Set();
1133
+ for (const doc of allDocs) {
1134
+ collections.add(doc.collection);
1135
+ }
1136
+ return Array.from(collections);
1137
+ }
1138
+ // ─── Query cache ─────────────────────────────────────────────────────────────
1139
+ /**
1140
+ * Retorna a entrada de `query_cache` para um hash de query, ou `null`.
1141
+ */
1142
+ async getQueryCache(queryHash) {
1143
+ const db = this.assertOpen();
1144
+ const result = await db.get(STORE_QUERY_CACHE, queryHash);
1145
+ return result ?? null;
1146
+ }
1147
+ /**
1148
+ * Insere ou atualiza uma entrada de `query_cache`.
1149
+ */
1150
+ async putQueryCache(entry) {
1151
+ const db = this.assertOpen();
1152
+ await db.put(STORE_QUERY_CACHE, entry);
1153
+ }
1154
+ /**
1155
+ * Remove uma entrada de `query_cache` pelo queryHash.
1156
+ */
1157
+ async deleteQueryCache(queryHash) {
1158
+ const db = this.assertOpen();
1159
+ await db.delete(STORE_QUERY_CACHE, queryHash);
1160
+ }
1161
+ };
1162
+
1163
+ // src/db/offline/mutation-queue.ts
1164
+ function generateUUIDv4() {
1165
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
1166
+ return crypto.randomUUID();
1167
+ }
1168
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1169
+ const r = Math.random() * 16 | 0;
1170
+ const v = c === "x" ? r : r & 3 | 8;
1171
+ return v.toString(16);
1172
+ });
1173
+ }
1174
+ var MutationQueue = class {
1175
+ store;
1176
+ /**
1177
+ * Ponteiro de sequência local.
1178
+ * Inicializado com 0 — o primeiro enqueue sincroniza o valor real do banco
1179
+ * (`_syncSeq`), garantindo que nunca sobreponha um seq existente.
1180
+ */
1181
+ seqCounter = 0;
1182
+ seqSynced = false;
1183
+ constructor(store) {
1184
+ this.store = store;
1185
+ }
1186
+ // ─── Seq management ─────────────────────────────────────────────────────────
1187
+ /**
1188
+ * Sincroniza o ponteiro de seq com o maior seq existente no banco.
1189
+ * Chamado lazy no primeiro enqueue.
1190
+ */
1191
+ async syncSeq() {
1192
+ if (this.seqSynced) return;
1193
+ const all = await this.store.listMutations();
1194
+ if (all.length > 0) {
1195
+ const maxSeq = Math.max(...all.map((m) => m.seq));
1196
+ this.seqCounter = maxSeq;
1197
+ }
1198
+ this.seqSynced = true;
1199
+ }
1200
+ nextSeq() {
1201
+ this.seqCounter += 1;
1202
+ return this.seqCounter;
1203
+ }
1204
+ // ─── Coalescing ─────────────────────────────────────────────────────────────
1205
+ /**
1206
+ * Tenta coalescir `newOp`/`newPayload` com a mutação existente `existing`.
1207
+ *
1208
+ * Regras de coalescing (I3 §4.4):
1209
+ * - update + update → update com merge dos campos (segundo vence nos conflitos)
1210
+ * - add + update → add com campos mesclados
1211
+ * - add + remove → nada (remove a mutação existente, retorna null para remove)
1212
+ * - set + update → set com campos mesclados
1213
+ * - any + remove (base servidor) → remove
1214
+ *
1215
+ * Retorna:
1216
+ * - `{ coalesced: Mutation }` — substitui a mutação existente (update in-place)
1217
+ * - `{ removed: true }` — a mutação existente deve ser deletada (add+remove)
1218
+ * - `null` — não é possível coalescir
1219
+ */
1220
+ tryCoalesce(existing, newOp, newPayload, newBatchId) {
1221
+ if (existing.batchId !== newBatchId) return null;
1222
+ if (existing.status === "inflight") return null;
1223
+ const existingOp = existing.op;
1224
+ if (existingOp === "add" && newOp === "remove") {
1225
+ return { removed: true };
1226
+ }
1227
+ if (existingOp === "update" && newOp === "update") {
1228
+ return {
1229
+ coalesced: {
1230
+ ...existing,
1231
+ payload: { ...existing.payload ?? {}, ...newPayload ?? {} }
1232
+ }
1233
+ };
1234
+ }
1235
+ if (existingOp === "add" && newOp === "update") {
1236
+ return {
1237
+ coalesced: {
1238
+ ...existing,
1239
+ op: "add",
1240
+ payload: { ...existing.payload ?? {}, ...newPayload ?? {} }
1241
+ }
1242
+ };
1243
+ }
1244
+ if (existingOp === "set" && newOp === "update") {
1245
+ return {
1246
+ coalesced: {
1247
+ ...existing,
1248
+ op: "set",
1249
+ payload: { ...existing.payload ?? {}, ...newPayload ?? {} }
1250
+ }
1251
+ };
1252
+ }
1253
+ if (newOp === "remove") {
1254
+ return {
1255
+ coalesced: {
1256
+ ...existing,
1257
+ op: "remove",
1258
+ payload: null
1259
+ }
1260
+ };
1261
+ }
1262
+ return null;
1263
+ }
1264
+ // ─── Enqueue ─────────────────────────────────────────────────────────────────
1265
+ /**
1266
+ * Enfileira uma nova mutação.
1267
+ *
1268
+ * Processo (I3 §4.1):
1269
+ * 1. Gera docId se op=add e não fornecido.
1270
+ * 2. Sincroniza seq (lazy).
1271
+ * 3. Tenta coalescir com a última mutação queued do mesmo [collection, docId].
1272
+ * 4. Se coalescing:
1273
+ * - `removed` → deleta mutação existente; retorna sem enfileirar nova.
1274
+ * - `coalesced` → substitui a mutação existente (mesmo seq, mesmo mutationId).
1275
+ * 5. Se não coalesce → enfileira nova mutação (novo seq, novo mutationId).
1276
+ *
1277
+ * Atômico: a persistência final é uma única operação putMutation.
1278
+ */
1279
+ async enqueue(params) {
1280
+ const { collection, op, payload, baseVersion, batchId } = params;
1281
+ const docId = params.docId ?? (op === "add" ? generateUUIDv4() : "");
1282
+ await this.syncSeq();
1283
+ const existingMutations = await this.store.listMutations({ collection, docId });
1284
+ const lastQueued = existingMutations.filter((m) => m.status === "queued").sort((a, b) => b.seq - a.seq)[0];
1285
+ if (lastQueued !== void 0) {
1286
+ const coalesceResult = this.tryCoalesce(lastQueued, op, payload, batchId);
1287
+ if (coalesceResult !== null) {
1288
+ if ("removed" in coalesceResult) {
1289
+ await this.store.deleteMutation(lastQueued.mutationId);
1290
+ const phantomMut = {
1291
+ seq: lastQueued.seq,
1292
+ mutationId: generateUUIDv4(),
1293
+ collection,
1294
+ docId,
1295
+ op: "remove",
1296
+ payload: null,
1297
+ baseVersion,
1298
+ enqueuedAt: Date.now(),
1299
+ attempts: 0,
1300
+ lastError: null,
1301
+ status: "queued",
1302
+ batchId
1303
+ };
1304
+ return phantomMut;
1305
+ }
1306
+ const { coalesced } = coalesceResult;
1307
+ await this.store.putMutation(coalesced);
1308
+ return coalesced;
1309
+ }
1310
+ }
1311
+ const seq = this.nextSeq();
1312
+ const mutation = {
1313
+ seq,
1314
+ mutationId: generateUUIDv4(),
1315
+ collection,
1316
+ docId,
1317
+ op,
1318
+ payload,
1319
+ baseVersion,
1320
+ enqueuedAt: Date.now(),
1321
+ attempts: 0,
1322
+ lastError: null,
1323
+ status: "queued",
1324
+ batchId
1325
+ };
1326
+ await this.store.putMutation(mutation);
1327
+ return mutation;
1328
+ }
1329
+ // ─── Leitura da fila ─────────────────────────────────────────────────────────
1330
+ /**
1331
+ * Retorna a primeira mutação com status `queued` (menor seq), ou `null`.
1332
+ */
1333
+ async peek() {
1334
+ const pending = await this.listPending();
1335
+ return pending[0] ?? null;
1336
+ }
1337
+ /**
1338
+ * Retorna todas as mutações com status `queued`, ordenadas por seq crescente.
1339
+ */
1340
+ async listPending() {
1341
+ return this.store.listMutations({ status: "queued" });
1342
+ }
1343
+ /**
1344
+ * Retorna TODAS as mutações (qualquer status), ordenadas por seq crescente.
1345
+ * Útil para inspeção e testes.
1346
+ */
1347
+ async listAll() {
1348
+ return this.store.listMutations();
1349
+ }
1350
+ /**
1351
+ * Conta o número de mutações com status `queued`.
1352
+ */
1353
+ async countPending() {
1354
+ const pending = await this.listPending();
1355
+ return pending.length;
1356
+ }
1357
+ /**
1358
+ * Retorna um lote de mutações `queued` para drenagem (I3 §6.2 FASE 1).
1359
+ * Ordena por seq crescente. O SyncEngine chama drain(), itera, e marca
1360
+ * cada mutação como applied/failed.
1361
+ */
1362
+ async drain(options) {
1363
+ const pending = await this.listPending();
1364
+ if (options?.maxBatch !== void 0 && options.maxBatch > 0) {
1365
+ return pending.slice(0, options.maxBatch);
1366
+ }
1367
+ return pending;
1368
+ }
1369
+ // ─── Ciclo de vida de mutações ────────────────────────────────────────────────
1370
+ /**
1371
+ * Marca uma mutação como `inflight` (está sendo enviada ao Core).
1372
+ * Chamado pelo SyncEngine antes de enviar o request.
1373
+ */
1374
+ async markInflight(mutationId) {
1375
+ const mut = await this.store.getMutation(mutationId);
1376
+ if (!mut) return;
1377
+ await this.store.putMutation({ ...mut, status: "inflight" });
1378
+ }
1379
+ /**
1380
+ * Remove a mutação da fila (sucesso de replay).
1381
+ * Chamado pelo SyncEngine ao receber confirmação do Core.
1382
+ */
1383
+ async markApplied(mutationId) {
1384
+ await this.store.deleteMutation(mutationId);
1385
+ }
1386
+ /**
1387
+ * Marca uma mutação como `failed` e registra o erro.
1388
+ * Incrementa `attempts`. Chamado pelo SyncEngine em falha permanente.
1389
+ */
1390
+ async markFailed(mutationId, error) {
1391
+ const mut = await this.store.getMutation(mutationId);
1392
+ if (!mut) return;
1393
+ await this.store.putMutation({
1394
+ ...mut,
1395
+ status: "failed",
1396
+ lastError: error,
1397
+ attempts: mut.attempts + 1
1398
+ });
1399
+ }
1400
+ /**
1401
+ * Incrementa `attempts` e volta para `queued` (falha transiente com backoff).
1402
+ * Chamado pelo SyncEngine em falha transiente (5xx, timeout).
1403
+ */
1404
+ async markRetry(mutationId, error) {
1405
+ const mut = await this.store.getMutation(mutationId);
1406
+ if (!mut) return;
1407
+ await this.store.putMutation({
1408
+ ...mut,
1409
+ status: "queued",
1410
+ lastError: error,
1411
+ attempts: mut.attempts + 1
1412
+ });
1413
+ }
1414
+ };
1415
+
1416
+ // src/db/offline/sync-engine.ts
1417
+ var SyncEngine = class {
1418
+ _store;
1419
+ _queue;
1420
+ _resolver;
1421
+ _bus;
1422
+ _transport;
1423
+ _tabCoordinator;
1424
+ _connectivity;
1425
+ /** `true` se um sync está atualmente em progresso — guarda re-entrância. */
1426
+ _syncing = false;
1427
+ /** `true` se destroy() foi chamado. */
1428
+ _destroyed = false;
1429
+ /**
1430
+ * Conjunto de coleções "conhecidas" pelo engine.
1431
+ * Populado ao aplicar docs do servidor (Fase 1 e 2) e ao ler do cache.
1432
+ * Persiste em sync_meta['activeCollections'] para sobreviver a reloads.
1433
+ */
1434
+ _activeCollections = /* @__PURE__ */ new Set();
1435
+ /** Estado de sync atual (fonte de verdade em RAM). */
1436
+ _state;
1437
+ /** Listeners de mudança de SyncState. */
1438
+ _stateListeners = /* @__PURE__ */ new Set();
1439
+ /** Cleanup functions dos listeners externos. */
1440
+ _cleanups = [];
1441
+ /** Timer de resync periódico. */
1442
+ _periodicTimer = null;
1443
+ constructor(opts) {
1444
+ this._store = opts.store;
1445
+ this._queue = opts.queue;
1446
+ this._resolver = opts.resolver;
1447
+ this._bus = opts.bus;
1448
+ this._transport = opts.transport;
1449
+ this._tabCoordinator = opts.tabCoordinator;
1450
+ this._connectivity = opts.connectivity;
1451
+ this._state = this._buildInitialState();
1452
+ this._wireListeners();
1453
+ const intervalMs = opts.periodicSyncIntervalMs ?? 5 * 60 * 1e3;
1454
+ if (intervalMs > 0) {
1455
+ this._periodicTimer = setInterval(() => {
1456
+ this._triggerSync("periodic");
1457
+ }, intervalMs);
1458
+ }
1459
+ }
1460
+ // ─── API pública ─────────────────────────────────────────────────────────────
1461
+ /**
1462
+ * Expõe o transporte de sync para acesso direto por `DbCollectionRefImpl`.
1463
+ * Necessário para que `onSnapshot` possa chamar `subscribeCollection` no
1464
+ * transport nosql-vm (HIGH-1 fix — realtime deltas).
1465
+ */
1466
+ get transport() {
1467
+ return this._transport;
1468
+ }
1469
+ /**
1470
+ * Retorna o estado de sync atual (snapshot síncrono).
1471
+ * Equivale a `client.db.syncState` na API pública do SDK (I3 §10.3).
1472
+ *
1473
+ * `pendingWrites` reflete o valor mais recente calculado de forma assíncrona.
1474
+ * Para garantir o valor mais atualizado, aguarde `refreshPendingWrites()` antes.
1475
+ */
1476
+ getSyncState() {
1477
+ return { ...this._state };
1478
+ }
1479
+ /**
1480
+ * Força a atualização de `pendingWrites` e retorna o estado atualizado.
1481
+ * Útil quando o chamador precisa do pendingWrites fresco sem aguardar um sync.
1482
+ */
1483
+ async refreshPendingWrites() {
1484
+ await this._refreshPendingWrites();
1485
+ return { ...this._state };
1486
+ }
1487
+ /**
1488
+ * Registra um listener de mudanças no SyncState.
1489
+ * Retorna uma função de unsubscribe.
1490
+ */
1491
+ onSyncStateChange(cb) {
1492
+ this._stateListeners.add(cb);
1493
+ return () => {
1494
+ this._stateListeners.delete(cb);
1495
+ };
1496
+ }
1497
+ /**
1498
+ * Força um sync imediato (I3 §10.3 `flush()`).
1499
+ * Resolve quando a fila esvazia OU rejeita se o engine estiver destruído.
1500
+ */
1501
+ async flush() {
1502
+ if (this._destroyed) return;
1503
+ await this.sync();
1504
+ }
1505
+ /**
1506
+ * Executa as 3 fases de sincronização.
1507
+ *
1508
+ * Guarda re-entrância: se já está em progresso, retorna imediatamente.
1509
+ * NÃO executa se esta aba não é líder ou se está offline.
1510
+ */
1511
+ async sync() {
1512
+ if (this._destroyed) return;
1513
+ if (!this._tabCoordinator.isLeader()) return;
1514
+ if (!this._connectivity.isOnline) return;
1515
+ if (this._syncing) return;
1516
+ this._syncing = true;
1517
+ this._updateState({ status: "syncing" });
1518
+ try {
1519
+ const phase1Ok = await this._phase1Push();
1520
+ if (!phase1Ok) {
1521
+ this._updateState({ status: "idle" });
1522
+ this._syncing = false;
1523
+ return;
1524
+ }
1525
+ await this._phase2Pull();
1526
+ this._phase3Realtime();
1527
+ this._updateState({ status: "idle", lastSyncedAt: Date.now() });
1528
+ } catch (err) {
1529
+ this._updateState({ status: "idle" });
1530
+ } finally {
1531
+ this._syncing = false;
1532
+ }
1533
+ }
1534
+ /**
1535
+ * Teardown: para timers, remove listeners, marca como destroyed.
1536
+ */
1537
+ destroy() {
1538
+ if (this._destroyed) return;
1539
+ this._destroyed = true;
1540
+ if (this._periodicTimer !== null) {
1541
+ clearInterval(this._periodicTimer);
1542
+ this._periodicTimer = null;
1543
+ }
1544
+ for (const cleanup of this._cleanups) {
1545
+ try {
1546
+ cleanup();
1547
+ } catch {
1548
+ }
1549
+ }
1550
+ this._cleanups.length = 0;
1551
+ this._stateListeners.clear();
1552
+ }
1553
+ // ─── FASE 1 — push (drenar a fila) ───────────────────────────────────────────
1554
+ /**
1555
+ * Drena a MutationQueue, enviando mutações em ordem de seq.
1556
+ *
1557
+ * Retorna `true` se a fase completou sem falhas transientes.
1558
+ * Retorna `false` se houve falha transiente (ciclo deve ser abortado).
1559
+ */
1560
+ async _phase1Push() {
1561
+ const mutations = await this._queue.drain();
1562
+ if (mutations.length === 0) return true;
1563
+ for (const mut of mutations) {
1564
+ await this._queue.markInflight(mut.mutationId);
1565
+ }
1566
+ let result;
1567
+ try {
1568
+ result = await this._transport.pushMutations(mutations);
1569
+ } catch (err) {
1570
+ for (const mut of mutations) {
1571
+ const errMsg = err instanceof Error ? err.message : String(err);
1572
+ await this._queue.markRetry(mut.mutationId, errMsg);
1573
+ }
1574
+ return false;
1575
+ }
1576
+ const busChanges = [];
1577
+ for (const res of result.results) {
1578
+ const mut = mutations.find((m) => m.mutationId === res.mutationId);
1579
+ if (!mut) continue;
1580
+ if (res.outcome === "confirmed") {
1581
+ await this._queue.markApplied(mut.mutationId);
1582
+ await this._applySyncedDoc(
1583
+ mut.collection,
1584
+ mut.docId,
1585
+ res.serverVersion,
1586
+ res.serverTimestamp,
1587
+ mut,
1588
+ busChanges
1589
+ );
1590
+ } else if (res.outcome === "superseded") {
1591
+ await this._queue.markApplied(mut.mutationId);
1592
+ await this._applySuperseded(mut, res, busChanges);
1593
+ } else if (res.outcome === "rejected") {
1594
+ await this._queue.markApplied(mut.mutationId);
1595
+ await this._applyRejected(mut, res, busChanges);
1596
+ }
1597
+ }
1598
+ if (busChanges.length > 0) {
1599
+ this._bus.emit(busChanges);
1600
+ }
1601
+ return true;
1602
+ }
1603
+ /** Atualiza o cache após confirmação de escrita (outcome=confirmed). */
1604
+ async _applySyncedDoc(collection, docId, serverVersion, serverTimestamp, mut, busChanges) {
1605
+ const existing = await this._store.getDoc(collection, docId);
1606
+ if (mut.op === "remove") {
1607
+ if (existing) {
1608
+ await this._store.putDoc({
1609
+ ...existing,
1610
+ meta: {
1611
+ ...existing.meta,
1612
+ serverVersion,
1613
+ updatedAtServer: serverTimestamp,
1614
+ updatedAtLocal: Date.now(),
1615
+ state: "synced",
1616
+ deleted: true,
1617
+ pendingMutationIds: []
1618
+ }
1619
+ });
1620
+ busChanges.push({ type: "removed", collection, doc: { id: docId, data: existing.data } });
1621
+ }
1622
+ return;
1623
+ }
1624
+ const newData = mut.payload ?? (existing?.data ?? {});
1625
+ const updatedDoc = {
1626
+ collection,
1627
+ id: docId,
1628
+ data: mut.op === "update" ? { ...existing?.data ?? {}, ...newData } : newData,
1629
+ meta: {
1630
+ serverVersion,
1631
+ updatedAtServer: serverTimestamp,
1632
+ updatedAtLocal: Date.now(),
1633
+ state: "synced",
1634
+ pendingMutationIds: [],
1635
+ deleted: false,
1636
+ ownerId: existing?.meta.ownerId ?? null
1637
+ }
1638
+ };
1639
+ await this._store.putDoc(updatedDoc);
1640
+ busChanges.push({
1641
+ type: existing ? "modified" : "added",
1642
+ collection,
1643
+ doc: { id: docId, data: updatedDoc.data }
1644
+ });
1645
+ }
1646
+ /** Processa resultado 'superseded' (LWW: servidor venceu). */
1647
+ async _applySuperseded(mut, res, busChanges) {
1648
+ const localDoc = await this._store.getDoc(mut.collection, mut.docId);
1649
+ const serverDocEnvelope = {
1650
+ collection: mut.collection,
1651
+ id: mut.docId,
1652
+ data: res.serverData,
1653
+ meta: {
1654
+ serverVersion: res.serverVersion,
1655
+ updatedAtServer: res.serverTimestamp,
1656
+ updatedAtLocal: Date.now(),
1657
+ state: "synced",
1658
+ pendingMutationIds: [],
1659
+ deleted: false,
1660
+ ownerId: localDoc?.meta.ownerId ?? null
1661
+ }
1662
+ };
1663
+ const localDocForResolver = localDoc ?? {
1664
+ collection: mut.collection,
1665
+ id: mut.docId,
1666
+ data: mut.payload ?? {},
1667
+ meta: {
1668
+ serverVersion: mut.baseVersion,
1669
+ updatedAtServer: res.serverTimestamp - 1,
1670
+ // garante server é mais novo
1671
+ updatedAtLocal: mut.enqueuedAt,
1672
+ state: "pending",
1673
+ pendingMutationIds: [mut.mutationId],
1674
+ deleted: false,
1675
+ ownerId: null
1676
+ }
1677
+ };
1678
+ const resolveResult = this._resolver.resolve(
1679
+ localDocForResolver,
1680
+ serverDocEnvelope,
1681
+ mut
1682
+ );
1683
+ const conflictRecord = resolveResult.conflictRecord ?? {
1684
+ collection: mut.collection,
1685
+ docId: mut.docId,
1686
+ mutationId: mut.mutationId,
1687
+ losingData: mut.payload ?? {},
1688
+ winningData: res.serverData,
1689
+ reason: "lww_server_newer",
1690
+ detectedAt: Date.now(),
1691
+ delivered: false
1692
+ };
1693
+ await this._store.appendConflict(conflictRecord);
1694
+ const updatedDoc = {
1695
+ collection: mut.collection,
1696
+ id: mut.docId,
1697
+ data: res.serverData,
1698
+ meta: {
1699
+ serverVersion: res.serverVersion,
1700
+ updatedAtServer: res.serverTimestamp,
1701
+ updatedAtLocal: Date.now(),
1702
+ state: "synced",
1703
+ pendingMutationIds: [],
1704
+ deleted: false,
1705
+ ownerId: localDoc?.meta.ownerId ?? null
1706
+ }
1707
+ };
1708
+ await this._store.putDoc(updatedDoc);
1709
+ busChanges.push({
1710
+ type: localDoc ? "modified" : "added",
1711
+ collection: mut.collection,
1712
+ doc: { id: mut.docId, data: res.serverData }
1713
+ });
1714
+ }
1715
+ /** Processa resultado 'rejected' (permissão/validação negada). */
1716
+ async _applyRejected(mut, res, busChanges) {
1717
+ const storedDoc = await this._store.getDoc(mut.collection, mut.docId);
1718
+ const localDoc = storedDoc ?? {
1719
+ collection: mut.collection,
1720
+ id: mut.docId,
1721
+ data: mut.payload ?? {},
1722
+ meta: {
1723
+ serverVersion: mut.baseVersion,
1724
+ updatedAtServer: null,
1725
+ updatedAtLocal: mut.enqueuedAt,
1726
+ state: "pending",
1727
+ pendingMutationIds: [mut.mutationId],
1728
+ deleted: false,
1729
+ ownerId: null
1730
+ }
1731
+ };
1732
+ const serverDocEnvelope = res.serverData ? {
1733
+ ...localDoc,
1734
+ data: res.serverData,
1735
+ meta: {
1736
+ ...localDoc.meta,
1737
+ serverVersion: res.serverVersion ?? localDoc.meta.serverVersion
1738
+ }
1739
+ } : null;
1740
+ const resolveResult = this._resolver.resolveRejected(
1741
+ localDoc,
1742
+ serverDocEnvelope,
1743
+ mut,
1744
+ res.reason
1745
+ );
1746
+ const conflictRecord = resolveResult.conflictRecord ?? {
1747
+ collection: mut.collection,
1748
+ docId: mut.docId,
1749
+ mutationId: mut.mutationId,
1750
+ losingData: mut.payload ?? {},
1751
+ winningData: res.serverData ?? {},
1752
+ reason: res.reason,
1753
+ detectedAt: Date.now(),
1754
+ delivered: false
1755
+ };
1756
+ await this._store.appendConflict(conflictRecord);
1757
+ if (res.serverData) {
1758
+ await this._store.putDoc({
1759
+ ...localDoc,
1760
+ data: res.serverData,
1761
+ meta: {
1762
+ ...localDoc.meta,
1763
+ state: "synced",
1764
+ pendingMutationIds: []
1765
+ }
1766
+ });
1767
+ busChanges.push({
1768
+ type: "modified",
1769
+ collection: mut.collection,
1770
+ doc: { id: mut.docId, data: res.serverData }
1771
+ });
1772
+ } else {
1773
+ await this._store.putDoc({
1774
+ ...localDoc,
1775
+ meta: {
1776
+ ...localDoc.meta,
1777
+ state: "synced",
1778
+ pendingMutationIds: []
1779
+ }
1780
+ });
1781
+ }
1782
+ }
1783
+ // ─── FASE 2 — pull (reconciliar o cache) ─────────────────────────────────────
1784
+ /**
1785
+ * Busca mudanças do servidor e aplica ao cache via ConflictResolver.
1786
+ *
1787
+ * Se `resyncRequired === true`, faz full resync em vez de pull incremental.
1788
+ */
1789
+ async _phase2Pull() {
1790
+ const watermark = await this._store.getMeta("lastSyncWatermark");
1791
+ const resumeToken = await this._store.getMeta("lastResumeToken");
1792
+ let pullResult;
1793
+ try {
1794
+ pullResult = await this._transport.pullChanges(watermark, resumeToken);
1795
+ } catch {
1796
+ return;
1797
+ }
1798
+ if (pullResult.resyncRequired) {
1799
+ await this._phase2FullResync();
1800
+ return;
1801
+ }
1802
+ const busChanges = [];
1803
+ await this._applyServerDocs(pullResult.docs, busChanges, false);
1804
+ if (pullResult.newWatermark !== null) {
1805
+ await this._store.setMeta("lastSyncWatermark", pullResult.newWatermark);
1806
+ }
1807
+ if (busChanges.length > 0) {
1808
+ this._bus.emit(busChanges);
1809
+ }
1810
+ }
1811
+ /** Full resync: lista completa + detecta deleções por ausência. */
1812
+ async _phase2FullResync() {
1813
+ const collections = await this._getActiveCollections();
1814
+ let resyncResult;
1815
+ try {
1816
+ resyncResult = await this._transport.fullResync(collections);
1817
+ } catch {
1818
+ return;
1819
+ }
1820
+ const busChanges = [];
1821
+ await this._applyServerDocs(resyncResult.docs, busChanges, true);
1822
+ const returnedKeys = new Set(
1823
+ resyncResult.docs.map((d) => `${d.collection}::${d.id}`)
1824
+ );
1825
+ for (const col of collections) {
1826
+ const queryResult = await this._store.listDocs(col, {});
1827
+ for (const { id } of queryResult.docs) {
1828
+ const key = `${col}::${id}`;
1829
+ if (!returnedKeys.has(key)) {
1830
+ const fullDoc = await this._store.getDoc(col, id);
1831
+ if (fullDoc && !fullDoc.meta.deleted) {
1832
+ await this._store.putDoc({
1833
+ ...fullDoc,
1834
+ meta: {
1835
+ ...fullDoc.meta,
1836
+ deleted: true,
1837
+ updatedAtLocal: Date.now(),
1838
+ state: "synced"
1839
+ }
1840
+ });
1841
+ busChanges.push({
1842
+ type: "removed",
1843
+ collection: col,
1844
+ doc: { id, data: fullDoc.data }
1845
+ });
1846
+ }
1847
+ }
1848
+ }
1849
+ }
1850
+ if (resyncResult.newWatermark !== null) {
1851
+ await this._store.setMeta("lastSyncWatermark", resyncResult.newWatermark);
1852
+ }
1853
+ await this._store.setMeta("lastFullResyncAt", Date.now());
1854
+ if (busChanges.length > 0) {
1855
+ this._bus.emit(busChanges);
1856
+ }
1857
+ }
1858
+ /**
1859
+ * Aplica uma lista de ServerDoc ao cache local via ConflictResolver.
1860
+ *
1861
+ * `isFullResync = true` indica que o conjunto é completo — usamos isso para
1862
+ * otimizar a path (sempre sobrescreve docs synced; pending passam pelo LWW).
1863
+ */
1864
+ async _applyServerDocs(docs, busChanges, _isFullResync) {
1865
+ for (const serverDoc of docs) {
1866
+ const localDoc = await this._store.getDoc(serverDoc.collection, serverDoc.id);
1867
+ if (serverDoc.deleted) {
1868
+ if (localDoc && !localDoc.meta.deleted) {
1869
+ await this._store.putDoc({
1870
+ ...localDoc,
1871
+ meta: {
1872
+ ...localDoc.meta,
1873
+ deleted: true,
1874
+ serverVersion: serverDoc.serverVersion,
1875
+ updatedAtServer: serverDoc.serverTimestamp,
1876
+ updatedAtLocal: Date.now(),
1877
+ state: "synced"
1878
+ }
1879
+ });
1880
+ busChanges.push({
1881
+ type: "removed",
1882
+ collection: serverDoc.collection,
1883
+ doc: { id: serverDoc.id, data: localDoc.data }
1884
+ });
1885
+ }
1886
+ continue;
1887
+ }
1888
+ if (localDoc && localDoc.meta.state === "pending") {
1889
+ const serverEnvelope = {
1890
+ collection: serverDoc.collection,
1891
+ id: serverDoc.id,
1892
+ data: serverDoc.data,
1893
+ meta: {
1894
+ serverVersion: serverDoc.serverVersion,
1895
+ updatedAtServer: serverDoc.serverTimestamp,
1896
+ updatedAtLocal: Date.now(),
1897
+ state: "synced",
1898
+ pendingMutationIds: [],
1899
+ deleted: false,
1900
+ ownerId: localDoc.meta.ownerId
1901
+ }
1902
+ };
1903
+ const pendingMuts = await this._queue.drain();
1904
+ const docMut = pendingMuts.find(
1905
+ (m) => m.collection === serverDoc.collection && m.docId === serverDoc.id
1906
+ );
1907
+ if (docMut) {
1908
+ const result = this._resolver.resolve(localDoc, serverEnvelope, docMut);
1909
+ if (result.conflictRecord) {
1910
+ await this._store.appendConflict(result.conflictRecord);
1911
+ }
1912
+ await this._store.putDoc({
1913
+ ...localDoc,
1914
+ meta: { ...localDoc.meta, state: "conflict" }
1915
+ });
1916
+ continue;
1917
+ }
1918
+ }
1919
+ const isNew = !localDoc;
1920
+ const newDoc = {
1921
+ collection: serverDoc.collection,
1922
+ id: serverDoc.id,
1923
+ data: serverDoc.data,
1924
+ meta: {
1925
+ serverVersion: serverDoc.serverVersion,
1926
+ updatedAtServer: serverDoc.serverTimestamp,
1927
+ updatedAtLocal: Date.now(),
1928
+ state: "synced",
1929
+ pendingMutationIds: [],
1930
+ deleted: false,
1931
+ ownerId: localDoc?.meta.ownerId ?? null
1932
+ }
1933
+ };
1934
+ await this._store.putDoc(newDoc);
1935
+ busChanges.push({
1936
+ type: isNew ? "added" : "modified",
1937
+ collection: serverDoc.collection,
1938
+ doc: { id: serverDoc.id, data: serverDoc.data }
1939
+ });
1940
+ }
1941
+ }
1942
+ // ─── FASE 3 — reabre listeners (realtime) ─────────────────────────────────────
1943
+ /**
1944
+ * Fase 3: sinaliza que o cache está reconciliado.
1945
+ *
1946
+ * O transporte de tempo real (Firestore onSnapshot / WebSocket) é gerido
1947
+ * pela camada superior — aqui apenas garantimos que o SyncState reflita
1948
+ * o término do sync, o que notifica os listeners `onSyncStateChange` e
1949
+ * transitivamente os `onSnapshot` da UI.
1950
+ */
1951
+ _phase3Realtime() {
1952
+ }
1953
+ // ─── Helpers ──────────────────────────────────────────────────────────────────
1954
+ /**
1955
+ * Retorna a lista de coleções com documentos no cache local.
1956
+ * Usado pelo full resync para saber quais coleções checar.
1957
+ *
1958
+ * Combina:
1959
+ * 1. Set em memória `_activeCollections` (populado ao aplicar docs)
1960
+ * 2. Coleções de mutações pendentes
1961
+ * 3. Coleções de conflict_log
1962
+ * 4. Coleções persistas em sync_meta['activeCollections']
1963
+ */
1964
+ async _getActiveCollections() {
1965
+ const collectionSet = new Set(this._activeCollections);
1966
+ const mutations = await this._queue.listAll();
1967
+ for (const m of mutations) collectionSet.add(m.collection);
1968
+ const conflicts = await this._store.listConflicts();
1969
+ for (const c of conflicts) collectionSet.add(c.collection);
1970
+ const persistedRaw = await this._store.getMeta("activeCollections");
1971
+ if (persistedRaw) {
1972
+ for (const col of persistedRaw) collectionSet.add(col);
1973
+ }
1974
+ const storedCollections = await this._store.listCollections();
1975
+ for (const col of storedCollections) collectionSet.add(col);
1976
+ return Array.from(collectionSet);
1977
+ }
1978
+ /** Constrói o estado inicial com base no estado atual dos colaboradores. */
1979
+ _buildInitialState() {
1980
+ const isOnline = this._connectivity.isOnline;
1981
+ return {
1982
+ status: isOnline ? "idle" : "offline",
1983
+ pendingWrites: 0,
1984
+ lastSyncedAt: null,
1985
+ isLeaderTab: this._tabCoordinator.isLeader()
1986
+ };
1987
+ }
1988
+ /**
1989
+ * Atualiza o SyncState em RAM e notifica os listeners.
1990
+ * Só emite se algo realmente mudou.
1991
+ */
1992
+ _updateState(partial) {
1993
+ const prev = this._state;
1994
+ const next = { ...prev, ...partial };
1995
+ const changed = prev.status !== next.status || prev.pendingWrites !== next.pendingWrites || prev.lastSyncedAt !== next.lastSyncedAt || prev.isLeaderTab !== next.isLeaderTab;
1996
+ this._state = next;
1997
+ if (changed) {
1998
+ this._emitState(next);
1999
+ }
2000
+ }
2001
+ _emitState(state) {
2002
+ for (const listener of this._stateListeners) {
2003
+ try {
2004
+ listener({ ...state });
2005
+ } catch {
2006
+ }
2007
+ }
2008
+ }
2009
+ /**
2010
+ * Atualiza `pendingWrites` no estado.
2011
+ * Chamado de forma assíncrona quando necessário.
2012
+ */
2013
+ async _refreshPendingWrites() {
2014
+ if (this._destroyed) return;
2015
+ try {
2016
+ const count = await this._queue.countPending();
2017
+ if (count !== this._state.pendingWrites) {
2018
+ this._updateState({ pendingWrites: count });
2019
+ }
2020
+ } catch {
2021
+ }
2022
+ }
2023
+ /** Dispara um sync de forma fire-and-forget (para gatilhos externos). */
2024
+ _triggerSync(_reason) {
2025
+ if (this._destroyed) return;
2026
+ this._refreshPendingWrites().catch(() => {
2027
+ });
2028
+ this.sync().catch(() => {
2029
+ });
2030
+ }
2031
+ /** Carrega activeCollections do sync_meta e popula o Set em memória. */
2032
+ _loadActiveCollections() {
2033
+ this._store.getMeta("activeCollections").then((raw) => {
2034
+ const cols = raw;
2035
+ if (cols) {
2036
+ for (const c of cols) this._activeCollections.add(c);
2037
+ }
2038
+ }).catch(() => {
2039
+ });
2040
+ }
2041
+ /** Conecta os listeners de ConnectivityMonitor e TabCoordinator. */
2042
+ _wireListeners() {
2043
+ this._loadActiveCollections();
2044
+ const unsubConn = this._connectivity.subscribe((state) => {
2045
+ if (state === "offline") {
2046
+ this._updateState({ status: "offline" });
2047
+ } else {
2048
+ if (this._state.status === "offline") {
2049
+ this._updateState({ status: "idle" });
2050
+ }
2051
+ this._triggerSync("connectivity:online");
2052
+ }
2053
+ });
2054
+ this._cleanups.push(unsubConn);
2055
+ const unsubRole = this._tabCoordinator.onRoleChange((role) => {
2056
+ const isLeader = role === "leader";
2057
+ this._updateState({ isLeaderTab: isLeader });
2058
+ if (isLeader) {
2059
+ this._triggerSync("role:leader");
2060
+ }
2061
+ });
2062
+ this._cleanups.push(unsubRole);
2063
+ }
2064
+ };
2065
+
2066
+ // src/db/offline/conflict-resolver.ts
2067
+ function isServerNewer(localUpdatedAtServer, remoteUpdatedAtServer) {
2068
+ if (remoteUpdatedAtServer === null) return false;
2069
+ if (localUpdatedAtServer === null) return true;
2070
+ return remoteUpdatedAtServer > localUpdatedAtServer;
2071
+ }
2072
+ var ConflictResolver = class _ConflictResolver {
2073
+ /**
2074
+ * Resolve um conflito com base na operação da mutação (auto-dispatch).
2075
+ *
2076
+ * - `add` / `set` → `resolveDocLevel`
2077
+ * - `update` → `resolveFieldRestricted`
2078
+ * - `remove` → a remoção sempre vence (LWW: operação mais recente é a destruição)
2079
+ */
2080
+ resolve(localDoc, serverDoc, pendingMutation) {
2081
+ switch (pendingMutation.op) {
2082
+ case "remove":
2083
+ return this.resolveRemove(localDoc, serverDoc, pendingMutation);
2084
+ case "update":
2085
+ return this.resolveFieldRestricted(localDoc, serverDoc, pendingMutation);
2086
+ case "add":
2087
+ case "set":
2088
+ default:
2089
+ return this.resolveDocLevel(localDoc, serverDoc, pendingMutation);
2090
+ }
2091
+ }
2092
+ /**
2093
+ * LWW documento-nível (para `set` e `add`).
2094
+ *
2095
+ * O documento inteiro com o timestamp de servidor mais recente vence.
2096
+ * Se o servidor for mais novo, a escrita local é descartada e um
2097
+ * `ConflictRecord` é emitido.
2098
+ */
2099
+ resolveDocLevel(localDoc, serverDoc, pendingMutation) {
2100
+ if (serverDoc === null) {
2101
+ const data = pendingMutation.payload ?? {};
2102
+ return { outcome: "no_conflict", resolvedData: data, conflictRecord: null };
2103
+ }
2104
+ if (localDoc === null) {
2105
+ return {
2106
+ outcome: "server_wins",
2107
+ resolvedData: serverDoc.data,
2108
+ conflictRecord: null
2109
+ };
2110
+ }
2111
+ const serverNewer = isServerNewer(
2112
+ localDoc.meta.updatedAtServer,
2113
+ serverDoc.meta.updatedAtServer
2114
+ );
2115
+ if (!serverNewer) {
2116
+ return {
2117
+ outcome: "local_wins",
2118
+ resolvedData: localDoc.data,
2119
+ conflictRecord: null
2120
+ };
2121
+ }
2122
+ const conflictRecord = {
2123
+ collection: pendingMutation.collection,
2124
+ docId: pendingMutation.docId,
2125
+ mutationId: pendingMutation.mutationId,
2126
+ losingData: localDoc.data,
2127
+ winningData: serverDoc.data,
2128
+ reason: "lww_server_newer",
2129
+ detectedAt: Date.now(),
2130
+ delivered: false
2131
+ };
2132
+ return {
2133
+ outcome: "server_wins",
2134
+ resolvedData: serverDoc.data,
2135
+ conflictRecord
2136
+ };
2137
+ }
2138
+ /**
2139
+ * LWW campo-restrito (para `update`).
2140
+ *
2141
+ * Apenas os campos declarados no payload da mutação são comparados.
2142
+ * Campos não tocados pela mutação são preservados do estado do servidor
2143
+ * (se disponível) ou do estado local (I3 §7.2).
2144
+ *
2145
+ * Resultado:
2146
+ * - Se o servidor for mais novo nos campos conflitantes → `server_wins`
2147
+ * para esses campos; o doc resultante é uma mescla de server (campos
2148
+ * conflitantes) + estado antes da mutação para os demais.
2149
+ * - Se o local for mais recente → `local_wins`; os campos do update são
2150
+ * aplicados sobre o server.
2151
+ * - Campos do server não tocados pelo update sempre preservados → `merged`.
2152
+ */
2153
+ resolveFieldRestricted(localDoc, serverDoc, pendingMutation) {
2154
+ const mutatedFields = Object.keys(pendingMutation.payload ?? {});
2155
+ if (serverDoc === null) {
2156
+ const base = localDoc?.data ?? {};
2157
+ const resolved = { ...base, ...pendingMutation.payload ?? {} };
2158
+ return { outcome: "no_conflict", resolvedData: resolved, conflictRecord: null };
2159
+ }
2160
+ const serverData = serverDoc.data;
2161
+ if (localDoc === null) {
2162
+ const resolved = { ...serverData, ...pendingMutation.payload ?? {} };
2163
+ return { outcome: "no_conflict", resolvedData: resolved, conflictRecord: null };
2164
+ }
2165
+ const serverNewer = isServerNewer(
2166
+ localDoc.meta.updatedAtServer,
2167
+ serverDoc.meta.updatedAtServer
2168
+ );
2169
+ if (!serverNewer) {
2170
+ const resolved = { ...serverData, ...pendingMutation.payload ?? {} };
2171
+ return { outcome: "local_wins", resolvedData: resolved, conflictRecord: null };
2172
+ }
2173
+ const losingFields = {};
2174
+ for (const field of mutatedFields) {
2175
+ losingFields[field] = localDoc.data[field];
2176
+ }
2177
+ const conflictRecord = {
2178
+ collection: pendingMutation.collection,
2179
+ docId: pendingMutation.docId,
2180
+ mutationId: pendingMutation.mutationId,
2181
+ losingData: losingFields,
2182
+ winningData: serverData,
2183
+ reason: "lww_server_newer",
2184
+ detectedAt: Date.now(),
2185
+ delivered: false
2186
+ };
2187
+ return {
2188
+ outcome: "server_wins",
2189
+ resolvedData: serverData,
2190
+ conflictRecord
2191
+ };
2192
+ }
2193
+ /**
2194
+ * Resolve uma operação `remove`.
2195
+ *
2196
+ * A remoção sempre vence no LWW (I3 §7.4: "a última operação é a destruição").
2197
+ * Se o servidor modificou o doc depois que o cliente enfileirou o remove, a
2198
+ * remoção ainda prevalece — comportamento documentado.
2199
+ */
2200
+ resolveRemove(_localDoc, serverDoc, _pendingMutation) {
2201
+ const emptyDoc = {};
2202
+ if (serverDoc !== null && serverDoc.meta.updatedAtServer !== null) {
2203
+ const conflictRecord = {
2204
+ collection: _pendingMutation.collection,
2205
+ docId: _pendingMutation.docId,
2206
+ mutationId: _pendingMutation.mutationId,
2207
+ losingData: serverDoc.data,
2208
+ winningData: {},
2209
+ reason: "lww_server_newer",
2210
+ detectedAt: Date.now(),
2211
+ delivered: false
2212
+ };
2213
+ return { outcome: "local_wins", resolvedData: emptyDoc, conflictRecord };
2214
+ }
2215
+ return { outcome: "local_wins", resolvedData: emptyDoc, conflictRecord: null };
2216
+ }
2217
+ /**
2218
+ * Resolve conflito com razão de rejeição explícita (servidor retornou
2219
+ * `rejected_permission` ou `rejected_validation`).
2220
+ *
2221
+ * Usado pelo SyncEngine quando o Core rejeita o replay por motivo não-LWW.
2222
+ */
2223
+ resolveRejected(localDoc, serverDoc, pendingMutation, reason) {
2224
+ const winningData = serverDoc?.data ?? {};
2225
+ const conflictRecord = {
2226
+ collection: pendingMutation.collection,
2227
+ docId: pendingMutation.docId,
2228
+ mutationId: pendingMutation.mutationId,
2229
+ losingData: localDoc.data,
2230
+ winningData,
2231
+ reason,
2232
+ detectedAt: Date.now(),
2233
+ delivered: false
2234
+ };
2235
+ return {
2236
+ outcome: "server_wins",
2237
+ resolvedData: serverDoc?.data ?? localDoc.data,
2238
+ conflictRecord
2239
+ };
2240
+ }
2241
+ // ─── Static helpers ─────────────────────────────────────────────────────────
2242
+ static resolve(localDoc, serverDoc, pendingMutation) {
2243
+ return new _ConflictResolver().resolve(localDoc, serverDoc, pendingMutation);
2244
+ }
2245
+ };
2246
+
2247
+ // src/db/offline/change-bus.ts
2248
+ function dedupeKey(c) {
2249
+ return `${c.collection}::${c.doc.id}`;
2250
+ }
2251
+ var ChangeBus = class {
2252
+ /** Listeners filtrados por coleção. */
2253
+ _collectionListeners = /* @__PURE__ */ new Map();
2254
+ /** Listeners globais (todas as coleções). */
2255
+ _globalListeners = /* @__PURE__ */ new Set();
2256
+ /**
2257
+ * Subscreve a eventos de uma coleção específica.
2258
+ *
2259
+ * @param collection - Nome da coleção a filtrar.
2260
+ * @param listener - Callback que recebe os changes da coleção.
2261
+ * @returns Função de unsubscribe.
2262
+ */
2263
+ subscribe(collection, listener) {
2264
+ if (!this._collectionListeners.has(collection)) {
2265
+ this._collectionListeners.set(collection, /* @__PURE__ */ new Set());
2266
+ }
2267
+ this._collectionListeners.get(collection).add(listener);
2268
+ return () => {
2269
+ const set = this._collectionListeners.get(collection);
2270
+ if (set) {
2271
+ set.delete(listener);
2272
+ if (set.size === 0) {
2273
+ this._collectionListeners.delete(collection);
2274
+ }
2275
+ }
2276
+ };
2277
+ }
2278
+ /**
2279
+ * Subscreve a eventos de TODAS as coleções.
2280
+ *
2281
+ * @param listener - Callback que recebe todos os changes, de qualquer coleção.
2282
+ * @returns Função de unsubscribe.
2283
+ */
2284
+ subscribeAll(listener) {
2285
+ this._globalListeners.add(listener);
2286
+ return () => {
2287
+ this._globalListeners.delete(listener);
2288
+ };
2289
+ }
2290
+ /**
2291
+ * Emite um array de `Change` events para todos os listeners relevantes.
2292
+ *
2293
+ * Agrupa os changes por coleção antes de despachar, para que cada listener
2294
+ * receba apenas os events da sua coleção.
2295
+ *
2296
+ * Deduplicação: events com o mesmo `[collection, id]` dentro do mesmo `emit()`
2297
+ * são compactados: apenas o último do array é mantido (o mais recente vence).
2298
+ * Isso cobre o caso Fase 1 + Fase 2 do SyncEngine emitindo o mesmo doc.
2299
+ *
2300
+ * Erros em listeners individuais são capturados e não interrompem os demais.
2301
+ */
2302
+ emit(changes) {
2303
+ if (changes.length === 0) return;
2304
+ const deduped = /* @__PURE__ */ new Map();
2305
+ for (const c of changes) {
2306
+ deduped.set(dedupeKey(c), c);
2307
+ }
2308
+ const uniqueChanges = Array.from(deduped.values());
2309
+ const byCollection = /* @__PURE__ */ new Map();
2310
+ for (const c of uniqueChanges) {
2311
+ if (!byCollection.has(c.collection)) {
2312
+ byCollection.set(c.collection, []);
2313
+ }
2314
+ byCollection.get(c.collection).push(c);
2315
+ }
2316
+ for (const [collection, collChanges] of byCollection) {
2317
+ const listeners = this._collectionListeners.get(collection);
2318
+ if (listeners) {
2319
+ for (const listener of listeners) {
2320
+ this._safeCall(listener, collChanges);
2321
+ }
2322
+ }
2323
+ }
2324
+ for (const listener of this._globalListeners) {
2325
+ this._safeCall(listener, uniqueChanges);
2326
+ }
2327
+ }
2328
+ /**
2329
+ * Número de listeners ativos (útil em testes).
2330
+ */
2331
+ get listenerCount() {
2332
+ let count = this._globalListeners.size;
2333
+ for (const set of this._collectionListeners.values()) {
2334
+ count += set.size;
2335
+ }
2336
+ return count;
2337
+ }
2338
+ /**
2339
+ * Remove todos os listeners registrados.
2340
+ * Útil para teardown em testes ou no shutdown do SDK.
2341
+ */
2342
+ clear() {
2343
+ this._collectionListeners.clear();
2344
+ this._globalListeners.clear();
2345
+ }
2346
+ // ─── Privado ────────────────────────────────────────────────────────────────
2347
+ _safeCall(listener, changes) {
2348
+ try {
2349
+ listener(changes);
2350
+ } catch {
2351
+ }
2352
+ }
2353
+ };
2354
+
2355
+ // src/db/offline/connectivity-monitor.ts
2356
+ var ConnectivityMonitor = class {
2357
+ _state;
2358
+ _listeners = /* @__PURE__ */ new Set();
2359
+ _nav;
2360
+ _target;
2361
+ _debounceMs;
2362
+ _debounceTimer = null;
2363
+ _started = false;
2364
+ // Handlers bound para remoção correta em removeEventListener
2365
+ _onOnline;
2366
+ _onOffline;
2367
+ constructor(options = {}) {
2368
+ this._nav = options.navigator ?? (typeof navigator !== "undefined" ? navigator : void 0);
2369
+ this._target = options.eventTarget ?? (typeof window !== "undefined" ? window : void 0);
2370
+ this._debounceMs = options.debounceMs ?? 300;
2371
+ this._state = this._nav?.onLine === false ? "offline" : "online";
2372
+ this._onOnline = () => this._handleNativeEvent("online");
2373
+ this._onOffline = () => this._handleNativeEvent("offline");
2374
+ }
2375
+ // ─── Ciclo de vida ──────────────────────────────────────────────────────────
2376
+ /**
2377
+ * Inicia a escuta de eventos. Deve ser chamado após instanciar.
2378
+ * Sem efeito se já foi iniciado.
2379
+ */
2380
+ start() {
2381
+ if (this._started) return;
2382
+ this._started = true;
2383
+ this._target?.addEventListener("online", this._onOnline);
2384
+ this._target?.addEventListener("offline", this._onOffline);
2385
+ }
2386
+ /**
2387
+ * Para a escuta e remove todos os listeners.
2388
+ * Deve ser chamado no shutdown para evitar memory leaks.
2389
+ */
2390
+ destroy() {
2391
+ this._started = false;
2392
+ this._target?.removeEventListener("online", this._onOnline);
2393
+ this._target?.removeEventListener("offline", this._onOffline);
2394
+ if (this._debounceTimer !== null) {
2395
+ clearTimeout(this._debounceTimer);
2396
+ this._debounceTimer = null;
2397
+ }
2398
+ this._listeners.clear();
2399
+ }
2400
+ // ─── Estado atual ───────────────────────────────────────────────────────────
2401
+ /**
2402
+ * Retorna o estado de conectividade atual.
2403
+ */
2404
+ getState() {
2405
+ return this._state;
2406
+ }
2407
+ /**
2408
+ * True se o estado atual é `'online'`.
2409
+ */
2410
+ get isOnline() {
2411
+ return this._state === "online";
2412
+ }
2413
+ /**
2414
+ * True se o estado atual é `'offline'`.
2415
+ */
2416
+ get isOffline() {
2417
+ return this._state === "offline";
2418
+ }
2419
+ // ─── Subscrições ────────────────────────────────────────────────────────────
2420
+ /**
2421
+ * Subscreve a mudanças de estado de conectividade.
2422
+ *
2423
+ * @param listener - Callback chamado ao mudar o estado.
2424
+ * @returns Função de unsubscribe (sem memory leak).
2425
+ */
2426
+ subscribe(listener) {
2427
+ this._listeners.add(listener);
2428
+ return () => {
2429
+ this._listeners.delete(listener);
2430
+ };
2431
+ }
2432
+ /**
2433
+ * Número de listeners ativos (útil em testes).
2434
+ */
2435
+ get listenerCount() {
2436
+ return this._listeners.size;
2437
+ }
2438
+ // ─── Força de estado (para testes e heartbeat externo) ─────────────────────
2439
+ /**
2440
+ * Força o estado para um valor específico, ignorando eventos nativos.
2441
+ * Útil para o SyncEngine injetar o resultado de um heartbeat real ao Core.
2442
+ * Respeita o debounce.
2443
+ */
2444
+ forceState(state) {
2445
+ this._scheduleTransition(state);
2446
+ }
2447
+ // ─── Privado ────────────────────────────────────────────────────────────────
2448
+ _handleNativeEvent(type) {
2449
+ const newState = type === "online" ? "online" : "offline";
2450
+ this._scheduleTransition(newState);
2451
+ }
2452
+ _scheduleTransition(newState) {
2453
+ if (this._debounceTimer !== null) {
2454
+ clearTimeout(this._debounceTimer);
2455
+ this._debounceTimer = null;
2456
+ }
2457
+ if (this._debounceMs <= 0) {
2458
+ this._applyTransition(newState);
2459
+ return;
2460
+ }
2461
+ this._debounceTimer = setTimeout(() => {
2462
+ this._debounceTimer = null;
2463
+ this._applyTransition(newState);
2464
+ }, this._debounceMs);
2465
+ }
2466
+ _applyTransition(newState) {
2467
+ if (newState === this._state) return;
2468
+ this._state = newState;
2469
+ this._notifyListeners(newState);
2470
+ }
2471
+ _notifyListeners(state) {
2472
+ for (const listener of this._listeners) {
2473
+ try {
2474
+ listener(state);
2475
+ } catch {
2476
+ }
2477
+ }
2478
+ }
2479
+ };
2480
+
2481
+ // src/db/offline/tab-coordinator.ts
2482
+ var TabCoordinator = class {
2483
+ _lockName;
2484
+ _channelName;
2485
+ _lockManager;
2486
+ _channel;
2487
+ _channelFactory;
2488
+ /** ID único desta aba (para debug e `sync_state`). */
2489
+ _tabId;
2490
+ /** Estado de papel atual. */
2491
+ _role = "follower";
2492
+ /** Promise resolve que libera o lock perpétuo. */
2493
+ _releaseLock = null;
2494
+ /** `true` se destroy() já foi chamado. */
2495
+ _destroyed = false;
2496
+ /** `true` se start() já foi chamado. */
2497
+ _started = false;
2498
+ /** Listeners de mudança de papel. */
2499
+ _roleListeners = /* @__PURE__ */ new Set();
2500
+ /** Listeners de mensagem recebida. */
2501
+ _messageListeners = /* @__PURE__ */ new Set();
2502
+ constructor(options) {
2503
+ this._lockName = options.lockName;
2504
+ this._channelName = options.channelName;
2505
+ this._tabId = `tab-${Math.random().toString(36).slice(2, 10)}-${Date.now()}`;
2506
+ this._lockManager = options.lockManager !== void 0 ? options.lockManager : typeof navigator !== "undefined" && "locks" in navigator && navigator.locks != null ? navigator.locks : void 0;
2507
+ if (options.broadcastChannel !== void 0) {
2508
+ this._channel = options.broadcastChannel;
2509
+ } else if (typeof BroadcastChannel !== "undefined") {
2510
+ const channelName = this._channelName;
2511
+ this._channelFactory = () => {
2512
+ const bc = new BroadcastChannel(channelName);
2513
+ const wrapper = {
2514
+ get onmessage() {
2515
+ return bc.onmessage;
2516
+ },
2517
+ set onmessage(cb) {
2518
+ bc.onmessage = cb ? (event) => cb(event.data) : null;
2519
+ },
2520
+ postMessage: (msg) => bc.postMessage(msg),
2521
+ close: () => bc.close()
2522
+ };
2523
+ return wrapper;
2524
+ };
2525
+ }
2526
+ }
2527
+ // ─── Ciclo de vida ───────────────────────────────────────────────────────────
2528
+ /**
2529
+ * Inicia o processo de eleição de líder.
2530
+ * Idempotente: sem efeito se já foi chamado.
2531
+ */
2532
+ start() {
2533
+ if (this._started || this._destroyed) return;
2534
+ this._started = true;
2535
+ if (!this._channel && this._channelFactory) {
2536
+ this._channel = this._channelFactory();
2537
+ }
2538
+ if (this._channel) {
2539
+ this._channel.onmessage = (msg) => {
2540
+ this._handleIncomingMessage(msg);
2541
+ };
2542
+ }
2543
+ if (this._lockManager) {
2544
+ this._electWithLocks();
2545
+ } else {
2546
+ this._becomeLeader();
2547
+ }
2548
+ }
2549
+ /**
2550
+ * Para o TabCoordinator: libera o lock, fecha o canal.
2551
+ * Idempotente: pode ser chamado múltiplas vezes.
2552
+ */
2553
+ destroy() {
2554
+ if (this._destroyed) return;
2555
+ this._destroyed = true;
2556
+ this._started = false;
2557
+ if (this._releaseLock) {
2558
+ this._releaseLock();
2559
+ this._releaseLock = null;
2560
+ }
2561
+ if (this._channel) {
2562
+ this._channel.onmessage = null;
2563
+ this._channel.close();
2564
+ this._channel = void 0;
2565
+ }
2566
+ this._role = "follower";
2567
+ this._roleListeners.clear();
2568
+ this._messageListeners.clear();
2569
+ }
2570
+ // ─── Estado ──────────────────────────────────────────────────────────────────
2571
+ /**
2572
+ * Retorna `true` se esta aba é atualmente a líder.
2573
+ */
2574
+ isLeader() {
2575
+ return !this._destroyed && this._role === "leader";
2576
+ }
2577
+ /**
2578
+ * Retorna o papel atual desta aba.
2579
+ */
2580
+ getRole() {
2581
+ return this._destroyed ? "follower" : this._role;
2582
+ }
2583
+ /**
2584
+ * ID único desta aba (para diagnóstico).
2585
+ */
2586
+ get tabId() {
2587
+ return this._tabId;
2588
+ }
2589
+ // ─── Subscrições ─────────────────────────────────────────────────────────────
2590
+ /**
2591
+ * Registra um listener para mudanças de papel (`'leader'` | `'follower'`).
2592
+ *
2593
+ * @returns Função de unsubscribe.
2594
+ */
2595
+ onRoleChange(listener) {
2596
+ this._roleListeners.add(listener);
2597
+ return () => {
2598
+ this._roleListeners.delete(listener);
2599
+ };
2600
+ }
2601
+ /**
2602
+ * Registra um listener para mensagens recebidas de outras abas via
2603
+ * BroadcastChannel. O remetente NÃO recebe suas próprias mensagens.
2604
+ *
2605
+ * @returns Função de unsubscribe.
2606
+ */
2607
+ onMessage(listener) {
2608
+ this._messageListeners.add(listener);
2609
+ return () => {
2610
+ this._messageListeners.delete(listener);
2611
+ };
2612
+ }
2613
+ // ─── Comunicação ─────────────────────────────────────────────────────────────
2614
+ /**
2615
+ * Transmite uma mensagem para todas as outras abas via BroadcastChannel.
2616
+ * Sem efeito se o canal não estiver disponível ou o coordinator foi destroyed.
2617
+ */
2618
+ broadcast(msg) {
2619
+ if (this._destroyed) return;
2620
+ try {
2621
+ this._channel?.postMessage(msg);
2622
+ } catch {
2623
+ }
2624
+ }
2625
+ // ─── Privado — eleição ───────────────────────────────────────────────────────
2626
+ /**
2627
+ * Inicia a disputa pelo lock Web Locks.
2628
+ *
2629
+ * `navigator.locks.request` com uma Promise-interna que nunca resolve:
2630
+ * enquanto a aba vive e o lock está ativo, a callback não retorna.
2631
+ * Ao chamar `destroy()` a Promise interna resolve → lock liberado.
2632
+ */
2633
+ _electWithLocks() {
2634
+ const lockPromise = new Promise((resolve) => {
2635
+ this._releaseLock = resolve;
2636
+ });
2637
+ Promise.resolve().then(() => {
2638
+ if (!this._destroyed && this._role === "follower") {
2639
+ this._notifyRoleChange("follower");
2640
+ }
2641
+ });
2642
+ this._lockManager.request(this._lockName, (_lock) => {
2643
+ if (this._destroyed) {
2644
+ return Promise.resolve();
2645
+ }
2646
+ this._becomeLeader();
2647
+ return lockPromise;
2648
+ }).catch(() => {
2649
+ });
2650
+ }
2651
+ /**
2652
+ * Transição para o papel de líder.
2653
+ */
2654
+ _becomeLeader() {
2655
+ if (this._destroyed) return;
2656
+ this._setRole("leader");
2657
+ Promise.resolve().then(() => {
2658
+ if (!this._destroyed) this._broadcastSyncState();
2659
+ });
2660
+ }
2661
+ /**
2662
+ * Muda o papel e notifica os listeners.
2663
+ */
2664
+ _setRole(role) {
2665
+ const previous = this._role;
2666
+ this._role = role;
2667
+ if (previous !== role) {
2668
+ this._notifyRoleChange(role);
2669
+ }
2670
+ }
2671
+ /**
2672
+ * Transmite o estado de sync atual (chamado ao se tornar líder).
2673
+ */
2674
+ _broadcastSyncState() {
2675
+ this.broadcast({
2676
+ type: "sync_state",
2677
+ leaderTabId: this._tabId,
2678
+ syncing: false,
2679
+ pendingWrites: 0
2680
+ });
2681
+ }
2682
+ // ─── Privado — mensagens ─────────────────────────────────────────────────────
2683
+ /**
2684
+ * Processa mensagem recebida de outra aba.
2685
+ * Mensagens de tipo desconhecido são ignoradas silenciosamente.
2686
+ */
2687
+ _handleIncomingMessage(msg) {
2688
+ if (this._destroyed) return;
2689
+ if (!msg || typeof msg.type !== "string") return;
2690
+ for (const listener of this._messageListeners) {
2691
+ try {
2692
+ listener(msg);
2693
+ } catch {
2694
+ }
2695
+ }
2696
+ }
2697
+ // ─── Privado — notificações ───────────────────────────────────────────────────
2698
+ _notifyRoleChange(role) {
2699
+ for (const listener of this._roleListeners) {
2700
+ try {
2701
+ listener(role);
2702
+ } catch {
2703
+ }
2704
+ }
2705
+ }
2706
+ };
2707
+
2708
+ // src/db/collection-ref.ts
2709
+ var COLL_RE = /^[a-z0-9][a-z0-9_-]{0,62}$/;
2710
+ function assertValidCollection(name) {
2711
+ if (!COLL_RE.test(name)) {
2712
+ throw new NeetruDbError(
2713
+ "db_invalid_query",
2714
+ `Nome de cole\xE7\xE3o inv\xE1lido: "${name}". Deve seguir o padr\xE3o ${COLL_RE}.`
2715
+ );
2716
+ }
2717
+ }
2718
+ function assertValidId(id, label = "id") {
2719
+ if (!id || typeof id !== "string" || id.trim() === "") {
2720
+ throw new NeetruDbError(
2721
+ "db_invalid_query",
2722
+ `${label} \xE9 obrigat\xF3rio e deve ser uma string n\xE3o-vazia.`
2723
+ );
2724
+ }
2725
+ }
2726
+ function toQueryDescriptor(query) {
2727
+ const desc = {};
2728
+ if (query?.where) {
2729
+ desc.where = query.where.map((f) => ({
2730
+ field: f.field,
2731
+ op: f.op,
2732
+ value: f.value
2733
+ }));
2734
+ }
2735
+ if (query?.orderBy) {
2736
+ desc.orderBy = {
2737
+ field: query.orderBy.field,
2738
+ direction: query.orderBy.direction
2739
+ };
2740
+ }
2741
+ if (query?.limit !== void 0) {
2742
+ desc.limit = query.limit;
2743
+ }
2744
+ if (query?.cursor) {
2745
+ try {
2746
+ const cursorObj = JSON.parse(atob(query.cursor));
2747
+ desc.cursor = { type: cursorObj.type ?? "startAfter", docId: cursorObj.docId };
2748
+ } catch {
2749
+ }
2750
+ }
2751
+ return desc;
2752
+ }
2753
+ function buildNextCursor(docs, limit) {
2754
+ if (docs.length < limit) return null;
2755
+ const lastDoc = docs[docs.length - 1];
2756
+ if (!lastDoc) return null;
2757
+ return btoa(JSON.stringify({ type: "startAfter", docId: lastDoc.id }));
2758
+ }
2759
+ var DbCollectionRefImpl = class {
2760
+ constructor(_collection, _store, _queue, _bus, _engine, _connectivity) {
2761
+ this._collection = _collection;
2762
+ this._store = _store;
2763
+ this._queue = _queue;
2764
+ this._bus = _bus;
2765
+ this._engine = _engine;
2766
+ this._connectivity = _connectivity;
2767
+ }
2768
+ _collection;
2769
+ _store;
2770
+ _queue;
2771
+ _bus;
2772
+ _engine;
2773
+ _connectivity;
2774
+ // ── helpers ────────────────────────────────────────────────────────────────
2775
+ /** Verifica se há mutações pendentes para esta coleção. */
2776
+ async _hasPendingWrites() {
2777
+ const pending = await this._queue.listPending();
2778
+ return pending.some((m) => m.collection === this._collection);
2779
+ }
2780
+ /** Verifica se há mutações pendentes para um doc específico. */
2781
+ async _docHasPendingWrites(id) {
2782
+ const pending = await this._queue.listPending();
2783
+ return pending.some((m) => m.collection === this._collection && m.docId === id);
2784
+ }
2785
+ _isOnline() {
2786
+ return this._connectivity.isOnline;
2787
+ }
2788
+ /** Constrói um DbGetResult para um doc específico, ou null se tombstoned/ausente. */
2789
+ async _buildGetResult(id) {
2790
+ const doc = await this._store.getDoc(this._collection, id);
2791
+ if (!doc || doc.meta.deleted) return null;
2792
+ const hasPending = await this._docHasPendingWrites(id);
2793
+ const isOnline = this._isOnline();
2794
+ const syncState = this._engine.getSyncState();
2795
+ const staleGet = !isOnline || syncState.status === "offline";
2796
+ const fromCacheGet = hasPending || syncState.lastSyncedAt === null || staleGet;
2797
+ return {
2798
+ docs: [{ id: doc.id, data: doc.data }],
2799
+ fromCache: fromCacheGet,
2800
+ stale: staleGet,
2801
+ hasPendingWrites: hasPending,
2802
+ changes: []
2803
+ };
2804
+ }
2805
+ /** Constrói um DbListResult para a coleção com query opcional. */
2806
+ async _buildListResult(q) {
2807
+ const desc = toQueryDescriptor(q);
2808
+ const effectiveLimit = desc.limit ?? 20;
2809
+ const result = await this._store.listDocs(this._collection, desc);
2810
+ const hasPending = await this._hasPendingWrites();
2811
+ const isOnline = this._isOnline();
2812
+ const syncState = this._engine.getSyncState();
2813
+ const nextCursor = buildNextCursor(result.docs, effectiveLimit);
2814
+ const stale = !isOnline || syncState.status === "offline";
2815
+ const fromCache = hasPending || syncState.lastSyncedAt === null || stale;
2816
+ return {
2817
+ docs: result.docs.map((d) => ({ id: d.id, data: d.data })),
2818
+ nextCursor,
2819
+ fromCache,
2820
+ stale,
2821
+ hasPendingWrites: hasPending,
2822
+ changes: []
2823
+ };
2824
+ }
2825
+ // ── CRUD ────────────────────────────────────────────────────────────────────
2826
+ async get(id) {
2827
+ assertValidId(id);
2828
+ return this._buildGetResult(id);
2829
+ }
2830
+ async list(q) {
2831
+ return this._buildListResult(q);
2832
+ }
2833
+ async add(data) {
2834
+ const mutation = await this._queue.enqueue({
2835
+ collection: this._collection,
2836
+ op: "add",
2837
+ payload: data,
2838
+ baseVersion: null,
2839
+ batchId: null
2840
+ });
2841
+ const docId = mutation.docId;
2842
+ await this._store.putDoc({
2843
+ collection: this._collection,
2844
+ id: docId,
2845
+ data,
2846
+ meta: {
2847
+ serverVersion: null,
2848
+ updatedAtServer: null,
2849
+ updatedAtLocal: Date.now(),
2850
+ state: "pending",
2851
+ pendingMutationIds: [mutation.mutationId],
2852
+ deleted: false,
2853
+ ownerId: null
2854
+ }
2855
+ });
2856
+ this._bus.emit([{
2857
+ type: "added",
2858
+ collection: this._collection,
2859
+ doc: { id: docId, data }
2860
+ }]);
2861
+ return { ok: true, id: docId };
2862
+ }
2863
+ async set(id, data) {
2864
+ assertValidId(id);
2865
+ const existing = await this._store.getDoc(this._collection, id);
2866
+ const mutation = await this._queue.enqueue({
2867
+ collection: this._collection,
2868
+ docId: id,
2869
+ op: "set",
2870
+ payload: data,
2871
+ baseVersion: existing?.meta.serverVersion ?? null,
2872
+ batchId: null
2873
+ });
2874
+ await this._store.putDoc({
2875
+ collection: this._collection,
2876
+ id,
2877
+ data,
2878
+ meta: {
2879
+ serverVersion: existing?.meta.serverVersion ?? null,
2880
+ updatedAtServer: existing?.meta.updatedAtServer ?? null,
2881
+ updatedAtLocal: Date.now(),
2882
+ state: "pending",
2883
+ pendingMutationIds: [mutation.mutationId],
2884
+ deleted: false,
2885
+ ownerId: null
2886
+ }
2887
+ });
2888
+ this._bus.emit([{
2889
+ type: existing && !existing.meta.deleted ? "modified" : "added",
2890
+ collection: this._collection,
2891
+ doc: { id, data }
2892
+ }]);
2893
+ return { ok: true };
2894
+ }
2895
+ async update(id, data) {
2896
+ assertValidId(id);
2897
+ const existing = await this._store.getDoc(this._collection, id);
2898
+ const mergedData = existing?.meta.deleted ? { ...data } : { ...existing?.data ?? {}, ...data };
2899
+ const mutation = await this._queue.enqueue({
2900
+ collection: this._collection,
2901
+ docId: id,
2902
+ op: "update",
2903
+ payload: data,
2904
+ baseVersion: existing?.meta.serverVersion ?? null,
2905
+ batchId: null
2906
+ });
2907
+ await this._store.putDoc({
2908
+ collection: this._collection,
2909
+ id,
2910
+ data: mergedData,
2911
+ meta: {
2912
+ serverVersion: existing?.meta.serverVersion ?? null,
2913
+ updatedAtServer: existing?.meta.updatedAtServer ?? null,
2914
+ updatedAtLocal: Date.now(),
2915
+ state: "pending",
2916
+ pendingMutationIds: [
2917
+ ...existing?.meta.pendingMutationIds ?? [],
2918
+ mutation.mutationId
2919
+ ],
2920
+ deleted: false,
2921
+ ownerId: existing?.meta.ownerId ?? null
2922
+ }
2923
+ });
2924
+ this._bus.emit([{
2925
+ type: "modified",
2926
+ collection: this._collection,
2927
+ doc: { id, data: mergedData }
2928
+ }]);
2929
+ return { ok: true };
2930
+ }
2931
+ async remove(id) {
2932
+ assertValidId(id);
2933
+ const existing = await this._store.getDoc(this._collection, id);
2934
+ if (!existing || existing.meta.deleted) ;
2935
+ await this._queue.enqueue({
2936
+ collection: this._collection,
2937
+ docId: id,
2938
+ op: "remove",
2939
+ payload: null,
2940
+ baseVersion: existing?.meta.serverVersion ?? null,
2941
+ batchId: null
2942
+ });
2943
+ await this._store.deleteDoc(this._collection, id);
2944
+ if (existing && !existing.meta.deleted) {
2945
+ this._bus.emit([{
2946
+ type: "removed",
2947
+ collection: this._collection,
2948
+ doc: { id, data: existing.data }
2949
+ }]);
2950
+ }
2951
+ return { ok: true };
2952
+ }
2953
+ async batch(ops) {
2954
+ const batchId = `batch-${Date.now()}-${Math.random().toString(36).slice(2)}`;
2955
+ const busChanges = [];
2956
+ for (const op of ops) {
2957
+ const id = op.id ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
2958
+ const data = op.data ?? {};
2959
+ const collection = op.collection;
2960
+ if (op.op === "add") {
2961
+ const mutation = await this._queue.enqueue({
2962
+ collection,
2963
+ op: "add",
2964
+ payload: data,
2965
+ baseVersion: null,
2966
+ batchId
2967
+ });
2968
+ const docId = mutation.docId;
2969
+ await this._store.putDoc({
2970
+ collection,
2971
+ id: docId,
2972
+ data,
2973
+ meta: {
2974
+ serverVersion: null,
2975
+ updatedAtServer: null,
2976
+ updatedAtLocal: Date.now(),
2977
+ state: "pending",
2978
+ pendingMutationIds: [mutation.mutationId],
2979
+ deleted: false,
2980
+ ownerId: null
2981
+ }
2982
+ });
2983
+ busChanges.push({ type: "added", collection, doc: { id: docId, data } });
2984
+ } else if (op.op === "set") {
2985
+ const existing = await this._store.getDoc(collection, id);
2986
+ const mutation = await this._queue.enqueue({
2987
+ collection,
2988
+ docId: id,
2989
+ op: "set",
2990
+ payload: data,
2991
+ baseVersion: existing?.meta.serverVersion ?? null,
2992
+ batchId
2993
+ });
2994
+ await this._store.putDoc({
2995
+ collection,
2996
+ id,
2997
+ data,
2998
+ meta: {
2999
+ serverVersion: existing?.meta.serverVersion ?? null,
3000
+ updatedAtServer: existing?.meta.updatedAtServer ?? null,
3001
+ updatedAtLocal: Date.now(),
3002
+ state: "pending",
3003
+ pendingMutationIds: [mutation.mutationId],
3004
+ deleted: false,
3005
+ ownerId: null
3006
+ }
3007
+ });
3008
+ busChanges.push({
3009
+ type: existing && !existing.meta.deleted ? "modified" : "added",
3010
+ collection,
3011
+ doc: { id, data }
3012
+ });
3013
+ } else if (op.op === "update") {
3014
+ const existing = await this._store.getDoc(collection, id);
3015
+ const merged = { ...existing?.data ?? {}, ...data };
3016
+ const mutation = await this._queue.enqueue({
3017
+ collection,
3018
+ docId: id,
3019
+ op: "update",
3020
+ payload: data,
3021
+ baseVersion: existing?.meta.serverVersion ?? null,
3022
+ batchId
3023
+ });
3024
+ await this._store.putDoc({
3025
+ collection,
3026
+ id,
3027
+ data: merged,
3028
+ meta: {
3029
+ serverVersion: existing?.meta.serverVersion ?? null,
3030
+ updatedAtServer: existing?.meta.updatedAtServer ?? null,
3031
+ updatedAtLocal: Date.now(),
3032
+ state: "pending",
3033
+ pendingMutationIds: [
3034
+ ...existing?.meta.pendingMutationIds ?? [],
3035
+ mutation.mutationId
3036
+ ],
3037
+ deleted: false,
3038
+ ownerId: existing?.meta.ownerId ?? null
3039
+ }
3040
+ });
3041
+ busChanges.push({ type: "modified", collection, doc: { id, data: merged } });
3042
+ } else if (op.op === "remove") {
3043
+ const existing = await this._store.getDoc(collection, id);
3044
+ await this._queue.enqueue({
3045
+ collection,
3046
+ docId: id,
3047
+ op: "remove",
3048
+ payload: null,
3049
+ baseVersion: existing?.meta.serverVersion ?? null,
3050
+ batchId
3051
+ });
3052
+ await this._store.deleteDoc(collection, id);
3053
+ if (existing && !existing.meta.deleted) {
3054
+ busChanges.push({ type: "removed", collection, doc: { id, data: existing.data } });
3055
+ }
3056
+ }
3057
+ }
3058
+ if (busChanges.length > 0) {
3059
+ this._bus.emit(busChanges);
3060
+ }
3061
+ return { ok: true };
3062
+ }
3063
+ // ── Realtime ─────────────────────────────────────────────────────────────────
3064
+ onDoc(id, cb) {
3065
+ assertValidId(id);
3066
+ this._buildGetResult(id).then((r) => {
3067
+ cb(r ? r.docs[0]?.data ?? null : null);
3068
+ }).catch(() => cb(null));
3069
+ return this._bus.subscribe(this._collection, (changes) => {
3070
+ const relevant = changes.find((c) => c.doc.id === id);
3071
+ if (!relevant) return;
3072
+ if (relevant.type === "removed") {
3073
+ cb(null);
3074
+ } else {
3075
+ cb(relevant.doc.data);
3076
+ }
3077
+ });
3078
+ }
3079
+ onSnapshot(q, cb) {
3080
+ this._buildListResult(q).then((snap) => cb(snap)).catch(() => {
3081
+ });
3082
+ const unsubBus = this._bus.subscribe(this._collection, async (_changes) => {
3083
+ try {
3084
+ const snap = await this._buildListResult(q);
3085
+ const delta = _changes.map((c) => ({
3086
+ type: c.type,
3087
+ doc: { id: c.doc.id, data: c.doc.data }
3088
+ }));
3089
+ cb({ ...snap, changes: delta });
3090
+ } catch {
3091
+ }
3092
+ });
3093
+ const unsubSync = this._engine.onSyncStateChange(async () => {
3094
+ try {
3095
+ const snap = await this._buildListResult(q);
3096
+ cb(snap);
3097
+ } catch {
3098
+ }
3099
+ });
3100
+ let unsubRealtime;
3101
+ if (typeof this._engine.transport.subscribeCollection === "function") {
3102
+ unsubRealtime = this._engine.transport.subscribeCollection(
3103
+ this._collection,
3104
+ async (remoteChanges, needsResync) => {
3105
+ if (needsResync) {
3106
+ return;
3107
+ }
3108
+ for (const rc of remoteChanges) {
3109
+ if (rc.type === "removed" || rc.data === null) {
3110
+ await this._store.deleteDoc(this._collection, rc.docId);
3111
+ this._bus.emit([{
3112
+ type: "removed",
3113
+ collection: this._collection,
3114
+ doc: { id: rc.docId, data: {} }
3115
+ }]);
3116
+ } else {
3117
+ await this._store.putDoc({
3118
+ collection: this._collection,
3119
+ id: rc.docId,
3120
+ data: rc.data,
3121
+ meta: {
3122
+ serverVersion: `rt_${Date.now()}`,
3123
+ updatedAtServer: Date.now(),
3124
+ updatedAtLocal: Date.now(),
3125
+ state: "synced",
3126
+ pendingMutationIds: [],
3127
+ deleted: false,
3128
+ ownerId: null
3129
+ }
3130
+ });
3131
+ this._bus.emit([{
3132
+ type: rc.type,
3133
+ collection: this._collection,
3134
+ doc: { id: rc.docId, data: rc.data }
3135
+ }]);
3136
+ }
3137
+ }
3138
+ }
3139
+ );
3140
+ }
3141
+ return () => {
3142
+ unsubBus();
3143
+ unsubSync();
3144
+ unsubRealtime?.();
3145
+ };
3146
+ }
3147
+ doc(id) {
3148
+ assertValidId(id);
3149
+ const self = this;
3150
+ return {
3151
+ async get() {
3152
+ return self._buildGetResult(id);
3153
+ },
3154
+ async set(data) {
3155
+ return self.set(id, data);
3156
+ },
3157
+ async update(data) {
3158
+ return self.update(id, data);
3159
+ },
3160
+ async remove() {
3161
+ return self.remove(id);
3162
+ },
3163
+ onSnapshot(cb) {
3164
+ self._buildGetResult(id).then((r) => cb(r)).catch(() => cb(null));
3165
+ const unsubBus = self._bus.subscribe(self._collection, async (changes) => {
3166
+ const relevant = changes.find((c) => c.doc.id === id);
3167
+ if (!relevant) return;
3168
+ try {
3169
+ if (relevant.type === "removed") {
3170
+ cb(null);
3171
+ } else {
3172
+ const result = await self._buildGetResult(id);
3173
+ cb(result);
3174
+ }
3175
+ } catch {
3176
+ cb(null);
3177
+ }
3178
+ });
3179
+ const unsubSync = self._engine.onSyncStateChange(async () => {
3180
+ try {
3181
+ const result = await self._buildGetResult(id);
3182
+ cb(result);
3183
+ } catch {
3184
+ cb(null);
3185
+ }
3186
+ });
3187
+ return () => {
3188
+ unsubBus();
3189
+ unsubSync();
3190
+ };
3191
+ }
3192
+ };
3193
+ }
3194
+ };
3195
+ var NeetruDbDocumentsImpl = class {
3196
+ _store;
3197
+ _queue;
3198
+ _bus;
3199
+ _engine;
3200
+ _connectivity;
3201
+ constructor(opts) {
3202
+ this._store = opts.store;
3203
+ this._queue = opts.queue;
3204
+ this._bus = opts.bus;
3205
+ this._engine = opts.engine;
3206
+ this._connectivity = opts.connectivity;
3207
+ }
3208
+ collection(name) {
3209
+ assertValidCollection(name);
3210
+ return new DbCollectionRefImpl(
3211
+ name,
3212
+ this._store,
3213
+ this._queue,
3214
+ this._bus,
3215
+ this._engine,
3216
+ this._connectivity
3217
+ );
3218
+ }
3219
+ get syncState() {
3220
+ return this._engine.getSyncState();
3221
+ }
3222
+ onSyncStateChanged(cb) {
3223
+ return this._engine.onSyncStateChange(cb);
3224
+ }
3225
+ async flush() {
3226
+ return this._engine.flush();
3227
+ }
3228
+ async clearCache() {
3229
+ await this._store.close();
3230
+ await this._store.open();
3231
+ }
3232
+ async getConflicts() {
3233
+ return this._store.listConflicts();
3234
+ }
3235
+ };
3236
+ async function createOfflineDocumentsNamespace(opts) {
3237
+ const store = new LocalStore(opts.dbName);
3238
+ await store.open();
3239
+ const queue = new MutationQueue(store);
3240
+ const resolver = new ConflictResolver();
3241
+ const bus = new ChangeBus();
3242
+ const connectivity = new ConnectivityMonitor({
3243
+ // Se startOnline=false, injeta um navigator falso
3244
+ navigator: opts.startOnline === false ? { onLine: false } : typeof navigator !== "undefined" ? navigator : void 0
3245
+ });
3246
+ const tabCoordinatorLike = opts.singleTab ? (
3247
+ // Fake tab coordinator para single-tab mode (sempre líder)
3248
+ {
3249
+ isLeader: () => true,
3250
+ onRoleChange: (_cb) => {
3251
+ return () => {
3252
+ };
3253
+ }
3254
+ }
3255
+ ) : new TabCoordinator({
3256
+ lockName: `neetru-offline:${opts.dbName}`,
3257
+ channelName: `neetru-offline:${opts.dbName}`
3258
+ });
3259
+ const engine = new SyncEngine({
3260
+ store,
3261
+ queue,
3262
+ resolver,
3263
+ bus,
3264
+ transport: opts.transport,
3265
+ tabCoordinator: tabCoordinatorLike,
3266
+ connectivity,
3267
+ periodicSyncIntervalMs: opts.periodicSyncIntervalMs ?? 5 * 60 * 1e3
3268
+ });
3269
+ return new NeetruDbDocumentsImpl({
3270
+ store,
3271
+ queue,
3272
+ bus,
3273
+ engine,
3274
+ connectivity
3275
+ });
3276
+ }
3277
+
3278
+ // src/db/sql/lease.ts
3279
+ var RENEWAL_THRESHOLD = 0.8;
3280
+ var MIN_RENEWAL_DELAY_MS = 3e4;
3281
+ var SqlLeaseManager = class {
3282
+ _lease;
3283
+ _pool;
3284
+ _orm;
3285
+ _renewalTimer = null;
3286
+ _closed = false;
3287
+ _deps;
3288
+ constructor(lease, pool, orm, deps) {
3289
+ this._lease = lease;
3290
+ this._pool = pool;
3291
+ this._orm = orm;
3292
+ this._deps = {
3293
+ ...deps,
3294
+ now: deps.now ?? (() => Date.now())
3295
+ };
3296
+ this._scheduleRenewal();
3297
+ }
3298
+ // ─── Superfície pública (NeetruSqlClient) ──────────────────────────────────
3299
+ get orm() {
3300
+ this._assertOpen();
3301
+ return this._orm;
3302
+ }
3303
+ async transaction(fn, opts) {
3304
+ this._assertOpen();
3305
+ try {
3306
+ if (opts?.isolationLevel) {
3307
+ return await this._orm.transaction(fn, {
3308
+ isolationLevel: opts.isolationLevel
3309
+ });
3310
+ }
3311
+ return await this._orm.transaction(fn);
3312
+ } catch (err) {
3313
+ throw mapPoolError(err);
3314
+ }
3315
+ }
3316
+ async close() {
3317
+ if (this._closed) return;
3318
+ this._closed = true;
3319
+ this._cancelRenewal();
3320
+ await this._pool.end().catch(() => {
3321
+ });
3322
+ }
3323
+ // ─── Renovação proativa ────────────────────────────────────────────────────
3324
+ /**
3325
+ * Calcula o delay de renovação: momento de ~80% do TTL restante.
3326
+ *
3327
+ * Fórmula: `renewAt = issuedAt + TTL * RENEWAL_THRESHOLD`
3328
+ * = `expiresAt - TTL * (1 - RENEWAL_THRESHOLD)`
3329
+ *
3330
+ * Se o lease já está além do ponto de renovação (ou TTL não calculável),
3331
+ * usa `MIN_RENEWAL_DELAY_MS` como fallback seguro.
3332
+ */
3333
+ _calcRenewalDelayMs() {
3334
+ const expiresAtMs = Date.parse(this._lease.expiresAt);
3335
+ if (!Number.isFinite(expiresAtMs)) return MIN_RENEWAL_DELAY_MS;
3336
+ const now = this._deps.now();
3337
+ const remainingMs = expiresAtMs - now;
3338
+ if (remainingMs <= 0) return MIN_RENEWAL_DELAY_MS;
3339
+ const renewInMs = remainingMs * (1 - RENEWAL_THRESHOLD);
3340
+ return Math.max(MIN_RENEWAL_DELAY_MS, Math.round(renewInMs));
3341
+ }
3342
+ _scheduleRenewal() {
3343
+ if (this._closed) return;
3344
+ const delayMs = this._calcRenewalDelayMs();
3345
+ this._renewalTimer = setTimeout(() => {
3346
+ void this._doRenew();
3347
+ }, delayMs);
3348
+ }
3349
+ _cancelRenewal() {
3350
+ if (this._renewalTimer !== null) {
3351
+ clearTimeout(this._renewalTimer);
3352
+ this._renewalTimer = null;
3353
+ }
3354
+ }
3355
+ async _doRenew() {
3356
+ if (this._closed) return;
3357
+ try {
3358
+ const renewOpts = {
3359
+ leaseId: this._lease.leaseId
3360
+ };
3361
+ if (this._deps.database !== void 0) {
3362
+ renewOpts.database = this._deps.database;
3363
+ }
3364
+ const newLease = await this._deps.fetchLease(renewOpts);
3365
+ await this._swapPool(newLease);
3366
+ } catch (err) {
3367
+ this._renewalTimer = setTimeout(() => {
3368
+ void this._doRenew();
3369
+ }, MIN_RENEWAL_DELAY_MS);
3370
+ if (process.env["NODE_ENV"] !== "production") {
3371
+ console.warn("[SqlLeaseManager] Lease renewal failed, will retry:", err);
3372
+ }
3373
+ return;
3374
+ }
3375
+ this._scheduleRenewal();
3376
+ }
3377
+ /**
3378
+ * Hot-swap do pool: cria pool novo, atualiza ponteiros, drena pool antigo.
3379
+ *
3380
+ * Exposto como método protegido para testes.
3381
+ */
3382
+ async _swapPool(newLease) {
3383
+ const credRotated = newLease.credentialVersion !== this._lease.credentialVersion;
3384
+ if (!credRotated && newLease.leaseId === this._lease.leaseId) {
3385
+ this._lease = newLease;
3386
+ return;
3387
+ }
3388
+ const newPool = this._deps.createPool(newLease);
3389
+ const newOrm = this._deps.createDrizzle(newPool, this._deps.schema);
3390
+ const oldPool = this._pool;
3391
+ this._lease = newLease;
3392
+ this._pool = newPool;
3393
+ this._orm = newOrm;
3394
+ void oldPool.end().catch(() => {
3395
+ });
3396
+ }
3397
+ // ─── Helpers ───────────────────────────────────────────────────────────────
3398
+ _assertOpen() {
3399
+ if (this._closed) {
3400
+ throw new NeetruDbError(
3401
+ "db_unavailable",
3402
+ "SqlLeaseManager foi fechado \u2014 chame close() apenas no shutdown."
3403
+ );
3404
+ }
3405
+ }
3406
+ };
3407
+ function mapPoolError(err) {
3408
+ if (err instanceof NeetruDbError) return err;
3409
+ const message = err instanceof Error ? err.message : String(err);
3410
+ const code = err instanceof Error ? err.code : void 0;
3411
+ if (typeof code === "string" && (code === "ECONNREFUSED" || code === "ENOTFOUND" || code === "ETIMEDOUT")) {
3412
+ return new NeetruDbError(
3413
+ "db_unavailable",
3414
+ `Pool connection failed (${code}): ${message}`
3415
+ );
3416
+ }
3417
+ if (message.includes("statement timeout") || message.includes("lock timeout")) {
3418
+ return new NeetruDbError("db_timeout", `Query timeout: ${message}`);
3419
+ }
3420
+ if (message.includes("40001") || message.includes("40P01") || message.includes("deadlock")) {
3421
+ return new NeetruDbError("db_conflict", `Transaction conflict: ${message}`);
3422
+ }
3423
+ if (message.includes("42501") || message.toLowerCase().includes("permission denied")) {
3424
+ return new NeetruDbError("db_permission_denied", `Permission denied: ${message}`);
3425
+ }
3426
+ return new NeetruDbError("db_unavailable", `Database error: ${message}`);
3427
+ }
3428
+
3429
+ // src/db/sql/sql-client.ts
3430
+ var LEASE_ENDPOINT = "/api/sdk/v1/db/lease";
3431
+ var LEASE_RENEW_ENDPOINT = "/api/sdk/v1/db/lease/renew";
3432
+ function mapEnvToCore(sdkEnv) {
3433
+ if (sdkEnv === "workspace") return "staging";
3434
+ if (sdkEnv === "prod") return "production";
3435
+ return "dev";
3436
+ }
3437
+ function createHttpLeaseFetcher(config) {
3438
+ return async (opts) => {
3439
+ const { httpRequest: httpRequest2 } = await Promise.resolve().then(() => (init_http(), http_exports));
3440
+ const isRenewal = Boolean(opts?.leaseId);
3441
+ const path = isRenewal ? LEASE_RENEW_ENDPOINT : LEASE_ENDPOINT;
3442
+ let body;
3443
+ if (isRenewal) {
3444
+ body = { leaseId: opts.leaseId };
3445
+ } else {
3446
+ body = {
3447
+ productId: config.productId ?? "",
3448
+ environment: mapEnvToCore(config.env ?? "prod")
3449
+ };
3450
+ if (opts?.database !== void 0) {
3451
+ body["database"] = opts.database;
3452
+ }
3453
+ }
3454
+ let raw;
3455
+ try {
3456
+ raw = await httpRequest2(config, {
3457
+ method: "POST",
3458
+ path,
3459
+ body,
3460
+ requireAuth: true,
3461
+ // Lease fetch é idempotente do ponto de vista de segurança — retries OK.
3462
+ retries: 2
3463
+ });
3464
+ } catch (err) {
3465
+ const msg = err instanceof Error ? err.message : String(err);
3466
+ throw new NeetruDbError(
3467
+ "db_unavailable",
3468
+ `Falha ao ${isRenewal ? "renovar" : "obter"} lease SQL: ${msg}`
3469
+ );
3470
+ }
3471
+ return parseLease(raw);
3472
+ };
3473
+ }
3474
+ function parseLease(raw) {
3475
+ if (!raw || typeof raw !== "object") {
3476
+ throw new NeetruDbError("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
3477
+ }
3478
+ const envelope = raw;
3479
+ const leaseObj = envelope["lease"];
3480
+ if (!leaseObj || typeof leaseObj !== "object") {
3481
+ throw new NeetruDbError(
3482
+ "db_unavailable",
3483
+ 'Resposta de lease inv\xE1lida: campo "lease" ausente ou n\xE3o \xE9 objeto. O Core retorna { kind, lease: { leaseId, host, ... } }.'
3484
+ );
3485
+ }
3486
+ const r = leaseObj;
3487
+ function req(field, type) {
3488
+ if (typeof r[field] !== type) {
3489
+ throw new NeetruDbError(
3490
+ "db_unavailable",
3491
+ `Campo obrigat\xF3rio "${field}" ausente ou tipo inv\xE1lido na resposta de lease.`
3492
+ );
3493
+ }
3494
+ return r[field];
3495
+ }
3496
+ return {
3497
+ leaseId: req("leaseId", "string"),
3498
+ host: req("host", "string"),
3499
+ port: typeof r["port"] === "number" ? r["port"] : 5433,
3500
+ dbName: req("dbName", "string"),
3501
+ user: req("user", "string"),
3502
+ password: req("password", "string"),
3503
+ sslca: typeof r["sslca"] === "string" ? r["sslca"] : null,
3504
+ clientCert: typeof r["clientCert"] === "string" ? r["clientCert"] : null,
3505
+ clientKey: typeof r["clientKey"] === "string" ? r["clientKey"] : null,
3506
+ credentialVersion: typeof r["credentialVersion"] === "number" ? r["credentialVersion"] : 1,
3507
+ expiresAt: req("expiresAt", "string")
3508
+ };
3509
+ }
3510
+ async function createSqlClientWithDeps(deps, options) {
3511
+ const depsWithDb = options?.database !== void 0 ? { ...deps, database: options.database } : deps;
3512
+ let lease;
3513
+ try {
3514
+ if (options?.database !== void 0) {
3515
+ lease = await depsWithDb.fetchLease({ database: options.database });
3516
+ } else {
3517
+ lease = await depsWithDb.fetchLease();
3518
+ }
3519
+ } catch (err) {
3520
+ if (err instanceof NeetruDbError) throw err;
3521
+ const msg = err instanceof Error ? err.message : String(err);
3522
+ throw new NeetruDbError("db_unavailable", `Falha ao obter lease inicial: ${msg}`);
3523
+ }
3524
+ let pool;
3525
+ try {
3526
+ pool = depsWithDb.createPool(lease);
3527
+ } catch (err) {
3528
+ const msg = err instanceof Error ? err.message : String(err);
3529
+ throw new NeetruDbError("db_unavailable", `Falha ao abrir pool: ${msg}`);
3530
+ }
3531
+ let orm;
3532
+ try {
3533
+ orm = depsWithDb.createDrizzle(pool, depsWithDb.schema);
3534
+ } catch (err) {
3535
+ await pool.end().catch(() => {
3536
+ });
3537
+ const msg = err instanceof Error ? err.message : String(err);
3538
+ throw new NeetruDbError("db_unavailable", `Falha ao criar handle Drizzle: ${msg}`);
3539
+ }
3540
+ return new SqlLeaseManager(lease, pool, orm, depsWithDb);
3541
+ }
3542
+ async function createSqlClientFromConfig(config, schema, options) {
3543
+ const fetchLease = createHttpLeaseFetcher(config);
3544
+ const createPool = (lease) => {
3545
+ const { Pool } = __require("pg");
3546
+ const ssl = lease.sslca ? {
3547
+ ca: lease.sslca,
3548
+ cert: lease.clientCert ?? void 0,
3549
+ key: lease.clientKey ?? void 0,
3550
+ rejectUnauthorized: true
3551
+ } : false;
3552
+ return new Pool({
3553
+ host: lease.host,
3554
+ port: lease.port,
3555
+ database: lease.dbName,
3556
+ user: lease.user,
3557
+ password: lease.password,
3558
+ ssl,
3559
+ max: 3,
3560
+ idleTimeoutMillis: 3e4,
3561
+ connectionTimeoutMillis: 1e4
3562
+ });
3563
+ };
3564
+ const createDrizzle = (pool, s) => {
3565
+ const { drizzle } = __require("drizzle-orm/node-postgres");
3566
+ return drizzle(pool, { schema: s });
3567
+ };
3568
+ return createSqlClientWithDeps(
3569
+ {
3570
+ fetchLease,
3571
+ createPool,
3572
+ createDrizzle,
3573
+ schema
3574
+ },
3575
+ options
3576
+ );
3577
+ }
3578
+
3579
+ // src/db/realtime/realtime-client.ts
3580
+ var WS_OPEN = 1;
3581
+ var WS_CLOSED = 3;
3582
+ var JITTER_MIN = 0.5;
3583
+ var JITTER_MAX = 1.5;
3584
+ var DEFAULT_BACKOFF_BASE_MS = 1e3;
3585
+ var DEFAULT_BACKOFF_MAX_MS = 3e4;
3586
+ var DEFAULT_HEARTBEAT_INTERVAL_MS = 25e3;
3587
+ var _idCounter = 0;
3588
+ function generateId() {
3589
+ if (typeof globalThis.crypto?.randomUUID === "function") {
3590
+ return globalThis.crypto.randomUUID();
3591
+ }
3592
+ return `nrt-sub-${Date.now()}-${++_idCounter}-${Math.random().toString(36).slice(2)}`;
3593
+ }
3594
+ var NeetruRealtimeClient = class {
3595
+ // ── configuração ──────────────────────────────────────────────────────────
3596
+ _gatewayUrl;
3597
+ _wsFactory;
3598
+ _setTimeout;
3599
+ _clearTimeout;
3600
+ _backoffBaseMs;
3601
+ _backoffMaxMs;
3602
+ _heartbeatIntervalMs;
3603
+ _ticketProvider;
3604
+ /** ID do banco lógico (BL-8) — embutido em query.filter._dbId de cada subscribe. */
3605
+ _dbId;
3606
+ /** Ticket atual — obtido antes de cada abertura de WS e embutido nos frames. */
3607
+ _currentTicket = null;
3608
+ // ── estado interno ────────────────────────────────────────────────────────
3609
+ /** Subscriptions ativas: id → entry */
3610
+ _subscriptions = /* @__PURE__ */ new Map();
3611
+ /** Listeners do estado da conexão. */
3612
+ _stateListeners = [];
3613
+ /** Estado atual da conexão. */
3614
+ _connectionState = "connecting";
3615
+ /** Socket atual (pode ser null entre tentativas). */
3616
+ _ws = null;
3617
+ /** Número da tentativa de reconexão corrente (reseta após conexão bem-sucedida). */
3618
+ _reconnectAttempt = 0;
3619
+ /** Handle do timer de backoff pendente. */
3620
+ _reconnectTimer = null;
3621
+ /** Handle do timer de heartbeat. */
3622
+ _heartbeatTimer = null;
3623
+ /** Indica que o cliente foi encerrado via `close()`. Não reconecta mais. */
3624
+ _closed = false;
3625
+ /**
3626
+ * Frames de subscribe que precisam ser enviados mas a socket ainda não
3627
+ * está aberta (estado CONNECTING). Drenados no onopen.
3628
+ */
3629
+ _pendingFrames = [];
3630
+ // ── construtor ────────────────────────────────────────────────────────────
3631
+ constructor(options) {
3632
+ this._gatewayUrl = options.gatewayUrl;
3633
+ this._wsFactory = options.webSocketFactory ?? defaultWebSocketFactory;
3634
+ this._setTimeout = options.setTimeoutFn ?? globalThis.setTimeout.bind(globalThis);
3635
+ this._clearTimeout = options.clearTimeoutFn ?? globalThis.clearTimeout.bind(globalThis);
3636
+ this._backoffBaseMs = options.backoffBaseMs ?? DEFAULT_BACKOFF_BASE_MS;
3637
+ this._backoffMaxMs = options.backoffMaxMs ?? DEFAULT_BACKOFF_MAX_MS;
3638
+ this._heartbeatIntervalMs = options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
3639
+ this._ticketProvider = options.ticketProvider;
3640
+ this._dbId = options.dbId;
3641
+ this._connect();
3642
+ }
3643
+ // ── API pública ───────────────────────────────────────────────────────────
3644
+ /**
3645
+ * Registra uma subscription em `collection` com `query` opcional.
3646
+ *
3647
+ * Envia um frame `subscribe` ao gateway (ou enfileira se o socket ainda
3648
+ * não está aberto). O `callback` é invocado com cada frame `delta`,
3649
+ * `resync`, `stale` ou `error` roteado para esta subscription.
3650
+ *
3651
+ * @returns O `subscriptionId` opaco — usar para cancelar via `unsubscribe()`.
3652
+ */
3653
+ subscribe(collection, query, callback) {
3654
+ if (this._closed) {
3655
+ return generateId();
3656
+ }
3657
+ const subscriptionId = generateId();
3658
+ this._subscriptions.set(subscriptionId, {
3659
+ subscriptionId,
3660
+ collection,
3661
+ query: Object.keys(query).length > 0 ? query : void 0,
3662
+ callback
3663
+ });
3664
+ const frame = {
3665
+ op: "subscribe",
3666
+ subscriptionId,
3667
+ collection,
3668
+ query: this._buildSubscribeQuery(query)
3669
+ };
3670
+ this._sendOrBuffer(frame);
3671
+ return subscriptionId;
3672
+ }
3673
+ /**
3674
+ * Cancela uma subscription.
3675
+ *
3676
+ * Envia um frame `unsubscribe` ao gateway e remove o listener local.
3677
+ * Frames subsequentes com este `subscriptionId` são silenciosamente descartados.
3678
+ */
3679
+ unsubscribe(subscriptionId) {
3680
+ if (!this._subscriptions.has(subscriptionId)) {
3681
+ return;
3682
+ }
3683
+ this._subscriptions.delete(subscriptionId);
3684
+ const frame = { op: "unsubscribe", subscriptionId };
3685
+ this._sendOrBuffer(frame);
3686
+ }
3687
+ /**
3688
+ * Registra um listener de mudanças no estado da conexão.
3689
+ *
3690
+ * O listener é invocado imediatamente com o estado atual e depois a cada
3691
+ * transição. Retorna uma função `unsubscribe`.
3692
+ */
3693
+ onConnectionState(listener) {
3694
+ this._stateListeners.push(listener);
3695
+ listener(this._connectionState);
3696
+ return () => {
3697
+ this._stateListeners = this._stateListeners.filter((l) => l !== listener);
3698
+ };
3699
+ }
3700
+ /**
3701
+ * Encerra o cliente definitivamente.
3702
+ *
3703
+ * Fecha o socket ativo, cancela timers pendentes e marca o cliente como
3704
+ * encerrado (sem mais reconexões).
3705
+ */
3706
+ close() {
3707
+ this._closed = true;
3708
+ this._cancelReconnectTimer();
3709
+ this._cancelHeartbeatTimer();
3710
+ if (this._ws) {
3711
+ this._detachHandlers(this._ws);
3712
+ if (this._ws.readyState !== WS_CLOSED) {
3713
+ this._ws.close(1e3, "client closed");
3714
+ }
3715
+ this._ws = null;
3716
+ }
3717
+ this._setState("disconnected");
3718
+ }
3719
+ // ── Conexão ───────────────────────────────────────────────────────────────
3720
+ /**
3721
+ * Busca um ticket de autenticação e, em seguida, cria um novo WebSocket e
3722
+ * instala os handlers de evento.
3723
+ *
3724
+ * A busca de ticket é obrigatória antes de abrir qualquer WS (primeira
3725
+ * conexão e reconexões). Se a busca falhar, a conexão é abortada com
3726
+ * estado `'connecting'` e o backoff reconectará em seguida.
3727
+ *
3728
+ * Fail-closed: o WebSocket NUNCA é aberto sem um ticket válido.
3729
+ */
3730
+ _connect() {
3731
+ if (this._closed) return;
3732
+ this._setState("connecting");
3733
+ void this._connectWithTicket();
3734
+ }
3735
+ /** Implementação assíncrona de _connect — busca ticket e abre WS. */
3736
+ async _connectWithTicket() {
3737
+ if (this._closed) return;
3738
+ let ticket;
3739
+ try {
3740
+ ticket = await this._ticketProvider();
3741
+ } catch (err) {
3742
+ if (this._closed) return;
3743
+ const delay = this._computeBackoffDelay(this._reconnectAttempt);
3744
+ this._reconnectAttempt++;
3745
+ this._reconnectTimer = this._setTimeout(() => {
3746
+ this._reconnectTimer = null;
3747
+ if (!this._closed) this._connect();
3748
+ }, delay);
3749
+ return;
3750
+ }
3751
+ if (this._closed) return;
3752
+ this._currentTicket = ticket;
3753
+ const ws = this._wsFactory(this._gatewayUrl);
3754
+ this._ws = ws;
3755
+ ws.onopen = this._handleOpen.bind(this);
3756
+ ws.onmessage = this._handleMessage.bind(this);
3757
+ ws.onclose = this._handleClose.bind(this);
3758
+ ws.onerror = this._handleError.bind(this);
3759
+ }
3760
+ // ── Handlers de WebSocket ─────────────────────────────────────────────────
3761
+ _handleOpen(_event) {
3762
+ if (this._closed) return;
3763
+ this._reconnectAttempt = 0;
3764
+ this._setState("connected");
3765
+ for (const frame of this._pendingFrames) {
3766
+ this._sendNow(frame);
3767
+ }
3768
+ this._pendingFrames = [];
3769
+ this._resubscribeAll();
3770
+ this._scheduleHeartbeat();
3771
+ }
3772
+ _handleMessage(event) {
3773
+ if (this._closed) return;
3774
+ let frame;
3775
+ try {
3776
+ frame = JSON.parse(event.data);
3777
+ } catch {
3778
+ return;
3779
+ }
3780
+ switch (frame.op) {
3781
+ case "delta":
3782
+ case "resync":
3783
+ case "stale":
3784
+ case "error":
3785
+ this._routeToSubscription(frame);
3786
+ break;
3787
+ case "pong":
3788
+ break;
3789
+ case "drain":
3790
+ this._handleDrain();
3791
+ break;
3792
+ }
3793
+ }
3794
+ _handleClose(_event) {
3795
+ if (this._closed) return;
3796
+ this._cancelHeartbeatTimer();
3797
+ this._ws = null;
3798
+ this._scheduleReconnect();
3799
+ }
3800
+ _handleError(_event) {
3801
+ if (this._closed) return;
3802
+ this._setState("connecting");
3803
+ }
3804
+ // ── Drain (graceful shutdown do gateway) ─────────────────────────────────
3805
+ _handleDrain() {
3806
+ if (this._closed) return;
3807
+ this._setState("draining");
3808
+ this._cancelHeartbeatTimer();
3809
+ if (this._ws) {
3810
+ this._detachHandlers(this._ws);
3811
+ if (this._ws.readyState !== WS_CLOSED) {
3812
+ this._ws.close(1001, "drain");
3813
+ }
3814
+ this._ws = null;
3815
+ }
3816
+ this._scheduleReconnect();
3817
+ }
3818
+ // ── Roteamento de frames ──────────────────────────────────────────────────
3819
+ _routeToSubscription(frame) {
3820
+ const entry = this._subscriptions.get(frame.subscriptionId);
3821
+ if (!entry) {
3822
+ return;
3823
+ }
3824
+ try {
3825
+ entry.callback(frame);
3826
+ } catch {
3827
+ }
3828
+ }
3829
+ // ── Resubscrição ──────────────────────────────────────────────────────────
3830
+ /**
3831
+ * Reenvía frames `subscribe` para todas as subscriptions ativas.
3832
+ * Chamado no `onopen` de reconexões para restaurar o estado remoto.
3833
+ *
3834
+ * Durante a PRIMEIRA conexão: _pendingFrames já foi drenado com os
3835
+ * subscribes iniciais acima. ResubscribeAll envia novamente — como a
3836
+ * lista de subscriptions foi populada pelos `subscribe()` calls anteriores
3837
+ * ao open, e os frames drenados também os incluem, teríamos duplicatas.
3838
+ *
3839
+ * Solução: resubscribeAll só é invocado após drenar _pendingFrames, e
3840
+ * como o gateway é idempotente para o mesmo subscriptionId (segundo o
3841
+ * design do componente #19), a duplicata é inócua. Em reconexões, onde
3842
+ * _pendingFrames está vazio, os frames são os únicos enviados.
3843
+ *
3844
+ * Para o caso do primeiro open com subscribes anteriores ao open, os
3845
+ * frames já foram drenados de _pendingFrames — não chamamos resubscribeAll
3846
+ * se era a primeira conexão (_reconnectAttempt era 0 antes de resetar).
3847
+ * Rastreamos isso com _hasConnectedOnce.
3848
+ */
3849
+ _hasConnectedOnce = false;
3850
+ _resubscribeAll() {
3851
+ if (!this._hasConnectedOnce) {
3852
+ this._hasConnectedOnce = true;
3853
+ return;
3854
+ }
3855
+ for (const entry of this._subscriptions.values()) {
3856
+ const frame = {
3857
+ op: "subscribe",
3858
+ subscriptionId: entry.subscriptionId,
3859
+ collection: entry.collection,
3860
+ query: this._buildSubscribeQuery(entry.query ?? {})
3861
+ };
3862
+ this._sendNow(frame);
3863
+ }
3864
+ }
3865
+ // ── Ticket embedding ──────────────────────────────────────────────────────
3866
+ /**
3867
+ * Constrói o descriptor `query` para um frame `subscribe`, embutindo o
3868
+ * `token` do ticket corrente em `query.filter._ticket` e o `_dbId` do
3869
+ * banco lógico em `query.filter._dbId` (BL-8 fix).
3870
+ *
3871
+ * O gateway extrai `filter._ticket` do primeiro frame `subscribe` e valida
3872
+ * contra `POST /api/sdk/v1/db/realtime/validate`. `filter._dbId` é exigido
3873
+ * pelo `@neetru/realtime-changestream._extractDbId` para rotear a
3874
+ * subscription ao banco correto — sem ele a subscription é rejeitada.
3875
+ *
3876
+ * Retorna `undefined` se a query seria vazia E não há ticket (estado
3877
+ * transitório antes do primeiro ticket — não deve ocorrer normalmente pois
3878
+ * `_connect` só abre o WS após obter o ticket).
3879
+ */
3880
+ _buildSubscribeQuery(query) {
3881
+ const ticket = this._currentTicket;
3882
+ const hasUserQuery = Object.keys(query).length > 0;
3883
+ if (!ticket) {
3884
+ return hasUserQuery ? query : void 0;
3885
+ }
3886
+ const mergedFilter = {
3887
+ ...query.filter ?? {},
3888
+ _ticket: ticket.token
3889
+ };
3890
+ if (this._dbId !== void 0) {
3891
+ mergedFilter["_dbId"] = this._dbId;
3892
+ }
3893
+ return {
3894
+ ...query,
3895
+ filter: mergedFilter
3896
+ };
3897
+ }
3898
+ // ── Backoff e reconexão ───────────────────────────────────────────────────
3899
+ /** Agenda uma tentativa de reconexão com backoff exponencial + jitter. */
3900
+ _scheduleReconnect() {
3901
+ if (this._closed) return;
3902
+ this._cancelReconnectTimer();
3903
+ this._setState("connecting");
3904
+ this._currentTicket = null;
3905
+ const delayMs = this._computeBackoffDelay(this._reconnectAttempt);
3906
+ this._reconnectAttempt++;
3907
+ this._reconnectTimer = this._setTimeout(() => {
3908
+ this._reconnectTimer = null;
3909
+ if (!this._closed) {
3910
+ this._connect();
3911
+ }
3912
+ }, delayMs);
3913
+ }
3914
+ /**
3915
+ * Calcula o delay de backoff para o attempt N.
3916
+ *
3917
+ * Fórmula: `min(baseMs * 2^N, maxMs) * jitter`
3918
+ * onde `jitter ∈ [JITTER_MIN, JITTER_MAX]` (±50%).
3919
+ */
3920
+ _computeBackoffDelay(attempt) {
3921
+ const exponential = this._backoffBaseMs * Math.pow(2, attempt);
3922
+ const capped = Math.min(exponential, this._backoffMaxMs);
3923
+ const jitter = JITTER_MIN + Math.random() * (JITTER_MAX - JITTER_MIN);
3924
+ return Math.round(capped * jitter);
3925
+ }
3926
+ _cancelReconnectTimer() {
3927
+ if (this._reconnectTimer !== null) {
3928
+ this._clearTimeout(this._reconnectTimer);
3929
+ this._reconnectTimer = null;
3930
+ }
3931
+ }
3932
+ // ── Heartbeat ─────────────────────────────────────────────────────────────
3933
+ /** Agenda o próximo ping. Não-operacional se heartbeatIntervalMs === 0. */
3934
+ _scheduleHeartbeat() {
3935
+ if (this._heartbeatIntervalMs === 0) return;
3936
+ this._cancelHeartbeatTimer();
3937
+ this._heartbeatTimer = this._setTimeout(() => {
3938
+ this._heartbeatTimer = null;
3939
+ this._sendPing();
3940
+ this._scheduleHeartbeat();
3941
+ }, this._heartbeatIntervalMs);
3942
+ }
3943
+ _cancelHeartbeatTimer() {
3944
+ if (this._heartbeatTimer !== null) {
3945
+ this._clearTimeout(this._heartbeatTimer);
3946
+ this._heartbeatTimer = null;
3947
+ }
3948
+ }
3949
+ _sendPing() {
3950
+ const frame = { op: "ping", subscriptionId: "" };
3951
+ this._sendOrBuffer(frame);
3952
+ }
3953
+ // ── Envio de frames ───────────────────────────────────────────────────────
3954
+ /**
3955
+ * Envia o frame imediatamente se o socket está aberto; caso contrário,
3956
+ * enfileira em `_pendingFrames` para envio no próximo `onopen`.
3957
+ */
3958
+ _sendOrBuffer(frame) {
3959
+ if (this._ws !== null && this._ws.readyState === WS_OPEN) {
3960
+ this._sendNow(frame);
3961
+ } else {
3962
+ if (frame.op !== "unsubscribe") {
3963
+ this._pendingFrames.push(frame);
3964
+ }
3965
+ }
3966
+ }
3967
+ /** Serializa e envia o frame imediatamente via WebSocket. */
3968
+ _sendNow(frame) {
3969
+ if (!this._ws || this._ws.readyState !== WS_OPEN) return;
3970
+ try {
3971
+ this._ws.send(JSON.stringify(frame));
3972
+ } catch {
3973
+ }
3974
+ }
3975
+ // ── Estado da conexão ─────────────────────────────────────────────────────
3976
+ _setState(state) {
3977
+ if (this._connectionState === state) return;
3978
+ this._connectionState = state;
3979
+ for (const listener of this._stateListeners) {
3980
+ try {
3981
+ listener(state);
3982
+ } catch {
3983
+ }
3984
+ }
3985
+ }
3986
+ // ── Desvinculação de handlers ─────────────────────────────────────────────
3987
+ /** Remove todos os handlers de um WebSocket (evita disparo após close()). */
3988
+ _detachHandlers(ws) {
3989
+ ws.onopen = null;
3990
+ ws.onmessage = null;
3991
+ ws.onclose = null;
3992
+ ws.onerror = null;
3993
+ }
3994
+ };
3995
+ var defaultWebSocketFactory = (url) => {
3996
+ if (typeof WebSocket === "undefined") {
3997
+ throw new Error(
3998
+ "[NeetruRealtimeClient] WebSocket n\xE3o dispon\xEDvel neste ambiente. Injete uma implementa\xE7\xE3o via `webSocketFactory` nas op\xE7\xF5es."
3999
+ );
4000
+ }
4001
+ return new WebSocket(url);
4002
+ };
4003
+
4004
+ // src/db/client-db.ts
4005
+ var DATASTORE_COLLECTION_ENDPOINT = (collection) => `/api/sdk/v1/datastore/${encodeURIComponent(collection)}`;
4006
+ var DATASTORE_DOC_ENDPOINT = (collection, docId) => `/api/sdk/v1/datastore/${encodeURIComponent(collection)}/${encodeURIComponent(docId)}`;
4007
+ function resolveTransport(engine, opts, config) {
4008
+ if (opts._transport) {
4009
+ return opts._transport;
4010
+ }
4011
+ if (engine === "firestore") {
4012
+ if (opts.firestoreTransport) {
4013
+ return opts.firestoreTransport;
4014
+ }
4015
+ }
4016
+ if (engine === "nosql-vm" && opts.realtimeGatewayUrl) {
4017
+ return createWebSocketSyncTransport(opts.realtimeGatewayUrl, config, opts);
4018
+ }
4019
+ return createRestSyncTransport(config);
4020
+ }
4021
+ function createRestSyncTransport(config) {
4022
+ return {
4023
+ async pushMutations(mutations) {
4024
+ if (!config) {
4025
+ throw new NeetruDbError(
4026
+ "db_unavailable",
4027
+ "[RestSyncTransport] config n\xE3o dispon\xEDvel \u2014 n\xE3o \xE9 poss\xEDvel enviar ao Core. Inicialize o transporte via createNeetruDb."
4028
+ );
4029
+ }
4030
+ const { httpRequest: httpRequest2 } = await Promise.resolve().then(() => (init_http(), http_exports));
4031
+ const results = [];
4032
+ const tenantScopeId = config.tenantId ?? config.productId;
4033
+ const tenantHeaders = tenantScopeId ? { "x-neetru-tenant": tenantScopeId } : void 0;
4034
+ for (const m of mutations) {
4035
+ try {
4036
+ let raw;
4037
+ if (m.op === "add") {
4038
+ raw = await httpRequest2(config, {
4039
+ method: "POST",
4040
+ path: DATASTORE_COLLECTION_ENDPOINT(m.collection),
4041
+ body: { data: m.payload ?? {} },
4042
+ requireAuth: true,
4043
+ retries: 0,
4044
+ headers: tenantHeaders
4045
+ });
4046
+ } else if (m.op === "set") {
4047
+ raw = await httpRequest2(config, {
4048
+ method: "PUT",
4049
+ path: DATASTORE_DOC_ENDPOINT(m.collection, m.docId),
4050
+ body: { data: m.payload ?? {} },
4051
+ requireAuth: true,
4052
+ retries: 2,
4053
+ headers: tenantHeaders
4054
+ });
4055
+ } else if (m.op === "update") {
4056
+ raw = await httpRequest2(config, {
4057
+ method: "PATCH",
4058
+ path: DATASTORE_DOC_ENDPOINT(m.collection, m.docId),
4059
+ body: { data: m.payload ?? {} },
4060
+ requireAuth: true,
4061
+ retries: 2,
4062
+ headers: tenantHeaders
4063
+ });
4064
+ } else {
4065
+ raw = await httpRequest2(config, {
4066
+ method: "DELETE",
4067
+ path: DATASTORE_DOC_ENDPOINT(m.collection, m.docId),
4068
+ requireAuth: true,
4069
+ retries: 2,
4070
+ headers: tenantHeaders
4071
+ });
4072
+ }
4073
+ const resp = raw;
4074
+ results.push({
4075
+ mutationId: m.mutationId,
4076
+ outcome: "confirmed",
4077
+ serverVersion: resp?.serverVersion ?? resp?.id ?? `rest_${Date.now()}`,
4078
+ serverTimestamp: Date.now()
4079
+ });
4080
+ } catch (err) {
4081
+ const msg = err instanceof Error ? err.message : String(err);
4082
+ throw new NeetruDbError("db_unavailable", `pushMutations falhou: ${msg}`);
4083
+ }
584
4084
  }
585
- return {
586
- ok: true,
587
- counterId: raw.counterId,
588
- value: raw.value,
589
- limit: raw.limit,
590
- remaining: raw.remaining,
591
- status: raw.status
592
- };
4085
+ return { results };
593
4086
  },
594
- /**
595
- * v0.3 — Verifica entitlement de um resource via GET /sdk/v1/entitlements.
596
- */
597
- async check(resource, options) {
598
- if (!resource || typeof resource !== "string") {
599
- throw new NeetruError("validation_failed", "resource is required");
4087
+ async pullChanges(_watermark, _resumeToken) {
4088
+ if (!config) {
4089
+ return { docs: [], newWatermark: Date.now(), resyncRequired: false };
600
4090
  }
601
- const productId = options?.productId ?? config.productId;
602
- const tenantId = options?.tenantId ?? config.tenantId;
603
- if (!productId || !tenantId) {
604
- throw new NeetruError(
605
- "validation_failed",
606
- "productId and tenantId required"
607
- );
4091
+ return { docs: [], newWatermark: Date.now(), resyncRequired: false };
4092
+ },
4093
+ async fullResync(_collections) {
4094
+ if (!config) {
4095
+ return { docs: [], newWatermark: Date.now() };
608
4096
  }
609
- const raw = await httpRequest(config, {
610
- method: "GET",
611
- path: "/sdk/v1/entitlements",
612
- query: { productId, tenantId, feature: resource },
613
- requireAuth: true
4097
+ return { docs: [], newWatermark: Date.now() };
4098
+ }
4099
+ };
4100
+ }
4101
+ function createWebSocketSyncTransport(gatewayUrl, config, opts) {
4102
+ const restTransport = createRestSyncTransport(config);
4103
+ const realtimeClient = new NeetruRealtimeClient({
4104
+ gatewayUrl,
4105
+ ticketProvider: buildTicketProvider(config, opts),
4106
+ dbId: opts.dbId,
4107
+ webSocketFactory: opts._wsFactory
4108
+ });
4109
+ return {
4110
+ pushMutations: restTransport.pushMutations.bind(restTransport),
4111
+ pullChanges: restTransport.pullChanges.bind(restTransport),
4112
+ fullResync: restTransport.fullResync.bind(restTransport),
4113
+ // HIGH-1: subscribeCollection — chamado por DbCollectionRefImpl.onSnapshot
4114
+ // quando o engine é nosql-vm. Registra a subscription no NeetruRealtimeClient
4115
+ // e traduz os frames inbound para o contrato de `onChange`.
4116
+ subscribeCollection(collection, onChange) {
4117
+ const subId = realtimeClient.subscribe(collection, {}, (frame) => {
4118
+ if (frame.op === "resync") {
4119
+ onChange([], true);
4120
+ return;
4121
+ }
4122
+ if (frame.op === "stale") {
4123
+ onChange([], true);
4124
+ return;
4125
+ }
4126
+ if (frame.op === "delta" && frame.changes) {
4127
+ const changes = frame.changes.map((c) => ({
4128
+ type: c.type === "insert" ? "added" : c.type === "delete" ? "removed" : "modified",
4129
+ docId: c.documentId,
4130
+ data: c.data ?? null
4131
+ }));
4132
+ if (changes.length > 0) {
4133
+ onChange(changes, false);
4134
+ }
4135
+ }
614
4136
  });
615
- if (!raw || typeof raw.allowed !== "boolean") {
616
- throw new NeetruError("invalid_response", "usage.check response missing allowed");
617
- }
618
- return {
619
- allowed: raw.allowed,
620
- reason: raw.reason,
621
- remaining: raw.remaining,
622
- limit: raw.limit,
623
- planId: raw.planId,
624
- planFeatures: raw.planFeatures
4137
+ return () => {
4138
+ realtimeClient.unsubscribe(subId);
625
4139
  };
626
4140
  }
627
4141
  };
628
4142
  }
629
-
630
- // src/support.ts
631
- var VALID_SEVERITIES = ["low", "normal", "high", "urgent"];
632
- var VALID_STATUSES = ["open", "pending", "resolved", "closed"];
633
- function toTicket(raw) {
634
- if (!raw || typeof raw !== "object") {
635
- throw new NeetruError("invalid_response", "Ticket response is not an object");
636
- }
637
- const r = raw;
638
- if (typeof r.id !== "string") {
639
- throw new NeetruError("invalid_response", "Ticket missing id");
640
- }
641
- return {
642
- id: r.id,
643
- subject: typeof r.subject === "string" ? r.subject : "",
644
- message: typeof r.message === "string" ? r.message : "",
645
- severity: VALID_SEVERITIES.includes(r.severity) ? r.severity : "normal",
646
- status: VALID_STATUSES.includes(r.status) ? r.status : "open",
647
- createdAt: typeof r.createdAt === "string" ? r.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
648
- updatedAt: typeof r.updatedAt === "string" ? r.updatedAt : void 0,
649
- productSlug: typeof r.productSlug === "string" ? r.productSlug : void 0
4143
+ function buildTicketProvider(config, opts) {
4144
+ return async () => {
4145
+ const { httpRequest: httpRequest2 } = await Promise.resolve().then(() => (init_http(), http_exports));
4146
+ const ticket = await httpRequest2(config, {
4147
+ method: "POST",
4148
+ path: "/api/sdk/v1/db/realtime/ticket",
4149
+ body: {
4150
+ productId: config.productId ?? "",
4151
+ collections: opts.collections ?? ["*"]
4152
+ },
4153
+ requireAuth: true,
4154
+ retries: 1
4155
+ });
4156
+ return ticket;
650
4157
  };
651
4158
  }
652
- function createSupportNamespace(config) {
4159
+ function createNeetruDb(config, dbOpts = {}) {
4160
+ const engine = dbOpts.engine ?? "rest";
4161
+ const transport = resolveTransport(engine, dbOpts, config);
4162
+ const dbId = dbOpts.dbId ?? "default";
4163
+ const dbName = dbOpts.dbName ?? `neetru-db__${config.productId ?? "sdk"}__${dbId}__${config.env}`;
4164
+ let _docsPromise = null;
4165
+ let _docsResolved = null;
4166
+ function getDocsPromise() {
4167
+ if (!_docsPromise) {
4168
+ _docsPromise = createOfflineDocumentsNamespace({
4169
+ dbName,
4170
+ transport,
4171
+ singleTab: dbOpts.singleTab ?? config.env !== "prod"
4172
+ }).then((docs) => {
4173
+ _docsResolved = docs;
4174
+ return docs;
4175
+ });
4176
+ }
4177
+ return _docsPromise;
4178
+ }
653
4179
  return {
654
- /**
655
- * Cria um ticket de suporte. Requer Bearer auth. Se `productSlug` não é
656
- * passado, o backend infere do escopo do token.
657
- */
658
- async createTicket(input) {
659
- if (!input || typeof input !== "object") {
660
- throw new NeetruError("validation_failed", "input is required");
661
- }
662
- if (!input.subject || typeof input.subject !== "string") {
663
- throw new NeetruError("validation_failed", "subject is required");
664
- }
665
- if (input.subject.length > 200) {
666
- throw new NeetruError("validation_failed", "subject max 200 chars");
667
- }
668
- if (!input.message || typeof input.message !== "string") {
669
- throw new NeetruError("validation_failed", "message is required");
670
- }
671
- if (input.message.length > 1e4) {
672
- throw new NeetruError("validation_failed", "message max 10000 chars");
673
- }
674
- if (input.severity && !VALID_SEVERITIES.includes(input.severity)) {
675
- throw new NeetruError("validation_failed", `severity must be one of ${VALID_SEVERITIES.join(", ")}`);
4180
+ collection(name) {
4181
+ if (_docsResolved) return _docsResolved.collection(name);
4182
+ return createLazyCollectionRef(name, getDocsPromise);
4183
+ },
4184
+ async sql(schema, options) {
4185
+ if (config.env === "dev") {
4186
+ throw new NeetruDbError(
4187
+ "db_unavailable",
4188
+ "[SDK] db.sql() n\xE3o dispon\xEDvel em NEETRU_ENV=dev. Use `neetru dev` para subir o container Postgres local."
4189
+ );
676
4190
  }
677
- const slug = input.productSlug ?? "_default";
678
- const body = {
679
- subject: input.subject,
680
- message: input.message,
681
- severity: input.severity ?? "normal"
4191
+ return createSqlClientFromConfig(config, schema, options);
4192
+ },
4193
+ get syncState() {
4194
+ return _docsResolved?.syncState ?? {
4195
+ status: "idle",
4196
+ pendingWrites: 0,
4197
+ lastSyncedAt: null,
4198
+ isLeaderTab: false
682
4199
  };
683
- const raw = await httpRequest(config, {
684
- method: "POST",
685
- path: `/api/v1/products/${encodeURIComponent(slug)}/tickets`,
686
- body,
687
- requireAuth: true
688
- });
689
- const candidate = raw && typeof raw === "object" && "ticket" in raw ? raw.ticket : raw;
690
- return toTicket(candidate);
691
4200
  },
692
- /**
693
- * Lista tickets do customer no produto atual (escopo do token).
694
- */
695
- async listMyTickets() {
696
- const raw = await httpRequest(config, {
697
- method: "GET",
698
- path: "/api/v1/products/_default/tickets",
699
- requireAuth: true
4201
+ onSyncStateChanged(cb) {
4202
+ if (_docsResolved) return _docsResolved.onSyncStateChanged(cb);
4203
+ let unsub = null;
4204
+ let cancelled = false;
4205
+ getDocsPromise().then((docs) => {
4206
+ if (!cancelled) {
4207
+ unsub = docs.onSyncStateChanged(cb);
4208
+ }
700
4209
  });
701
- const list = Array.isArray(raw) ? raw : raw && typeof raw === "object" && "tickets" in raw ? raw.tickets ?? [] : [];
702
- return list.map(toTicket);
4210
+ return () => {
4211
+ cancelled = true;
4212
+ unsub?.();
4213
+ };
4214
+ },
4215
+ async flush() {
4216
+ const docs = await getDocsPromise();
4217
+ return docs.flush();
4218
+ },
4219
+ async clearCache() {
4220
+ const docs = await getDocsPromise();
4221
+ return docs.clearCache();
4222
+ },
4223
+ async getConflicts() {
4224
+ const docs = await getDocsPromise();
4225
+ return docs.getConflicts();
703
4226
  }
704
4227
  };
705
4228
  }
706
-
707
- // src/db.ts
708
- var COLL_RE = /^[a-z0-9][a-z0-9_-]{0,62}$/;
709
- function assertValidCollection(name) {
710
- if (!COLL_RE.test(name)) {
711
- throw new NeetruError(
712
- "validation_failed",
713
- `Invalid collection name: "${name}". Must match ${COLL_RE}.`
714
- );
715
- }
716
- }
717
- function serializeWhere(filter) {
718
- const { field, op, value } = filter;
719
- if (op === "in") {
720
- if (!Array.isArray(value)) {
721
- throw new NeetruError(
722
- "validation_failed",
723
- `where op="in" requer value array (recebido: ${typeof value})`
724
- );
725
- }
726
- return `${field}:in:${value.map((v) => String(v)).join(",")}`;
4229
+ function createLazyCollectionRef(name, getDocsPromise) {
4230
+ async function getRef() {
4231
+ const docs = await getDocsPromise();
4232
+ return docs.collection(name);
727
4233
  }
728
- return `${field}:${op}:${String(value)}`;
729
- }
730
- function createDbNamespace(config) {
731
4234
  return {
732
- collection(name) {
733
- assertValidCollection(name);
734
- const headers = {};
735
- if (config.tenantId) headers["x-neetru-tenant"] = config.tenantId;
4235
+ async get(id) {
4236
+ return (await getRef()).get(id);
4237
+ },
4238
+ async list(q) {
4239
+ return (await getRef()).list(q);
4240
+ },
4241
+ async add(data) {
4242
+ return (await getRef()).add(data);
4243
+ },
4244
+ async set(id, data) {
4245
+ return (await getRef()).set(id, data);
4246
+ },
4247
+ async update(id, data) {
4248
+ return (await getRef()).update(id, data);
4249
+ },
4250
+ async remove(id) {
4251
+ return (await getRef()).remove(id);
4252
+ },
4253
+ async batch(ops) {
4254
+ return (await getRef()).batch(ops);
4255
+ },
4256
+ onDoc(id, cb) {
4257
+ let unsub = null;
4258
+ let cancelled = false;
4259
+ getRef().then((ref) => {
4260
+ if (!cancelled) {
4261
+ unsub = ref.onDoc(id, cb);
4262
+ }
4263
+ });
4264
+ return () => {
4265
+ cancelled = true;
4266
+ unsub?.();
4267
+ };
4268
+ },
4269
+ onSnapshot(q, cb) {
4270
+ let unsub = null;
4271
+ let cancelled = false;
4272
+ getRef().then((ref) => {
4273
+ if (!cancelled) {
4274
+ unsub = ref.onSnapshot(q, cb);
4275
+ }
4276
+ });
4277
+ return () => {
4278
+ cancelled = true;
4279
+ unsub?.();
4280
+ };
4281
+ },
4282
+ doc(id) {
736
4283
  return {
737
- async list(opts) {
738
- let path = `/api/sdk/v1/datastore/${name}`;
739
- const params = new URLSearchParams();
740
- if (opts?.limit !== void 0) params.set("limit", String(opts.limit));
741
- if (opts?.where && opts.where.length > 0) {
742
- for (const f of opts.where) {
743
- params.append("where", serializeWhere(f));
744
- }
745
- }
746
- if (config.tenantId) params.set("tenantId", config.tenantId);
747
- const qs = params.toString();
748
- if (qs) path += `?${qs}`;
749
- const raw = await httpRequest(config, {
750
- method: "GET",
751
- path,
752
- requireAuth: true,
753
- headers
754
- });
755
- if (!raw || !Array.isArray(raw.items)) {
756
- throw new NeetruError(
757
- "invalid_response",
758
- "datastore.list missing items[]"
759
- );
760
- }
761
- return raw.items;
762
- },
763
- async get(id) {
764
- if (!id || typeof id !== "string") {
765
- throw new NeetruError("validation_failed", "id required");
766
- }
767
- try {
768
- const raw = await httpRequest(config, {
769
- method: "GET",
770
- path: `/api/sdk/v1/datastore/${name}/${encodeURIComponent(id)}`,
771
- requireAuth: true,
772
- headers
773
- });
774
- return raw?.item ?? null;
775
- } catch (err) {
776
- if (err instanceof NeetruError && err.code === "not_found") return null;
777
- throw err;
778
- }
4284
+ async get() {
4285
+ return (await getRef()).doc(id).get();
779
4286
  },
780
- async add(data) {
781
- if (!data || typeof data !== "object") {
782
- throw new NeetruError("validation_failed", "data object required");
783
- }
784
- const raw = await httpRequest(config, {
785
- method: "POST",
786
- path: `/api/sdk/v1/datastore/${name}`,
787
- body: { data },
788
- requireAuth: true,
789
- headers
790
- });
791
- if (!raw || typeof raw.id !== "string") {
792
- throw new NeetruError("invalid_response", "datastore.add missing id");
793
- }
794
- return { ok: true, id: raw.id };
4287
+ async set(data) {
4288
+ return (await getRef()).doc(id).set(data);
795
4289
  },
796
- async set(id, data) {
797
- if (!id || typeof id !== "string") {
798
- throw new NeetruError("validation_failed", "id required");
799
- }
800
- await httpRequest(config, {
801
- method: "PUT",
802
- path: `/api/sdk/v1/datastore/${name}/${encodeURIComponent(id)}`,
803
- body: { data },
804
- requireAuth: true,
805
- headers
806
- });
807
- return { ok: true };
4290
+ async update(data) {
4291
+ return (await getRef()).doc(id).update(data);
808
4292
  },
809
- async update(id, data) {
810
- if (!id || typeof id !== "string") {
811
- throw new NeetruError("validation_failed", "id required");
812
- }
813
- await httpRequest(config, {
814
- method: "PATCH",
815
- path: `/api/sdk/v1/datastore/${name}/${encodeURIComponent(id)}`,
816
- body: { data },
817
- requireAuth: true,
818
- headers
819
- });
820
- return { ok: true };
4293
+ async remove() {
4294
+ return (await getRef()).doc(id).remove();
821
4295
  },
822
- async remove(id) {
823
- if (!id || typeof id !== "string") {
824
- throw new NeetruError("validation_failed", "id required");
825
- }
826
- await httpRequest(config, {
827
- method: "DELETE",
828
- path: `/api/sdk/v1/datastore/${name}/${encodeURIComponent(id)}`,
829
- requireAuth: true,
830
- headers
4296
+ onSnapshot(cb) {
4297
+ let unsub = null;
4298
+ let cancelled = false;
4299
+ getRef().then((ref) => {
4300
+ if (!cancelled) {
4301
+ unsub = ref.doc(id).onSnapshot(cb);
4302
+ }
831
4303
  });
832
- return { ok: true };
4304
+ return () => {
4305
+ cancelled = true;
4306
+ unsub?.();
4307
+ };
833
4308
  }
834
4309
  };
835
4310
  }
@@ -837,6 +4312,8 @@ function createDbNamespace(config) {
837
4312
  }
838
4313
 
839
4314
  // src/checkout.ts
4315
+ init_errors();
4316
+ init_http();
840
4317
  function parseStartResponse(raw) {
841
4318
  if (!raw || typeof raw !== "object") {
842
4319
  throw new NeetruError("invalid_response", "checkout.start response is not an object");
@@ -1012,6 +4489,8 @@ function createCheckoutNamespace(config) {
1012
4489
  }
1013
4490
 
1014
4491
  // src/webhooks.ts
4492
+ init_errors();
4493
+ init_http();
1015
4494
  var VALID_EVENTS = [
1016
4495
  "subscription.activated",
1017
4496
  "subscription.cancelled",
@@ -1153,6 +4632,8 @@ var MockWebhooks = class {
1153
4632
  };
1154
4633
 
1155
4634
  // src/notifications.ts
4635
+ init_errors();
4636
+ init_http();
1156
4637
  var VALID_SEVERITIES2 = [
1157
4638
  "info",
1158
4639
  "success",
@@ -1521,24 +5002,61 @@ var MockDb = class {
1521
5002
  return typeof v === "number" && typeof f.value === "number" && v >= f.value;
1522
5003
  case "in":
1523
5004
  return Array.isArray(f.value) && f.value.includes(v);
5005
+ case "array-contains":
5006
+ return Array.isArray(v) && v.includes(f.value);
5007
+ case "not-in":
5008
+ return Array.isArray(f.value) && !f.value.includes(v);
1524
5009
  default:
1525
5010
  return true;
1526
5011
  }
1527
5012
  };
1528
5013
  let autoSeq = 0;
1529
- return {
1530
- async list(opts) {
5014
+ function buildListResult(items) {
5015
+ return {
5016
+ docs: items.map((d, i) => ({ id: d.id ?? String(i), data: d })),
5017
+ nextCursor: null,
5018
+ fromCache: false,
5019
+ stale: false,
5020
+ hasPendingWrites: false,
5021
+ changes: []
5022
+ };
5023
+ }
5024
+ function buildGetResult(data, id) {
5025
+ return {
5026
+ docs: [{ id, data }],
5027
+ fromCache: false,
5028
+ stale: false,
5029
+ hasPendingWrites: false,
5030
+ changes: []
5031
+ };
5032
+ }
5033
+ const ref = {
5034
+ async list(q) {
1531
5035
  let items = Array.from(coll.values());
1532
- if (opts?.where && opts.where.length > 0) {
5036
+ if (q?.where && q.where.length > 0) {
1533
5037
  items = items.filter(
1534
- (doc) => opts.where.every((f) => matchesFilter(doc, f))
5038
+ (doc) => q.where.every((f) => matchesFilter(doc, f))
1535
5039
  );
1536
5040
  }
1537
- if (opts?.limit !== void 0) items = items.slice(0, opts.limit);
1538
- return items;
5041
+ if (q?.orderBy) {
5042
+ const { field, direction } = q.orderBy;
5043
+ items = items.slice().sort((a, b) => {
5044
+ const av = a[field];
5045
+ const bv = b[field];
5046
+ const avs = av ?? "";
5047
+ const bvs = bv ?? "";
5048
+ const cmp = avs < bvs ? -1 : avs > bvs ? 1 : 0;
5049
+ return direction === "desc" ? -cmp : cmp;
5050
+ });
5051
+ }
5052
+ const limit = q?.limit ?? 20;
5053
+ items = items.slice(0, limit);
5054
+ return buildListResult(items);
1539
5055
  },
1540
5056
  async get(id) {
1541
- return coll.get(id) ?? null;
5057
+ const data = coll.get(id);
5058
+ if (!data) return null;
5059
+ return buildGetResult(data, id);
1542
5060
  },
1543
5061
  async add(data) {
1544
5062
  const id = `mock-${++autoSeq}-${Math.random().toString(36).slice(2, 8)}`;
@@ -1561,8 +5079,103 @@ var MockDb = class {
1561
5079
  async remove(id) {
1562
5080
  coll.delete(id);
1563
5081
  return { ok: true };
5082
+ },
5083
+ async batch(ops) {
5084
+ for (const op of ops) {
5085
+ const collMap = (() => {
5086
+ if (!_store.has(op.collection)) _store.set(op.collection, /* @__PURE__ */ new Map());
5087
+ return _store.get(op.collection);
5088
+ })();
5089
+ const id = op.id ?? `mock-batch-${++autoSeq}`;
5090
+ if (op.op === "add") {
5091
+ collMap.set(id, { ...op.data ?? {}, id });
5092
+ } else if (op.op === "set") {
5093
+ collMap.set(id, { ...op.data ?? {}, id });
5094
+ } else if (op.op === "update") {
5095
+ const cur = collMap.get(id);
5096
+ collMap.set(id, { ...cur ?? {}, ...op.data ?? {}, id });
5097
+ } else if (op.op === "remove") {
5098
+ collMap.delete(id);
5099
+ }
5100
+ }
5101
+ return { ok: true };
5102
+ },
5103
+ onDoc(id, cb) {
5104
+ const data = coll.get(id);
5105
+ Promise.resolve().then(() => cb(data ? data : null));
5106
+ return () => {
5107
+ };
5108
+ },
5109
+ onSnapshot(q, cb) {
5110
+ Promise.resolve().then(async () => {
5111
+ const snap = await ref.list(q);
5112
+ cb(snap);
5113
+ });
5114
+ return () => {
5115
+ };
5116
+ },
5117
+ doc(id) {
5118
+ return {
5119
+ async get() {
5120
+ const data = coll.get(id);
5121
+ if (!data) return null;
5122
+ return buildGetResult(data, id);
5123
+ },
5124
+ async set(data) {
5125
+ coll.set(id, { ...data, id });
5126
+ return { ok: true };
5127
+ },
5128
+ async update(data) {
5129
+ const cur = coll.get(id);
5130
+ if (!cur) {
5131
+ coll.set(id, { ...data, id });
5132
+ } else {
5133
+ coll.set(id, { ...cur, ...data });
5134
+ }
5135
+ return { ok: true };
5136
+ },
5137
+ async remove() {
5138
+ coll.delete(id);
5139
+ return { ok: true };
5140
+ },
5141
+ onSnapshot(cb) {
5142
+ const data = coll.get(id);
5143
+ Promise.resolve().then(
5144
+ () => cb(data ? buildGetResult(data, id) : null)
5145
+ );
5146
+ return () => {
5147
+ };
5148
+ }
5149
+ };
1564
5150
  }
1565
5151
  };
5152
+ return ref;
5153
+ }
5154
+ async sql(_schema) {
5155
+ throw new NeetruDbError(
5156
+ "db_unavailable",
5157
+ '[MockDb] sql() n\xE3o dispon\xEDvel no mock. Use createNeetruClient({ env: "dev" }) e `neetru dev` para o banco local.'
5158
+ );
5159
+ }
5160
+ get syncState() {
5161
+ return {
5162
+ status: "idle",
5163
+ pendingWrites: 0,
5164
+ lastSyncedAt: null,
5165
+ isLeaderTab: true
5166
+ };
5167
+ }
5168
+ onSyncStateChanged(_cb) {
5169
+ return () => {
5170
+ };
5171
+ }
5172
+ async flush() {
5173
+ }
5174
+ async clearCache() {
5175
+ this._store.clear();
5176
+ }
5177
+ async getConflicts() {
5178
+ return [];
1566
5179
  }
1567
5180
  /** Test helper — substitui fixture inteira de uma collection. */
1568
5181
  __setFixture(name, items) {
@@ -1733,7 +5346,7 @@ function createNeetruClient(config = {}) {
1733
5346
  const usage = config.mocks?.usage ?? (isDev ? new MockUsage() : createUsageNamespace(resolved));
1734
5347
  const support = config.mocks?.support ?? (isDev ? new MockSupport() : createSupportNamespace(resolved));
1735
5348
  const entitlements = config.mocks?.entitlements ?? (isDev ? new MockEntitlements() : createEntitlementsNamespace(resolved));
1736
- const db = config.mocks?.db ?? (isDev ? new MockDb() : createDbNamespace(resolved));
5349
+ const db = config.mocks?.db ?? createNeetruDb(resolved, config.db);
1737
5350
  const webhooks = config.mocks?.webhooks ?? (isDev ? new MockWebhooks() : createWebhooksNamespace(resolved));
1738
5351
  const notifications = config.mocks?.notifications ?? (isDev ? new MockNotifications() : createNotificationsNamespace(resolved));
1739
5352
  const client = Object.freeze({
@@ -1753,12 +5366,13 @@ function createNeetruClient(config = {}) {
1753
5366
  }
1754
5367
 
1755
5368
  // src/index.ts
1756
- var VERSION = "1.2.0";
5369
+ init_errors();
5370
+ var VERSION = "2.0.0";
1757
5371
  function initNeetru(config) {
1758
- const { apiUrl, baseUrl, ...rest } = config;
1759
- return createNeetruClient({ ...rest, baseUrl: baseUrl ?? apiUrl });
5372
+ const { apiUrl: _apiUrl, baseUrl, ...rest } = config;
5373
+ return createNeetruClient({ ...rest, baseUrl });
1760
5374
  }
1761
5375
 
1762
- export { DEFAULT_BASE_URL, DEV_FIXTURE_USER, MockAuth, MockCheckout, MockDb, MockEntitlements, MockNotifications, MockSupport, MockUsage, MockWebhooks, NeetruError, VERSION, createCheckoutNamespace, createNeetruClient, createNotificationsNamespace, createWebhooksNamespace, initNeetru };
5376
+ export { DEFAULT_BASE_URL, DEV_FIXTURE_USER, MockAuth, MockCheckout, MockDb, MockEntitlements, MockNotifications, MockSupport, MockUsage, MockWebhooks, NeetruDbError, NeetruError, VERSION, createCheckoutNamespace, createNeetruClient, createNeetruDb, createNotificationsNamespace, createWebhooksNamespace, initNeetru };
1763
5377
  //# sourceMappingURL=index.mjs.map
1764
5378
  //# sourceMappingURL=index.mjs.map