@neetru/sdk 1.1.1 → 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.
- package/CHANGELOG.md +284 -214
- package/README.md +194 -218
- package/dist/auth.cjs +4181 -346
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.d.cts +5 -1
- package/dist/auth.d.ts +5 -1
- package/dist/auth.mjs +4181 -346
- package/dist/auth.mjs.map +1 -1
- package/dist/catalog.cjs +63 -24
- package/dist/catalog.cjs.map +1 -1
- package/dist/catalog.d.cts +6 -2
- package/dist/catalog.d.ts +6 -2
- package/dist/catalog.mjs +63 -24
- package/dist/catalog.mjs.map +1 -1
- package/dist/checkout.cjs +60 -18
- package/dist/checkout.cjs.map +1 -1
- package/dist/checkout.d.cts +5 -1
- package/dist/checkout.d.ts +5 -1
- package/dist/checkout.mjs +60 -18
- package/dist/checkout.mjs.map +1 -1
- package/dist/collection-ref-BBvTTXoG.d.cts +423 -0
- package/dist/collection-ref-BBvTTXoG.d.ts +423 -0
- package/dist/db-react.cjs +136 -0
- package/dist/db-react.cjs.map +1 -0
- package/dist/db-react.d.cts +99 -0
- package/dist/db-react.d.ts +99 -0
- package/dist/db-react.mjs +112 -0
- package/dist/db-react.mjs.map +1 -0
- package/dist/db.cjs +3652 -143
- package/dist/db.cjs.map +1 -1
- package/dist/db.d.cts +5 -8
- package/dist/db.d.ts +5 -8
- package/dist/db.mjs +3649 -143
- package/dist/db.mjs.map +1 -1
- package/dist/entitlements.cjs +101 -24
- package/dist/entitlements.cjs.map +1 -1
- package/dist/entitlements.d.cts +15 -5
- package/dist/entitlements.d.ts +15 -5
- package/dist/entitlements.mjs +101 -24
- package/dist/entitlements.mjs.map +1 -1
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.mjs.map +1 -1
- package/dist/index.cjs +4341 -282
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -6
- package/dist/index.d.ts +13 -6
- package/dist/index.mjs +4243 -189
- package/dist/index.mjs.map +1 -1
- package/dist/mocks.cjs +186 -9
- package/dist/mocks.cjs.map +1 -1
- package/dist/mocks.d.cts +21 -6
- package/dist/mocks.d.ts +21 -6
- package/dist/mocks.mjs +186 -9
- package/dist/mocks.mjs.map +1 -1
- package/dist/notifications.cjs +296 -0
- package/dist/notifications.cjs.map +1 -0
- package/dist/notifications.d.cts +5 -0
- package/dist/notifications.d.ts +5 -0
- package/dist/notifications.mjs +293 -0
- package/dist/notifications.mjs.map +1 -0
- package/dist/react.cjs +7 -3
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +5 -1
- package/dist/react.d.ts +5 -1
- package/dist/react.mjs +7 -3
- package/dist/react.mjs.map +1 -1
- package/dist/support.cjs +60 -18
- package/dist/support.cjs.map +1 -1
- package/dist/support.d.cts +5 -1
- package/dist/support.d.ts +5 -1
- package/dist/support.mjs +60 -18
- package/dist/support.mjs.map +1 -1
- package/dist/telemetry.cjs +130 -19
- package/dist/telemetry.cjs.map +1 -1
- package/dist/telemetry.d.cts +21 -1
- package/dist/telemetry.d.ts +21 -1
- package/dist/telemetry.mjs +130 -19
- package/dist/telemetry.mjs.map +1 -1
- package/dist/types-B1jylbMC.d.ts +1364 -0
- package/dist/types-Kmt4y1FQ.d.cts +1364 -0
- package/dist/usage.cjs +60 -18
- package/dist/usage.cjs.map +1 -1
- package/dist/usage.d.cts +5 -1
- package/dist/usage.d.ts +5 -1
- package/dist/usage.mjs +60 -18
- package/dist/usage.mjs.map +1 -1
- package/dist/webhooks.cjs +316 -0
- package/dist/webhooks.cjs.map +1 -0
- package/dist/webhooks.d.cts +5 -0
- package/dist/webhooks.d.ts +5 -0
- package/dist/webhooks.mjs +312 -0
- package/dist/webhooks.mjs.map +1 -0
- package/package.json +133 -101
- package/dist/types-BA53dd8S.d.cts +0 -490
- package/dist/types-BA53dd8S.d.ts +0 -490
package/dist/index.mjs
CHANGED
|
@@ -1,22 +1,65 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
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/
|
|
17
|
-
var
|
|
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
|
|
40
|
+
var http_exports = {};
|
|
41
|
+
__export(http_exports, {
|
|
42
|
+
httpRequest: () => httpRequest
|
|
43
|
+
});
|
|
44
|
+
function backoffMs(attempt) {
|
|
45
|
+
const base = 200 * Math.pow(4, attempt);
|
|
46
|
+
const jitter = base * 0.2 * (Math.random() * 2 - 1);
|
|
47
|
+
return Math.max(50, Math.round(base + jitter));
|
|
48
|
+
}
|
|
49
|
+
function parseRetryAfter(value) {
|
|
50
|
+
if (!value) return null;
|
|
51
|
+
const secs = Number(value);
|
|
52
|
+
if (Number.isFinite(secs) && secs >= 0) return Math.round(secs * 1e3);
|
|
53
|
+
const dateMs = Date.parse(value);
|
|
54
|
+
if (Number.isFinite(dateMs)) {
|
|
55
|
+
const delta = dateMs - Date.now();
|
|
56
|
+
if (delta > 0) return delta;
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
function sleep(ms) {
|
|
61
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
62
|
+
}
|
|
20
63
|
function statusToCode(status) {
|
|
21
64
|
if (status === 401) return "unauthorized";
|
|
22
65
|
if (status === 403) return "forbidden";
|
|
@@ -50,6 +93,7 @@ async function safeJson(res) {
|
|
|
50
93
|
async function httpRequest(config, opts) {
|
|
51
94
|
const method = opts.method ?? "GET";
|
|
52
95
|
const url = buildUrl(config.baseUrl, opts.path, opts.query);
|
|
96
|
+
const maxRetries = opts.retries ?? DEFAULT_RETRIES;
|
|
53
97
|
const headers = {
|
|
54
98
|
accept: "application/json",
|
|
55
99
|
...opts.headers
|
|
@@ -63,24 +107,32 @@ async function httpRequest(config, opts) {
|
|
|
63
107
|
}
|
|
64
108
|
headers.authorization = `Bearer ${config.apiKey}`;
|
|
65
109
|
}
|
|
66
|
-
const
|
|
67
|
-
if (
|
|
110
|
+
const bodyString = opts.body !== void 0 && method !== "GET" && method !== "DELETE" ? JSON.stringify(opts.body) : void 0;
|
|
111
|
+
if (bodyString !== void 0) {
|
|
68
112
|
headers["content-type"] = "application/json";
|
|
69
|
-
init.body = JSON.stringify(opts.body);
|
|
70
113
|
}
|
|
71
|
-
|
|
72
|
-
let
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
114
|
+
let lastError = null;
|
|
115
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
116
|
+
const init = { method, headers };
|
|
117
|
+
if (bodyString !== void 0) init.body = bodyString;
|
|
118
|
+
init.signal = AbortSignal.timeout(3e4);
|
|
119
|
+
let res;
|
|
120
|
+
try {
|
|
121
|
+
res = await config.fetch(url, init);
|
|
122
|
+
} catch (err2) {
|
|
123
|
+
const message2 = err2 instanceof DOMException && err2.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${err2 instanceof Error ? err2.message : "fetch failed"}`;
|
|
124
|
+
lastError = new NeetruError("network_error", message2);
|
|
125
|
+
if (attempt < maxRetries) {
|
|
126
|
+
await sleep(backoffMs(attempt));
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
throw lastError;
|
|
130
|
+
}
|
|
131
|
+
const requestId = res.headers.get("x-request-id") ?? res.headers.get("x-correlation-id") ?? void 0;
|
|
132
|
+
if (res.ok) {
|
|
133
|
+
const parsed = await safeJson(res);
|
|
134
|
+
return parsed;
|
|
78
135
|
}
|
|
79
|
-
const message = err instanceof Error ? err.message : "fetch failed";
|
|
80
|
-
throw new NeetruError("network_error", `Network error: ${message}`);
|
|
81
|
-
}
|
|
82
|
-
const requestId = res.headers.get("x-request-id") ?? res.headers.get("x-correlation-id") ?? void 0;
|
|
83
|
-
if (!res.ok) {
|
|
84
136
|
const body = await safeJson(res);
|
|
85
137
|
let code = statusToCode(res.status);
|
|
86
138
|
let message = `HTTP ${res.status}`;
|
|
@@ -93,13 +145,41 @@ async function httpRequest(config, opts) {
|
|
|
93
145
|
if (typeof errField.message === "string") message = errField.message;
|
|
94
146
|
}
|
|
95
147
|
}
|
|
96
|
-
|
|
148
|
+
const err = new NeetruError(code, message, res.status, requestId);
|
|
149
|
+
lastError = err;
|
|
150
|
+
const isRetryable = RETRYABLE_CODES.has(code);
|
|
151
|
+
if (isRetryable && attempt < maxRetries) {
|
|
152
|
+
const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
|
|
153
|
+
const delay = retryAfter ?? backoffMs(attempt);
|
|
154
|
+
await sleep(delay);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
throw err;
|
|
97
158
|
}
|
|
98
|
-
|
|
99
|
-
return parsed;
|
|
159
|
+
throw lastError ?? new NeetruError("unknown", "unexpected httpRequest exit");
|
|
100
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";
|
|
101
179
|
|
|
102
180
|
// src/catalog.ts
|
|
181
|
+
init_errors();
|
|
182
|
+
init_http();
|
|
103
183
|
function toProduct(raw) {
|
|
104
184
|
if (!raw || typeof raw !== "object") {
|
|
105
185
|
throw new NeetruError("invalid_response", "Catalog response item is not an object");
|
|
@@ -136,12 +216,10 @@ function createCatalogNamespace(config) {
|
|
|
136
216
|
* Lista produtos publicados. Por default só `published=true`; staff
|
|
137
217
|
* pode passar `includeDrafts: true` (requer Bearer com role admin/operator).
|
|
138
218
|
*/
|
|
139
|
-
async list(
|
|
219
|
+
async list(_opts = {}) {
|
|
140
220
|
const raw = await httpRequest(config, {
|
|
141
221
|
method: "GET",
|
|
142
|
-
path: "/api/v1/
|
|
143
|
-
query: opts.includeDrafts ? { drafts: "true" } : void 0,
|
|
144
|
-
requireAuth: true
|
|
222
|
+
path: "/api/sdk/v1/catalog"
|
|
145
223
|
});
|
|
146
224
|
if (!raw || !Array.isArray(raw.products)) {
|
|
147
225
|
throw new NeetruError(
|
|
@@ -165,8 +243,7 @@ function createCatalogNamespace(config) {
|
|
|
165
243
|
}
|
|
166
244
|
const raw = await httpRequest(config, {
|
|
167
245
|
method: "GET",
|
|
168
|
-
path: `/api/v1/
|
|
169
|
-
requireAuth: true
|
|
246
|
+
path: `/api/sdk/v1/catalog/${encodeURIComponent(slug)}`
|
|
170
247
|
});
|
|
171
248
|
if (!raw || !raw.product) {
|
|
172
249
|
throw new NeetruError(
|
|
@@ -180,6 +257,8 @@ function createCatalogNamespace(config) {
|
|
|
180
257
|
}
|
|
181
258
|
|
|
182
259
|
// src/entitlements.ts
|
|
260
|
+
init_errors();
|
|
261
|
+
init_http();
|
|
183
262
|
function toEntitlementCheck(raw) {
|
|
184
263
|
if (!raw || typeof raw !== "object") {
|
|
185
264
|
throw new NeetruError("invalid_response", "Entitlement response is not an object");
|
|
@@ -195,34 +274,71 @@ function toEntitlementCheck(raw) {
|
|
|
195
274
|
reason: typeof r.reason === "string" ? r.reason : void 0
|
|
196
275
|
};
|
|
197
276
|
}
|
|
277
|
+
var CACHE_TTL_MS = 6e4;
|
|
278
|
+
var CACHE_MAX = 100;
|
|
198
279
|
function createEntitlementsNamespace(config) {
|
|
199
|
-
|
|
280
|
+
const cache = /* @__PURE__ */ new Map();
|
|
281
|
+
function cacheKey(productSlug, feature) {
|
|
282
|
+
return `${productSlug}::${feature}`;
|
|
283
|
+
}
|
|
284
|
+
function readCache(key) {
|
|
285
|
+
const entry = cache.get(key);
|
|
286
|
+
if (!entry) return null;
|
|
287
|
+
if (entry.expiresAt < Date.now()) {
|
|
288
|
+
cache.delete(key);
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
cache.delete(key);
|
|
292
|
+
cache.set(key, entry);
|
|
293
|
+
return entry.value;
|
|
294
|
+
}
|
|
295
|
+
function writeCache(key, value) {
|
|
296
|
+
if (cache.size >= CACHE_MAX) {
|
|
297
|
+
const oldest = cache.keys().next().value;
|
|
298
|
+
if (oldest !== void 0) cache.delete(oldest);
|
|
299
|
+
}
|
|
300
|
+
cache.set(key, { value, expiresAt: Date.now() + CACHE_TTL_MS });
|
|
301
|
+
}
|
|
302
|
+
async function checkDetailed(productSlug, feature, opts = {}) {
|
|
200
303
|
if (!productSlug) throw new NeetruError("validation_failed", "productSlug is required");
|
|
201
304
|
if (!feature) throw new NeetruError("validation_failed", "feature is required");
|
|
305
|
+
const key = cacheKey(productSlug, feature);
|
|
306
|
+
if (!opts.cacheBust) {
|
|
307
|
+
const cached = readCache(key);
|
|
308
|
+
if (cached) return cached;
|
|
309
|
+
}
|
|
202
310
|
const raw = await httpRequest(config, {
|
|
203
311
|
method: "GET",
|
|
204
312
|
path: "/api/v1/sdk/entitlements/check",
|
|
205
313
|
query: { slug: productSlug, feature },
|
|
206
314
|
requireAuth: true
|
|
207
315
|
});
|
|
208
|
-
|
|
316
|
+
const result = toEntitlementCheck(raw);
|
|
317
|
+
writeCache(key, result);
|
|
318
|
+
return result;
|
|
209
319
|
}
|
|
210
320
|
return {
|
|
211
321
|
/**
|
|
212
322
|
* Verifica se o caller pode usar `feature` no produto `productSlug`.
|
|
213
|
-
* Retorno simples: `true` libera, `false` bloqueia.
|
|
323
|
+
* Retorno simples: `true` libera, `false` bloqueia. Cache 60s automático.
|
|
214
324
|
*
|
|
215
325
|
* Use `checkDetailed` se precisar do `reason` pra mensagem de upgrade.
|
|
216
326
|
*/
|
|
217
|
-
async check(productSlug, feature) {
|
|
218
|
-
const result = await checkDetailed(productSlug, feature);
|
|
327
|
+
async check(productSlug, feature, opts) {
|
|
328
|
+
const result = await checkDetailed(productSlug, feature, opts);
|
|
219
329
|
return result.allowed;
|
|
220
330
|
},
|
|
221
|
-
checkDetailed
|
|
331
|
+
checkDetailed,
|
|
332
|
+
/** Test helper: limpa o cache LRU. */
|
|
333
|
+
__resetCache() {
|
|
334
|
+
cache.clear();
|
|
335
|
+
}
|
|
222
336
|
};
|
|
223
337
|
}
|
|
224
338
|
|
|
225
339
|
// src/telemetry.ts
|
|
340
|
+
init_errors();
|
|
341
|
+
init_http();
|
|
226
342
|
var VALID_LOG_LEVELS = ["debug", "info", "warn", "error", "fatal"];
|
|
227
343
|
function consoleFor(level) {
|
|
228
344
|
switch (level) {
|
|
@@ -240,7 +356,44 @@ function consoleFor(level) {
|
|
|
240
356
|
return console.log.bind(console);
|
|
241
357
|
}
|
|
242
358
|
}
|
|
359
|
+
var TRACK_FLUSH_MS = 500;
|
|
360
|
+
var TRACK_MAX_QUEUE = 50;
|
|
243
361
|
function createTelemetryNamespace(config) {
|
|
362
|
+
const queue = [];
|
|
363
|
+
let flushTimer = null;
|
|
364
|
+
async function drainQueue() {
|
|
365
|
+
if (queue.length === 0) return;
|
|
366
|
+
const batch = queue.splice(0, queue.length);
|
|
367
|
+
flushTimer = null;
|
|
368
|
+
await Promise.allSettled(
|
|
369
|
+
batch.map(async (ev) => {
|
|
370
|
+
try {
|
|
371
|
+
const body = { name: ev.name };
|
|
372
|
+
if (ev.properties && typeof ev.properties === "object") {
|
|
373
|
+
body.properties = ev.properties;
|
|
374
|
+
}
|
|
375
|
+
if (ev.timestamp) body.timestamp = ev.timestamp;
|
|
376
|
+
await httpRequest(config, {
|
|
377
|
+
method: "POST",
|
|
378
|
+
path: "/api/v1/sdk/telemetry/event",
|
|
379
|
+
body,
|
|
380
|
+
requireAuth: true,
|
|
381
|
+
retries: 1
|
|
382
|
+
});
|
|
383
|
+
} catch (err) {
|
|
384
|
+
if (typeof console !== "undefined") {
|
|
385
|
+
console.warn("[neetru-sdk] telemetry.track flush failed for event", ev.name, err);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
})
|
|
389
|
+
);
|
|
390
|
+
}
|
|
391
|
+
function scheduleFlush() {
|
|
392
|
+
if (flushTimer) return;
|
|
393
|
+
flushTimer = setTimeout(() => {
|
|
394
|
+
void drainQueue();
|
|
395
|
+
}, TRACK_FLUSH_MS);
|
|
396
|
+
}
|
|
244
397
|
return {
|
|
245
398
|
/**
|
|
246
399
|
* Persiste um evento de uso. Lança `NeetruError` em qualquer falha
|
|
@@ -280,6 +433,38 @@ function createTelemetryNamespace(config) {
|
|
|
280
433
|
}
|
|
281
434
|
return { ok: true, eventId: raw.eventId };
|
|
282
435
|
},
|
|
436
|
+
/**
|
|
437
|
+
* Fire-and-forget: enqueue + flush 500ms debounce. Não retorna `eventId`
|
|
438
|
+
* — falhas são logadas como warning. Ideal pra alta frequência.
|
|
439
|
+
*
|
|
440
|
+
* @example
|
|
441
|
+
* ```ts
|
|
442
|
+
* client.telemetry.track({ name: 'page_view', properties: { path: '/' } });
|
|
443
|
+
* // segue execução; flush async em background
|
|
444
|
+
* ```
|
|
445
|
+
*/
|
|
446
|
+
track(input) {
|
|
447
|
+
if (!input || typeof input !== "object") return;
|
|
448
|
+
if (typeof input.name !== "string" || input.name.length === 0) return;
|
|
449
|
+
if (input.name.length > 128) return;
|
|
450
|
+
queue.push(input);
|
|
451
|
+
if (queue.length >= TRACK_MAX_QUEUE) {
|
|
452
|
+
void drainQueue();
|
|
453
|
+
} else {
|
|
454
|
+
scheduleFlush();
|
|
455
|
+
}
|
|
456
|
+
},
|
|
457
|
+
/**
|
|
458
|
+
* Força flush imediato da queue de `track()`. Resolva antes de
|
|
459
|
+
* page unload / SSR boundary pra não perder eventos.
|
|
460
|
+
*/
|
|
461
|
+
async flush() {
|
|
462
|
+
if (flushTimer) {
|
|
463
|
+
clearTimeout(flushTimer);
|
|
464
|
+
flushTimer = null;
|
|
465
|
+
}
|
|
466
|
+
await drainQueue();
|
|
467
|
+
},
|
|
283
468
|
/**
|
|
284
469
|
* Registra um log estruturado per-product (Sprint 6).
|
|
285
470
|
*
|
|
@@ -331,7 +516,7 @@ function createTelemetryNamespace(config) {
|
|
|
331
516
|
if (cid) headers["x-correlation-id"] = cid;
|
|
332
517
|
const raw = await httpRequest(config, {
|
|
333
518
|
method: "POST",
|
|
334
|
-
path: "/sdk/v1/telemetry/log",
|
|
519
|
+
path: "/api/sdk/v1/telemetry/log",
|
|
335
520
|
body,
|
|
336
521
|
requireAuth: true,
|
|
337
522
|
headers
|
|
@@ -349,6 +534,8 @@ function createTelemetryNamespace(config) {
|
|
|
349
534
|
}
|
|
350
535
|
|
|
351
536
|
// src/usage.ts
|
|
537
|
+
init_errors();
|
|
538
|
+
init_http();
|
|
352
539
|
function toQuota(metric, raw) {
|
|
353
540
|
if (!raw || typeof raw !== "object") {
|
|
354
541
|
throw new NeetruError("invalid_response", "Quota response is not an object");
|
|
@@ -485,6 +672,8 @@ function createUsageNamespace(config) {
|
|
|
485
672
|
}
|
|
486
673
|
|
|
487
674
|
// src/support.ts
|
|
675
|
+
init_errors();
|
|
676
|
+
init_http();
|
|
488
677
|
var VALID_SEVERITIES = ["low", "normal", "high", "urgent"];
|
|
489
678
|
var VALID_STATUSES = ["open", "pending", "resolved", "closed"];
|
|
490
679
|
function toTicket(raw) {
|
|
@@ -546,148 +735,3576 @@ function createSupportNamespace(config) {
|
|
|
546
735
|
const candidate = raw && typeof raw === "object" && "ticket" in raw ? raw.ticket : raw;
|
|
547
736
|
return toTicket(candidate);
|
|
548
737
|
},
|
|
549
|
-
/**
|
|
550
|
-
* Lista tickets do customer no produto atual (escopo do token).
|
|
551
|
-
*/
|
|
552
|
-
async listMyTickets() {
|
|
553
|
-
const raw = await httpRequest(config, {
|
|
554
|
-
method: "GET",
|
|
555
|
-
path: "/api/v1/products/_default/tickets",
|
|
556
|
-
requireAuth: true
|
|
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
|
+
}
|
|
4084
|
+
}
|
|
4085
|
+
return { results };
|
|
4086
|
+
},
|
|
4087
|
+
async pullChanges(_watermark, _resumeToken) {
|
|
4088
|
+
if (!config) {
|
|
4089
|
+
return { docs: [], newWatermark: Date.now(), resyncRequired: false };
|
|
4090
|
+
}
|
|
4091
|
+
return { docs: [], newWatermark: Date.now(), resyncRequired: false };
|
|
4092
|
+
},
|
|
4093
|
+
async fullResync(_collections) {
|
|
4094
|
+
if (!config) {
|
|
4095
|
+
return { docs: [], newWatermark: Date.now() };
|
|
4096
|
+
}
|
|
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
|
+
}
|
|
557
4136
|
});
|
|
558
|
-
|
|
559
|
-
|
|
4137
|
+
return () => {
|
|
4138
|
+
realtimeClient.unsubscribe(subId);
|
|
4139
|
+
};
|
|
560
4140
|
}
|
|
561
4141
|
};
|
|
562
4142
|
}
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
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;
|
|
4157
|
+
};
|
|
573
4158
|
}
|
|
574
|
-
function
|
|
575
|
-
const
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
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
|
+
});
|
|
582
4176
|
}
|
|
583
|
-
return
|
|
4177
|
+
return _docsPromise;
|
|
584
4178
|
}
|
|
585
|
-
return `${field}:${op}:${String(value)}`;
|
|
586
|
-
}
|
|
587
|
-
function createDbNamespace(config) {
|
|
588
4179
|
return {
|
|
589
4180
|
collection(name) {
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
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
|
+
);
|
|
4190
|
+
}
|
|
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
|
|
4199
|
+
};
|
|
4200
|
+
},
|
|
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
|
+
}
|
|
4209
|
+
});
|
|
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();
|
|
4226
|
+
}
|
|
4227
|
+
};
|
|
4228
|
+
}
|
|
4229
|
+
function createLazyCollectionRef(name, getDocsPromise) {
|
|
4230
|
+
async function getRef() {
|
|
4231
|
+
const docs = await getDocsPromise();
|
|
4232
|
+
return docs.collection(name);
|
|
4233
|
+
}
|
|
4234
|
+
return {
|
|
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) {
|
|
593
4283
|
return {
|
|
594
|
-
async
|
|
595
|
-
|
|
596
|
-
let path = `/sdk/v1/datastore/${name}`;
|
|
597
|
-
const params = new URLSearchParams();
|
|
598
|
-
if (opts?.limit !== void 0) params.set("limit", String(opts.limit));
|
|
599
|
-
if (opts?.where && opts.where.length > 0) {
|
|
600
|
-
for (const f of opts.where) {
|
|
601
|
-
params.append("where", serializeWhere(f));
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
if (config.tenantId) params.set("tenantId", config.tenantId);
|
|
605
|
-
const qs = params.toString();
|
|
606
|
-
if (qs) path += `?${qs}`;
|
|
607
|
-
const raw = await httpRequest(config, {
|
|
608
|
-
method: "GET",
|
|
609
|
-
path,
|
|
610
|
-
requireAuth: true,
|
|
611
|
-
headers
|
|
612
|
-
});
|
|
613
|
-
if (!raw || !Array.isArray(raw.items)) {
|
|
614
|
-
throw new NeetruError(
|
|
615
|
-
"invalid_response",
|
|
616
|
-
"datastore.list missing items[]"
|
|
617
|
-
);
|
|
618
|
-
}
|
|
619
|
-
return raw.items;
|
|
620
|
-
},
|
|
621
|
-
async get(id) {
|
|
622
|
-
if (!id || typeof id !== "string") {
|
|
623
|
-
throw new NeetruError("validation_failed", "id required");
|
|
624
|
-
}
|
|
625
|
-
try {
|
|
626
|
-
const raw = await httpRequest(config, {
|
|
627
|
-
method: "GET",
|
|
628
|
-
path: `/sdk/v1/datastore/${name}/${encodeURIComponent(id)}`,
|
|
629
|
-
requireAuth: true,
|
|
630
|
-
headers
|
|
631
|
-
});
|
|
632
|
-
return raw?.item ?? null;
|
|
633
|
-
} catch (err) {
|
|
634
|
-
if (err instanceof NeetruError && err.code === "not_found") return null;
|
|
635
|
-
throw err;
|
|
636
|
-
}
|
|
4284
|
+
async get() {
|
|
4285
|
+
return (await getRef()).doc(id).get();
|
|
637
4286
|
},
|
|
638
|
-
async
|
|
639
|
-
|
|
640
|
-
throw new NeetruError("validation_failed", "data object required");
|
|
641
|
-
}
|
|
642
|
-
const raw = await httpRequest(config, {
|
|
643
|
-
method: "POST",
|
|
644
|
-
path: `/sdk/v1/datastore/${name}`,
|
|
645
|
-
body: { data },
|
|
646
|
-
requireAuth: true,
|
|
647
|
-
headers
|
|
648
|
-
});
|
|
649
|
-
if (!raw || typeof raw.id !== "string") {
|
|
650
|
-
throw new NeetruError("invalid_response", "datastore.add missing id");
|
|
651
|
-
}
|
|
652
|
-
return { ok: true, id: raw.id };
|
|
4287
|
+
async set(data) {
|
|
4288
|
+
return (await getRef()).doc(id).set(data);
|
|
653
4289
|
},
|
|
654
|
-
async
|
|
655
|
-
|
|
656
|
-
throw new NeetruError("validation_failed", "id required");
|
|
657
|
-
}
|
|
658
|
-
await httpRequest(config, {
|
|
659
|
-
method: "PUT",
|
|
660
|
-
path: `/sdk/v1/datastore/${name}/${encodeURIComponent(id)}`,
|
|
661
|
-
body: { data },
|
|
662
|
-
requireAuth: true,
|
|
663
|
-
headers
|
|
664
|
-
});
|
|
665
|
-
return { ok: true };
|
|
4290
|
+
async update(data) {
|
|
4291
|
+
return (await getRef()).doc(id).update(data);
|
|
666
4292
|
},
|
|
667
|
-
async
|
|
668
|
-
|
|
669
|
-
throw new NeetruError("validation_failed", "id required");
|
|
670
|
-
}
|
|
671
|
-
await httpRequest(config, {
|
|
672
|
-
method: "PATCH",
|
|
673
|
-
path: `/sdk/v1/datastore/${name}/${encodeURIComponent(id)}`,
|
|
674
|
-
body: { data },
|
|
675
|
-
requireAuth: true,
|
|
676
|
-
headers
|
|
677
|
-
});
|
|
678
|
-
return { ok: true };
|
|
4293
|
+
async remove() {
|
|
4294
|
+
return (await getRef()).doc(id).remove();
|
|
679
4295
|
},
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
requireAuth: true,
|
|
688
|
-
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
|
+
}
|
|
689
4303
|
});
|
|
690
|
-
return
|
|
4304
|
+
return () => {
|
|
4305
|
+
cancelled = true;
|
|
4306
|
+
unsub?.();
|
|
4307
|
+
};
|
|
691
4308
|
}
|
|
692
4309
|
};
|
|
693
4310
|
}
|
|
@@ -695,6 +4312,8 @@ function createDbNamespace(config) {
|
|
|
695
4312
|
}
|
|
696
4313
|
|
|
697
4314
|
// src/checkout.ts
|
|
4315
|
+
init_errors();
|
|
4316
|
+
init_http();
|
|
698
4317
|
function parseStartResponse(raw) {
|
|
699
4318
|
if (!raw || typeof raw !== "object") {
|
|
700
4319
|
throw new NeetruError("invalid_response", "checkout.start response is not an object");
|
|
@@ -869,6 +4488,301 @@ function createCheckoutNamespace(config) {
|
|
|
869
4488
|
return createHttpCheckoutNamespace(config);
|
|
870
4489
|
}
|
|
871
4490
|
|
|
4491
|
+
// src/webhooks.ts
|
|
4492
|
+
init_errors();
|
|
4493
|
+
init_http();
|
|
4494
|
+
var VALID_EVENTS = [
|
|
4495
|
+
"subscription.activated",
|
|
4496
|
+
"subscription.cancelled",
|
|
4497
|
+
"subscription.payment_failed",
|
|
4498
|
+
"subscription.trial_ending",
|
|
4499
|
+
"usage.quota_exceeded",
|
|
4500
|
+
"account.suspended",
|
|
4501
|
+
"account.reactivated",
|
|
4502
|
+
"support.ticket_replied"
|
|
4503
|
+
];
|
|
4504
|
+
function toEndpoint(raw) {
|
|
4505
|
+
if (!raw || typeof raw !== "object") {
|
|
4506
|
+
throw new NeetruError("invalid_response", "Webhook response is not an object");
|
|
4507
|
+
}
|
|
4508
|
+
const r = raw;
|
|
4509
|
+
if (typeof r.id !== "string") {
|
|
4510
|
+
throw new NeetruError("invalid_response", "Webhook missing id");
|
|
4511
|
+
}
|
|
4512
|
+
return {
|
|
4513
|
+
id: r.id,
|
|
4514
|
+
url: typeof r.url === "string" ? r.url : "",
|
|
4515
|
+
events: Array.isArray(r.events) ? r.events.filter(
|
|
4516
|
+
(e) => VALID_EVENTS.includes(e)
|
|
4517
|
+
) : [],
|
|
4518
|
+
hasSecret: r.hasSecret === true,
|
|
4519
|
+
status: r.status === "active" || r.status === "degraded" || r.status === "disabled" ? r.status : "active",
|
|
4520
|
+
lastDeliveryAt: typeof r.lastDeliveryAt === "string" ? r.lastDeliveryAt : void 0,
|
|
4521
|
+
consecutiveFailures: typeof r.consecutiveFailures === "number" ? r.consecutiveFailures : void 0,
|
|
4522
|
+
createdAt: typeof r.createdAt === "string" ? r.createdAt : (/* @__PURE__ */ new Date()).toISOString()
|
|
4523
|
+
};
|
|
4524
|
+
}
|
|
4525
|
+
function validateInput(input) {
|
|
4526
|
+
if (!input.url || typeof input.url !== "string") {
|
|
4527
|
+
throw new NeetruError("validation_failed", "url \xE9 obrigat\xF3ria");
|
|
4528
|
+
}
|
|
4529
|
+
try {
|
|
4530
|
+
const parsed = new URL(input.url);
|
|
4531
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
|
|
4532
|
+
throw new Error("invalid protocol");
|
|
4533
|
+
}
|
|
4534
|
+
} catch {
|
|
4535
|
+
throw new NeetruError("validation_failed", `url inv\xE1lida: ${input.url}`);
|
|
4536
|
+
}
|
|
4537
|
+
if (!Array.isArray(input.events) || input.events.length === 0) {
|
|
4538
|
+
throw new NeetruError("validation_failed", "events deve ter pelo menos 1 evento");
|
|
4539
|
+
}
|
|
4540
|
+
for (const ev of input.events) {
|
|
4541
|
+
if (!VALID_EVENTS.includes(ev)) {
|
|
4542
|
+
throw new NeetruError("validation_failed", `evento desconhecido: ${ev}`);
|
|
4543
|
+
}
|
|
4544
|
+
}
|
|
4545
|
+
if (input.secret !== void 0 && input.secret.length < 16) {
|
|
4546
|
+
throw new NeetruError("validation_failed", "secret deve ter \u226516 chars (recomendado 32+)");
|
|
4547
|
+
}
|
|
4548
|
+
}
|
|
4549
|
+
function createWebhooksNamespace(config) {
|
|
4550
|
+
return {
|
|
4551
|
+
async register(input) {
|
|
4552
|
+
validateInput(input);
|
|
4553
|
+
const raw = await httpRequest(config, {
|
|
4554
|
+
method: "POST",
|
|
4555
|
+
path: "/api/sdk/v1/webhooks",
|
|
4556
|
+
body: input,
|
|
4557
|
+
requireAuth: true
|
|
4558
|
+
});
|
|
4559
|
+
return toEndpoint(raw);
|
|
4560
|
+
},
|
|
4561
|
+
async list() {
|
|
4562
|
+
const raw = await httpRequest(config, {
|
|
4563
|
+
method: "GET",
|
|
4564
|
+
path: "/api/sdk/v1/webhooks",
|
|
4565
|
+
requireAuth: true
|
|
4566
|
+
});
|
|
4567
|
+
const list = Array.isArray(raw?.endpoints) ? raw.endpoints : [];
|
|
4568
|
+
return list.map(toEndpoint);
|
|
4569
|
+
},
|
|
4570
|
+
async unregister(id) {
|
|
4571
|
+
if (!id) throw new NeetruError("validation_failed", "id obrigat\xF3rio");
|
|
4572
|
+
await httpRequest(config, {
|
|
4573
|
+
method: "DELETE",
|
|
4574
|
+
path: `/api/sdk/v1/webhooks/${encodeURIComponent(id)}`,
|
|
4575
|
+
requireAuth: true
|
|
4576
|
+
});
|
|
4577
|
+
return { ok: true };
|
|
4578
|
+
},
|
|
4579
|
+
async test(id) {
|
|
4580
|
+
if (!id) throw new NeetruError("validation_failed", "id obrigat\xF3rio");
|
|
4581
|
+
const raw = await httpRequest(config, {
|
|
4582
|
+
method: "POST",
|
|
4583
|
+
path: `/api/sdk/v1/webhooks/${encodeURIComponent(id)}/test`,
|
|
4584
|
+
requireAuth: true
|
|
4585
|
+
});
|
|
4586
|
+
if (!raw || typeof raw !== "object") {
|
|
4587
|
+
return { ok: false, error: "invalid response" };
|
|
4588
|
+
}
|
|
4589
|
+
const r = raw;
|
|
4590
|
+
return {
|
|
4591
|
+
ok: r.ok === true,
|
|
4592
|
+
statusCode: typeof r.statusCode === "number" ? r.statusCode : void 0,
|
|
4593
|
+
durationMs: typeof r.durationMs === "number" ? r.durationMs : void 0,
|
|
4594
|
+
error: typeof r.error === "string" ? r.error : void 0
|
|
4595
|
+
};
|
|
4596
|
+
}
|
|
4597
|
+
};
|
|
4598
|
+
}
|
|
4599
|
+
var MockWebhooks = class {
|
|
4600
|
+
endpoints = /* @__PURE__ */ new Map();
|
|
4601
|
+
nextId = 1;
|
|
4602
|
+
async register(input) {
|
|
4603
|
+
validateInput(input);
|
|
4604
|
+
const id = `mock_wh_${this.nextId++}`;
|
|
4605
|
+
const endpoint = {
|
|
4606
|
+
id,
|
|
4607
|
+
url: input.url,
|
|
4608
|
+
events: input.events,
|
|
4609
|
+
hasSecret: !!input.secret,
|
|
4610
|
+
status: "active",
|
|
4611
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4612
|
+
};
|
|
4613
|
+
this.endpoints.set(id, endpoint);
|
|
4614
|
+
return endpoint;
|
|
4615
|
+
}
|
|
4616
|
+
async list() {
|
|
4617
|
+
return [...this.endpoints.values()];
|
|
4618
|
+
}
|
|
4619
|
+
async unregister(id) {
|
|
4620
|
+
if (!this.endpoints.has(id)) {
|
|
4621
|
+
throw new NeetruError("not_found", `Webhook ${id} n\xE3o encontrado`);
|
|
4622
|
+
}
|
|
4623
|
+
this.endpoints.delete(id);
|
|
4624
|
+
return { ok: true };
|
|
4625
|
+
}
|
|
4626
|
+
async test(id) {
|
|
4627
|
+
if (!this.endpoints.has(id)) {
|
|
4628
|
+
throw new NeetruError("not_found", `Webhook ${id} n\xE3o encontrado`);
|
|
4629
|
+
}
|
|
4630
|
+
return { ok: true, statusCode: 200, durationMs: 42 };
|
|
4631
|
+
}
|
|
4632
|
+
};
|
|
4633
|
+
|
|
4634
|
+
// src/notifications.ts
|
|
4635
|
+
init_errors();
|
|
4636
|
+
init_http();
|
|
4637
|
+
var VALID_SEVERITIES2 = [
|
|
4638
|
+
"info",
|
|
4639
|
+
"success",
|
|
4640
|
+
"warning",
|
|
4641
|
+
"error"
|
|
4642
|
+
];
|
|
4643
|
+
function toNotification(raw) {
|
|
4644
|
+
if (!raw || typeof raw !== "object") {
|
|
4645
|
+
throw new NeetruError("invalid_response", "Notification response is not an object");
|
|
4646
|
+
}
|
|
4647
|
+
const r = raw;
|
|
4648
|
+
if (typeof r.id !== "string") {
|
|
4649
|
+
throw new NeetruError("invalid_response", "Notification missing id");
|
|
4650
|
+
}
|
|
4651
|
+
const sev = VALID_SEVERITIES2.includes(r.severity) ? r.severity : "info";
|
|
4652
|
+
return {
|
|
4653
|
+
id: r.id,
|
|
4654
|
+
userId: typeof r.userId === "string" ? r.userId : "",
|
|
4655
|
+
kind: typeof r.kind === "string" ? r.kind : "unknown",
|
|
4656
|
+
severity: sev,
|
|
4657
|
+
title: typeof r.title === "string" ? r.title : "",
|
|
4658
|
+
body: typeof r.body === "string" ? r.body : void 0,
|
|
4659
|
+
link: typeof r.link === "string" ? r.link : void 0,
|
|
4660
|
+
metadata: r.metadata && typeof r.metadata === "object" ? r.metadata : void 0,
|
|
4661
|
+
createdAt: typeof r.createdAt === "string" ? r.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
|
|
4662
|
+
readAt: typeof r.readAt === "string" ? r.readAt : void 0,
|
|
4663
|
+
dismissedAt: typeof r.dismissedAt === "string" ? r.dismissedAt : void 0
|
|
4664
|
+
};
|
|
4665
|
+
}
|
|
4666
|
+
function validateInput2(input) {
|
|
4667
|
+
if (!input.userId) throw new NeetruError("validation_failed", "userId obrigat\xF3rio");
|
|
4668
|
+
if (!input.kind) throw new NeetruError("validation_failed", "kind obrigat\xF3rio");
|
|
4669
|
+
if (!input.title) throw new NeetruError("validation_failed", "title obrigat\xF3rio");
|
|
4670
|
+
if (input.severity && !VALID_SEVERITIES2.includes(input.severity)) {
|
|
4671
|
+
throw new NeetruError(
|
|
4672
|
+
"validation_failed",
|
|
4673
|
+
`severity inv\xE1lida: ${input.severity} (use ${VALID_SEVERITIES2.join("|")})`
|
|
4674
|
+
);
|
|
4675
|
+
}
|
|
4676
|
+
if (input.title.length > 200) {
|
|
4677
|
+
throw new NeetruError("validation_failed", "title m\xE1x 200 chars");
|
|
4678
|
+
}
|
|
4679
|
+
if (input.body && input.body.length > 2e3) {
|
|
4680
|
+
throw new NeetruError("validation_failed", "body m\xE1x 2000 chars");
|
|
4681
|
+
}
|
|
4682
|
+
}
|
|
4683
|
+
function createNotificationsNamespace(config) {
|
|
4684
|
+
return {
|
|
4685
|
+
async send(input) {
|
|
4686
|
+
validateInput2(input);
|
|
4687
|
+
const raw = await httpRequest(config, {
|
|
4688
|
+
method: "POST",
|
|
4689
|
+
path: "/api/sdk/v1/notifications",
|
|
4690
|
+
body: input,
|
|
4691
|
+
requireAuth: true
|
|
4692
|
+
});
|
|
4693
|
+
return toNotification(raw);
|
|
4694
|
+
},
|
|
4695
|
+
async list(userId, options) {
|
|
4696
|
+
if (!userId) throw new NeetruError("validation_failed", "userId obrigat\xF3rio");
|
|
4697
|
+
const params = new URLSearchParams();
|
|
4698
|
+
if (options?.includeDismissed) params.set("includeDismissed", "true");
|
|
4699
|
+
if (options?.onlyUnread) params.set("onlyUnread", "true");
|
|
4700
|
+
if (options?.limit) {
|
|
4701
|
+
params.set("limit", Math.min(Math.max(1, options.limit), 200).toString());
|
|
4702
|
+
}
|
|
4703
|
+
const qs = params.toString();
|
|
4704
|
+
const raw = await httpRequest(config, {
|
|
4705
|
+
method: "GET",
|
|
4706
|
+
path: `/api/sdk/v1/notifications/user/${encodeURIComponent(userId)}${qs ? `?${qs}` : ""}`,
|
|
4707
|
+
requireAuth: true
|
|
4708
|
+
});
|
|
4709
|
+
const list = Array.isArray(raw?.notifications) ? raw.notifications : [];
|
|
4710
|
+
return list.map(toNotification);
|
|
4711
|
+
},
|
|
4712
|
+
async markRead(id) {
|
|
4713
|
+
if (!id) throw new NeetruError("validation_failed", "id obrigat\xF3rio");
|
|
4714
|
+
await httpRequest(config, {
|
|
4715
|
+
method: "POST",
|
|
4716
|
+
path: `/api/sdk/v1/notifications/${encodeURIComponent(id)}/read`,
|
|
4717
|
+
requireAuth: true
|
|
4718
|
+
});
|
|
4719
|
+
return { ok: true };
|
|
4720
|
+
},
|
|
4721
|
+
async dismiss(id) {
|
|
4722
|
+
if (!id) throw new NeetruError("validation_failed", "id obrigat\xF3rio");
|
|
4723
|
+
await httpRequest(config, {
|
|
4724
|
+
method: "POST",
|
|
4725
|
+
path: `/api/sdk/v1/notifications/${encodeURIComponent(id)}/dismiss`,
|
|
4726
|
+
requireAuth: true
|
|
4727
|
+
});
|
|
4728
|
+
return { ok: true };
|
|
4729
|
+
}
|
|
4730
|
+
};
|
|
4731
|
+
}
|
|
4732
|
+
var MockNotifications = class {
|
|
4733
|
+
notifications = /* @__PURE__ */ new Map();
|
|
4734
|
+
nextId = 1;
|
|
4735
|
+
async send(input) {
|
|
4736
|
+
validateInput2(input);
|
|
4737
|
+
if (input.fingerprint) {
|
|
4738
|
+
const dayAgo = Date.now() - 864e5;
|
|
4739
|
+
for (const existing of this.notifications.values()) {
|
|
4740
|
+
const meta = existing.metadata ?? {};
|
|
4741
|
+
if (meta.fingerprint === input.fingerprint && existing.userId === input.userId && new Date(existing.createdAt).getTime() > dayAgo) {
|
|
4742
|
+
return existing;
|
|
4743
|
+
}
|
|
4744
|
+
}
|
|
4745
|
+
}
|
|
4746
|
+
const id = `mock_notif_${this.nextId++}`;
|
|
4747
|
+
const notif = {
|
|
4748
|
+
id,
|
|
4749
|
+
userId: input.userId,
|
|
4750
|
+
kind: input.kind,
|
|
4751
|
+
severity: input.severity ?? "info",
|
|
4752
|
+
title: input.title,
|
|
4753
|
+
body: input.body,
|
|
4754
|
+
link: input.link,
|
|
4755
|
+
metadata: input.fingerprint ? { ...input.metadata ?? {}, fingerprint: input.fingerprint } : input.metadata,
|
|
4756
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4757
|
+
};
|
|
4758
|
+
this.notifications.set(id, notif);
|
|
4759
|
+
return notif;
|
|
4760
|
+
}
|
|
4761
|
+
async list(userId, options) {
|
|
4762
|
+
if (!userId) throw new NeetruError("validation_failed", "userId obrigat\xF3rio");
|
|
4763
|
+
const limit = Math.min(Math.max(1, options?.limit ?? 50), 200);
|
|
4764
|
+
return [...this.notifications.values()].filter((n) => n.userId === userId).filter((n) => options?.includeDismissed || !n.dismissedAt).filter((n) => !options?.onlyUnread || !n.readAt).sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, limit);
|
|
4765
|
+
}
|
|
4766
|
+
async markRead(id) {
|
|
4767
|
+
const n = this.notifications.get(id);
|
|
4768
|
+
if (!n) throw new NeetruError("not_found", `Notification ${id} n\xE3o encontrada`);
|
|
4769
|
+
if (!n.readAt) {
|
|
4770
|
+
n.readAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
4771
|
+
this.notifications.set(id, n);
|
|
4772
|
+
}
|
|
4773
|
+
return { ok: true };
|
|
4774
|
+
}
|
|
4775
|
+
async dismiss(id) {
|
|
4776
|
+
const n = this.notifications.get(id);
|
|
4777
|
+
if (!n) throw new NeetruError("not_found", `Notification ${id} n\xE3o encontrada`);
|
|
4778
|
+
if (!n.dismissedAt) {
|
|
4779
|
+
n.dismissedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
4780
|
+
this.notifications.set(id, n);
|
|
4781
|
+
}
|
|
4782
|
+
return { ok: true };
|
|
4783
|
+
}
|
|
4784
|
+
};
|
|
4785
|
+
|
|
872
4786
|
// src/mocks.ts
|
|
873
4787
|
var DEV_FIXTURE_USER = Object.freeze({
|
|
874
4788
|
uid: "dev-fixture-uid-0001",
|
|
@@ -1004,14 +4918,14 @@ var MockUsage = class {
|
|
|
1004
4918
|
this._counters.clear();
|
|
1005
4919
|
}
|
|
1006
4920
|
};
|
|
1007
|
-
var mockTicketSeq = 0;
|
|
1008
4921
|
var MockSupport = class {
|
|
1009
4922
|
_tickets = [];
|
|
4923
|
+
_ticketSeq = 0;
|
|
1010
4924
|
async createTicket(input) {
|
|
1011
4925
|
if (!input?.subject) throw new Error("subject required");
|
|
1012
4926
|
if (!input?.message) throw new Error("message required");
|
|
1013
4927
|
const ticket = {
|
|
1014
|
-
id: `mock-ticket-${++
|
|
4928
|
+
id: `mock-ticket-${++this._ticketSeq}`,
|
|
1015
4929
|
subject: input.subject,
|
|
1016
4930
|
message: input.message,
|
|
1017
4931
|
severity: input.severity ?? "normal",
|
|
@@ -1028,6 +4942,7 @@ var MockSupport = class {
|
|
|
1028
4942
|
/** Test helper. */
|
|
1029
4943
|
__reset() {
|
|
1030
4944
|
this._tickets = [];
|
|
4945
|
+
this._ticketSeq = 0;
|
|
1031
4946
|
}
|
|
1032
4947
|
};
|
|
1033
4948
|
var MockEntitlements = class {
|
|
@@ -1087,24 +5002,61 @@ var MockDb = class {
|
|
|
1087
5002
|
return typeof v === "number" && typeof f.value === "number" && v >= f.value;
|
|
1088
5003
|
case "in":
|
|
1089
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);
|
|
1090
5009
|
default:
|
|
1091
5010
|
return true;
|
|
1092
5011
|
}
|
|
1093
5012
|
};
|
|
1094
5013
|
let autoSeq = 0;
|
|
1095
|
-
|
|
1096
|
-
|
|
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) {
|
|
1097
5035
|
let items = Array.from(coll.values());
|
|
1098
|
-
if (
|
|
5036
|
+
if (q?.where && q.where.length > 0) {
|
|
1099
5037
|
items = items.filter(
|
|
1100
|
-
(doc) =>
|
|
5038
|
+
(doc) => q.where.every((f) => matchesFilter(doc, f))
|
|
1101
5039
|
);
|
|
1102
5040
|
}
|
|
1103
|
-
if (
|
|
1104
|
-
|
|
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);
|
|
1105
5055
|
},
|
|
1106
5056
|
async get(id) {
|
|
1107
|
-
|
|
5057
|
+
const data = coll.get(id);
|
|
5058
|
+
if (!data) return null;
|
|
5059
|
+
return buildGetResult(data, id);
|
|
1108
5060
|
},
|
|
1109
5061
|
async add(data) {
|
|
1110
5062
|
const id = `mock-${++autoSeq}-${Math.random().toString(36).slice(2, 8)}`;
|
|
@@ -1127,8 +5079,103 @@ var MockDb = class {
|
|
|
1127
5079
|
async remove(id) {
|
|
1128
5080
|
coll.delete(id);
|
|
1129
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
|
+
};
|
|
1130
5150
|
}
|
|
1131
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 [];
|
|
1132
5179
|
}
|
|
1133
5180
|
/** Test helper — substitui fixture inteira de uma collection. */
|
|
1134
5181
|
__setFixture(name, items) {
|
|
@@ -1250,7 +5297,9 @@ function createOidcAuthNamespace(config) {
|
|
|
1250
5297
|
if (storage) storage.removeItem(STORAGE_KEY);
|
|
1251
5298
|
cachedUser = null;
|
|
1252
5299
|
try {
|
|
1253
|
-
|
|
5300
|
+
const overrideAuthUrl = typeof globalThis.NEETRU_AUTH_URL === "string" ? globalThis.NEETRU_AUTH_URL : null;
|
|
5301
|
+
const idpOrigin = overrideAuthUrl ?? config.baseUrl.replace(/^https?:\/\/api\./, "https://auth.");
|
|
5302
|
+
await config.fetch(`${idpOrigin}/api/v1/oauth/revoke`, {
|
|
1254
5303
|
method: "POST",
|
|
1255
5304
|
headers: { "content-type": "application/json" }
|
|
1256
5305
|
});
|
|
@@ -1297,7 +5346,9 @@ function createNeetruClient(config = {}) {
|
|
|
1297
5346
|
const usage = config.mocks?.usage ?? (isDev ? new MockUsage() : createUsageNamespace(resolved));
|
|
1298
5347
|
const support = config.mocks?.support ?? (isDev ? new MockSupport() : createSupportNamespace(resolved));
|
|
1299
5348
|
const entitlements = config.mocks?.entitlements ?? (isDev ? new MockEntitlements() : createEntitlementsNamespace(resolved));
|
|
1300
|
-
const db = config.mocks?.db ?? (
|
|
5349
|
+
const db = config.mocks?.db ?? createNeetruDb(resolved, config.db);
|
|
5350
|
+
const webhooks = config.mocks?.webhooks ?? (isDev ? new MockWebhooks() : createWebhooksNamespace(resolved));
|
|
5351
|
+
const notifications = config.mocks?.notifications ?? (isDev ? new MockNotifications() : createNotificationsNamespace(resolved));
|
|
1301
5352
|
const client = Object.freeze({
|
|
1302
5353
|
config: resolved,
|
|
1303
5354
|
auth,
|
|
@@ -1307,18 +5358,21 @@ function createNeetruClient(config = {}) {
|
|
|
1307
5358
|
usage,
|
|
1308
5359
|
support,
|
|
1309
5360
|
db,
|
|
1310
|
-
checkout: createCheckoutNamespace(resolved)
|
|
5361
|
+
checkout: createCheckoutNamespace(resolved),
|
|
5362
|
+
webhooks,
|
|
5363
|
+
notifications
|
|
1311
5364
|
});
|
|
1312
5365
|
return client;
|
|
1313
5366
|
}
|
|
1314
5367
|
|
|
1315
5368
|
// src/index.ts
|
|
1316
|
-
|
|
5369
|
+
init_errors();
|
|
5370
|
+
var VERSION = "2.0.0";
|
|
1317
5371
|
function initNeetru(config) {
|
|
1318
|
-
const { apiUrl, baseUrl, ...rest } = config;
|
|
1319
|
-
return createNeetruClient({ ...rest, baseUrl
|
|
5372
|
+
const { apiUrl: _apiUrl, baseUrl, ...rest } = config;
|
|
5373
|
+
return createNeetruClient({ ...rest, baseUrl });
|
|
1320
5374
|
}
|
|
1321
5375
|
|
|
1322
|
-
export { DEFAULT_BASE_URL, DEV_FIXTURE_USER, MockAuth, MockCheckout, MockDb, MockEntitlements, MockSupport, MockUsage, NeetruError, VERSION, createCheckoutNamespace, createNeetruClient, 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 };
|
|
1323
5377
|
//# sourceMappingURL=index.mjs.map
|
|
1324
5378
|
//# sourceMappingURL=index.mjs.map
|