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.esm.js CHANGED
@@ -2187,6 +2187,10 @@ var init_web2 = __esm({
2187
2187
  });
2188
2188
 
2189
2189
  // node_modules/@capacitor/app/dist/esm/index.js
2190
+ var esm_exports2 = {};
2191
+ __export(esm_exports2, {
2192
+ App: () => App
2193
+ });
2190
2194
  var App;
2191
2195
  var init_esm2 = __esm({
2192
2196
  "node_modules/@capacitor/app/dist/esm/index.js"() {
@@ -5027,6 +5031,12 @@ var init_webviewWindow = __esm({
5027
5031
  });
5028
5032
 
5029
5033
  // src/services/useGoogleAuth.js
5034
+ var useGoogleAuth_exports = {};
5035
+ __export(useGoogleAuth_exports, {
5036
+ createGoogleLogin: () => createGoogleLogin,
5037
+ initializeGoogleLogin: () => initializeGoogleLogin,
5038
+ subscribeGoogleLogin: () => subscribeGoogleLogin
5039
+ });
5030
5040
  function emitGoogleLogin(user, err = null) {
5031
5041
  googleListeners.forEach((cb) => {
5032
5042
  try {
@@ -5043,7 +5053,7 @@ function subscribeGoogleLogin(cb) {
5043
5053
  if (i !== -1) googleListeners.splice(i, 1);
5044
5054
  };
5045
5055
  }
5046
- var googleInitialized, googleListeners, authWindowRef, handleCallback, initializeGoogleLogin, createGoogleLogin;
5056
+ var googleInitialized, googleListeners, authWindowRef, authCleanupTimer, authMessageListener, cleanupAuthWindow, handleCallback, initializeGoogleLogin, createGoogleLogin;
5047
5057
  var init_useGoogleAuth = __esm({
5048
5058
  "src/services/useGoogleAuth.js"() {
5049
5059
  init_esm2();
@@ -5053,8 +5063,58 @@ var init_useGoogleAuth = __esm({
5053
5063
  googleInitialized = false;
5054
5064
  googleListeners = [];
5055
5065
  authWindowRef = null;
5066
+ authCleanupTimer = null;
5067
+ authMessageListener = null;
5068
+ cleanupAuthWindow = async () => {
5069
+ if (authCleanupTimer) {
5070
+ clearInterval(authCleanupTimer);
5071
+ authCleanupTimer = null;
5072
+ }
5073
+ if (authMessageListener && typeof window !== "undefined") {
5074
+ window.removeEventListener("message", authMessageListener);
5075
+ authMessageListener = null;
5076
+ }
5077
+ if (authWindowRef) {
5078
+ const currentAuthWindow = authWindowRef;
5079
+ authWindowRef = null;
5080
+ try {
5081
+ if (typeof currentAuthWindow?.close === "function") {
5082
+ await currentAuthWindow.close();
5083
+ }
5084
+ } catch (e) {
5085
+ console.warn("Error closing auth window:", e);
5086
+ }
5087
+ }
5088
+ if (isTauri) {
5089
+ try {
5090
+ const tauriAuthWindow = await WebviewWindow.getByLabel("auth");
5091
+ if (tauriAuthWindow && tauriAuthWindow !== authWindowRef) {
5092
+ await tauriAuthWindow.close();
5093
+ }
5094
+ } catch (e) {
5095
+ console.warn("Error closing Tauri auth window by label:", e);
5096
+ }
5097
+ }
5098
+ if (isCapacitor) {
5099
+ try {
5100
+ await Browser2.close();
5101
+ } catch (e) {
5102
+ console.warn("Error closing Capacitor browser:", e);
5103
+ }
5104
+ }
5105
+ if (typeof window !== "undefined" && window !== window.parent) {
5106
+ try {
5107
+ if (authWindowRef && typeof authWindowRef.close === "function") {
5108
+ await authWindowRef.close();
5109
+ }
5110
+ } catch (e) {
5111
+ console.warn("Error closing popup fallback:", e);
5112
+ }
5113
+ }
5114
+ };
5056
5115
  handleCallback = async (url) => {
5057
5116
  try {
5117
+ await cleanupAuthWindow();
5058
5118
  if (!url?.includes("token=")) return;
5059
5119
  const params = new URLSearchParams(url.split("?")[1]);
5060
5120
  const token = params.get("token");
@@ -5100,14 +5160,7 @@ var init_useGoogleAuth = __esm({
5100
5160
  url = url?.url || url?.payload || null;
5101
5161
  }
5102
5162
  if (!url) return;
5103
- if (authWindowRef) {
5104
- try {
5105
- await authWindowRef.close();
5106
- authWindowRef = null;
5107
- } catch (e) {
5108
- }
5109
- }
5110
- handleCallback(url);
5163
+ await handleCallback(url);
5111
5164
  });
5112
5165
  }
5113
5166
  };
@@ -5159,21 +5212,21 @@ var init_useGoogleAuth = __esm({
5159
5212
  console.error("Popup blocked");
5160
5213
  return;
5161
5214
  }
5162
- const listener = (event) => {
5163
- if (event.origin !== serviceUrl) return;
5215
+ authWindowRef = popup;
5216
+ authMessageListener = async (event) => {
5217
+ const serviceOrigin = new URL(serviceUrl).origin;
5218
+ if (event.origin !== serviceOrigin) return;
5164
5219
  if (event.data?.type === "google-auth") {
5165
5220
  const token = event.data?.token || null;
5166
5221
  const url = token ? `${window.location.href}${window.location.href.includes("?") ? "&" : "?"}token=${token}` : window.location.href;
5167
- popup.close();
5168
- window.removeEventListener("message", listener);
5169
- handleCallback(url);
5222
+ await handleCallback(url);
5170
5223
  }
5171
5224
  };
5172
- window.addEventListener("message", listener);
5173
- const timer = setInterval(() => {
5225
+ window.addEventListener("message", authMessageListener);
5226
+ authCleanupTimer = setInterval(() => {
5174
5227
  if (popup.closed) {
5175
- clearInterval(timer);
5176
- window.removeEventListener("message", listener);
5228
+ cleanupAuthWindow().catch(() => {
5229
+ });
5177
5230
  }
5178
5231
  }, 500);
5179
5232
  return;
@@ -5224,17 +5277,17 @@ var init_useYocoPayment = __esm({
5224
5277
  }) => {
5225
5278
  try {
5226
5279
  addLog("PAYMENT CALLBACK:", url);
5227
- if (!url?.includes("state=")) return;
5280
+ if (!url?.includes("status=")) return;
5228
5281
  const params = new URLSearchParams(url.split("?")[1]);
5229
- const state = params.get("state");
5230
- addLog("PAYMENT RESULT:", state);
5231
- if (state == "success") {
5282
+ const status = params.get("status");
5283
+ addLog("PAYMENT RESULT:", status);
5284
+ if (status == "success") {
5232
5285
  addLog("PAYMENT SUCCESS");
5233
5286
  } else {
5234
5287
  addLog("PAYMENT FAILED");
5235
5288
  }
5236
- externalCallback(state, null);
5237
- emitPaymentStatus(state, null);
5289
+ externalCallback(status, null);
5290
+ emitPaymentStatus(status, null);
5238
5291
  } catch (err) {
5239
5292
  addLog("PAYMENT CALLBACK ERROR:", err.message);
5240
5293
  externalCallback(null, err);
@@ -5278,13 +5331,15 @@ var init_useYocoPayment = __esm({
5278
5331
  createPayment = async (amountZAR, {
5279
5332
  appId = "tevrocsoft",
5280
5333
  serviceUrl = "https://tevrocsoftapi.netlify.app",
5334
+ payAccount = "default",
5281
5335
  externalCallback = () => {
5282
5336
  }
5283
5337
  } = {}) => {
5284
5338
  await initializePayment(externalCallback);
5285
5339
  const cents = Math.round(Number(amountZAR) * 100);
5286
- const basePaymentUrl = `${serviceUrl}/pay`;
5287
- const paymentUrl = `${basePaymentUrl}?mode=mobile&amount=${cents}&app=${appId}`;
5340
+ const basePaymentUrl = `${serviceUrl.replace(/\/$/, "")}/yoco-pay`;
5341
+ const paymentUrl = `${basePaymentUrl}?mode=mobile&amount=${cents}&app=${appId}&account=${payAccount}`;
5342
+ console.log(basePaymentUrl, paymentUrl);
5288
5343
  if (isCapacitor) {
5289
5344
  await Browser2.open({
5290
5345
  url: paymentUrl
@@ -5292,7 +5347,7 @@ var init_useYocoPayment = __esm({
5292
5347
  return;
5293
5348
  }
5294
5349
  if (isTauri) {
5295
- const url = `${basePaymentUrl}?mode=desktop&amount=${cents}&app=${appId}`;
5350
+ const url = `${basePaymentUrl}?mode=desktop&amount=${cents}&app=${appId}&account=${payAccount}`;
5296
5351
  const win = new WebviewWindow("payment", {
5297
5352
  url,
5298
5353
  title: "Complete Payment",
@@ -5312,7 +5367,55 @@ var init_useYocoPayment = __esm({
5312
5367
  }
5313
5368
  const isLocalhost = window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1";
5314
5369
  const mode = isLocalhost ? "localhost" : "netlify";
5315
- window.location.href = `${basePaymentUrl}?mode=${mode}&amount=${cents}&app=${appId}`;
5370
+ const finalUrl = `${basePaymentUrl}?mode=${mode}&amount=${cents}&app=${appId}`;
5371
+ try {
5372
+ const popup = window.open(finalUrl, "yocoPayment", "width=500,height=650");
5373
+ if (!popup) {
5374
+ window.location.href = finalUrl;
5375
+ return;
5376
+ }
5377
+ let listenerAttached = true;
5378
+ let timerRunning = true;
5379
+ const listener = (event) => {
5380
+ try {
5381
+ const serviceOrigin = new URL(serviceUrl).origin;
5382
+ if (event.origin !== serviceOrigin) return;
5383
+ if (event.data?.type === "payment-result") {
5384
+ const status = event.data?.status || null;
5385
+ listenerAttached = false;
5386
+ timerRunning = false;
5387
+ window.removeEventListener("message", listener);
5388
+ try {
5389
+ popup.close();
5390
+ } catch (e) {
5391
+ }
5392
+ const url = status ? `${window.location.href}${window.location.href.includes("?") ? "&" : "?"}status=${status}` : window.location.href;
5393
+ handlePaymentCallback(url, externalCallback);
5394
+ }
5395
+ } catch (err) {
5396
+ console.error("Payment listener error", err);
5397
+ }
5398
+ };
5399
+ window.addEventListener("message", listener);
5400
+ const timer = setInterval(() => {
5401
+ if (!timerRunning) {
5402
+ clearInterval(timer);
5403
+ return;
5404
+ }
5405
+ if (popup.closed) {
5406
+ clearInterval(timer);
5407
+ timerRunning = false;
5408
+ if (listenerAttached) {
5409
+ listenerAttached = false;
5410
+ window.removeEventListener("message", listener);
5411
+ }
5412
+ }
5413
+ }, 500);
5414
+ return;
5415
+ } catch (e) {
5416
+ window.location.href = finalUrl;
5417
+ return;
5418
+ }
5316
5419
  };
5317
5420
  }
5318
5421
  });
@@ -5848,6 +5951,252 @@ function createProjectStore(appId) {
5848
5951
  };
5849
5952
  }
5850
5953
 
5954
+ // src/services/offline.js
5955
+ function createOfflineManager(client) {
5956
+ const store = createNativeStore(client.appId);
5957
+ const listeners2 = /* @__PURE__ */ new Map();
5958
+ async function getQueue() {
5959
+ const snapshot = await store.get("sync_queue");
5960
+ return snapshot.val() || [];
5961
+ }
5962
+ async function setQueue(q) {
5963
+ await store.set("sync_queue", q || []);
5964
+ }
5965
+ function isOnline() {
5966
+ try {
5967
+ if (typeof navigator !== "undefined" && typeof navigator.onLine !== "undefined") return navigator.onLine;
5968
+ } catch (e) {
5969
+ }
5970
+ try {
5971
+ return true;
5972
+ } catch (e) {
5973
+ return true;
5974
+ }
5975
+ }
5976
+ async function queueOperation(entity, op, recordId, payload) {
5977
+ const q = await getQueue();
5978
+ const item = { id: crypto.randomUUID?.() || String(Date.now()), entity, op, recordId, payload, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
5979
+ q.push(item);
5980
+ await setQueue(q);
5981
+ if (op === "create" || op === "update") {
5982
+ const id = recordId || payload?.id || `loc_${Date.now()}`;
5983
+ await store.set(`entities/${entity}/${id}`, { ...payload || {}, id });
5984
+ return { data: { ...payload || {}, id } };
5985
+ }
5986
+ if (op === "delete") {
5987
+ await store.remove(`entities/${entity}/${recordId}`);
5988
+ return { deleted: true, id: recordId };
5989
+ }
5990
+ return null;
5991
+ }
5992
+ async function syncOnce() {
5993
+ if (!isOnline()) return { ok: false, reason: "offline" };
5994
+ let q = await getQueue();
5995
+ if (!q || q.length === 0) return { ok: true, synced: 0 };
5996
+ emit2("sync:start", { count: q.length });
5997
+ for (const item of [...q]) {
5998
+ try {
5999
+ const localSnapshot = (await store.get(`entities/${item.entity}/${item.recordId || item.payload && item.payload.id || ""}`)).val();
6000
+ if (item.op === "create") {
6001
+ const res = await client.request(`/entities/${encodeURIComponent(item.entity)}`, { method: "POST", body: item.payload });
6002
+ const serverId = res?.data?.id || res?.id || item.recordId;
6003
+ if (serverId) {
6004
+ await store.set(`entities/${item.entity}/${serverId}`, res?.data || { ...item.payload || {}, id: serverId });
6005
+ }
6006
+ q = q.filter((qitem) => qitem.id !== item.id);
6007
+ emit2("sync:item", { item, result: res });
6008
+ } else if (item.op === "update") {
6009
+ const res = await client.request(`/entities/${encodeURIComponent(item.entity)}/${encodeURIComponent(item.recordId)}`, { method: "PATCH", body: item.payload });
6010
+ const serverData = res?.data ?? res;
6011
+ const serverUpdated = serverData?.updatedAt || serverData?.updated_date || null;
6012
+ const localUpdated = localSnapshot?.updatedAt || localSnapshot?.updated_date || null;
6013
+ if (localUpdated && serverUpdated && localUpdated > serverUpdated && JSON.stringify(localSnapshot) !== JSON.stringify(serverData)) {
6014
+ const conflictId = `${item.entity}/${item.recordId}`;
6015
+ await store.set(`conflicts/${conflictId}`, { local: localSnapshot, server: serverData, item });
6016
+ emit2("conflict", { conflictId, local: localSnapshot, server: serverData, item });
6017
+ } else {
6018
+ if (serverData) await store.set(`entities/${item.entity}/${item.recordId}`, serverData);
6019
+ q = q.filter((qitem) => qitem.id !== item.id);
6020
+ emit2("sync:item", { item, result: res });
6021
+ }
6022
+ } else if (item.op === "delete") {
6023
+ await client.request(`/entities/${encodeURIComponent(item.entity)}/${encodeURIComponent(item.recordId)}`, { method: "DELETE" });
6024
+ await store.remove(`entities/${item.entity}/${item.recordId}`);
6025
+ q = q.filter((qitem) => qitem.id !== item.id);
6026
+ emit2("sync:item", { item, result: { deleted: true } });
6027
+ }
6028
+ } catch (err) {
6029
+ console.warn("Sync failed for item", item, err);
6030
+ emit2("sync:error", { item, error: err });
6031
+ break;
6032
+ }
6033
+ }
6034
+ await setQueue(q);
6035
+ emit2("sync:end", { remaining: q.length });
6036
+ return { ok: true, synced: 0, remaining: q.length };
6037
+ }
6038
+ let autoInterval = null;
6039
+ let platformListeners = [];
6040
+ let capacitorNetwork = null;
6041
+ let capacitorApp = null;
6042
+ let lastNetworkStatus = null;
6043
+ function startAutoSync(intervalMs = 3e4) {
6044
+ if (typeof window !== "undefined") {
6045
+ const onOnline = () => syncOnce();
6046
+ window.addEventListener("online", onOnline);
6047
+ platformListeners.push(() => window.removeEventListener("online", onOnline));
6048
+ const onVis = () => {
6049
+ if (!document.hidden) syncOnce();
6050
+ };
6051
+ document.addEventListener("visibilitychange", onVis);
6052
+ platformListeners.push(() => document.removeEventListener("visibilitychange", onVis));
6053
+ const onFocus = () => syncOnce();
6054
+ window.addEventListener("focus", onFocus);
6055
+ platformListeners.push(() => window.removeEventListener("focus", onFocus));
6056
+ }
6057
+ (async () => {
6058
+ try {
6059
+ const netMod = await import("@capacitor/network");
6060
+ capacitorNetwork = netMod.Network || netMod;
6061
+ if (capacitorNetwork && capacitorNetwork.getStatus) {
6062
+ const st = await capacitorNetwork.getStatus();
6063
+ lastNetworkStatus = st.connected;
6064
+ const listener = capacitorNetwork.addListener("networkStatusChange", (status) => {
6065
+ lastNetworkStatus = status.connected;
6066
+ if (status.connected) syncOnce();
6067
+ });
6068
+ platformListeners.push(() => listener.remove());
6069
+ }
6070
+ } catch (e) {
6071
+ }
6072
+ try {
6073
+ const appMod = await Promise.resolve().then(() => (init_esm2(), esm_exports2));
6074
+ capacitorApp = appMod.App || appMod;
6075
+ if (capacitorApp && capacitorApp.addListener) {
6076
+ const sub = capacitorApp.addListener("appStateChange", (state) => {
6077
+ if (state.isActive) syncOnce();
6078
+ });
6079
+ platformListeners.push(() => sub.remove());
6080
+ try {
6081
+ const pauseSub = capacitorApp.addListener("pause", async () => {
6082
+ try {
6083
+ const bg = await import("@capacitor/background-task");
6084
+ const BackgroundTask = bg.BackgroundTask || bg;
6085
+ if (BackgroundTask && BackgroundTask.beforeExit) {
6086
+ const taskId = BackgroundTask.beforeExit(async () => {
6087
+ await syncOnce();
6088
+ try {
6089
+ BackgroundTask.finish({ taskId });
6090
+ } catch (e) {
6091
+ }
6092
+ });
6093
+ } else {
6094
+ await syncOnce();
6095
+ }
6096
+ } catch (e) {
6097
+ await syncOnce();
6098
+ }
6099
+ });
6100
+ platformListeners.push(() => pauseSub.remove());
6101
+ const resumeSub = capacitorApp.addListener("resume", async () => {
6102
+ await syncOnce();
6103
+ });
6104
+ platformListeners.push(() => resumeSub.remove());
6105
+ } catch (e) {
6106
+ }
6107
+ }
6108
+ } catch (e) {
6109
+ }
6110
+ try {
6111
+ if (typeof window !== "undefined" && (window.__TAURI__ || window.__TAURI_INTERNALS__)) {
6112
+ try {
6113
+ const tauriEvent = window.__TAURI__?.event;
6114
+ if (tauriEvent && tauriEvent.listen) {
6115
+ const unsub1 = await tauriEvent.listen("tauri://update", () => syncOnce()).catch(() => null);
6116
+ const unsub2 = await tauriEvent.listen("tauri://resume", () => syncOnce()).catch(() => null);
6117
+ if (unsub1) platformListeners.push(() => unsub1.then((u) => u()).catch(() => {
6118
+ }));
6119
+ if (unsub2) platformListeners.push(() => unsub2.then((u) => u()).catch(() => {
6120
+ }));
6121
+ }
6122
+ } catch (err) {
6123
+ }
6124
+ }
6125
+ } catch (e) {
6126
+ }
6127
+ })();
6128
+ if (!autoInterval) autoInterval = setInterval(() => syncOnce(), intervalMs);
6129
+ }
6130
+ function stopAutoSync() {
6131
+ for (const rm of platformListeners.splice(0)) {
6132
+ try {
6133
+ rm();
6134
+ } catch (e) {
6135
+ }
6136
+ }
6137
+ if (autoInterval) {
6138
+ clearInterval(autoInterval);
6139
+ autoInterval = null;
6140
+ }
6141
+ }
6142
+ function emit2(event, payload) {
6143
+ try {
6144
+ if (!listeners2.has(event)) return;
6145
+ for (const cb of listeners2.get(event)) {
6146
+ try {
6147
+ cb(payload);
6148
+ } catch (e) {
6149
+ console.warn("listener error", e);
6150
+ }
6151
+ }
6152
+ } catch (e) {
6153
+ }
6154
+ }
6155
+ return {
6156
+ store,
6157
+ isOnline,
6158
+ queueOperation,
6159
+ syncOnce,
6160
+ startAutoSync,
6161
+ stopAutoSync,
6162
+ getQueue,
6163
+ // events
6164
+ on: (event, cb) => {
6165
+ if (!listeners2.has(event)) listeners2.set(event, /* @__PURE__ */ new Set());
6166
+ listeners2.get(event).add(cb);
6167
+ return () => listeners2.get(event).delete(cb);
6168
+ },
6169
+ off: (event, cb) => {
6170
+ if (!listeners2.has(event)) return;
6171
+ listeners2.get(event).delete(cb);
6172
+ },
6173
+ listConflicts: async () => {
6174
+ const snapshot = await store.get("conflicts");
6175
+ return snapshot.val() || {};
6176
+ },
6177
+ resolveConflict: async (conflictId, resolution = "useServer") => {
6178
+ const parts = String(conflictId).split("/");
6179
+ const entity = parts.shift();
6180
+ const id = parts.join("/");
6181
+ const conflict = (await store.get(`conflicts/${conflictId}`)).val();
6182
+ if (!conflict) return null;
6183
+ if (resolution === "useServer") {
6184
+ await store.set(`entities/${entity}/${id}`, conflict.server);
6185
+ await store.remove(`conflicts/${conflictId}`);
6186
+ const q = await getQueue();
6187
+ await setQueue(q.filter((i) => !(i.entity === entity && String(i.recordId) === String(id))));
6188
+ return { applied: "server" };
6189
+ }
6190
+ if (resolution === "useLocal") {
6191
+ await queueOperation(entity, "update", id, conflict.local);
6192
+ await store.remove(`conflicts/${conflictId}`);
6193
+ return { requeued: true };
6194
+ }
6195
+ return null;
6196
+ }
6197
+ };
6198
+ }
6199
+
5851
6200
  // src/index.js
5852
6201
  init_useGoogleAuth();
5853
6202
  init_useYocoPayment();
@@ -5859,6 +6208,13 @@ async function getPlatformModule() {
5859
6208
  }
5860
6209
  return platformModule;
5861
6210
  }
6211
+ var googleModule = null;
6212
+ async function getGoogleModule() {
6213
+ if (!googleModule) {
6214
+ googleModule = await Promise.resolve().then(() => (init_useGoogleAuth(), useGoogleAuth_exports));
6215
+ }
6216
+ return googleModule;
6217
+ }
5862
6218
  var TevrocError = class extends Error {
5863
6219
  constructor(message, options = {}) {
5864
6220
  super(message);
@@ -5881,6 +6237,7 @@ var TevrocClient = class {
5881
6237
  this.serviceUrl = normalizeBaseUrl(serviceUrl);
5882
6238
  this.appId = options.appId;
5883
6239
  this.appName = options.appName;
6240
+ this.payAccount = options.payAccount ?? "default";
5884
6241
  this.isNative = options.isNative ?? false;
5885
6242
  this.fetch = (options.fetch ?? globalThis.fetch).bind(globalThis);
5886
6243
  if (typeof this.fetch !== "function") {
@@ -5905,6 +6262,7 @@ var TevrocClient = class {
5905
6262
  googleDrive: createGoogleDriveApi(this.appId),
5906
6263
  projects: createProjectStore(this.appId)
5907
6264
  };
6265
+ this.offline = createOfflineManager(this);
5908
6266
  this.payments = createPaymentApi(this);
5909
6267
  this.platform = createPlatformApi(this);
5910
6268
  }
@@ -5930,6 +6288,7 @@ var TevrocClient = class {
5930
6288
  const controller = new AbortController();
5931
6289
  const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? this.timeoutMs);
5932
6290
  const token = this.token || getStoredToken();
6291
+ console.log(token, options);
5933
6292
  if (token && options.auth !== false) {
5934
6293
  headers.set("authorization", `Bearer ${token}`);
5935
6294
  }
@@ -5946,7 +6305,7 @@ var TevrocClient = class {
5946
6305
  if (value !== void 0 && value !== null) headers.set(key, String(value));
5947
6306
  }
5948
6307
  }
5949
- console.log(headers, url);
6308
+ console.error(headers, url);
5950
6309
  try {
5951
6310
  const response = await this.fetch(url, {
5952
6311
  method,
@@ -5979,13 +6338,18 @@ function createPlatformApi(client) {
5979
6338
  }
5980
6339
  function createPaymentApi(client) {
5981
6340
  return {
5982
- create: async ({ amountZAR, appId = "tevrocsoft", mode = "web" }) => {
6341
+ create: async ({ amountZAR, appId = "tevrocsoft", mode = "web", account = "default", externalCallback = void 0 } = {}) => {
5983
6342
  return await createPayment(amountZAR, {
5984
6343
  appId,
5985
6344
  serviceUrl: client.serviceUrl,
5986
- mode
6345
+ mode,
6346
+ payAccount: account,
6347
+ externalCallback
5987
6348
  });
5988
6349
  },
6350
+ createCheckout: async (payload = {}) => {
6351
+ return await client.request("/create-checkout", { method: "POST", body: payload, auth: false });
6352
+ },
5989
6353
  onstatus: (callback) => {
5990
6354
  if (typeof callback !== "function") {
5991
6355
  throw new Error("onstatus requires a function");
@@ -5997,31 +6361,83 @@ function createPaymentApi(client) {
5997
6361
  function createAuthApi(client) {
5998
6362
  return {
5999
6363
  async register(input) {
6000
- const result = await client.request("/auth/register", { method: "POST", body: input, auth: false });
6364
+ const body = buildAuthPayload(input, client);
6365
+ const result = await client.request("/auth/register", { method: "POST", body, auth: false });
6001
6366
  if (result.token) client.setToken(result.token);
6002
6367
  return result;
6003
6368
  },
6369
+ // base44
6370
+ loginWithProvider: async (provider, redirectTo, setToken = async () => {
6371
+ }) => {
6372
+ if (provider === "google") {
6373
+ const { createGoogleLogin: createGoogleLogin2, subscribeGoogleLogin: subscribeGoogleLogin2 } = await getGoogleModule();
6374
+ console.log({
6375
+ serviceUrl: client.serviceUrl,
6376
+ appId: client.appId,
6377
+ appName: client.appName
6378
+ });
6379
+ createGoogleLogin2({
6380
+ serviceUrl: client.serviceUrl,
6381
+ appId: client.appId,
6382
+ appName: client.appName
6383
+ });
6384
+ if (redirectTo) {
6385
+ const unsub = subscribeGoogleLogin2(async (user, err) => {
6386
+ console.log("Google callback:", user, err);
6387
+ unsub();
6388
+ if (!user) return;
6389
+ const result = await client.request("/auth/google", {
6390
+ method: "POST",
6391
+ body: buildAuthPayload({ accessToken: user.accessToken }, client),
6392
+ auth: false
6393
+ });
6394
+ console.log(result);
6395
+ await setToken(result.token, result.user);
6396
+ console.log("Redirecting to:", redirectTo);
6397
+ window.location.href = redirectTo;
6398
+ });
6399
+ }
6400
+ }
6401
+ },
6402
+ // extra
6004
6403
  googleLogin: (params) => createGoogleLogin(params),
6005
6404
  onGoogleLogin: (callback) => {
6006
6405
  return subscribeGoogleLogin(callback);
6007
6406
  },
6407
+ //
6008
6408
  async login(input) {
6009
- const result = await client.request("/auth/login", { method: "POST", body: input, auth: false });
6409
+ const body = buildAuthPayload(input, client);
6410
+ const result = await client.request("/auth/login", { method: "POST", body, auth: false });
6010
6411
  if (result.token) client.setToken(result.token);
6011
6412
  return result;
6012
6413
  },
6013
6414
  async logout() {
6014
- const result = await client.request("/auth/logout", { method: "POST" });
6415
+ const result = await client.request("/auth/logout", { method: "POST", body: buildAuthPayload({}, client) });
6015
6416
  client.clearToken();
6016
6417
  return result;
6017
6418
  },
6018
- me: () => client.request("/auth/me"),
6019
- verifyOtp: (input) => client.request("/auth/verify-otp", { method: "POST", body: input, auth: false }),
6020
- changePassword: (input) => client.request("/auth/change-password", { method: "POST", body: input }),
6021
- resetPassword: (input) => client.request("/auth/reset-password", { method: "POST", body: input, auth: false }),
6022
- loginUrl: (redirectTo) => client.request("/auth/login-url", { query: redirectTo ? { redirectTo } : void 0, auth: false })
6419
+ inviteUser: (input) => client.request("/users/invite", { method: "POST", body: buildAuthPayload(input, client) }),
6420
+ acceptInvite: (input) => client.request("/auth/accept-invite", { method: "POST", body: buildAuthPayload(input, client), auth: false }),
6421
+ me: () => client.request("/auth/me", { headers: buildAuthHeaders(client) }),
6422
+ verifyOtp: (input) => client.request("/auth/verify-otp", { method: "POST", body: buildAuthPayload(input, client), auth: false }),
6423
+ changePassword: (input) => client.request("/auth/change-password", { method: "POST", body: buildAuthPayload(input, client) }),
6424
+ resetPassword: (input) => client.request("/auth/reset-password", { method: "POST", body: buildAuthPayload(input, client), auth: false }),
6425
+ loginUrl: (redirectTo) => client.request("/auth/login-url", {
6426
+ query: redirectTo ? { redirectTo, appId: client.appId || void 0 } : { appId: client.appId || void 0 },
6427
+ auth: false
6428
+ })
6023
6429
  };
6024
6430
  }
6431
+ function buildAuthPayload(input = {}, client) {
6432
+ const payload = { ...input || {} };
6433
+ if (client?.appId && payload.appId == null) {
6434
+ payload.appId = client.appId;
6435
+ }
6436
+ return payload;
6437
+ }
6438
+ function buildAuthHeaders(client) {
6439
+ return client?.appId ? { "x-app-id": client.appId } : {};
6440
+ }
6025
6441
  function createEntityRegistry(client) {
6026
6442
  return new Proxy(
6027
6443
  {},
@@ -6035,18 +6451,96 @@ function createEntityRegistry(client) {
6035
6451
  }
6036
6452
  function createEntityApi2(client, entity) {
6037
6453
  const base = `/entities/${encodeURIComponent(entity)}`;
6454
+ function matchesFilterLocal(record, filter = {}) {
6455
+ return Object.entries(filter).every(([k, v]) => {
6456
+ if (v && typeof v === "object") {
6457
+ if ("$eq" in v) return record?.[k] === v.$eq;
6458
+ return true;
6459
+ }
6460
+ return record?.[k] === v;
6461
+ });
6462
+ }
6038
6463
  return {
6039
- list: (options) => client.request(base, { query: options }),
6040
- get: (id) => client.request(`${base}/${encodeURIComponent(id)}`),
6041
- create: (record) => client.request(base, { method: "POST", body: record }),
6042
- update: (id, patch) => client.request(`${base}/${encodeURIComponent(id)}`, { method: "PATCH", body: patch }),
6043
- delete: (id) => client.request(`${base}/${encodeURIComponent(id)}`, { method: "DELETE" }),
6044
- query: (input = {}) => client.request(`${base}/query`, { method: "POST", body: input }),
6045
- filter: (filter = {}, sortOrOptions, limit) => client.request(`${base}/query`, { method: "POST", body: normalizeFilterInput(filter, sortOrOptions, limit) }),
6046
- bulkCreate: (records) => client.request(`${base}/bulk`, { method: "POST", body: { records } }),
6047
- bulkUpdate: (records) => client.request(`${base}/bulk`, { method: "PATCH", body: { records } }),
6048
- bulkDelete: (ids) => client.request(`${base}/bulk`, { method: "DELETE", body: { ids } }),
6049
- import: (records) => client.request(`${base}/import`, { method: "POST", body: { records } })
6464
+ list: async (options) => {
6465
+ if (!client.offline?.isOnline()) {
6466
+ const snapshot = await client.native.store.get(`entities/${entity}`);
6467
+ const rows = Object.values(snapshot.val() || {});
6468
+ return { data: rows, limit: options?.limit, offset: options?.offset || 0 };
6469
+ }
6470
+ return client.request(base, { query: options });
6471
+ },
6472
+ get: async (id) => {
6473
+ if (!client.offline?.isOnline()) {
6474
+ const data = (await client.native.store.get(`${entity}/${id}`)).val();
6475
+ return { data };
6476
+ }
6477
+ return client.request(`${base}/${encodeURIComponent(id)}`);
6478
+ },
6479
+ create: async (record) => {
6480
+ if (!client.offline?.isOnline()) return client.offline.queueOperation(entity, "create", record?.id, record);
6481
+ return client.request(base, { method: "POST", body: record });
6482
+ },
6483
+ update: async (id, patch) => {
6484
+ if (!client.offline?.isOnline()) return client.offline.queueOperation(entity, "update", id, patch);
6485
+ return client.request(`${base}/${encodeURIComponent(id)}`, { method: "PATCH", body: patch });
6486
+ },
6487
+ delete: async (id) => {
6488
+ if (!client.offline?.isOnline()) return client.offline.queueOperation(entity, "delete", id);
6489
+ return client.request(`${base}/${encodeURIComponent(id)}`, { method: "DELETE" });
6490
+ },
6491
+ query: async (input = {}) => {
6492
+ if (!client.offline?.isOnline()) {
6493
+ const snapshot = await client.native.store.get(`entities/${entity}`);
6494
+ const rows = Object.values(snapshot.val() || {}).filter((r) => matchesFilterLocal(r, input.filter || input.where || input.filters || {}));
6495
+ return { data: rows.slice(0, input.limit || 200), limit: input.limit };
6496
+ }
6497
+ return client.request(`${base}/query`, { method: "POST", body: input });
6498
+ },
6499
+ filter: async (filter = {}, sortOrOptions, limit) => {
6500
+ if (!client.offline?.isOnline()) return createEntityApi2(client, entity).query({ filter, limit });
6501
+ return client.request(`${base}/query`, { method: "POST", body: normalizeFilterInput(filter, sortOrOptions, limit) });
6502
+ },
6503
+ bulkCreate: async (records) => {
6504
+ if (!client.offline?.isOnline()) {
6505
+ let inserted = 0;
6506
+ for (const r of records) {
6507
+ await client.offline.queueOperation(entity, "create", r?.id, r);
6508
+ inserted += 1;
6509
+ }
6510
+ return { inserted };
6511
+ }
6512
+ return client.request(`${base}/bulk`, { method: "POST", body: { records } });
6513
+ },
6514
+ bulkUpdate: async (records) => {
6515
+ if (!client.offline?.isOnline()) {
6516
+ let updated = 0;
6517
+ for (const r of records) {
6518
+ if (!r?.id) continue;
6519
+ await client.offline.queueOperation(entity, "update", r.id, r);
6520
+ updated += 1;
6521
+ }
6522
+ return { updated };
6523
+ }
6524
+ return client.request(`${base}/bulk`, { method: "PATCH", body: { records } });
6525
+ },
6526
+ bulkDelete: async (ids) => {
6527
+ if (!client.offline?.isOnline()) {
6528
+ for (const id of ids) await client.offline.queueOperation(entity, "delete", id);
6529
+ return { deleted: ids.length };
6530
+ }
6531
+ return client.request(`${base}/bulk`, { method: "DELETE", body: { ids } });
6532
+ },
6533
+ import: async (records) => {
6534
+ if (!client.offline?.isOnline()) {
6535
+ let imported = 0;
6536
+ for (const r of records) {
6537
+ await client.offline.queueOperation(entity, "create", r?.id, r);
6538
+ imported += 1;
6539
+ }
6540
+ return { imported };
6541
+ }
6542
+ return client.request(`${base}/import`, { method: "POST", body: { records } });
6543
+ }
6050
6544
  };
6051
6545
  }
6052
6546
  function createFunctionRegistry(client) {