@firstpick/pi-package-webui 0.7.7 → 0.7.8

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/public/index.html CHANGED
@@ -12,7 +12,17 @@
12
12
  <link rel="manifest" href="/manifest.webmanifest" />
13
13
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
14
14
  <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
15
- <link rel="stylesheet" href="/styles.css?v=84" />
15
+ <link rel="stylesheet" href="/styles.css?v=86" />
16
+ <script>
17
+ // Public-only issue-bot runtime configuration. Keep disabled unless the gateway,
18
+ // Turnstile site key, exact CORS origin, and private-report destination are approved.
19
+ window.__PI_WEBUI_ISSUE_BOT_CONFIG__ ??= Object.freeze({
20
+ enabled: false,
21
+ gatewayBaseUrl: "",
22
+ turnstileSiteKey: "",
23
+ privateSecurityReportUrl: "",
24
+ });
25
+ </script>
16
26
  <style id="webuiBootFailureStyles">
17
27
  .webui-boot-failure[hidden] { display: none !important; }
18
28
  .webui-boot-failure {
@@ -902,6 +912,9 @@
902
912
  </div>
903
913
  </section>
904
914
  </div>
915
+ <footer class="side-panel-footer">
916
+ <button id="openIssueButton" class="open-issue-button" type="button" aria-haspopup="dialog" aria-controls="issueWizardDialog">Open Issue</button>
917
+ </footer>
905
918
  </aside>
906
919
  </main>
907
920
 
@@ -922,6 +935,47 @@
922
935
  <span class="undo-toast-progress" aria-hidden="true"></span>
923
936
  </aside>
924
937
 
938
+ <dialog id="issueWizardDialog" class="extension-dialog issue-wizard-dialog" aria-labelledby="issueWizardTitle" aria-describedby="issueWizardDescription">
939
+ <form method="dialog">
940
+ <header class="issue-wizard-header">
941
+ <div>
942
+ <span class="issue-wizard-kicker">GitHub issue</span>
943
+ <h2 id="issueWizardTitle">Open an issue</h2>
944
+ <p id="issueWizardDescription" class="muted">Use this five-step wizard to prepare a complete issue you can copy to GitHub.</p>
945
+ </div>
946
+ <button id="issueWizardCloseButton" type="button" aria-label="Close Open Issue wizard">Close</button>
947
+ </header>
948
+ <div class="issue-wizard-progress-row">
949
+ <span id="issueWizardProgress" class="issue-wizard-progress">Step 1 of 5</span>
950
+ <span>1 Category · 2 Component · 3 Template · 4 Details · 5 Review</span>
951
+ </div>
952
+ <div id="issueWizardPages" class="issue-wizard-pages">
953
+ <section class="issue-wizard-page" data-issue-wizard-page="1" aria-label="Step 1: choose issue category" hidden></section>
954
+ <section class="issue-wizard-page" data-issue-wizard-page="2" aria-label="Step 2: choose affected component" hidden></section>
955
+ <section class="issue-wizard-page" data-issue-wizard-page="3" aria-label="Step 3: choose issue template" hidden></section>
956
+ <section class="issue-wizard-page" data-issue-wizard-page="4" aria-label="Step 4: add issue details" hidden></section>
957
+ <section class="issue-wizard-page" data-issue-wizard-page="5" aria-label="Step 5: review GitHub issue" hidden></section>
958
+ </div>
959
+ <p id="issueWizardStatus" class="issue-wizard-status muted" role="status" aria-live="polite" aria-atomic="true">Start by choosing an issue category.</p>
960
+ <section id="issueWizardSubmissionStatus" class="issue-wizard-submission-status" role="status" aria-live="polite" aria-atomic="true" hidden>
961
+ <p id="issueWizardSubmissionMessage" class="issue-wizard-submission-message"></p>
962
+ <div class="issue-wizard-submission-actions">
963
+ <a id="issueWizardSubmissionLink" target="_blank" rel="noopener noreferrer" hidden></a>
964
+ <button id="issueWizardRefreshButton" type="button" hidden>Refresh status</button>
965
+ </div>
966
+ <p id="issueWizardSecurityGuidance" class="issue-wizard-security-guidance" hidden>Do not include security details or credentials in a public issue. <a id="issueWizardSecurityLink" target="_blank" rel="noopener noreferrer" hidden>Use private vulnerability reporting</a>.</p>
967
+ </section>
968
+ <div id="issueWizardTurnstile" class="issue-wizard-turnstile" aria-label="Bot protection challenge"></div>
969
+ <menu class="issue-wizard-actions">
970
+ <button id="issueWizardBackButton" type="button">Back</button>
971
+ <button id="issueWizardContinueButton" class="primary" type="button" disabled>Continue</button>
972
+ <button id="issueWizardCopyButton" type="button" hidden>Copy complete issue</button>
973
+ <button id="issueWizardBotButton" type="button" disabled hidden aria-describedby="issueWizardBotHint issueWizardSubmissionStatus">Send</button>
974
+ </menu>
975
+ <p id="issueWizardBotHint" class="issue-wizard-bot-hint muted" hidden>Automated submission is not enabled. Copy the issue and create it manually instead.</p>
976
+ </form>
977
+ </dialog>
978
+
925
979
  <dialog id="piReleaseNotesDialog" class="extension-dialog pi-release-notes-dialog" aria-labelledby="piReleaseNotesTitle">
926
980
  <form method="dialog">
927
981
  <div class="pi-release-notes-header">
@@ -1228,7 +1282,7 @@
1228
1282
  </form>
1229
1283
  </dialog>
1230
1284
 
1231
- <script id="webuiBootLoader" data-app-src="/app.js?v=91">
1285
+ <script id="webuiBootLoader" data-app-src="/app.js?v=92">
1232
1286
  (() => {
1233
1287
  "use strict";
1234
1288
 
@@ -0,0 +1,344 @@
1
+ const DEFAULT_POLL_AFTER_MS = 2_500;
2
+ const MIN_POLL_AFTER_MS = 500;
3
+ const MAX_POLL_AFTER_MS = 10_000;
4
+ const DEFAULT_MAX_POLL_DURATION_MS = 120_000;
5
+ const TURNSTILE_SCRIPT_URL = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
6
+ const TURNSTILE_SCRIPT_ID = "piWebuiIssueBotTurnstile";
7
+ const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
8
+ const SUBMISSION_ID = /^[A-Za-z0-9_-]{22}$/u;
9
+ const STATUS_TOKEN = /^[A-Za-z0-9_-]{43}$/u;
10
+
11
+ export const ISSUE_BOT_PUBLIC_STATUSES = Object.freeze(["queued", "checking", "created", "rejected", "review", "unavailable", "unknown"]);
12
+ export const ISSUE_BOT_SAFE_REASON_CODES = Object.freeze([
13
+ "invalid_submission", "sensitive_content", "rate_limited", "not_accepted", "manual_review", "admission_disabled", "unavailable", "unknown",
14
+ ]);
15
+
16
+ /** This public configuration intentionally contains no credential and is disabled by default. */
17
+ export const ISSUE_BOT_DEFAULT_RUNTIME_CONFIG = Object.freeze({
18
+ enabled: false,
19
+ gatewayBaseUrl: "",
20
+ turnstileSiteKey: "",
21
+ privateSecurityReportUrl: "",
22
+ });
23
+
24
+ function isPlainObject(value) {
25
+ return value !== null && typeof value === "object" && !Array.isArray(value);
26
+ }
27
+
28
+ function exactObject(value, keys) {
29
+ if (!isPlainObject(value)) return false;
30
+ const actual = Object.keys(value).sort();
31
+ const expected = [...keys].sort();
32
+ return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
33
+ }
34
+
35
+ function safeHttpsUrl(value, { allowPath = true } = {}) {
36
+ if (typeof value !== "string" || !value.trim()) return "";
37
+ try {
38
+ const url = new URL(value);
39
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) return "";
40
+ if (!allowPath && url.pathname !== "/") return "";
41
+ return url.href.replace(/\/$/u, "");
42
+ } catch {
43
+ return "";
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Read only an explicit, pre-app-load public configuration object. Query strings,
49
+ * storage, and server credentials are deliberately not configuration channels.
50
+ */
51
+ export function readIssueBotRuntimeConfig(value = globalThis.__PI_WEBUI_ISSUE_BOT_CONFIG__) {
52
+ const source = isPlainObject(value) ? value : ISSUE_BOT_DEFAULT_RUNTIME_CONFIG;
53
+ const gatewayBaseUrl = safeHttpsUrl(source.gatewayBaseUrl);
54
+ const privateSecurityReportUrl = safeHttpsUrl(source.privateSecurityReportUrl);
55
+ const turnstileSiteKey = typeof source.turnstileSiteKey === "string" && /^[A-Za-z0-9_-]{1,2048}$/u.test(source.turnstileSiteKey)
56
+ ? source.turnstileSiteKey
57
+ : "";
58
+ const enabled = source.enabled === true && !!gatewayBaseUrl && !!turnstileSiteKey;
59
+ return Object.freeze({ enabled, gatewayBaseUrl, turnstileSiteKey, privateSecurityReportUrl });
60
+ }
61
+
62
+ function abortError() {
63
+ return new DOMException("Issue bot request aborted.", "AbortError");
64
+ }
65
+
66
+ function throwIfAborted(signal) {
67
+ if (signal?.aborted) throw abortError();
68
+ }
69
+
70
+ function waitForDelay(delayMs, signal) {
71
+ return new Promise((resolve, reject) => {
72
+ throwIfAborted(signal);
73
+ const timer = setTimeout(() => {
74
+ signal?.removeEventListener("abort", onAbort);
75
+ resolve();
76
+ }, delayMs);
77
+ const onAbort = () => {
78
+ clearTimeout(timer);
79
+ reject(abortError());
80
+ };
81
+ signal?.addEventListener("abort", onAbort, { once: true });
82
+ });
83
+ }
84
+
85
+ function safeIssue(issue) {
86
+ if (!isPlainObject(issue) || !isPlainObject(issue.fields)) return null;
87
+ const identifiers = ["categoryId", "componentId", "templateId"];
88
+ const output = {};
89
+ for (const key of identifiers) {
90
+ if (typeof issue[key] !== "string" || !issue[key] || issue[key].length > 128) return null;
91
+ output[key] = issue[key];
92
+ }
93
+ if (typeof issue.summary !== "string" || !issue.summary || issue.summary.length > 160) return null;
94
+ const fields = {};
95
+ for (const [key, value] of Object.entries(issue.fields)) {
96
+ if (!key || key.length > 128 || typeof value !== "string" || !value || value.length > 4_000) return null;
97
+ fields[key] = value;
98
+ }
99
+ return { ...output, summary: issue.summary, fields };
100
+ }
101
+
102
+ function safePollAfterMs(value) {
103
+ return Number.isInteger(value) && value >= MIN_POLL_AFTER_MS && value <= 60_000 ? value : null;
104
+ }
105
+
106
+ function safeSubmissionId(value) {
107
+ return typeof value === "string" && SUBMISSION_ID.test(value) ? value : "";
108
+ }
109
+
110
+ function safeReasonCode(value) {
111
+ return typeof value === "string" && ISSUE_BOT_SAFE_REASON_CODES.includes(value) ? value : "";
112
+ }
113
+
114
+ function safeGithubIssue(value, number) {
115
+ if (!Number.isSafeInteger(number) || number < 1) return "";
116
+ if (typeof value !== "string") return "";
117
+ try {
118
+ const url = new URL(value);
119
+ if (url.protocol !== "https:" || url.hostname !== "github.com" || url.port || url.username || url.password || url.search || url.hash) return "";
120
+ const match = url.pathname.match(/^\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/issues\/([1-9]\d*)$/u);
121
+ if (!match || Number(match[1]) !== number) return "";
122
+ return url.href;
123
+ } catch {
124
+ return "";
125
+ }
126
+ }
127
+
128
+ function parseStatusEnvelope(value, { admission = false } = {}) {
129
+ const extra = admission ? ["statusToken"] : [];
130
+ const inFlightKeys = ["ok", "status", "submissionId", "pollAfterMs", ...extra];
131
+ const createdKeys = ["ok", "status", "submissionId", "issueUrl", "issueNumber", ...extra];
132
+ const terminalKeys = ["ok", "status", "submissionId", "reasonCode", ...extra];
133
+ if (!isPlainObject(value) || value.ok !== true || !safeSubmissionId(value.submissionId)) return null;
134
+ if (admission && (typeof value.statusToken !== "string" || !STATUS_TOKEN.test(value.statusToken))) return null;
135
+ if (value.status === "queued" || value.status === "checking") {
136
+ const pollAfterMs = safePollAfterMs(value.pollAfterMs);
137
+ if (!exactObject(value, inFlightKeys) || pollAfterMs === null) return null;
138
+ return Object.freeze({ ok: true, status: value.status, submissionId: value.submissionId, pollAfterMs });
139
+ }
140
+ if (value.status === "created") {
141
+ const issueUrl = safeGithubIssue(value.issueUrl, value.issueNumber);
142
+ if (!exactObject(value, createdKeys) || !issueUrl) return null;
143
+ return Object.freeze({ ok: true, status: "created", submissionId: value.submissionId, issueUrl, issueNumber: value.issueNumber });
144
+ }
145
+ if (["rejected", "review", "unavailable", "unknown"].includes(value.status)) {
146
+ const reasonCode = safeReasonCode(value.reasonCode);
147
+ if (!exactObject(value, terminalKeys) || !reasonCode) return null;
148
+ return Object.freeze({ ok: true, status: value.status, submissionId: value.submissionId, reasonCode });
149
+ }
150
+ return null;
151
+ }
152
+
153
+ function unavailableResult() {
154
+ return Object.freeze({ ok: false, status: "unavailable", reasonCode: "unavailable" });
155
+ }
156
+
157
+ function isInFlight(result) {
158
+ return result?.status === "queued" || result?.status === "checking";
159
+ }
160
+
161
+ function endpoint(baseUrl, path) {
162
+ return `${baseUrl}${path}`;
163
+ }
164
+
165
+ async function parseJsonResponse(response) {
166
+ if (!response?.ok) return null;
167
+ try { return await response.json(); } catch { return null; }
168
+ }
169
+
170
+ let turnstileApiPromise = null;
171
+
172
+ function loadTurnstileApi(documentRef) {
173
+ if (globalThis.turnstile?.render) return Promise.resolve(globalThis.turnstile);
174
+ if (turnstileApiPromise) return turnstileApiPromise;
175
+ turnstileApiPromise = new Promise((resolve, reject) => {
176
+ const existing = documentRef.getElementById(TURNSTILE_SCRIPT_ID);
177
+ const script = existing || documentRef.createElement("script");
178
+ const finish = () => globalThis.turnstile?.render ? resolve(globalThis.turnstile) : reject(new Error("Turnstile did not initialize."));
179
+ script.addEventListener("load", finish, { once: true });
180
+ script.addEventListener("error", () => reject(new Error("Turnstile failed to load.")), { once: true });
181
+ if (!existing) {
182
+ script.id = TURNSTILE_SCRIPT_ID;
183
+ script.src = TURNSTILE_SCRIPT_URL;
184
+ script.async = true;
185
+ script.defer = true;
186
+ documentRef.head.append(script);
187
+ }
188
+ }).catch((error) => {
189
+ turnstileApiPromise = null;
190
+ throw error;
191
+ });
192
+ return turnstileApiPromise;
193
+ }
194
+
195
+ /** Acquire one non-persisted Turnstile token for the current dialog submission. */
196
+ export async function getIssueBotTurnstileToken({ siteKey, idempotencyKey, container, signal, documentRef = globalThis.document } = {}) {
197
+ throwIfAborted(signal);
198
+ if (!documentRef || !container || typeof siteKey !== "string" || !siteKey || typeof idempotencyKey !== "string" || !UUID_V4.test(idempotencyKey)) {
199
+ throw new Error("Turnstile is unavailable.");
200
+ }
201
+ const api = await loadTurnstileApi(documentRef);
202
+ throwIfAborted(signal);
203
+ return new Promise((resolve, reject) => {
204
+ let widgetId;
205
+ let settled = false;
206
+ const cleanup = () => {
207
+ signal?.removeEventListener("abort", onAbort);
208
+ if (widgetId !== undefined) {
209
+ try { api.remove?.(widgetId); } catch { /* Turnstile cleanup is best effort. */ }
210
+ }
211
+ container.replaceChildren();
212
+ };
213
+ const finish = (callback) => (value) => {
214
+ if (settled) return;
215
+ settled = true;
216
+ cleanup();
217
+ callback(value);
218
+ };
219
+ const onAbort = finish(() => reject(abortError()));
220
+ signal?.addEventListener("abort", onAbort, { once: true });
221
+ try {
222
+ widgetId = api.render(container, {
223
+ sitekey: siteKey,
224
+ action: "issue_bot_submit",
225
+ cData: idempotencyKey,
226
+ size: "invisible",
227
+ callback: finish((token) => typeof token === "string" && token ? resolve(token) : reject(new Error("Turnstile returned no token."))),
228
+ "error-callback": finish(() => reject(new Error("Turnstile verification failed."))),
229
+ "expired-callback": finish(() => reject(new Error("Turnstile token expired."))),
230
+ "timeout-callback": finish(() => reject(new Error("Turnstile timed out."))),
231
+ });
232
+ api.execute?.(widgetId);
233
+ } catch (error) {
234
+ finish(() => reject(error))();
235
+ }
236
+ });
237
+ }
238
+
239
+ /**
240
+ * Dependency-injected browser adapter. It owns network protocol validation and never
241
+ * persists the status capability; callers retain only an opaque in-memory refresh handle.
242
+ */
243
+ export function createIssueBotClient({
244
+ config = readIssueBotRuntimeConfig(),
245
+ fetchImpl = globalThis.fetch?.bind(globalThis),
246
+ getTurnstileToken = getIssueBotTurnstileToken,
247
+ uuidFactory = () => globalThis.crypto?.randomUUID?.(),
248
+ now = () => Date.now(),
249
+ sleep = waitForDelay,
250
+ maxPollDurationMs = DEFAULT_MAX_POLL_DURATION_MS,
251
+ turnstileContainer = null,
252
+ } = {}) {
253
+ const runtimeConfig = readIssueBotRuntimeConfig(config);
254
+ const available = runtimeConfig.enabled && typeof fetchImpl === "function" && typeof getTurnstileToken === "function" && typeof uuidFactory === "function";
255
+
256
+ async function requestAdmission(issue, signal) {
257
+ const idempotencyKey = uuidFactory();
258
+ if (typeof idempotencyKey !== "string" || !UUID_V4.test(idempotencyKey)) return null;
259
+ const turnstileToken = await getTurnstileToken({ siteKey: runtimeConfig.turnstileSiteKey, idempotencyKey, container: turnstileContainer, signal });
260
+ throwIfAborted(signal);
261
+ if (typeof turnstileToken !== "string" || !turnstileToken || turnstileToken.length > 2_048) return null;
262
+ const response = await fetchImpl(endpoint(runtimeConfig.gatewayBaseUrl, "/v1/submissions"), {
263
+ method: "POST",
264
+ mode: "cors",
265
+ credentials: "omit",
266
+ cache: "no-store",
267
+ signal,
268
+ headers: { "content-type": "application/json" },
269
+ body: JSON.stringify({ schemaVersion: 1, idempotencyKey, turnstileToken, issue }),
270
+ });
271
+ const body = await parseJsonResponse(response);
272
+ const envelope = parseStatusEnvelope(body, { admission: true });
273
+ if (!envelope || typeof body?.statusToken !== "string" || !STATUS_TOKEN.test(body.statusToken)) return null;
274
+ return { envelope, statusToken: body.statusToken };
275
+ }
276
+
277
+ async function requestStatus(submissionId, statusToken, signal) {
278
+ const response = await fetchImpl(endpoint(runtimeConfig.gatewayBaseUrl, `/v1/submissions/${submissionId}`), {
279
+ method: "GET",
280
+ mode: "cors",
281
+ credentials: "omit",
282
+ cache: "no-store",
283
+ signal,
284
+ headers: { authorization: `Bearer ${statusToken}` },
285
+ });
286
+ return parseStatusEnvelope(await parseJsonResponse(response));
287
+ }
288
+
289
+ function createRefreshHandle(admission, statusToken) {
290
+ let latest = admission;
291
+ const poll = async ({ signal, onStatus } = {}) => {
292
+ if (!isInFlight(latest)) return latest;
293
+ const startedAt = now();
294
+ let delayMs = latest.pollAfterMs;
295
+ onStatus?.(latest);
296
+ while (isInFlight(latest)) {
297
+ throwIfAborted(signal);
298
+ const elapsed = now() - startedAt;
299
+ if (!Number.isFinite(elapsed) || elapsed >= maxPollDurationMs) return Object.freeze({ ...latest, timedOut: true });
300
+ await sleep(Math.min(delayMs, Math.max(0, maxPollDurationMs - elapsed)), signal);
301
+ throwIfAborted(signal);
302
+ let next;
303
+ try { next = await requestStatus(latest.submissionId, statusToken, signal); } catch (error) {
304
+ if (error?.name === "AbortError") throw error;
305
+ latest = unavailableResult();
306
+ onStatus?.(latest);
307
+ return latest;
308
+ }
309
+ if (!next || next.submissionId !== latest.submissionId) {
310
+ latest = unavailableResult();
311
+ onStatus?.(latest);
312
+ return latest;
313
+ }
314
+ latest = next;
315
+ onStatus?.(latest);
316
+ delayMs = Math.min(MAX_POLL_AFTER_MS, Math.max(delayMs * 2, latest.pollAfterMs || DEFAULT_POLL_AFTER_MS));
317
+ }
318
+ return latest;
319
+ };
320
+ return Object.freeze({ refresh: poll });
321
+ }
322
+
323
+ return Object.freeze({
324
+ available,
325
+ runtimeConfig,
326
+ async submit({ issue, signal, onStatus } = {}) {
327
+ if (!available) return Object.freeze({ result: unavailableResult(), handle: null });
328
+ const structuredIssue = safeIssue(issue);
329
+ if (!structuredIssue) return Object.freeze({ result: unavailableResult(), handle: null });
330
+ let admission;
331
+ try { admission = await requestAdmission(structuredIssue, signal); } catch (error) {
332
+ if (error?.name === "AbortError") throw error;
333
+ return Object.freeze({ result: unavailableResult(), handle: null });
334
+ }
335
+ if (!admission) return Object.freeze({ result: unavailableResult(), handle: null });
336
+ const { envelope, statusToken } = admission;
337
+ onStatus?.(envelope);
338
+ if (!isInFlight(envelope)) return Object.freeze({ result: envelope, handle: null });
339
+ const handle = createRefreshHandle(envelope, statusToken);
340
+ const result = await handle.refresh({ signal, onStatus });
341
+ return Object.freeze({ result, handle });
342
+ },
343
+ });
344
+ }