@pageops/sdk 0.1.6 → 0.1.7

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/index.d.ts CHANGED
@@ -16,6 +16,7 @@ declare class PageOpsSDKController {
16
16
  private sourceUploadStatus;
17
17
  private sourceUploadError;
18
18
  private sourceUploading;
19
+ private sourceRefreshTimer;
19
20
  private streaming;
20
21
  mount(options: PageOpsMountOptions): void;
21
22
  unmount(): void;
@@ -33,6 +34,11 @@ declare class PageOpsSDKController {
33
34
  private uploadSource;
34
35
  private ask;
35
36
  private upsertStep;
37
+ private latestAnalysisStatus;
38
+ private isProjectMemoryUpdating;
39
+ private questionUnavailableReason;
40
+ private scheduleSourceRefresh;
41
+ private stopSourceRefresh;
36
42
  private renderPanel;
37
43
  private renderSourceUploader;
38
44
  private renderSourceItem;
@@ -1,21 +1,21 @@
1
1
  var w = Object.defineProperty;
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 $ {
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 c = (r, t, e) => x(r, typeof t != "symbol" ? t + "" : t, e);
4
+ class S {
5
5
  constructor(t) {
6
6
  this.options = t;
7
7
  }
8
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;
9
+ var i, o, a;
10
10
  return this.request("/context/session", {
11
11
  method: "POST",
12
12
  body: JSON.stringify({
13
13
  app_id: this.options.appId,
14
14
  env: this.options.env,
15
15
  route: t.route,
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 : [],
16
+ url: (i = t.url) != null ? i : location.href,
17
+ title: (o = t.title) != null ? o : document.title,
18
+ menu_path: (a = t.menuPath) != null ? a : [],
19
19
  tenant_id: t.tenantId,
20
20
  user_role: t.userRole,
21
21
  build_version: t.buildVersion
@@ -49,73 +49,73 @@ class $ {
49
49
  });
50
50
  }
51
51
  async request(t, e) {
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;
52
+ var o, a;
53
+ const s = (e == null ? void 0 : e.body) instanceof FormData ? e.headers : { "content-type": "application/json", ...(o = e == null ? void 0 : e.headers) != null ? o : {} }, n = await fetch(`${this.base()}${t}`, { ...e, headers: s }), i = await n.json();
54
+ if (!n.ok) throw new Error((a = i.message) != null ? a : "PageOps 请求失败");
55
+ return i;
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 P(i) {
63
- return i.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
62
+ function P(r) {
63
+ return r.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
64
64
  }
65
- function f(i) {
66
- return P(i).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
65
+ function f(r) {
66
+ return P(r).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
67
67
  }
68
- function C(i, t) {
69
- const e = i[t], s = i[t + 1];
68
+ function T(r, t) {
69
+ const e = r[t], s = r[t + 1];
70
70
  if (!(e != null && e.includes("|")) || !/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s != null ? s : "")) return null;
71
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 };
72
+ let i = t;
73
+ for (; i < r.length && r[i].includes("|") && r[i].trim(); )
74
+ n.push(r[i]), i += 1;
75
+ const o = (h) => h.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((m) => f(m.trim())), a = o(n[0]).map((h) => `<th>${h}</th>`).join(""), d = n.slice(2).map((h) => `<tr>${o(h).map((m) => `<td>${m}</td>`).join("")}</tr>`).join("");
76
+ return { html: `<table><thead><tr>${a}</tr></thead><tbody>${d}</tbody></table>`, next: i };
77
77
  }
78
- function S(i) {
79
- const t = i.split(`
78
+ function $(r) {
79
+ const t = r.split(`
80
80
  `), e = [];
81
81
  for (let s = 0; s < t.length; s += 1) {
82
82
  const n = t[s];
83
83
  if (n.trim().startsWith("```")) {
84
- const r = [];
84
+ const o = [];
85
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(`
86
+ o.push(t[s]), s += 1;
87
+ e.push(`<pre><code>${P(o.join(`
88
88
  `))}</code></pre>`);
89
89
  continue;
90
90
  }
91
- const o = C(t, s);
92
- if (o) {
93
- e.push(o.html), s = o.next - 1;
91
+ const i = T(t, s);
92
+ if (i) {
93
+ e.push(i.html), s = i.next - 1;
94
94
  continue;
95
95
  }
96
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>");
97
97
  }
98
98
  return e.join("");
99
99
  }
100
- async function E(i, t) {
101
- var o, r, l;
102
- const e = i.getReader(), s = new TextDecoder();
100
+ async function U(r, t) {
101
+ var i, o, a;
102
+ const e = r.getReader(), s = new TextDecoder();
103
103
  let n = "";
104
104
  for (; ; ) {
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(`
105
+ const { done: d, value: h } = await e.read();
106
+ if (d) break;
107
+ n += s.decode(h, { stream: !0 });
108
+ const m = n.split(`
109
109
 
110
110
  `);
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));
111
+ n = (i = m.pop()) != null ? i : "";
112
+ for (const y of m) {
113
+ const p = (o = y.match(/^event: (.+)$/m)) == null ? void 0 : o[1], l = (a = y.match(/^data: (.+)$/m)) == null ? void 0 : a[1];
114
+ p && l && t(p, JSON.parse(l));
115
115
  }
116
116
  }
117
117
  }
118
- class T {
118
+ class C {
119
119
  constructor() {
120
120
  c(this, "client", null);
121
121
  c(this, "options", null);
@@ -132,24 +132,25 @@ class T {
132
132
  c(this, "sourceUploadStatus", "");
133
133
  c(this, "sourceUploadError", "");
134
134
  c(this, "sourceUploading", !1);
135
+ c(this, "sourceRefreshTimer", null);
135
136
  c(this, "streaming", "");
136
137
  }
137
138
  mount(t) {
138
139
  var e;
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();
140
+ 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();
140
141
  }
141
142
  unmount() {
142
143
  var t;
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 = "";
144
+ this.stopSourceRefresh(), (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 = "";
144
145
  }
145
146
  open() {
146
147
  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());
147
148
  }
148
149
  close() {
149
- this.renderClosed();
150
+ this.stopSourceRefresh(), this.renderClosed();
150
151
  }
151
152
  updateContext(t) {
152
- this.options && (this.options = { ...this.options, ...t }, this.client = new $(this.options), this.context = null, this.contextKey = "");
153
+ this.options && (this.options = { ...this.options, ...t }, this.client = new S(this.options), this.context = null, this.contextKey = "");
153
154
  }
154
155
  renderClosed() {
155
156
  var t;
@@ -165,12 +166,12 @@ class T {
165
166
  return (s = (e = (t = this.options) == null ? void 0 : t.getPageContext) == null ? void 0 : e.call(t)) != null ? s : {};
166
167
  }
167
168
  getPageContextKey(t) {
168
- var e, s, n, o;
169
+ var e, s, n, i;
169
170
  return JSON.stringify([
170
171
  (e = t.route) != null ? e : "",
171
172
  (s = t.url) != null ? s : location.href,
172
173
  (n = t.title) != null ? n : document.title,
173
- (o = t.menuPath) != null ? o : []
174
+ (i = t.menuPath) != null ? i : []
174
175
  ]);
175
176
  }
176
177
  async loadSources() {
@@ -180,7 +181,7 @@ class T {
180
181
  } catch (t) {
181
182
  this.sourceUploadError = t instanceof Error ? t.message : "源码包状态加载失败";
182
183
  }
183
- this.renderPanel();
184
+ this.scheduleSourceRefresh(), this.renderPanel();
184
185
  }
185
186
  }
186
187
  async loadConversations() {
@@ -199,7 +200,7 @@ class T {
199
200
  if (this.client) {
200
201
  this.sourceUploading = !0, this.sourceUploadStatus = "上传中...", this.sourceUploadError = "", this.renderPanel();
201
202
  try {
202
- await this.client.uploadSource(t), this.sourceSnapshots = await this.client.listSources(), this.sourceUploadStatus = "上传完成";
203
+ await this.client.uploadSource(t), this.sourceSnapshots = await this.client.listSources(), this.sourceUploadStatus = this.isProjectMemoryUpdating() ? "源码上传完成,项目记忆更新中..." : "上传完成", this.scheduleSourceRefresh();
203
204
  } catch (e) {
204
205
  this.sourceUploadError = e instanceof Error ? e.message : "源码包上传失败", this.sourceUploadStatus = "";
205
206
  } finally {
@@ -208,49 +209,73 @@ class T {
208
209
  }
209
210
  }
210
211
  async ask(t) {
212
+ var i;
211
213
  if (!this.client) return;
212
- if (!this.sourceSnapshots.length) {
213
- this.sourceUploadError = "请先上传代码包后再提问。", this.renderPanel();
214
+ const e = this.questionUnavailableReason();
215
+ if (e) {
216
+ this.sourceUploadError = e, this.renderPanel();
214
217
  return;
215
218
  }
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;
219
+ const s = this.getPageContextKey(this.getPageContext());
220
+ if (this.currentThread && this.selectedPageKey && this.selectedPageKey !== s && (this.currentThread = null), this.currentThread || await this.newConversation(), !this.currentThread) return;
218
221
  this.messages.push({ id: `local-${Date.now()}`, role: "user", content: t, metadata_json: {} }), this.steps = [], this.streaming = "", 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();
222
+ const n = await this.client.streamQuestion(this.currentThread.id, t);
223
+ if (!n.ok) {
224
+ const o = await n.json().catch(() => ({}));
225
+ throw new Error(String((i = o.message) != null ? i : "PageOps 流式问答失败"));
226
+ }
227
+ if (!n.body) throw new Error("PageOps 流式问答失败");
228
+ await U(n.body, (o, a) => {
229
+ var d;
230
+ o === "step" && this.upsertStep(a), o === "delta" && (this.streaming += String((d = a.content) != null ? d : "")), o === "done" && this.selectThread(this.currentThread), o === "error" && this.upsertStep({ id: "error", title: "执行失败", status: "failed", details: a }), this.renderPanel();
224
231
  });
225
232
  }
226
233
  upsertStep(t) {
227
234
  const e = this.steps.findIndex((s) => s.id === t.id);
228
235
  this.steps = e === -1 ? [...this.steps, t] : this.steps.map((s) => s.id === t.id ? { ...s, ...t } : s);
229
236
  }
237
+ latestAnalysisStatus() {
238
+ var t, e, s;
239
+ return String((s = (e = (t = this.sourceSnapshots[0]) == null ? void 0 : t.metadata) == null ? void 0 : e.analysis_status) != null ? s : "");
240
+ }
241
+ isProjectMemoryUpdating() {
242
+ return ["pending", "running"].includes(this.latestAnalysisStatus());
243
+ }
244
+ questionUnavailableReason() {
245
+ return this.sourceSnapshots.length ? this.isProjectMemoryUpdating() ? "项目记忆正在更新,完成前暂不能问答。" : this.latestAnalysisStatus() === "failed" ? "项目记忆更新失败,请重新上传或重新索引。" : "" : "请先上传代码包后再提问。";
246
+ }
247
+ scheduleSourceRefresh() {
248
+ this.stopSourceRefresh(), this.isProjectMemoryUpdating() && (this.sourceRefreshTimer = setTimeout(() => void this.loadSources(), 1500));
249
+ }
250
+ stopSourceRefresh() {
251
+ this.sourceRefreshTimer && clearTimeout(this.sourceRefreshTimer), this.sourceRefreshTimer = null;
252
+ }
230
253
  renderPanel() {
231
- this.panel && (this.panel.innerHTML = `
254
+ if (!this.panel) return;
255
+ const t = this.questionUnavailableReason(), e = t || "请输入页面分析问题,Enter 发送,Shift + Enter 换行";
256
+ this.panel.innerHTML = `
232
257
  <aside class="po-sidebar">
233
258
  <div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
234
259
  <button class="po-new" data-action="new">+ 新建问答</button>
235
260
  <input class="po-search" placeholder="搜索问答" />
236
- <div class="po-thread-list">${this.conversations.map((t) => {
237
- var e;
261
+ <div class="po-thread-list">${this.conversations.map((s) => {
262
+ var n;
238
263
  return `
239
- <button class="po-thread ${t.id === ((e = this.currentThread) == null ? void 0 : e.id) ? "active" : ""}" data-thread="${t.id}">
240
- <strong>${u(t.title)}</strong><span>${b(t.created_at)}</span>
264
+ <button class="po-thread ${s.id === ((n = this.currentThread) == null ? void 0 : n.id) ? "active" : ""}" data-thread="${s.id}">
265
+ <strong>${u(s.title)}</strong><span>${b(s.created_at)}</span>
241
266
  </button>`;
242
267
  }).join("")}</div>
243
268
  </aside>
244
269
  <main class="po-chat">
245
270
  <header><div><p>问数回答</p><h2>${this.currentThread ? u(this.currentThread.title) : "未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
246
271
  <section class="po-messages">
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>` : ""}
272
+ ${this.messages.map((s) => `<article class="po-message ${s.role}"><b>${s.role === "user" ? "你" : "PageOps 分析"}</b><div>${s.role === "assistant" ? $(s.content) : u(s.content)}</div></article>`).join("")}
273
+ ${this.streaming ? `<article class="po-message assistant streaming"><b>PageOps 分析</b><div>${$(this.streaming)}</div></article>` : ""}
249
274
  </section>
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>
275
+ <form class="po-composer"><textarea ${t ? "disabled" : ""} placeholder="${u(e)}"></textarea><button type="submit" ${t ? "disabled" : ""}>${t ? "暂不可提问" : "发送"}</button></form>
251
276
  </main>
252
277
  <aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
253
- `, this.bindPanelEvents());
278
+ `, this.bindPanelEvents();
254
279
  }
255
280
  renderSourceUploader() {
256
281
  return `
@@ -268,8 +293,9 @@ class T {
268
293
  `;
269
294
  }
270
295
  renderSourceItem(t) {
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>`;
296
+ var a, d, h;
297
+ const e = t.filename || "未命名代码包", s = t.created_at ? b(t.created_at) : "刚刚上传", n = E(t.archive_bytes || t.total_bytes || 0), i = String((d = (a = t.metadata) == null ? void 0 : a.analysis_status) != null ? d : "unknown"), o = (h = { pending: "项目记忆等待更新", running: "项目记忆更新中", ready: "项目记忆已就绪", failed: "项目记忆更新失败" }[i]) != null ? h : "项目记忆状态未知";
298
+ return `<article class="po-source-item"><strong>${u(e)}</strong><span>${u(s)} · ${u(n)}</span><span>${u(o)}</span></article>`;
273
299
  }
274
300
  renderSteps() {
275
301
  return (this.steps.length ? this.steps : [{ id: "idle", title: "等待任务", status: "pending", details: { message: "发送消息后展示执行过程。" } }]).map((e) => {
@@ -278,43 +304,43 @@ class T {
278
304
  }).join("");
279
305
  }
280
306
  bindPanelEvents() {
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) => {
283
- var p;
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);
307
+ var t, e, s, n, i, o, a, d, h, m, y;
308
+ (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()), (o = (i = this.panel) == null ? void 0 : i.querySelector('[data-action="upload-source"]')) == null || o.addEventListener("change", (p) => {
309
+ var g;
310
+ const l = (g = p.target.files) == null ? void 0 : g[0];
311
+ l && this.uploadSource(l);
312
+ }), (a = this.panel) == null || a.querySelectorAll("[data-thread]").forEach((p) => {
313
+ p.addEventListener("click", () => {
314
+ const l = this.conversations.find((g) => g.id === p.dataset.thread);
315
+ l && this.selectThread(l);
290
316
  });
291
- }), (d = (m = this.panel) == null ? void 0 : m.querySelector("form")) == null || d.addEventListener("submit", (h) => {
317
+ }), (h = (d = this.panel) == null ? void 0 : d.querySelector("form")) == null || h.addEventListener("submit", (p) => {
292
318
  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());
319
+ p.preventDefault();
320
+ const l = (v = this.panel) == null ? void 0 : v.querySelector("textarea"), g = l == null ? void 0 : l.value.trim();
321
+ g && (l.value = "", this.ask(g));
322
+ }), (y = (m = this.panel) == null ? void 0 : m.querySelector("textarea")) == null || y.addEventListener("keydown", (p) => {
323
+ var g, v;
324
+ const l = p;
325
+ l.key === "Enter" && !l.shiftKey && (l.preventDefault(), (v = (g = this.panel) == null ? void 0 : g.querySelector("form")) == null || v.requestSubmit());
300
326
  });
301
327
  }
302
328
  }
303
- function u(i) {
304
- return i.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
329
+ function u(r) {
330
+ return r.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
305
331
  }
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));
332
+ function b(r) {
333
+ return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(r));
308
334
  }
309
- function U(i) {
310
- if (!i) return "0 B";
335
+ function E(r) {
336
+ if (!r) return "0 B";
311
337
  const t = ["B", "KB", "MB", "GB"];
312
- let e = i, s = 0;
338
+ let e = r, s = 0;
313
339
  for (; e >= 1024 && s < t.length - 1; )
314
340
  e /= 1024, s += 1;
315
341
  return `${e >= 10 || s === 0 ? e.toFixed(0) : e.toFixed(1)} ${t[s]}`;
316
342
  }
317
- const _ = new T();
343
+ const _ = new C();
318
344
  export {
319
345
  _ as PageOpsSDK
320
346
  };
@@ -1,27 +1,27 @@
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(`
1
+ (function(u,h){typeof exports=="object"&&typeof module!="undefined"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(u=typeof globalThis!="undefined"?globalThis:u||self,h(u.PageOpsSDK={}))})(this,(function(u){"use strict";var K=Object.defineProperty;var O=(u,h,S)=>h in u?K(u,h,{enumerable:!0,configurable:!0,writable:!0,value:S}):u[h]=S;var c=(u,h,S)=>O(u,typeof h!="symbol"?h+"":h,S);class h{constructor(e){this.options=e}async createContext(e=(n=>(n=(t=>(s=>(s=(t=this.options).getPageContext)==null?void 0:s.call(t))())())!=null?n:{})()){var i,r,a;return this.request("/context/session",{method:"POST",body:JSON.stringify({app_id:this.options.appId,env:this.options.env,route:e.route,url:(i=e.url)!=null?i:location.href,title:(r=e.title)!=null?r:document.title,menu_path:(a=e.menuPath)!=null?a:[],tenant_id:e.tenantId,user_role:e.userRole,build_version:e.buildVersion})})}async listConversations(){return(await this.request(`/conversations?app_id=${encodeURIComponent(this.options.appId)}`)).conversations}async createConversation(e,t){return this.request("/conversations",{method:"POST",body:JSON.stringify({app_id:this.options.appId,context_session_id:e,title:t})})}async listMessages(e){return(await this.request(`/conversations/${encodeURIComponent(e)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages}async listSources(){return(await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources}uploadSource(e){const t=new FormData;return t.append("file",e),this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`,{method:"POST",body:t,headers:{}})}streamQuestion(e,t){return fetch(`${this.base()}/question/stream`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:this.options.appId,thread_id:e,question:t})})}async request(e,t){var r,a;const s=(t==null?void 0:t.body)instanceof FormData?t.headers:{"content-type":"application/json",...(r=t==null?void 0:t.headers)!=null?r:{}},n=await fetch(`${this.base()}${e}`,{...t,headers:s}),i=await n.json();if(!n.ok)throw new Error((a=i.message)!=null?a:"PageOps 请求失败");return i}base(){const e=this.options.apiBase.replace(/\/$/,"");return e.endsWith("/api")?e:`${e}/api`}}function S(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function v(o){return S(o).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function x(o,e){const t=o[e],s=o[e+1];if(!(t!=null&&t.includes("|"))||!/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s!=null?s:""))return null;const n=[];let i=e;for(;i<o.length&&o[i].includes("|")&&o[i].trim();)n.push(o[i]),i+=1;const r=d=>d.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(y=>v(y.trim())),a=r(n[0]).map(d=>`<th>${d}</th>`).join(""),g=n.slice(2).map(d=>`<tr>${r(d).map(y=>`<td>${y}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${a}</tr></thead><tbody>${g}</tbody></table>`,next:i}}function P(o){const e=o.split(`
2
+ `),t=[];for(let s=0;s<e.length;s+=1){const n=e[s];if(n.trim().startsWith("```")){const r=[];for(s+=1;s<e.length&&!e[s].trim().startsWith("```");)r.push(e[s]),s+=1;t.push(`<pre><code>${S(r.join(`
3
+ `))}</code></pre>`);continue}const i=x(e,s);if(i){t.push(i.html),s=i.next-1;continue}n.startsWith("### ")?t.push(`<h4>${v(n.slice(4))}</h4>`):n.startsWith("## ")?t.push(`<h3>${v(n.slice(3))}</h3>`):n.startsWith("# ")?t.push(`<h2>${v(n.slice(2))}</h2>`):n.startsWith("- ")?t.push(`<li>${v(n.slice(2))}</li>`):n.trim()?t.push(`<p>${v(n)}</p>`):t.push("<br>")}return t.join("")}async function T(o,e){var i,r,a;const t=o.getReader(),s=new TextDecoder;let n="";for(;;){const{done:g,value:d}=await t.read();if(g)break;n+=s.decode(d,{stream:!0});const y=n.split(`
4
4
 
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
+ `);n=(i=y.pop())!=null?i:"";for(const $ of y){const m=(r=$.match(/^event: (.+)$/m))==null?void 0:r[1],l=(a=$.match(/^data: (.+)$/m))==null?void 0:a[1];m&&l&&e(m,JSON.parse(l))}}}class U{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,"sourceRefreshTimer",null);c(this,"streaming","")}mount(e){var t;this.unmount(),this.options=e,this.client=new h(e),this.root=document.createElement("div"),this.root.className="pageops-sdk",((t=e.container)!=null?t:document.body).appendChild(this.root),this.renderClosed()}unmount(){var e;this.stopSourceRefresh(),(e=this.root)==null||e.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.stopSourceRefresh(),this.renderClosed()}updateContext(e){this.options&&(this.options={...this.options,...e},this.client=new h(this.options),this.context=null,this.contextKey="")}renderClosed(){var e;this.root&&(this.root.innerHTML='<button class="po-fab" type="button">多轮问答</button>',(e=this.root.querySelector("button"))==null||e.addEventListener("click",()=>this.open()))}async ensureContext(){if(!this.client||!this.options)throw new Error("PageOps SDK 未初始化");const e=this.getPageContext(),t=this.getPageContextKey(e);return this.context&&this.contextKey===t?this.context:(this.context=await this.client.createContext(e),this.contextKey=t,this.context)}getPageContext(){var e,t,s;return(s=(t=(e=this.options)==null?void 0:e.getPageContext)==null?void 0:t.call(e))!=null?s:{}}getPageContextKey(e){var t,s,n,i;return JSON.stringify([(t=e.route)!=null?t:"",(s=e.url)!=null?s:location.href,(n=e.title)!=null?n:document.title,(i=e.menuPath)!=null?i:[]])}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceUploadError=""}catch(e){this.sourceUploadError=e instanceof Error?e.message:"源码包状态加载失败"}this.scheduleSourceRefresh(),this.renderPanel()}}async loadConversations(){this.client&&(this.conversations=await this.client.listConversations(),this.renderPanel())}async newConversation(){var s;if(!this.client)return;const e=await this.ensureContext(),t=(s=e.menu_path)!=null&&s.length?e.menu_path.join(" / "):e.route||document.title||"新的问答";this.currentThread=await this.client.createConversation(e.id,t),this.selectedPageKey=this.contextKey,this.conversations=[this.currentThread,...this.conversations],this.messages=[],this.steps=[],this.streaming="",this.renderPanel()}async selectThread(e){this.client&&(this.currentThread=e,this.selectedPageKey=this.getPageContextKey(this.getPageContext()),this.messages=await this.client.listMessages(e.id),this.steps=[],this.streaming="",this.renderPanel())}async uploadSource(e){if(this.client){this.sourceUploading=!0,this.sourceUploadStatus="上传中...",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(e),this.sourceSnapshots=await this.client.listSources(),this.sourceUploadStatus=this.isProjectMemoryUpdating()?"源码上传完成,项目记忆更新中...":"上传完成",this.scheduleSourceRefresh()}catch(t){this.sourceUploadError=t instanceof Error?t.message:"源码包上传失败",this.sourceUploadStatus=""}finally{this.sourceUploading=!1,this.renderPanel()}}}async ask(e){var i;if(!this.client)return;const t=this.questionUnavailableReason();if(t){this.sourceUploadError=t,this.renderPanel();return}const s=this.getPageContextKey(this.getPageContext());if(this.currentThread&&this.selectedPageKey&&this.selectedPageKey!==s&&(this.currentThread=null),this.currentThread||await this.newConversation(),!this.currentThread)return;this.messages.push({id:`local-${Date.now()}`,role:"user",content:e,metadata_json:{}}),this.steps=[],this.streaming="",this.renderPanel();const n=await this.client.streamQuestion(this.currentThread.id,e);if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(String((i=r.message)!=null?i:"PageOps 流式问答失败"))}if(!n.body)throw new Error("PageOps 流式问答失败");await T(n.body,(r,a)=>{var g;r==="step"&&this.upsertStep(a),r==="delta"&&(this.streaming+=String((g=a.content)!=null?g:"")),r==="done"&&this.selectThread(this.currentThread),r==="error"&&this.upsertStep({id:"error",title:"执行失败",status:"failed",details:a}),this.renderPanel()})}upsertStep(e){const t=this.steps.findIndex(s=>s.id===e.id);this.steps=t===-1?[...this.steps,e]:this.steps.map(s=>s.id===e.id?{...s,...e}:s)}latestAnalysisStatus(){var e,t,s;return String((s=(t=(e=this.sourceSnapshots[0])==null?void 0:e.metadata)==null?void 0:t.analysis_status)!=null?s:"")}isProjectMemoryUpdating(){return["pending","running"].includes(this.latestAnalysisStatus())}questionUnavailableReason(){return this.sourceSnapshots.length?this.isProjectMemoryUpdating()?"项目记忆正在更新,完成前暂不能问答。":this.latestAnalysisStatus()==="failed"?"项目记忆更新失败,请重新上传或重新索引。":"":"请先上传代码包后再提问。"}scheduleSourceRefresh(){this.stopSourceRefresh(),this.isProjectMemoryUpdating()&&(this.sourceRefreshTimer=setTimeout(()=>void this.loadSources(),1500))}stopSourceRefresh(){this.sourceRefreshTimer&&clearTimeout(this.sourceRefreshTimer),this.sourceRefreshTimer=null}renderPanel(){if(!this.panel)return;const e=this.questionUnavailableReason(),t=e||"请输入页面分析问题,Enter 发送,Shift + Enter 换行";this.panel.innerHTML=`
6
6
  <aside class="po-sidebar">
7
7
  <div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
8
8
  <button class="po-new" data-action="new">+ 新建问答</button>
9
9
  <input class="po-search" placeholder="搜索问答" />
10
- <div class="po-thread-list">${this.conversations.map(t=>{var e;return`
11
- <button class="po-thread ${t.id===((e=this.currentThread)==null?void 0:e.id)?"active":""}" data-thread="${t.id}">
12
- <strong>${u(t.title)}</strong><span>${w(t.created_at)}</span>
10
+ <div class="po-thread-list">${this.conversations.map(s=>{var n;return`
11
+ <button class="po-thread ${s.id===((n=this.currentThread)==null?void 0:n.id)?"active":""}" data-thread="${s.id}">
12
+ <strong>${p(s.title)}</strong><span>${w(s.created_at)}</span>
13
13
  </button>`}).join("")}</div>
14
14
  </aside>
15
15
  <main class="po-chat">
16
- <header><div><p>问数回答</p><h2>${this.currentThread?u(this.currentThread.title):"未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
16
+ <header><div><p>问数回答</p><h2>${this.currentThread?p(this.currentThread.title):"未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
17
17
  <section class="po-messages">
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("")}
18
+ ${this.messages.map(s=>`<article class="po-message ${s.role}"><b>${s.role==="user"?"你":"PageOps 分析"}</b><div>${s.role==="assistant"?P(s.content):p(s.content)}</div></article>`).join("")}
19
19
  ${this.streaming?`<article class="po-message assistant streaming"><b>PageOps 分析</b><div>${P(this.streaming)}</div></article>`:""}
20
20
  </section>
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
+ <form class="po-composer"><textarea ${e?"disabled":""} placeholder="${p(t)}"></textarea><button type="submit" ${e?"disabled":""}>${e?"暂不可提问":"发送"}</button></form>
22
22
  </main>
23
23
  <aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
24
- `,this.bindPanelEvents())}renderSourceUploader(){return`
24
+ `,this.bindPanelEvents()}renderSourceUploader(){return`
25
25
  <div class="po-source-uploader">
26
26
  <strong>源码包</strong>
27
27
  <p>上传 zip、tar、tar.gz 或 tgz 后,PageOps 将基于代码证据回答问题。</p>
@@ -29,8 +29,8 @@
29
29
  <span>${this.sourceUploading?"上传中...":"选择代码包"}</span>
30
30
  <input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading?"disabled":""} />
31
31
  </label>
32
- ${this.sourceUploadStatus?`<p class="po-upload-status">${u(this.sourceUploadStatus)}</p>`:""}
33
- ${this.sourceSnapshots.length?`<div class="po-source-list">${this.sourceSnapshots.map(t=>this.renderSourceItem(t)).join("")}</div>`:'<p class="po-upload-empty">当前系统暂无代码包,请先上传后再提问。</p>'}
34
- ${this.sourceUploadError?`<p class="po-upload-error">${u(this.sourceUploadError)}</p>`:""}
32
+ ${this.sourceUploadStatus?`<p class="po-upload-status">${p(this.sourceUploadStatus)}</p>`:""}
33
+ ${this.sourceSnapshots.length?`<div class="po-source-list">${this.sourceSnapshots.map(e=>this.renderSourceItem(e)).join("")}</div>`:'<p class="po-upload-empty">当前系统暂无代码包,请先上传后再提问。</p>'}
34
+ ${this.sourceUploadError?`<p class="po-upload-error">${p(this.sourceUploadError)}</p>`:""}
35
35
  </div>
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"})}));
36
+ `}renderSourceItem(e){var a,g,d;const t=e.filename||"未命名代码包",s=e.created_at?w(e.created_at):"刚刚上传",n=C(e.archive_bytes||e.total_bytes||0),i=String((g=(a=e.metadata)==null?void 0:a.analysis_status)!=null?g:"unknown"),r=(d={pending:"项目记忆等待更新",running:"项目记忆更新中",ready:"项目记忆已就绪",failed:"项目记忆更新失败"}[i])!=null?d:"项目记忆状态未知";return`<article class="po-source-item"><strong>${p(t)}</strong><span>${p(s)} · ${p(n)}</span><span>${p(r)}</span></article>`}renderSteps(){return(this.steps.length?this.steps:[{id:"idle",title:"等待任务",status:"pending",details:{message:"发送消息后展示执行过程。"}}]).map(t=>{var s;return`<details class="po-step ${t.status}" ${t.status==="running"||t.status==="failed"?"open":""}><summary><strong>${p(t.title)}</strong><span>${t.status}</span></summary><pre>${p(JSON.stringify((s=t.details)!=null?s:{},null,2))}</pre></details>`}).join("")}bindPanelEvents(){var e,t,s,n,i,r,a,g,d,y,$;(t=(e=this.panel)==null?void 0:e.querySelector('[data-action="new"]'))==null||t.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",m=>{var f;const l=(f=m.target.files)==null?void 0:f[0];l&&this.uploadSource(l)}),(a=this.panel)==null||a.querySelectorAll("[data-thread]").forEach(m=>{m.addEventListener("click",()=>{const l=this.conversations.find(f=>f.id===m.dataset.thread);l&&this.selectThread(l)})}),(d=(g=this.panel)==null?void 0:g.querySelector("form"))==null||d.addEventListener("submit",m=>{var b;m.preventDefault();const l=(b=this.panel)==null?void 0:b.querySelector("textarea"),f=l==null?void 0:l.value.trim();f&&(l.value="",this.ask(f))}),($=(y=this.panel)==null?void 0:y.querySelector("textarea"))==null||$.addEventListener("keydown",m=>{var f,b;const l=m;l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),(b=(f=this.panel)==null?void 0:f.querySelector("form"))==null||b.requestSubmit())})}}function p(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 C(o){if(!o)return"0 B";const e=["B","KB","MB","GB"];let t=o,s=0;for(;t>=1024&&s<e.length-1;)t/=1024,s+=1;return`${t>=10||s===0?t.toFixed(0):t.toFixed(1)} ${e[s]}`}const E=new U;u.PageOpsSDK=E,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})}));
package/dist/types.d.ts CHANGED
@@ -56,6 +56,7 @@ export interface SourceSnapshot {
56
56
  file_count: number;
57
57
  total_bytes?: number;
58
58
  created_at?: string | null;
59
+ metadata?: Record<string, unknown>;
59
60
  }
60
61
  export interface SourceSnapshotListResponse {
61
62
  sources: SourceSnapshot[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pageops/sdk",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "PageOps embeddable frontend SDK",
5
5
  "type": "module",
6
6
  "main": "dist/pageops-sdk.umd.cjs",
@@ -15,7 +15,9 @@
15
15
  },
16
16
  "./dist/pageops-sdk.css": "./dist/pageops-sdk.css"
17
17
  },
18
- "files": ["dist"],
18
+ "files": [
19
+ "dist"
20
+ ],
19
21
  "scripts": {
20
22
  "build": "vite build && tsc --emitDeclarationOnly",
21
23
  "pack:check": "npm pack --dry-run"