tevrocsdk 0.1.33 → 0.1.35

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/tevroc-sdk.umd.js CHANGED
@@ -1,8 +1,16 @@
1
1
  var Tevroc = (() => {
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined") return require.apply(this, arguments);
12
+ throw Error('Dynamic require of "' + x + '" is not supported');
13
+ });
6
14
  var __esm = (fn, res, err) => function __init() {
7
15
  if (err) throw err[0];
8
16
  try {
@@ -23,6 +31,14 @@ var Tevroc = (() => {
23
31
  }
24
32
  return to;
25
33
  };
34
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
35
+ // If the importer is in node compatibility mode or this is not an ESM
36
+ // file that has been converted to a CommonJS file using a Babel-
37
+ // compatible transform (i.e. "__esModule" has not been set), then set
38
+ // "default" to the CommonJS "module.exports" for node compatibility.
39
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
40
+ mod
41
+ ));
26
42
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
43
 
28
44
  // src/services/usePlatform.js
@@ -2199,6 +2215,10 @@ var Tevroc = (() => {
2199
2215
  });
2200
2216
 
2201
2217
  // node_modules/@capacitor/app/dist/esm/index.js
2218
+ var esm_exports2 = {};
2219
+ __export(esm_exports2, {
2220
+ App: () => App
2221
+ });
2202
2222
  var App;
2203
2223
  var init_esm2 = __esm({
2204
2224
  "node_modules/@capacitor/app/dist/esm/index.js"() {
@@ -5039,6 +5059,12 @@ var Tevroc = (() => {
5039
5059
  });
5040
5060
 
5041
5061
  // src/services/useGoogleAuth.js
5062
+ var useGoogleAuth_exports = {};
5063
+ __export(useGoogleAuth_exports, {
5064
+ createGoogleLogin: () => createGoogleLogin,
5065
+ initializeGoogleLogin: () => initializeGoogleLogin,
5066
+ subscribeGoogleLogin: () => subscribeGoogleLogin
5067
+ });
5042
5068
  function emitGoogleLogin(user, err = null) {
5043
5069
  googleListeners.forEach((cb) => {
5044
5070
  try {
@@ -5055,7 +5081,7 @@ var Tevroc = (() => {
5055
5081
  if (i !== -1) googleListeners.splice(i, 1);
5056
5082
  };
5057
5083
  }
5058
- var googleInitialized, googleListeners, authWindowRef, handleCallback, initializeGoogleLogin, createGoogleLogin;
5084
+ var googleInitialized, googleListeners, authWindowRef, authCleanupTimer, authMessageListener, cleanupAuthWindow, handleCallback, initializeGoogleLogin, createGoogleLogin;
5059
5085
  var init_useGoogleAuth = __esm({
5060
5086
  "src/services/useGoogleAuth.js"() {
5061
5087
  init_esm2();
@@ -5065,8 +5091,58 @@ var Tevroc = (() => {
5065
5091
  googleInitialized = false;
5066
5092
  googleListeners = [];
5067
5093
  authWindowRef = null;
5094
+ authCleanupTimer = null;
5095
+ authMessageListener = null;
5096
+ cleanupAuthWindow = async () => {
5097
+ if (authCleanupTimer) {
5098
+ clearInterval(authCleanupTimer);
5099
+ authCleanupTimer = null;
5100
+ }
5101
+ if (authMessageListener && typeof window !== "undefined") {
5102
+ window.removeEventListener("message", authMessageListener);
5103
+ authMessageListener = null;
5104
+ }
5105
+ if (authWindowRef) {
5106
+ const currentAuthWindow = authWindowRef;
5107
+ authWindowRef = null;
5108
+ try {
5109
+ if (typeof currentAuthWindow?.close === "function") {
5110
+ await currentAuthWindow.close();
5111
+ }
5112
+ } catch (e) {
5113
+ console.warn("Error closing auth window:", e);
5114
+ }
5115
+ }
5116
+ if (isTauri) {
5117
+ try {
5118
+ const tauriAuthWindow = await WebviewWindow.getByLabel("auth");
5119
+ if (tauriAuthWindow && tauriAuthWindow !== authWindowRef) {
5120
+ await tauriAuthWindow.close();
5121
+ }
5122
+ } catch (e) {
5123
+ console.warn("Error closing Tauri auth window by label:", e);
5124
+ }
5125
+ }
5126
+ if (isCapacitor) {
5127
+ try {
5128
+ await Browser2.close();
5129
+ } catch (e) {
5130
+ console.warn("Error closing Capacitor browser:", e);
5131
+ }
5132
+ }
5133
+ if (typeof window !== "undefined" && window !== window.parent) {
5134
+ try {
5135
+ if (authWindowRef && typeof authWindowRef.close === "function") {
5136
+ await authWindowRef.close();
5137
+ }
5138
+ } catch (e) {
5139
+ console.warn("Error closing popup fallback:", e);
5140
+ }
5141
+ }
5142
+ };
5068
5143
  handleCallback = async (url) => {
5069
5144
  try {
5145
+ await cleanupAuthWindow();
5070
5146
  if (!url?.includes("token=")) return;
5071
5147
  const params = new URLSearchParams(url.split("?")[1]);
5072
5148
  const token = params.get("token");
@@ -5112,14 +5188,7 @@ var Tevroc = (() => {
5112
5188
  url = url?.url || url?.payload || null;
5113
5189
  }
5114
5190
  if (!url) return;
5115
- if (authWindowRef) {
5116
- try {
5117
- await authWindowRef.close();
5118
- authWindowRef = null;
5119
- } catch (e) {
5120
- }
5121
- }
5122
- handleCallback(url);
5191
+ await handleCallback(url);
5123
5192
  });
5124
5193
  }
5125
5194
  };
@@ -5171,21 +5240,21 @@ var Tevroc = (() => {
5171
5240
  console.error("Popup blocked");
5172
5241
  return;
5173
5242
  }
5174
- const listener = (event) => {
5175
- if (event.origin !== serviceUrl) return;
5243
+ authWindowRef = popup;
5244
+ authMessageListener = async (event) => {
5245
+ const serviceOrigin = new URL(serviceUrl).origin;
5246
+ if (event.origin !== serviceOrigin) return;
5176
5247
  if (event.data?.type === "google-auth") {
5177
5248
  const token = event.data?.token || null;
5178
5249
  const url = token ? `${window.location.href}${window.location.href.includes("?") ? "&" : "?"}token=${token}` : window.location.href;
5179
- popup.close();
5180
- window.removeEventListener("message", listener);
5181
- handleCallback(url);
5250
+ await handleCallback(url);
5182
5251
  }
5183
5252
  };
5184
- window.addEventListener("message", listener);
5185
- const timer = setInterval(() => {
5253
+ window.addEventListener("message", authMessageListener);
5254
+ authCleanupTimer = setInterval(() => {
5186
5255
  if (popup.closed) {
5187
- clearInterval(timer);
5188
- window.removeEventListener("message", listener);
5256
+ cleanupAuthWindow().catch(() => {
5257
+ });
5189
5258
  }
5190
5259
  }, 500);
5191
5260
  return;
@@ -5236,17 +5305,17 @@ var Tevroc = (() => {
5236
5305
  }) => {
5237
5306
  try {
5238
5307
  addLog("PAYMENT CALLBACK:", url);
5239
- if (!url?.includes("state=")) return;
5308
+ if (!url?.includes("status=")) return;
5240
5309
  const params = new URLSearchParams(url.split("?")[1]);
5241
- const state = params.get("state");
5242
- addLog("PAYMENT RESULT:", state);
5243
- if (state == "success") {
5310
+ const status = params.get("status");
5311
+ addLog("PAYMENT RESULT:", status);
5312
+ if (status == "success") {
5244
5313
  addLog("PAYMENT SUCCESS");
5245
5314
  } else {
5246
5315
  addLog("PAYMENT FAILED");
5247
5316
  }
5248
- externalCallback(state, null);
5249
- emitPaymentStatus(state, null);
5317
+ externalCallback(status, null);
5318
+ emitPaymentStatus(status, null);
5250
5319
  } catch (err) {
5251
5320
  addLog("PAYMENT CALLBACK ERROR:", err.message);
5252
5321
  externalCallback(null, err);
@@ -5290,13 +5359,15 @@ var Tevroc = (() => {
5290
5359
  createPayment = async (amountZAR, {
5291
5360
  appId = "tevrocsoft",
5292
5361
  serviceUrl = "https://tevrocsoftapi.netlify.app",
5362
+ payAccount = "default",
5293
5363
  externalCallback = () => {
5294
5364
  }
5295
5365
  } = {}) => {
5296
5366
  await initializePayment(externalCallback);
5297
5367
  const cents = Math.round(Number(amountZAR) * 100);
5298
- const basePaymentUrl = `${serviceUrl}/pay`;
5299
- const paymentUrl = `${basePaymentUrl}?mode=mobile&amount=${cents}&app=${appId}`;
5368
+ const basePaymentUrl = `${serviceUrl.replace(/\/$/, "")}/yoco-pay`;
5369
+ const paymentUrl = `${basePaymentUrl}?mode=mobile&amount=${cents}&app=${appId}&account=${payAccount}`;
5370
+ console.log(basePaymentUrl, paymentUrl);
5300
5371
  if (isCapacitor) {
5301
5372
  await Browser2.open({
5302
5373
  url: paymentUrl
@@ -5304,7 +5375,7 @@ var Tevroc = (() => {
5304
5375
  return;
5305
5376
  }
5306
5377
  if (isTauri) {
5307
- const url = `${basePaymentUrl}?mode=desktop&amount=${cents}&app=${appId}`;
5378
+ const url = `${basePaymentUrl}?mode=desktop&amount=${cents}&app=${appId}&account=${payAccount}`;
5308
5379
  const win = new WebviewWindow("payment", {
5309
5380
  url,
5310
5381
  title: "Complete Payment",
@@ -5324,7 +5395,55 @@ var Tevroc = (() => {
5324
5395
  }
5325
5396
  const isLocalhost = window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1";
5326
5397
  const mode = isLocalhost ? "localhost" : "netlify";
5327
- window.location.href = `${basePaymentUrl}?mode=${mode}&amount=${cents}&app=${appId}`;
5398
+ const finalUrl = `${basePaymentUrl}?mode=${mode}&amount=${cents}&app=${appId}`;
5399
+ try {
5400
+ const popup = window.open(finalUrl, "yocoPayment", "width=500,height=650");
5401
+ if (!popup) {
5402
+ window.location.href = finalUrl;
5403
+ return;
5404
+ }
5405
+ let listenerAttached = true;
5406
+ let timerRunning = true;
5407
+ const listener = (event) => {
5408
+ try {
5409
+ const serviceOrigin = new URL(serviceUrl).origin;
5410
+ if (event.origin !== serviceOrigin) return;
5411
+ if (event.data?.type === "payment-result") {
5412
+ const status = event.data?.status || null;
5413
+ listenerAttached = false;
5414
+ timerRunning = false;
5415
+ window.removeEventListener("message", listener);
5416
+ try {
5417
+ popup.close();
5418
+ } catch (e) {
5419
+ }
5420
+ const url = status ? `${window.location.href}${window.location.href.includes("?") ? "&" : "?"}status=${status}` : window.location.href;
5421
+ handlePaymentCallback(url, externalCallback);
5422
+ }
5423
+ } catch (err) {
5424
+ console.error("Payment listener error", err);
5425
+ }
5426
+ };
5427
+ window.addEventListener("message", listener);
5428
+ const timer = setInterval(() => {
5429
+ if (!timerRunning) {
5430
+ clearInterval(timer);
5431
+ return;
5432
+ }
5433
+ if (popup.closed) {
5434
+ clearInterval(timer);
5435
+ timerRunning = false;
5436
+ if (listenerAttached) {
5437
+ listenerAttached = false;
5438
+ window.removeEventListener("message", listener);
5439
+ }
5440
+ }
5441
+ }, 500);
5442
+ return;
5443
+ } catch (e) {
5444
+ window.location.href = finalUrl;
5445
+ return;
5446
+ }
5328
5447
  };
5329
5448
  }
5330
5449
  });
@@ -5868,6 +5987,252 @@ var Tevroc = (() => {
5868
5987
  };
5869
5988
  }
5870
5989
 
5990
+ // src/services/offline.js
5991
+ function createOfflineManager(client) {
5992
+ const store = createNativeStore(client.appId);
5993
+ const listeners2 = /* @__PURE__ */ new Map();
5994
+ async function getQueue() {
5995
+ const snapshot = await store.get("sync_queue");
5996
+ return snapshot.val() || [];
5997
+ }
5998
+ async function setQueue(q) {
5999
+ await store.set("sync_queue", q || []);
6000
+ }
6001
+ function isOnline() {
6002
+ try {
6003
+ if (typeof navigator !== "undefined" && typeof navigator.onLine !== "undefined") return navigator.onLine;
6004
+ } catch (e) {
6005
+ }
6006
+ try {
6007
+ return true;
6008
+ } catch (e) {
6009
+ return true;
6010
+ }
6011
+ }
6012
+ async function queueOperation(entity, op, recordId, payload) {
6013
+ const q = await getQueue();
6014
+ const item = { id: crypto.randomUUID?.() || String(Date.now()), entity, op, recordId, payload, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
6015
+ q.push(item);
6016
+ await setQueue(q);
6017
+ if (op === "create" || op === "update") {
6018
+ const id = recordId || payload?.id || `loc_${Date.now()}`;
6019
+ await store.set(`entities/${entity}/${id}`, { ...payload || {}, id });
6020
+ return { data: { ...payload || {}, id } };
6021
+ }
6022
+ if (op === "delete") {
6023
+ await store.remove(`entities/${entity}/${recordId}`);
6024
+ return { deleted: true, id: recordId };
6025
+ }
6026
+ return null;
6027
+ }
6028
+ async function syncOnce() {
6029
+ if (!isOnline()) return { ok: false, reason: "offline" };
6030
+ let q = await getQueue();
6031
+ if (!q || q.length === 0) return { ok: true, synced: 0 };
6032
+ emit2("sync:start", { count: q.length });
6033
+ for (const item of [...q]) {
6034
+ try {
6035
+ const localSnapshot = (await store.get(`entities/${item.entity}/${item.recordId || item.payload && item.payload.id || ""}`)).val();
6036
+ if (item.op === "create") {
6037
+ const res = await client.request(`/entities/${encodeURIComponent(item.entity)}`, { method: "POST", body: item.payload });
6038
+ const serverId = res?.data?.id || res?.id || item.recordId;
6039
+ if (serverId) {
6040
+ await store.set(`entities/${item.entity}/${serverId}`, res?.data || { ...item.payload || {}, id: serverId });
6041
+ }
6042
+ q = q.filter((qitem) => qitem.id !== item.id);
6043
+ emit2("sync:item", { item, result: res });
6044
+ } else if (item.op === "update") {
6045
+ const res = await client.request(`/entities/${encodeURIComponent(item.entity)}/${encodeURIComponent(item.recordId)}`, { method: "PATCH", body: item.payload });
6046
+ const serverData = res?.data ?? res;
6047
+ const serverUpdated = serverData?.updatedAt || serverData?.updated_date || null;
6048
+ const localUpdated = localSnapshot?.updatedAt || localSnapshot?.updated_date || null;
6049
+ if (localUpdated && serverUpdated && localUpdated > serverUpdated && JSON.stringify(localSnapshot) !== JSON.stringify(serverData)) {
6050
+ const conflictId = `${item.entity}/${item.recordId}`;
6051
+ await store.set(`conflicts/${conflictId}`, { local: localSnapshot, server: serverData, item });
6052
+ emit2("conflict", { conflictId, local: localSnapshot, server: serverData, item });
6053
+ } else {
6054
+ if (serverData) await store.set(`entities/${item.entity}/${item.recordId}`, serverData);
6055
+ q = q.filter((qitem) => qitem.id !== item.id);
6056
+ emit2("sync:item", { item, result: res });
6057
+ }
6058
+ } else if (item.op === "delete") {
6059
+ await client.request(`/entities/${encodeURIComponent(item.entity)}/${encodeURIComponent(item.recordId)}`, { method: "DELETE" });
6060
+ await store.remove(`entities/${item.entity}/${item.recordId}`);
6061
+ q = q.filter((qitem) => qitem.id !== item.id);
6062
+ emit2("sync:item", { item, result: { deleted: true } });
6063
+ }
6064
+ } catch (err) {
6065
+ console.warn("Sync failed for item", item, err);
6066
+ emit2("sync:error", { item, error: err });
6067
+ break;
6068
+ }
6069
+ }
6070
+ await setQueue(q);
6071
+ emit2("sync:end", { remaining: q.length });
6072
+ return { ok: true, synced: 0, remaining: q.length };
6073
+ }
6074
+ let autoInterval = null;
6075
+ let platformListeners = [];
6076
+ let capacitorNetwork = null;
6077
+ let capacitorApp = null;
6078
+ let lastNetworkStatus = null;
6079
+ function startAutoSync(intervalMs = 3e4) {
6080
+ if (typeof window !== "undefined") {
6081
+ const onOnline = () => syncOnce();
6082
+ window.addEventListener("online", onOnline);
6083
+ platformListeners.push(() => window.removeEventListener("online", onOnline));
6084
+ const onVis = () => {
6085
+ if (!document.hidden) syncOnce();
6086
+ };
6087
+ document.addEventListener("visibilitychange", onVis);
6088
+ platformListeners.push(() => document.removeEventListener("visibilitychange", onVis));
6089
+ const onFocus = () => syncOnce();
6090
+ window.addEventListener("focus", onFocus);
6091
+ platformListeners.push(() => window.removeEventListener("focus", onFocus));
6092
+ }
6093
+ (async () => {
6094
+ try {
6095
+ const netMod = await import("@capacitor/network");
6096
+ capacitorNetwork = netMod.Network || netMod;
6097
+ if (capacitorNetwork && capacitorNetwork.getStatus) {
6098
+ const st = await capacitorNetwork.getStatus();
6099
+ lastNetworkStatus = st.connected;
6100
+ const listener = capacitorNetwork.addListener("networkStatusChange", (status) => {
6101
+ lastNetworkStatus = status.connected;
6102
+ if (status.connected) syncOnce();
6103
+ });
6104
+ platformListeners.push(() => listener.remove());
6105
+ }
6106
+ } catch (e) {
6107
+ }
6108
+ try {
6109
+ const appMod = await Promise.resolve().then(() => (init_esm2(), esm_exports2));
6110
+ capacitorApp = appMod.App || appMod;
6111
+ if (capacitorApp && capacitorApp.addListener) {
6112
+ const sub = capacitorApp.addListener("appStateChange", (state) => {
6113
+ if (state.isActive) syncOnce();
6114
+ });
6115
+ platformListeners.push(() => sub.remove());
6116
+ try {
6117
+ const pauseSub = capacitorApp.addListener("pause", async () => {
6118
+ try {
6119
+ const bg = await import("@capacitor/background-task");
6120
+ const BackgroundTask = bg.BackgroundTask || bg;
6121
+ if (BackgroundTask && BackgroundTask.beforeExit) {
6122
+ const taskId = BackgroundTask.beforeExit(async () => {
6123
+ await syncOnce();
6124
+ try {
6125
+ BackgroundTask.finish({ taskId });
6126
+ } catch (e) {
6127
+ }
6128
+ });
6129
+ } else {
6130
+ await syncOnce();
6131
+ }
6132
+ } catch (e) {
6133
+ await syncOnce();
6134
+ }
6135
+ });
6136
+ platformListeners.push(() => pauseSub.remove());
6137
+ const resumeSub = capacitorApp.addListener("resume", async () => {
6138
+ await syncOnce();
6139
+ });
6140
+ platformListeners.push(() => resumeSub.remove());
6141
+ } catch (e) {
6142
+ }
6143
+ }
6144
+ } catch (e) {
6145
+ }
6146
+ try {
6147
+ if (typeof window !== "undefined" && (window.__TAURI__ || window.__TAURI_INTERNALS__)) {
6148
+ try {
6149
+ const tauriEvent = window.__TAURI__?.event;
6150
+ if (tauriEvent && tauriEvent.listen) {
6151
+ const unsub1 = await tauriEvent.listen("tauri://update", () => syncOnce()).catch(() => null);
6152
+ const unsub2 = await tauriEvent.listen("tauri://resume", () => syncOnce()).catch(() => null);
6153
+ if (unsub1) platformListeners.push(() => unsub1.then((u) => u()).catch(() => {
6154
+ }));
6155
+ if (unsub2) platformListeners.push(() => unsub2.then((u) => u()).catch(() => {
6156
+ }));
6157
+ }
6158
+ } catch (err) {
6159
+ }
6160
+ }
6161
+ } catch (e) {
6162
+ }
6163
+ })();
6164
+ if (!autoInterval) autoInterval = setInterval(() => syncOnce(), intervalMs);
6165
+ }
6166
+ function stopAutoSync() {
6167
+ for (const rm of platformListeners.splice(0)) {
6168
+ try {
6169
+ rm();
6170
+ } catch (e) {
6171
+ }
6172
+ }
6173
+ if (autoInterval) {
6174
+ clearInterval(autoInterval);
6175
+ autoInterval = null;
6176
+ }
6177
+ }
6178
+ function emit2(event, payload) {
6179
+ try {
6180
+ if (!listeners2.has(event)) return;
6181
+ for (const cb of listeners2.get(event)) {
6182
+ try {
6183
+ cb(payload);
6184
+ } catch (e) {
6185
+ console.warn("listener error", e);
6186
+ }
6187
+ }
6188
+ } catch (e) {
6189
+ }
6190
+ }
6191
+ return {
6192
+ store,
6193
+ isOnline,
6194
+ queueOperation,
6195
+ syncOnce,
6196
+ startAutoSync,
6197
+ stopAutoSync,
6198
+ getQueue,
6199
+ // events
6200
+ on: (event, cb) => {
6201
+ if (!listeners2.has(event)) listeners2.set(event, /* @__PURE__ */ new Set());
6202
+ listeners2.get(event).add(cb);
6203
+ return () => listeners2.get(event).delete(cb);
6204
+ },
6205
+ off: (event, cb) => {
6206
+ if (!listeners2.has(event)) return;
6207
+ listeners2.get(event).delete(cb);
6208
+ },
6209
+ listConflicts: async () => {
6210
+ const snapshot = await store.get("conflicts");
6211
+ return snapshot.val() || {};
6212
+ },
6213
+ resolveConflict: async (conflictId, resolution = "useServer") => {
6214
+ const parts = String(conflictId).split("/");
6215
+ const entity = parts.shift();
6216
+ const id = parts.join("/");
6217
+ const conflict = (await store.get(`conflicts/${conflictId}`)).val();
6218
+ if (!conflict) return null;
6219
+ if (resolution === "useServer") {
6220
+ await store.set(`entities/${entity}/${id}`, conflict.server);
6221
+ await store.remove(`conflicts/${conflictId}`);
6222
+ const q = await getQueue();
6223
+ await setQueue(q.filter((i) => !(i.entity === entity && String(i.recordId) === String(id))));
6224
+ return { applied: "server" };
6225
+ }
6226
+ if (resolution === "useLocal") {
6227
+ await queueOperation(entity, "update", id, conflict.local);
6228
+ await store.remove(`conflicts/${conflictId}`);
6229
+ return { requeued: true };
6230
+ }
6231
+ return null;
6232
+ }
6233
+ };
6234
+ }
6235
+
5871
6236
  // src/index.js
5872
6237
  init_useGoogleAuth();
5873
6238
  init_useYocoPayment();
@@ -5879,6 +6244,13 @@ var Tevroc = (() => {
5879
6244
  }
5880
6245
  return platformModule;
5881
6246
  }
6247
+ var googleModule = null;
6248
+ async function getGoogleModule() {
6249
+ if (!googleModule) {
6250
+ googleModule = await Promise.resolve().then(() => (init_useGoogleAuth(), useGoogleAuth_exports));
6251
+ }
6252
+ return googleModule;
6253
+ }
5882
6254
  var TevrocError = class extends Error {
5883
6255
  constructor(message, options = {}) {
5884
6256
  super(message);
@@ -5901,6 +6273,7 @@ var Tevroc = (() => {
5901
6273
  this.serviceUrl = normalizeBaseUrl(serviceUrl);
5902
6274
  this.appId = options.appId;
5903
6275
  this.appName = options.appName;
6276
+ this.payAccount = options.payAccount ?? "default";
5904
6277
  this.isNative = options.isNative ?? false;
5905
6278
  this.fetch = (options.fetch ?? globalThis.fetch).bind(globalThis);
5906
6279
  if (typeof this.fetch !== "function") {
@@ -5925,6 +6298,7 @@ var Tevroc = (() => {
5925
6298
  googleDrive: createGoogleDriveApi(this.appId),
5926
6299
  projects: createProjectStore(this.appId)
5927
6300
  };
6301
+ this.offline = createOfflineManager(this);
5928
6302
  this.payments = createPaymentApi(this);
5929
6303
  this.platform = createPlatformApi(this);
5930
6304
  }
@@ -5950,6 +6324,7 @@ var Tevroc = (() => {
5950
6324
  const controller = new AbortController();
5951
6325
  const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? this.timeoutMs);
5952
6326
  const token = this.token || getStoredToken();
6327
+ console.log(token, options);
5953
6328
  if (token && options.auth !== false) {
5954
6329
  headers.set("authorization", `Bearer ${token}`);
5955
6330
  }
@@ -5966,7 +6341,7 @@ var Tevroc = (() => {
5966
6341
  if (value !== void 0 && value !== null) headers.set(key, String(value));
5967
6342
  }
5968
6343
  }
5969
- console.log(headers, url);
6344
+ console.error(headers, url);
5970
6345
  try {
5971
6346
  const response = await this.fetch(url, {
5972
6347
  method,
@@ -5999,13 +6374,18 @@ var Tevroc = (() => {
5999
6374
  }
6000
6375
  function createPaymentApi(client) {
6001
6376
  return {
6002
- create: async ({ amountZAR, appId = "tevrocsoft", mode = "web" }) => {
6377
+ create: async ({ amountZAR, appId = "tevrocsoft", mode = "web", account = "default", externalCallback = void 0 } = {}) => {
6003
6378
  return await createPayment(amountZAR, {
6004
6379
  appId,
6005
6380
  serviceUrl: client.serviceUrl,
6006
- mode
6381
+ mode,
6382
+ payAccount: account,
6383
+ externalCallback
6007
6384
  });
6008
6385
  },
6386
+ createCheckout: async (payload = {}) => {
6387
+ return await client.request("/create-checkout", { method: "POST", body: payload, auth: false });
6388
+ },
6009
6389
  onstatus: (callback) => {
6010
6390
  if (typeof callback !== "function") {
6011
6391
  throw new Error("onstatus requires a function");
@@ -6017,31 +6397,83 @@ var Tevroc = (() => {
6017
6397
  function createAuthApi(client) {
6018
6398
  return {
6019
6399
  async register(input) {
6020
- const result = await client.request("/auth/register", { method: "POST", body: input, auth: false });
6400
+ const body = buildAuthPayload(input, client);
6401
+ const result = await client.request("/auth/register", { method: "POST", body, auth: false });
6021
6402
  if (result.token) client.setToken(result.token);
6022
6403
  return result;
6023
6404
  },
6405
+ // base44
6406
+ loginWithProvider: async (provider, redirectTo, setToken = async () => {
6407
+ }) => {
6408
+ if (provider === "google") {
6409
+ const { createGoogleLogin: createGoogleLogin2, subscribeGoogleLogin: subscribeGoogleLogin2 } = await getGoogleModule();
6410
+ console.log({
6411
+ serviceUrl: client.serviceUrl,
6412
+ appId: client.appId,
6413
+ appName: client.appName
6414
+ });
6415
+ createGoogleLogin2({
6416
+ serviceUrl: client.serviceUrl,
6417
+ appId: client.appId,
6418
+ appName: client.appName
6419
+ });
6420
+ if (redirectTo) {
6421
+ const unsub = subscribeGoogleLogin2(async (user, err) => {
6422
+ console.log("Google callback:", user, err);
6423
+ unsub();
6424
+ if (!user) return;
6425
+ const result = await client.request("/auth/google", {
6426
+ method: "POST",
6427
+ body: buildAuthPayload({ accessToken: user.accessToken }, client),
6428
+ auth: false
6429
+ });
6430
+ console.log(result);
6431
+ await setToken(result.token, result.user);
6432
+ console.log("Redirecting to:", redirectTo);
6433
+ window.location.href = redirectTo;
6434
+ });
6435
+ }
6436
+ }
6437
+ },
6438
+ // extra
6024
6439
  googleLogin: (params) => createGoogleLogin(params),
6025
6440
  onGoogleLogin: (callback) => {
6026
6441
  return subscribeGoogleLogin(callback);
6027
6442
  },
6443
+ //
6028
6444
  async login(input) {
6029
- const result = await client.request("/auth/login", { method: "POST", body: input, auth: false });
6445
+ const body = buildAuthPayload(input, client);
6446
+ const result = await client.request("/auth/login", { method: "POST", body, auth: false });
6030
6447
  if (result.token) client.setToken(result.token);
6031
6448
  return result;
6032
6449
  },
6033
6450
  async logout() {
6034
- const result = await client.request("/auth/logout", { method: "POST" });
6451
+ const result = await client.request("/auth/logout", { method: "POST", body: buildAuthPayload({}, client) });
6035
6452
  client.clearToken();
6036
6453
  return result;
6037
6454
  },
6038
- me: () => client.request("/auth/me"),
6039
- verifyOtp: (input) => client.request("/auth/verify-otp", { method: "POST", body: input, auth: false }),
6040
- changePassword: (input) => client.request("/auth/change-password", { method: "POST", body: input }),
6041
- resetPassword: (input) => client.request("/auth/reset-password", { method: "POST", body: input, auth: false }),
6042
- loginUrl: (redirectTo) => client.request("/auth/login-url", { query: redirectTo ? { redirectTo } : void 0, auth: false })
6455
+ inviteUser: (input) => client.request("/users/invite", { method: "POST", body: buildAuthPayload(input, client) }),
6456
+ acceptInvite: (input) => client.request("/auth/accept-invite", { method: "POST", body: buildAuthPayload(input, client), auth: false }),
6457
+ me: () => client.request("/auth/me", { headers: buildAuthHeaders(client) }),
6458
+ verifyOtp: (input) => client.request("/auth/verify-otp", { method: "POST", body: buildAuthPayload(input, client), auth: false }),
6459
+ changePassword: (input) => client.request("/auth/change-password", { method: "POST", body: buildAuthPayload(input, client) }),
6460
+ resetPassword: (input) => client.request("/auth/reset-password", { method: "POST", body: buildAuthPayload(input, client), auth: false }),
6461
+ loginUrl: (redirectTo) => client.request("/auth/login-url", {
6462
+ query: redirectTo ? { redirectTo, appId: client.appId || void 0 } : { appId: client.appId || void 0 },
6463
+ auth: false
6464
+ })
6043
6465
  };
6044
6466
  }
6467
+ function buildAuthPayload(input = {}, client) {
6468
+ const payload = { ...input || {} };
6469
+ if (client?.appId && payload.appId == null) {
6470
+ payload.appId = client.appId;
6471
+ }
6472
+ return payload;
6473
+ }
6474
+ function buildAuthHeaders(client) {
6475
+ return client?.appId ? { "x-app-id": client.appId } : {};
6476
+ }
6045
6477
  function createEntityRegistry(client) {
6046
6478
  return new Proxy(
6047
6479
  {},
@@ -6055,18 +6487,96 @@ var Tevroc = (() => {
6055
6487
  }
6056
6488
  function createEntityApi2(client, entity) {
6057
6489
  const base = `/entities/${encodeURIComponent(entity)}`;
6490
+ function matchesFilterLocal(record, filter = {}) {
6491
+ return Object.entries(filter).every(([k, v]) => {
6492
+ if (v && typeof v === "object") {
6493
+ if ("$eq" in v) return record?.[k] === v.$eq;
6494
+ return true;
6495
+ }
6496
+ return record?.[k] === v;
6497
+ });
6498
+ }
6058
6499
  return {
6059
- list: (options) => client.request(base, { query: options }),
6060
- get: (id) => client.request(`${base}/${encodeURIComponent(id)}`),
6061
- create: (record) => client.request(base, { method: "POST", body: record }),
6062
- update: (id, patch) => client.request(`${base}/${encodeURIComponent(id)}`, { method: "PATCH", body: patch }),
6063
- delete: (id) => client.request(`${base}/${encodeURIComponent(id)}`, { method: "DELETE" }),
6064
- query: (input = {}) => client.request(`${base}/query`, { method: "POST", body: input }),
6065
- filter: (filter = {}, sortOrOptions, limit) => client.request(`${base}/query`, { method: "POST", body: normalizeFilterInput(filter, sortOrOptions, limit) }),
6066
- bulkCreate: (records) => client.request(`${base}/bulk`, { method: "POST", body: { records } }),
6067
- bulkUpdate: (records) => client.request(`${base}/bulk`, { method: "PATCH", body: { records } }),
6068
- bulkDelete: (ids) => client.request(`${base}/bulk`, { method: "DELETE", body: { ids } }),
6069
- import: (records) => client.request(`${base}/import`, { method: "POST", body: { records } })
6500
+ list: async (options) => {
6501
+ if (!client.offline?.isOnline()) {
6502
+ const snapshot = await client.native.store.get(`entities/${entity}`);
6503
+ const rows = Object.values(snapshot.val() || {});
6504
+ return { data: rows, limit: options?.limit, offset: options?.offset || 0 };
6505
+ }
6506
+ return client.request(base, { query: options });
6507
+ },
6508
+ get: async (id) => {
6509
+ if (!client.offline?.isOnline()) {
6510
+ const data = (await client.native.store.get(`${entity}/${id}`)).val();
6511
+ return { data };
6512
+ }
6513
+ return client.request(`${base}/${encodeURIComponent(id)}`);
6514
+ },
6515
+ create: async (record) => {
6516
+ if (!client.offline?.isOnline()) return client.offline.queueOperation(entity, "create", record?.id, record);
6517
+ return client.request(base, { method: "POST", body: record });
6518
+ },
6519
+ update: async (id, patch) => {
6520
+ if (!client.offline?.isOnline()) return client.offline.queueOperation(entity, "update", id, patch);
6521
+ return client.request(`${base}/${encodeURIComponent(id)}`, { method: "PATCH", body: patch });
6522
+ },
6523
+ delete: async (id) => {
6524
+ if (!client.offline?.isOnline()) return client.offline.queueOperation(entity, "delete", id);
6525
+ return client.request(`${base}/${encodeURIComponent(id)}`, { method: "DELETE" });
6526
+ },
6527
+ query: async (input = {}) => {
6528
+ if (!client.offline?.isOnline()) {
6529
+ const snapshot = await client.native.store.get(`entities/${entity}`);
6530
+ const rows = Object.values(snapshot.val() || {}).filter((r) => matchesFilterLocal(r, input.filter || input.where || input.filters || {}));
6531
+ return { data: rows.slice(0, input.limit || 200), limit: input.limit };
6532
+ }
6533
+ return client.request(`${base}/query`, { method: "POST", body: input });
6534
+ },
6535
+ filter: async (filter = {}, sortOrOptions, limit) => {
6536
+ if (!client.offline?.isOnline()) return createEntityApi2(client, entity).query({ filter, limit });
6537
+ return client.request(`${base}/query`, { method: "POST", body: normalizeFilterInput(filter, sortOrOptions, limit) });
6538
+ },
6539
+ bulkCreate: async (records) => {
6540
+ if (!client.offline?.isOnline()) {
6541
+ let inserted = 0;
6542
+ for (const r of records) {
6543
+ await client.offline.queueOperation(entity, "create", r?.id, r);
6544
+ inserted += 1;
6545
+ }
6546
+ return { inserted };
6547
+ }
6548
+ return client.request(`${base}/bulk`, { method: "POST", body: { records } });
6549
+ },
6550
+ bulkUpdate: async (records) => {
6551
+ if (!client.offline?.isOnline()) {
6552
+ let updated = 0;
6553
+ for (const r of records) {
6554
+ if (!r?.id) continue;
6555
+ await client.offline.queueOperation(entity, "update", r.id, r);
6556
+ updated += 1;
6557
+ }
6558
+ return { updated };
6559
+ }
6560
+ return client.request(`${base}/bulk`, { method: "PATCH", body: { records } });
6561
+ },
6562
+ bulkDelete: async (ids) => {
6563
+ if (!client.offline?.isOnline()) {
6564
+ for (const id of ids) await client.offline.queueOperation(entity, "delete", id);
6565
+ return { deleted: ids.length };
6566
+ }
6567
+ return client.request(`${base}/bulk`, { method: "DELETE", body: { ids } });
6568
+ },
6569
+ import: async (records) => {
6570
+ if (!client.offline?.isOnline()) {
6571
+ let imported = 0;
6572
+ for (const r of records) {
6573
+ await client.offline.queueOperation(entity, "create", r?.id, r);
6574
+ imported += 1;
6575
+ }
6576
+ return { imported };
6577
+ }
6578
+ return client.request(`${base}/import`, { method: "POST", body: { records } });
6579
+ }
6070
6580
  };
6071
6581
  }
6072
6582
  function createFunctionRegistry(client) {