tevrocsdk 0.1.33 → 0.1.34

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/README.md CHANGED
@@ -19,6 +19,159 @@ npm install tevrocsdk
19
19
  </script>
20
20
  ```
21
21
 
22
+ ## Native / desktop integration (Capacitor and Tauri)
23
+
24
+ Tevroc SDK works in web apps, but it also fits naturally into mobile and desktop shells. When you need OAuth callbacks, native file access, or deep links, the host app usually provides the platform bridge and the SDK supplies the API client.
25
+
26
+ ### Capacitor (mobile)
27
+ - Declare the app identity and a custom URL scheme in your Capacitor config so the app can receive OAuth redirects.
28
+ - Add an Android intent filter so the platform can route callback URLs back into your app.
29
+ - Listen for the platform event and forward the URL into your auth callback flow.
30
+
31
+ Typical file locations:
32
+
33
+ ```text
34
+ project-root/
35
+ ├── capacitor.config.ts
36
+ ├── android/
37
+ │ └── app/
38
+ │ └── src/
39
+ │ └── main/
40
+ │ └── AndroidManifest.xml
41
+ └── src/
42
+ └── app code that handles appUrlOpen events
43
+ ```
44
+
45
+ A typical setup looks like this:
46
+
47
+ File: capacitor.config.ts
48
+
49
+ ```ts
50
+ import type { CapacitorConfig } from "@capacitor/cli";
51
+
52
+ const config: CapacitorConfig = {
53
+ appId: "com.example.app",
54
+ appName: "Example App",
55
+ webDir: "dist",
56
+ plugins: {
57
+ App: {
58
+ appUrlOpen: {
59
+ androidScheme: "myapp",
60
+ iosScheme: "myapp",
61
+ },
62
+ },
63
+ },
64
+ };
65
+
66
+ export default config;
67
+ ```
68
+
69
+ File: android/app/src/main/AndroidManifest.xml
70
+
71
+ ```xml
72
+ <manifest>
73
+ <uses-permission android:name="android.permission.INTERNET" />
74
+ <application>
75
+ <intent-filter>
76
+ <action android:name="android.intent.action.VIEW" />
77
+ <category android:name="android.intent.category.DEFAULT" />
78
+ <category android:name="android.intent.category.BROWSABLE" />
79
+ <data android:scheme="myapp" />
80
+ </intent-filter>
81
+ </application>
82
+ </manifest>
83
+ ```
84
+
85
+ File: src/main.ts or your app bootstrap file
86
+
87
+ ```ts
88
+ import { App } from "@capacitor/app";
89
+
90
+ App.addListener("appUrlOpen", ({ url }) => {
91
+ handleAuthCallback(url);
92
+ });
93
+ ```
94
+
95
+ ### Tauri (desktop)
96
+ - Register a custom protocol in your Tauri config so the desktop app can receive deep links.
97
+ - Add the relevant Rust plugins for deep-link handling and single-instance behavior.
98
+ - Emit a frontend event from the Rust side and listen for it in your app.
99
+
100
+ Typical file locations:
101
+
102
+ ```text
103
+ project-root/
104
+ ├── src-tauri/
105
+ │ ├── tauri.conf.json
106
+ │ ├── Cargo.toml
107
+ │ └── src/
108
+ │ └── lib.rs
109
+ └── src/
110
+ └── frontend code that listens for deep-link events
111
+ ```
112
+
113
+ A typical setup looks like this:
114
+
115
+ File: src-tauri/tauri.conf.json
116
+
117
+ ```json
118
+ {
119
+ "identifier": "com.example.desktop",
120
+ "plugins": {
121
+ "deep-link": {
122
+ "desktop": {
123
+ "schemes": ["myapp"]
124
+ }
125
+ }
126
+ }
127
+ }
128
+ ```
129
+
130
+ File: src-tauri/Cargo.toml
131
+
132
+ ```toml
133
+ [dependencies]
134
+ tauri = { version = "2", features = [] }
135
+ tauri-plugin-deep-link = "2"
136
+ tauri-plugin-single-instance = "2"
137
+ ```
138
+
139
+ File: src-tauri/src/lib.rs
140
+
141
+ ```rust
142
+ use tauri::{Manager, Emitter};
143
+ use tauri_plugin_deep_link::DeepLinkExt;
144
+ use serde_json::json;
145
+
146
+ #[cfg_attr(mobile, tauri::mobile_entry_point)]
147
+ pub fn run() {
148
+ let builder = tauri::Builder::default()
149
+ .plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| {
150
+ if let Some(url) = argv.get(1) {
151
+ let _ = app.emit_to("main", "deep-link://open-url", json!(url));
152
+ }
153
+ }))
154
+ .plugin(tauri_plugin_deep_link::init())
155
+ .setup(|app| {
156
+ #[cfg(any(target_os = "linux", all(debug_assertions, windows)))]
157
+ app.deep_link().register_all()?;
158
+ Ok(())
159
+ });
160
+
161
+ builder.run(tauri::generate_context!()).expect("error while running app");
162
+ }
163
+ ```
164
+
165
+ File: src/main.ts or your app bootstrap file
166
+
167
+ ```ts
168
+ import { listen } from "@tauri-apps/api/event";
169
+
170
+ listen("deep-link://open-url", (event) => {
171
+ handleAuthCallback(event.payload as string);
172
+ });
173
+ ```
174
+
22
175
  ## Create a client
23
176
 
24
177
  Start by creating a client with your Tevroc worker URL and app details. This gives you a single object that you can use throughout your app for authentication, data access, integrations, and more.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tevrocsdk",
3
- "version": "0.1.33",
3
+ "version": "0.1.34",
4
4
  "description": "JavaScript SDK for the Tevroc API.",
5
5
  "main": "./tevroc-sdk.umd.js",
6
6
  "module": "./tevroc-sdk.esm.js",
package/tevroc-sdk.esm.js CHANGED
@@ -5027,6 +5027,12 @@ var init_webviewWindow = __esm({
5027
5027
  });
5028
5028
 
5029
5029
  // src/services/useGoogleAuth.js
5030
+ var useGoogleAuth_exports = {};
5031
+ __export(useGoogleAuth_exports, {
5032
+ createGoogleLogin: () => createGoogleLogin,
5033
+ initializeGoogleLogin: () => initializeGoogleLogin,
5034
+ subscribeGoogleLogin: () => subscribeGoogleLogin
5035
+ });
5030
5036
  function emitGoogleLogin(user, err = null) {
5031
5037
  googleListeners.forEach((cb) => {
5032
5038
  try {
@@ -5043,7 +5049,7 @@ function subscribeGoogleLogin(cb) {
5043
5049
  if (i !== -1) googleListeners.splice(i, 1);
5044
5050
  };
5045
5051
  }
5046
- var googleInitialized, googleListeners, authWindowRef, handleCallback, initializeGoogleLogin, createGoogleLogin;
5052
+ var googleInitialized, googleListeners, authWindowRef, authCleanupTimer, authMessageListener, cleanupAuthWindow, handleCallback, initializeGoogleLogin, createGoogleLogin;
5047
5053
  var init_useGoogleAuth = __esm({
5048
5054
  "src/services/useGoogleAuth.js"() {
5049
5055
  init_esm2();
@@ -5053,8 +5059,58 @@ var init_useGoogleAuth = __esm({
5053
5059
  googleInitialized = false;
5054
5060
  googleListeners = [];
5055
5061
  authWindowRef = null;
5062
+ authCleanupTimer = null;
5063
+ authMessageListener = null;
5064
+ cleanupAuthWindow = async () => {
5065
+ if (authCleanupTimer) {
5066
+ clearInterval(authCleanupTimer);
5067
+ authCleanupTimer = null;
5068
+ }
5069
+ if (authMessageListener && typeof window !== "undefined") {
5070
+ window.removeEventListener("message", authMessageListener);
5071
+ authMessageListener = null;
5072
+ }
5073
+ if (authWindowRef) {
5074
+ const currentAuthWindow = authWindowRef;
5075
+ authWindowRef = null;
5076
+ try {
5077
+ if (typeof currentAuthWindow?.close === "function") {
5078
+ await currentAuthWindow.close();
5079
+ }
5080
+ } catch (e) {
5081
+ console.warn("Error closing auth window:", e);
5082
+ }
5083
+ }
5084
+ if (isTauri) {
5085
+ try {
5086
+ const tauriAuthWindow = await WebviewWindow.getByLabel("auth");
5087
+ if (tauriAuthWindow && tauriAuthWindow !== authWindowRef) {
5088
+ await tauriAuthWindow.close();
5089
+ }
5090
+ } catch (e) {
5091
+ console.warn("Error closing Tauri auth window by label:", e);
5092
+ }
5093
+ }
5094
+ if (isCapacitor) {
5095
+ try {
5096
+ await Browser2.close();
5097
+ } catch (e) {
5098
+ console.warn("Error closing Capacitor browser:", e);
5099
+ }
5100
+ }
5101
+ if (typeof window !== "undefined" && window !== window.parent) {
5102
+ try {
5103
+ if (authWindowRef && typeof authWindowRef.close === "function") {
5104
+ await authWindowRef.close();
5105
+ }
5106
+ } catch (e) {
5107
+ console.warn("Error closing popup fallback:", e);
5108
+ }
5109
+ }
5110
+ };
5056
5111
  handleCallback = async (url) => {
5057
5112
  try {
5113
+ await cleanupAuthWindow();
5058
5114
  if (!url?.includes("token=")) return;
5059
5115
  const params = new URLSearchParams(url.split("?")[1]);
5060
5116
  const token = params.get("token");
@@ -5100,14 +5156,7 @@ var init_useGoogleAuth = __esm({
5100
5156
  url = url?.url || url?.payload || null;
5101
5157
  }
5102
5158
  if (!url) return;
5103
- if (authWindowRef) {
5104
- try {
5105
- await authWindowRef.close();
5106
- authWindowRef = null;
5107
- } catch (e) {
5108
- }
5109
- }
5110
- handleCallback(url);
5159
+ await handleCallback(url);
5111
5160
  });
5112
5161
  }
5113
5162
  };
@@ -5159,21 +5208,21 @@ var init_useGoogleAuth = __esm({
5159
5208
  console.error("Popup blocked");
5160
5209
  return;
5161
5210
  }
5162
- const listener = (event) => {
5163
- if (event.origin !== serviceUrl) return;
5211
+ authWindowRef = popup;
5212
+ authMessageListener = async (event) => {
5213
+ const serviceOrigin = new URL(serviceUrl).origin;
5214
+ if (event.origin !== serviceOrigin) return;
5164
5215
  if (event.data?.type === "google-auth") {
5165
5216
  const token = event.data?.token || null;
5166
5217
  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);
5218
+ await handleCallback(url);
5170
5219
  }
5171
5220
  };
5172
- window.addEventListener("message", listener);
5173
- const timer = setInterval(() => {
5221
+ window.addEventListener("message", authMessageListener);
5222
+ authCleanupTimer = setInterval(() => {
5174
5223
  if (popup.closed) {
5175
- clearInterval(timer);
5176
- window.removeEventListener("message", listener);
5224
+ cleanupAuthWindow().catch(() => {
5225
+ });
5177
5226
  }
5178
5227
  }, 500);
5179
5228
  return;
@@ -5224,17 +5273,17 @@ var init_useYocoPayment = __esm({
5224
5273
  }) => {
5225
5274
  try {
5226
5275
  addLog("PAYMENT CALLBACK:", url);
5227
- if (!url?.includes("state=")) return;
5276
+ if (!url?.includes("status=")) return;
5228
5277
  const params = new URLSearchParams(url.split("?")[1]);
5229
- const state = params.get("state");
5230
- addLog("PAYMENT RESULT:", state);
5231
- if (state == "success") {
5278
+ const status = params.get("status");
5279
+ addLog("PAYMENT RESULT:", status);
5280
+ if (status == "success") {
5232
5281
  addLog("PAYMENT SUCCESS");
5233
5282
  } else {
5234
5283
  addLog("PAYMENT FAILED");
5235
5284
  }
5236
- externalCallback(state, null);
5237
- emitPaymentStatus(state, null);
5285
+ externalCallback(status, null);
5286
+ emitPaymentStatus(status, null);
5238
5287
  } catch (err) {
5239
5288
  addLog("PAYMENT CALLBACK ERROR:", err.message);
5240
5289
  externalCallback(null, err);
@@ -5278,13 +5327,15 @@ var init_useYocoPayment = __esm({
5278
5327
  createPayment = async (amountZAR, {
5279
5328
  appId = "tevrocsoft",
5280
5329
  serviceUrl = "https://tevrocsoftapi.netlify.app",
5330
+ payAccount = "default",
5281
5331
  externalCallback = () => {
5282
5332
  }
5283
5333
  } = {}) => {
5284
5334
  await initializePayment(externalCallback);
5285
5335
  const cents = Math.round(Number(amountZAR) * 100);
5286
- const basePaymentUrl = `${serviceUrl}/pay`;
5287
- const paymentUrl = `${basePaymentUrl}?mode=mobile&amount=${cents}&app=${appId}`;
5336
+ const basePaymentUrl = `${serviceUrl.replace(/\/$/, "")}/yoco-pay`;
5337
+ const paymentUrl = `${basePaymentUrl}?mode=mobile&amount=${cents}&app=${appId}&account=${payAccount}`;
5338
+ console.log(basePaymentUrl, paymentUrl);
5288
5339
  if (isCapacitor) {
5289
5340
  await Browser2.open({
5290
5341
  url: paymentUrl
@@ -5292,7 +5343,7 @@ var init_useYocoPayment = __esm({
5292
5343
  return;
5293
5344
  }
5294
5345
  if (isTauri) {
5295
- const url = `${basePaymentUrl}?mode=desktop&amount=${cents}&app=${appId}`;
5346
+ const url = `${basePaymentUrl}?mode=desktop&amount=${cents}&app=${appId}&account=${payAccount}`;
5296
5347
  const win = new WebviewWindow("payment", {
5297
5348
  url,
5298
5349
  title: "Complete Payment",
@@ -5312,7 +5363,55 @@ var init_useYocoPayment = __esm({
5312
5363
  }
5313
5364
  const isLocalhost = window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1";
5314
5365
  const mode = isLocalhost ? "localhost" : "netlify";
5315
- window.location.href = `${basePaymentUrl}?mode=${mode}&amount=${cents}&app=${appId}`;
5366
+ const finalUrl = `${basePaymentUrl}?mode=${mode}&amount=${cents}&app=${appId}`;
5367
+ try {
5368
+ const popup = window.open(finalUrl, "yocoPayment", "width=500,height=650");
5369
+ if (!popup) {
5370
+ window.location.href = finalUrl;
5371
+ return;
5372
+ }
5373
+ let listenerAttached = true;
5374
+ let timerRunning = true;
5375
+ const listener = (event) => {
5376
+ try {
5377
+ const serviceOrigin = new URL(serviceUrl).origin;
5378
+ if (event.origin !== serviceOrigin) return;
5379
+ if (event.data?.type === "payment-result") {
5380
+ const status = event.data?.status || null;
5381
+ listenerAttached = false;
5382
+ timerRunning = false;
5383
+ window.removeEventListener("message", listener);
5384
+ try {
5385
+ popup.close();
5386
+ } catch (e) {
5387
+ }
5388
+ const url = status ? `${window.location.href}${window.location.href.includes("?") ? "&" : "?"}status=${status}` : window.location.href;
5389
+ handlePaymentCallback(url, externalCallback);
5390
+ }
5391
+ } catch (err) {
5392
+ console.error("Payment listener error", err);
5393
+ }
5394
+ };
5395
+ window.addEventListener("message", listener);
5396
+ const timer = setInterval(() => {
5397
+ if (!timerRunning) {
5398
+ clearInterval(timer);
5399
+ return;
5400
+ }
5401
+ if (popup.closed) {
5402
+ clearInterval(timer);
5403
+ timerRunning = false;
5404
+ if (listenerAttached) {
5405
+ listenerAttached = false;
5406
+ window.removeEventListener("message", listener);
5407
+ }
5408
+ }
5409
+ }, 500);
5410
+ return;
5411
+ } catch (e) {
5412
+ window.location.href = finalUrl;
5413
+ return;
5414
+ }
5316
5415
  };
5317
5416
  }
5318
5417
  });
@@ -5859,6 +5958,13 @@ async function getPlatformModule() {
5859
5958
  }
5860
5959
  return platformModule;
5861
5960
  }
5961
+ var googleModule = null;
5962
+ async function getGoogleModule() {
5963
+ if (!googleModule) {
5964
+ googleModule = await Promise.resolve().then(() => (init_useGoogleAuth(), useGoogleAuth_exports));
5965
+ }
5966
+ return googleModule;
5967
+ }
5862
5968
  var TevrocError = class extends Error {
5863
5969
  constructor(message, options = {}) {
5864
5970
  super(message);
@@ -5881,6 +5987,7 @@ var TevrocClient = class {
5881
5987
  this.serviceUrl = normalizeBaseUrl(serviceUrl);
5882
5988
  this.appId = options.appId;
5883
5989
  this.appName = options.appName;
5990
+ this.payAccount = options.payAccount ?? "default";
5884
5991
  this.isNative = options.isNative ?? false;
5885
5992
  this.fetch = (options.fetch ?? globalThis.fetch).bind(globalThis);
5886
5993
  if (typeof this.fetch !== "function") {
@@ -5930,6 +6037,7 @@ var TevrocClient = class {
5930
6037
  const controller = new AbortController();
5931
6038
  const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? this.timeoutMs);
5932
6039
  const token = this.token || getStoredToken();
6040
+ console.log(token, options);
5933
6041
  if (token && options.auth !== false) {
5934
6042
  headers.set("authorization", `Bearer ${token}`);
5935
6043
  }
@@ -5946,7 +6054,7 @@ var TevrocClient = class {
5946
6054
  if (value !== void 0 && value !== null) headers.set(key, String(value));
5947
6055
  }
5948
6056
  }
5949
- console.log(headers, url);
6057
+ console.error(headers, url);
5950
6058
  try {
5951
6059
  const response = await this.fetch(url, {
5952
6060
  method,
@@ -5979,13 +6087,18 @@ function createPlatformApi(client) {
5979
6087
  }
5980
6088
  function createPaymentApi(client) {
5981
6089
  return {
5982
- create: async ({ amountZAR, appId = "tevrocsoft", mode = "web" }) => {
6090
+ create: async ({ amountZAR, appId = "tevrocsoft", mode = "web", account = "default", externalCallback = void 0 } = {}) => {
5983
6091
  return await createPayment(amountZAR, {
5984
6092
  appId,
5985
6093
  serviceUrl: client.serviceUrl,
5986
- mode
6094
+ mode,
6095
+ payAccount: account,
6096
+ externalCallback
5987
6097
  });
5988
6098
  },
6099
+ createCheckout: async (payload = {}) => {
6100
+ return await client.request("/create-checkout", { method: "POST", body: payload, auth: false });
6101
+ },
5989
6102
  onstatus: (callback) => {
5990
6103
  if (typeof callback !== "function") {
5991
6104
  throw new Error("onstatus requires a function");
@@ -5997,31 +6110,83 @@ function createPaymentApi(client) {
5997
6110
  function createAuthApi(client) {
5998
6111
  return {
5999
6112
  async register(input) {
6000
- const result = await client.request("/auth/register", { method: "POST", body: input, auth: false });
6113
+ const body = buildAuthPayload(input, client);
6114
+ const result = await client.request("/auth/register", { method: "POST", body, auth: false });
6001
6115
  if (result.token) client.setToken(result.token);
6002
6116
  return result;
6003
6117
  },
6118
+ // base44
6119
+ loginWithProvider: async (provider, redirectTo, setToken = async () => {
6120
+ }) => {
6121
+ if (provider === "google") {
6122
+ const { createGoogleLogin: createGoogleLogin2, subscribeGoogleLogin: subscribeGoogleLogin2 } = await getGoogleModule();
6123
+ console.log({
6124
+ serviceUrl: client.serviceUrl,
6125
+ appId: client.appId,
6126
+ appName: client.appName
6127
+ });
6128
+ createGoogleLogin2({
6129
+ serviceUrl: client.serviceUrl,
6130
+ appId: client.appId,
6131
+ appName: client.appName
6132
+ });
6133
+ if (redirectTo) {
6134
+ const unsub = subscribeGoogleLogin2(async (user, err) => {
6135
+ console.log("Google callback:", user, err);
6136
+ unsub();
6137
+ if (!user) return;
6138
+ const result = await client.request("/auth/google", {
6139
+ method: "POST",
6140
+ body: buildAuthPayload({ accessToken: user.accessToken }, client),
6141
+ auth: false
6142
+ });
6143
+ console.log(result);
6144
+ await setToken(result.token, result.user);
6145
+ console.log("Redirecting to:", redirectTo);
6146
+ window.location.href = redirectTo;
6147
+ });
6148
+ }
6149
+ }
6150
+ },
6151
+ // extra
6004
6152
  googleLogin: (params) => createGoogleLogin(params),
6005
6153
  onGoogleLogin: (callback) => {
6006
6154
  return subscribeGoogleLogin(callback);
6007
6155
  },
6156
+ //
6008
6157
  async login(input) {
6009
- const result = await client.request("/auth/login", { method: "POST", body: input, auth: false });
6158
+ const body = buildAuthPayload(input, client);
6159
+ const result = await client.request("/auth/login", { method: "POST", body, auth: false });
6010
6160
  if (result.token) client.setToken(result.token);
6011
6161
  return result;
6012
6162
  },
6013
6163
  async logout() {
6014
- const result = await client.request("/auth/logout", { method: "POST" });
6164
+ const result = await client.request("/auth/logout", { method: "POST", body: buildAuthPayload({}, client) });
6015
6165
  client.clearToken();
6016
6166
  return result;
6017
6167
  },
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 })
6168
+ inviteUser: (input) => client.request("/users/invite", { method: "POST", body: buildAuthPayload(input, client) }),
6169
+ acceptInvite: (input) => client.request("/auth/accept-invite", { method: "POST", body: buildAuthPayload(input, client), auth: false }),
6170
+ me: () => client.request("/auth/me", { headers: buildAuthHeaders(client) }),
6171
+ verifyOtp: (input) => client.request("/auth/verify-otp", { method: "POST", body: buildAuthPayload(input, client), auth: false }),
6172
+ changePassword: (input) => client.request("/auth/change-password", { method: "POST", body: buildAuthPayload(input, client) }),
6173
+ resetPassword: (input) => client.request("/auth/reset-password", { method: "POST", body: buildAuthPayload(input, client), auth: false }),
6174
+ loginUrl: (redirectTo) => client.request("/auth/login-url", {
6175
+ query: redirectTo ? { redirectTo, appId: client.appId || void 0 } : { appId: client.appId || void 0 },
6176
+ auth: false
6177
+ })
6023
6178
  };
6024
6179
  }
6180
+ function buildAuthPayload(input = {}, client) {
6181
+ const payload = { ...input || {} };
6182
+ if (client?.appId && payload.appId == null) {
6183
+ payload.appId = client.appId;
6184
+ }
6185
+ return payload;
6186
+ }
6187
+ function buildAuthHeaders(client) {
6188
+ return client?.appId ? { "x-app-id": client.appId } : {};
6189
+ }
6025
6190
  function createEntityRegistry(client) {
6026
6191
  return new Proxy(
6027
6192
  {},