@pagelines/sdk 1.0.472 → 1.0.474

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