@pageops/sdk 0.1.4 → 0.1.6

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/client.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import type { ContextSession, ConversationMessage, ConversationThread, PageOpsMountOptions, SourceSnapshot } from './types';
1
+ import type { ContextSession, ConversationMessage, ConversationThread, PageOpsContext, PageOpsMountOptions, SourceSnapshot } from './types';
2
2
  export declare class PageOpsClient {
3
3
  private options;
4
4
  constructor(options: PageOpsMountOptions);
5
- createContext(): Promise<ContextSession>;
5
+ createContext(context?: PageOpsContext): Promise<ContextSession>;
6
6
  listConversations(): Promise<ConversationThread[]>;
7
7
  createConversation(contextSessionId: string, title?: string): Promise<ConversationThread>;
8
8
  listMessages(threadId: string): Promise<ConversationMessage[]>;
package/dist/index.d.ts CHANGED
@@ -6,6 +6,8 @@ declare class PageOpsSDKController {
6
6
  private root;
7
7
  private panel;
8
8
  private context;
9
+ private contextKey;
10
+ private selectedPageKey;
9
11
  private currentThread;
10
12
  private conversations;
11
13
  private messages;
@@ -22,6 +24,8 @@ declare class PageOpsSDKController {
22
24
  updateContext(options: Partial<PageOpsMountOptions>): void;
23
25
  private renderClosed;
24
26
  private ensureContext;
27
+ private getPageContext;
28
+ private getPageContextKey;
25
29
  private loadSources;
26
30
  private loadConversations;
27
31
  private newConversation;
@@ -1 +1 @@
1
- .pageops-sdk{--po-text: #172033;--po-muted: #64748b;--po-border: #dbe5f5;--po-soft-border: #e2e8f0;--po-surface: #ffffff;--po-soft: #f8fafc;--po-panel: #fbfdff;--po-primary: #2563eb;--po-primary-dark: #1d4ed8;--po-shadow: 0 24px 70px rgb(15 23 42 / 18%);color:var(--po-text);font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}.pageops-sdk *,.pageops-sdk *:before,.pageops-sdk *:after{box-sizing:border-box}.pageops-sdk button,.pageops-sdk input,.pageops-sdk textarea{font:inherit}.pageops-sdk button{cursor:pointer}.po-fab{position:fixed;right:24px;bottom:24px;z-index:2147483000;border:0;border-radius:999px;padding:12px 18px;background:linear-gradient(135deg,#2563eb,#14b8a6);color:#fff;font-weight:800;box-shadow:0 18px 42px #2563eb47}.po-panel{position:fixed;inset:40px;z-index:2147483000;display:grid;grid-template-columns:250px minmax(0,1fr) 340px;min-height:520px;overflow:hidden;border:1px solid var(--po-border);border-radius:24px;background:var(--po-surface);box-shadow:var(--po-shadow)}.po-sidebar{display:flex;min-width:0;min-height:0;flex-direction:column;gap:12px;overflow:hidden;border-right:1px solid #dbeafe;background:#eef5ff;padding:16px}.po-brand{display:flex;align-items:center;gap:10px}.po-brand strong,.po-brand span{display:block}.po-brand span{margin-top:2px;color:var(--po-muted);font-size:12px}.po-logo{width:34px;height:34px;flex:0 0 auto;border-radius:12px;background:linear-gradient(135deg,#5eead4,#2563eb)}.po-new,.po-composer button{border:0;border-radius:10px;background:var(--po-primary);color:#fff;font-weight:750}.po-new{width:100%;padding:10px 12px}.po-search,.po-composer textarea{width:100%;border:1px solid #cbd5e1;border-radius:10px;background:#fff;color:var(--po-text);outline:none}.po-search{padding:9px 10px}.po-thread-list{display:grid;align-content:start;gap:8px;min-height:0;overflow:auto}.po-thread{display:grid;gap:4px;width:100%;border:1px solid transparent;border-radius:10px;background:transparent;color:#334155;padding:9px 10px;text-align:left}.po-thread.active{border-color:#bfdbfe;background:#fff;color:var(--po-text)}.po-thread span{color:#94a3b8;font-size:12px}.po-chat{display:flex;min-width:0;min-height:0;flex-direction:column;background:linear-gradient(180deg,#fff,var(--po-panel));padding:22px 26px}.po-chat header,.po-trace header{display:flex;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid var(--po-soft-border);padding-bottom:14px}.po-chat header p,.po-chat header h2,.po-trace header h2{margin:0}.po-chat header p,.po-chat header span{color:var(--po-muted);font-size:12px}.po-chat header h2,.po-trace header h2{font-size:20px;letter-spacing:-.02em}.po-messages{display:grid;align-content:start;gap:14px;min-height:0;flex:1;overflow:auto;padding:18px 4px 18px 0}.po-message{display:grid;max-width:82%;gap:6px;border:1px solid var(--po-soft-border);border-radius:14px;padding:11px 13px;line-height:1.55;white-space:pre-wrap;word-break:break-word}.po-message b{font-size:12px;opacity:.78}.po-message.user{justify-self:end;border-color:var(--po-primary);background:var(--po-primary);color:#fff}.po-message.assistant{justify-self:start;background:var(--po-soft)}.po-message.streaming{border-color:#bfdbfe;background:#eff6ff}.po-message code{border-radius:5px;background:#eaf0ff;color:var(--po-primary-dark);padding:1px 5px}.po-message h2,.po-message h3,.po-message h4,.po-message p{margin:8px 0}.po-message table{width:100%;margin:12px 0;border-collapse:collapse;border-radius:10px;font-size:14px}.po-message th,.po-message td{border:1px solid var(--po-border);padding:8px 10px;text-align:left;vertical-align:top}.po-message th{background:#eef5ff;color:#334155;font-weight:800}.po-composer{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:end;gap:10px;border-top:1px solid var(--po-soft-border);padding-top:12px}.po-composer textarea{min-height:88px;resize:vertical;padding:10px}.po-composer button{min-height:44px;padding:0 16px}.po-trace{display:flex;min-height:0;flex-direction:column;border-left:1px solid var(--po-soft-border);background:#fafbff}.po-trace header{padding:18px}.po-trace header button{width:32px;height:32px;border:1px solid #cbd5e1;border-radius:10px;background:#fff;color:#334155;font-size:20px;line-height:1}.po-trace section{display:grid;align-content:start;gap:12px;min-height:0;overflow:auto;padding:16px}.po-source-uploader{display:grid;gap:8px;border:1px solid var(--po-soft-border);border-radius:14px;background:#fff;padding:12px}.po-source-uploader p{margin:0;color:var(--po-muted);font-size:12px;line-height:1.5}.po-upload-button{display:inline-flex;justify-content:center;border:1px solid #bfdbfe;border-radius:10px;background:#eff6ff;color:var(--po-primary-dark);padding:8px 10px;font-weight:750;cursor:pointer}.po-upload-button input{display:none}.po-upload-status{color:#166534!important}.po-upload-empty{color:#92400e!important}.po-source-list{display:grid;gap:6px}.po-source-item{display:grid;gap:3px;border:1px solid #dbeafe;border-radius:10px;background:#f8fbff;padding:8px}.po-source-item strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.po-source-item span{color:var(--po-muted);font-size:12px}.po-composer textarea:disabled,.po-composer button:disabled{cursor:not-allowed;opacity:.62}.po-upload-error{color:#b91c1c!important}.po-step{border:1px solid var(--po-soft-border);border-radius:14px;background:#fff;padding:12px}.po-step.running{border-color:#bfdbfe;background:#eff6ff}.po-step.completed{border-color:#bbf7d0}.po-step.failed{border-color:#fecaca;background:#fff1f2}.po-step summary{display:flex;justify-content:space-between;gap:8px;cursor:pointer}.po-step summary::marker{color:var(--po-muted)}.po-step pre{overflow:auto;margin:10px 0 0;border-radius:12px;background:#0f172a;color:#e2e8f0;padding:12px;font-size:12px;white-space:pre-wrap}@media(max-width:900px){.po-panel{inset:12px;grid-template-columns:1fr;overflow:auto}.po-sidebar,.po-trace{min-height:220px;border:0}.po-chat{min-height:520px}.po-message{max-width:94%}}
1
+ .pageops-sdk{--po-text: #172033;--po-muted: #64748b;--po-border: #dbe5f5;--po-soft-border: #e2e8f0;--po-surface: #ffffff;--po-soft: #f8fafc;--po-panel: #fbfdff;--po-primary: #2563eb;--po-primary-dark: #1d4ed8;--po-shadow: 0 24px 70px rgb(15 23 42 / 18%);color:var(--po-text);font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}.pageops-sdk *,.pageops-sdk *:before,.pageops-sdk *:after{box-sizing:border-box}.pageops-sdk button,.pageops-sdk input,.pageops-sdk textarea{font:inherit}.pageops-sdk button{cursor:pointer}.po-fab{position:fixed;right:24px;bottom:24px;z-index:2147483000;border:0;border-radius:999px;padding:12px 18px;background:linear-gradient(135deg,#2563eb,#14b8a6);color:#fff;font-weight:800;box-shadow:0 18px 42px #2563eb47}.po-panel{position:fixed;inset:40px;z-index:2147483000;display:grid;grid-template-columns:250px minmax(0,1fr) 340px;min-height:520px;overflow:hidden;border:1px solid var(--po-border);border-radius:24px;background:var(--po-surface);box-shadow:var(--po-shadow)}.po-sidebar{display:flex;min-width:0;min-height:0;flex-direction:column;gap:12px;overflow:hidden;border-right:1px solid #dbeafe;background:#eef5ff;padding:16px}.po-brand{display:flex;align-items:center;gap:10px}.po-brand strong,.po-brand span{display:block}.po-brand span{margin-top:2px;color:var(--po-muted);font-size:12px}.po-logo{width:34px;height:34px;flex:0 0 auto;border-radius:12px;background:linear-gradient(135deg,#5eead4,#2563eb)}.po-new,.po-composer button{border:0;border-radius:10px;background:var(--po-primary);color:#fff;font-weight:750}.po-new{width:100%;padding:10px 12px}.po-search,.po-composer textarea{width:100%;border:1px solid #cbd5e1;border-radius:10px;background:#fff;color:var(--po-text);outline:none}.po-search{padding:9px 10px}.po-thread-list{display:grid;align-content:start;gap:8px;min-height:0;overflow:auto}.po-thread{display:grid;gap:4px;width:100%;border:1px solid transparent;border-radius:10px;background:transparent;color:#334155;padding:9px 10px;text-align:left}.po-thread.active{border-color:#bfdbfe;background:#fff;color:var(--po-text)}.po-thread span{color:#94a3b8;font-size:12px}.po-chat{display:flex;min-width:0;min-height:0;flex-direction:column;background:linear-gradient(180deg,#fff,var(--po-panel));padding:22px 26px}.po-chat header,.po-trace header{display:flex;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid var(--po-soft-border);padding-bottom:14px}.po-chat header p,.po-chat header h2,.po-trace header h2{margin:0}.po-chat header p,.po-chat header span{color:var(--po-muted);font-size:12px}.po-chat header h2,.po-trace header h2{font-size:20px;letter-spacing:-.02em}.po-messages{display:grid;align-content:start;gap:14px;min-height:0;flex:1;overflow:auto;padding:18px 4px 18px 0}.po-message{display:grid;max-width:82%;gap:6px;border:1px solid var(--po-soft-border);border-radius:14px;padding:11px 13px;line-height:1.55;white-space:pre-wrap;word-break:break-word}.po-message b{font-size:12px;opacity:.78}.po-message.user{justify-self:end;border-color:var(--po-primary);background:var(--po-primary);color:#fff}.po-message.assistant{justify-self:start;background:var(--po-soft)}.po-message.streaming{border-color:#bfdbfe;background:#eff6ff}.po-message code{border-radius:5px;background:#eaf0ff;color:var(--po-primary-dark);padding:1px 5px}.po-message pre{max-width:100%;margin:8px 0;overflow:auto;border:1px solid var(--po-border);border-radius:6px;background:#f8fafc;padding:10px 12px;white-space:pre}.po-message pre code{border-radius:0;background:transparent;color:#1f2937;padding:0}.po-message h2,.po-message h3,.po-message h4,.po-message p{margin:8px 0}.po-message table{width:100%;margin:12px 0;border-collapse:collapse;border-radius:10px;font-size:14px}.po-message th,.po-message td{border:1px solid var(--po-border);padding:8px 10px;text-align:left;vertical-align:top}.po-message th{background:#eef5ff;color:#334155;font-weight:800}.po-composer{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:end;gap:10px;border-top:1px solid var(--po-soft-border);padding-top:12px}.po-composer textarea{min-height:88px;resize:vertical;padding:10px}.po-composer button{min-height:44px;padding:0 16px}.po-trace{display:flex;min-height:0;flex-direction:column;border-left:1px solid var(--po-soft-border);background:#fafbff}.po-trace header{padding:18px}.po-trace header button{width:32px;height:32px;border:1px solid #cbd5e1;border-radius:10px;background:#fff;color:#334155;font-size:20px;line-height:1}.po-trace section{display:grid;align-content:start;gap:12px;min-height:0;overflow:auto;padding:16px}.po-source-uploader{display:grid;gap:8px;border:1px solid var(--po-soft-border);border-radius:14px;background:#fff;padding:12px}.po-source-uploader p{margin:0;color:var(--po-muted);font-size:12px;line-height:1.5}.po-upload-button{display:inline-flex;justify-content:center;border:1px solid #bfdbfe;border-radius:10px;background:#eff6ff;color:var(--po-primary-dark);padding:8px 10px;font-weight:750;cursor:pointer}.po-upload-button input{display:none}.po-upload-status{color:#166534!important}.po-upload-empty{color:#92400e!important}.po-source-list{display:grid;gap:6px}.po-source-item{display:grid;gap:3px;border:1px solid #dbeafe;border-radius:10px;background:#f8fbff;padding:8px}.po-source-item strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.po-source-item span{color:var(--po-muted);font-size:12px}.po-composer textarea:disabled,.po-composer button:disabled{cursor:not-allowed;opacity:.62}.po-upload-error{color:#b91c1c!important}.po-step{border:1px solid var(--po-soft-border);border-radius:14px;background:#fff;padding:12px}.po-step.running{border-color:#bfdbfe;background:#eff6ff}.po-step.completed{border-color:#bbf7d0}.po-step.failed{border-color:#fecaca;background:#fff1f2}.po-step summary{display:flex;justify-content:space-between;gap:8px;cursor:pointer}.po-step summary::marker{color:var(--po-muted)}.po-step pre{overflow:auto;margin:10px 0 0;border-radius:12px;background:#0f172a;color:#e2e8f0;padding:12px;font-size:12px;white-space:pre-wrap}@media(max-width:900px){.po-panel{inset:12px;grid-template-columns:1fr;overflow:auto}.po-sidebar,.po-trace{min-height:220px;border:0}.po-chat{min-height:520px}.po-message{max-width:94%}}
@@ -1,21 +1,21 @@
1
1
  var w = Object.defineProperty;
2
- var x = (r, t, e) => t in r ? w(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;
3
- var a = (r, t, e) => x(r, typeof t != "symbol" ? t + "" : t, e);
4
- class S {
2
+ var x = (i, t, e) => t in i ? w(i, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : i[t] = e;
3
+ var c = (i, t, e) => x(i, typeof t != "symbol" ? t + "" : t, e);
4
+ class $ {
5
5
  constructor(t) {
6
6
  this.options = t;
7
7
  }
8
- async createContext() {
9
- var e, s, o, n, c;
10
- const t = (o = (s = (e = this.options).getPageContext) == null ? void 0 : s.call(e)) != null ? o : {};
8
+ async createContext(t = ((n) => (n = ((e) => ((s) => (s = (e = this.options).getPageContext) == null ? void 0 : s.call(e))())()) != null ? n : {})()) {
9
+ var o, r, l;
11
10
  return this.request("/context/session", {
12
11
  method: "POST",
13
12
  body: JSON.stringify({
14
13
  app_id: this.options.appId,
15
14
  env: this.options.env,
16
15
  route: t.route,
17
- url: (n = t.url) != null ? n : location.href,
18
- title: (c = t.title) != null ? c : document.title,
16
+ url: (o = t.url) != null ? o : location.href,
17
+ title: (r = t.title) != null ? r : document.title,
18
+ menu_path: (l = t.menuPath) != null ? l : [],
19
19
  tenant_id: t.tenantId,
20
20
  user_role: t.userRole,
21
21
  build_version: t.buildVersion
@@ -49,88 +49,98 @@ class S {
49
49
  });
50
50
  }
51
51
  async request(t, e) {
52
- var c, h;
53
- const s = (e == null ? void 0 : e.body) instanceof FormData ? e.headers : { "content-type": "application/json", ...(c = e == null ? void 0 : e.headers) != null ? c : {} }, o = await fetch(`${this.base()}${t}`, { ...e, headers: s }), n = await o.json();
54
- if (!o.ok) throw new Error((h = n.message) != null ? h : "PageOps 请求失败");
55
- return n;
52
+ var r, l;
53
+ const s = (e == null ? void 0 : e.body) instanceof FormData ? e.headers : { "content-type": "application/json", ...(r = e == null ? void 0 : e.headers) != null ? r : {} }, n = await fetch(`${this.base()}${t}`, { ...e, headers: s }), o = await n.json();
54
+ if (!n.ok) throw new Error((l = o.message) != null ? l : "PageOps 请求失败");
55
+ return o;
56
56
  }
57
57
  base() {
58
58
  const t = this.options.apiBase.replace(/\/$/, "");
59
59
  return t.endsWith("/api") ? t : `${t}/api`;
60
60
  }
61
61
  }
62
- function E(r) {
63
- return r.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
62
+ function P(i) {
63
+ return i.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
64
64
  }
65
- function f(r) {
66
- return E(r).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
65
+ function f(i) {
66
+ return P(i).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
67
67
  }
68
- function U(r, t) {
69
- const e = r[t], s = r[t + 1];
68
+ function C(i, t) {
69
+ const e = i[t], s = i[t + 1];
70
70
  if (!(e != null && e.includes("|")) || !/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s != null ? s : "")) return null;
71
- const o = [];
72
- let n = t;
73
- for (; n < r.length && r[n].includes("|") && r[n].trim(); )
74
- o.push(r[n]), n += 1;
75
- const c = (d) => d.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((m) => f(m.trim())), h = c(o[0]).map((d) => `<th>${d}</th>`).join(""), g = o.slice(2).map((d) => `<tr>${c(d).map((m) => `<td>${m}</td>`).join("")}</tr>`).join("");
76
- return { html: `<table><thead><tr>${h}</tr></thead><tbody>${g}</tbody></table>`, next: n };
71
+ const n = [];
72
+ let o = t;
73
+ for (; o < i.length && i[o].includes("|") && i[o].trim(); )
74
+ n.push(i[o]), o += 1;
75
+ const r = (d) => d.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((g) => f(g.trim())), l = r(n[0]).map((d) => `<th>${d}</th>`).join(""), m = n.slice(2).map((d) => `<tr>${r(d).map((g) => `<td>${g}</td>`).join("")}</tr>`).join("");
76
+ return { html: `<table><thead><tr>${l}</tr></thead><tbody>${m}</tbody></table>`, next: o };
77
77
  }
78
- function b(r) {
79
- const t = r.split(`
78
+ function S(i) {
79
+ const t = i.split(`
80
80
  `), e = [];
81
81
  for (let s = 0; s < t.length; s += 1) {
82
- const o = U(t, s);
82
+ const n = t[s];
83
+ if (n.trim().startsWith("```")) {
84
+ const r = [];
85
+ for (s += 1; s < t.length && !t[s].trim().startsWith("```"); )
86
+ r.push(t[s]), s += 1;
87
+ e.push(`<pre><code>${P(r.join(`
88
+ `))}</code></pre>`);
89
+ continue;
90
+ }
91
+ const o = C(t, s);
83
92
  if (o) {
84
93
  e.push(o.html), s = o.next - 1;
85
94
  continue;
86
95
  }
87
- const n = t[s];
88
96
  n.startsWith("### ") ? e.push(`<h4>${f(n.slice(4))}</h4>`) : n.startsWith("## ") ? e.push(`<h3>${f(n.slice(3))}</h3>`) : n.startsWith("# ") ? e.push(`<h2>${f(n.slice(2))}</h2>`) : n.startsWith("- ") ? e.push(`<li>${f(n.slice(2))}</li>`) : n.trim() ? e.push(`<p>${f(n)}</p>`) : e.push("<br>");
89
97
  }
90
98
  return e.join("");
91
99
  }
92
- async function C(r, t) {
93
- var n, c, h;
94
- const e = r.getReader(), s = new TextDecoder();
95
- let o = "";
100
+ async function E(i, t) {
101
+ var o, r, l;
102
+ const e = i.getReader(), s = new TextDecoder();
103
+ let n = "";
96
104
  for (; ; ) {
97
- const { done: g, value: d } = await e.read();
98
- if (g) break;
99
- o += s.decode(d, { stream: !0 });
100
- const m = o.split(`
105
+ const { done: m, value: d } = await e.read();
106
+ if (m) break;
107
+ n += s.decode(d, { stream: !0 });
108
+ const g = n.split(`
101
109
 
102
110
  `);
103
- o = (n = m.pop()) != null ? n : "";
104
- for (const v of m) {
105
- const l = (c = v.match(/^event: (.+)$/m)) == null ? void 0 : c[1], i = (h = v.match(/^data: (.+)$/m)) == null ? void 0 : h[1];
106
- l && i && t(l, JSON.parse(i));
111
+ n = (o = g.pop()) != null ? o : "";
112
+ for (const y of g) {
113
+ const h = (r = y.match(/^event: (.+)$/m)) == null ? void 0 : r[1], a = (l = y.match(/^data: (.+)$/m)) == null ? void 0 : l[1];
114
+ h && a && t(h, JSON.parse(a));
107
115
  }
108
116
  }
109
117
  }
110
- class P {
118
+ class T {
111
119
  constructor() {
112
- a(this, "client", null);
113
- a(this, "options", null);
114
- a(this, "root", null);
115
- a(this, "panel", null);
116
- a(this, "context", null);
117
- a(this, "currentThread", null);
118
- a(this, "conversations", []);
119
- a(this, "messages", []);
120
- a(this, "steps", []);
121
- a(this, "sourceSnapshots", []);
122
- a(this, "sourceUploadStatus", "");
123
- a(this, "sourceUploadError", "");
124
- a(this, "sourceUploading", !1);
125
- a(this, "streaming", "");
120
+ c(this, "client", null);
121
+ c(this, "options", null);
122
+ c(this, "root", null);
123
+ c(this, "panel", null);
124
+ c(this, "context", null);
125
+ c(this, "contextKey", "");
126
+ c(this, "selectedPageKey", "");
127
+ c(this, "currentThread", null);
128
+ c(this, "conversations", []);
129
+ c(this, "messages", []);
130
+ c(this, "steps", []);
131
+ c(this, "sourceSnapshots", []);
132
+ c(this, "sourceUploadStatus", "");
133
+ c(this, "sourceUploadError", "");
134
+ c(this, "sourceUploading", !1);
135
+ c(this, "streaming", "");
126
136
  }
127
137
  mount(t) {
128
138
  var e;
129
- this.unmount(), this.options = t, this.client = new S(t), this.root = document.createElement("div"), this.root.className = "pageops-sdk", ((e = t.container) != null ? e : document.body).appendChild(this.root), this.renderClosed();
139
+ this.unmount(), this.options = t, this.client = new $(t), this.root = document.createElement("div"), this.root.className = "pageops-sdk", ((e = t.container) != null ? e : document.body).appendChild(this.root), this.renderClosed();
130
140
  }
131
141
  unmount() {
132
142
  var t;
133
- (t = this.root) == null || t.remove(), this.root = null, this.panel = null, this.context = null, this.currentThread = null, this.conversations = [], this.messages = [], this.steps = [], this.sourceSnapshots = [], this.sourceUploadStatus = "", this.sourceUploadError = "", this.sourceUploading = !1, this.streaming = "";
143
+ (t = this.root) == null || t.remove(), this.root = null, this.panel = null, this.context = null, this.contextKey = "", this.selectedPageKey = "", this.currentThread = null, this.conversations = [], this.messages = [], this.steps = [], this.sourceSnapshots = [], this.sourceUploadStatus = "", this.sourceUploadError = "", this.sourceUploading = !1, this.streaming = "";
134
144
  }
135
145
  open() {
136
146
  this.root && (this.root.innerHTML = "", this.panel = document.createElement("div"), this.panel.className = "po-panel", this.root.appendChild(this.panel), this.loadSources(), this.loadConversations(), this.renderPanel());
@@ -139,16 +149,29 @@ class P {
139
149
  this.renderClosed();
140
150
  }
141
151
  updateContext(t) {
142
- this.options && (this.options = { ...this.options, ...t }, this.client = new S(this.options));
152
+ this.options && (this.options = { ...this.options, ...t }, this.client = new $(this.options), this.context = null, this.contextKey = "");
143
153
  }
144
154
  renderClosed() {
145
155
  var t;
146
156
  this.root && (this.root.innerHTML = '<button class="po-fab" type="button">多轮问答</button>', (t = this.root.querySelector("button")) == null || t.addEventListener("click", () => this.open()));
147
157
  }
148
158
  async ensureContext() {
149
- if (this.context) return this.context;
150
- if (!this.client) throw new Error("PageOps SDK 未初始化");
151
- return this.context = await this.client.createContext(), this.context;
159
+ if (!this.client || !this.options) throw new Error("PageOps SDK 未初始化");
160
+ const t = this.getPageContext(), e = this.getPageContextKey(t);
161
+ return this.context && this.contextKey === e ? this.context : (this.context = await this.client.createContext(t), this.contextKey = e, this.context);
162
+ }
163
+ getPageContext() {
164
+ var t, e, s;
165
+ return (s = (e = (t = this.options) == null ? void 0 : t.getPageContext) == null ? void 0 : e.call(t)) != null ? s : {};
166
+ }
167
+ getPageContextKey(t) {
168
+ var e, s, n, o;
169
+ return JSON.stringify([
170
+ (e = t.route) != null ? e : "",
171
+ (s = t.url) != null ? s : location.href,
172
+ (n = t.title) != null ? n : document.title,
173
+ (o = t.menuPath) != null ? o : []
174
+ ]);
152
175
  }
153
176
  async loadSources() {
154
177
  if (this.client) {
@@ -164,12 +187,13 @@ class P {
164
187
  this.client && (this.conversations = await this.client.listConversations(), this.renderPanel());
165
188
  }
166
189
  async newConversation() {
190
+ var s;
167
191
  if (!this.client) return;
168
- const t = await this.ensureContext();
169
- this.currentThread = await this.client.createConversation(t.id, t.route || document.title || "新的问答"), this.conversations = [this.currentThread, ...this.conversations], this.messages = [], this.steps = [], this.streaming = "", this.renderPanel();
192
+ const t = await this.ensureContext(), e = (s = t.menu_path) != null && s.length ? t.menu_path.join(" / ") : t.route || document.title || "新的问答";
193
+ this.currentThread = await this.client.createConversation(t.id, e), this.selectedPageKey = this.contextKey, this.conversations = [this.currentThread, ...this.conversations], this.messages = [], this.steps = [], this.streaming = "", this.renderPanel();
170
194
  }
171
195
  async selectThread(t) {
172
- this.client && (this.currentThread = t, this.messages = await this.client.listMessages(t.id), this.steps = [], this.streaming = "", this.renderPanel());
196
+ this.client && (this.currentThread = t, this.selectedPageKey = this.getPageContextKey(this.getPageContext()), this.messages = await this.client.listMessages(t.id), this.steps = [], this.streaming = "", this.renderPanel());
173
197
  }
174
198
  async uploadSource(t) {
175
199
  if (this.client) {
@@ -189,13 +213,14 @@ class P {
189
213
  this.sourceUploadError = "请先上传代码包后再提问。", this.renderPanel();
190
214
  return;
191
215
  }
192
- if (this.currentThread || await this.newConversation(), !this.currentThread) return;
216
+ const e = this.getPageContextKey(this.getPageContext());
217
+ if (this.currentThread && this.selectedPageKey && this.selectedPageKey !== e && (this.currentThread = null), this.currentThread || await this.newConversation(), !this.currentThread) return;
193
218
  this.messages.push({ id: `local-${Date.now()}`, role: "user", content: t, metadata_json: {} }), this.steps = [], this.streaming = "", this.renderPanel();
194
- const e = await this.client.streamQuestion(this.currentThread.id, t);
195
- if (!e.ok || !e.body) throw new Error("PageOps 流式问答失败");
196
- await C(e.body, (s, o) => {
197
- var n;
198
- s === "step" && this.upsertStep(o), s === "delta" && (this.streaming += String((n = o.content) != null ? n : "")), s === "done" && this.selectThread(this.currentThread), s === "error" && this.upsertStep({ id: "error", title: "执行失败", status: "failed", details: o }), this.renderPanel();
219
+ const s = await this.client.streamQuestion(this.currentThread.id, t);
220
+ if (!s.ok || !s.body) throw new Error("PageOps 流式问答失败");
221
+ await E(s.body, (n, o) => {
222
+ var r;
223
+ n === "step" && this.upsertStep(o), n === "delta" && (this.streaming += String((r = o.content) != null ? r : "")), n === "done" && this.selectThread(this.currentThread), n === "error" && this.upsertStep({ id: "error", title: "执行失败", status: "failed", details: o }), this.renderPanel();
199
224
  });
200
225
  }
201
226
  upsertStep(t) {
@@ -212,15 +237,15 @@ class P {
212
237
  var e;
213
238
  return `
214
239
  <button class="po-thread ${t.id === ((e = this.currentThread) == null ? void 0 : e.id) ? "active" : ""}" data-thread="${t.id}">
215
- <strong>${u(t.title)}</strong><span>${y(t.created_at)}</span>
240
+ <strong>${u(t.title)}</strong><span>${b(t.created_at)}</span>
216
241
  </button>`;
217
242
  }).join("")}</div>
218
243
  </aside>
219
244
  <main class="po-chat">
220
245
  <header><div><p>问数回答</p><h2>${this.currentThread ? u(this.currentThread.title) : "未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
221
246
  <section class="po-messages">
222
- ${this.messages.map((t) => `<article class="po-message ${t.role}"><b>${t.role === "user" ? "你" : "PageOps 分析"}</b><div>${t.role === "assistant" ? b(t.content) : u(t.content)}</div></article>`).join("")}
223
- ${this.streaming ? `<article class="po-message assistant streaming"><b>PageOps 分析</b><div>${b(this.streaming)}</div></article>` : ""}
247
+ ${this.messages.map((t) => `<article class="po-message ${t.role}"><b>${t.role === "user" ? "你" : "PageOps 分析"}</b><div>${t.role === "assistant" ? S(t.content) : u(t.content)}</div></article>`).join("")}
248
+ ${this.streaming ? `<article class="po-message assistant streaming"><b>PageOps 分析</b><div>${S(this.streaming)}</div></article>` : ""}
224
249
  </section>
225
250
  <form class="po-composer"><textarea ${this.sourceSnapshots.length ? "" : "disabled"} placeholder="${this.sourceSnapshots.length ? "请输入页面分析问题,Enter 发送,Shift + Enter 换行" : "请先上传代码包后再提问"}"></textarea><button type="submit" ${this.sourceSnapshots.length ? "" : "disabled"}>${this.sourceSnapshots.length ? "发送" : "请先上传代码包"}</button></form>
226
251
  </main>
@@ -243,8 +268,8 @@ class P {
243
268
  `;
244
269
  }
245
270
  renderSourceItem(t) {
246
- const e = t.filename || "未命名代码包", s = t.created_at ? y(t.created_at) : "刚刚上传", o = T(t.archive_bytes || t.total_bytes || 0);
247
- return `<article class="po-source-item"><strong>${u(e)}</strong><span>${u(s)} · ${u(o)}</span></article>`;
271
+ const e = t.filename || "未命名代码包", s = t.created_at ? b(t.created_at) : "刚刚上传", n = U(t.archive_bytes || t.total_bytes || 0);
272
+ return `<article class="po-source-item"><strong>${u(e)}</strong><span>${u(s)} · ${u(n)}</span></article>`;
248
273
  }
249
274
  renderSteps() {
250
275
  return (this.steps.length ? this.steps : [{ id: "idle", title: "等待任务", status: "pending", details: { message: "发送消息后展示执行过程。" } }]).map((e) => {
@@ -253,43 +278,43 @@ class P {
253
278
  }).join("");
254
279
  }
255
280
  bindPanelEvents() {
256
- var t, e, s, o, n, c, h, g, d, m, v;
257
- (e = (t = this.panel) == null ? void 0 : t.querySelector('[data-action="new"]')) == null || e.addEventListener("click", () => void this.newConversation()), (o = (s = this.panel) == null ? void 0 : s.querySelector('[data-action="close"]')) == null || o.addEventListener("click", () => this.close()), (c = (n = this.panel) == null ? void 0 : n.querySelector('[data-action="upload-source"]')) == null || c.addEventListener("change", (l) => {
281
+ var t, e, s, n, o, r, l, m, d, g, y;
282
+ (e = (t = this.panel) == null ? void 0 : t.querySelector('[data-action="new"]')) == null || e.addEventListener("click", () => void this.newConversation()), (n = (s = this.panel) == null ? void 0 : s.querySelector('[data-action="close"]')) == null || n.addEventListener("click", () => this.close()), (r = (o = this.panel) == null ? void 0 : o.querySelector('[data-action="upload-source"]')) == null || r.addEventListener("change", (h) => {
258
283
  var p;
259
- const i = (p = l.target.files) == null ? void 0 : p[0];
260
- i && this.uploadSource(i);
261
- }), (h = this.panel) == null || h.querySelectorAll("[data-thread]").forEach((l) => {
262
- l.addEventListener("click", () => {
263
- const i = this.conversations.find((p) => p.id === l.dataset.thread);
264
- i && this.selectThread(i);
284
+ const a = (p = h.target.files) == null ? void 0 : p[0];
285
+ a && this.uploadSource(a);
286
+ }), (l = this.panel) == null || l.querySelectorAll("[data-thread]").forEach((h) => {
287
+ h.addEventListener("click", () => {
288
+ const a = this.conversations.find((p) => p.id === h.dataset.thread);
289
+ a && this.selectThread(a);
265
290
  });
266
- }), (d = (g = this.panel) == null ? void 0 : g.querySelector("form")) == null || d.addEventListener("submit", (l) => {
267
- var $;
268
- l.preventDefault();
269
- const i = ($ = this.panel) == null ? void 0 : $.querySelector("textarea"), p = i == null ? void 0 : i.value.trim();
270
- p && (i.value = "", this.ask(p));
271
- }), (v = (m = this.panel) == null ? void 0 : m.querySelector("textarea")) == null || v.addEventListener("keydown", (l) => {
272
- var p, $;
273
- const i = l;
274
- i.key === "Enter" && !i.shiftKey && (i.preventDefault(), ($ = (p = this.panel) == null ? void 0 : p.querySelector("form")) == null || $.requestSubmit());
291
+ }), (d = (m = this.panel) == null ? void 0 : m.querySelector("form")) == null || d.addEventListener("submit", (h) => {
292
+ var v;
293
+ h.preventDefault();
294
+ const a = (v = this.panel) == null ? void 0 : v.querySelector("textarea"), p = a == null ? void 0 : a.value.trim();
295
+ p && (a.value = "", this.ask(p));
296
+ }), (y = (g = this.panel) == null ? void 0 : g.querySelector("textarea")) == null || y.addEventListener("keydown", (h) => {
297
+ var p, v;
298
+ const a = h;
299
+ a.key === "Enter" && !a.shiftKey && (a.preventDefault(), (v = (p = this.panel) == null ? void 0 : p.querySelector("form")) == null || v.requestSubmit());
275
300
  });
276
301
  }
277
302
  }
278
- function u(r) {
279
- return r.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
303
+ function u(i) {
304
+ return i.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
280
305
  }
281
- function y(r) {
282
- return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(r));
306
+ function b(i) {
307
+ return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(i));
283
308
  }
284
- function T(r) {
285
- if (!r) return "0 B";
309
+ function U(i) {
310
+ if (!i) return "0 B";
286
311
  const t = ["B", "KB", "MB", "GB"];
287
- let e = r, s = 0;
312
+ let e = i, s = 0;
288
313
  for (; e >= 1024 && s < t.length - 1; )
289
314
  e /= 1024, s += 1;
290
315
  return `${e >= 10 || s === 0 ? e.toFixed(0) : e.toFixed(1)} ${t[s]}`;
291
316
  }
292
- const _ = new P();
317
+ const _ = new T();
293
318
  export {
294
319
  _ as PageOpsSDK
295
320
  };
@@ -1,21 +1,22 @@
1
- (function(d,c){typeof exports=="object"&&typeof module!="undefined"?c(exports):typeof define=="function"&&define.amd?define(["exports"],c):(d=typeof globalThis!="undefined"?globalThis:d||self,c(d.PageOpsSDK={}))})(this,(function(d){"use strict";var O=Object.defineProperty;var _=(d,c,v)=>c in d?O(d,c,{enumerable:!0,configurable:!0,writable:!0,value:v}):d[c]=v;var a=(d,c,v)=>_(d,typeof c!="symbol"?c+"":c,v);class c{constructor(t){this.options=t}async createContext(){var e,s,o,n,l;const t=(o=(s=(e=this.options).getPageContext)==null?void 0:s.call(e))!=null?o:{};return this.request("/context/session",{method:"POST",body:JSON.stringify({app_id:this.options.appId,env:this.options.env,route:t.route,url:(n=t.url)!=null?n:location.href,title:(l=t.title)!=null?l:document.title,tenant_id:t.tenantId,user_role:t.userRole,build_version:t.buildVersion})})}async listConversations(){return(await this.request(`/conversations?app_id=${encodeURIComponent(this.options.appId)}`)).conversations}async createConversation(t,e){return this.request("/conversations",{method:"POST",body:JSON.stringify({app_id:this.options.appId,context_session_id:t,title:e})})}async listMessages(t){return(await this.request(`/conversations/${encodeURIComponent(t)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages}async listSources(){return(await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources}uploadSource(t){const e=new FormData;return e.append("file",t),this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`,{method:"POST",body:e,headers:{}})}streamQuestion(t,e){return fetch(`${this.base()}/question/stream`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:this.options.appId,thread_id:t,question:e})})}async request(t,e){var l,u;const s=(e==null?void 0:e.body)instanceof FormData?e.headers:{"content-type":"application/json",...(l=e==null?void 0:e.headers)!=null?l:{}},o=await fetch(`${this.base()}${t}`,{...e,headers:s}),n=await o.json();if(!o.ok)throw new Error((u=n.message)!=null?u:"PageOps 请求失败");return n}base(){const t=this.options.apiBase.replace(/\/$/,"");return t.endsWith("/api")?t:`${t}/api`}}function v(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function S(i){return v(i).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function E(i,t){const e=i[t],s=i[t+1];if(!(e!=null&&e.includes("|"))||!/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s!=null?s:""))return null;const o=[];let n=t;for(;n<i.length&&i[n].includes("|")&&i[n].trim();)o.push(i[n]),n+=1;const l=m=>m.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(g=>S(g.trim())),u=l(o[0]).map(m=>`<th>${m}</th>`).join(""),$=o.slice(2).map(m=>`<tr>${l(m).map(g=>`<td>${g}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${u}</tr></thead><tbody>${$}</tbody></table>`,next:n}}function w(i){const t=i.split(`
2
- `),e=[];for(let s=0;s<t.length;s+=1){const o=E(t,s);if(o){e.push(o.html),s=o.next-1;continue}const n=t[s];n.startsWith("### ")?e.push(`<h4>${S(n.slice(4))}</h4>`):n.startsWith("## ")?e.push(`<h3>${S(n.slice(3))}</h3>`):n.startsWith("# ")?e.push(`<h2>${S(n.slice(2))}</h2>`):n.startsWith("- ")?e.push(`<li>${S(n.slice(2))}</li>`):n.trim()?e.push(`<p>${S(n)}</p>`):e.push("<br>")}return e.join("")}async function P(i,t){var n,l,u;const e=i.getReader(),s=new TextDecoder;let o="";for(;;){const{done:$,value:m}=await e.read();if($)break;o+=s.decode(m,{stream:!0});const g=o.split(`
1
+ (function(d,l){typeof exports=="object"&&typeof module!="undefined"?l(exports):typeof define=="function"&&define.amd?define(["exports"],l):(d=typeof globalThis!="undefined"?globalThis:d||self,l(d.PageOpsSDK={}))})(this,(function(d){"use strict";var K=Object.defineProperty;var O=(d,l,y)=>l in d?K(d,l,{enumerable:!0,configurable:!0,writable:!0,value:y}):d[l]=y;var c=(d,l,y)=>O(d,typeof l!="symbol"?l+"":l,y);class l{constructor(t){this.options=t}async createContext(t=(n=>(n=(e=>(s=>(s=(e=this.options).getPageContext)==null?void 0:s.call(e))())())!=null?n:{})()){var i,r,h;return this.request("/context/session",{method:"POST",body:JSON.stringify({app_id:this.options.appId,env:this.options.env,route:t.route,url:(i=t.url)!=null?i:location.href,title:(r=t.title)!=null?r:document.title,menu_path:(h=t.menuPath)!=null?h:[],tenant_id:t.tenantId,user_role:t.userRole,build_version:t.buildVersion})})}async listConversations(){return(await this.request(`/conversations?app_id=${encodeURIComponent(this.options.appId)}`)).conversations}async createConversation(t,e){return this.request("/conversations",{method:"POST",body:JSON.stringify({app_id:this.options.appId,context_session_id:t,title:e})})}async listMessages(t){return(await this.request(`/conversations/${encodeURIComponent(t)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages}async listSources(){return(await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources}uploadSource(t){const e=new FormData;return e.append("file",t),this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`,{method:"POST",body:e,headers:{}})}streamQuestion(t,e){return fetch(`${this.base()}/question/stream`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:this.options.appId,thread_id:t,question:e})})}async request(t,e){var r,h;const s=(e==null?void 0:e.body)instanceof FormData?e.headers:{"content-type":"application/json",...(r=e==null?void 0:e.headers)!=null?r:{}},n=await fetch(`${this.base()}${t}`,{...e,headers:s}),i=await n.json();if(!n.ok)throw new Error((h=i.message)!=null?h:"PageOps 请求失败");return i}base(){const t=this.options.apiBase.replace(/\/$/,"");return t.endsWith("/api")?t:`${t}/api`}}function y(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function v(o){return y(o).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function x(o,t){const e=o[t],s=o[t+1];if(!(e!=null&&e.includes("|"))||!/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s!=null?s:""))return null;const n=[];let i=t;for(;i<o.length&&o[i].includes("|")&&o[i].trim();)n.push(o[i]),i+=1;const r=g=>g.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(f=>v(f.trim())),h=r(n[0]).map(g=>`<th>${g}</th>`).join(""),S=n.slice(2).map(g=>`<tr>${r(g).map(f=>`<td>${f}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${h}</tr></thead><tbody>${S}</tbody></table>`,next:i}}function P(o){const t=o.split(`
2
+ `),e=[];for(let s=0;s<t.length;s+=1){const n=t[s];if(n.trim().startsWith("```")){const r=[];for(s+=1;s<t.length&&!t[s].trim().startsWith("```");)r.push(t[s]),s+=1;e.push(`<pre><code>${y(r.join(`
3
+ `))}</code></pre>`);continue}const i=x(t,s);if(i){e.push(i.html),s=i.next-1;continue}n.startsWith("### ")?e.push(`<h4>${v(n.slice(4))}</h4>`):n.startsWith("## ")?e.push(`<h3>${v(n.slice(3))}</h3>`):n.startsWith("# ")?e.push(`<h2>${v(n.slice(2))}</h2>`):n.startsWith("- ")?e.push(`<li>${v(n.slice(2))}</li>`):n.trim()?e.push(`<p>${v(n)}</p>`):e.push("<br>")}return e.join("")}async function C(o,t){var i,r,h;const e=o.getReader(),s=new TextDecoder;let n="";for(;;){const{done:S,value:g}=await e.read();if(S)break;n+=s.decode(g,{stream:!0});const f=n.split(`
3
4
 
4
- `);o=(n=g.pop())!=null?n:"";for(const y of g){const h=(l=y.match(/^event: (.+)$/m))==null?void 0:l[1],r=(u=y.match(/^data: (.+)$/m))==null?void 0:u[1];h&&r&&t(h,JSON.parse(r))}}}class T{constructor(){a(this,"client",null);a(this,"options",null);a(this,"root",null);a(this,"panel",null);a(this,"context",null);a(this,"currentThread",null);a(this,"conversations",[]);a(this,"messages",[]);a(this,"steps",[]);a(this,"sourceSnapshots",[]);a(this,"sourceUploadStatus","");a(this,"sourceUploadError","");a(this,"sourceUploading",!1);a(this,"streaming","")}mount(t){var e;this.unmount(),this.options=t,this.client=new c(t),this.root=document.createElement("div"),this.root.className="pageops-sdk",((e=t.container)!=null?e:document.body).appendChild(this.root),this.renderClosed()}unmount(){var t;(t=this.root)==null||t.remove(),this.root=null,this.panel=null,this.context=null,this.currentThread=null,this.conversations=[],this.messages=[],this.steps=[],this.sourceSnapshots=[],this.sourceUploadStatus="",this.sourceUploadError="",this.sourceUploading=!1,this.streaming=""}open(){this.root&&(this.root.innerHTML="",this.panel=document.createElement("div"),this.panel.className="po-panel",this.root.appendChild(this.panel),this.loadSources(),this.loadConversations(),this.renderPanel())}close(){this.renderClosed()}updateContext(t){this.options&&(this.options={...this.options,...t},this.client=new c(this.options))}renderClosed(){var t;this.root&&(this.root.innerHTML='<button class="po-fab" type="button">多轮问答</button>',(t=this.root.querySelector("button"))==null||t.addEventListener("click",()=>this.open()))}async ensureContext(){if(this.context)return this.context;if(!this.client)throw new Error("PageOps SDK 未初始化");return this.context=await this.client.createContext(),this.context}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceUploadError=""}catch(t){this.sourceUploadError=t instanceof Error?t.message:"源码包状态加载失败"}this.renderPanel()}}async loadConversations(){this.client&&(this.conversations=await this.client.listConversations(),this.renderPanel())}async newConversation(){if(!this.client)return;const t=await this.ensureContext();this.currentThread=await this.client.createConversation(t.id,t.route||document.title||"新的问答"),this.conversations=[this.currentThread,...this.conversations],this.messages=[],this.steps=[],this.streaming="",this.renderPanel()}async selectThread(t){this.client&&(this.currentThread=t,this.messages=await this.client.listMessages(t.id),this.steps=[],this.streaming="",this.renderPanel())}async uploadSource(t){if(this.client){this.sourceUploading=!0,this.sourceUploadStatus="上传中...",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(t),this.sourceSnapshots=await this.client.listSources(),this.sourceUploadStatus="上传完成"}catch(e){this.sourceUploadError=e instanceof Error?e.message:"源码包上传失败",this.sourceUploadStatus=""}finally{this.sourceUploading=!1,this.renderPanel()}}}async ask(t){if(!this.client)return;if(!this.sourceSnapshots.length){this.sourceUploadError="请先上传代码包后再提问。",this.renderPanel();return}if(this.currentThread||await this.newConversation(),!this.currentThread)return;this.messages.push({id:`local-${Date.now()}`,role:"user",content:t,metadata_json:{}}),this.steps=[],this.streaming="",this.renderPanel();const e=await this.client.streamQuestion(this.currentThread.id,t);if(!e.ok||!e.body)throw new Error("PageOps 流式问答失败");await P(e.body,(s,o)=>{var n;s==="step"&&this.upsertStep(o),s==="delta"&&(this.streaming+=String((n=o.content)!=null?n:"")),s==="done"&&this.selectThread(this.currentThread),s==="error"&&this.upsertStep({id:"error",title:"执行失败",status:"failed",details:o}),this.renderPanel()})}upsertStep(t){const e=this.steps.findIndex(s=>s.id===t.id);this.steps=e===-1?[...this.steps,t]:this.steps.map(s=>s.id===t.id?{...s,...t}:s)}renderPanel(){this.panel&&(this.panel.innerHTML=`
5
+ `);n=(i=f.pop())!=null?i:"";for(const $ of f){const p=(r=$.match(/^event: (.+)$/m))==null?void 0:r[1],a=(h=$.match(/^data: (.+)$/m))==null?void 0:h[1];p&&a&&t(p,JSON.parse(a))}}}class T{constructor(){c(this,"client",null);c(this,"options",null);c(this,"root",null);c(this,"panel",null);c(this,"context",null);c(this,"contextKey","");c(this,"selectedPageKey","");c(this,"currentThread",null);c(this,"conversations",[]);c(this,"messages",[]);c(this,"steps",[]);c(this,"sourceSnapshots",[]);c(this,"sourceUploadStatus","");c(this,"sourceUploadError","");c(this,"sourceUploading",!1);c(this,"streaming","")}mount(t){var e;this.unmount(),this.options=t,this.client=new l(t),this.root=document.createElement("div"),this.root.className="pageops-sdk",((e=t.container)!=null?e:document.body).appendChild(this.root),this.renderClosed()}unmount(){var t;(t=this.root)==null||t.remove(),this.root=null,this.panel=null,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.conversations=[],this.messages=[],this.steps=[],this.sourceSnapshots=[],this.sourceUploadStatus="",this.sourceUploadError="",this.sourceUploading=!1,this.streaming=""}open(){this.root&&(this.root.innerHTML="",this.panel=document.createElement("div"),this.panel.className="po-panel",this.root.appendChild(this.panel),this.loadSources(),this.loadConversations(),this.renderPanel())}close(){this.renderClosed()}updateContext(t){this.options&&(this.options={...this.options,...t},this.client=new l(this.options),this.context=null,this.contextKey="")}renderClosed(){var t;this.root&&(this.root.innerHTML='<button class="po-fab" type="button">多轮问答</button>',(t=this.root.querySelector("button"))==null||t.addEventListener("click",()=>this.open()))}async ensureContext(){if(!this.client||!this.options)throw new Error("PageOps SDK 未初始化");const t=this.getPageContext(),e=this.getPageContextKey(t);return this.context&&this.contextKey===e?this.context:(this.context=await this.client.createContext(t),this.contextKey=e,this.context)}getPageContext(){var t,e,s;return(s=(e=(t=this.options)==null?void 0:t.getPageContext)==null?void 0:e.call(t))!=null?s:{}}getPageContextKey(t){var e,s,n,i;return JSON.stringify([(e=t.route)!=null?e:"",(s=t.url)!=null?s:location.href,(n=t.title)!=null?n:document.title,(i=t.menuPath)!=null?i:[]])}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceUploadError=""}catch(t){this.sourceUploadError=t instanceof Error?t.message:"源码包状态加载失败"}this.renderPanel()}}async loadConversations(){this.client&&(this.conversations=await this.client.listConversations(),this.renderPanel())}async newConversation(){var s;if(!this.client)return;const t=await this.ensureContext(),e=(s=t.menu_path)!=null&&s.length?t.menu_path.join(" / "):t.route||document.title||"新的问答";this.currentThread=await this.client.createConversation(t.id,e),this.selectedPageKey=this.contextKey,this.conversations=[this.currentThread,...this.conversations],this.messages=[],this.steps=[],this.streaming="",this.renderPanel()}async selectThread(t){this.client&&(this.currentThread=t,this.selectedPageKey=this.getPageContextKey(this.getPageContext()),this.messages=await this.client.listMessages(t.id),this.steps=[],this.streaming="",this.renderPanel())}async uploadSource(t){if(this.client){this.sourceUploading=!0,this.sourceUploadStatus="上传中...",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(t),this.sourceSnapshots=await this.client.listSources(),this.sourceUploadStatus="上传完成"}catch(e){this.sourceUploadError=e instanceof Error?e.message:"源码包上传失败",this.sourceUploadStatus=""}finally{this.sourceUploading=!1,this.renderPanel()}}}async ask(t){if(!this.client)return;if(!this.sourceSnapshots.length){this.sourceUploadError="请先上传代码包后再提问。",this.renderPanel();return}const e=this.getPageContextKey(this.getPageContext());if(this.currentThread&&this.selectedPageKey&&this.selectedPageKey!==e&&(this.currentThread=null),this.currentThread||await this.newConversation(),!this.currentThread)return;this.messages.push({id:`local-${Date.now()}`,role:"user",content:t,metadata_json:{}}),this.steps=[],this.streaming="",this.renderPanel();const s=await this.client.streamQuestion(this.currentThread.id,t);if(!s.ok||!s.body)throw new Error("PageOps 流式问答失败");await C(s.body,(n,i)=>{var r;n==="step"&&this.upsertStep(i),n==="delta"&&(this.streaming+=String((r=i.content)!=null?r:"")),n==="done"&&this.selectThread(this.currentThread),n==="error"&&this.upsertStep({id:"error",title:"执行失败",status:"failed",details:i}),this.renderPanel()})}upsertStep(t){const e=this.steps.findIndex(s=>s.id===t.id);this.steps=e===-1?[...this.steps,t]:this.steps.map(s=>s.id===t.id?{...s,...t}:s)}renderPanel(){this.panel&&(this.panel.innerHTML=`
5
6
  <aside class="po-sidebar">
6
7
  <div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
7
8
  <button class="po-new" data-action="new">+ 新建问答</button>
8
9
  <input class="po-search" placeholder="搜索问答" />
9
10
  <div class="po-thread-list">${this.conversations.map(t=>{var e;return`
10
11
  <button class="po-thread ${t.id===((e=this.currentThread)==null?void 0:e.id)?"active":""}" data-thread="${t.id}">
11
- <strong>${p(t.title)}</strong><span>${x(t.created_at)}</span>
12
+ <strong>${u(t.title)}</strong><span>${w(t.created_at)}</span>
12
13
  </button>`}).join("")}</div>
13
14
  </aside>
14
15
  <main class="po-chat">
15
- <header><div><p>问数回答</p><h2>${this.currentThread?p(this.currentThread.title):"未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
16
+ <header><div><p>问数回答</p><h2>${this.currentThread?u(this.currentThread.title):"未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
16
17
  <section class="po-messages">
17
- ${this.messages.map(t=>`<article class="po-message ${t.role}"><b>${t.role==="user"?"你":"PageOps 分析"}</b><div>${t.role==="assistant"?w(t.content):p(t.content)}</div></article>`).join("")}
18
- ${this.streaming?`<article class="po-message assistant streaming"><b>PageOps 分析</b><div>${w(this.streaming)}</div></article>`:""}
18
+ ${this.messages.map(t=>`<article class="po-message ${t.role}"><b>${t.role==="user"?"你":"PageOps 分析"}</b><div>${t.role==="assistant"?P(t.content):u(t.content)}</div></article>`).join("")}
19
+ ${this.streaming?`<article class="po-message assistant streaming"><b>PageOps 分析</b><div>${P(this.streaming)}</div></article>`:""}
19
20
  </section>
20
21
  <form class="po-composer"><textarea ${this.sourceSnapshots.length?"":"disabled"} placeholder="${this.sourceSnapshots.length?"请输入页面分析问题,Enter 发送,Shift + Enter 换行":"请先上传代码包后再提问"}"></textarea><button type="submit" ${this.sourceSnapshots.length?"":"disabled"}>${this.sourceSnapshots.length?"发送":"请先上传代码包"}</button></form>
21
22
  </main>
@@ -28,8 +29,8 @@
28
29
  <span>${this.sourceUploading?"上传中...":"选择代码包"}</span>
29
30
  <input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading?"disabled":""} />
30
31
  </label>
31
- ${this.sourceUploadStatus?`<p class="po-upload-status">${p(this.sourceUploadStatus)}</p>`:""}
32
+ ${this.sourceUploadStatus?`<p class="po-upload-status">${u(this.sourceUploadStatus)}</p>`:""}
32
33
  ${this.sourceSnapshots.length?`<div class="po-source-list">${this.sourceSnapshots.map(t=>this.renderSourceItem(t)).join("")}</div>`:'<p class="po-upload-empty">当前系统暂无代码包,请先上传后再提问。</p>'}
33
- ${this.sourceUploadError?`<p class="po-upload-error">${p(this.sourceUploadError)}</p>`:""}
34
+ ${this.sourceUploadError?`<p class="po-upload-error">${u(this.sourceUploadError)}</p>`:""}
34
35
  </div>
35
- `}renderSourceItem(t){const e=t.filename||"未命名代码包",s=t.created_at?x(t.created_at):"刚刚上传",o=U(t.archive_bytes||t.total_bytes||0);return`<article class="po-source-item"><strong>${p(e)}</strong><span>${p(s)} · ${p(o)}</span></article>`}renderSteps(){return(this.steps.length?this.steps:[{id:"idle",title:"等待任务",status:"pending",details:{message:"发送消息后展示执行过程。"}}]).map(e=>{var s;return`<details class="po-step ${e.status}" ${e.status==="running"||e.status==="failed"?"open":""}><summary><strong>${p(e.title)}</strong><span>${e.status}</span></summary><pre>${p(JSON.stringify((s=e.details)!=null?s:{},null,2))}</pre></details>`}).join("")}bindPanelEvents(){var t,e,s,o,n,l,u,$,m,g,y;(e=(t=this.panel)==null?void 0:t.querySelector('[data-action="new"]'))==null||e.addEventListener("click",()=>void this.newConversation()),(o=(s=this.panel)==null?void 0:s.querySelector('[data-action="close"]'))==null||o.addEventListener("click",()=>this.close()),(l=(n=this.panel)==null?void 0:n.querySelector('[data-action="upload-source"]'))==null||l.addEventListener("change",h=>{var f;const r=(f=h.target.files)==null?void 0:f[0];r&&this.uploadSource(r)}),(u=this.panel)==null||u.querySelectorAll("[data-thread]").forEach(h=>{h.addEventListener("click",()=>{const r=this.conversations.find(f=>f.id===h.dataset.thread);r&&this.selectThread(r)})}),(m=($=this.panel)==null?void 0:$.querySelector("form"))==null||m.addEventListener("submit",h=>{var b;h.preventDefault();const r=(b=this.panel)==null?void 0:b.querySelector("textarea"),f=r==null?void 0:r.value.trim();f&&(r.value="",this.ask(f))}),(y=(g=this.panel)==null?void 0:g.querySelector("textarea"))==null||y.addEventListener("keydown",h=>{var f,b;const r=h;r.key==="Enter"&&!r.shiftKey&&(r.preventDefault(),(b=(f=this.panel)==null?void 0:f.querySelector("form"))==null||b.requestSubmit())})}}function p(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function x(i){return new Intl.DateTimeFormat("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(i))}function U(i){if(!i)return"0 B";const t=["B","KB","MB","GB"];let e=i,s=0;for(;e>=1024&&s<t.length-1;)e/=1024,s+=1;return`${e>=10||s===0?e.toFixed(0):e.toFixed(1)} ${t[s]}`}const C=new T;d.PageOpsSDK=C,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})}));
36
+ `}renderSourceItem(t){const e=t.filename||"未命名代码包",s=t.created_at?w(t.created_at):"刚刚上传",n=E(t.archive_bytes||t.total_bytes||0);return`<article class="po-source-item"><strong>${u(e)}</strong><span>${u(s)} · ${u(n)}</span></article>`}renderSteps(){return(this.steps.length?this.steps:[{id:"idle",title:"等待任务",status:"pending",details:{message:"发送消息后展示执行过程。"}}]).map(e=>{var s;return`<details class="po-step ${e.status}" ${e.status==="running"||e.status==="failed"?"open":""}><summary><strong>${u(e.title)}</strong><span>${e.status}</span></summary><pre>${u(JSON.stringify((s=e.details)!=null?s:{},null,2))}</pre></details>`}).join("")}bindPanelEvents(){var t,e,s,n,i,r,h,S,g,f,$;(e=(t=this.panel)==null?void 0:t.querySelector('[data-action="new"]'))==null||e.addEventListener("click",()=>void this.newConversation()),(n=(s=this.panel)==null?void 0:s.querySelector('[data-action="close"]'))==null||n.addEventListener("click",()=>this.close()),(r=(i=this.panel)==null?void 0:i.querySelector('[data-action="upload-source"]'))==null||r.addEventListener("change",p=>{var m;const a=(m=p.target.files)==null?void 0:m[0];a&&this.uploadSource(a)}),(h=this.panel)==null||h.querySelectorAll("[data-thread]").forEach(p=>{p.addEventListener("click",()=>{const a=this.conversations.find(m=>m.id===p.dataset.thread);a&&this.selectThread(a)})}),(g=(S=this.panel)==null?void 0:S.querySelector("form"))==null||g.addEventListener("submit",p=>{var b;p.preventDefault();const a=(b=this.panel)==null?void 0:b.querySelector("textarea"),m=a==null?void 0:a.value.trim();m&&(a.value="",this.ask(m))}),($=(f=this.panel)==null?void 0:f.querySelector("textarea"))==null||$.addEventListener("keydown",p=>{var m,b;const a=p;a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),(b=(m=this.panel)==null?void 0:m.querySelector("form"))==null||b.requestSubmit())})}}function u(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function w(o){return new Intl.DateTimeFormat("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(o))}function E(o){if(!o)return"0 B";const t=["B","KB","MB","GB"];let e=o,s=0;for(;e>=1024&&s<t.length-1;)e/=1024,s+=1;return`${e>=10||s===0?e.toFixed(0):e.toFixed(1)} ${t[s]}`}const U=new T;d.PageOpsSDK=U,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})}));
package/dist/types.d.ts CHANGED
@@ -2,6 +2,7 @@ export interface PageOpsContext {
2
2
  route?: string;
3
3
  url?: string;
4
4
  title?: string;
5
+ menuPath?: string[];
5
6
  tenantId?: string;
6
7
  userRole?: string;
7
8
  buildVersion?: string;
@@ -20,6 +21,7 @@ export interface ContextSession {
20
21
  route?: string;
21
22
  url?: string;
22
23
  title?: string;
24
+ menu_path?: string[];
23
25
  tenant_id?: string;
24
26
  user_role?: string;
25
27
  build_version?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pageops/sdk",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "PageOps embeddable frontend SDK",
5
5
  "type": "module",
6
6
  "main": "dist/pageops-sdk.umd.cjs",