@pagelines/sdk 1.0.472 → 1.0.473

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/dist/sdkClient.js CHANGED
@@ -1,28 +1,28 @@
1
- var Q = Object.defineProperty;
2
- var Y = (c, e, t) => e in c ? Q(c, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : c[e] = t;
3
- var l = (c, e) => Q(c, "name", { value: e, configurable: !0 });
4
- var i = (c, e, t) => Y(c, typeof e != "symbol" ? e + "" : e, t);
5
- import { APP_PORT as Z, APP_PROD_URL as ee, createRefreshingFetch as te, cookieUtil as x, createLogger as re, objectId as B, SettingsObject as oe } from "@pagelines/core";
6
- import { watch as $, ref as k, computed as V } from "vue";
7
- import { hc as se } from "hono/client";
8
- function f(c, e) {
9
- return c || (e ? `http://localhost:${Z}` : ee);
1
+ var V = Object.defineProperty;
2
+ var Z = (l, e, t) => e in l ? V(l, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : l[e] = t;
3
+ var d = (l, e) => V(l, "name", { value: e, configurable: !0 });
4
+ var n = (l, e, t) => Z(l, typeof e != "symbol" ? e + "" : e, t);
5
+ import { APP_PORT as ee, APP_PROD_URL as te, createRefreshingFetch as re, cookieUtil as b, createLogger as oe, shortId as se, objectId as O, SettingsObject as ae } from "@pagelines/core";
6
+ import { watch as R, ref as A, computed as Q } from "vue";
7
+ import { hc as ie } from "hono/client";
8
+ function y(l, e) {
9
+ return l || (e ? `http://localhost:${ee}` : te);
10
10
  }
11
- l(f, "resolveApiBase");
12
- function ie(c, e, t) {
13
- const r = f(c.apiBase, c.isDev), o = t ? te({
11
+ d(y, "resolveApiBase");
12
+ function ne(l, e, t) {
13
+ const r = y(l.apiBase, l.isDev), o = t ? re({
14
14
  fetch: globalThis.fetch.bind(globalThis),
15
15
  getDeviceId: t.getDeviceId,
16
16
  refreshUrl: `${r}/api/auth/refresh`,
17
17
  onAccessTokenRefreshed: t.onAccessTokenRefreshed,
18
18
  onTerminalFailure: t.onTerminalFailure
19
19
  }) : globalThis.fetch.bind(globalThis);
20
- return se(r, {
21
- fetch: /* @__PURE__ */ l(async (n, u) => {
22
- const a = x.getAuthToken(), d = await o(n, {
23
- ...u,
20
+ return ie(r, {
21
+ fetch: /* @__PURE__ */ d(async (c, h) => {
22
+ const a = b.getAuthToken(), i = await o(c, {
23
+ ...h,
24
24
  headers: {
25
- ...u?.headers,
25
+ ...h?.headers,
26
26
  "Content-Type": "application/json",
27
27
  // Only include Authorization header if token exists
28
28
  ...a && { Authorization: `Bearer ${a}` }
@@ -34,46 +34,46 @@ function ie(c, e, t) {
34
34
  credentials: "include"
35
35
  });
36
36
  if (e) {
37
- const p = d.json.bind(d);
38
- d.json = async () => {
39
- const g = await p();
40
- return typeof g == "object" && g !== null && "ok" in g && ("user" in g || "token" in g) && e(g), g;
37
+ const f = i.json.bind(i);
38
+ i.json = async () => {
39
+ const u = await f();
40
+ return typeof u == "object" && u !== null && "ok" in u && ("user" in u || "token" in u) && e(u), u;
41
41
  };
42
42
  }
43
- return d;
43
+ return i;
44
44
  }, "fetch")
45
45
  });
46
46
  }
47
- l(ie, "createApiClient");
48
- let ae = /* @__PURE__ */ Symbol("clean"), v = [], y = 0;
49
- const b = 4, L = /* @__PURE__ */ l(/* @__NO_SIDE_EFFECTS__ */ (c) => {
47
+ d(ne, "createApiClient");
48
+ let ce = /* @__PURE__ */ Symbol("clean"), p = [], x = 0;
49
+ const U = 4, W = /* @__PURE__ */ d(/* @__NO_SIDE_EFFECTS__ */ (l) => {
50
50
  let e = [], t = {
51
51
  get() {
52
52
  return t.lc || t.listen(() => {
53
53
  })(), t.value;
54
54
  },
55
- init: c,
55
+ init: l,
56
56
  lc: 0,
57
57
  listen(r) {
58
58
  return t.lc = e.push(r), () => {
59
- for (let s = y + b; s < v.length; )
60
- v[s] === r ? v.splice(s, b) : s += b;
59
+ for (let s = x + U; s < p.length; )
60
+ p[s] === r ? p.splice(s, U) : s += U;
61
61
  let o = e.indexOf(r);
62
62
  ~o && (e.splice(o, 1), --t.lc || t.off());
63
63
  };
64
64
  },
65
65
  notify(r, o) {
66
- let s = !v.length;
67
- for (let n of e)
68
- v.push(n, t.value, r, o);
66
+ let s = !p.length;
67
+ for (let c of e)
68
+ p.push(c, t.value, r, o);
69
69
  if (s) {
70
- for (y = 0; y < v.length; y += b)
71
- v[y](
72
- v[y + 1],
73
- v[y + 2],
74
- v[y + 3]
70
+ for (x = 0; x < p.length; x += U)
71
+ p[x](
72
+ p[x + 1],
73
+ p[x + 2],
74
+ p[x + 3]
75
75
  );
76
- v.length = 0;
76
+ p.length = 0;
77
77
  }
78
78
  },
79
79
  /* It will be called on last listener unsubscribing.
@@ -88,14 +88,14 @@ const b = 4, L = /* @__PURE__ */ l(/* @__NO_SIDE_EFFECTS__ */ (c) => {
88
88
  let o = t.listen(r);
89
89
  return r(t.value), o;
90
90
  },
91
- value: c
91
+ value: l
92
92
  };
93
- return process.env.NODE_ENV !== "production" && (t[ae] = () => {
93
+ return process.env.NODE_ENV !== "production" && (t[ce] = () => {
94
94
  e = [], t.lc = 0, t.off();
95
95
  }), t;
96
- }, "atom"), m = globalThis, A = m.__PL_AUTH_USER__ ?? (m.__PL_AUTH_USER__ = /* @__PURE__ */ L(void 0)), U = m.__PL_AUTH_TOKEN__ ?? (m.__PL_AUTH_TOKEN__ = /* @__PURE__ */ L(null)), E = m.__PL_AUTH_DEVICE_ID__ ?? (m.__PL_AUTH_DEVICE_ID__ = /* @__PURE__ */ L(null)), N = class N {
96
+ }, "atom"), w = globalThis, E = w.__PL_AUTH_USER__ ?? (w.__PL_AUTH_USER__ = /* @__PURE__ */ W(void 0)), T = w.__PL_AUTH_TOKEN__ ?? (w.__PL_AUTH_TOKEN__ = /* @__PURE__ */ W(null)), $ = w.__PL_AUTH_DEVICE_ID__ ?? (w.__PL_AUTH_DEVICE_ID__ = /* @__PURE__ */ W(null)), G = class G {
97
97
  constructor() {
98
- i(this, "logger", re("SDKStorage"));
98
+ n(this, "logger", oe("SDKStorage"));
99
99
  }
100
100
  /**
101
101
  * Check if localStorage is fully functional (some test environments provide partial mocks)
@@ -107,12 +107,12 @@ const b = 4, L = /* @__PURE__ */ l(/* @__NO_SIDE_EFFECTS__ */ (c) => {
107
107
  * Sync Vue reactive refs with global nanostores for cross-bundle persistence.
108
108
  */
109
109
  syncWithGlobalStores(e) {
110
- const { activeUser: t, token: r, deviceId: o } = e, s = A.get(), n = U.get(), u = E.get();
111
- s && (t.value = s), n && (r.value = n), u && (o.value = u), $(t, (a) => A.set(a), { immediate: !0 }), $(r, (a) => U.set(a), { immediate: !0 }), $(o, (a) => E.set(a), { immediate: !0 }), A.subscribe((a) => {
110
+ const { activeUser: t, token: r, deviceId: o } = e, s = E.get(), c = T.get(), h = $.get();
111
+ s && (t.value = s), c && (r.value = c), h && (o.value = h), R(t, (a) => E.set(a), { immediate: !0 }), R(r, (a) => T.set(a), { immediate: !0 }), R(o, (a) => $.set(a), { immediate: !0 }), E.subscribe((a) => {
112
112
  a !== t.value && (t.value = a);
113
- }), U.subscribe((a) => {
113
+ }), T.subscribe((a) => {
114
114
  a !== r.value && (r.value = a);
115
- }), E.subscribe((a) => {
115
+ }), $.subscribe((a) => {
116
116
  a !== o.value && (o.value = a);
117
117
  });
118
118
  }
@@ -123,9 +123,9 @@ const b = 4, L = /* @__PURE__ */ l(/* @__NO_SIDE_EFFECTS__ */ (c) => {
123
123
  loadFromStorage(e) {
124
124
  if (typeof window > "u")
125
125
  return;
126
- const t = x.getAuthToken();
126
+ const t = b.getAuthToken();
127
127
  t && (e.token.value = t);
128
- const r = x.getDeviceId();
128
+ const r = b.getDeviceId();
129
129
  if (r && (e.deviceId.value = r), this.isLocalStorageFunctional())
130
130
  try {
131
131
  const o = localStorage.getItem("pagelines-user");
@@ -139,7 +139,7 @@ const b = 4, L = /* @__PURE__ */ l(/* @__NO_SIDE_EFFECTS__ */ (c) => {
139
139
  * deviceId is server-owned (Set-Cookie) — JS doesn't write it.
140
140
  */
141
141
  saveToStorage(e) {
142
- if (!(typeof window > "u") && (e.token.value ? x.setAuthToken(e.token.value) : x.removeAuthToken(), this.isLocalStorageFunctional()))
142
+ if (!(typeof window > "u") && (e.token.value ? b.setAuthToken(e.token.value) : b.removeAuthToken(), this.isLocalStorageFunctional()))
143
143
  try {
144
144
  e.activeUser.value ? localStorage.setItem("pagelines-user", JSON.stringify(e.activeUser.value)) : localStorage.removeItem("pagelines-user");
145
145
  } catch (t) {
@@ -153,13 +153,13 @@ const b = 4, L = /* @__PURE__ */ l(/* @__NO_SIDE_EFFECTS__ */ (c) => {
153
153
  */
154
154
  clearStorage() {
155
155
  if (!(typeof window > "u")) {
156
- if (x.removeAuthToken(), this.isLocalStorageFunctional())
156
+ if (b.removeAuthToken(), this.isLocalStorageFunctional())
157
157
  try {
158
158
  localStorage.removeItem("pagelines-user");
159
159
  } catch (e) {
160
160
  this.logger.error("Failed to clear user from localStorage", { data: e });
161
161
  }
162
- A.set(void 0), U.set(null), E.set(null);
162
+ E.set(void 0), T.set(null), $.set(null);
163
163
  }
164
164
  }
165
165
  /**
@@ -186,20 +186,20 @@ const b = 4, L = /* @__PURE__ */ l(/* @__NO_SIDE_EFFECTS__ */ (c) => {
186
186
  }
187
187
  }
188
188
  };
189
- l(N, "SDKStorage");
190
- let R = N;
191
- const H = [
189
+ d(G, "SDKStorage");
190
+ let P = G;
191
+ const X = [
192
192
  "Deploying your server...",
193
193
  "Setting up your workspace...",
194
194
  "Installing tools...",
195
195
  "Almost ready..."
196
- ], G = class G {
196
+ ], M = class M {
197
197
  constructor(e) {
198
- i(this, "ctx");
198
+ n(this, "ctx");
199
199
  this.ctx = e;
200
200
  }
201
201
  async create(e) {
202
- const t = e.orgId || this.resolveOrgId(), r = f(this.ctx.apiBase, this.ctx.isDev), s = await (await fetch(`${r}/api/agent`, {
202
+ const t = e.orgId || this.resolveOrgId(), r = y(this.ctx.apiBase, this.ctx.isDev), s = await (await fetch(`${r}/api/agent`, {
203
203
  method: "POST",
204
204
  headers: {
205
205
  "Content-Type": "application/json",
@@ -208,13 +208,13 @@ const H = [
208
208
  body: JSON.stringify({ name: e.name, orgId: t })
209
209
  })).json();
210
210
  if (!s.ok || !s.data?.[0]) {
211
- const n = s.error || "Failed to create agent";
212
- throw this.ctx.error.value = n, new Error(n);
211
+ const c = s.error || "Failed to create agent";
212
+ throw this.ctx.error.value = c, new Error(c);
213
213
  }
214
214
  return this.ctx.processApiResponse(s), s.data[0];
215
215
  }
216
216
  async getStatus(e) {
217
- const t = f(this.ctx.apiBase, this.ctx.isDev), o = await (await fetch(`${t}/api/agent/${e.agentId}/status`, {
217
+ const t = y(this.ctx.apiBase, this.ctx.isDev), o = await (await fetch(`${t}/api/agent/${e.agentId}/status`, {
218
218
  headers: {
219
219
  ...this.ctx.token.value && { Authorization: `Bearer ${this.ctx.token.value}` }
220
220
  }
@@ -222,9 +222,9 @@ const H = [
222
222
  return !o.ok || !o.data ? { status: "unknown", ready: !1, error: "Failed to check status" } : o.data;
223
223
  }
224
224
  async waitUntilReady(e) {
225
- const { agentId: t, onStatus: r, timeoutMs: o = 3e5, pollIntervalMs: s = 3e3 } = e, n = Date.now();
226
- let u = 0;
227
- for (; Date.now() - n < o; ) {
225
+ const { agentId: t, onStatus: r, timeoutMs: o = 3e5, pollIntervalMs: s = 3e3 } = e, c = Date.now();
226
+ let h = 0;
227
+ for (; Date.now() - c < o; ) {
228
228
  const a = await this.getStatus({ agentId: t });
229
229
  if (a.ready) {
230
230
  r?.("Ready!");
@@ -232,13 +232,13 @@ const H = [
232
232
  }
233
233
  if (a.status === "error")
234
234
  throw new Error(a.error || "Provisioning failed");
235
- r && u < H.length && (r(H[u]), u++), await new Promise((d) => setTimeout(d, s));
235
+ r && h < X.length && (r(X[h]), h++), await new Promise((i) => setTimeout(i, s));
236
236
  }
237
237
  throw new Error("Agent provisioning timed out — please try again");
238
238
  }
239
239
  /** Send a typed webhook event to a bot agent. No auth required — the proxy is public. */
240
240
  async webhook(e) {
241
- const r = `${f(this.ctx.apiBase, this.ctx.isDev)}/api/bot-api/agents/${e.agentId}/webhook`, o = { type: e.type, data: e.data };
241
+ const r = `${y(this.ctx.apiBase, this.ctx.isDev)}/api/bot-api/agents/${e.agentId}/webhook`, o = { type: e.type, data: e.data };
242
242
  e.meta && (o.meta = e.meta);
243
243
  const s = await fetch(r, {
244
244
  method: "POST",
@@ -246,8 +246,8 @@ const H = [
246
246
  body: JSON.stringify(o)
247
247
  });
248
248
  if (!s.ok) {
249
- const n = await s.text().catch(() => "Unknown error");
250
- throw new Error(`Webhook delivery failed (${s.status}): ${n.slice(0, 200)}`);
249
+ const c = await s.text().catch(() => "Unknown error");
250
+ throw new Error(`Webhook delivery failed (${s.status}): ${c.slice(0, 200)}`);
251
251
  }
252
252
  return s.json();
253
253
  }
@@ -258,24 +258,24 @@ const H = [
258
258
  return t;
259
259
  }
260
260
  };
261
- l(G, "AgentClient");
262
- let P = G;
263
- async function w(c, e) {
264
- c.loading.value = !0, c.error.value = null;
261
+ d(M, "AgentClient");
262
+ let _ = M;
263
+ async function S(l, e) {
264
+ l.loading.value = !0, l.error.value = null;
265
265
  try {
266
266
  return await e();
267
267
  } finally {
268
- c.loading.value = !1;
268
+ l.loading.value = !1;
269
269
  }
270
270
  }
271
- l(w, "withLoadingState");
272
- const M = class M {
271
+ d(S, "withLoadingState");
272
+ const z = class z {
273
273
  constructor(e) {
274
- i(this, "ctx");
274
+ n(this, "ctx");
275
275
  this.ctx = e;
276
276
  }
277
277
  async sendCode(e) {
278
- return w(this.ctx, async () => {
278
+ return S(this.ctx, async () => {
279
279
  try {
280
280
  const r = await (await this.ctx.api.auth["check-email"].$post({
281
281
  json: { email: e }
@@ -290,7 +290,7 @@ const M = class M {
290
290
  });
291
291
  }
292
292
  async verifyCode(e, t) {
293
- return w(this.ctx, async () => {
293
+ return S(this.ctx, async () => {
294
294
  try {
295
295
  const o = await (await this.ctx.api.auth["verify-code"].$post({
296
296
  json: { email: e, code: t }
@@ -305,7 +305,7 @@ const M = class M {
305
305
  });
306
306
  }
307
307
  async logout() {
308
- return w(this.ctx, async () => {
308
+ return S(this.ctx, async () => {
309
309
  try {
310
310
  await this.ctx.api.auth.logout.$post();
311
311
  } catch (e) {
@@ -316,7 +316,7 @@ const M = class M {
316
316
  }
317
317
  async getCurrentUser() {
318
318
  if (this.ctx.token.value)
319
- return w(this.ctx, async () => {
319
+ return S(this.ctx, async () => {
320
320
  try {
321
321
  const t = await (await this.ctx.api.auth.me.$get()).json();
322
322
  if (!t.ok) {
@@ -331,7 +331,7 @@ const M = class M {
331
331
  });
332
332
  }
333
333
  async requestAuthCode(e) {
334
- return w(this.ctx, async () => {
334
+ return S(this.ctx, async () => {
335
335
  try {
336
336
  const r = await (await this.ctx.api.auth["check-email"].$post({
337
337
  json: { email: e.email }
@@ -343,7 +343,7 @@ const M = class M {
343
343
  });
344
344
  }
345
345
  async loginWithCode(e) {
346
- return w(this.ctx, async () => {
346
+ return S(this.ctx, async () => {
347
347
  try {
348
348
  const r = await (await this.ctx.api.auth["verify-code"].$post({
349
349
  json: { email: e.email, code: e.code }
@@ -359,45 +359,45 @@ const M = class M {
359
359
  this.ctx.logger.error("loginWithGoogle: Only available in browser");
360
360
  return;
361
361
  }
362
- const t = f(this.ctx.apiBase, this.ctx.isDev), r = window.location.origin, o = `${t}/auth/google-popup?origin=${encodeURIComponent(r)}`, s = 500, n = 600, u = window.screenX + (window.outerWidth - s) / 2, a = window.screenY + (window.outerHeight - n) / 2, d = window.open(
362
+ const t = y(this.ctx.apiBase, this.ctx.isDev), r = window.location.origin, o = `${t}/auth/google-popup?origin=${encodeURIComponent(r)}`, s = 500, c = 600, h = window.screenX + (window.outerWidth - s) / 2, a = window.screenY + (window.outerHeight - c) / 2, i = window.open(
363
363
  o,
364
364
  "google-auth",
365
- `width=${s},height=${n},left=${u},top=${a},popup=yes`
365
+ `width=${s},height=${c},left=${h},top=${a},popup=yes`
366
366
  );
367
- if (!d) {
368
- const h = "Popup was blocked. Please allow popups for this site.";
369
- this.ctx.error.value = h, e?.onError?.(h);
367
+ if (!i) {
368
+ const v = "Popup was blocked. Please allow popups for this site.";
369
+ this.ctx.error.value = v, e?.onError?.(v);
370
370
  return;
371
371
  }
372
- const p = /* @__PURE__ */ l((h) => {
373
- const S = new URL(t).origin;
374
- if (h.origin === S) {
375
- if (h.data?.type === "auth-success") {
376
- window.removeEventListener("message", p);
377
- const { token: I, user: K } = h.data;
378
- this.ctx.processApiResponse({ ok: !0, data: {}, token: I, user: K }), this.ctx.logger.info("Google login successful"), e?.onSuccess?.(K);
379
- } else if (h.data?.type === "auth-error") {
380
- window.removeEventListener("message", p);
381
- const I = h.data.error || "Google authentication failed";
382
- this.ctx.error.value = I, this.ctx.logger.error("Google login failed", { error: I }), e?.onError?.(I);
372
+ const f = /* @__PURE__ */ d((v) => {
373
+ const k = new URL(t).origin;
374
+ if (v.origin === k) {
375
+ if (v.data?.type === "auth-success") {
376
+ window.removeEventListener("message", f);
377
+ const { token: g, user: I } = v.data;
378
+ this.ctx.processApiResponse({ ok: !0, data: {}, token: g, user: I }), this.ctx.logger.info("Google login successful"), e?.onSuccess?.(I);
379
+ } else if (v.data?.type === "auth-error") {
380
+ window.removeEventListener("message", f);
381
+ const g = v.data.error || "Google authentication failed";
382
+ this.ctx.error.value = g, this.ctx.logger.error("Google login failed", { error: g }), e?.onError?.(g);
383
383
  }
384
384
  }
385
385
  }, "handler");
386
- window.addEventListener("message", p);
387
- const g = setInterval(() => {
388
- d.closed && (clearInterval(g), window.removeEventListener("message", p));
386
+ window.addEventListener("message", f);
387
+ const u = setInterval(() => {
388
+ i.closed && (clearInterval(u), window.removeEventListener("message", f));
389
389
  }, 500);
390
390
  }
391
391
  };
392
- l(M, "AuthClient");
393
- let j = M;
394
- const W = class W {
392
+ d(z, "AuthClient");
393
+ let j = z;
394
+ const J = class J {
395
395
  constructor(e) {
396
- i(this, "ctx");
396
+ n(this, "ctx");
397
397
  this.ctx = e;
398
398
  }
399
399
  async startTrial(e) {
400
- const t = this.resolveOrgId(), r = f(this.ctx.apiBase, this.ctx.isDev), s = await (await fetch(`${r}/api/billing/checkout/create`, {
400
+ const t = this.resolveOrgId(), r = y(this.ctx.apiBase, this.ctx.isDev), s = await (await fetch(`${r}/api/billing/checkout/create`, {
401
401
  method: "POST",
402
402
  headers: {
403
403
  "Content-Type": "application/json",
@@ -410,8 +410,8 @@ const W = class W {
410
410
  })
411
411
  })).json();
412
412
  if (!s.ok || !s.data?.url) {
413
- const n = s.error || "Failed to create checkout session";
414
- throw this.ctx.error.value = n, new Error(n);
413
+ const c = s.error || "Failed to create checkout session";
414
+ throw this.ctx.error.value = c, new Error(c);
415
415
  }
416
416
  window.location.href = s.data.url;
417
417
  }
@@ -419,7 +419,7 @@ const W = class W {
419
419
  return this.getStatus();
420
420
  }
421
421
  async getStatus() {
422
- const e = this.resolveOrgId(), t = f(this.ctx.apiBase, this.ctx.isDev), o = await (await fetch(`${t}/api/billing/details/${e}`, {
422
+ const e = this.resolveOrgId(), t = y(this.ctx.apiBase, this.ctx.isDev), o = await (await fetch(`${t}/api/billing/details/${e}`, {
423
423
  headers: {
424
424
  ...this.ctx.token.value && { Authorization: `Bearer ${this.ctx.token.value}` }
425
425
  }
@@ -448,110 +448,177 @@ const W = class W {
448
448
  return t;
449
449
  }
450
450
  };
451
- l(W, "BillingClient");
452
- let C = W;
453
- const z = class z {
451
+ d(J, "BillingClient");
452
+ let F = J;
453
+ const le = /* @__PURE__ */ new Set(["message", "message_delta", "working_state", "working_end", "error", "stream_end"]);
454
+ function ue(l) {
455
+ const e = l.split(`
456
+ `).filter((o) => o.length > 0);
457
+ let t, r;
458
+ for (const o of e)
459
+ o.startsWith("event:") ? t = o.slice(6).trim() : o.startsWith("data:") && (r = o.slice(5).trim());
460
+ if (!t || r === void 0 || !le.has(t))
461
+ return null;
462
+ try {
463
+ return { event: t, data: JSON.parse(r) };
464
+ } catch {
465
+ return null;
466
+ }
467
+ }
468
+ d(ue, "parseChatEvent");
469
+ const q = class q {
454
470
  constructor(e) {
455
- i(this, "ctx");
471
+ n(this, "ctx");
456
472
  this.ctx = e;
457
473
  }
474
+ /**
475
+ * Public/visitor chat — anonymous chat against an agent's public handle.
476
+ * Stays on the legacy `AgentChatServer` route for now; substrate doesn't
477
+ * support visitor identities yet (deferred per `plans/features/chat.md`).
478
+ */
458
479
  async chatStream(e) {
459
- const r = `${f(this.ctx.apiBase, this.ctx.isDev)}/api/agent/public/${encodeURIComponent(e.handle)}/chat/stream`;
460
- return this._streamChat({
461
- url: r,
462
- headers: { "Content-Type": "application/json" },
463
- body: {
464
- message: e.message,
465
- conversationId: e.conversationId,
466
- history: e.history,
467
- visitorId: e.visitorId,
468
- context: e.context,
469
- attachments: e.attachments
470
- },
471
- conversationId: e.conversationId,
472
- onDelta: e.onDelta,
473
- onDone: e.onDone,
474
- onError: e.onError,
475
- onStatus: e.onStatus
476
- });
477
- }
478
- async chatStreamAuthenticated(e) {
479
- const r = `${f(this.ctx.apiBase, this.ctx.isDev)}/api/agent/${encodeURIComponent(e.agentId)}/chat/stream`;
480
- return this._streamChat({
481
- url: r,
482
- headers: {
483
- "Content-Type": "application/json",
484
- ...this.ctx.token.value && { Authorization: `Bearer ${this.ctx.token.value}` }
485
- },
486
- body: {
487
- message: e.message,
488
- conversationId: e.conversationId,
489
- history: e.history,
490
- attachments: e.attachments
491
- },
492
- conversationId: e.conversationId,
493
- onDelta: e.onDelta,
494
- onDone: e.onDone,
495
- onError: e.onError,
496
- onStatus: e.onStatus
497
- });
498
- }
499
- /** Shared SSE streaming logic for both public and authenticated chat */
500
- async _streamChat(e) {
480
+ const r = `${y(this.ctx.apiBase, this.ctx.isDev)}/api/agent/public/${encodeURIComponent(e.handle)}/chat/stream`;
501
481
  try {
502
- const t = await fetch(e.url, {
482
+ const o = await fetch(r, {
503
483
  method: "POST",
504
- headers: e.headers,
505
- body: JSON.stringify(e.body)
484
+ headers: { "Content-Type": "application/json" },
485
+ body: JSON.stringify({
486
+ message: e.message,
487
+ conversationId: e.conversationId,
488
+ history: e.history,
489
+ visitorId: e.visitorId,
490
+ context: e.context,
491
+ attachments: e.attachments
492
+ })
506
493
  });
507
- if (!t.ok) {
508
- const u = await t.json().catch(() => ({ error: "Request failed" }));
509
- e.onError(u.error || `HTTP ${t.status}`);
494
+ if (!o.ok) {
495
+ const i = await o.json().catch(() => ({ error: "Request failed" }));
496
+ e.onError(i.error || `HTTP ${o.status}`);
510
497
  return;
511
498
  }
512
- const r = t.body?.getReader();
513
- if (!r) {
499
+ const s = o.body?.getReader();
500
+ if (!s) {
514
501
  e.onError("No response stream");
515
502
  return;
516
503
  }
517
- const o = new TextDecoder();
518
- let s = "", n = e.conversationId || "";
504
+ const c = new TextDecoder();
505
+ let h = "", a = e.conversationId || "";
519
506
  for (; ; ) {
520
- const { done: u, value: a } = await r.read();
521
- if (u)
507
+ const { done: i, value: f } = await s.read();
508
+ if (i)
522
509
  break;
523
- s += o.decode(a, { stream: !0 });
524
- const d = s.split(`
510
+ h += c.decode(f, { stream: !0 });
511
+ const u = h.split(`
525
512
  `);
526
- s = d.pop() || "";
527
- for (const p of d) {
528
- if (!p.startsWith("data: "))
513
+ h = u.pop() || "";
514
+ for (const v of u) {
515
+ if (!v.startsWith("data: "))
529
516
  continue;
530
- const g = p.slice(6).trim();
531
- if (g === "[DONE]") {
532
- e.onDone(n);
517
+ const k = v.slice(6).trim();
518
+ if (k === "[DONE]") {
519
+ e.onDone(a);
533
520
  return;
534
521
  }
535
522
  try {
536
- const h = JSON.parse(g);
537
- if (h.pl_status) {
538
- e.onStatus?.(h.pl_status);
523
+ const g = JSON.parse(k);
524
+ if (g.pl_status) {
525
+ e.onStatus?.(g.pl_status);
539
526
  continue;
540
527
  }
541
- h.pl_metadata?.conversationId && (n = h.pl_metadata.conversationId);
542
- const S = h.choices?.[0]?.delta;
543
- S?.content && e.onDelta(S.content);
528
+ g.pl_metadata?.conversationId && (a = g.pl_metadata.conversationId);
529
+ const I = g.choices?.[0]?.delta;
530
+ I?.content && e.onDelta(I.content);
544
531
  } catch {
545
532
  }
546
533
  }
547
534
  }
548
- e.onDone(n);
549
- } catch (t) {
550
- e.onError(t instanceof Error ? t.message : "Stream failed");
535
+ e.onDone(a);
536
+ } catch (o) {
537
+ e.onError(o instanceof Error ? o.message : "Stream failed");
538
+ }
539
+ }
540
+ /**
541
+ * Authenticated chat — substrate-backed (POST /api/messages + SSE on
542
+ * /api/chat/:agentId/stream). Same callback contract as the legacy
543
+ * `chatStream` so callers don't need to know which transport runs underneath.
544
+ * Mirrors `src/modules/agent/client.ts → sendChatMessageStream`.
545
+ */
546
+ async chatStreamAuthenticated(e) {
547
+ const t = y(this.ctx.apiBase, this.ctx.isDev), r = this.ctx.token.value ? { Authorization: `Bearer ${this.ctx.token.value}` } : {}, o = `nonce_${se(16)}`;
548
+ let s;
549
+ try {
550
+ const i = await fetch(`${t}/api/messages`, {
551
+ method: "POST",
552
+ headers: { "Content-Type": "application/json", ...r },
553
+ body: JSON.stringify({ agentId: e.agentId, content: e.message, clientNonce: o })
554
+ }), f = await i.json();
555
+ if (!f.ok) {
556
+ e.onError(f.error || `Send failed: HTTP ${i.status}`);
557
+ return;
558
+ }
559
+ s = f.data;
560
+ } catch (i) {
561
+ e.onError(i instanceof Error ? i.message : "Send failed");
562
+ return;
563
+ }
564
+ let c = !1, h = !1, a;
565
+ try {
566
+ const i = await fetch(`${t}/api/chat/${encodeURIComponent(e.agentId)}/stream?since=${encodeURIComponent(s.sequence)}`, {
567
+ headers: r
568
+ });
569
+ if (!i.ok) {
570
+ e.onError(`Stream failed: HTTP ${i.status}`);
571
+ return;
572
+ }
573
+ if (a = i.body?.getReader(), !a) {
574
+ e.onError("No response stream");
575
+ return;
576
+ }
577
+ const f = new TextDecoder();
578
+ let u = "";
579
+ e: for (; ; ) {
580
+ const { done: v, value: k } = await a.read();
581
+ if (v)
582
+ break;
583
+ u += f.decode(k, { stream: !0 });
584
+ let g = u.indexOf(`
585
+
586
+ `);
587
+ for (; g !== -1; ) {
588
+ const I = u.slice(0, g);
589
+ u = u.slice(g + 2);
590
+ const m = ue(I);
591
+ if (m) {
592
+ if (m.event === "working_state")
593
+ e.onStatus?.(m.data.description);
594
+ else if (m.event === "message_delta")
595
+ e.onDelta(m.data.delta);
596
+ else if (m.event === "error") {
597
+ c = !0, e.onError(m.data.message);
598
+ break e;
599
+ } else if (m.event === "message" && m.data.message.role === "assistant") {
600
+ h = !0;
601
+ break e;
602
+ } else if (m.event === "stream_end")
603
+ break e;
604
+ }
605
+ g = u.indexOf(`
606
+
607
+ `);
608
+ }
609
+ }
610
+ !c && h ? e.onDone(s.conversationId) : c || e.onError("Stream ended before reply arrived");
611
+ } catch (i) {
612
+ e.onError(i instanceof Error ? i.message : "Stream failed");
613
+ } finally {
614
+ try {
615
+ await a?.cancel();
616
+ } catch {
617
+ }
551
618
  }
552
619
  }
553
620
  async chatMessage(e) {
554
- const r = `${f(this.ctx.apiBase, this.ctx.isDev)}/api/agent/public/${encodeURIComponent(e.handle)}/chat`;
621
+ const r = `${y(this.ctx.apiBase, this.ctx.isDev)}/api/agent/public/${encodeURIComponent(e.handle)}/chat`;
555
622
  try {
556
623
  const s = await (await fetch(r, {
557
624
  method: "POST",
@@ -577,11 +644,11 @@ const z = class z {
577
644
  }
578
645
  }
579
646
  };
580
- l(z, "ChatClient");
581
- let F = z;
582
- const q = class q {
647
+ d(q, "ChatClient");
648
+ let C = q;
649
+ const K = class K {
583
650
  constructor(e) {
584
- i(this, "ctx");
651
+ n(this, "ctx");
585
652
  this.ctx = e;
586
653
  }
587
654
  async getPublicAgent(e) {
@@ -623,7 +690,7 @@ const q = class q {
623
690
  generateAnonId() {
624
691
  const e = "pagelinesAnonId";
625
692
  let t = this.ctx.storage.getItem(e);
626
- return t || (t = B({ prefix: "anon" }), this.ctx.storage.setItem(e, t)), t;
693
+ return t || (t = O({ prefix: "anon" }), this.ctx.storage.setItem(e, t)), t;
627
694
  }
628
695
  track(e) {
629
696
  try {
@@ -638,11 +705,11 @@ const q = class q {
638
705
  }
639
706
  }
640
707
  };
641
- l(q, "UserClient");
642
- let O = q;
643
- const J = class J {
708
+ d(K, "UserClient");
709
+ let L = K;
710
+ const H = class H {
644
711
  constructor() {
645
- i(this, "key", "__PAGELINES_SDK__");
712
+ n(this, "key", "__PAGELINES_SDK__");
646
713
  }
647
714
  get() {
648
715
  if (!(typeof window > "u"))
@@ -655,33 +722,33 @@ const J = class J {
655
722
  typeof window < "u" && delete globalThis[this.key];
656
723
  }
657
724
  };
658
- l(J, "SDKGlobal");
659
- let _ = J;
660
- const T = new _(), D = class D extends oe {
725
+ d(H, "SDKGlobal");
726
+ let N = H;
727
+ const D = new N(), B = class B extends ae {
661
728
  constructor(t = {}) {
662
- const r = T.get();
729
+ const r = D.get();
663
730
  if (r)
664
731
  return console.debug("[PageLinesSDK] Returning existing singleton instance"), r;
665
732
  super("PageLinesSDK", t);
666
733
  // Vue reactive state
667
- i(this, "activeUser", k());
668
- i(this, "token", k(null));
734
+ n(this, "activeUser", A());
735
+ n(this, "token", A(null));
669
736
  // Refresh credential lives in HttpOnly pl-refresh-token cookie — JS never
670
737
  // holds it, so no reactive ref. /api/auth/refresh reads the cookie via the
671
738
  // browser's automatic credentials: 'include' attach.
672
- i(this, "deviceId", k(null));
673
- i(this, "loading", k(!1));
674
- i(this, "error", k(null));
675
- i(this, "apiBase", this.settings.apiBase || void 0);
739
+ n(this, "deviceId", A(null));
740
+ n(this, "loading", A(!1));
741
+ n(this, "error", A(null));
742
+ n(this, "apiBase", this.settings.apiBase || void 0);
676
743
  // Storage handler for persistence
677
- i(this, "storage", new R());
744
+ n(this, "storage", new P());
678
745
  // Auto-managed session ID for usage tracking
679
- i(this, "sessionId", B({ prefix: "ses" }));
746
+ n(this, "sessionId", O({ prefix: "ses" }));
680
747
  // Typed Hono RPC client - uses SDKAppType (auth/self/usage routes only)
681
748
  // Initialized in constructor (definite assignment via singleton pattern)
682
- i(this, "apiClient");
749
+ n(this, "apiClient");
683
750
  // Computed properties derived from activeUser (matches UserClient pattern)
684
- i(this, "currentAgent", V(() => {
751
+ n(this, "currentAgent", Q(() => {
685
752
  const t = this.activeUser.value;
686
753
  if (!t?.agents)
687
754
  return;
@@ -689,7 +756,7 @@ const T = new _(), D = class D extends oe {
689
756
  if (r)
690
757
  return t.agents.find((o) => o.agentId === r);
691
758
  }));
692
- i(this, "currentOrg", V(() => {
759
+ n(this, "currentOrg", Q(() => {
693
760
  const t = this.currentAgent.value;
694
761
  if (!t?.orgId)
695
762
  return;
@@ -698,23 +765,23 @@ const T = new _(), D = class D extends oe {
698
765
  return r.orgs.find((o) => o.orgId === t.orgId);
699
766
  }));
700
767
  // Initialization state
701
- i(this, "initialized");
702
- i(this, "resolveUser");
768
+ n(this, "initialized");
769
+ n(this, "resolveUser");
703
770
  // Sub-clients (new preferred API surface)
704
- i(this, "agent");
705
- i(this, "auth");
706
- i(this, "billing");
707
- i(this, "chat");
708
- i(this, "user");
709
- T.set(this), this.apiClient = ie(
771
+ n(this, "agent");
772
+ n(this, "auth");
773
+ n(this, "billing");
774
+ n(this, "chat");
775
+ n(this, "user");
776
+ D.set(this), this.apiClient = ne(
710
777
  { isDev: this.isDev, apiBase: this.apiBase },
711
778
  this.processApiResponse.bind(this),
712
779
  {
713
- getDeviceId: /* @__PURE__ */ l(() => this.deviceId.value, "getDeviceId"),
714
- onAccessTokenRefreshed: /* @__PURE__ */ l((s) => {
780
+ getDeviceId: /* @__PURE__ */ d(() => this.deviceId.value, "getDeviceId"),
781
+ onAccessTokenRefreshed: /* @__PURE__ */ d((s) => {
715
782
  this.token.value = s, this.persistAuth();
716
783
  }, "onAccessTokenRefreshed"),
717
- onTerminalFailure: /* @__PURE__ */ l(() => {
784
+ onTerminalFailure: /* @__PURE__ */ d(() => {
718
785
  this.clearSession();
719
786
  }, "onTerminalFailure")
720
787
  }
@@ -733,7 +800,7 @@ const T = new _(), D = class D extends oe {
733
800
  logger: this.logger,
734
801
  processApiResponse: this.processApiResponse.bind(this)
735
802
  };
736
- this.agent = new P(o), this.auth = new j(o), this.billing = new C(o), this.chat = new F(o), this.user = new O(o), this.logger.info("PageLinesSDK initialized"), this.storage.loadFromStorage(this.authRefs()), this.storage.syncWithGlobalStores(this.authRefs()), this.initialized = new Promise((s) => {
803
+ this.agent = new _(o), this.auth = new j(o), this.billing = new F(o), this.chat = new C(o), this.user = new L(o), this.logger.info("PageLinesSDK initialized"), this.storage.loadFromStorage(this.authRefs()), this.storage.syncWithGlobalStores(this.authRefs()), this.initialized = new Promise((s) => {
737
804
  this.resolveUser = s;
738
805
  }), this.token.value && !this.activeUser.value ? this.getCurrentUser().then((s) => {
739
806
  this.resolveUser && (this.resolveUser(s), this.resolveUser = void 0);
@@ -747,7 +814,7 @@ const T = new _(), D = class D extends oe {
747
814
  * Recommended: Use this instead of constructor for shared state
748
815
  */
749
816
  static getInstance(t = {}) {
750
- return T.get() || new D(t);
817
+ return D.get() || new B(t);
751
818
  }
752
819
  get isDev() {
753
820
  return this.settings.isDev ?? (typeof window < "u" ? window.location.hostname === "localhost" || window.location.hostname.includes("127.0.0.1") : !1);
@@ -781,7 +848,7 @@ const T = new _(), D = class D extends oe {
781
848
  }
782
849
  // Full reset - clears session + state + destroys singleton
783
850
  clear() {
784
- this.logger.info("Clearing SDK completely"), this.clearSession(), this.loading.value = !1, this.sessionId = B({ prefix: "ses" }), T.delete();
851
+ this.logger.info("Clearing SDK completely"), this.clearSession(), this.loading.value = !1, this.sessionId = O({ prefix: "ses" }), D.delete();
785
852
  }
786
853
  // Backward-compatible delegates — these forward to sub-clients
787
854
  // Can be removed in a future breaking change
@@ -812,9 +879,6 @@ const T = new _(), D = class D extends oe {
812
879
  async chatStreamAuthenticated(t) {
813
880
  return this.chat.chatStreamAuthenticated(t);
814
881
  }
815
- async chatMessage(t) {
816
- return this.chat.chatMessage(t);
817
- }
818
882
  async getPublicAgent(t) {
819
883
  return this.user.getPublicAgent(t);
820
884
  }
@@ -828,14 +892,14 @@ const T = new _(), D = class D extends oe {
828
892
  return this.user.track(t);
829
893
  }
830
894
  };
831
- l(D, "PageLinesSDK");
832
- let X = D;
895
+ d(B, "PageLinesSDK");
896
+ let Y = B;
833
897
  export {
834
- P as A,
835
- F as C,
836
- X as P,
837
- O as U,
898
+ _ as A,
899
+ C,
900
+ Y as P,
901
+ L as U,
838
902
  j as a,
839
- f as r
903
+ y as r
840
904
  };
841
905
  //# sourceMappingURL=sdkClient.js.map