@pagelines/sdk 1.0.148

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 (70) hide show
  1. package/README.md +542 -0
  2. package/dist/AgentProvider.vue_vue_type_script_setup_true_lang-BGCgpGEW.js +42 -0
  3. package/dist/AgentProvider.vue_vue_type_script_setup_true_lang-BGCgpGEW.js.map +1 -0
  4. package/dist/AgentWidgetInline-pTCUPNqY.js +35 -0
  5. package/dist/AgentWidgetInline-pTCUPNqY.js.map +1 -0
  6. package/dist/AgentWidgetModal-BA74AH8E.js +66 -0
  7. package/dist/AgentWidgetModal-BA74AH8E.js.map +1 -0
  8. package/dist/AgentWidgetPopup-pe5CmJfa.js +117 -0
  9. package/dist/AgentWidgetPopup-pe5CmJfa.js.map +1 -0
  10. package/dist/AgentWrap.vue_vue_type_script_setup_true_lang-Bvik7Wdb.js +5139 -0
  11. package/dist/AgentWrap.vue_vue_type_script_setup_true_lang-Bvik7Wdb.js.map +1 -0
  12. package/dist/FModal.vue_vue_type_script_setup_true_lang-cL0BFEkZ.js +172 -0
  13. package/dist/FModal.vue_vue_type_script_setup_true_lang-cL0BFEkZ.js.map +1 -0
  14. package/dist/agent/AgentController.d.ts +81 -0
  15. package/dist/agent/ClientAudio.d.ts +102 -0
  16. package/dist/agent/constants.d.ts +16 -0
  17. package/dist/agent/index.d.ts +10 -0
  18. package/dist/agent/schema.d.ts +46 -0
  19. package/dist/agent/test/AgentController.test.d.ts +1 -0
  20. package/dist/agent/test/utils.test.d.ts +1 -0
  21. package/dist/agent/ui/AgentChat.vue.d.ts +27 -0
  22. package/dist/agent/ui/AgentInputEmail.vue.d.ts +9 -0
  23. package/dist/agent/ui/AgentInputOneTimeCode.vue.d.ts +13 -0
  24. package/dist/agent/ui/AgentModal.vue.d.ts +16 -0
  25. package/dist/agent/ui/AgentProvider.vue.d.ts +22 -0
  26. package/dist/agent/ui/AgentSidebarClose.vue.d.ts +6 -0
  27. package/dist/agent/ui/AgentWidget.vue.d.ts +17 -0
  28. package/dist/agent/ui/AgentWrap.vue.d.ts +128 -0
  29. package/dist/agent/ui/ElAgentAbout.vue.d.ts +6 -0
  30. package/dist/agent/ui/ElAgentButton.vue.d.ts +26 -0
  31. package/dist/agent/ui/ElAgentChat.vue.d.ts +11 -0
  32. package/dist/agent/ui/ElAgentHeader.vue.d.ts +6 -0
  33. package/dist/agent/ui/ElAgentModeSidebar.vue.d.ts +11 -0
  34. package/dist/agent/ui/ElAgentSidebar.vue.d.ts +14 -0
  35. package/dist/agent/ui/ElAuthGate.vue.d.ts +6 -0
  36. package/dist/agent/ui/ElModeHeader.vue.d.ts +9 -0
  37. package/dist/agent/ui/ElSidebar.vue.d.ts +30 -0
  38. package/dist/agent/utils.d.ts +34 -0
  39. package/dist/agent.js +162 -0
  40. package/dist/agent.js.map +1 -0
  41. package/dist/api.d.ts +23 -0
  42. package/dist/constants/socialPlatforms.d.ts +10 -0
  43. package/dist/demo/index.d.ts +105 -0
  44. package/dist/demo.js +264 -0
  45. package/dist/demo.js.map +1 -0
  46. package/dist/index.d.ts +7 -0
  47. package/dist/sdk.css +1 -0
  48. package/dist/sdk.js +9 -0
  49. package/dist/sdk.js.map +1 -0
  50. package/dist/sdkClient-BmWhfelO.js +939 -0
  51. package/dist/sdkClient-BmWhfelO.js.map +1 -0
  52. package/dist/sdkClient.d.ts +762 -0
  53. package/dist/sdkStorage.d.ts +39 -0
  54. package/dist/socialPlatforms-Ck-b3SnQ.js +82 -0
  55. package/dist/socialPlatforms-Ck-b3SnQ.js.map +1 -0
  56. package/dist/test/api.test.d.ts +1 -0
  57. package/dist/test/build.test.d.ts +1 -0
  58. package/dist/types/SDKAppType.stub.d.ts +6 -0
  59. package/dist/vite-env.d.ts +13 -0
  60. package/dist/vite.config.sdk.d.ts +2 -0
  61. package/dist/vitest.config.d.ts +2 -0
  62. package/dist/widget/PLWidget.d.ts +55 -0
  63. package/dist/widget/composables/usePLWidget.d.ts +57 -0
  64. package/dist/widget/index.d.ts +4 -0
  65. package/dist/widget/ui/AgentWidgetInline.vue.d.ts +17 -0
  66. package/dist/widget/ui/AgentWidgetModal.vue.d.ts +22 -0
  67. package/dist/widget/ui/AgentWidgetPopup.vue.d.ts +24 -0
  68. package/dist/widget.js +188 -0
  69. package/dist/widget.js.map +1 -0
  70. package/package.json +94 -0
@@ -0,0 +1,939 @@
1
+ var V = Object.defineProperty;
2
+ var Z = (d, o, e) => o in d ? V(d, o, { enumerable: !0, configurable: !0, writable: !0, value: e }) : d[o] = e;
3
+ var l = (d, o) => V(d, "name", { value: o, configurable: !0 });
4
+ var s = (d, o, e) => Z(d, typeof o != "symbol" ? o + "" : o, e);
5
+ import { APP_PORT as F, APP_PROD_URL as D } from "@pagelines/types";
6
+ import { watch as W, ref as C, computed as H } from "vue";
7
+ import { hc as ee } from "hono/client";
8
+ function O(d = {}) {
9
+ const { prefix: o = "id_" } = d, e = o.length >= 3 ? o.substring(0, 3) : o.padEnd(3, "_"), t = Math.floor(Date.now() / 1e3).toString(16).padStart(8, "0");
10
+ let r = "";
11
+ for (let i = 0; i < 16; i++)
12
+ r += Math.floor(Math.random() * 16).toString(16);
13
+ return e + t + r;
14
+ }
15
+ l(O, "objectId");
16
+ const b = globalThis.process, m = typeof window < "u", P = typeof b < "u" && !m, I = m ? typeof window < "u" && window.location && !window.location.hostname.includes("localhost") : P && typeof b < "u" && b.env?.NODE_ENV === "production", te = !I, x = {
17
+ error: { priority: 50, color: "#FF0000", nodeColor: "\x1B[31m" },
18
+ warn: { priority: 40, color: "#FFA500", nodeColor: "\x1B[33m" },
19
+ info: { priority: 30, color: "#00ABFF", nodeColor: "\x1B[36m" },
20
+ debug: { priority: 20, color: "#00BD0C", nodeColor: "\x1B[32m" },
21
+ trace: { priority: 10, color: "#5233FF", nodeColor: "\x1B[35m" }
22
+ }, oe = ["password", "token", "secret", "apikey", "api_key", "authorization", "cookie"], k = class k {
23
+ constructor(o = {}, e) {
24
+ s(this, "settings");
25
+ s(this, "enabledInBrowser", !1);
26
+ s(this, "context");
27
+ this.context = e, this.settings = {
28
+ enabled: o.enabled ?? !0,
29
+ minLevel: o.minLevel ?? this.getDefaultLevel(),
30
+ timestamps: o.timestamps ?? !0
31
+ }, m && this.initBrowserLogging();
32
+ }
33
+ getDefaultLevel() {
34
+ if (P && typeof b < "u" && b.env?.LOG_LEVEL)
35
+ return b.env.LOG_LEVEL;
36
+ if (m && typeof localStorage < "u" && typeof localStorage.getItem == "function") {
37
+ const o = localStorage.getItem("PAGELINES_LOG_LEVEL");
38
+ if (o)
39
+ return o;
40
+ }
41
+ return I ? "info" : "debug";
42
+ }
43
+ initBrowserLogging() {
44
+ if (!m)
45
+ return;
46
+ const e = typeof localStorage?.getItem == "function" && localStorage.getItem("PAGELINES_LOG") === "true", t = window.location?.hostname || "";
47
+ this.enabledInBrowser = te || e || t === "localhost" || t.includes("127.0.0.1"), I && !e && !k.hasShownHelp && (console.log(
48
+ "%cPageLines Logger (disabled in production)",
49
+ "color: #888; font-size: 12px"
50
+ ), console.log(
51
+ '%cTo enable: localStorage.setItem("PAGELINES_LOG", "true")',
52
+ "color: #888; font-size: 11px"
53
+ ), k.hasShownHelp = !0);
54
+ }
55
+ shouldLog(o) {
56
+ if (!this.settings.enabled || m && !this.enabledInBrowser)
57
+ return !1;
58
+ const e = x[o].priority, t = x[this.settings.minLevel].priority;
59
+ return e >= t;
60
+ }
61
+ formatTimestamp() {
62
+ return (/* @__PURE__ */ new Date()).toLocaleTimeString("en-GB", {
63
+ hour12: !1,
64
+ hour: "2-digit",
65
+ minute: "2-digit",
66
+ second: "2-digit"
67
+ });
68
+ }
69
+ formatISOTimestamp() {
70
+ return (/* @__PURE__ */ new Date()).toISOString();
71
+ }
72
+ redactSensitive(o) {
73
+ if (typeof o != "object" || o === null)
74
+ return o;
75
+ if (Array.isArray(o))
76
+ return o.map((t) => this.redactSensitive(t));
77
+ const e = {};
78
+ for (const [t, r] of Object.entries(o)) {
79
+ const i = t.toLowerCase();
80
+ oe.some((n) => i.includes(n)) ? e[t] = "[REDACTED]" : typeof r == "object" && r !== null ? e[t] = this.redactSensitive(r) : e[t] = r;
81
+ }
82
+ return e;
83
+ }
84
+ formatData(o, e = 3, t = 0) {
85
+ if (t >= e)
86
+ return "[Max Depth]";
87
+ if (o == null)
88
+ return o;
89
+ if (o instanceof Error)
90
+ return {
91
+ name: o.name,
92
+ message: o.message,
93
+ stack: I ? o.stack?.split(`
94
+ `).slice(0, 3).join(`
95
+ `) : o.stack,
96
+ ...o
97
+ // Include any additional error properties
98
+ };
99
+ if (o instanceof Date)
100
+ return o.toISOString();
101
+ if (typeof o != "object")
102
+ return o;
103
+ if (Array.isArray(o))
104
+ return o.length > 20 && I ? `Array(${o.length}) [${o.slice(0, 3).map((r) => this.formatData(r, e, t + 1)).join(", ")}, ...]` : o.map((r) => this.formatData(r, e, t + 1));
105
+ try {
106
+ const r = {}, i = Object.entries(o), n = I ? 50 : 200;
107
+ for (const [c, u] of i.slice(0, n))
108
+ r[c] = this.formatData(u, e, t + 1);
109
+ return i.length > n && (r["..."] = `${i.length - n} more properties`), this.redactSensitive(r);
110
+ } catch {
111
+ return "[Unserializable]";
112
+ }
113
+ }
114
+ logToBrowser(o) {
115
+ if (!m || !this.shouldLog(o.level))
116
+ return;
117
+ const { level: e, description: t, context: r, data: i, error: n } = o, c = x[e], a = `[${r || this.context || "www"}] ${e.toUpperCase()}:`, h = `color: ${c.color}; font-weight: bold;`;
118
+ i !== void 0 ? console[e](`%c${a}`, h, t, this.formatData(i)) : console[e](`%c${a}`, h, t), n && (n instanceof Error ? console.error(n) : console.error("Error details:", n));
119
+ }
120
+ logToNode(o) {
121
+ if (!P || !this.shouldLog(o.level))
122
+ return;
123
+ const { level: e, description: t, context: r, data: i, error: n } = o, c = r || this.context || "www";
124
+ if (I) {
125
+ const u = {
126
+ timestamp: this.formatISOTimestamp(),
127
+ level: e.toUpperCase()
128
+ };
129
+ i && (u.data = this.formatData(i)), n && (u.error = this.formatData(n)), console[e](`${u.timestamp} ${u.level} [${c}] ${t}`, i || n ? JSON.stringify({ data: i, error: n }) : "");
130
+ } else {
131
+ const u = x[e], a = this.formatTimestamp(), h = "\x1B[0m", w = "\x1B[2m", S = u.nodeColor || "", g = `${w}${a}${h} ${S}${e.toUpperCase()} (${c}):${h} ${t}`;
132
+ console[e](g), i !== void 0 && console.log(JSON.stringify(this.formatData(i), null, 2)), n && (n instanceof Error ? (console.error(`\x1B[31mError:${h}`, n.message), n.stack && console.error(`\x1B[90m${n.stack}${h}`)) : console.error("Error:", n));
133
+ }
134
+ }
135
+ log(o) {
136
+ m ? this.logToBrowser(o) : P && this.logToNode(o);
137
+ }
138
+ error(o, e) {
139
+ this.log({ level: "error", description: o, data: e, context: this.context });
140
+ }
141
+ warn(o, e) {
142
+ this.log({ level: "warn", description: o, data: e, context: this.context });
143
+ }
144
+ info(o, e) {
145
+ this.log({ level: "info", description: o, data: e, context: this.context });
146
+ }
147
+ debug(o, e) {
148
+ this.log({ level: "debug", description: o, data: e, context: this.context });
149
+ }
150
+ trace(o, e) {
151
+ this.log({ level: "trace", description: o, data: e, context: this.context });
152
+ }
153
+ isEnabled() {
154
+ return m ? this.enabledInBrowser : !0;
155
+ }
156
+ setLevel(o) {
157
+ this.settings.minLevel = o;
158
+ }
159
+ createContextLogger(o) {
160
+ const e = new k(this.settings, o);
161
+ return {
162
+ error: /* @__PURE__ */ l((t, r) => e.error(t, r), "error"),
163
+ warn: /* @__PURE__ */ l((t, r) => e.warn(t, r), "warn"),
164
+ info: /* @__PURE__ */ l((t, r) => e.info(t, r), "info"),
165
+ debug: /* @__PURE__ */ l((t, r) => e.debug(t, r), "debug"),
166
+ trace: /* @__PURE__ */ l((t, r) => e.trace(t, r), "trace"),
167
+ isEnabled: /* @__PURE__ */ l(() => e.isEnabled(), "isEnabled"),
168
+ setLevel: /* @__PURE__ */ l((t) => e.setLevel(t), "setLevel")
169
+ };
170
+ }
171
+ };
172
+ l(k, "Logger"), s(k, "hasShownHelp", !1);
173
+ let j = k;
174
+ function Y(d) {
175
+ return new j({}, d).createContextLogger(d);
176
+ }
177
+ l(Y, "createLogger");
178
+ const v = new j();
179
+ v.error.bind(v);
180
+ v.warn.bind(v);
181
+ v.info.bind(v);
182
+ v.debug.bind(v);
183
+ v.trace.bind(v);
184
+ const K = class K {
185
+ constructor(o, e) {
186
+ s(this, "name");
187
+ s(this, "settings");
188
+ s(this, "logger");
189
+ this.name = o, this.settings = e, this.logger = Y(o);
190
+ }
191
+ };
192
+ l(K, "SettingsObject");
193
+ let G = K;
194
+ const q = class q {
195
+ constructor() {
196
+ // Configuration properties
197
+ s(this, "tokenName", "auth-token");
198
+ s(this, "tokenMaxAge", 3600 * 24 * 7);
199
+ // 7 days
200
+ s(this, "fallbackStorageKey", "token");
201
+ // For localStorage migration
202
+ s(this, "productionDomain", ".pagelines.com");
203
+ }
204
+ /**
205
+ * Get cookie value by name
206
+ */
207
+ getCookie(o) {
208
+ if (typeof document > "u")
209
+ return null;
210
+ const e = document.cookie.split(";");
211
+ for (const t of e) {
212
+ const [r, i] = t.trim().split("=");
213
+ if (r === o)
214
+ return decodeURIComponent(i || "");
215
+ }
216
+ return null;
217
+ }
218
+ /**
219
+ * Set cookie with secure defaults
220
+ */
221
+ setCookie(o, e, t = {}) {
222
+ if (typeof document > "u")
223
+ return;
224
+ const {
225
+ secure: r = !0,
226
+ sameSite: i = "lax",
227
+ maxAge: n = 3600 * 24 * 7,
228
+ // 7 days default
229
+ domain: c,
230
+ path: u = "/"
231
+ } = t;
232
+ let a = `${o}=${encodeURIComponent(e)}`;
233
+ a += `; Path=${u}`, a += `; Max-Age=${n}`, a += `; SameSite=${i}`, r && (a += "; Secure"), c && (a += `; Domain=${c}`), document.cookie = a;
234
+ }
235
+ /**
236
+ * Remove cookie by setting expired date
237
+ */
238
+ removeCookie(o, e = {}) {
239
+ this.setCookie(o, "", { ...e, maxAge: 0 });
240
+ }
241
+ /**
242
+ * Check if localStorage is fully functional (some test environments provide partial mocks)
243
+ */
244
+ isLocalStorageFunctional() {
245
+ return typeof window < "u" && typeof window.localStorage?.getItem == "function" && typeof window.localStorage?.setItem == "function" && typeof window.localStorage?.removeItem == "function";
246
+ }
247
+ /**
248
+ * Get auth token with fallback to localStorage for migration
249
+ */
250
+ getAuthToken() {
251
+ const o = this.getCookie(this.tokenName);
252
+ if (o)
253
+ return o;
254
+ if (this.isLocalStorageFunctional()) {
255
+ const e = window.localStorage.getItem(this.fallbackStorageKey);
256
+ if (e)
257
+ return this.setAuthToken(e), window.localStorage.removeItem(this.fallbackStorageKey), e;
258
+ }
259
+ return null;
260
+ }
261
+ /**
262
+ * Set auth token in cookie with production-ready settings
263
+ */
264
+ setAuthToken(o) {
265
+ const e = typeof window < "u" && window.location.hostname !== "localhost";
266
+ this.setCookie(this.tokenName, o, {
267
+ secure: e,
268
+ sameSite: "lax",
269
+ maxAge: this.tokenMaxAge,
270
+ domain: e ? this.productionDomain : void 0,
271
+ path: "/"
272
+ });
273
+ }
274
+ /**
275
+ * Remove auth token
276
+ */
277
+ removeAuthToken() {
278
+ const o = typeof window < "u" && window.location.hostname !== "localhost";
279
+ this.removeCookie(this.tokenName, {
280
+ domain: o ? this.productionDomain : void 0,
281
+ path: "/"
282
+ }), this.isLocalStorageFunctional() && window.localStorage.removeItem(this.fallbackStorageKey);
283
+ }
284
+ };
285
+ l(q, "CookieUtil");
286
+ let M = q;
287
+ const $ = new M();
288
+ function re(d, o) {
289
+ const e = d.apiBase || (d.isDev ? `http://localhost:${F}` : D);
290
+ return ee(e, {
291
+ fetch: /* @__PURE__ */ l(async (r, i) => {
292
+ const n = $.getAuthToken(), c = await fetch(r, {
293
+ ...i,
294
+ headers: {
295
+ ...i?.headers,
296
+ "Content-Type": "application/json",
297
+ // Only include Authorization header if token exists
298
+ ...n && { Authorization: `Bearer ${n}` }
299
+ },
300
+ // Use 'omit' for Bearer tokens (not cookies) to allow CORS wildcard origin
301
+ credentials: "omit"
302
+ });
303
+ if (o) {
304
+ const u = c.json.bind(c);
305
+ c.json = async () => {
306
+ const a = await u();
307
+ return typeof a == "object" && a !== null && "ok" in a && ("user" in a || "token" in a) && o(a), a;
308
+ };
309
+ }
310
+ return c;
311
+ }, "fetch")
312
+ });
313
+ }
314
+ l(re, "createApiClient");
315
+ let ie = /* @__PURE__ */ Symbol("clean"), f = [], y = 0;
316
+ const A = 4, X = /* @__PURE__ */ l(/* @__NO_SIDE_EFFECTS__ */ (d) => {
317
+ let o = [], e = {
318
+ get() {
319
+ return e.lc || e.listen(() => {
320
+ })(), e.value;
321
+ },
322
+ lc: 0,
323
+ listen(t) {
324
+ return e.lc = o.push(t), () => {
325
+ for (let i = y + A; i < f.length; )
326
+ f[i] === t ? f.splice(i, A) : i += A;
327
+ let r = o.indexOf(t);
328
+ ~r && (o.splice(r, 1), --e.lc || e.off());
329
+ };
330
+ },
331
+ notify(t, r) {
332
+ let i = !f.length;
333
+ for (let n of o)
334
+ f.push(n, e.value, t, r);
335
+ if (i) {
336
+ for (y = 0; y < f.length; y += A)
337
+ f[y](
338
+ f[y + 1],
339
+ f[y + 2],
340
+ f[y + 3]
341
+ );
342
+ f.length = 0;
343
+ }
344
+ },
345
+ /* It will be called on last listener unsubscribing.
346
+ We will redefine it in onMount and onStop. */
347
+ off() {
348
+ },
349
+ set(t) {
350
+ let r = e.value;
351
+ r !== t && (e.value = t, e.notify(r));
352
+ },
353
+ subscribe(t) {
354
+ let r = e.listen(t);
355
+ return t(e.value), r;
356
+ },
357
+ value: d
358
+ };
359
+ return process.env.NODE_ENV !== "production" && (e[ie] = () => {
360
+ o = [], e.lc = 0, e.off();
361
+ }), e;
362
+ }, "atom"), U = /* @__PURE__ */ X(void 0), T = /* @__PURE__ */ X(null), z = class z {
363
+ constructor() {
364
+ s(this, "logger", Y("SDKStorage"));
365
+ }
366
+ /**
367
+ * Check if localStorage is fully functional (some test environments provide partial mocks)
368
+ */
369
+ isLocalStorageFunctional() {
370
+ return typeof window < "u" && typeof localStorage?.getItem == "function" && typeof localStorage?.setItem == "function" && typeof localStorage?.removeItem == "function";
371
+ }
372
+ /**
373
+ * Sync Vue reactive refs with global nanostores for cross-page persistence
374
+ */
375
+ syncWithGlobalStores(o, e) {
376
+ const t = U.get(), r = T.get();
377
+ t && (o.value = t), r && (e.value = r), W(o, (i) => {
378
+ U.set(i);
379
+ }, { immediate: !0 }), W(e, (i) => {
380
+ T.set(i);
381
+ }, { immediate: !0 }), U.subscribe((i) => {
382
+ i !== o.value && (o.value = i);
383
+ }), T.subscribe((i) => {
384
+ i !== e.value && (e.value = i);
385
+ });
386
+ }
387
+ /**
388
+ * Load user and token from browser storage on initialization
389
+ */
390
+ loadFromStorage(o, e) {
391
+ if (typeof window > "u")
392
+ return;
393
+ const t = $.getAuthToken();
394
+ if (t && (e.value = t), this.isLocalStorageFunctional())
395
+ try {
396
+ const r = localStorage.getItem("pagelines-user");
397
+ r && (o.value = JSON.parse(r));
398
+ } catch (r) {
399
+ this.logger.error("Failed to load user from localStorage", { data: r });
400
+ }
401
+ }
402
+ /**
403
+ * Save current user and token to browser storage
404
+ */
405
+ saveToStorage(o, e) {
406
+ if (!(typeof window > "u") && (e.value ? $.setAuthToken(e.value) : $.removeAuthToken(), this.isLocalStorageFunctional()))
407
+ try {
408
+ o.value ? localStorage.setItem("pagelines-user", JSON.stringify(o.value)) : localStorage.removeItem("pagelines-user");
409
+ } catch (t) {
410
+ this.logger.error("Failed to save user to localStorage", { data: t });
411
+ }
412
+ }
413
+ /**
414
+ * Clear all stored user data and tokens
415
+ */
416
+ clearStorage() {
417
+ if (!(typeof window > "u")) {
418
+ if ($.removeAuthToken(), this.isLocalStorageFunctional())
419
+ try {
420
+ localStorage.removeItem("pagelines-user");
421
+ } catch (o) {
422
+ this.logger.error("Failed to clear user from localStorage", { data: o });
423
+ }
424
+ U.set(void 0), T.set(null);
425
+ }
426
+ }
427
+ /**
428
+ * Generic localStorage getter
429
+ */
430
+ getItem(o) {
431
+ if (!this.isLocalStorageFunctional())
432
+ return null;
433
+ try {
434
+ return localStorage.getItem(o);
435
+ } catch (e) {
436
+ return this.logger.error("Failed to get item from localStorage", { key: o, error: e }), null;
437
+ }
438
+ }
439
+ /**
440
+ * Generic localStorage setter
441
+ */
442
+ setItem(o, e) {
443
+ if (this.isLocalStorageFunctional())
444
+ try {
445
+ localStorage.setItem(o, e);
446
+ } catch (t) {
447
+ this.logger.error("Failed to set item in localStorage", { key: o, error: t });
448
+ }
449
+ }
450
+ };
451
+ l(z, "SDKStorage");
452
+ let R = z;
453
+ const J = class J {
454
+ constructor() {
455
+ s(this, "key", "__PAGELINES_SDK__");
456
+ }
457
+ get() {
458
+ if (!(typeof window > "u"))
459
+ return globalThis[this.key];
460
+ }
461
+ set(o) {
462
+ typeof window < "u" && (globalThis[this.key] = o);
463
+ }
464
+ delete() {
465
+ typeof window < "u" && delete globalThis[this.key];
466
+ }
467
+ };
468
+ l(J, "SDKGlobal");
469
+ let _ = J;
470
+ const B = new _(), N = class N extends G {
471
+ constructor(e = {}) {
472
+ const t = B.get();
473
+ if (t)
474
+ return console.debug("[PageLinesSDK] Returning existing singleton instance"), t;
475
+ super("PageLinesSDK", e);
476
+ // Vue reactive state
477
+ s(this, "activeUser", C());
478
+ s(this, "token", C(null));
479
+ s(this, "loading", C(!1));
480
+ s(this, "error", C(null));
481
+ s(this, "apiBase", this.settings.apiBase || void 0);
482
+ // Storage handler for persistence
483
+ s(this, "storage", new R());
484
+ // Auto-managed session ID for usage tracking
485
+ s(this, "sessionId", O({ prefix: "ses" }));
486
+ // Typed Hono RPC client - uses SDKAppType (auth/self/usage routes only)
487
+ // Initialized in constructor (definite assignment via singleton pattern)
488
+ s(this, "apiClient");
489
+ // Computed properties derived from activeUser (matches UserClient pattern)
490
+ s(this, "currentAgent", H(() => {
491
+ const e = this.activeUser.value;
492
+ if (!e?.agents)
493
+ return;
494
+ const t = e.primaryAgentId || e.agents[0]?.agentId;
495
+ if (t)
496
+ return e.agents.find((r) => r.agentId === t);
497
+ }));
498
+ s(this, "currentOrg", H(() => {
499
+ const e = this.currentAgent.value;
500
+ if (!e?.orgId)
501
+ return;
502
+ const t = this.activeUser.value;
503
+ if (t?.orgs)
504
+ return t.orgs.find((r) => r.orgId === e.orgId);
505
+ }));
506
+ // Initialization state
507
+ s(this, "initialized");
508
+ s(this, "resolveUser");
509
+ B.set(this), this.apiClient = re(
510
+ { isDev: this.isDev, apiBase: this.apiBase },
511
+ this.processApiResponse.bind(this)
512
+ ), this.logger.info("PageLinesSDK initialized"), this.storage.loadFromStorage(this.activeUser, this.token), this.storage.syncWithGlobalStores(this.activeUser, this.token), this.initialized = new Promise((r) => {
513
+ this.resolveUser = r;
514
+ }), this.token.value && !this.activeUser.value ? this.getCurrentUser().then((r) => {
515
+ this.resolveUser && (this.resolveUser(r), this.resolveUser = void 0);
516
+ }).catch((r) => {
517
+ this.logger.error("Auto user fetch failed", { data: r }), this.resolveUser && (this.resolveUser(void 0), this.resolveUser = void 0);
518
+ }) : this.activeUser.value ? this.resolveUser?.(this.activeUser.value) : this.resolveUser?.(void 0);
519
+ }
520
+ /**
521
+ * Get singleton instance in browser (creates if doesn't exist)
522
+ * Node.js: Always creates new instance (no singleton)
523
+ * Recommended: Use this instead of constructor for shared state
524
+ */
525
+ static getInstance(e = {}) {
526
+ return B.get() || new N(e);
527
+ }
528
+ get isDev() {
529
+ return this.settings.isDev ?? (typeof window < "u" ? window.location.hostname === "localhost" || window.location.hostname.includes("127.0.0.1") : !1);
530
+ }
531
+ // Bypass stub typing for route access (production builds use SDKAppType stub)
532
+ // Runtime types are validated via Zod at API boundaries
533
+ get api() {
534
+ return this.apiClient.api;
535
+ }
536
+ // Process ApiResponse for automatic user/token updates - public for dependency injection
537
+ processApiResponse(e) {
538
+ e.ok && e.user && (this.activeUser.value = e.user, this.logger.info("User updated from API response", { data: e.user })), e.ok && e.token && (this.token.value = e.token, this.storage.saveToStorage(this.activeUser, this.token), this.logger.info("Token updated from API response")), this.resolveUser && e.ok && (this.resolveUser(e.user), this.resolveUser = void 0);
539
+ }
540
+ // Clear all user data and tokens
541
+ clearSession() {
542
+ this.logger.info("Clearing session"), this.activeUser.value = void 0, this.token.value = null, this.error.value = null, this.storage.clearStorage();
543
+ }
544
+ // Full reset - clears session + state + destroys singleton
545
+ clear() {
546
+ this.logger.info("Clearing SDK completely"), this.clearSession(), this.loading.value = !1, this.sessionId = O({ prefix: "ses" }), B.delete();
547
+ }
548
+ // Convenience methods for common auth operations
549
+ async sendCode(e) {
550
+ this.loading.value = !0, this.error.value = null;
551
+ try {
552
+ const r = await (await this.api.auth["check-email"].$post({
553
+ json: { email: e }
554
+ })).json();
555
+ if (!r.ok)
556
+ throw this.error.value = r.error, new Error(r.error);
557
+ } catch (t) {
558
+ this.logger.error("Send code error", { data: t });
559
+ const r = t instanceof Error ? t.message : "Failed to send verification code";
560
+ throw this.error.value = r, t;
561
+ } finally {
562
+ this.loading.value = !1;
563
+ }
564
+ }
565
+ async verifyCode(e, t) {
566
+ this.loading.value = !0, this.error.value = null;
567
+ try {
568
+ const i = await (await this.api.auth["verify-code"].$post({
569
+ json: { email: e, code: t }
570
+ })).json();
571
+ if (!i.ok)
572
+ throw this.error.value = i.error, new Error(i.error);
573
+ } catch (r) {
574
+ this.logger.error("Verify code error", { data: r });
575
+ const i = r instanceof Error ? r.message : "Failed to verify code";
576
+ throw this.error.value = i, r;
577
+ } finally {
578
+ this.loading.value = !1;
579
+ }
580
+ }
581
+ async login(e, t) {
582
+ this.loading.value = !0, this.error.value = null;
583
+ try {
584
+ const i = await (await this.api.auth.login.$post({
585
+ json: { email: e, password: t }
586
+ })).json();
587
+ if (!i.ok)
588
+ throw this.error.value = i.error, new Error(i.error);
589
+ } catch (r) {
590
+ this.logger.error("Login error", { data: r });
591
+ const i = r instanceof Error ? r.message : "Login failed";
592
+ throw this.error.value = i, r;
593
+ } finally {
594
+ this.loading.value = !1;
595
+ }
596
+ }
597
+ async logout() {
598
+ this.loading.value = !0, this.error.value = null;
599
+ try {
600
+ await this.api.auth.logout.$post(), this.activeUser.value = void 0, this.token.value = null, this.storage.clearStorage();
601
+ } catch (e) {
602
+ this.logger.error("Logout error (user still logged out locally)", { data: e }), this.activeUser.value = void 0, this.token.value = null, this.storage.clearStorage();
603
+ } finally {
604
+ this.loading.value = !1;
605
+ }
606
+ }
607
+ async getCurrentUser() {
608
+ if (this.token.value) {
609
+ this.loading.value = !0;
610
+ try {
611
+ const t = await (await this.api.auth.me.$get()).json();
612
+ if (!t.ok) {
613
+ this.error.value = t.error, t.error.includes("Authentication") && (this.activeUser.value = void 0, this.token.value = null, this.storage.clearStorage());
614
+ return;
615
+ }
616
+ return t.user;
617
+ } catch (e) {
618
+ this.logger.error("Get current user error", { data: e }), this.error.value = e instanceof Error ? e.message : "Failed to get user info";
619
+ return;
620
+ } finally {
621
+ this.loading.value = !1;
622
+ }
623
+ }
624
+ }
625
+ async getPublicAgent(e) {
626
+ this.loading.value = !0, this.error.value = null;
627
+ try {
628
+ const r = await (await this.api.agent.public[":handle"].$get({
629
+ param: { handle: e.handle }
630
+ })).json();
631
+ if (!r.ok) {
632
+ this.error.value = r.error, this.logger.error("Failed to fetch public agent", { handle: e.handle, error: r.error });
633
+ return;
634
+ }
635
+ return r.data;
636
+ } catch (t) {
637
+ this.logger.error("Get public agent error", { handle: e.handle, error: t }), this.error.value = t instanceof Error ? t.message : "Failed to fetch agent";
638
+ return;
639
+ } finally {
640
+ this.loading.value = !1;
641
+ }
642
+ }
643
+ async getAgentByEmail(e) {
644
+ this.loading.value = !0, this.error.value = null;
645
+ try {
646
+ const r = await (await this.api.agent["by-email"][":email"].$get({
647
+ param: { email: e.email }
648
+ })).json();
649
+ if (!r.ok) {
650
+ this.error.value = r.error, this.logger.error("Failed to fetch agent by email", { email: e.email, error: r.error });
651
+ return;
652
+ }
653
+ return r.data;
654
+ } catch (t) {
655
+ this.logger.error("Get agent by email error", { email: e.email, error: t }), this.error.value = t instanceof Error ? t.message : "Failed to fetch agent";
656
+ return;
657
+ } finally {
658
+ this.loading.value = !1;
659
+ }
660
+ }
661
+ async requestAuthCode(e) {
662
+ this.loading.value = !0, this.error.value = null;
663
+ try {
664
+ const r = await (await this.api.auth["check-email"].$post({
665
+ json: { email: e.email }
666
+ })).json();
667
+ return r.ok ? (this.logger.info("Auth code requested successfully", { email: e.email }), !0) : (this.error.value = r.error, this.logger.error("Failed to request auth code", { email: e.email, error: r.error }), !1);
668
+ } catch (t) {
669
+ return this.logger.error("Request auth code error", { email: e.email, error: t }), this.error.value = t instanceof Error ? t.message : "Failed to request auth code", !1;
670
+ } finally {
671
+ this.loading.value = !1;
672
+ }
673
+ }
674
+ async loginWithCode(e) {
675
+ this.loading.value = !0, this.error.value = null;
676
+ try {
677
+ const r = await (await this.api.auth["verify-code"].$post({
678
+ json: { email: e.email, code: e.code }
679
+ })).json();
680
+ return this.logger.info("Login with code response", {
681
+ hasUser: !!r.user,
682
+ hasToken: !!r.token,
683
+ ok: r.ok
684
+ }), r.ok ? (this.logger.info("Login successful", { email: e.email }), e.orgId && e.autoCreateContact !== !1 && this.activeUser.value?.userId && await this.autoCreateContact({
685
+ userId: this.activeUser.value.userId,
686
+ orgId: e.orgId
687
+ }), !0) : (this.error.value = r.error, this.logger.error("Login failed", { email: e.email, error: r.error }), !1);
688
+ } catch (t) {
689
+ return this.logger.error("Login with code error", { email: e.email, error: t }), this.error.value = t instanceof Error ? t.message : "Login failed", !1;
690
+ } finally {
691
+ this.loading.value = !1;
692
+ }
693
+ }
694
+ async trackUsage(e) {
695
+ try {
696
+ const t = this.currentAgent.value;
697
+ if (!t?.orgId)
698
+ return this.logger.error("Cannot track usage: no current agent with orgId", { args: e }), !1;
699
+ const i = await (await this.api.usage.record.$post({
700
+ json: {
701
+ orgId: t.orgId,
702
+ agentId: e.agentId,
703
+ sessionId: this.sessionId,
704
+ // Auto-managed by SDK
705
+ type: e.type,
706
+ quantity: e.quantity,
707
+ // Track the participant if provided, otherwise use current user or anonymous
708
+ userId: e.participantId || this.activeUser.value?.userId || "anonymous"
709
+ }
710
+ })).json();
711
+ return i.ok ? !0 : (this.logger.error("Failed to track usage", { error: i.error, args: e }), !1);
712
+ } catch (t) {
713
+ return this.logger.error("Track usage error", { error: t, args: e }), !1;
714
+ }
715
+ }
716
+ /**
717
+ * Auto-create contact on authentication
718
+ * Called internally by loginWithCode - can be disabled with autoCreateContact: false
719
+ */
720
+ async autoCreateContact(e) {
721
+ try {
722
+ const r = await (await this.api.contact.resolve.$post({
723
+ json: { userId: e.userId, orgId: e.orgId }
724
+ })).json();
725
+ return r.ok ? (this.logger.info("Contact resolved", { userId: e.userId, orgId: e.orgId }), !0) : (this.logger.error("Failed to auto-create contact", { error: r.error, args: e }), !1);
726
+ } catch (t) {
727
+ return this.logger.error("Auto-create contact error", { error: t, args: e }), !1;
728
+ }
729
+ }
730
+ /**
731
+ * Start conversation session (auto-creates conversation if needed)
732
+ * Returns conversation data for tracking messages
733
+ */
734
+ async startConversation(e) {
735
+ try {
736
+ const t = this.currentAgent.value;
737
+ if (!t?.orgId) {
738
+ this.logger.error("Cannot start conversation: no current agent with orgId", { args: e });
739
+ return;
740
+ }
741
+ const i = await (await this.api.conversation.start.$post({
742
+ json: {
743
+ orgId: t.orgId,
744
+ agentId: e.agentId,
745
+ userId: e.userId || this.activeUser.value?.userId,
746
+ anonId: e.anonId,
747
+ channel: e.channel
748
+ }
749
+ })).json();
750
+ if (!i.ok || !i.data) {
751
+ const n = i.ok ? "No conversation data returned" : "error" in i ? i.error : "Unknown error";
752
+ this.logger.error("Failed to start conversation", { error: n, args: e });
753
+ return;
754
+ }
755
+ return this.logger.info("Conversation started", { conversationId: i.data.conversationId }), i.data;
756
+ } catch (t) {
757
+ this.logger.error("Start conversation error", { error: t, args: e });
758
+ return;
759
+ }
760
+ }
761
+ /**
762
+ * Generate anonymous ID for tracking unauthenticated users
763
+ * Stored in localStorage for persistence across sessions
764
+ */
765
+ generateAnonId() {
766
+ const e = "pagelinesAnonId";
767
+ let t = this.storage.getItem(e);
768
+ return t || (t = O({ prefix: "anon" }), this.storage.setItem(e, t)), t;
769
+ }
770
+ /**
771
+ * Save message to conversation
772
+ * Called by AgentController to persist messages
773
+ */
774
+ async saveMessage(e) {
775
+ try {
776
+ const r = await (await this.api.conversation.messages.$post({
777
+ json: {
778
+ sessionId: e.conversationId,
779
+ participantId: e.participantId,
780
+ content: e.content,
781
+ role: e.role
782
+ }
783
+ })).json();
784
+ return r.ok ? !0 : (this.logger.error("Failed to save message", { error: "error" in r ? r.error : "Unknown error", args: e }), !1);
785
+ } catch (t) {
786
+ return this.logger.error("Save message error", { error: t, args: e }), !1;
787
+ }
788
+ }
789
+ /**
790
+ * Stream chat with a public agent (no auth required).
791
+ * Uses raw fetch + SSE parsing for streaming responses.
792
+ */
793
+ async chatStream(e) {
794
+ const r = `${this.apiBase || (this.isDev ? `http://localhost:${F}` : D)}/api/agent/public/${encodeURIComponent(e.handle)}/chat/stream`;
795
+ try {
796
+ const i = await fetch(r, {
797
+ method: "POST",
798
+ headers: { "Content-Type": "application/json" },
799
+ body: JSON.stringify({
800
+ message: e.message,
801
+ conversationId: e.conversationId,
802
+ history: e.history,
803
+ visitorId: e.visitorId
804
+ })
805
+ });
806
+ if (!i.ok) {
807
+ const h = await i.json().catch(() => ({ error: "Request failed" }));
808
+ e.onError(h.error || `HTTP ${i.status}`);
809
+ return;
810
+ }
811
+ const n = i.body?.getReader();
812
+ if (!n) {
813
+ e.onError("No response stream");
814
+ return;
815
+ }
816
+ const c = new TextDecoder();
817
+ let u = "", a = e.conversationId || "";
818
+ for (; ; ) {
819
+ const { done: h, value: w } = await n.read();
820
+ if (h)
821
+ break;
822
+ u += c.decode(w, { stream: !0 });
823
+ const S = u.split(`
824
+ `);
825
+ u = S.pop() || "";
826
+ for (const g of S) {
827
+ if (!g.startsWith("data: "))
828
+ continue;
829
+ const L = g.slice(6).trim();
830
+ if (L === "[DONE]") {
831
+ e.onDone(a);
832
+ return;
833
+ }
834
+ try {
835
+ const p = JSON.parse(L);
836
+ p.pl_metadata?.conversationId && (a = p.pl_metadata.conversationId);
837
+ const E = p.choices?.[0]?.delta;
838
+ E?.content && e.onDelta(E.content);
839
+ } catch {
840
+ }
841
+ }
842
+ }
843
+ e.onDone(a);
844
+ } catch (i) {
845
+ e.onError(i instanceof Error ? i.message : "Stream failed");
846
+ }
847
+ }
848
+ /**
849
+ * Non-streaming chat with a public agent (no auth required).
850
+ */
851
+ async chatMessage(e) {
852
+ const r = `${this.apiBase || (this.isDev ? `http://localhost:${F}` : D)}/api/agent/public/${encodeURIComponent(e.handle)}/chat`;
853
+ try {
854
+ const n = await (await fetch(r, {
855
+ method: "POST",
856
+ headers: { "Content-Type": "application/json" },
857
+ body: JSON.stringify({
858
+ message: e.message,
859
+ conversationId: e.conversationId,
860
+ visitorId: e.visitorId
861
+ })
862
+ })).json();
863
+ if (!n.ok || !n.data) {
864
+ this.logger.error("chatMessage failed", { error: !n.ok && "error" in n ? n.error : "Unknown" });
865
+ return;
866
+ }
867
+ return {
868
+ conversationId: n.data.conversationId,
869
+ content: n.data.message.content
870
+ };
871
+ } catch (i) {
872
+ this.logger.error("chatMessage error", { error: i });
873
+ return;
874
+ }
875
+ }
876
+ /**
877
+ * Sign in with Google via popup window
878
+ * Opens app.pagelines.com/auth/google-popup which handles the full OAuth flow,
879
+ * then postMessages the token/user back to this window.
880
+ */
881
+ loginWithGoogle(e) {
882
+ if (typeof window > "u") {
883
+ this.logger.error("loginWithGoogle: Only available in browser");
884
+ return;
885
+ }
886
+ const t = this.apiBase || (this.isDev ? `http://localhost:${F}` : D), r = window.location.origin, i = `${t}/auth/google-popup?origin=${encodeURIComponent(r)}`, n = 500, c = 600, u = window.screenX + (window.outerWidth - n) / 2, a = window.screenY + (window.outerHeight - c) / 2, h = window.open(
887
+ i,
888
+ "google-auth",
889
+ `width=${n},height=${c},left=${u},top=${a},popup=yes`
890
+ );
891
+ if (!h) {
892
+ const g = "Popup was blocked. Please allow popups for this site.";
893
+ this.error.value = g, e?.onError?.(g);
894
+ return;
895
+ }
896
+ const w = /* @__PURE__ */ l((g) => {
897
+ const L = new URL(t).origin;
898
+ if (g.origin === L) {
899
+ if (g.data?.type === "auth-success") {
900
+ window.removeEventListener("message", w);
901
+ const { token: p, user: E } = g.data;
902
+ this.processApiResponse({ ok: !0, data: {}, token: p, user: E }), this.logger.info("Google login successful"), e?.onSuccess?.(E);
903
+ } else if (g.data?.type === "auth-error") {
904
+ window.removeEventListener("message", w);
905
+ const p = g.data.error || "Google authentication failed";
906
+ this.error.value = p, this.logger.error("Google login failed", { error: p }), e?.onError?.(p);
907
+ }
908
+ }
909
+ }, "handler");
910
+ window.addEventListener("message", w);
911
+ const S = setInterval(() => {
912
+ h.closed && (clearInterval(S), window.removeEventListener("message", w));
913
+ }, 500);
914
+ }
915
+ /**
916
+ * Track conversion events (view_profile, profile_interaction)
917
+ * Sends event to parent window if embedded, otherwise logs locally
918
+ */
919
+ track(e) {
920
+ try {
921
+ typeof window < "u" && window.parent !== window && window.parent.postMessage({
922
+ type: "pagelines_track",
923
+ event: e.event,
924
+ agentId: e.agentId,
925
+ properties: e.properties || {}
926
+ }, "*"), this.logger.info("SDK event tracked", { event: e.event, agentId: e.agentId });
927
+ } catch (t) {
928
+ this.logger.error("Track event error", { error: t, args: e });
929
+ }
930
+ }
931
+ };
932
+ l(N, "PageLinesSDK");
933
+ let Q = N;
934
+ export {
935
+ Q as P,
936
+ G as S,
937
+ Y as c
938
+ };
939
+ //# sourceMappingURL=sdkClient-BmWhfelO.js.map