@neetru/sdk 3.0.2 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +554 -530
  2. package/dist/auth.cjs +219 -54
  3. package/dist/auth.cjs.map +1 -1
  4. package/dist/auth.d.cts +1 -2
  5. package/dist/auth.d.ts +1 -2
  6. package/dist/auth.mjs +219 -54
  7. package/dist/auth.mjs.map +1 -1
  8. package/dist/catalog.cjs +50 -2
  9. package/dist/catalog.cjs.map +1 -1
  10. package/dist/catalog.d.cts +1 -2
  11. package/dist/catalog.d.ts +1 -2
  12. package/dist/catalog.mjs +50 -2
  13. package/dist/catalog.mjs.map +1 -1
  14. package/dist/checkout.cjs +52 -3
  15. package/dist/checkout.cjs.map +1 -1
  16. package/dist/checkout.d.cts +1 -2
  17. package/dist/checkout.d.ts +1 -2
  18. package/dist/checkout.mjs +52 -3
  19. package/dist/checkout.mjs.map +1 -1
  20. package/dist/db-react.cjs +18 -6
  21. package/dist/db-react.cjs.map +1 -1
  22. package/dist/db-react.d.cts +35 -13
  23. package/dist/db-react.d.ts +35 -13
  24. package/dist/db-react.mjs +18 -6
  25. package/dist/db-react.mjs.map +1 -1
  26. package/dist/db.cjs +164 -56
  27. package/dist/db.cjs.map +1 -1
  28. package/dist/db.d.cts +1 -2
  29. package/dist/db.d.ts +1 -2
  30. package/dist/db.mjs +164 -56
  31. package/dist/db.mjs.map +1 -1
  32. package/dist/entitlements.cjs +50 -2
  33. package/dist/entitlements.cjs.map +1 -1
  34. package/dist/entitlements.d.cts +1 -2
  35. package/dist/entitlements.d.ts +1 -2
  36. package/dist/entitlements.mjs +50 -2
  37. package/dist/entitlements.mjs.map +1 -1
  38. package/dist/errors.cjs.map +1 -1
  39. package/dist/errors.d.cts +3 -1
  40. package/dist/errors.d.ts +3 -1
  41. package/dist/errors.mjs.map +1 -1
  42. package/dist/firestore-compat.cjs +411 -0
  43. package/dist/firestore-compat.cjs.map +1 -0
  44. package/dist/firestore-compat.d.cts +319 -0
  45. package/dist/firestore-compat.d.ts +319 -0
  46. package/dist/firestore-compat.mjs +383 -0
  47. package/dist/firestore-compat.mjs.map +1 -0
  48. package/dist/index.cjs +266 -66
  49. package/dist/index.cjs.map +1 -1
  50. package/dist/index.d.cts +9 -4
  51. package/dist/index.d.ts +9 -4
  52. package/dist/index.mjs +265 -67
  53. package/dist/index.mjs.map +1 -1
  54. package/dist/mocks.cjs.map +1 -1
  55. package/dist/mocks.d.cts +1 -2
  56. package/dist/mocks.d.ts +1 -2
  57. package/dist/mocks.mjs.map +1 -1
  58. package/dist/notifications.cjs +50 -2
  59. package/dist/notifications.cjs.map +1 -1
  60. package/dist/notifications.d.cts +1 -2
  61. package/dist/notifications.d.ts +1 -2
  62. package/dist/notifications.mjs +50 -2
  63. package/dist/notifications.mjs.map +1 -1
  64. package/dist/react.cjs +268 -2
  65. package/dist/react.cjs.map +1 -1
  66. package/dist/react.d.cts +135 -3
  67. package/dist/react.d.ts +135 -3
  68. package/dist/react.mjs +266 -3
  69. package/dist/react.mjs.map +1 -1
  70. package/dist/support.cjs +50 -2
  71. package/dist/support.cjs.map +1 -1
  72. package/dist/support.d.cts +1 -2
  73. package/dist/support.d.ts +1 -2
  74. package/dist/support.mjs +50 -2
  75. package/dist/support.mjs.map +1 -1
  76. package/dist/telemetry.cjs +65 -4
  77. package/dist/telemetry.cjs.map +1 -1
  78. package/dist/telemetry.d.cts +1 -2
  79. package/dist/telemetry.d.ts +1 -2
  80. package/dist/telemetry.mjs +65 -4
  81. package/dist/telemetry.mjs.map +1 -1
  82. package/dist/{types-D7zVkO3n.d.ts → types-B3XFHD4A.d.ts} +640 -2
  83. package/dist/{types-Dc4bjrrt.d.cts → types-DePdSU3P.d.cts} +640 -2
  84. package/dist/usage.cjs +50 -2
  85. package/dist/usage.cjs.map +1 -1
  86. package/dist/usage.d.cts +1 -2
  87. package/dist/usage.d.ts +1 -2
  88. package/dist/usage.mjs +50 -2
  89. package/dist/usage.mjs.map +1 -1
  90. package/dist/webhooks.cjs +83 -2
  91. package/dist/webhooks.cjs.map +1 -1
  92. package/dist/webhooks.d.cts +1 -2
  93. package/dist/webhooks.d.ts +1 -2
  94. package/dist/webhooks.mjs +83 -3
  95. package/dist/webhooks.mjs.map +1 -1
  96. package/package.json +156 -151
  97. package/dist/collection-ref-BDdfD87k.d.cts +0 -581
  98. package/dist/collection-ref-BDdfD87k.d.ts +0 -581
package/dist/auth.d.cts CHANGED
@@ -1,5 +1,4 @@
1
- import { o as NeetruClientConfig, N as NeetruClient } from './types-Dc4bjrrt.cjs';
2
- import './collection-ref-BDdfD87k.cjs';
1
+ import { B as NeetruClientConfig, z as NeetruClient } from './types-DePdSU3P.cjs';
3
2
  import 'drizzle-orm/node-postgres';
4
3
  import './errors.cjs';
5
4
 
package/dist/auth.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { o as NeetruClientConfig, N as NeetruClient } from './types-D7zVkO3n.js';
2
- import './collection-ref-BDdfD87k.js';
1
+ import { B as NeetruClientConfig, z as NeetruClient } from './types-B3XFHD4A.js';
3
2
  import 'drizzle-orm/node-postgres';
4
3
  import './errors.js';
5
4
 
package/dist/auth.mjs CHANGED
@@ -51,8 +51,47 @@ var init_idempotency = __esm({
51
51
  // src/http.ts
52
52
  var http_exports = {};
53
53
  __export(http_exports, {
54
+ checkCoreVersionCompat: () => checkCoreVersionCompat,
54
55
  httpRequest: () => httpRequest
55
56
  });
57
+ function stripRevision(v) {
58
+ return v.split("+")[0] ?? v;
59
+ }
60
+ function compareCalVer(a, b) {
61
+ const partsA = stripRevision(a).split(".").map(Number);
62
+ const partsB = stripRevision(b).split(".").map(Number);
63
+ const len = Math.max(partsA.length, partsB.length);
64
+ for (let i = 0; i < len; i++) {
65
+ const pa = partsA[i] ?? 0;
66
+ const pb = partsB[i] ?? 0;
67
+ if (pa !== pb) return pa - pb;
68
+ }
69
+ return 0;
70
+ }
71
+ function getSdkMajor() {
72
+ try {
73
+ const ver = globalThis.__NEETRU_SDK_VERSION__;
74
+ if (ver) return parseInt(ver.split(".")[0] ?? "3", 10);
75
+ } catch {
76
+ }
77
+ return 3;
78
+ }
79
+ function checkCoreVersionCompat(coreVersion) {
80
+ if (!coreVersion) return;
81
+ const sdkMajor = getSdkMajor();
82
+ const minCore = COMPAT_MATRIX[sdkMajor];
83
+ if (!minCore) return;
84
+ const stripped = stripRevision(coreVersion);
85
+ if (compareCalVer(stripped, minCore) < 0) {
86
+ const key = `${sdkMajor}:${stripped}`;
87
+ if (!_warnedCoreTooOld.has(key)) {
88
+ _warnedCoreTooOld.add(key);
89
+ console.warn(
90
+ `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${coreVersion}" \xE9 anterior ao m\xEDnimo recomendado "${minCore}" para SDK major ${sdkMajor}. Alguns recursos podem n\xE3o funcionar corretamente. Atualize o Core para a vers\xE3o mais recente.`
91
+ );
92
+ }
93
+ }
94
+ }
56
95
  function backoffMs(attempt) {
57
96
  const base = 200 * Math.pow(4, attempt);
58
97
  const jitter = base * 0.2 * (Math.random() * 2 - 1);
@@ -61,11 +100,11 @@ function backoffMs(attempt) {
61
100
  function parseRetryAfter(value) {
62
101
  if (!value) return null;
63
102
  const secs = Number(value);
64
- if (Number.isFinite(secs) && secs >= 0) return Math.round(secs * 1e3);
103
+ if (Number.isFinite(secs) && secs >= 0) return Math.min(Math.round(secs * 1e3), MAX_RETRY_AFTER_MS);
65
104
  const dateMs = Date.parse(value);
66
105
  if (Number.isFinite(dateMs)) {
67
106
  const delta = dateMs - Date.now();
68
- if (delta > 0) return delta;
107
+ if (delta > 0) return Math.min(delta, MAX_RETRY_AFTER_MS);
69
108
  }
70
109
  return null;
71
110
  }
@@ -76,6 +115,7 @@ function statusToCode(status) {
76
115
  if (status === 401) return "unauthorized";
77
116
  if (status === 403) return "forbidden";
78
117
  if (status === 404) return "not_found";
118
+ if (status === 409) return "conflict";
79
119
  if (status === 422 || status === 400) return "validation_failed";
80
120
  if (status === 429) return "rate_limited";
81
121
  if (status >= 500) return "server_error";
@@ -147,6 +187,8 @@ async function httpRequest(config, opts) {
147
187
  }
148
188
  const requestId = res.headers.get("x-request-id") ?? res.headers.get("x-correlation-id") ?? void 0;
149
189
  if (res.ok) {
190
+ const coreVersion = res.headers.get("x-neetru-version");
191
+ if (coreVersion) checkCoreVersionCompat(coreVersion);
150
192
  const parsed = await safeJson(res);
151
193
  return parsed;
152
194
  }
@@ -175,11 +217,17 @@ async function httpRequest(config, opts) {
175
217
  }
176
218
  throw lastError ?? new NeetruError("unknown", "unexpected httpRequest exit");
177
219
  }
178
- var DEFAULT_RETRIES_READ, DEFAULT_RETRIES_WRITE, READ_METHODS, RETRYABLE_CODES;
220
+ var COMPAT_MATRIX, _warnedCoreTooOld, DEFAULT_RETRIES_READ, DEFAULT_RETRIES_WRITE, READ_METHODS, RETRYABLE_CODES, MAX_RETRY_AFTER_MS;
179
221
  var init_http = __esm({
180
222
  "src/http.ts"() {
181
223
  init_errors();
182
224
  init_idempotency();
225
+ COMPAT_MATRIX = {
226
+ // SDK major 3.x requer Core ≥ 2026.05.1 (suporte a X-Neetru-Version header,
227
+ // runTransaction write-after-read, verifyWebhookRequest, webhooks 3.0+)
228
+ 3: "2026.05.1"
229
+ };
230
+ _warnedCoreTooOld = /* @__PURE__ */ new Set();
183
231
  DEFAULT_RETRIES_READ = 2;
184
232
  DEFAULT_RETRIES_WRITE = 0;
185
233
  READ_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
@@ -188,6 +236,7 @@ var init_http = __esm({
188
236
  "server_error",
189
237
  "network_error"
190
238
  ]);
239
+ MAX_RETRY_AFTER_MS = 6e4;
191
240
  }
192
241
  });
193
242
 
@@ -889,11 +938,11 @@ var TRACK_MAX_QUEUE = 50;
889
938
  function createTelemetryNamespace(config) {
890
939
  const queue = [];
891
940
  let flushTimer = null;
941
+ let _inflightDrain = null;
892
942
  async function drainQueue() {
893
943
  if (queue.length === 0) return;
894
944
  const batch = queue.splice(0, queue.length);
895
- flushTimer = null;
896
- await Promise.allSettled(
945
+ const work = Promise.allSettled(
897
946
  batch.map(async (ev) => {
898
947
  try {
899
948
  const body = { name: ev.name };
@@ -915,6 +964,14 @@ function createTelemetryNamespace(config) {
915
964
  }
916
965
  })
917
966
  );
967
+ _inflightDrain = work.then(() => {
968
+ _inflightDrain = null;
969
+ });
970
+ await work;
971
+ flushTimer = null;
972
+ if (queue.length > 0) {
973
+ scheduleFlush();
974
+ }
918
975
  }
919
976
  function scheduleFlush() {
920
977
  if (flushTimer) return;
@@ -977,6 +1034,10 @@ function createTelemetryNamespace(config) {
977
1034
  if (input.name.length > 128) return;
978
1035
  queue.push(input);
979
1036
  if (queue.length >= TRACK_MAX_QUEUE) {
1037
+ if (flushTimer) {
1038
+ clearTimeout(flushTimer);
1039
+ flushTimer = null;
1040
+ }
980
1041
  void drainQueue();
981
1042
  } else {
982
1043
  scheduleFlush();
@@ -991,6 +1052,7 @@ function createTelemetryNamespace(config) {
991
1052
  clearTimeout(flushTimer);
992
1053
  flushTimer = null;
993
1054
  }
1055
+ if (_inflightDrain) await _inflightDrain;
994
1056
  await drainQueue();
995
1057
  },
996
1058
  /**
@@ -1479,6 +1541,31 @@ var LocalStore = class {
1479
1541
  this.db?.close();
1480
1542
  this.db = null;
1481
1543
  }
1544
+ /**
1545
+ * Apaga completamente o banco IndexedDB e o recria do zero.
1546
+ *
1547
+ * Ao contrário de `close()` + `open()` (que reabre o banco existente sem
1548
+ * apagar dados), `clearAll()` chama `indexedDB.deleteDatabase(dbName)` e
1549
+ * só então chama `open()` — garantindo que nenhum documento, mutação ou
1550
+ * metadado sobrevive.
1551
+ *
1552
+ * BUG fix: `clearCache()` em `NeetruDbDocumentsImpl` chamava close+open,
1553
+ * que reabre o mesmo banco. `clearAll()` é o método correto.
1554
+ */
1555
+ async clearAll() {
1556
+ if (this.db !== null) {
1557
+ this.db.close();
1558
+ this.db = null;
1559
+ }
1560
+ await new Promise((resolve, reject) => {
1561
+ const req = indexedDB.deleteDatabase(this.dbName);
1562
+ req.onsuccess = () => resolve();
1563
+ req.onerror = () => reject(req.error);
1564
+ req.onblocked = () => {
1565
+ };
1566
+ });
1567
+ await this.open();
1568
+ }
1482
1569
  assertOpen() {
1483
1570
  if (this.db === null) {
1484
1571
  throw new Error("LocalStore: banco n\xE3o est\xE1 aberto. Chame open() primeiro.");
@@ -1686,6 +1773,12 @@ var MemoryStore = class {
1686
1773
  async open() {
1687
1774
  }
1688
1775
  async close() {
1776
+ }
1777
+ /**
1778
+ * Apaga todos os dados em memória — equivalente ao `indexedDB.deleteDatabase`
1779
+ * que `LocalStore.clearAll()` executa em ambientes com IndexedDB.
1780
+ */
1781
+ async clearAll() {
1689
1782
  this._docs.clear();
1690
1783
  this._mutations.clear();
1691
1784
  this._meta.clear();
@@ -2041,7 +2134,60 @@ var MutationQueue = class {
2041
2134
  }
2042
2135
  };
2043
2136
 
2137
+ // src/db/field-value.ts
2138
+ var NEETRU_SENTINEL_KEY = "__neetru__";
2139
+ function isFieldSentinel(v) {
2140
+ return typeof v === "object" && v !== null && NEETRU_SENTINEL_KEY in v && typeof v[NEETRU_SENTINEL_KEY] === "string";
2141
+ }
2142
+ function isServerTimestampSentinel(v) {
2143
+ return isFieldSentinel(v) && v.__neetru__ === "serverTimestamp";
2144
+ }
2145
+ function isIncrementSentinel(v) {
2146
+ return isFieldSentinel(v) && v.__neetru__ === "increment" && typeof v.operand === "number" && Number.isFinite(v.operand);
2147
+ }
2148
+ function resolveSentinelLocally(value, baseValue) {
2149
+ if (isServerTimestampSentinel(value)) {
2150
+ return Date.now();
2151
+ }
2152
+ if (isIncrementSentinel(value)) {
2153
+ const base = typeof baseValue === "number" && Number.isFinite(baseValue) ? baseValue : 0;
2154
+ return base + value.operand;
2155
+ }
2156
+ return value;
2157
+ }
2158
+ function resolveSentinelsLocally(data, existing) {
2159
+ let touched = false;
2160
+ const out = {};
2161
+ for (const [k, v] of Object.entries(data)) {
2162
+ if (isFieldSentinel(v)) {
2163
+ touched = true;
2164
+ out[k] = resolveSentinelLocally(v, existing?.[k]);
2165
+ } else {
2166
+ out[k] = v;
2167
+ }
2168
+ }
2169
+ return touched ? out : data;
2170
+ }
2171
+ function hasFieldSentinel(data) {
2172
+ for (const v of Object.values(data)) {
2173
+ if (isFieldSentinel(v)) return true;
2174
+ }
2175
+ return false;
2176
+ }
2177
+
2044
2178
  // src/db/offline/sync-engine.ts
2179
+ function hasSentinels(payload) {
2180
+ return payload !== null && hasFieldSentinel(payload);
2181
+ }
2182
+ function sanitizeSentinelPayload(payload) {
2183
+ if (payload === null) return null;
2184
+ if (!hasFieldSentinel(payload)) return payload;
2185
+ const out = {};
2186
+ for (const [k, v] of Object.entries(payload)) {
2187
+ if (!isFieldSentinel(v)) out[k] = v;
2188
+ }
2189
+ return out;
2190
+ }
2045
2191
  var SyncEngine = class {
2046
2192
  _store;
2047
2193
  _queue;
@@ -2147,6 +2293,8 @@ var SyncEngine = class {
2147
2293
  const phase1Ok = await this._phase1Push();
2148
2294
  if (!phase1Ok) {
2149
2295
  this._updateState({ status: "idle" });
2296
+ this._refreshPendingWrites().catch(() => {
2297
+ });
2150
2298
  this._syncing = false;
2151
2299
  return;
2152
2300
  }
@@ -2249,11 +2397,16 @@ var SyncEngine = class {
2249
2397
  }
2250
2398
  return;
2251
2399
  }
2252
- const newData = mut.payload ?? (existing?.data ?? {});
2400
+ const literalPayload = sanitizeSentinelPayload(mut.payload);
2401
+ const newData = literalPayload ?? (existing?.data ?? {});
2253
2402
  const updatedDoc = {
2254
2403
  collection,
2255
2404
  id: docId,
2256
- data: mut.op === "update" ? { ...existing?.data ?? {}, ...newData } : newData,
2405
+ data: mut.op === "update" ? { ...existing?.data ?? {}, ...newData } : (
2406
+ // add/set: se o payload tinha sentinels, o cache otimista (existing.data)
2407
+ // é a fonte de verdade até o pull; senão usa o payload literal.
2408
+ hasSentinels(mut.payload) ? { ...existing?.data ?? {}, ...newData } : newData
2409
+ ),
2257
2410
  meta: {
2258
2411
  serverVersion,
2259
2412
  updatedAtServer: serverTimestamp,
@@ -2528,7 +2681,7 @@ var SyncEngine = class {
2528
2681
  ownerId: localDoc.meta.ownerId
2529
2682
  }
2530
2683
  };
2531
- const pendingMuts = await this._queue.drain();
2684
+ const pendingMuts = await this._queue.listAll();
2532
2685
  const docMut = pendingMuts.find(
2533
2686
  (m) => m.collection === serverDoc.collection && m.docId === serverDoc.id
2534
2687
  );
@@ -3335,43 +3488,6 @@ var TabCoordinator = class {
3335
3488
 
3336
3489
  // src/db/collection-ref.ts
3337
3490
  init_db_errors();
3338
-
3339
- // src/db/field-value.ts
3340
- var NEETRU_SENTINEL_KEY = "__neetru__";
3341
- function isFieldSentinel(v) {
3342
- return typeof v === "object" && v !== null && NEETRU_SENTINEL_KEY in v && typeof v[NEETRU_SENTINEL_KEY] === "string";
3343
- }
3344
- function isServerTimestampSentinel(v) {
3345
- return isFieldSentinel(v) && v.__neetru__ === "serverTimestamp";
3346
- }
3347
- function isIncrementSentinel(v) {
3348
- return isFieldSentinel(v) && v.__neetru__ === "increment" && typeof v.operand === "number" && Number.isFinite(v.operand);
3349
- }
3350
- function resolveSentinelLocally(value, baseValue) {
3351
- if (isServerTimestampSentinel(value)) {
3352
- return Date.now();
3353
- }
3354
- if (isIncrementSentinel(value)) {
3355
- const base = typeof baseValue === "number" && Number.isFinite(baseValue) ? baseValue : 0;
3356
- return base + value.operand;
3357
- }
3358
- return value;
3359
- }
3360
- function resolveSentinelsLocally(data, existing) {
3361
- let touched = false;
3362
- const out = {};
3363
- for (const [k, v] of Object.entries(data)) {
3364
- if (isFieldSentinel(v)) {
3365
- touched = true;
3366
- out[k] = resolveSentinelLocally(v, existing?.[k]);
3367
- } else {
3368
- out[k] = v;
3369
- }
3370
- }
3371
- return touched ? out : data;
3372
- }
3373
-
3374
- // src/db/collection-ref.ts
3375
3491
  function isIndexedDBUnavailable() {
3376
3492
  return typeof indexedDB === "undefined" || typeof window === "undefined";
3377
3493
  }
@@ -3919,8 +4035,13 @@ var NeetruDbDocumentsImpl = class {
3919
4035
  return this._engine.flush();
3920
4036
  }
3921
4037
  async clearCache() {
3922
- await this._store.close();
3923
- await this._store.open();
4038
+ const storeWithClear = this._store;
4039
+ if (typeof storeWithClear.clearAll === "function") {
4040
+ await storeWithClear.clearAll();
4041
+ } else {
4042
+ await this._store.close();
4043
+ await this._store.open();
4044
+ }
3924
4045
  }
3925
4046
  async getConflicts() {
3926
4047
  return this._store.listConflicts();
@@ -4807,7 +4928,8 @@ function createHttpCheckoutNamespace(config) {
4807
4928
  method: "POST",
4808
4929
  path: "/api/v1/checkout/intents",
4809
4930
  body,
4810
- requireAuth: true
4931
+ requireAuth: true,
4932
+ idempotencyKey: true
4811
4933
  });
4812
4934
  const result = parseStartResponse(raw);
4813
4935
  const shouldRedirect = input.autoRedirect !== false;
@@ -5562,6 +5684,7 @@ function createOidcAuthNamespace(config) {
5562
5684
  const STORAGE_KEY = "neetru_id_token";
5563
5685
  const listeners = /* @__PURE__ */ new Set();
5564
5686
  let cachedUser = null;
5687
+ let _expiryTimerId = null;
5565
5688
  function getStorage() {
5566
5689
  try {
5567
5690
  return typeof globalThis.localStorage !== "undefined" ? globalThis.localStorage : null;
@@ -5584,6 +5707,9 @@ function createOidcAuthNamespace(config) {
5584
5707
  function tokenToUser(token) {
5585
5708
  const payload = decodeJwtPayload(token);
5586
5709
  if (!payload || typeof payload.sub !== "string") return null;
5710
+ if (typeof payload.exp === "number" && payload.exp * 1e3 < Date.now()) {
5711
+ return null;
5712
+ }
5587
5713
  return {
5588
5714
  uid: payload.sub,
5589
5715
  email: typeof payload.email === "string" ? payload.email : "",
@@ -5597,12 +5723,28 @@ function createOidcAuthNamespace(config) {
5597
5723
  };
5598
5724
  }
5599
5725
  function loadCachedUser() {
5600
- if (cachedUser) return cachedUser;
5726
+ if (cachedUser) {
5727
+ const exp = cachedUser.exp;
5728
+ if (typeof exp === "number" && exp * 1e3 < Date.now()) {
5729
+ cachedUser = null;
5730
+ const storage2 = getStorage();
5731
+ storage2?.removeItem(STORAGE_KEY);
5732
+ notify();
5733
+ return null;
5734
+ }
5735
+ return cachedUser;
5736
+ }
5601
5737
  const storage = getStorage();
5602
5738
  if (!storage) return null;
5603
5739
  const token = storage.getItem(STORAGE_KEY);
5604
5740
  if (!token) return null;
5605
- cachedUser = tokenToUser(token);
5741
+ const user = tokenToUser(token);
5742
+ if (!user) {
5743
+ storage.removeItem(STORAGE_KEY);
5744
+ return null;
5745
+ }
5746
+ cachedUser = user;
5747
+ scheduleExpiryTimer(user);
5606
5748
  return cachedUser;
5607
5749
  }
5608
5750
  function notify() {
@@ -5613,6 +5755,23 @@ function createOidcAuthNamespace(config) {
5613
5755
  }
5614
5756
  }
5615
5757
  }
5758
+ function cancelExpiryTimer() {
5759
+ if (_expiryTimerId !== null) {
5760
+ clearTimeout(_expiryTimerId);
5761
+ _expiryTimerId = null;
5762
+ }
5763
+ }
5764
+ function scheduleExpiryTimer(user) {
5765
+ cancelExpiryTimer();
5766
+ const exp = user.exp;
5767
+ if (typeof exp !== "number") return;
5768
+ const msUntilExpiry = exp * 1e3 - Date.now();
5769
+ if (msUntilExpiry <= 0) return;
5770
+ _expiryTimerId = setTimeout(() => {
5771
+ _expiryTimerId = null;
5772
+ loadCachedUser();
5773
+ }, msUntilExpiry + 1);
5774
+ }
5616
5775
  return {
5617
5776
  async signIn(options) {
5618
5777
  if (typeof globalThis.location !== "undefined" && typeof globalThis.location.assign === "function") {
@@ -5640,18 +5799,24 @@ function createOidcAuthNamespace(config) {
5640
5799
  },
5641
5800
  async signOut() {
5642
5801
  const storage = getStorage();
5802
+ const storedToken = storage?.getItem(STORAGE_KEY) ?? null;
5643
5803
  if (storage) storage.removeItem(STORAGE_KEY);
5804
+ cancelExpiryTimer();
5644
5805
  cachedUser = null;
5645
5806
  const overrideAuthUrl = typeof globalThis.NEETRU_AUTH_URL === "string" ? globalThis.NEETRU_AUTH_URL : null;
5646
5807
  const idpOrigin = overrideAuthUrl ?? config.baseUrl.replace(/^https?:\/\/api\./, "https://auth.");
5647
5808
  const revokeUrl = `${idpOrigin}/api/v1/oauth/revoke`;
5809
+ const revokeBody = storedToken ? JSON.stringify({ token: storedToken }) : null;
5648
5810
  let revokeError = null;
5649
5811
  for (let attempt = 0; attempt < 2; attempt++) {
5650
5812
  try {
5651
- await config.fetch(revokeUrl, {
5652
- method: "POST",
5653
- headers: { "content-type": "application/json" }
5654
- });
5813
+ if (revokeBody) {
5814
+ await config.fetch(revokeUrl, {
5815
+ method: "POST",
5816
+ headers: { "content-type": "application/json" },
5817
+ body: revokeBody
5818
+ });
5819
+ }
5655
5820
  revokeError = null;
5656
5821
  break;
5657
5822
  } catch (err) {