@spotpatch/vite 1.14.0 → 1.15.0

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.
@@ -1,10 +1,11 @@
1
- var It=Object.freeze({maximumTargets:20,maximumQuestionCharacters:4e3,maximumAnswerCharacters:4e4,maximumAnswerBlocks:40,maximumSources:64,maximumReadFiles:32,maximumReadBytesPerFile:65536,maximumReadBytesTotal:524288,maximumToolCalls:48,maximumModelTurns:12,jobTimeoutMs:3e5,resultTtlMs:9e5,maximumActiveJobsPerSession:1,maximumRetainedResultsPerSession:1,maximumRetainedEvents:256,maximumEventSubscribers:4,eventHeartbeatMs:15e3,maximumRequestBodyBytes:262144,maximumSearchQueryCharacters:256,maximumSearchResults:64,maximumSearchPreviewCharacters:500,capabilityTimeoutMs:3e4,maximumIdCharacters:128,maximumProfileIdCharacters:64,maximumLabelCharacters:256,maximumRelativePathCharacters:1024,maximumLanguageCharacters:64,maximumPhaseMessageCharacters:1024,maximumExecutors:32,contentHashHexCharacters:64}),ke=Object.freeze(["configured-key","managed-codex"]),Pe=Object.freeze(["ready","degraded","unavailable"]),me=Object.freeze(["queued","authorizing","running","cancelling","answered","cancelled","failed"]),De=Object.freeze(["insufficient-evidence","partial-context","source-truncated","source-stale"]),Rt=Object.freeze(["insufficient-evidence","partial-context"]),Ke=Object.freeze(["started","succeeded","failed"]),Me=Object.freeze(["one","few","many"]),Ue=Object.freeze(["exact","probable","approximate"]);var S="/__spotpatch/v1",Ce="X-SpotPatch-Token",ge=Object.freeze({bootstrap:`${S}/bootstrap`,sourceContext:`${S}/source-context`,openEditor:`${S}/open-editor`,dataFlowComponentReport:`${S}/data-flow/component-report`,dataFlowPageReport:`${S}/data-flow/page-report`,agentCapability:`${S}/agent/capability`,agentWorkspaceHealth:`${S}/agent/workspace-health`,agentJobs:`${S}/agent/jobs`,askCapability:`${S}/ask/capability`,askJobs:`${S}/ask/jobs`,externalHandoffCapability:`${S}/external-handoff/capability`,externalHandoffPublish:`${S}/external-handoff/publish`,externalHandoffStatus:`${S}/external-handoff/status`,externalHandoffResolveDelivery:`${S}/external-handoff/resolve-delivery`,externalAgentControlStatus:`${S}/external-agent/control/status`,externalAgentControlConnect:`${S}/external-agent/control/connect`,externalAgentControlDisconnect:`${S}/external-agent/control/disconnect`,externalAgentControlCancel:`${S}/external-agent/control/cancel`,externalAgentEvents:`${S}/external-agent/events`,externalAgentResult:`${S}/external-agent/result`});function he(e,t,o={}){let a=`${ge.askJobs}/${encodeURIComponent(e)}/${t}`;if(t!=="events"&&o.afterSequence!==void 0)throw new RangeError("afterSequence is only valid for the events endpoint.");if(o.afterSequence===void 0)return a;if(!Number.isSafeInteger(o.afterSequence)||o.afterSequence<0)throw new RangeError("afterSequence must be a non-negative safe integer.");return`${a}?afterSequence=${String(o.afterSequence)}`}var Lt={ASK_DISABLED:"ASK_DISABLED",ASK_SELECTION_REQUIRED:"ASK_SELECTION_REQUIRED",ASK_SELECTION_STALE:"ASK_SELECTION_STALE",ASK_QUESTION_INVALID:"ASK_QUESTION_INVALID",ASK_EXECUTOR_UNAVAILABLE:"ASK_EXECUTOR_UNAVAILABLE",ASK_TIMEOUT:"ASK_TIMEOUT",ASK_CONSENT_REQUIRED:"ASK_CONSENT_REQUIRED",ASK_BUSY:"ASK_BUSY",ASK_IDEMPOTENCY_CONFLICT:"ASK_IDEMPOTENCY_CONFLICT",ASK_SOURCE_SCOPE_DENIED:"ASK_SOURCE_SCOPE_DENIED",ASK_LIMIT_EXCEEDED:"ASK_LIMIT_EXCEEDED",ASK_ANSWER_INVALID:"ASK_ANSWER_INVALID",ASK_WRITE_ATTEMPTED:"ASK_WRITE_ATTEMPTED",ASK_CANCELLED:"ASK_CANCELLED",ASK_RESULT_EXPIRED:"ASK_RESULT_EXPIRED",ASK_PROTOCOL_INCOMPATIBLE:"ASK_PROTOCOL_INCOMPATIBLE"},Ot=Object.freeze({INVALID_REQUEST:"INVALID_REQUEST",INVALID_TOKEN:"INVALID_TOKEN",ORIGIN_NOT_ALLOWED:"ORIGIN_NOT_ALLOWED",...Lt,INTERNAL_ERROR:"INTERNAL_ERROR"}),vt=Object.values(Ot);function Se(e){return typeof e=="string"&&vt.includes(e)}function v(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function m(e,t,o=[]){let a=Object.keys(e),f=new Set([...t,...o]);return t.every(r=>r in e)&&a.every(r=>f.has(r))}function H(e,t){return typeof e=="string"&&t.includes(e)}function R(e){return typeof e=="string"&&e.trim().length>0}function J(e){return typeof e=="string"&&e.length>0&&e.length<=128&&/^[A-Za-z0-9_-]+$/u.test(e)}function ie(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))}function Be(e){return Number.isSafeInteger(e)&&Number(e)>0}function je(e){return Se(e)&&e.startsWith("ASK_")}function we(e){return Array.isArray(e)&&e.every(t=>J(t))}function Je(e){return new Set(e).size===e.length}function Nt(e){return!v(e)||!m(e,["executorId","kind","label","requestedModelLabel","effectiveModelLabel","state","providerDataConsentRequired","readOnlyProven"],["errorCode"])||!J(e.executorId)||!H(e.kind,ke)||!R(e.label)||!R(e.requestedModelLabel)||!R(e.effectiveModelLabel)||!H(e.state,Pe)||typeof e.providerDataConsentRequired!="boolean"||typeof e.readOnlyProven!="boolean"||e.errorCode!==void 0&&!je(e.errorCode)?!1:e.state==="ready"?e.readOnlyProven&&e.errorCode===void 0:e.errorCode!==void 0}function it(e){if(!v(e)||!m(e,["schemaVersion","enabled","executors","safety","checkedAt"])||e.schemaVersion!==1||typeof e.enabled!="boolean"||!Array.isArray(e.executors)||!e.executors.every(Nt)||!v(e.safety)||!m(e.safety,["selectionRequired","singleTurn","writesAllowed","historyStored"])||e.safety.selectionRequired!==!0||e.safety.singleTurn!==!0||e.safety.writesAllowed!==!1||e.safety.historyStored!==!1||!ie(e.checkedAt))return!1;let t=e.executors.map(o=>o.executorId);return(e.enabled||e.executors.length===0)&&Je(t)}function ct(e){return v(e)&&m(e,["executorId","kind","label","modelLabel"])&&J(e.executorId)&&H(e.kind,ke)&&R(e.label)&&R(e.modelLabel)}function xe(e){if(!v(e)||!m(e,["schemaVersion","jobId","selectionId","status","executor","createdAt","updatedAt","canCancel"],["phaseMessage","errorCode"])||e.schemaVersion!==1||!J(e.jobId)||!J(e.selectionId)||!H(e.status,me)||!ct(e.executor)||!ie(e.createdAt)||!ie(e.updatedAt)||Date.parse(e.updatedAt)<Date.parse(e.createdAt)||typeof e.canCancel!="boolean"||e.phaseMessage!==void 0&&!R(e.phaseMessage)||e.errorCode!==void 0&&!je(e.errorCode))return!1;let t=["queued","authorizing","running"].includes(e.status);return e.canCancel!==t?!1:e.status==="cancelled"?e.errorCode==="ASK_CANCELLED":e.status==="failed"?e.errorCode!==void 0&&e.errorCode!=="ASK_CANCELLED":e.errorCode===void 0}function rt(e){return!(!v(e)||!m(e,["sourceId","label","relativePath","fileId","startLine","endLine","confidence","targetIds","contentHash"],["sourceVersion"])||!J(e.sourceId)||!R(e.label)||!R(e.relativePath)||e.relativePath.startsWith("/")||e.relativePath.includes("\\")||e.relativePath.split("/").some(t=>t===""||t==="."||t==="..")||!J(e.fileId)||!Be(e.startLine)||!Be(e.endLine)||e.endLine<e.startLine||!H(e.confidence,Ue)||!we(e.targetIds)||e.targetIds.length===0||!Je(e.targetIds)||e.sourceVersion!==void 0&&!R(e.sourceVersion)||typeof e.contentHash!="string"||!/^[a-f0-9]{64}$/u.test(e.contentHash))}function st(e){return v(e)&&m(e,["code"])&&H(e.code,De)}function at(e){return!v(e)||typeof e.kind!="string"?!1:e.kind==="paragraph"?m(e,["kind","text","sourceIds"])&&R(e.text)&&we(e.sourceIds):e.kind==="code"?m(e,["kind","code","sourceIds"],["language"])&&typeof e.code=="string"&&e.code.length>0&&we(e.sourceIds)&&(e.language===void 0||R(e.language)):e.kind!=="list"||!m(e,["kind","items"])?!1:Array.isArray(e.items)&&e.items.length>0&&e.items.every(t=>v(t)&&m(t,["text","sourceIds"])&&R(t.text)&&we(t.sourceIds))}function Pt(e){if(!v(e)||!m(e,["schemaVersion","jobId","selectionId","contextHash","executor","blocks","sources","warnings","createdAt","expiresAt"])||e.schemaVersion!==1||!J(e.jobId)||!J(e.selectionId)||typeof e.contextHash!="string"||!/^[a-f0-9]{64}$/u.test(e.contextHash)||!ct(e.executor)||!Array.isArray(e.blocks)||e.blocks.length===0||!e.blocks.every(at)||!Array.isArray(e.sources)||!e.sources.every(rt)||!Array.isArray(e.warnings)||!e.warnings.every(st)||!ie(e.createdAt)||!ie(e.expiresAt)||Date.parse(e.expiresAt)<=Date.parse(e.createdAt))return!1;let t=e.sources.filter(rt),o=e.blocks.filter(at),a=e.warnings.filter(st),f=t.map(l=>l.sourceId);if(!Je(f))return!1;let r=new Set(f),c=o.flatMap(l=>l.kind==="list"?l.items.flatMap(C=>C.sourceIds):l.sourceIds);return c.every(l=>r.has(l))&&f.every(l=>c.includes(l))&&(c.length>0||a.some(l=>l.code==="insufficient-evidence"))}function dt(e){return!v(e)||!m(e,["snapshot"],["result"])||!xe(e.snapshot)||e.result!==void 0&&!Pt(e.result)?!1:e.snapshot.status==="answered"===(e.result!==void 0)&&(e.result===void 0||e.result.jobId===e.snapshot.jobId&&e.result.selectionId===e.snapshot.selectionId&&e.result.executor.executorId===e.snapshot.executor.executorId)}function lt(e){return!v(e)||!m(e,["schemaVersion","sequence","jobId","status","timestamp","type"],["snapshot","message","activity","state","errorCode"])||e.schemaVersion!==1||!Be(e.sequence)||!J(e.jobId)||!H(e.status,me)||!ie(e.timestamp)?!1:e.type==="snapshot"?m(e,["schemaVersion","sequence","jobId","status","timestamp","type","snapshot"])&&xe(e.snapshot)&&e.snapshot.jobId===e.jobId&&e.snapshot.status===e.status:e.type==="phase"?m(e,["schemaVersion","sequence","jobId","status","timestamp","type","message"])&&R(e.message)&&!["answered","cancelled","failed"].includes(e.status):e.type==="answer-ready"?m(e,["schemaVersion","sequence","jobId","status","timestamp","type"])&&e.status==="answered":e.type==="error"?m(e,["schemaVersion","sequence","jobId","status","timestamp","type","errorCode"])&&je(e.errorCode)&&(e.status==="cancelled"&&e.errorCode==="ASK_CANCELLED"||e.status==="failed"&&e.errorCode!=="ASK_CANCELLED"):e.type!=="read-activity"||!m(e,["schemaVersion","sequence","jobId","status","timestamp","type","activity","state"])||e.status!=="running"||!v(e.activity)||!H(e.state,Ke)?!1:e.activity.kind==="source"?m(e.activity,["kind","sourceId","relativePath"])&&J(e.activity.sourceId)&&R(e.activity.relativePath):e.activity.kind==="file-count"&&m(e.activity,["kind","bucket"])&&H(e.activity.bucket,Me)}var Dt=2e6,ut=1e5,Kt=4e6,k=class extends Error{constructor(o){super("SpotPatch Contextual Ask request failed.");this.code=o;this.name="ContextualAskApiError"}code};function qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ft(e){if(!(!qe(e)&&!Array.isArray(e)||Object.isFrozen(e))){for(let t of Object.values(e))ft(t);Object.freeze(e)}}function Ae(e){return ft(e),e}function gt(e){try{return JSON.parse(e)}catch{throw new k}}async function Mt(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw await e.body?.cancel(),new k;if(e.body===null)throw new k;let a=e.body.getReader(),f=new TextDecoder("utf-8",{fatal:!0}),r=0,c="";try{for(;;){let l=await a.read();if(l.done)return c+f.decode();if(r+=l.value.byteLength,r>t)throw await a.cancel(),new k;c+=f.decode(l.value,{stream:!0})}}catch(l){throw l instanceof k||l instanceof DOMException&&l.name==="AbortError"?l:new k}finally{a.releaseLock()}}async function pt(e){let t=gt(await Mt(e,Dt));if(!qe(t))throw new k;if(!e.ok){let o=t.ok===!1&&qe(t.error)&&Se(t.error.code)?t.error.code:void 0;throw new k(o)}if(t.ok!==!0||!("data"in t))throw new k;return t.data}function Te(e){return e instanceof k?e.code:void 0}function ht(e){let t=new Set;function o(){for(let r of t)r.abort();t.clear()}async function a(r,c,l){let C=new AbortController;t.add(C);try{let L=await e.fetch(r,{method:c,headers:{...l===void 0?{}:{"Content-Type":"application/json"},[Ce]:e.sessionToken},...l===void 0?{}:{body:JSON.stringify(l)},signal:C.signal});return await pt(L)}finally{t.delete(C)}}async function f(r,c,l){let C=new AbortController;t.add(C);try{let L=await e.fetch(he(r,"events",{afterSequence:c}),{method:"GET",headers:{[Ce]:e.sessionToken},signal:C.signal});if(!L.ok){await pt(L);return}if(L.body===null)throw new k;let w=L.body.getReader(),b=new TextDecoder("utf-8",{fatal:!0}),D="",K=0,q=c,M=E=>{if(E.trim().length===0)return;if(new TextEncoder().encode(E).byteLength>ut)throw new k;let I=gt(E);if(!lt(I)||I.jobId!==r||I.sequence<=q)throw new k;q=I.sequence,l(Ae(I))};try{for(;;){let E=await w.read();if(E.done){M(D+b.decode());return}if(K+=E.value.byteLength,K>Kt)throw await w.cancel(),new k;D+=b.decode(E.value,{stream:!0});let I=D.split(`
2
- `);if(D=I.pop()??"",new TextEncoder().encode(D).byteLength>ut)throw await w.cancel(),new k;for(let G of I)M(G)}}catch(E){throw E instanceof k||E instanceof DOMException&&E.name==="AbortError"?E:new k}finally{w.releaseLock()}}finally{t.delete(C)}}return Object.freeze({async capability(){let r=await a(ge.askCapability,"GET");if(!it(r))throw new k;return Ae(r)},async cancelJob(r){let c=await a(he(r,"cancel"),"POST",{});if(!xe(c)||c.jobId!==r)throw new k;return Ae(c)},cancelPending:o,async createJob(r){let c=await a(ge.askJobs,"POST",r);if(!xe(c)||c.selectionId!==r.envelope.selection.selectionId||c.executor.executorId!==r.executorId)throw new k;return Ae(c)},dispose:o,events:f,async result(r){let c=await a(he(r,"result"),"GET");if(!dt(c)||c.snapshot.jobId!==r)throw new k;return Ae(c)}})}function $e(e){return e instanceof DOMException&&e.name==="AbortError"}function xt(e){let t=!1,o=0,a=!1,f,r,c="",l=!1,C=!1,L=new Map,w=e.api??ht({fetch:e.fetch,sessionToken:e.sessionToken});function b(i){return t&&o===i}function D(i){let x=e.getSelection();if(i.length===0||i.length>4e3||x===void 0)return;let g=new Date().toISOString();return{schemaVersion:1,taskId:e.createId(),selection:{schemaVersion:1,selectionId:e.createId(),locale:x.locale,targets:x.targets.map(h=>({targetId:h.id,page:h.page,source:h.source,react:{...h.react,componentStack:[...h.react.componentStack]},element:h.element,styles:{...h.styles,classNames:[...h.styles.classNames],matchedRules:h.styles.matchedRules.map(O=>({...O})),computed:{...h.styles.computed},warnings:[...h.styles.warnings]},...h.code===void 0?{}:{code:h.code},warnings:[]})),createdAt:g},task:{kind:"ask",question:i},createdAt:g}}async function K(){if(l)return;let i=o;e.panel.renderCapability(void 0);try{let x=await w.capability();if(!b(i))return;l=!0,e.panel.renderCapability(x);let g=e.panel.readExecutorId();e.panel.setConsent(g!==void 0&&L.get(g)===!0)}catch(x){if(!b(i)||$e(x))return;e.panel.renderError(Te(x))}}function q(i,x){b(x)&&(e.panel.renderEvent(i),i.type==="snapshot"&&(f=i.snapshot))}async function M(){if(a)return;let i=e.panel.readQuestion(),x=e.panel.readExecutorId(),g=D(i);if(i.length===0||x===void 0||!e.panel.readConsent()||g===void 0)return;let h=++o;c=i,a=!0,e.onBusyChange(!0),r=void 0,f=void 0,e.panel.setBusy(!0);try{let O=await w.createJob({schemaVersion:1,requestId:e.createId(),envelope:g,executorId:x,providerDataConsent:!0});if(!b(h)||(f=O,e.panel.renderJob(O),await w.events(O.jobId,0,le=>{q(le,h)}),!b(h)))return;let U=await w.result(O.jobId);if(!b(h))return;if(f=U.snapshot,a=!1,e.onBusyChange(!1),U.result===void 0){e.panel.renderJob(U.snapshot),U.snapshot.status==="failed"&&e.panel.renderError(U.snapshot.errorCode);return}r=U.result,e.panel.renderAnswer(U.result,!1)}catch(O){if(!b(h)||$e(O))return;a=!1,e.onBusyChange(!1),e.panel.renderError(Te(O))}finally{b(h)&&(a=!1,e.panel.setBusy(!1))}}async function E(){if(!a||f?.canCancel!==!0)return;let i=o;try{let x=await w.cancelJob(f.jobId);if(!b(i))return;f=x,a=!1,e.onBusyChange(!1),e.panel.renderJob(x),e.panel.setBusy(!1)}catch(x){if(!b(i)||$e(x))return;a=!1,e.onBusyChange(!1),e.panel.renderError(Te(x))}}function I(){o+=1;let i=f;a=!1,e.onBusyChange(!1),f=void 0,w.cancelPending(),i?.canCancel===!0&&w.cancelJob(i.jobId).catch(()=>{}),e.panel.setBusy(!1)}function G(){a&&I(),o+=1,f=void 0,r=void 0,c="",e.panel.clear(),e.panel.focusQuestion()}function Y(){let i=e.panel.answerPlainText();i.length===0||e.clipboard===void 0||e.clipboard.writeText(i).then(()=>{e.panel.notify("copied")}).catch(()=>{e.panel.notify("copy-failed")})}function oe(){if(r===void 0||a)return;let i=e.panel.answerPlainText().trim().slice(0,4e3);if(i.length===0)return;let x=Object.freeze({kind:"contextual-ask",askJobId:r.jobId,question:c,answerDigest:i,sourceIds:r.sources.map(g=>g.sourceId)});e.onConvert(x),e.panel.setOrigin(x),e.panel.setMode("change"),e.panel.notify("converted")}function re(i){let x=e.panel.selectedSourceId(i.target);if(x===void 0)return;let g=e.panel.sourceById(x);g!==void 0&&e.onOpenSource(g).catch(()=>{e.panel.notify("source-open-failed")})}function ce(i){i.target!==e.panel.questionInput||i.key!=="Enter"||C||i.isComposing||!i.metaKey&&!i.ctrlKey||(i.preventDefault(),M())}function _(){let i=e.panel.readExecutorId();e.panel.setConsent(i!==void 0&&L.get(i)===!0)}function $(){C=!0}function se(){C=!1}function ae(){let i=e.panel.readExecutorId();i!==void 0&&L.set(i,e.panel.readConsent())}function V(){M()}function T(){E()}function y(){t||(t=!0,e.panel.submitButton.addEventListener("click",V),e.panel.cancelButton.addEventListener("click",T),e.panel.newQuestionButton.addEventListener("click",G),e.panel.copyButton.addEventListener("click",Y),e.panel.convertButton.addEventListener("click",oe),e.panel.executorSelect.addEventListener("change",_),e.panel.consentCheckbox.addEventListener("change",ae),e.panel.questionInput.addEventListener("keydown",ce),e.panel.questionInput.addEventListener("compositionstart",$),e.panel.questionInput.addEventListener("compositionend",se),e.panel.root.addEventListener("click",re),K())}function de(){t&&(I(),t=!1,e.panel.submitButton.removeEventListener("click",V),e.panel.cancelButton.removeEventListener("click",T),e.panel.newQuestionButton.removeEventListener("click",G),e.panel.copyButton.removeEventListener("click",Y),e.panel.convertButton.removeEventListener("click",oe),e.panel.executorSelect.removeEventListener("change",_),e.panel.consentCheckbox.removeEventListener("change",ae),e.panel.questionInput.removeEventListener("keydown",ce),e.panel.questionInput.removeEventListener("compositionstart",$),e.panel.questionInput.removeEventListener("compositionend",se),e.panel.root.removeEventListener("click",re),w.dispose())}return Object.freeze({beginSelection(){o+=1,a=!1,e.onBusyChange(!1),f=void 0,r=void 0,c="",e.panel.clear(),K()},cancelPending:I,dispose:de,isBusy:()=>a,mount:y,selectionChanged(){r!==void 0&&e.panel.renderAnswer(r,!0)}})}var Ut=Symbol.for("spotpatch.contextual-ask.v1");function At(e){globalThis[Ut]=e}var bt="data-spotpatch-ui",nn=Object.freeze({highlight:2147483646,controls:2147483647}),on=Object.freeze({compactInset:8,compactViewportWidth:520,desktopInset:24,dragActivationDistance:6,edgeSnapDistance:20,workbenchMaxHeight:620,workbenchMaxWidth:460});function s(e,t){let o=e.createElement(t);return o.setAttribute(bt,""),o}function N(e,t,o=""){let a=s(e,"button");return a.type="button",a.className=o,a.textContent=t,a}var Bt=Object.freeze({mode:Object.freeze({ask:"Ask",change:"Change",label:"Task mode"}),title:"Ask about this selection",subtitle:"One question, one sourced answer. SpotPatch will not write code.",questionLabel:"Question",questionPlaceholder:"What does this component do?",suggestionsLabel:"Suggested questions",suggestions:Object.freeze(["What does this component do?","Where does its data come from?","Why is it implemented this way?"]),executorLabel:"Read-only executor",loadingExecutors:"Checking available executors…",noExecutor:"No verified read-only executor is available.",unavailable:"unavailable",consent:"Allow the selected source snapshot to be sent to this provider for this answer.",dataSummary:(e,t)=>`${String(e)} selected element${e===1?"":"s"} · ${String(t)} source-backed`,safety:"Single turn · read-only · no history",submit:"Ask",cancel:"Cancel",newQuestion:"Start over",copy:"Copy answer",convert:"Turn into change request",answerTitle:"Answer",sourcesTitle:"Sources",stale:"The selection changed after this answer. Ask again before relying on it.",convertedTitle:"From contextual answer",convertedBody:"The answer and source references remain local and have not started a change.",status:Object.freeze({queued:"Queued",authorizing:"Verifying read-only access",running:"Analyzing selected source",cancelling:"Cancelling",answered:"Answer ready",cancelled:"Cancelled",failed:"Could not answer"}),sourceLabel:(e,t,o)=>`${e}:${String(t)}${o===t?"":`–${String(o)}`}`,readSource:e=>`Reading ${e}`,readFiles:e=>`Reading ${e} files`,copied:"Answer copied.",copyFailed:"The answer could not be copied.",sourceOpenFailed:"The source could not be opened.",converted:"Switched to Change with the answer attached as local context.",error:e=>e===void 0?"SpotPatch could not complete this question.":{INVALID_TOKEN:"The local SpotPatch session expired. Refresh the page.",ORIGIN_NOT_ALLOWED:"The local request failed its same-origin security check. Refresh or restart the dev server.",ASK_DISABLED:"Contextual Ask is disabled.",ASK_SELECTION_REQUIRED:"Select at least one element first.",ASK_SELECTION_STALE:"The selected source changed. Refresh the selection and ask again.",ASK_QUESTION_INVALID:"Enter one valid question.",ASK_EXECUTOR_UNAVAILABLE:"The selected read-only executor is unavailable.",ASK_TIMEOUT:"The read-only executor took too long to answer. Try the question again.",ASK_CONSENT_REQUIRED:"Confirm provider data access for this answer.",ASK_BUSY:"Another workspace task is active. Try again when it finishes.",ASK_CANCELLED:"The question was cancelled.",ASK_RESULT_EXPIRED:"This answer has expired. Ask again.",ASK_WRITE_ATTEMPTED:"The executor attempted a write and was stopped.",ASK_ANSWER_INVALID:"The executor returned an invalid sourced answer.",ASK_PROTOCOL_INCOMPATIBLE:"The executor protocol is incompatible.",ASK_LIMIT_EXCEEDED:"The selected context is too large.",ASK_SOURCE_SCOPE_DENIED:"A requested source was outside the granted snapshot."}[e]??"SpotPatch could not complete this question.",warning:e=>e==="insufficient-evidence"?"The selected source did not contain enough evidence for a complete answer.":"Some source references were omitted because they could not be verified."}),jt=Object.freeze({mode:Object.freeze({ask:"问答",change:"修改",label:"任务模式"}),title:"询问所选元素",subtitle:"一次提问,一次带源码引用的回答;SpotPatch 不会写入代码。",questionLabel:"问题",questionPlaceholder:"这个组件是做什么的?",suggestionsLabel:"推荐问题",suggestions:Object.freeze(["这个组件是做什么的?","它的数据从哪里来?","为什么要这样实现?"]),executorLabel:"只读执行器",loadingExecutors:"正在检查可用执行器…",noExecutor:"目前没有通过只读验证的执行器。",unavailable:"不可用",consent:"允许本次回答将所选源码快照发送给该提供商。",dataSummary:(e,t)=>`${String(e)} 个已选元素 · ${String(t)} 个具备源码上下文`,safety:"单轮 · 只读 · 不保存历史",submit:"提问",cancel:"取消",newQuestion:"重新开始",copy:"复制回答",convert:"转成修改请求",answerTitle:"回答",sourcesTitle:"源码引用",stale:"回答后选择已发生变化。请重新提问后再采信此回答。",convertedTitle:"来自上下文问答",convertedBody:"回答与源码引用仅作为本地上下文保留,尚未发起任何修改。",status:Object.freeze({queued:"已排队",authorizing:"正在验证只读权限",running:"正在分析所选源码",cancelling:"正在取消",answered:"回答已就绪",cancelled:"已取消",failed:"无法回答"}),sourceLabel:(e,t,o)=>`${e}:${String(t)}${o===t?"":`–${String(o)}`}`,readSource:e=>`正在读取 ${e}`,readFiles:e=>`正在读取 ${e} 个文件`,copied:"回答已复制。",copyFailed:"无法复制回答。",sourceOpenFailed:"无法打开源码。",converted:"已切换到修改模式,并把回答作为本地上下文附带。",error:e=>e===void 0?"SpotPatch 未能完成本次提问。":{INVALID_TOKEN:"本地 SpotPatch 会话已失效,请刷新页面。",ORIGIN_NOT_ALLOWED:"本地请求未通过同源安全校验,请刷新页面或重启开发服务。",ASK_DISABLED:"上下文问答未启用。",ASK_SELECTION_REQUIRED:"请先选择至少一个元素。",ASK_SELECTION_STALE:"所选源码已经变化,请刷新选择后重新提问。",ASK_QUESTION_INVALID:"请输入一个有效的问题。",ASK_EXECUTOR_UNAVAILABLE:"所选只读执行器当前不可用。",ASK_TIMEOUT:"只读执行器未能在限定时间内返回回答,请重新提问。",ASK_CONSENT_REQUIRED:"请确认本次回答的提供商数据访问。",ASK_BUSY:"工作区正在执行其他任务,请稍后重试。",ASK_CANCELLED:"本次提问已取消。",ASK_RESULT_EXPIRED:"回答已过期,请重新提问。",ASK_WRITE_ATTEMPTED:"执行器尝试写入,已被阻止。",ASK_ANSWER_INVALID:"执行器返回的带引用回答无效。",ASK_PROTOCOL_INCOMPATIBLE:"执行器协议不兼容。",ASK_LIMIT_EXCEEDED:"所选上下文过大。",ASK_SOURCE_SCOPE_DENIED:"请求的源码超出了授权快照范围。"}[e]??"SpotPatch 未能完成本次提问。",warning:e=>e==="insufficient-evidence"?"所选源码不足以支持完整回答。":"部分源码引用因无法验证而被省略。"});function Ve(e){return e==="zh-CN"?jt:Bt}function Jt(e){let t=e.createElement("style");return t.textContent=`
1
+ var ye=Object.freeze({maximumTargets:20,maximumQuestionCharacters:4e3,maximumAnswerCharacters:4e4,maximumAnswerBlocks:40,maximumSources:64,maximumReadFiles:32,maximumReadBytesPerFile:65536,maximumReadBytesTotal:524288,maximumToolCalls:48,maximumModelTurns:12,jobTimeoutMs:3e5,resultTtlMs:9e5,maximumActiveJobsPerSession:1,maximumRetainedResultsPerSession:1,maximumRetainedEvents:256,maximumEventSubscribers:4,eventHeartbeatMs:15e3,maximumRequestBodyBytes:262144,maximumSearchQueryCharacters:256,maximumSearchResults:64,maximumSearchPreviewCharacters:500,capabilityTimeoutMs:3e4,maximumIdCharacters:128,maximumProfileIdCharacters:64,maximumLabelCharacters:256,maximumRelativePathCharacters:1024,maximumLanguageCharacters:64,maximumPhaseMessageCharacters:1024,maximumExecutors:32,maximumModels:800,contentHashHexCharacters:64}),ke=Object.freeze(["configured-key","managed-codex"]),Ke=Object.freeze(["ready","degraded","unavailable"]),Ee=Object.freeze(["queued","authorizing","running","cancelling","answered","cancelled","failed"]),Me=Object.freeze(["insufficient-evidence","partial-context","source-truncated","source-stale"]),wt=Object.freeze(["insufficient-evidence","partial-context"]),Ue=Object.freeze(["started","succeeded","failed"]),Be=Object.freeze(["one","few","many"]),je=Object.freeze(["exact","probable","approximate"]);var _="/__spotpatch/v1",Ce="X-SpotPatch-Token",fe=Object.freeze({bootstrap:`${_}/bootstrap`,sourceContext:`${_}/source-context`,openEditor:`${_}/open-editor`,dataFlowComponentReport:`${_}/data-flow/component-report`,dataFlowPageReport:`${_}/data-flow/page-report`,agentCapability:`${_}/agent/capability`,agentWorkspaceHealth:`${_}/agent/workspace-health`,agentJobs:`${_}/agent/jobs`,askCapability:`${_}/ask/capability`,askJobs:`${_}/ask/jobs`,externalHandoffCapability:`${_}/external-handoff/capability`,externalHandoffPublish:`${_}/external-handoff/publish`,externalHandoffStatus:`${_}/external-handoff/status`,externalHandoffResolveDelivery:`${_}/external-handoff/resolve-delivery`,externalAgentControlStatus:`${_}/external-agent/control/status`,externalAgentControlConnect:`${_}/external-agent/control/connect`,externalAgentControlDisconnect:`${_}/external-agent/control/disconnect`,externalAgentControlCancel:`${_}/external-agent/control/cancel`,externalAgentEvents:`${_}/external-agent/events`,externalAgentResult:`${_}/external-agent/result`});function ge(e,t,n={}){let s=`${fe.askJobs}/${encodeURIComponent(e)}/${t}`;if(t!=="events"&&n.afterSequence!==void 0)throw new RangeError("afterSequence is only valid for the events endpoint.");if(n.afterSequence===void 0)return s;if(!Number.isSafeInteger(n.afterSequence)||n.afterSequence<0)throw new RangeError("afterSequence must be a non-negative safe integer.");return`${s}?afterSequence=${String(n.afterSequence)}`}var Tt={ASK_DISABLED:"ASK_DISABLED",ASK_SELECTION_REQUIRED:"ASK_SELECTION_REQUIRED",ASK_SELECTION_STALE:"ASK_SELECTION_STALE",ASK_QUESTION_INVALID:"ASK_QUESTION_INVALID",ASK_EXECUTOR_UNAVAILABLE:"ASK_EXECUTOR_UNAVAILABLE",ASK_TIMEOUT:"ASK_TIMEOUT",ASK_CONSENT_REQUIRED:"ASK_CONSENT_REQUIRED",ASK_BUSY:"ASK_BUSY",ASK_IDEMPOTENCY_CONFLICT:"ASK_IDEMPOTENCY_CONFLICT",ASK_SOURCE_SCOPE_DENIED:"ASK_SOURCE_SCOPE_DENIED",ASK_LIMIT_EXCEEDED:"ASK_LIMIT_EXCEEDED",ASK_ANSWER_INVALID:"ASK_ANSWER_INVALID",ASK_WRITE_ATTEMPTED:"ASK_WRITE_ATTEMPTED",ASK_CANCELLED:"ASK_CANCELLED",ASK_RESULT_EXPIRED:"ASK_RESULT_EXPIRED",ASK_PROTOCOL_INCOMPATIBLE:"ASK_PROTOCOL_INCOMPATIBLE"},_t=Object.freeze({INVALID_REQUEST:"INVALID_REQUEST",INVALID_TOKEN:"INVALID_TOKEN",ORIGIN_NOT_ALLOWED:"ORIGIN_NOT_ALLOWED",...Tt,INTERNAL_ERROR:"INTERNAL_ERROR"}),It=Object.values(_t);function Se(e){return typeof e=="string"&&It.includes(e)}function D(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function T(e,t,n=[]){let s=Object.keys(e),g=new Set([...t,...n]);return t.every(r=>r in e)&&s.every(r=>g.has(r))}function H(e,t){return typeof e=="string"&&t.includes(e)}function L(e){return typeof e=="string"&&e.trim().length>0}function J(e){return typeof e=="string"&&e.length>0&&e.length<=128&&/^[A-Za-z0-9_-]+$/u.test(e)}function ae(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))}function Je(e){return Number.isSafeInteger(e)&&Number(e)>0}function qe(e){return Se(e)&&e.startsWith("ASK_")}function we(e){return Array.isArray(e)&&e.every(t=>J(t))}function Te(e){return new Set(e).size===e.length}function vt(e){return!D(e)||!T(e,["executorId","kind","label","requestedModelLabel","effectiveModelLabel","state","providerDataConsentRequired","readOnlyProven"],["errorCode","models"])||!J(e.executorId)||!H(e.kind,ke)||!L(e.label)||!L(e.requestedModelLabel)||!L(e.effectiveModelLabel)||e.models!==void 0&&(!Array.isArray(e.models)||e.models.length===0||e.models.length>ye.maximumModels||!e.models.every(t=>L(t)&&t.length<=ye.maximumLabelCharacters)||!Te(e.models))||!H(e.state,Ke)||typeof e.providerDataConsentRequired!="boolean"||typeof e.readOnlyProven!="boolean"||e.errorCode!==void 0&&!qe(e.errorCode)?!1:e.state==="ready"?e.readOnlyProven&&e.errorCode===void 0:e.errorCode!==void 0}function st(e){if(!D(e)||!T(e,["schemaVersion","enabled","executors","safety","checkedAt"])||e.schemaVersion!==1||typeof e.enabled!="boolean"||!Array.isArray(e.executors)||!e.executors.every(vt)||!D(e.safety)||!T(e.safety,["selectionRequired","singleTurn","writesAllowed","historyStored"])||e.safety.selectionRequired!==!0||e.safety.singleTurn!==!0||e.safety.writesAllowed!==!1||e.safety.historyStored!==!1||!ae(e.checkedAt))return!1;let t=e.executors.map(n=>n.executorId);return(e.enabled||e.executors.length===0)&&Te(t)}function at(e){return D(e)&&T(e,["executorId","kind","label","modelLabel"])&&J(e.executorId)&&H(e.kind,ke)&&L(e.label)&&L(e.modelLabel)}function he(e){if(!D(e)||!T(e,["schemaVersion","jobId","selectionId","status","executor","createdAt","updatedAt","canCancel"],["phaseMessage","errorCode"])||e.schemaVersion!==1||!J(e.jobId)||!J(e.selectionId)||!H(e.status,Ee)||!at(e.executor)||!ae(e.createdAt)||!ae(e.updatedAt)||Date.parse(e.updatedAt)<Date.parse(e.createdAt)||typeof e.canCancel!="boolean"||e.phaseMessage!==void 0&&!L(e.phaseMessage)||e.errorCode!==void 0&&!qe(e.errorCode))return!1;let t=["queued","authorizing","running"].includes(e.status);return e.canCancel!==t?!1:e.status==="cancelled"?e.errorCode==="ASK_CANCELLED":e.status==="failed"?e.errorCode!==void 0&&e.errorCode!=="ASK_CANCELLED":e.errorCode===void 0}function nt(e){return!(!D(e)||!T(e,["sourceId","label","relativePath","fileId","startLine","endLine","confidence","targetIds","contentHash"],["sourceVersion"])||!J(e.sourceId)||!L(e.label)||!L(e.relativePath)||e.relativePath.startsWith("/")||e.relativePath.includes("\\")||e.relativePath.split("/").some(t=>t===""||t==="."||t==="..")||!J(e.fileId)||!Je(e.startLine)||!Je(e.endLine)||e.endLine<e.startLine||!H(e.confidence,je)||!we(e.targetIds)||e.targetIds.length===0||!Te(e.targetIds)||e.sourceVersion!==void 0&&!L(e.sourceVersion)||typeof e.contentHash!="string"||!/^[a-f0-9]{64}$/u.test(e.contentHash))}function ot(e){return D(e)&&T(e,["code"])&&H(e.code,Me)}function rt(e){return!D(e)||typeof e.kind!="string"?!1:e.kind==="paragraph"?T(e,["kind","text","sourceIds"])&&L(e.text)&&we(e.sourceIds):e.kind==="code"?T(e,["kind","code","sourceIds"],["language"])&&typeof e.code=="string"&&e.code.length>0&&we(e.sourceIds)&&(e.language===void 0||L(e.language)):e.kind!=="list"||!T(e,["kind","items"])?!1:Array.isArray(e.items)&&e.items.length>0&&e.items.every(t=>D(t)&&T(t,["text","sourceIds"])&&L(t.text)&&we(t.sourceIds))}function Rt(e){if(!D(e)||!T(e,["schemaVersion","jobId","selectionId","contextHash","executor","blocks","sources","warnings","createdAt","expiresAt"])||e.schemaVersion!==1||!J(e.jobId)||!J(e.selectionId)||typeof e.contextHash!="string"||!/^[a-f0-9]{64}$/u.test(e.contextHash)||!at(e.executor)||!Array.isArray(e.blocks)||e.blocks.length===0||!e.blocks.every(rt)||!Array.isArray(e.sources)||!e.sources.every(nt)||!Array.isArray(e.warnings)||!e.warnings.every(ot)||!ae(e.createdAt)||!ae(e.expiresAt)||Date.parse(e.expiresAt)<=Date.parse(e.createdAt))return!1;let t=e.sources.filter(nt),n=e.blocks.filter(rt),s=e.warnings.filter(ot),g=t.map(d=>d.sourceId);if(!Te(g))return!1;let r=new Set(g),a=n.flatMap(d=>d.kind==="list"?d.items.flatMap(k=>k.sourceIds):d.sourceIds);return a.every(d=>r.has(d))&&g.every(d=>a.includes(d))&&(a.length>0||s.some(d=>d.code==="insufficient-evidence"))}function it(e){return!D(e)||!T(e,["snapshot"],["result"])||!he(e.snapshot)||e.result!==void 0&&!Rt(e.result)?!1:e.snapshot.status==="answered"===(e.result!==void 0)&&(e.result===void 0||e.result.jobId===e.snapshot.jobId&&e.result.selectionId===e.snapshot.selectionId&&e.result.executor.executorId===e.snapshot.executor.executorId)}function ct(e){return!D(e)||!T(e,["schemaVersion","sequence","jobId","status","timestamp","type"],["snapshot","message","activity","state","errorCode"])||e.schemaVersion!==1||!Je(e.sequence)||!J(e.jobId)||!H(e.status,Ee)||!ae(e.timestamp)?!1:e.type==="snapshot"?T(e,["schemaVersion","sequence","jobId","status","timestamp","type","snapshot"])&&he(e.snapshot)&&e.snapshot.jobId===e.jobId&&e.snapshot.status===e.status:e.type==="phase"?T(e,["schemaVersion","sequence","jobId","status","timestamp","type","message"])&&L(e.message)&&!["answered","cancelled","failed"].includes(e.status):e.type==="answer-ready"?T(e,["schemaVersion","sequence","jobId","status","timestamp","type"])&&e.status==="answered":e.type==="error"?T(e,["schemaVersion","sequence","jobId","status","timestamp","type","errorCode"])&&qe(e.errorCode)&&(e.status==="cancelled"&&e.errorCode==="ASK_CANCELLED"||e.status==="failed"&&e.errorCode!=="ASK_CANCELLED"):e.type!=="read-activity"||!T(e,["schemaVersion","sequence","jobId","status","timestamp","type","activity","state"])||e.status!=="running"||!D(e.activity)||!H(e.state,Ue)?!1:e.activity.kind==="source"?T(e.activity,["kind","sourceId","relativePath"])&&J(e.activity.sourceId)&&L(e.activity.relativePath):e.activity.kind==="file-count"&&T(e.activity,["kind","bucket"])&&H(e.activity.bucket,Be)}var Lt=2e6,dt=1e5,Ot=4e6,S=class extends Error{constructor(n){super("SpotPatch Contextual Ask request failed.");this.code=n;this.name="ContextualAskApiError"}code};function $e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pt(e){if(!(!$e(e)&&!Array.isArray(e)||Object.isFrozen(e))){for(let t of Object.values(e))pt(t);Object.freeze(e)}}function be(e){return pt(e),e}function ut(e){try{return JSON.parse(e)}catch{throw new S}}async function Nt(e,t){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>t)throw await e.body?.cancel(),new S;if(e.body===null)throw new S;let s=e.body.getReader(),g=new TextDecoder("utf-8",{fatal:!0}),r=0,a="";try{for(;;){let d=await s.read();if(d.done)return a+g.decode();if(r+=d.value.byteLength,r>t)throw await s.cancel(),new S;a+=g.decode(d.value,{stream:!0})}}catch(d){throw d instanceof S||d instanceof DOMException&&d.name==="AbortError"?d:new S}finally{s.releaseLock()}}async function lt(e){let t=ut(await Nt(e,Lt));if(!$e(t))throw new S;if(!e.ok){let n=t.ok===!1&&$e(t.error)&&Se(t.error.code)?t.error.code:void 0;throw new S(n)}if(t.ok!==!0||!("data"in t))throw new S;return t.data}function _e(e){return e instanceof S?e.code:void 0}function ft(e){let t=new Set;function n(){for(let r of t)r.abort();t.clear()}async function s(r,a,d){let k=new AbortController;t.add(k);try{let v=await e.fetch(r,{method:a,headers:{...d===void 0?{}:{"Content-Type":"application/json"},[Ce]:e.sessionToken},...d===void 0?{}:{body:JSON.stringify(d)},signal:k.signal});return await lt(v)}finally{t.delete(k)}}async function g(r,a,d){let k=new AbortController;t.add(k);try{let v=await e.fetch(ge(r,"events",{afterSequence:a}),{method:"GET",headers:{[Ce]:e.sessionToken},signal:k.signal});if(!v.ok){await lt(v);return}if(v.body===null)throw new S;let E=v.body.getReader(),b=new TextDecoder("utf-8",{fatal:!0}),P="",O=0,l=a,m=u=>{if(u.trim().length===0)return;if(new TextEncoder().encode(u).byteLength>dt)throw new S;let A=ut(u);if(!ct(A)||A.jobId!==r||A.sequence<=l)throw new S;l=A.sequence,d(be(A))};try{for(;;){let u=await E.read();if(u.done){m(P+b.decode());return}if(O+=u.value.byteLength,O>Ot)throw await E.cancel(),new S;P+=b.decode(u.value,{stream:!0});let A=P.split(`
2
+ `);if(P=A.pop()??"",new TextEncoder().encode(P).byteLength>dt)throw await E.cancel(),new S;for(let N of A)m(N)}}catch(u){throw u instanceof S||u instanceof DOMException&&u.name==="AbortError"?u:new S}finally{E.releaseLock()}}finally{t.delete(k)}}return Object.freeze({async capability(){let r=await s(fe.askCapability,"GET");if(!st(r))throw new S;return be(r)},async cancelJob(r){let a=await s(ge(r,"cancel"),"POST",{});if(!he(a)||a.jobId!==r)throw new S;return be(a)},cancelPending:n,async createJob(r){let a=await s(fe.askJobs,"POST",r);if(!he(a)||a.selectionId!==r.envelope.selection.selectionId||a.executor.executorId!==r.executorId)throw new S;return be(a)},dispose:n,events:g,async result(r){let a=await s(ge(r,"result"),"GET");if(!it(a)||a.snapshot.jobId!==r)throw new S;return be(a)}})}function Ve(e){return e instanceof DOMException&&e.name==="AbortError"}function gt(e){let t=!1,n=0,s=!1,g,r,a="",d=!1,k=!1,v=new Map,E=e.api??ft({fetch:e.fetch,sessionToken:e.sessionToken});function b(i){return t&&n===i}function P(i){let x=e.getSelection();if(i.length===0||i.length>4e3||x===void 0)return;let w=new Date().toISOString();return{schemaVersion:1,taskId:e.createId(),selection:{schemaVersion:1,selectionId:e.createId(),locale:x.locale,targets:x.targets.map(y=>({targetId:y.id,page:y.page,source:y.source,react:{...y.react,componentStack:[...y.react.componentStack]},element:y.element,styles:{...y.styles,classNames:[...y.styles.classNames],matchedRules:y.styles.matchedRules.map(F=>({...F})),computed:{...y.styles.computed},warnings:[...y.styles.warnings]},...y.code===void 0?{}:{code:y.code},warnings:[]})),createdAt:w},task:{kind:"ask",question:i},createdAt:w}}async function O(){if(d)return;let i=n;e.panel.renderCapability(void 0);try{let x=await E.capability();if(!b(i))return;d=!0,e.panel.renderCapability(x);let w=e.panel.readExecutorId();e.panel.setConsent(w!==void 0&&v.get(w)===!0)}catch(x){if(!b(i)||Ve(x))return;e.panel.renderError(_e(x))}}function l(i,x){b(x)&&(e.panel.renderEvent(i),i.type==="snapshot"&&(g=i.snapshot))}async function m(){if(s)return;let i=e.panel.readQuestion(),x=e.panel.readExecutorId(),w=P(i);if(i.length===0||x===void 0||!e.panel.readConsent()||w===void 0)return;let y=++n,F=e.panel.readModel();a=i,s=!0,e.onBusyChange(!0),r=void 0,g=void 0,e.panel.setBusy(!0);try{let B=await E.createJob({schemaVersion:1,requestId:e.createId(),envelope:w,executorId:x,...F===void 0?{}:{model:F},providerDataConsent:!0});if(!b(y)||(g=B,e.panel.renderJob(B),await E.events(B.jobId,0,de=>{l(de,y)}),!b(y)))return;let $=await E.result(B.jobId);if(!b(y))return;if(g=$.snapshot,s=!1,e.onBusyChange(!1),$.result===void 0){e.panel.renderJob($.snapshot),$.snapshot.status==="failed"&&e.panel.renderError($.snapshot.errorCode);return}r=$.result,e.panel.renderAnswer($.result,!1)}catch(B){if(!b(y)||Ve(B))return;s=!1,e.onBusyChange(!1),e.panel.renderError(_e(B))}finally{b(y)&&(s=!1,e.panel.setBusy(!1))}}async function u(){if(!s||g?.canCancel!==!0)return;let i=n;try{let x=await E.cancelJob(g.jobId);if(!b(i))return;g=x,s=!1,e.onBusyChange(!1),e.panel.renderJob(x),e.panel.setBusy(!1)}catch(x){if(!b(i)||Ve(x))return;s=!1,e.onBusyChange(!1),e.panel.renderError(_e(x))}}function A(){n+=1;let i=g;s=!1,e.onBusyChange(!1),g=void 0,E.cancelPending(),i?.canCancel===!0&&E.cancelJob(i.jobId).catch(()=>{}),e.panel.setBusy(!1)}function N(){s&&A(),n+=1,g=void 0,r=void 0,a="",e.panel.clear(),e.panel.focusQuestion()}function q(){let i=e.panel.answerPlainText();i.length===0||e.clipboard===void 0||e.clipboard.writeText(i).then(()=>{e.panel.notify("copied")}).catch(()=>{e.panel.notify("copy-failed")})}function te(){if(r===void 0||s)return;let i=e.panel.answerPlainText().trim().slice(0,4e3);if(i.length===0)return;let x=Object.freeze({kind:"contextual-ask",askJobId:r.jobId,question:a,answerDigest:i,sourceIds:r.sources.map(w=>w.sourceId)});e.onConvert(x),e.panel.setOrigin(x),e.panel.setMode("change"),e.panel.notify("converted")}function ne(i){let x=e.panel.selectedSourceId(i.target);if(x===void 0)return;let w=e.panel.sourceById(x);w!==void 0&&e.onOpenSource(w).catch(()=>{e.panel.notify("source-open-failed")})}function ie(i){i.target!==e.panel.questionInput||i.key!=="Enter"||k||i.isComposing||!i.metaKey&&!i.ctrlKey||(i.preventDefault(),m())}function I(){let i=e.panel.readExecutorId();e.panel.setConsent(i!==void 0&&v.get(i)===!0)}function W(){k=!0}function oe(){k=!1}function re(){let i=e.panel.readExecutorId();i!==void 0&&v.set(i,e.panel.readConsent())}function U(){m()}function R(){u()}function se(){t||(t=!0,e.panel.submitButton.addEventListener("click",U),e.panel.cancelButton.addEventListener("click",R),e.panel.newQuestionButton.addEventListener("click",N),e.panel.copyButton.addEventListener("click",q),e.panel.convertButton.addEventListener("click",te),e.panel.executorSelect.addEventListener("change",I),e.panel.consentCheckbox.addEventListener("change",re),e.panel.questionInput.addEventListener("keydown",ie),e.panel.questionInput.addEventListener("compositionstart",W),e.panel.questionInput.addEventListener("compositionend",oe),e.panel.root.addEventListener("click",ne),O())}function ce(){t&&(A(),t=!1,e.panel.submitButton.removeEventListener("click",U),e.panel.cancelButton.removeEventListener("click",R),e.panel.newQuestionButton.removeEventListener("click",N),e.panel.copyButton.removeEventListener("click",q),e.panel.convertButton.removeEventListener("click",te),e.panel.executorSelect.removeEventListener("change",I),e.panel.consentCheckbox.removeEventListener("change",re),e.panel.questionInput.removeEventListener("keydown",ie),e.panel.questionInput.removeEventListener("compositionstart",W),e.panel.questionInput.removeEventListener("compositionend",oe),e.panel.root.removeEventListener("click",ne),E.dispose())}return Object.freeze({beginSelection(){n+=1,s=!1,e.onBusyChange(!1),g=void 0,r=void 0,a="",e.panel.clear(),O()},cancelPending:A,dispose:ce,isBusy:()=>s,mount:se,selectionChanged(){r!==void 0&&e.panel.renderAnswer(r,!0)}})}var Pt=Symbol.for("spotpatch.contextual-ask.v1");function ht(e){globalThis[Pt]=e}var bt="data-spotpatch-ui",Yt=Object.freeze({highlight:2147483646,controls:2147483647}),Zt=Object.freeze({compactInset:8,compactViewportWidth:520,desktopInset:24,dragActivationDistance:6,edgeSnapDistance:20,workbenchMaxHeight:620,workbenchMaxWidth:460});function c(e,t){let n=e.createElement(t);return n.setAttribute(bt,""),n}function K(e,t,n=""){let s=c(e,"button");return s.type="button",s.className=n,s.textContent=t,s}function We(e,t){let n=c(e,"div");n.className="spotpatch-ask-executor-picker";let s=K(e,"","spotpatch-ask-executor");s.id=`spotpatch-ask-picker-${Math.random().toString(36).slice(2)}`,s.setAttribute("role","combobox"),s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-expanded","false");let g=c(e,"span");s.append(g);let r=c(e,"div");r.id=`${s.id}-menu`,r.className="spotpatch-ask-executor-menu",r.setAttribute("role","listbox"),r.hidden=!0,s.setAttribute("aria-controls",r.id);let a=c(e,"select");a.className="spotpatch-ask-executor-native",a.tabIndex=-1,a.setAttribute("aria-hidden","true"),n.append(s,r,a);function d(l=!1){r.hidden||(r.hidden=!0,s.setAttribute("aria-expanded","false"),s.removeAttribute("aria-activedescendant"),l&&s.focus({preventScroll:!0}),t())}function k(l){let m=[...r.children],u=m[l];if(u===void 0)return;for(let q of m)q.dataset.active=String(q===u);s.setAttribute("aria-activedescendant",u.id);let A=u.getBoundingClientRect(),N=r.getBoundingClientRect();A.top<N.top?r.scrollTop-=N.top-A.top:A.bottom>N.bottom&&(r.scrollTop+=A.bottom-N.bottom)}function v(){s.disabled||!r.hidden||(r.hidden=!1,s.setAttribute("aria-expanded","true"),k(Math.max(0,a.selectedIndex)),t())}function E(){g.textContent=a.selectedOptions[0]?.textContent??"",s.title=g.textContent,s.dataset.empty=String(a.value.length===0);for(let l of[...r.children])l.setAttribute("aria-selected",String(l.dataset.value===a.value))}function b(l){s.disabled||(a.value=l,E(),d(!0),a.dispatchEvent(new Event("change",{bubbles:!0})))}function P(){d(),r.replaceChildren();for(let[l,m]of[...a.options].entries()){let u=c(e,"div");u.id=`${r.id}-${String(l)}`,u.className="spotpatch-ask-executor-option",u.setAttribute("role","option"),u.dataset.value=m.value,u.textContent=m.textContent,u.title=m.textContent,u.addEventListener("pointerdown",A=>{A.preventDefault()}),u.addEventListener("click",()=>{b(m.value)}),r.append(u)}E()}s.addEventListener("click",()=>{r.hidden?v():d()}),s.addEventListener("keydown",l=>{if(l.key==="Escape"&&!r.hidden){l.preventDefault(),l.stopPropagation(),d();return}if(l.key==="Tab"){d();return}if(["Enter"," "].includes(l.key)&&!r.hidden){l.preventDefault();let A=[...r.children].find(N=>N.id===s.getAttribute("aria-activedescendant"));A?.dataset.value!==void 0&&b(A.dataset.value);return}if(!["ArrowDown","ArrowUp","Home","End"].includes(l.key))return;if(l.preventDefault(),r.hidden){v();return}let m=[...r.children],u=m.findIndex(A=>A.id===s.getAttribute("aria-activedescendant"));k(l.key==="Home"?0:l.key==="End"?m.length-1:(u+(l.key==="ArrowDown"?1:-1)+m.length)%m.length)}),n.addEventListener("focusout",l=>{(!(l.relatedTarget instanceof Node)||!n.contains(l.relatedTarget))&&d()});let O=l=>{l.composedPath().includes(n)||d()};return e.addEventListener("pointerdown",O),a.addEventListener("change",E),{root:n,trigger:s,select:a,rebuild:P,close:d,setDisabled(l){a.disabled=l,s.disabled=l||a.options.length<2,s.dataset.expandable=String(!s.disabled),s.disabled&&d()},dispose(){e.removeEventListener("pointerdown",O)}}}var Dt=Object.freeze({mode:Object.freeze({ask:"Ask",change:"Change",label:"Task mode"}),title:"Ask about this selection",subtitle:"One question, one sourced answer. SpotPatch will not write code.",questionLabel:"Question",questionPlaceholder:"What does this component do?",suggestionsLabel:"Suggested questions",suggestions:Object.freeze(["What does this component do?","Where does its data come from?","Why is it implemented this way?"]),executorLabel:"Read-only executor",modelLabel:"Model",loadingExecutors:"Checking available executors…",noExecutor:"No verified read-only executor is available.",unavailable:"unavailable",consent:"Allow the selected source snapshot to be sent to this provider for this answer.",dataSummary:(e,t)=>`${String(e)} selected element${e===1?"":"s"} · ${String(t)} source-backed`,safety:"Single turn · read-only · no history",submit:"Ask",cancel:"Cancel",newQuestion:"Start over",copy:"Copy answer",convert:"Turn into change request",answerTitle:"Answer",sourcesTitle:"Sources",stale:"The selection changed after this answer. Ask again before relying on it.",convertedTitle:"From contextual answer",convertedBody:"The answer and source references remain local and have not started a change.",status:Object.freeze({queued:"Queued",authorizing:"Verifying read-only access",running:"Analyzing selected source",cancelling:"Cancelling",answered:"Answer ready",cancelled:"Cancelled",failed:"Could not answer"}),sourceLabel:(e,t,n)=>`${e}:${String(t)}${n===t?"":`–${String(n)}`}`,readSource:e=>`Reading ${e}`,readFiles:e=>`Reading ${e} files`,copied:"Answer copied.",copyFailed:"The answer could not be copied.",sourceOpenFailed:"The source could not be opened.",converted:"Switched to Change with the answer attached as local context.",error:e=>e===void 0?"SpotPatch could not complete this question.":{INVALID_TOKEN:"The local SpotPatch session expired. Refresh the page.",ORIGIN_NOT_ALLOWED:"The local request failed its same-origin security check. Refresh or restart the dev server.",ASK_DISABLED:"Contextual Ask is disabled.",ASK_SELECTION_REQUIRED:"Select at least one element first.",ASK_SELECTION_STALE:"The selected source changed. Refresh the selection and ask again.",ASK_QUESTION_INVALID:"Enter one valid question.",ASK_EXECUTOR_UNAVAILABLE:"The selected read-only executor is unavailable.",ASK_TIMEOUT:"The read-only executor took too long to answer. Try the question again.",ASK_CONSENT_REQUIRED:"Confirm provider data access for this answer.",ASK_BUSY:"Another workspace task is active. Try again when it finishes.",ASK_CANCELLED:"The question was cancelled.",ASK_RESULT_EXPIRED:"This answer has expired. Ask again.",ASK_WRITE_ATTEMPTED:"The executor attempted a write and was stopped.",ASK_ANSWER_INVALID:"The executor returned an invalid sourced answer.",ASK_PROTOCOL_INCOMPATIBLE:"The executor protocol is incompatible.",ASK_LIMIT_EXCEEDED:"The selected context is too large.",ASK_SOURCE_SCOPE_DENIED:"A requested source was outside the granted snapshot."}[e]??"SpotPatch could not complete this question.",warning:e=>e==="insufficient-evidence"?"The selected source did not contain enough evidence for a complete answer.":"Some source references were omitted because they could not be verified."}),Kt=Object.freeze({mode:Object.freeze({ask:"问答",change:"修改",label:"任务模式"}),title:"询问所选元素",subtitle:"一次提问,一次带源码引用的回答;SpotPatch 不会写入代码。",questionLabel:"问题",questionPlaceholder:"这个组件是做什么的?",suggestionsLabel:"推荐问题",suggestions:Object.freeze(["这个组件是做什么的?","它的数据从哪里来?","为什么要这样实现?"]),executorLabel:"只读执行器",modelLabel:"模型",loadingExecutors:"正在检查可用执行器…",noExecutor:"目前没有通过只读验证的执行器。",unavailable:"不可用",consent:"允许本次回答将所选源码快照发送给该提供商。",dataSummary:(e,t)=>`${String(e)} 个已选元素 · ${String(t)} 个具备源码上下文`,safety:"单轮 · 只读 · 不保存历史",submit:"提问",cancel:"取消",newQuestion:"重新开始",copy:"复制回答",convert:"转成修改请求",answerTitle:"回答",sourcesTitle:"源码引用",stale:"回答后选择已发生变化。请重新提问后再采信此回答。",convertedTitle:"来自上下文问答",convertedBody:"回答与源码引用仅作为本地上下文保留,尚未发起任何修改。",status:Object.freeze({queued:"已排队",authorizing:"正在验证只读权限",running:"正在分析所选源码",cancelling:"正在取消",answered:"回答已就绪",cancelled:"已取消",failed:"无法回答"}),sourceLabel:(e,t,n)=>`${e}:${String(t)}${n===t?"":`–${String(n)}`}`,readSource:e=>`正在读取 ${e}`,readFiles:e=>`正在读取 ${e} 个文件`,copied:"回答已复制。",copyFailed:"无法复制回答。",sourceOpenFailed:"无法打开源码。",converted:"已切换到修改模式,并把回答作为本地上下文附带。",error:e=>e===void 0?"SpotPatch 未能完成本次提问。":{INVALID_TOKEN:"本地 SpotPatch 会话已失效,请刷新页面。",ORIGIN_NOT_ALLOWED:"本地请求未通过同源安全校验,请刷新页面或重启开发服务。",ASK_DISABLED:"上下文问答未启用。",ASK_SELECTION_REQUIRED:"请先选择至少一个元素。",ASK_SELECTION_STALE:"所选源码已经变化,请刷新选择后重新提问。",ASK_QUESTION_INVALID:"请输入一个有效的问题。",ASK_EXECUTOR_UNAVAILABLE:"所选只读执行器当前不可用。",ASK_TIMEOUT:"只读执行器未能在限定时间内返回回答,请重新提问。",ASK_CONSENT_REQUIRED:"请确认本次回答的提供商数据访问。",ASK_BUSY:"工作区正在执行其他任务,请稍后重试。",ASK_CANCELLED:"本次提问已取消。",ASK_RESULT_EXPIRED:"回答已过期,请重新提问。",ASK_WRITE_ATTEMPTED:"执行器尝试写入,已被阻止。",ASK_ANSWER_INVALID:"执行器返回的带引用回答无效。",ASK_PROTOCOL_INCOMPATIBLE:"执行器协议不兼容。",ASK_LIMIT_EXCEEDED:"所选上下文过大。",ASK_SOURCE_SCOPE_DENIED:"请求的源码超出了授权快照范围。"}[e]??"SpotPatch 未能完成本次提问。",warning:e=>e==="insufficient-evidence"?"所选源码不足以支持完整回答。":"部分源码引用因无法验证而被省略。"});function ze(e){return e==="zh-CN"?Kt:Dt}function Mt(e){let t=e.createElement("style");return t.textContent=`
3
3
  .spotpatch-ask-mode { display: grid; grid-template-columns: 1fr 1fr; gap: 4px; margin-bottom: 14px; padding: 4px; border: 1px solid var(--spotpatch-border-subtle); border-radius: 10px; background: #0a0a0e; }
4
4
  .spotpatch-ask-mode button { min-height: 34px; border: 0; border-radius: 7px; color: var(--spotpatch-text-secondary); background: transparent; cursor: pointer; font-size: 12px; font-weight: 700; }
5
5
  .spotpatch-ask-mode button[aria-selected="true"] { color: #f7f7ff; background: linear-gradient(135deg, rgb(139 123 255 / 25%), rgb(82 168 255 / 14%)); box-shadow: inset 0 0 0 1px rgb(139 123 255 / 24%); }
6
6
  .spotpatch-ask-panel { display: grid; gap: 14px; }
7
- .spotpatch-ask-field { display: grid; gap: 7px; }
7
+ .spotpatch-ask-field { display: grid; gap: 7px; min-width: 0; }
8
+ .spotpatch-ask-field[hidden] { display: none; }
8
9
  .spotpatch-ask-field > label, .spotpatch-ask-label { color: #c9cad2; font-size: 11px; font-weight: 680; }
9
10
  .spotpatch-ask-question { box-sizing: border-box; width: 100%; min-height: 92px; resize: vertical; border: 1px solid var(--spotpatch-border); border-radius: 10px; padding: 11px 12px; outline: none; color: var(--spotpatch-text); background: var(--spotpatch-bg-input); line-height: 1.55; }
10
11
  .spotpatch-ask-question:focus { border-color: rgb(139 123 255 / 68%); box-shadow: 0 0 0 3px rgb(139 123 255 / 12%); }
@@ -19,10 +20,10 @@ var It=Object.freeze({maximumTargets:20,maximumQuestionCharacters:4e3,maximumAns
19
20
  .spotpatch-ask-executor:focus-visible { border-color: rgb(139 123 255 / 68%); box-shadow: 0 0 0 3px rgb(139 123 255 / 12%); }
20
21
  .spotpatch-ask-executor:disabled { color: var(--spotpatch-text); background: rgb(255 255 255 / 3%); cursor: default; opacity: 1; }
21
22
  .spotpatch-ask-executor[data-empty="true"]:disabled { color: var(--spotpatch-text-muted); }
22
- .spotpatch-ask-executor-menu { display: grid; gap: 3px; border: 1px solid var(--spotpatch-border); border-radius: 9px; padding: 4px; background: #101116; box-shadow: 0 10px 28px rgb(0 0 0 / 28%); }
23
+ .spotpatch-ask-executor-menu { display: grid; gap: 3px; border: 1px solid var(--spotpatch-border); border-radius: 9px; padding: 4px; background: var(--spotpatch-bg-input); max-height: 224px; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; box-shadow: 0 10px 28px rgb(0 0 0 / 28%); }
23
24
  .spotpatch-ask-executor-menu[hidden] { display: none; }
24
- .spotpatch-ask-executor-option { box-sizing: border-box; min-height: 34px; border: 0; border-radius: 6px; padding: 7px 9px; color: var(--spotpatch-text-secondary); background: transparent; cursor: pointer; font: inherit; text-align: left; }
25
- .spotpatch-ask-executor-option:hover, .spotpatch-ask-executor-option:focus-visible { color: #fff; background: rgb(139 123 255 / 13%); outline: none; }
25
+ .spotpatch-ask-executor-option { box-sizing: border-box; min-height: 34px; border: 0; border-radius: 6px; padding: 7px 9px; color: var(--spotpatch-text-secondary); background: transparent; cursor: pointer; font: inherit; text-align: left; overflow-wrap: anywhere; }
26
+ .spotpatch-ask-executor-option[data-active="true"], .spotpatch-ask-executor-option:hover { color: #fff; background: rgb(139 123 255 / 13%); outline: none; }
26
27
  .spotpatch-ask-executor-option[aria-selected="true"] { color: #f4f1ff; background: rgb(139 123 255 / 20%); }
27
28
  .spotpatch-ask-executor-native { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; border: 0; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; }
28
29
  .spotpatch-ask-executor-status { margin: 0; border-left: 2px solid var(--spotpatch-warning); padding-left: 8px; color: #d8b66c; font-size: 10.5px; line-height: 1.45; }
@@ -53,10 +54,10 @@ var It=Object.freeze({maximumTargets:20,maximumQuestionCharacters:4e3,maximumAns
53
54
  .spotpatch-ask-origin strong { display: block; margin-bottom: 2px; color: #d9d4ff; font-size: 11px; }
54
55
  @media (max-width: 420px) { .spotpatch-ask-data { display: grid; } .spotpatch-ask-actions, .spotpatch-ask-answer-actions { justify-content: stretch; } .spotpatch-ask-actions button, .spotpatch-ask-answer-actions button { flex: 1 1 auto; } }
55
56
  @media (prefers-reduced-motion: reduce) { .spotpatch-ask-panel *, .spotpatch-ask-mode * { scroll-behavior: auto !important; transition: none !important; } }
56
- `,t}function We(e,t,o,a,f){if(o.length===0)return;let r=s(e,"div");r.className="spotpatch-ask-citations";for(let c of o){let l=a.get(c);if(l===void 0)continue;let C=N(e,f.sourceLabel(l.relativePath,l.startLine,l.endLine),"spotpatch-ask-source");C.dataset.askSourceId=l.sourceId,C.title=l.label,r.append(C)}t.append(r)}function yt(e){let{document:t}=e,o=Ve(e.locale()),a="change",f,r,c,l,C="",L="",w=Object.freeze({contextReady:!1,targetCount:0,sourceCount:0}),b=!1,D=s(t,"section"),K=s(t,"div");K.className="spotpatch-ask-mode",K.setAttribute("role","tablist");let q=N(t,""),M=N(t,"");q.setAttribute("role","tab"),M.setAttribute("role","tab"),K.append(q,M);let E=s(t,"aside");E.className="spotpatch-ask-origin",E.hidden=!0;let I=s(t,"strong"),G=s(t,"span");E.append(I,G);let Y=s(t,"div");Y.className="spotpatch-ask-panel";let oe=s(t,"div");oe.className="spotpatch-ask-field";let re=s(t,"label"),ce=`spotpatch-ask-question-${Math.random().toString(36).slice(2)}`;re.htmlFor=ce;let _=s(t,"textarea");_.id=ce,_.className="spotpatch-ask-question",_.maxLength=4e3;let $=s(t,"div");$.className="spotpatch-ask-suggestions",$.setAttribute("aria-label",""),oe.append(re,_,$);let se=s(t,"div");se.className="spotpatch-ask-field";let ae=s(t,"label"),V=s(t,"div");V.className="spotpatch-ask-executor-picker";let T=N(t,"","spotpatch-ask-executor"),y=s(t,"select"),de=`spotpatch-ask-executor-${Math.random().toString(36).slice(2)}`,i=`${de}-menu`;T.id=de,T.setAttribute("role","combobox"),T.setAttribute("aria-controls",i),T.setAttribute("aria-expanded","false");let x=s(t,"span");T.append(x);let g=s(t,"div");g.id=i,g.className="spotpatch-ask-executor-menu",g.setAttribute("role","listbox"),g.hidden=!0,y.className="spotpatch-ask-executor-native",y.tabIndex=-1,y.setAttribute("aria-hidden","true"),ae.htmlFor=de;let h=s(t,"p");h.className="spotpatch-ask-executor-status",h.setAttribute("role","status"),h.hidden=!0,V.append(T,g,y),se.append(ae,V,h);let O=s(t,"div");O.className="spotpatch-ask-safety";let U=s(t,"div");U.className="spotpatch-ask-data";let le=s(t,"span"),He=s(t,"strong");U.append(le,He);let _e=s(t,"label");_e.className="spotpatch-ask-consent";let z=s(t,"input");z.type="checkbox";let ze=s(t,"span");_e.append(z,ze),O.append(U,_e);let B=s(t,"div");B.className="spotpatch-ask-status",B.setAttribute("role","status"),B.setAttribute("aria-live","polite"),B.hidden=!0;let Ie=s(t,"strong"),Z=s(t,"div");Z.className="spotpatch-ask-activity",B.append(Ie,Z);let W=s(t,"div");W.className="spotpatch-ask-error",W.setAttribute("role","alert"),W.hidden=!0;let Re=s(t,"div");Re.className="spotpatch-ask-actions";let be=N(t,""),ue=N(t,""),pe=N(t,"","spotpatch-primary");ue.hidden=!0,Re.append(be,ue,pe);let ee=s(t,"article");ee.className="spotpatch-ask-answer",ee.hidden=!0;let te=s(t,"div");te.className="spotpatch-ask-stale",te.hidden=!0;let Fe=s(t,"h3"),Le=s(t,"div"),F=s(t,"div");F.className="spotpatch-ask-blocks";let ye=s(t,"section");ye.className="spotpatch-ask-sources";let Xe=s(t,"h4"),Ee=s(t,"div");Ee.className="spotpatch-ask-source-list",ye.append(Xe,Ee);let Oe=s(t,"div");Oe.className="spotpatch-ask-answer-actions";let ve=N(t,""),Ne=N(t,"","spotpatch-primary");Oe.append(ve,Ne),ee.append(te,Fe,Le,F,ye,Oe),Y.append(oe,se,O,B,W,Re,ee),D.append(K,E,Y);function Qe(){let n=f?.executors.find(d=>d.executorId===y.value);return n?.state==="ready"&&n.readOnlyProven}function kt(){return f?.executors.some(n=>n.state==="ready"&&n.readOnlyProven)===!0}function mt(){return f?.executors.filter(n=>n.state==="ready"&&n.readOnlyProven).length??0}function ne(n=!1){g.hidden||(g.hidden=!0,T.setAttribute("aria-expanded","false"),n&&T.focus({preventScroll:!0}),e.onViewChange())}function Ge(n=!1){if(!(T.disabled||!g.hidden)){if(g.hidden=!1,T.setAttribute("aria-expanded","true"),n){let d=g.querySelector('.spotpatch-ask-executor-option[aria-selected="true"]'),p=g.firstElementChild;(d??(p instanceof HTMLElement?p:null))?.focus({preventScroll:!0})}e.onViewChange()}}function Ye(){let n=[...y.options].find(d=>d.value===y.value);x.textContent=n?.textContent??o.noExecutor,T.dataset.empty=String(y.value.length===0);for(let d of g.querySelectorAll(".spotpatch-ask-executor-option"))d.setAttribute("aria-selected",String(d.dataset.executorId===y.value))}function P(){pe.disabled=b||_.value.trim().length===0||!Qe()||!z.checked||w.targetCount===0,w.contextReady||(pe.disabled=!0),_.disabled=b;let n=mt(),d=b||f===void 0||!kt();y.disabled=d,T.disabled=d||n<2,T.dataset.expandable=String(!d&&n>1),T.disabled&&ne(),z.disabled=b||!Qe(),be.hidden=b||r===void 0,ue.hidden=!b}function fe(){let n=a==="ask";q.setAttribute("aria-selected",String(n)),M.setAttribute("aria-selected",String(!n)),Y.hidden=!n,e.changeRoot.hidden=n,e.changeActions.hidden=n,E.hidden=n||E.dataset.active!=="true",(l!==a||C!==o.title||L!==o.subtitle)&&(l=a,C=o.title,L=o.subtitle,e.onModeChange(a,o.title,o.subtitle)),e.onViewChange()}function Ct(){$.replaceChildren();for(let n of o.suggestions){let d=N(t,n);d.type="button",d.addEventListener("click",()=>{_.value=n,P(),_.focus()}),$.append(d)}}function Ze(){o=Ve(e.locale()),K.setAttribute("aria-label",o.mode.label),q.textContent=o.mode.ask,M.textContent=o.mode.change,re.textContent=o.questionLabel,_.placeholder=o.questionPlaceholder,$.setAttribute("aria-label",o.suggestionsLabel),ae.textContent=o.executorLabel,ze.textContent=o.consent,He.textContent=o.safety,pe.textContent=o.submit,ue.textContent=o.cancel,be.textContent=o.newQuestion,ve.textContent=o.copy,Ne.textContent=o.convert,Fe.textContent=o.answerTitle,Xe.textContent=o.sourcesTitle,te.textContent=o.stale,I.textContent=o.convertedTitle,G.textContent=o.convertedBody,le.textContent=o.dataSummary(w.targetCount,w.sourceCount),Ct(),et(f),r!==void 0&&nt(r,!te.hidden)}function et(n){f=n;let d=y.value;if(y.replaceChildren(),g.replaceChildren(),ne(),h.hidden=!0,h.textContent="",n===void 0){let p=t.createElement("option");p.textContent=o.loadingExecutors,p.value="",y.append(p)}else if(!n.enabled||n.executors.length===0){let p=t.createElement("option");p.textContent=o.noExecutor,p.value="",y.append(p)}else{let p=n.executors.filter(u=>u.state==="ready"&&u.readOnlyProven),A=n.executors.filter(u=>u.state!=="ready"||!u.readOnlyProven);for(let u of p){let j=t.createElement("option");j.value=u.executorId,j.textContent=`${u.label} · ${u.effectiveModelLabel}`,y.append(j);let X=N(t,j.textContent,"spotpatch-ask-executor-option");X.dataset.executorId=u.executorId,X.setAttribute("role","option"),X.addEventListener("click",()=>{y.value=u.executorId,Ye(),ne(!0),y.dispatchEvent(new Event("change",{bubbles:!0}))}),g.append(X)}if(p.length===0){let u=t.createElement("option");u.textContent=o.noExecutor,u.value="",y.append(u)}y.value=p.some(u=>u.executorId===d)?d:p[0]?.executorId??"",A.length>0&&(h.textContent=A.map(u=>`${u.label}: ${o.error(u.errorCode)}`).join(" "),h.hidden=!1)}Ye(),P()}function tt(n){c=n,B.hidden=!1,W.hidden=!0,Ie.textContent=o.status[n.status],["answered","cancelled","failed"].includes(n.status)?(b=!1,e.onExecutionChange()):e.onExecutionChange({scene:"running",tone:"running",headline:o.status[n.status],expandedHeadline:o.status[n.status],action:o.safety,expandedAction:o.safety,meta:`${n.executor.label} · ${n.executor.modelLabel}`,recentActivities:Object.freeze([]),startedAt:n.createdAt}),P()}function St(n){if(n.type==="snapshot"){tt(n.snapshot);return}if(n.type==="phase"&&(Ie.textContent=o.status[n.status]),n.type==="read-activity"&&n.state==="started"){let d=s(t,"span");for(d.textContent=n.activity.kind==="source"?o.readSource(n.activity.relativePath):o.readFiles(n.activity.bucket),Z.append(d);Z.childElementCount>5;)Z.firstElementChild?.remove();if(c!==void 0){let p=d.textContent;e.onExecutionChange({scene:"running",tone:"running",headline:o.status.running,expandedHeadline:o.status.running,action:p,expandedAction:p,meta:`${c.executor.label} · ${c.executor.modelLabel}`,activity:{key:`ask:${String(n.sequence)}`,kind:"read",label:p,state:"active"},recentActivities:Object.freeze([]),startedAt:c.createdAt})}}}function nt(n,d){r=n,c=void 0,e.onExecutionChange();let p=new Map(n.sources.map(A=>[A.sourceId,A]));F.replaceChildren(),Le.replaceChildren(),Ee.replaceChildren(),te.hidden=!d;for(let A of n.warnings){let u=s(t,"div");u.className="spotpatch-ask-warning",u.textContent=o.warning(A.code),Le.append(u)}for(let A of n.blocks)if(A.kind==="paragraph"){let u=s(t,"p");u.textContent=A.text,F.append(u),We(t,F,A.sourceIds,p,o)}else if(A.kind==="code"){let u=s(t,"pre"),j=s(t,"code");A.language!==void 0&&(j.dataset.language=A.language),j.textContent=A.code,u.append(j),F.append(u),We(t,F,A.sourceIds,p,o)}else{let u=s(t,"ul");for(let j of A.items){let X=s(t,"li");X.textContent=j.text,We(t,X,j.sourceIds,p,o),u.append(X)}F.append(u)}for(let A of n.sources){let u=N(t,o.sourceLabel(A.relativePath,A.startLine,A.endLine),"spotpatch-ask-source");u.dataset.askSourceId=A.sourceId,u.title=A.label,Ee.append(u)}ye.hidden=n.sources.length===0,ee.hidden=!1,B.hidden=!0,b=!1,P(),e.onViewChange()}function wt(){if(r===void 0)return"";let n=r.blocks.flatMap(p=>p.kind==="paragraph"?[p.text]:p.kind==="code"?[p.code]:p.items.map(A=>`- ${A.text}`)).join(`
57
+ `,t}function He(e,t,n,s,g){if(n.length===0)return;let r=c(e,"div");r.className="spotpatch-ask-citations";for(let a of n){let d=s.get(a);if(d===void 0)continue;let k=K(e,g.sourceLabel(d.relativePath,d.startLine,d.endLine),"spotpatch-ask-source");k.dataset.askSourceId=d.sourceId,k.title=d.label,r.append(k)}t.append(r)}function xt(e){let{document:t}=e,n=ze(e.locale()),s="change",g,r,a,d,k="",v="",E=Object.freeze({contextReady:!1,targetCount:0,sourceCount:0}),b=!1,P=c(t,"section"),O=c(t,"div");O.className="spotpatch-ask-mode",O.setAttribute("role","tablist");let l=K(t,""),m=K(t,"");l.setAttribute("role","tab"),m.setAttribute("role","tab"),O.append(l,m);let u=c(t,"aside");u.className="spotpatch-ask-origin",u.hidden=!0;let A=c(t,"strong"),N=c(t,"span");u.append(A,N);let q=c(t,"div");q.className="spotpatch-ask-panel";let te=c(t,"div");te.className="spotpatch-ask-field";let ne=c(t,"label"),ie=`spotpatch-ask-question-${Math.random().toString(36).slice(2)}`;ne.htmlFor=ie;let I=c(t,"textarea");I.id=ie,I.className="spotpatch-ask-question",I.maxLength=4e3;let W=c(t,"div");W.className="spotpatch-ask-suggestions",W.setAttribute("aria-label",""),te.append(ne,I,W);let oe=c(t,"div");oe.className="spotpatch-ask-field";let re=c(t,"label"),U=We(t,e.onViewChange),R=U.select;re.htmlFor=U.trigger.id;let se=c(t,"div");se.className="spotpatch-ask-field";let ce=c(t,"label"),i=We(t,e.onViewChange);ce.htmlFor=i.trigger.id,se.append(ce,i.root);let x,w=c(t,"p");w.className="spotpatch-ask-executor-status",w.setAttribute("role","status"),w.hidden=!0,oe.append(re,U.root,w);let y=c(t,"div");y.className="spotpatch-ask-safety";let F=c(t,"div");F.className="spotpatch-ask-data";let B=c(t,"span"),$=c(t,"strong");F.append(B,$);let de=c(t,"label");de.className="spotpatch-ask-consent";let X=c(t,"input");X.type="checkbox";let Fe=c(t,"span");de.append(X,Fe),y.append(F,de);let j=c(t,"div");j.className="spotpatch-ask-status",j.setAttribute("role","status"),j.setAttribute("aria-live","polite"),j.hidden=!0;let Ie=c(t,"strong"),Y=c(t,"div");Y.className="spotpatch-ask-activity",j.append(Ie,Y);let z=c(t,"div");z.className="spotpatch-ask-error",z.setAttribute("role","alert"),z.hidden=!0;let ve=c(t,"div");ve.className="spotpatch-ask-actions";let xe=K(t,""),le=K(t,""),pe=K(t,"","spotpatch-primary");le.hidden=!0,ve.append(xe,le,pe);let Z=c(t,"article");Z.className="spotpatch-ask-answer",Z.hidden=!0;let ee=c(t,"div");ee.className="spotpatch-ask-stale",ee.hidden=!0;let Xe=c(t,"h3"),Re=c(t,"div"),Q=c(t,"div");Q.className="spotpatch-ask-blocks";let Ae=c(t,"section");Ae.className="spotpatch-ask-sources";let Qe=c(t,"h4"),me=c(t,"div");me.className="spotpatch-ask-source-list",Ae.append(Qe,me);let Le=c(t,"div");Le.className="spotpatch-ask-answer-actions";let Oe=K(t,""),Ne=K(t,"","spotpatch-primary");Le.append(Oe,Ne),Z.append(ee,Xe,Re,Q,Ae,Le),q.append(te,oe,se,y,j,z,ve,Z),P.append(O,u,q);function Pe(){let o=g?.executors.find(C=>C.executorId===R.value);return o?.state==="ready"&&o.readOnlyProven}function mt(){return g?.executors.some(o=>o.state==="ready"&&o.readOnlyProven)===!0}function Ge(){let o=g?.executors.find(h=>h.executorId===R.value),C=x===o?.executorId?i.select.value:void 0;x=o?.executorId;let f=o?.models;se.hidden=f===void 0,i.select.replaceChildren();for(let h of f??[]){let p=t.createElement("option");p.value=h,p.textContent=h,i.select.append(p)}i.select.value=f?.find(h=>h===C)??f?.find(h=>h===o?.requestedModelLabel)??f?.[0]??"",i.rebuild()}function M(){pe.disabled=b||I.value.trim().length===0||!Pe()||!X.checked||E.targetCount===0,E.contextReady||(pe.disabled=!0),I.disabled=b;let o=b||g===void 0||!mt();U.setDisabled(o),i.setDisabled(b||!Pe()),X.disabled=b||!Pe(),xe.hidden=b||r===void 0,le.hidden=!b}function ue(){let o=s==="ask";l.setAttribute("aria-selected",String(o)),m.setAttribute("aria-selected",String(!o)),q.hidden=!o,e.changeRoot.hidden=o,e.changeActions.hidden=o,u.hidden=o||u.dataset.active!=="true",(d!==s||k!==n.title||v!==n.subtitle)&&(d=s,k=n.title,v=n.subtitle,e.onModeChange(s,n.title,n.subtitle)),e.onViewChange()}function yt(){W.replaceChildren();for(let o of n.suggestions){let C=K(t,o);C.type="button",C.addEventListener("click",()=>{I.value=o,M(),I.focus()}),W.append(C)}}function Ye(){n=ze(e.locale()),O.setAttribute("aria-label",n.mode.label),l.textContent=n.mode.ask,m.textContent=n.mode.change,ne.textContent=n.questionLabel,I.placeholder=n.questionPlaceholder,W.setAttribute("aria-label",n.suggestionsLabel),re.textContent=n.executorLabel,ce.textContent=n.modelLabel,U.root.querySelector("[role=listbox]")?.setAttribute("aria-label",n.executorLabel),i.root.querySelector("[role=listbox]")?.setAttribute("aria-label",n.modelLabel),Fe.textContent=n.consent,$.textContent=n.safety,pe.textContent=n.submit,le.textContent=n.cancel,xe.textContent=n.newQuestion,Oe.textContent=n.copy,Ne.textContent=n.convert,Xe.textContent=n.answerTitle,Qe.textContent=n.sourcesTitle,ee.textContent=n.stale,A.textContent=n.convertedTitle,N.textContent=n.convertedBody,B.textContent=n.dataSummary(E.targetCount,E.sourceCount),yt(),Ze(g),r!==void 0&&tt(r,!ee.hidden)}function Ze(o){g=o;let C=R.value;if(R.replaceChildren(),U.close(),w.hidden=!0,w.textContent="",o===void 0){let f=t.createElement("option");f.textContent=n.loadingExecutors,f.value="",R.append(f)}else if(!o.enabled||o.executors.length===0){let f=t.createElement("option");f.textContent=n.noExecutor,f.value="",R.append(f)}else{let f=o.executors.filter(p=>p.state==="ready"&&p.readOnlyProven),h=o.executors.filter(p=>p.state!=="ready"||!p.readOnlyProven);for(let p of f){let V=t.createElement("option");V.value=p.executorId,V.textContent=p.models===void 0?`${p.label} · ${p.effectiveModelLabel}`:p.label,R.append(V)}if(f.length===0){let p=t.createElement("option");p.textContent=n.noExecutor,p.value="",R.append(p)}R.value=f.some(p=>p.executorId===C)?C:f[0]?.executorId??"",h.length>0&&(w.textContent=h.map(p=>`${p.label}: ${n.error(p.errorCode)}`).join(" "),w.hidden=!1)}U.rebuild(),Ge(),M()}function et(o){a=o,j.hidden=!1,z.hidden=!0,Ie.textContent=n.status[o.status],["answered","cancelled","failed"].includes(o.status)?(b=!1,e.onExecutionChange()):e.onExecutionChange({scene:"running",tone:"running",headline:n.status[o.status],expandedHeadline:n.status[o.status],action:n.safety,expandedAction:n.safety,meta:`${o.executor.label} · ${o.executor.modelLabel}`,recentActivities:Object.freeze([]),startedAt:o.createdAt}),M()}function kt(o){if(o.type==="snapshot"){et(o.snapshot);return}if(o.type==="phase"&&(Ie.textContent=n.status[o.status]),o.type==="read-activity"&&o.state==="started"){let C=c(t,"span");for(C.textContent=o.activity.kind==="source"?n.readSource(o.activity.relativePath):n.readFiles(o.activity.bucket),Y.append(C);Y.childElementCount>5;)Y.firstElementChild?.remove();if(a!==void 0){let f=C.textContent;e.onExecutionChange({scene:"running",tone:"running",headline:n.status.running,expandedHeadline:n.status.running,action:f,expandedAction:f,meta:`${a.executor.label} · ${a.executor.modelLabel}`,activity:{key:`ask:${String(o.sequence)}`,kind:"read",label:f,state:"active"},recentActivities:Object.freeze([]),startedAt:a.createdAt})}}}function tt(o,C){r=o,a=void 0,e.onExecutionChange();let f=new Map(o.sources.map(h=>[h.sourceId,h]));Q.replaceChildren(),Re.replaceChildren(),me.replaceChildren(),ee.hidden=!C;for(let h of o.warnings){let p=c(t,"div");p.className="spotpatch-ask-warning",p.textContent=n.warning(h.code),Re.append(p)}for(let h of o.blocks)if(h.kind==="paragraph"){let p=c(t,"p");p.textContent=h.text,Q.append(p),He(t,Q,h.sourceIds,f,n)}else if(h.kind==="code"){let p=c(t,"pre"),V=c(t,"code");h.language!==void 0&&(V.dataset.language=h.language),V.textContent=h.code,p.append(V),Q.append(p),He(t,Q,h.sourceIds,f,n)}else{let p=c(t,"ul");for(let V of h.items){let De=c(t,"li");De.textContent=V.text,He(t,De,V.sourceIds,f,n),p.append(De)}Q.append(p)}for(let h of o.sources){let p=K(t,n.sourceLabel(h.relativePath,h.startLine,h.endLine),"spotpatch-ask-source");p.dataset.askSourceId=h.sourceId,p.title=h.label,me.append(p)}Ae.hidden=o.sources.length===0,Z.hidden=!1,j.hidden=!0,b=!1,M(),e.onViewChange()}function Et(){if(r===void 0)return"";let o=r.blocks.flatMap(f=>f.kind==="paragraph"?[f.text]:f.kind==="code"?[f.code]:f.items.map(h=>`- ${h.text}`)).join(`
57
58
 
58
- `),d=r.sources.map(p=>o.sourceLabel(p.relativePath,p.startLine,p.endLine)).join(`
59
- `);return d.length===0?n:`${n}
59
+ `),C=r.sources.map(f=>n.sourceLabel(f.relativePath,f.startLine,f.endLine)).join(`
60
+ `);return C.length===0?o:`${o}
60
61
 
61
- ${o.sourcesTitle}
62
- ${d}`}function Tt(){r=void 0,c=void 0,e.onExecutionChange(),_.value="",ee.hidden=!0,B.hidden=!0,W.hidden=!0,Z.replaceChildren(),te.hidden=!0,b=!1,P(),e.onViewChange()}q.addEventListener("click",()=>{a="ask",fe(),_.focus({preventScroll:!0})}),M.addEventListener("click",()=>{a="change",fe()}),_.addEventListener("input",P),y.addEventListener("change",P),T.addEventListener("click",()=>{g.hidden?Ge():ne()}),T.addEventListener("keydown",n=>{n.key!=="ArrowDown"&&n.key!=="ArrowUp"||(n.preventDefault(),Ge(!0))}),g.addEventListener("keydown",n=>{let d=[...g.querySelectorAll(".spotpatch-ask-executor-option")];if(n.key==="Escape"){n.preventDefault(),ne(!0);return}if(!["ArrowDown","ArrowUp","Home","End"].includes(n.key))return;n.preventDefault();let p=d.indexOf(t.activeElement),A=n.key==="Home"?0:n.key==="End"?d.length-1:n.key==="ArrowDown"?(p+1+d.length)%d.length:(p-1+d.length)%d.length;d[A]?.focus({preventScroll:!0})}),V.addEventListener("focusout",n=>{(!(n.relatedTarget instanceof Node)||!V.contains(n.relatedTarget))&&ne()});let ot=n=>{n.composedPath().includes(V)||ne()};t.addEventListener("pointerdown",ot),z.addEventListener("change",P);let _t=e.subscribeLocale(Ze);return Ze(),fe(),Object.freeze({root:D,styles:Jt(t),questionInput:_,executorSelect:y,consentCheckbox:z,submitButton:pe,cancelButton:ue,newQuestionButton:be,copyButton:ve,convertButton:Ne,clear:Tt,dispose:()=>{_t(),t.removeEventListener("pointerdown",ot)},focusQuestion:()=>{_.focus({preventScroll:!0})},mode:()=>a,notify(n){let d=n==="copied"?o.copied:n==="copy-failed"?o.copyFailed:n==="converted"?o.converted:o.sourceOpenFailed;e.announce(d)},readConsent:()=>z.checked,readExecutorId:()=>y.value||void 0,readQuestion:()=>_.value.trim(),renderAnswer:nt,renderCapability:et,renderError(n){c=void 0,e.onExecutionChange(),W.textContent=o.error(n),W.hidden=!1,B.hidden=!0,b=!1,P(),e.onViewChange()},renderEvent:St,renderJob:tt,selectedSourceId(n){return n instanceof Element?n.closest("[data-ask-source-id]")?.dataset.askSourceId:void 0},setBusy(n){b=n,n&&(B.hidden=!1,W.hidden=!0,ee.hidden=!0,Z.replaceChildren()),P()},setConsent(n){z.checked=n,P()},setMode(n){a=n,fe()},setOrigin(n){E.dataset.active=String(n!==void 0),E.hidden=a==="ask"||n===void 0,e.onViewChange()},setSelectionPreview(n){w=n,le.textContent=o.dataSummary(n.targetCount,n.sourceCount),P()},setSelectionVisible(n){D.hidden=!n,n&&fe()},sourceById:n=>r?.sources.find(d=>d.sourceId===n),answerPlainText:wt})}var qt=Object.freeze({createPanel:yt,createWorkflow:xt});function Et(){At(qt)}Et();
62
+ ${n.sourcesTitle}
63
+ ${C}`}function Ct(){r=void 0,a=void 0,e.onExecutionChange(),I.value="",Z.hidden=!0,j.hidden=!0,z.hidden=!0,Y.replaceChildren(),ee.hidden=!0,b=!1,M(),e.onViewChange()}l.addEventListener("click",()=>{s="ask",ue(),I.focus({preventScroll:!0})}),m.addEventListener("click",()=>{s="change",ue()}),I.addEventListener("input",M),R.addEventListener("change",()=>{Ge(),M(),e.onViewChange()}),X.addEventListener("change",M);let St=e.subscribeLocale(Ye);return Ye(),ue(),Object.freeze({root:P,styles:Mt(t),questionInput:I,executorSelect:R,consentCheckbox:X,submitButton:pe,cancelButton:le,newQuestionButton:xe,copyButton:Oe,convertButton:Ne,clear:Ct,dispose:()=>{St(),U.dispose(),i.dispose()},focusQuestion:()=>{I.focus({preventScroll:!0})},mode:()=>s,notify(o){let C=o==="copied"?n.copied:o==="copy-failed"?n.copyFailed:o==="converted"?n.converted:n.sourceOpenFailed;e.announce(C)},readConsent:()=>X.checked,readExecutorId:()=>R.value||void 0,readModel:()=>i.select.value||void 0,readQuestion:()=>I.value.trim(),renderAnswer:tt,renderCapability:Ze,renderError(o){a=void 0,e.onExecutionChange(),z.textContent=n.error(o),z.hidden=!1,j.hidden=!0,b=!1,M(),e.onViewChange()},renderEvent:kt,renderJob:et,selectedSourceId(o){return o instanceof Element?o.closest("[data-ask-source-id]")?.dataset.askSourceId:void 0},setBusy(o){b=o,o&&(j.hidden=!1,z.hidden=!0,Z.hidden=!0,Y.replaceChildren()),M()},setConsent(o){X.checked=o,M()},setMode(o){s=o,ue()},setOrigin(o){u.dataset.active=String(o!==void 0),u.hidden=s==="ask"||o===void 0,e.onViewChange()},setSelectionPreview(o){E=o,B.textContent=n.dataSummary(o.targetCount,o.sourceCount),M()},setSelectionVisible(o){P.hidden=!o,o&&ue()},sourceById:o=>r?.sources.find(C=>C.sourceId===o),answerPlainText:Et})}var Ut=Object.freeze({createPanel:xt,createWorkflow:gt});function At(){ht(Ut)}At();
@@ -1,5 +1,5 @@
1
- var M="data-spotpatch-ui",re=Object.freeze({highlight:2147483646,controls:2147483647}),se=Object.freeze({compactInset:8,compactViewportWidth:520,desktopInset:24,dragActivationDistance:6,edgeSnapDistance:20,workbenchMaxHeight:620,workbenchMaxWidth:460});function u(e,t){let n=e.createElement(t);return n.setAttribute(M,""),n}function C(e,t,n=""){let o=u(e,"button");return o.type="button",o.className=n,o.textContent=t,o}var j=Object.freeze({"zh-CN":Object.freeze({bindings:"数据去向",changes:"修改说明",componentEmpty:"当前组件没有找到可证明的接口。未找到不等于没有请求。",componentTab:"数据链路",componentTitle:"组件数据链路",consumed:"读取字段",declared:"代码声明,尚未在本次页面会话中观测",diagnostics:"诊断",disabled:"数据链路能力未启用,请在插件配置中设置 dataFlow: {}。",error:"数据链路报告加载失败",evidence:"证据",loading:"正在分析源码并合并运行时证据…",logicalObserved:"本次会话已进入 tRPC 调用链",noParameters:"未提取到可证明的参数键",observed:"本次会话已实际请求",pageEmpty:"当前已选页面范围内没有静态接口或运行时网络记录。",pageTab:"页面接口",pageTitle:"页面接口",parameters:"请求参数",refresh:"刷新证据",unknown:"未知"}),"en-US":Object.freeze({bindings:"Data destinations",changes:"Changes",componentEmpty:"No proven interface was found for this component. This does not prove that no request exists.",componentTab:"Data flow",componentTitle:"Component data flow",consumed:"Consumed fields",declared:"Declared in code, not observed in this page session",diagnostics:"Diagnostics",disabled:"Data flow is disabled. Set dataFlow: {} in the plugin options.",error:"Failed to load the data-flow report",evidence:"Evidence",loading:"Analyzing source and merging runtime evidence…",logicalObserved:"Dispatched through the tRPC link in this session",noParameters:"No proven parameter keys were extracted",observed:"Actually requested in this session",pageEmpty:"No static interface or runtime traffic is available for the selected page scope.",pageTab:"Page APIs",pageTitle:"Page interfaces",parameters:"Request parameters",refresh:"Refresh evidence",unknown:"Unknown"})});function F(e,t,n){let o=u(e,"span");return o.className="spotpatch-data-flow-badge",o.dataset.tone=n,o.textContent=t,o}function O(e,t,n){let o=u(e,"div");o.className="spotpatch-data-flow-detail";let a=u(e,"span");a.textContent=t;let i=u(e,"code");return i.textContent=n,o.append(a,i),o}function K(e,t,n){let o=u(e,"article");o.className="spotpatch-data-flow-card";let a=u(e,"div");a.className="spotpatch-data-flow-card-head";let i=u(e,"div");i.className="spotpatch-data-flow-endpoint";let r=u(e,"strong");r.textContent=t.method??n.unknown;let f=u(e,"code");f.textContent=t.url===void 0?t.operation??n.unknown:`${t.url.origin??""}${t.url.pathname}`,i.append(r,f);let c=u(e,"div");c.className="spotpatch-data-flow-badges",c.append(F(e,t.execution==="observed"?t.kind==="rpc"?n.logicalObserved:n.observed:n.declared,t.execution==="observed"?"success":"neutral"),F(e,t.proof,t.proof==="proven"?"proof":"warning"),F(e,t.association,"neutral")),a.append(i,c);let m=t.parameters.length===0?n.noParameters:t.parameters.map(g=>`${g.position}.${g.path}${g.type===void 0?"":`: ${g.type}`}${g.sensitive?" [sensitive]":""}${g.condition===void 0?"":` [when ${g.condition}]`}`).join(`
2
- `),A=t.response.consumedFields.length===0?n.unknown:t.response.consumedFields.join(", "),S=t.suppliedBindings.length===0?n.unknown:t.suppliedBindings.join(", "),h=u(e,"div");h.className="spotpatch-data-flow-card-body";let E=new Set(t.observationIds),b=t.evidenceIds.filter(g=>!E.has(g)).length;return h.append(O(e,n.parameters,m),O(e,n.consumed,A),O(e,n.bindings,S),O(e,n.evidence,`${String(b)} static · ${String(t.observationIds.length)} runtime`)),o.append(a,h),o}function z(e,t){let n=u(e,"section");n.className="spotpatch-data-flow-panel";let o=u(e,"h3");o.textContent=t;let a=u(e,"p");a.className="spotpatch-data-flow-status";let i=u(e,"div");return i.className="spotpatch-data-flow-list",n.append(o,a,i),Object.freeze({root:n,status:a,list:i})}function q(e,t,n,o,a,i){let r=j[n()],f=z(e,r.componentTitle),c=z(e,r.pageTitle),m=C(e,r.refresh),A=e.createElement("style");A.textContent=W,m.classList.add("spotpatch-data-flow-refresh"),f.root.prepend(m);let S=u(e,"div"),h=u(e,"nav");h.className="spotpatch-view-tabs",h.setAttribute("aria-label","SpotPatch views"),h.setAttribute("role","tablist");let E=new Map([["changes",o],["component-data",f.root],["page-data",c.root],["diagnostics",a]]),b=new Map,g="changes";for(let s of E.keys()){let l=C(e,"");l.dataset.viewId=s,l.id=`spotpatch-view-${s}-tab`,l.setAttribute("role","tab"),l.setAttribute("aria-selected",String(s===g));let p=E.get(s);p?.setAttribute("aria-labelledby",l.id),p?.setAttribute("role","tabpanel"),!t&&(s==="component-data"||s==="page-data")&&(l.hidden=!0),b.set(s,l),h.append(l)}S.append(h,...E.values());function w(s){if(E.has(s)){g=s;for(let[l,p]of E){p.hidden=l!==s;let y=b.get(l);y?.setAttribute("aria-selected",String(l===s)),y!==void 0&&(y.tabIndex=l===s?0:-1)}i()}}function D(s){if(!(s.target instanceof HTMLButtonElement))return;let l=s.target.dataset.viewId;l!==void 0&&w(l)}h.addEventListener("click",D),w(g);function T(s,l,p){if(s.list.replaceChildren(),s.status.dataset.state=l.status,!t||l.status==="disabled"){s.status.textContent=r.disabled;return}if(l.status==="loading"){s.status.textContent=r.loading;return}if(l.status==="error"){s.status.textContent=l.message??r.error;return}let y=l.report,L=y===void 0?"":[...new Set(y.diagnostics.map(({code:v})=>v))].join(", "),P=L.length===0?"":` · ${r.diagnostics}: ${L}`;if(y===void 0||y.dependencies.length===0){s.status.textContent=`${p}${P}`;return}s.status.textContent=`${String(y.dependencies.length)} · ${y.completeness.complete?"complete":"partial"}${P}`,s.list.append(...y.dependencies.map(v=>K(e,v,r)))}return Object.freeze({root:S,refreshButton:m,styles:A,dispose(){h.removeEventListener("click",D)},render(s){r=j[n()];let l=[r.changes,r.componentTab,r.pageTab,r.diagnostics];[...b.values()].forEach((p,y)=>{p.textContent=l[y]??""}),m.textContent=`${r.refresh} · ${String(s.observationCount)}`,m.disabled=!t||s.component.status==="loading",T(f,s.component,r.componentEmpty),T(c,s.page,r.pageEmpty)},resetView(){w("changes")}})}var W=`
1
+ var M="data-spotpatch-ui",re=Object.freeze({highlight:2147483646,controls:2147483647}),se=Object.freeze({compactInset:8,compactViewportWidth:520,desktopInset:24,dragActivationDistance:6,edgeSnapDistance:20,workbenchMaxHeight:620,workbenchMaxWidth:460});function u(e,t){let n=e.createElement(t);return n.setAttribute(M,""),n}function F(e,t,n=""){let o=u(e,"button");return o.type="button",o.className=n,o.textContent=t,o}var j=Object.freeze({"zh-CN":Object.freeze({server:"服务端(静态证据)",client:"浏览器",bindings:"数据去向",changes:"修改说明",componentEmpty:"当前组件没有找到可证明的接口。未找到不等于没有请求。",componentTab:"数据链路",componentTitle:"组件数据链路",consumed:"读取字段",declared:"代码声明,尚未在本次页面会话中观测",diagnostics:"诊断",disabled:"数据链路能力未启用,请在插件配置中设置 dataFlow: {}。",error:"数据链路报告加载失败",evidence:"证据",loading:"正在分析源码并合并运行时证据…",logicalObserved:"本次会话已进入 tRPC 调用链",noParameters:"未提取到可证明的参数键",observed:"本次会话已实际请求",pageEmpty:"当前已选页面范围内没有静态接口或运行时网络记录。",pageTab:"页面接口",pageTitle:"页面接口",parameters:"请求参数",refresh:"刷新证据",unknown:"未知"}),"en-US":Object.freeze({server:"Server (static evidence)",client:"Browser",bindings:"Data destinations",changes:"Changes",componentEmpty:"No proven interface was found for this component. This does not prove that no request exists.",componentTab:"Data flow",componentTitle:"Component data flow",consumed:"Consumed fields",declared:"Declared in code, not observed in this page session",diagnostics:"Diagnostics",disabled:"Data flow is disabled. Set dataFlow: {} in the plugin options.",error:"Failed to load the data-flow report",evidence:"Evidence",loading:"Analyzing source and merging runtime evidence…",logicalObserved:"Dispatched through the tRPC link in this session",noParameters:"No proven parameter keys were extracted",observed:"Actually requested in this session",pageEmpty:"No static interface or runtime traffic is available for the selected page scope.",pageTab:"Page APIs",pageTitle:"Page interfaces",parameters:"Request parameters",refresh:"Refresh evidence",unknown:"Unknown"})});function v(e,t,n){let o=u(e,"span");return o.className="spotpatch-data-flow-badge",o.dataset.tone=n,o.textContent=t,o}function O(e,t,n){let o=u(e,"div");o.className="spotpatch-data-flow-detail";let a=u(e,"span");a.textContent=t;let s=u(e,"code");return s.textContent=n,o.append(a,s),o}function W(e,t,n){let o=u(e,"article");o.className="spotpatch-data-flow-card";let a=u(e,"div");a.className="spotpatch-data-flow-card-head";let s=u(e,"div");s.className="spotpatch-data-flow-endpoint";let r=u(e,"strong");r.textContent=t.method??n.unknown;let f=u(e,"code");f.textContent=t.url===void 0?t.operation??n.unknown:`${t.url.origin??""}${t.url.pathname}`,s.append(r,f);let c=u(e,"div");c.className="spotpatch-data-flow-badges",c.append(v(e,t.execution==="observed"?t.kind==="rpc"?n.logicalObserved:n.observed:n.declared,t.execution==="observed"?"success":"neutral"),v(e,t.proof,t.proof==="proven"?"proof":"warning"),v(e,t.association,"neutral")),a.append(s,c),t.environment!==void 0&&c.append(v(e,n[t.environment],"neutral"));let m=t.parameters.length===0?n.noParameters:t.parameters.map(g=>`${g.position}.${g.path}${g.type===void 0?"":`: ${g.type}`}${g.sensitive?" [sensitive]":""}${g.condition===void 0?"":` [when ${g.condition}]`}`).join(`
2
+ `),A=t.response.consumedFields.length===0?n.unknown:t.response.consumedFields.join(", "),S=t.suppliedBindings.length===0?n.unknown:t.suppliedBindings.join(", "),h=u(e,"div");h.className="spotpatch-data-flow-card-body";let b=new Set(t.observationIds),E=t.evidenceIds.filter(g=>!b.has(g)).length;return h.append(O(e,n.parameters,m),O(e,n.consumed,A),O(e,n.bindings,S),O(e,n.evidence,`${String(E)} static · ${String(t.observationIds.length)} runtime`)),o.append(a,h),o}function z(e,t){let n=u(e,"section");n.className="spotpatch-data-flow-panel";let o=u(e,"h3");o.textContent=t;let a=u(e,"p");a.className="spotpatch-data-flow-status";let s=u(e,"div");return s.className="spotpatch-data-flow-list",n.append(o,a,s),Object.freeze({root:n,status:a,list:s})}function q(e,t,n,o,a,s){let r=j[n()],f=z(e,r.componentTitle),c=z(e,r.pageTitle),m=F(e,r.refresh),A=e.createElement("style");A.textContent=K,m.classList.add("spotpatch-data-flow-refresh"),f.root.prepend(m);let S=u(e,"div"),h=u(e,"nav");h.className="spotpatch-view-tabs",h.setAttribute("aria-label","SpotPatch views"),h.setAttribute("role","tablist");let b=new Map([["changes",o],["component-data",f.root],["page-data",c.root],["diagnostics",a]]),E=new Map,g="changes";for(let i of b.keys()){let l=F(e,"");l.dataset.viewId=i,l.id=`spotpatch-view-${i}-tab`,l.setAttribute("role","tab"),l.setAttribute("aria-selected",String(i===g));let p=b.get(i);p?.setAttribute("aria-labelledby",l.id),p?.setAttribute("role","tabpanel"),!t&&(i==="component-data"||i==="page-data")&&(l.hidden=!0),E.set(i,l),h.append(l)}S.append(h,...b.values());function w(i){if(b.has(i)){g=i;for(let[l,p]of b){p.hidden=l!==i;let y=E.get(l);y?.setAttribute("aria-selected",String(l===i)),y!==void 0&&(y.tabIndex=l===i?0:-1)}s()}}function D(i){if(!(i.target instanceof HTMLButtonElement))return;let l=i.target.dataset.viewId;l!==void 0&&w(l)}h.addEventListener("click",D),w(g);function T(i,l,p){if(i.list.replaceChildren(),i.status.dataset.state=l.status,!t||l.status==="disabled"){i.status.textContent=r.disabled;return}if(l.status==="loading"){i.status.textContent=r.loading;return}if(l.status==="error"){i.status.textContent=l.message??r.error;return}let y=l.report,L=y===void 0?"":[...new Set(y.diagnostics.map(({code:C})=>C))].join(", "),P=L.length===0?"":` · ${r.diagnostics}: ${L}`;if(y===void 0||y.dependencies.length===0){i.status.textContent=`${p}${P}`;return}i.status.textContent=`${String(y.dependencies.length)} · ${y.completeness.complete?"complete":"partial"}${P}`,i.list.append(...y.dependencies.map(C=>W(e,C,r)))}return Object.freeze({root:S,refreshButton:m,styles:A,dispose(){h.removeEventListener("click",D)},render(i){r=j[n()];let l=[r.changes,r.componentTab,r.pageTab,r.diagnostics];[...E.values()].forEach((p,y)=>{p.textContent=l[y]??""}),m.textContent=`${r.refresh} · ${String(i.observationCount)}`,m.disabled=!t||i.component.status==="loading",T(f,i.component,r.componentEmpty),T(c,i.page,r.pageEmpty)},resetView(){w("changes")}})}var K=`
3
3
  .spotpatch-view-tabs { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 4px; margin-bottom: 12px; padding: 3px; border: 1px solid rgb(255 255 255 / 7%); border-radius: 9px; background: rgb(3 7 18 / 42%); }
4
4
  .spotpatch-view-tabs button { min-width: 0; border: 0; border-radius: 7px; padding: 7px 5px; color: var(--spotpatch-text-muted); background: transparent; cursor: pointer; font-size: 10.5px; }
5
5
  .spotpatch-view-tabs button[aria-selected="true"] { color: #f8fafc; background: rgb(139 124 247 / 18%); }
@@ -23,4 +23,4 @@ var M="data-spotpatch-ui",re=Object.freeze({highlight:2147483646,controls:214748
23
23
  .spotpatch-data-flow-detail { display: grid; grid-template-columns: 82px minmax(0, 1fr); gap: 8px; align-items: start; }
24
24
  .spotpatch-data-flow-detail > span { color: var(--spotpatch-text-muted); font-size: 10px; }
25
25
  .spotpatch-data-flow-detail > code { overflow-wrap: anywhere; color: #cbd5e1; font: 10px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; }
26
- `;var V=Symbol.for("spotpatch.data-flow.extension.v1");function H(e,t=globalThis){t[V]=e}var d=Object.freeze({observationMaxEntries:100,observationMaxBytes:262144,observationTtlMs:3e5,protocolRequestMaxBytes:32768,reportMaxBytes:131072,reportMaxEvidence:200,reportMaxDiagnostics:256,capabilityMaxReasons:64,graphMaxDepth:5,graphMaxModules:50,graphMaxCallsites:100,analysisTimeoutMs:2e3,reportMaxFields:100,sourceMaxComponents:256}),fe=d.reportMaxFields,me=Object.freeze({observationMaxEntries:d.observationMaxEntries,observationMaxBytes:d.observationMaxBytes,observationTtlMs:d.observationTtlMs,reportMaxBytes:d.reportMaxBytes});var G=Symbol.for("spotpatch.data-flow.runtime.v1");function _(e=globalThis){return e[G]}var $=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]);function J(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function I(e){let t=J(e);return $.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function R(e,t){return Object.freeze(e.slice(0,Math.max(0,t)))}function Y(e){let t=e.url===void 0?void 0:R(e.url.queryKeys,d.reportMaxFields),n=R(e.parameters,d.reportMaxFields).map(m=>Object.freeze({...m,evidenceIds:R(m.evidenceIds,d.reportMaxEvidence)})),o=R(e.response.consumedFields,d.reportMaxFields),a=R(e.suppliedBindings,d.graphMaxCallsites),i=R(e.locationIds,d.graphMaxCallsites),r=R(e.evidenceIds,d.reportMaxEvidence),f=R(e.observationIds,d.observationMaxEntries);return t?.length!==e.url?.queryKeys.length||n.length!==e.parameters.length||n.some((m,A)=>m.evidenceIds.length!==e.parameters[A]?.evidenceIds.length)||o.length!==e.response.consumedFields.length||a.length!==e.suppliedBindings.length||i.length!==e.locationIds.length||r.length!==e.evidenceIds.length||f.length!==e.observationIds.length?Object.freeze({dependency:Object.freeze({...e,...e.url===void 0?{}:{url:Object.freeze({...e.url,queryKeys:t??Object.freeze([])})},parameters:Object.freeze(n),response:Object.freeze({consumedFields:o}),suppliedBindings:a,locationIds:i,evidenceIds:r,observationIds:f}),trimmed:!0}):Object.freeze({dependency:e,trimmed:!1})}function Q(e,t){return Object.freeze([...new Set([...e.flatMap(n=>[...n.evidenceIds,...n.parameters.flatMap(o=>o.evidenceIds)]),...t.flatMap(n=>n.evidenceIds)])])}function Z(e,t,n){let o=new Map(e.map(r=>[r.id,r])),a=[],i=new Set;for(let r of t){let f=o.get(r);f!==void 0&&!i.has(r)&&(a.push(f),i.add(r))}if(n)for(let r of e)i.has(r.id)||a.push(r);return R(a,d.reportMaxEvidence)}function ee(e,t){return Object.freeze({...e,parameters:Object.freeze(e.parameters.map(n=>Object.freeze({...n,evidenceIds:Object.freeze(n.evidenceIds.filter(o=>t.has(o)))}))),evidenceIds:Object.freeze(e.evidenceIds.filter(n=>t.has(n)))})}function te(e){return e==="analysis"?"DATA_FLOW_ANALYSIS_TRUNCATED":"DATA_FLOW_OBSERVATION_DROPPED"}function x(e,t={}){let n=Math.min(Math.max(0,t.maximumDependencies??d.graphMaxCallsites),d.graphMaxCallsites),o=R(e.dependencies,n).map(Y),a=o.map(({dependency:p})=>p),i=R(e.baseline.analyzedSourceVersions,d.graphMaxModules),r=e.dependencies.length>a.length||o.some(({trimmed:p})=>p)||e.baseline.analyzedSourceVersions.length>i.length||e.capability.reasons.length>d.capabilityMaxReasons||e.evidence.length>d.reportMaxEvidence||e.diagnostics.length>d.reportMaxDiagnostics;if(!(t.forceTruncation===!0||r))return e;let c=t.mode??"analysis",m=te(c),A=`${e.reportId}_collection_${c}`,S=Object.freeze([...e.capability.reasons.filter(p=>p.code!==m).slice(0,d.capabilityMaxReasons-1),Object.freeze({code:m,retryable:!1})]),h=Object.freeze([...e.diagnostics.filter(p=>p.id!==A).slice(0,d.reportMaxDiagnostics-1),Object.freeze({id:A,code:m,severity:"warning",retryable:!1,evidenceIds:Object.freeze([])})]),E=Q(a,h),b=Z(e.evidence,E,e.dependencies.length===a.length),g=new Set(b.map(({id:p})=>p)),w=Object.freeze(a.map(p=>ee(p,g))),D=Object.freeze(h.map(p=>Object.freeze({...p,evidenceIds:Object.freeze(p.evidenceIds.filter(y=>g.has(y)))}))),T=e.dependencies.length-a.length,s=e.baseline.analyzedSourceVersions.length-i.length,l=s>0&&T===0?"modules":"callsites";return Object.freeze({...e,baseline:Object.freeze({...e.baseline,analyzedSourceVersions:i}),capability:Object.freeze({...e.capability,...c==="analysis"&&e.capability.staticAnalysis==="available"?{staticAnalysis:"partial"}:{},reasons:S}),dependencies:w,evidence:b,diagnostics:D,...c==="analysis"?{completeness:Object.freeze({...e.completeness,complete:!1,frontierCount:e.completeness.frontierCount+T+s+(r&&T===0&&s===0?1:0),truncatedBy:t.truncatedBy??e.completeness.truncatedBy??l})}:{}})}function ne(e,t){let n=t.origin;return!(t.kind==="rpc"?e.transport==="trpc"&&t.operation!==void 0&&e.operation===t.operation:t.kind==="http"?e.transport==="fetch"||e.transport==="xhr":!1)||e.freshness!=="current"||n===void 0||e.requestCallsiteId!==n.requestCallsiteId||e.sourceVersion!==n.sourceVersion||t.method!==void 0&&e.method.toUpperCase()!==t.method.toUpperCase()||t.url!==void 0&&e.url.pathname!==t.url.pathname||t.url?.origin!==void 0&&e.url.origin!==t.url.origin||n.componentSourceId!==void 0&&e.componentSourceId!==void 0&&e.componentSourceId!==n.componentSourceId||n.triggerCallsiteId!==void 0&&e.triggerCallsiteId!==void 0&&e.triggerCallsiteId!==n.triggerCallsiteId?!1:t.association!=="transitive"||e.componentSourceId===n.componentSourceId&&e.triggerCallsiteId===n.triggerCallsiteId}function oe(e){return Object.freeze({id:e.id,kind:"runtime-observation",summaryKey:"dataFlow.evidence.runtimeDispatch"})}function U(e,t){let n=new Set,o=e.map(a=>{let i=t.filter(c=>ne(c,a));for(let c of i)n.add(c.id);if(i.length===0)return a;let r=[...new Set(i.flatMap(({url:c})=>c.origin===void 0?[]:[c.origin]))],f=r.length===1?r[0]:void 0;return Object.freeze({...a,...a.url===void 0||a.url.origin!==void 0||f===void 0?{}:{url:Object.freeze({...a.url,origin:f})},execution:"observed",observationIds:Object.freeze([...new Set([...a.observationIds,...i.map(({id:c})=>c)])]),evidenceIds:Object.freeze([...new Set([...a.evidenceIds,...i.map(({id:c})=>c)])])})});return Object.freeze({dependencies:Object.freeze(o),matchedObservationIds:n})}function B(e,t,n){let o=new Set(e.map(({id:a})=>a));return Object.freeze([...e,...t.flatMap(a=>n.has(a.id)&&!o.has(a.id)?[oe(a)]:[])])}function k(e,t){let n=t.filter(a=>a.componentSourceId===void 0||a.componentSourceId===e.component.componentSourceId),o=U(e.dependencies,n);return x(Object.freeze({...e,dependencies:o.dependencies,evidence:B(e.evidence,n,o.matchedObservationIds)}),{mode:"observation"})}function ae(e){let t=e.transport==="trpc";return Object.freeze({id:e.id,kind:t?"rpc":"http",direction:e.method==="GET"||e.method==="HEAD"||e.method==="QUERY"||e.method==="SUBSCRIPTION"?"read":"write",execution:"observed",proof:"unavailable",association:"unassigned",method:e.method,...t?e.operation===void 0?{}:{operation:e.operation}:{url:e.url},parameters:Object.freeze((t?[]:e.url.queryKeys).map(n=>Object.freeze({path:n,position:"query",sensitive:I(n),valueState:"not-collected",evidenceIds:Object.freeze([e.id])}))),response:Object.freeze({consumedFields:Object.freeze([])}),suppliedBindings:Object.freeze([]),locationIds:Object.freeze([]),evidenceIds:Object.freeze([e.id]),observationIds:Object.freeze([e.id])})}function N(e,t){let n=t.filter(({freshness:r})=>r==="current"),o=U(e.dependencies,n),a=n.filter(({id:r})=>!o.matchedObservationIds.has(r)).map(ae),i=new Set(n.map(({id:r})=>r));return x(Object.freeze({...e,dependencies:Object.freeze([...o.dependencies,...a]),evidence:B(e.evidence,n,i)}),{mode:"observation"})}function X(){H(Object.freeze({createPanel:q,getComponentRegistration(e){return _()?.getComponentRegistration(e)},observations(e){let t=_();return t?.updateRoute(e),t?.observations()??Object.freeze([])},mergeComponentReport:k,mergePageReport:N}))}X();
26
+ `;var V=Symbol.for("spotpatch.data-flow.extension.v1");function H(e,t=globalThis){t[V]=e}var d=Object.freeze({observationMaxEntries:100,observationMaxBytes:262144,observationTtlMs:3e5,protocolRequestMaxBytes:32768,reportMaxBytes:131072,reportMaxEvidence:200,reportMaxDiagnostics:256,capabilityMaxReasons:64,graphMaxDepth:5,graphMaxModules:50,graphMaxCallsites:100,analysisTimeoutMs:2e3,reportMaxFields:100,sourceMaxComponents:256}),fe=d.reportMaxFields,me=Object.freeze({observationMaxEntries:d.observationMaxEntries,observationMaxBytes:d.observationMaxBytes,observationTtlMs:d.observationTtlMs,reportMaxBytes:d.reportMaxBytes});var G=Symbol.for("spotpatch.data-flow.runtime.v1");function x(e=globalThis){return e[G]}var $=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]);function J(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function I(e){let t=J(e);return $.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function R(e,t){return Object.freeze(e.slice(0,Math.max(0,t)))}function Y(e){let t=e.url===void 0?void 0:R(e.url.queryKeys,d.reportMaxFields),n=R(e.parameters,d.reportMaxFields).map(m=>Object.freeze({...m,evidenceIds:R(m.evidenceIds,d.reportMaxEvidence)})),o=R(e.response.consumedFields,d.reportMaxFields),a=R(e.suppliedBindings,d.graphMaxCallsites),s=R(e.locationIds,d.graphMaxCallsites),r=R(e.evidenceIds,d.reportMaxEvidence),f=R(e.observationIds,d.observationMaxEntries);return t?.length!==e.url?.queryKeys.length||n.length!==e.parameters.length||n.some((m,A)=>m.evidenceIds.length!==e.parameters[A]?.evidenceIds.length)||o.length!==e.response.consumedFields.length||a.length!==e.suppliedBindings.length||s.length!==e.locationIds.length||r.length!==e.evidenceIds.length||f.length!==e.observationIds.length?Object.freeze({dependency:Object.freeze({...e,...e.url===void 0?{}:{url:Object.freeze({...e.url,queryKeys:t??Object.freeze([])})},parameters:Object.freeze(n),response:Object.freeze({consumedFields:o}),suppliedBindings:a,locationIds:s,evidenceIds:r,observationIds:f}),trimmed:!0}):Object.freeze({dependency:e,trimmed:!1})}function Q(e,t){return Object.freeze([...new Set([...e.flatMap(n=>[...n.evidenceIds,...n.parameters.flatMap(o=>o.evidenceIds)]),...t.flatMap(n=>n.evidenceIds)])])}function Z(e,t,n){let o=new Map(e.map(r=>[r.id,r])),a=[],s=new Set;for(let r of t){let f=o.get(r);f!==void 0&&!s.has(r)&&(a.push(f),s.add(r))}if(n)for(let r of e)s.has(r.id)||a.push(r);return R(a,d.reportMaxEvidence)}function ee(e,t){return Object.freeze({...e,parameters:Object.freeze(e.parameters.map(n=>Object.freeze({...n,evidenceIds:Object.freeze(n.evidenceIds.filter(o=>t.has(o)))}))),evidenceIds:Object.freeze(e.evidenceIds.filter(n=>t.has(n)))})}function te(e){return e==="analysis"?"DATA_FLOW_ANALYSIS_TRUNCATED":"DATA_FLOW_OBSERVATION_DROPPED"}function _(e,t={}){let n=Math.min(Math.max(0,t.maximumDependencies??d.graphMaxCallsites),d.graphMaxCallsites),o=R(e.dependencies,n).map(Y),a=o.map(({dependency:p})=>p),s=R(e.baseline.analyzedSourceVersions,d.graphMaxModules),r=e.dependencies.length>a.length||o.some(({trimmed:p})=>p)||e.baseline.analyzedSourceVersions.length>s.length||e.capability.reasons.length>d.capabilityMaxReasons||e.evidence.length>d.reportMaxEvidence||e.diagnostics.length>d.reportMaxDiagnostics;if(!(t.forceTruncation===!0||r))return e;let c=t.mode??"analysis",m=te(c),A=`${e.reportId}_collection_${c}`,S=Object.freeze([...e.capability.reasons.filter(p=>p.code!==m).slice(0,d.capabilityMaxReasons-1),Object.freeze({code:m,retryable:!1})]),h=Object.freeze([...e.diagnostics.filter(p=>p.id!==A).slice(0,d.reportMaxDiagnostics-1),Object.freeze({id:A,code:m,severity:"warning",retryable:!1,evidenceIds:Object.freeze([])})]),b=Q(a,h),E=Z(e.evidence,b,e.dependencies.length===a.length),g=new Set(E.map(({id:p})=>p)),w=Object.freeze(a.map(p=>ee(p,g))),D=Object.freeze(h.map(p=>Object.freeze({...p,evidenceIds:Object.freeze(p.evidenceIds.filter(y=>g.has(y)))}))),T=e.dependencies.length-a.length,i=e.baseline.analyzedSourceVersions.length-s.length,l=i>0&&T===0?"modules":"callsites";return Object.freeze({...e,baseline:Object.freeze({...e.baseline,analyzedSourceVersions:s}),capability:Object.freeze({...e.capability,...c==="analysis"&&e.capability.staticAnalysis==="available"?{staticAnalysis:"partial"}:{},reasons:S}),dependencies:w,evidence:E,diagnostics:D,...c==="analysis"?{completeness:Object.freeze({...e.completeness,complete:!1,frontierCount:e.completeness.frontierCount+T+i+(r&&T===0&&i===0?1:0),truncatedBy:t.truncatedBy??e.completeness.truncatedBy??l})}:{}})}function ne(e,t){let n=t.origin,o=t.kind==="rpc"?e.transport==="trpc"&&t.operation!==void 0&&e.operation===t.operation:t.kind==="http"?e.transport==="fetch"||e.transport==="xhr":!1;return t.environment==="server"||!o||e.freshness!=="current"||n===void 0||e.requestCallsiteId!==n.requestCallsiteId||e.sourceVersion!==n.sourceVersion||t.method!==void 0&&e.method.toUpperCase()!==t.method.toUpperCase()||t.url!==void 0&&e.url.pathname!==t.url.pathname||t.url?.origin!==void 0&&e.url.origin!==t.url.origin||n.componentSourceId!==void 0&&e.componentSourceId!==void 0&&e.componentSourceId!==n.componentSourceId||n.triggerCallsiteId!==void 0&&e.triggerCallsiteId!==void 0&&e.triggerCallsiteId!==n.triggerCallsiteId?!1:t.association!=="transitive"||e.componentSourceId===n.componentSourceId&&e.triggerCallsiteId===n.triggerCallsiteId}function oe(e){return Object.freeze({id:e.id,kind:"runtime-observation",summaryKey:"dataFlow.evidence.runtimeDispatch"})}function U(e,t){let n=new Set,o=e.map(a=>{let s=t.filter(c=>ne(c,a));for(let c of s)n.add(c.id);if(s.length===0)return a;let r=[...new Set(s.flatMap(({url:c})=>c.origin===void 0?[]:[c.origin]))],f=r.length===1?r[0]:void 0;return Object.freeze({...a,...a.url===void 0||a.url.origin!==void 0||f===void 0?{}:{url:Object.freeze({...a.url,origin:f})},execution:"observed",observationIds:Object.freeze([...new Set([...a.observationIds,...s.map(({id:c})=>c)])]),evidenceIds:Object.freeze([...new Set([...a.evidenceIds,...s.map(({id:c})=>c)])])})});return Object.freeze({dependencies:Object.freeze(o),matchedObservationIds:n})}function B(e,t,n){let o=new Set(e.map(({id:a})=>a));return Object.freeze([...e,...t.flatMap(a=>n.has(a.id)&&!o.has(a.id)?[oe(a)]:[])])}function k(e,t){let n=new Set([e.component.componentSourceId,...e.dependencies.filter(s=>s.environment!=="server").map(s=>s.origin?.componentSourceId)]),o=t.filter(s=>s.componentSourceId===void 0||n.has(s.componentSourceId)),a=U(e.dependencies,o);return _(Object.freeze({...e,dependencies:a.dependencies,evidence:B(e.evidence,o,a.matchedObservationIds)}),{mode:"observation"})}function ae(e){let t=e.transport==="trpc";return Object.freeze({id:e.id,kind:t?"rpc":"http",direction:e.method==="GET"||e.method==="HEAD"||e.method==="QUERY"||e.method==="SUBSCRIPTION"?"read":"write",execution:"observed",proof:"unavailable",association:"unassigned",method:e.method,...t?e.operation===void 0?{}:{operation:e.operation}:{url:e.url},parameters:Object.freeze((t?[]:e.url.queryKeys).map(n=>Object.freeze({path:n,position:"query",sensitive:I(n),valueState:"not-collected",evidenceIds:Object.freeze([e.id])}))),response:Object.freeze({consumedFields:Object.freeze([])}),suppliedBindings:Object.freeze([]),locationIds:Object.freeze([]),evidenceIds:Object.freeze([e.id]),observationIds:Object.freeze([e.id])})}function N(e,t){let n=t.filter(({freshness:r})=>r==="current"),o=U(e.dependencies,n),a=n.filter(({id:r})=>!o.matchedObservationIds.has(r)).map(ae),s=new Set(n.map(({id:r})=>r));return _(Object.freeze({...e,dependencies:Object.freeze([...o.dependencies,...a]),evidence:B(e.evidence,n,s)}),{mode:"observation"})}function X(){H(Object.freeze({createPanel:q,getComponentRegistration(e){return x()?.getComponentRegistration(e)},observations(e){let t=x();return t?.updateRoute(e),t?.observations()??Object.freeze([])},mergeComponentReport:k,mergePageReport:N}))}X();
@@ -1 +1 @@
1
- var v=Object.freeze({observationMaxEntries:100,observationMaxBytes:262144,observationTtlMs:3e5,protocolRequestMaxBytes:32768,reportMaxBytes:131072,reportMaxEvidence:200,reportMaxDiagnostics:256,capabilityMaxReasons:64,graphMaxDepth:5,graphMaxModules:50,graphMaxCallsites:100,analysisTimeoutMs:2e3,reportMaxFields:100,sourceMaxComponents:256}),A=v.reportMaxFields,ne=Object.freeze({observationMaxEntries:v.observationMaxEntries,observationMaxBytes:v.observationMaxBytes,observationTtlMs:v.observationTtlMs,reportMaxBytes:v.reportMaxBytes});var s="/__spotpatch/v1";var re=Object.freeze({bootstrap:`${s}/bootstrap`,sourceContext:`${s}/source-context`,openEditor:`${s}/open-editor`,dataFlowComponentReport:`${s}/data-flow/component-report`,dataFlowPageReport:`${s}/data-flow/page-report`,agentCapability:`${s}/agent/capability`,agentWorkspaceHealth:`${s}/agent/workspace-health`,agentJobs:`${s}/agent/jobs`,askCapability:`${s}/ask/capability`,askJobs:`${s}/ask/jobs`,externalHandoffCapability:`${s}/external-handoff/capability`,externalHandoffPublish:`${s}/external-handoff/publish`,externalHandoffStatus:`${s}/external-handoff/status`,externalHandoffResolveDelivery:`${s}/external-handoff/resolve-delivery`,externalAgentControlStatus:`${s}/external-agent/control/status`,externalAgentControlConnect:`${s}/external-agent/control/connect`,externalAgentControlDisconnect:`${s}/external-agent/control/disconnect`,externalAgentControlCancel:`${s}/external-agent/control/cancel`,externalAgentEvents:`${s}/external-agent/events`,externalAgentResult:`${s}/external-agent/result`});var P=Symbol.for("spotpatch.data-flow.runtime.v1"),K=Symbol.for("react.memo"),J=Symbol.for("react.forward_ref");function j(e){return e.performance?.now()??Date.now()}function T(e){let n=0,o=(()=>{try{let a=new Uint8Array(8);return globalThis.crypto.getRandomValues(a),Array.from(a,p=>p.toString(36).padStart(2,"0")).join("")}catch{return"local"}})();return()=>(n+=1,`${e}_${o}_${n.toString(36)}`)}function U(e,n){try{let o=new URL(e,n);return Object.freeze({origin:o.origin,pathname:o.pathname,queryKeys:Object.freeze([...new Set(o.searchParams.keys())].sort().slice(0,A))})}catch{return Object.freeze({pathname:e.split(/[?#]/u,1)[0]??"{invalid}",queryKeys:Object.freeze([])})}}function Y(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function Q(e,n){return n?.method!==void 0?n.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function $(e,n){try{let o=new URL(e,n).pathname;return o===s||o.startsWith(`${s}/`)}catch{return!1}}function Z(e){return new TextEncoder().encode(JSON.stringify(e)).byteLength}function ee(e,n){let o=[],a=0;function p(d){for(;o[0]!==void 0&&d-o[0].recordedAt>e.observationTtlMs;){let f=o.shift();f!==void 0&&(a-=f.bytes)}}return Object.freeze({add(d){let f=j(n);p(f);let y=Z(d);if(!(y>e.observationMaxBytes))for(o.push(Object.freeze({bytes:y,observation:d,recordedAt:f})),a+=y;o.length>e.observationMaxEntries||a>e.observationMaxBytes;){let h=o.shift();h!==void 0&&(a-=h.bytes)}},clear(){o.length=0,a=0},values(){return p(j(n)),Object.freeze(o.map(({observation:d})=>d))}})}function w(e,n){try{return Object.getOwnPropertyDescriptor(e,n)}catch{return}}function te(e){let n=w(e,"$$typeof")?.value,o=n===K?"type":n===J?"render":void 0;if(o===void 0)return;let a=w(e,o)?.value;return typeof a=="object"&&a!==null||typeof a=="function"?a:void 0}function S(e,n,o,a=w(e,n)){if(!(a===void 0||!("value"in a)||!a.writable)){try{Object.defineProperty(e,n,{...a,value:o})}catch{return}return()=>{try{w(e,n)?.value===o&&Object.defineProperty(e,n,a)}catch{}}}}function O(e){try{e()}catch{}}function z(e,n=globalThis,o={}){let a=new WeakMap,p=new WeakMap,d=ee(e.limits,n),f=T("invocation"),y=T("observation"),h=T("page")(),q=T("route"),m=q(),F,D,g,L=!1,x=(()=>{try{return n.fetch}catch{return}})();function H(t,r){if(x===void 0)throw new TypeError("Fetch is unavailable.");let l=Reflect.apply(x,this,[t,r]);return O(()=>{let i=g,c=i?.invocationToken,b=Y(t);$(b,n.location?.href??"http://spotpatch.invalid/")||o.shouldObserveFetch?.(t,r,n.location?.href??"http://spotpatch.invalid/")===!1||d.add(Object.freeze({schemaVersion:1,id:y(),pageEpoch:h,routeEpoch:m,...i===void 0?{}:{requestCallsiteId:i.requestCallsiteId,sourceVersion:i.sourceVersion},...c===void 0?{}:{invocationId:c.invocationId,componentSourceId:c.componentSourceId,triggerCallsiteId:c.triggerCallsiteId},transport:"fetch",method:Q(t,r),url:U(b,n.location?.href??"http://spotpatch.invalid/"),outcome:"dispatched",freshness:"current",diagnosticIds:Object.freeze([])}))}),l}let W=x===void 0?void 0:S(n,"fetch",H),u=(()=>{try{return n.XMLHttpRequest?.prototype}catch{return}})(),k=u===void 0?void 0:w(u,"open"),C=u===void 0?void 0:w(u,"send");function N(t,r,...l){let i=k?.value;typeof i=="function"&&Reflect.apply(i,this,[t,r,...l]),O(()=>{p.set(this,Object.freeze({method:t,url:String(r)}))})}function B(t){let r=C?.value;typeof r=="function"&&Reflect.apply(r,this,[t]),O(()=>{let l=p.get(this);if(l===void 0||$(l.url,n.location?.href??"http://spotpatch.invalid/")||o.shouldObserveXhr?.(l.url,n.location?.href??"http://spotpatch.invalid/")===!1)return;let i=g,c=i?.invocationToken;d.add(Object.freeze({schemaVersion:1,id:y(),pageEpoch:h,routeEpoch:m,...i===void 0?{}:{requestCallsiteId:i.requestCallsiteId,sourceVersion:i.sourceVersion},...c===void 0?{}:{invocationId:c.invocationId,componentSourceId:c.componentSourceId,triggerCallsiteId:c.triggerCallsiteId},transport:"xhr",method:l.method.toUpperCase(),url:U(l.url,n.location?.href??"http://spotpatch.invalid/"),outcome:"dispatched",freshness:"current",diagnosticIds:Object.freeze([])}))})}let G=u===void 0||typeof k?.value!="function"?void 0:S(u,"open",N,k),X=u===void 0||typeof C?.value!="function"?void 0:S(u,"send",B,C),I=Object.freeze({beginInvocation(t){return Object.freeze({invocationId:f(),componentSourceId:t.componentSourceId,triggerCallsiteId:t.triggerCallsiteId,sourceVersion:t.sourceVersion})},bindInvocation(t,r){return function(...i){return I.withInvocation(t,()=>Reflect.apply(r,this,i))}},bindTrigger(t,r){if(typeof r!="function")return r;let l=r;return function(...c){let b=I.beginInvocation(t);return I.withInvocation(b,()=>Reflect.apply(l,this,c))}},captureInvocation:()=>D,clear:d.clear,createTrpcLink(){return()=>t=>(O(()=>{let r=t.op.path,l=t.op.type;if(typeof r!="string"||r.length===0||r.length>512||l!=="query"&&l!=="mutation"&&l!=="subscription")return;let i=g,c=i?.invocationToken;d.add(Object.freeze({schemaVersion:1,id:y(),pageEpoch:h,routeEpoch:m,...i===void 0?{}:{requestCallsiteId:i.requestCallsiteId,sourceVersion:i.sourceVersion},...c===void 0?{}:{invocationId:c.invocationId,componentSourceId:c.componentSourceId,triggerCallsiteId:c.triggerCallsiteId},transport:"trpc",method:l.toUpperCase(),operation:r,url:Object.freeze({pathname:r,queryKeys:Object.freeze([])}),outcome:"dispatched",freshness:"current",diagnosticIds:Object.freeze([])}))}),t.next(t.op))},dispose(){L||(L=!0,d.clear(),W?.(),G?.(),X?.())},getComponentRegistration:t=>a.get(t),getCurrentRequestFrame:()=>g,observations:()=>Object.freeze(d.values().map(t=>t.routeEpoch===m?t:Object.freeze({...t,freshness:"stale-route"}))),registerComponent(t,r,l){let i=Object.freeze({componentSourceId:r,sourceVersion:l}),c=[t],b=new Set;for(;c.length>0;){let R=c.pop();if(R===void 0||b.has(R))continue;b.add(R),a.set(R,i);let E=te(R);E!==void 0&&c.push(E)}},updateRoute(t){F===void 0?F=t:F!==t&&(F=t,m=q())},withInvocation(t,r){let l=D;D=t;try{return r()}finally{D=l}},withRequestFrame(t,r,l){let i=g;g=Object.freeze({requestCallsiteId:r.requestCallsiteId,sourceVersion:r.sourceVersion,...t===void 0?{}:{invocationToken:t}});try{return l()}finally{g=i}}});return I}function M(e,n=globalThis,o={}){if(!e.enabled)return;let a=n[P]??z(e,n,o);return n[P]=a,a}var V=M(__SPOTPATCH_DATA_FLOW_CONFIG__);if(V===void 0)throw new Error("SpotPatch data-flow prelude was loaded while disabled.");var ge=V;export{ge as dataFlowRuntime};
1
+ var v=Object.freeze({observationMaxEntries:100,observationMaxBytes:262144,observationTtlMs:3e5,protocolRequestMaxBytes:32768,reportMaxBytes:131072,reportMaxEvidence:200,reportMaxDiagnostics:256,capabilityMaxReasons:64,graphMaxDepth:5,graphMaxModules:50,graphMaxCallsites:100,analysisTimeoutMs:2e3,reportMaxFields:100,sourceMaxComponents:256}),A=v.reportMaxFields,ne=Object.freeze({observationMaxEntries:v.observationMaxEntries,observationMaxBytes:v.observationMaxBytes,observationTtlMs:v.observationTtlMs,reportMaxBytes:v.reportMaxBytes});var s="/__spotpatch/v1";var re=Object.freeze({bootstrap:`${s}/bootstrap`,sourceContext:`${s}/source-context`,openEditor:`${s}/open-editor`,dataFlowComponentReport:`${s}/data-flow/component-report`,dataFlowPageReport:`${s}/data-flow/page-report`,agentCapability:`${s}/agent/capability`,agentWorkspaceHealth:`${s}/agent/workspace-health`,agentJobs:`${s}/agent/jobs`,askCapability:`${s}/ask/capability`,askJobs:`${s}/ask/jobs`,externalHandoffCapability:`${s}/external-handoff/capability`,externalHandoffPublish:`${s}/external-handoff/publish`,externalHandoffStatus:`${s}/external-handoff/status`,externalHandoffResolveDelivery:`${s}/external-handoff/resolve-delivery`,externalAgentControlStatus:`${s}/external-agent/control/status`,externalAgentControlConnect:`${s}/external-agent/control/connect`,externalAgentControlDisconnect:`${s}/external-agent/control/disconnect`,externalAgentControlCancel:`${s}/external-agent/control/cancel`,externalAgentEvents:`${s}/external-agent/events`,externalAgentResult:`${s}/external-agent/result`});var E=Symbol.for("spotpatch.data-flow.runtime.v1"),K=Symbol.for("react.memo"),J=Symbol.for("react.forward_ref");function j(e){return e.performance?.now()??Date.now()}function T(e){let n=0,o=(()=>{try{let a=new Uint8Array(8);return globalThis.crypto.getRandomValues(a),Array.from(a,p=>p.toString(36).padStart(2,"0")).join("")}catch{return"local"}})();return()=>(n+=1,`${e}_${o}_${n.toString(36)}`)}function U(e,n){try{let o=new URL(e,n);return Object.freeze({origin:o.origin,pathname:o.pathname,queryKeys:Object.freeze([...new Set(o.searchParams.keys())].sort().slice(0,A))})}catch{return Object.freeze({pathname:e.split(/[?#]/u,1)[0]??"{invalid}",queryKeys:Object.freeze([])})}}function Y(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function Q(e,n){return n?.method!==void 0?n.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function $(e,n){try{let o=new URL(e,n).pathname;return o===s||o.startsWith(`${s}/`)}catch{return!1}}function Z(e){return new TextEncoder().encode(JSON.stringify(e)).byteLength}function ee(e,n){let o=[],a=0;function p(d){for(;o[0]!==void 0&&d-o[0].recordedAt>e.observationTtlMs;){let f=o.shift();f!==void 0&&(a-=f.bytes)}}return Object.freeze({add(d){let f=j(n);p(f);let y=Z(d);if(!(y>e.observationMaxBytes))for(o.push(Object.freeze({bytes:y,observation:d,recordedAt:f})),a+=y;o.length>e.observationMaxEntries||a>e.observationMaxBytes;){let h=o.shift();h!==void 0&&(a-=h.bytes)}},clear(){o.length=0,a=0},values(){return p(j(n)),Object.freeze(o.map(({observation:d})=>d))}})}function w(e,n){try{return Object.getOwnPropertyDescriptor(e,n)}catch{return}}function te(e){let n=w(e,"$$typeof")?.value,o=n===K?"type":n===J?"render":void 0;if(o===void 0)return;let a=w(e,o)?.value;return typeof a=="object"&&a!==null||typeof a=="function"?a:void 0}function S(e,n,o,a=w(e,n)){if(!(a===void 0||!("value"in a)||!a.writable)){try{Object.defineProperty(e,n,{...a,value:o})}catch{return}return()=>{try{w(e,n)?.value===o&&Object.defineProperty(e,n,a)}catch{}}}}function O(e){try{e()}catch{}}function z(e,n=globalThis,o={}){let a=new WeakMap,p=new WeakMap,d=ee(e.limits,n),f=T("invocation"),y=T("observation"),h=T("page")(),q=T("route"),m=q(),F,D,g,L=!1,x=(()=>{try{return n.fetch}catch{return}})();function W(t,r){if(x===void 0)throw new TypeError("Fetch is unavailable.");let l=Reflect.apply(x,this,[t,r]);return O(()=>{let i=g,c=i?.invocationToken,b=Y(t);$(b,n.location?.href??"http://spotpatch.invalid/")||o.shouldObserveFetch?.(t,r,n.location?.href??"http://spotpatch.invalid/")===!1||d.add(Object.freeze({schemaVersion:1,id:y(),pageEpoch:h,routeEpoch:m,...i===void 0?{}:{requestCallsiteId:i.requestCallsiteId,sourceVersion:i.sourceVersion},...c===void 0?{}:{invocationId:c.invocationId,componentSourceId:c.componentSourceId,triggerCallsiteId:c.triggerCallsiteId},transport:"fetch",method:Q(t,r),url:U(b,n.location?.href??"http://spotpatch.invalid/"),outcome:"dispatched",freshness:"current",diagnosticIds:Object.freeze([])}))}),l}let H=x===void 0?void 0:S(n,"fetch",W),u=(()=>{try{return n.XMLHttpRequest?.prototype}catch{return}})(),k=u===void 0?void 0:w(u,"open"),C=u===void 0?void 0:w(u,"send");function N(t,r,...l){let i=k?.value;typeof i=="function"&&Reflect.apply(i,this,[t,r,...l]),O(()=>{p.set(this,Object.freeze({method:t,url:String(r)}))})}function B(t){let r=C?.value;typeof r=="function"&&Reflect.apply(r,this,[t]),O(()=>{let l=p.get(this);if(l===void 0||$(l.url,n.location?.href??"http://spotpatch.invalid/")||o.shouldObserveXhr?.(l.url,n.location?.href??"http://spotpatch.invalid/")===!1)return;let i=g,c=i?.invocationToken;d.add(Object.freeze({schemaVersion:1,id:y(),pageEpoch:h,routeEpoch:m,...i===void 0?{}:{requestCallsiteId:i.requestCallsiteId,sourceVersion:i.sourceVersion},...c===void 0?{}:{invocationId:c.invocationId,componentSourceId:c.componentSourceId,triggerCallsiteId:c.triggerCallsiteId},transport:"xhr",method:l.method.toUpperCase(),url:U(l.url,n.location?.href??"http://spotpatch.invalid/"),outcome:"dispatched",freshness:"current",diagnosticIds:Object.freeze([])}))})}let G=u===void 0||typeof k?.value!="function"?void 0:S(u,"open",N,k),X=u===void 0||typeof C?.value!="function"?void 0:S(u,"send",B,C),I=Object.freeze({beginInvocation(t){return Object.freeze({invocationId:f(),componentSourceId:t.componentSourceId,triggerCallsiteId:t.triggerCallsiteId,sourceVersion:t.sourceVersion})},bindInvocation(t,r){return function(...i){return I.withInvocation(t,()=>Reflect.apply(r,this,i))}},bindTrigger(t,r){if(typeof r!="function")return r;let l=r;return function(...c){let b=I.beginInvocation(t);return I.withInvocation(b,()=>Reflect.apply(l,this,c))}},captureInvocation:()=>D,clear:d.clear,createTrpcLink(){return()=>t=>(O(()=>{let r=t.op.path,l=t.op.type;if(typeof r!="string"||r.length===0||r.length>512||l!=="query"&&l!=="mutation"&&l!=="subscription")return;let i=g,c=i?.invocationToken;d.add(Object.freeze({schemaVersion:1,id:y(),pageEpoch:h,routeEpoch:m,...i===void 0?{}:{requestCallsiteId:i.requestCallsiteId,sourceVersion:i.sourceVersion},...c===void 0?{}:{invocationId:c.invocationId,componentSourceId:c.componentSourceId,triggerCallsiteId:c.triggerCallsiteId},transport:"trpc",method:l.toUpperCase(),operation:r,url:Object.freeze({pathname:r,queryKeys:Object.freeze([])}),outcome:"dispatched",freshness:"current",diagnosticIds:Object.freeze([])}))}),t.next(t.op))},dispose(){L||(L=!0,d.clear(),H?.(),G?.(),X?.())},getComponentRegistration:t=>a.get(t),getCurrentRequestFrame:()=>g,observations:()=>Object.freeze(d.values().map(t=>t.routeEpoch===m?t:Object.freeze({...t,freshness:"stale-route"}))),registerComponent(t,r,l){let i=Object.freeze({componentSourceId:r,sourceVersion:l}),c=[t],b=new Set;for(;c.length>0;){let R=c.pop();if(R===void 0||b.has(R))continue;b.add(R),a.set(R,i);let P=te(R);P!==void 0&&c.push(P)}},updateRoute(t){F===void 0?F=t:F!==t&&(F=t,m=q())},withInvocation(t,r){let l=D;D=t;try{return r()}finally{D=l}},withRequestFrame(t,r,l){let i=g;g=Object.freeze({requestCallsiteId:r.requestCallsiteId,sourceVersion:r.sourceVersion,...t===void 0?{}:{invocationToken:t}});try{return l()}finally{g=i}}});return I}function M(e,n=globalThis,o={}){if(!e.enabled)return;let a=n[E]??z(e,n,o);return n[E]=a,a}var V=M(__SPOTPATCH_DATA_FLOW_CONFIG__);if(V===void 0)throw new Error("SpotPatch data-flow prelude was loaded while disabled.");var be=V;export{be as dataFlowRuntime};