@popmelt.com/core 0.6.6 → 0.6.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge-entry.mjs +130 -42
- package/dist/cli.mjs +130 -42
- package/dist/index.mjs +22 -22
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server-E44GIKD2.mjs +221 -0
- package/dist/server.mjs +128 -40
- package/package.json +1 -1
- package/dist/server-HPHAQXHA.mjs +0 -133
package/package.json
CHANGED
package/dist/server-HPHAQXHA.mjs
DELETED
|
@@ -1,133 +0,0 @@
|
|
|
1
|
-
import{spawn as gn}from"child_process";import{createHash as yn}from"crypto";import{dirname as vn,join as wn}from"path";import{fileURLToPath as Sn}from"url";import{execFileSync as Xt,spawn as Yt}from"child_process";import{createHash as Vt,randomUUID as Oe}from"crypto";import{mkdir as Kt,readFile as nt,readdir as Zt,stat as en,unlink as tn,writeFile as Pe}from"fs/promises";import{createServer as nn}from"http";import{tmpdir as sn}from"os";import{basename as on,dirname as rn,join as ne}from"path";import{fileURLToPath as an}from"url";function De(i,t){return`<!DOCTYPE html>
|
|
2
|
-
<html>
|
|
3
|
-
<head>
|
|
4
|
-
<meta charset="utf-8">
|
|
5
|
-
<title>Popmelt Canvas</title>
|
|
6
|
-
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
7
|
-
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
8
|
-
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">
|
|
9
|
-
<style>*{margin:0;padding:0;box-sizing:border-box}html,body,#root{height:100%;overflow:hidden}</style>
|
|
10
|
-
</head>
|
|
11
|
-
<body>
|
|
12
|
-
<div id="root"></div>
|
|
13
|
-
<script type="importmap">
|
|
14
|
-
{"imports":{
|
|
15
|
-
"react":"https://esm.sh/react@19?dev",
|
|
16
|
-
"react-dom/client":"https://esm.sh/react-dom@19/client?dev",
|
|
17
|
-
"react/jsx-runtime":"https://esm.sh/react@19/jsx-runtime?dev"
|
|
18
|
-
}}
|
|
19
|
-
</script>
|
|
20
|
-
<script type="module">
|
|
21
|
-
import { mountCanvas } from 'http://localhost:${i}/canvas/app.mjs';
|
|
22
|
-
mountCanvas(document.getElementById('root'), {
|
|
23
|
-
devOrigin: '${t}',
|
|
24
|
-
bridgeOrigin: 'http://localhost:${i}',
|
|
25
|
-
});
|
|
26
|
-
</script>
|
|
27
|
-
</body>
|
|
28
|
-
</html>`}import{spawn as Pt}from"child_process";import{createInterface as xt}from"readline";var It=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),Ne=1e5;function bt(i){let t=i.input?.file_path||i.input?.path;if(!t)return;let n=t.includes(".")?`.${t.split(".").pop().toLowerCase()}`:"";if(!It.has(n))return;let e;if(i.name==="Write"&&typeof i.input?.content=="string"?e=i.input.content:i.name==="Edit"&&typeof i.input?.new_string=="string"&&(e=i.input.new_string),!!e)return e.length>Ne?e.slice(0,Ne)+`
|
|
29
|
-
\u2026[truncated]`:e}function fe(i,t){let{prompt:n,projectRoot:e,maxTurns:s=40,maxBudgetUsd:l=1,allowedTools:a=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:r="claude",resumeSessionId:p,model:f,timeoutMs:N=3e5,onEvent:U}=t,C=[];p?C.push("--resume",p,"-p",n):C.push("-p",n),C.push("--output-format","stream-json","--verbose","--max-turns",String(s),"--max-budget-usd",String(l)),f&&C.push("--model",f);for(let L of a)C.push("--allowedTools",L);let I=Pt(r,C,{cwd:e,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0}}),H=new Promise(L=>{let G,k=[],J=[],O=!1,B="",g=!1,F=setTimeout(()=>{g=!0,I.kill("SIGTERM"),setTimeout(()=>{try{I.kill("SIGKILL")}catch{}},5e3)},N),y=xt({input:I.stdout}),w=new Set;y.on("line",D=>{if(D.trim())try{let _=JSON.parse(D);_.session_id&&!G&&(G=_.session_id);let Z=_.type??(_.event?.type?`event.${_.event.type}`:"unknown");if(w.add(Z),_.type==="result"&&_.result&&k.length===0){let R=typeof _.result=="string"?_.result:"";R&&(k.push(R),U?.({type:"delta",jobId:i,text:R},i))}if(_.type==="assistant"&&Array.isArray(_.message?.content))for(let R of _.message.content){if(R.type==="text"&&R.text&&(k.push(R.text),U?.({type:"delta",jobId:i,text:R.text},i)),R.type==="tool_use"&&R.name){let ae=R.input?.file_path||R.input?.path||void 0,pe=bt(R);U?.({type:"tool_use",jobId:i,tool:R.name,...ae?{file:ae}:{},...pe?{content:pe}:{}},i),R.name==="Edit"&&R.input?.file_path?J.push({tool:"Edit",file_path:R.input.file_path,old_string:R.input.old_string,new_string:R.input.new_string,replace_all:R.input.replace_all}):R.name==="Write"&&R.input?.file_path&&J.push({tool:"Write",file_path:R.input.file_path,content:R.input.content})}R.type==="thinking"&&R.thinking&&U?.({type:"thinking",jobId:i,text:R.thinking},i)}_.type==="user"&&_.tool_use_result?.file?.filePath&&U?.({type:"tool_use",jobId:i,tool:"Read",file:_.tool_use_result.file.filePath},i)}catch{}});let S=[];I.stderr?.on("data",D=>{S.push(D.toString())}),I.on("close",D=>{if(clearTimeout(F),y.close(),k.length===0&&w.size>0&&console.warn(`[Claude:${i}] No text captured. Event types seen: ${[...w].join(", ")}`),g)O=!0,B=`Timed out after ${Math.round(N/6e4)} minutes`;else if(D!==0&&D!==null){O=!0;let _=S.join("").trim(),Z=k.length===0&&w.size>0?` (no text captured, event types: ${[...w].join(", ")})`:"";B=_||`Claude process exited with code ${D}${Z}`}L({sessionId:G,text:k.join(""),success:!O,error:O?B:void 0,fileEdits:J.length>0?J:void 0})}),I.on("error",D=>{clearTimeout(F),O=!0,B=D.message,L({sessionId:G,text:k.join(""),success:!1,error:B,fileEdits:J.length>0?J:void 0})})});return{process:I,result:H}}import{spawn as Tt}from"child_process";import{createInterface as kt}from"readline";function Et(i){let t=i.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return t?t[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i}function Be(i,t){let{prompt:n,projectRoot:e,screenshotPath:s,resumeSessionId:l,model:a,onEvent:r}=t,p=[];l?(p.push("exec","resume",l),a&&p.push("-m",a),p.push("--json","--full-auto",n),s&&p.push("--image",s)):(p.push("exec","--json","--full-auto"),a&&p.push("-m",a),p.push(n),s&&p.push("--image",s));let f=Tt("codex",p,{cwd:e,stdio:["ignore","pipe","pipe"],env:{...process.env}}),N=new Promise(U=>{let C,I=[],H=[],L=!1,G="",k=kt({input:f.stdout}),J=new Set;k.on("line",B=>{if(B.trim())try{let g=JSON.parse(B),F=g.type??"unknown";if(J.add(F),F==="thread.started"&&g.thread_id&&!C&&(C=g.thread_id),(F==="item.agentMessage.delta"||F==="item/agentMessage/delta")&&g.delta?.text&&(I.push(g.delta.text),r?.({type:"delta",jobId:i,text:g.delta.text},i)),(F==="item.reasoning.delta"||F==="item/reasoning/delta")&&g.delta?.text&&r?.({type:"thinking",jobId:i,text:g.delta.text},i),(F==="item.started"||F==="item/started")&&g.item){let y=g.item.type;if(y==="command_execution"){let w=g.item.command,S=w?Et(w):void 0,D=S?`Bash: ${S.split(`
|
|
30
|
-
`)[0].slice(0,80)}`:"Bash";H.push(D),r?.({type:"tool_use",jobId:i,tool:"Bash",...S?{content:S}:{}},i)}else if(y==="file_change"){let w=g.item.filename||g.item.path;H.push(w?`Edit ${w.split("/").pop()}`:"Edit"),r?.({type:"tool_use",jobId:i,tool:"Edit",...w?{file:w}:{}},i)}else if(y==="file_read"){let w=g.item.filename||g.item.path;H.push(w?`Read ${w.split("/").pop()}`:"Read"),r?.({type:"tool_use",jobId:i,tool:"Read",...w?{file:w}:{}},i)}else if(y==="web_search")H.push("WebSearch"),r?.({type:"tool_use",jobId:i,tool:"WebSearch"},i);else if(y==="mcp_tool_call"){let w=g.item.tool_name||g.item.name||"MCP";H.push(w),r?.({type:"tool_use",jobId:i,tool:w},i)}}if((F==="item.completed"||F==="item/completed")&&g.item){if(g.item.type==="agent_message"){let y=g.item.text;typeof y=="string"&&y&&(I.push(y),r?.({type:"delta",jobId:i,text:y},i))}else if(g.item.type==="reasoning"){let y=g.item.text;typeof y=="string"&&y&&r?.({type:"thinking",jobId:i,text:y},i)}else if(g.item.type==="file_change"&&Array.isArray(g.item.changes))for(let y of g.item.changes){let w=y.path||y.filename,S=y.kind==="add"?"Write":"Edit";w&&(H.push(`${S} ${w.split("/").pop()}`),r?.({type:"tool_use",jobId:i,tool:S,file:w},i))}}F==="turn.failed"&&(L=!0,G=g.error?.message||g.message||"Turn failed")}catch{}});let O=[];f.stderr?.on("data",B=>{O.push(B.toString())}),f.on("close",B=>{k.close(),I.length===0&&J.size>0&&console.warn(`[Codex:${i}] No text captured. Event types seen: ${[...J].join(", ")}`),B!==0&&B!==null&&(L=!0,G=O.join("")||`Codex process exited with code ${B}`),U({sessionId:C,text:I.join(""),success:!L,error:L?G:void 0,toolsUsed:H.length>0?H:void 0})}),f.on("error",B=>{L=!0,G=B.message,U({sessionId:C,text:I.join(""),success:!1,error:G,toolsUsed:H.length>0?H:void 0})})});return{process:f,result:N}}import{execFile as Rt}from"child_process";import{copyFile as Je,mkdir as Ue,readdir as $t,readFile as Mt,writeFile as Ot}from"fs/promises";import{join as re}from"path";var me=class{constructor(t){this.projectRoot=t;let n=re(t,".popmelt");this.decisionsDir=re(n,"decisions"),this.screenshotsDir=re(n,"screenshots")}async persist(t,n,e){try{await Ue(this.decisionsDir,{recursive:!0}),await Ue(this.screenshotsDir,{recursive:!0});try{await Je(n,re(this.screenshotsDir,`s-${t.id}.png`))}catch{}for(let s=0;s<e.length;s++)try{let l=t.pastedImagePaths[s];l&&await Je(e[s],re(this.screenshotsDir,l.replace("screenshots/","")))}catch{}await Ot(re(this.decisionsDir,`d-${t.id}.json`),JSON.stringify(t,null,2))}catch(s){console.error("[DecisionStore] Failed to persist decision record:",s)}}async listDecisionIds(){try{return(await $t(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch{return[]}}async loadDecision(t){try{let n=await Mt(re(this.decisionsDir,`d-${t}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(t){return(await Promise.all(t.map(e=>this.loadDecision(e)))).filter(e=>e!==null)}captureGitDiff(t){return new Promise(n=>{Rt("git",["diff","HEAD"],{cwd:t,timeout:5e3,maxBuffer:1024*1024},(e,s)=>{if(e){n(null);return}n(s||null)})})}};import{readFile as Fe,writeFile as ce}from"fs/promises";import{join as Ie}from"path";var te="[Materializer]",Ct={version:1,materializedIds:[],lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},ge=class{constructor(t,n,e={}){this.projectRoot=t;this.decisionStore=n;this.options=e;this.cachedIndex=null;this.running=!1;let s=Ie(t,".popmelt");this.indexPath=Ie(s,"materialized.json"),this.modelPath=Ie(s,"model.json")}get isRunning(){return this.running}async loadModel(){try{let t=await Fe(this.modelPath,"utf-8");return JSON.parse(t)}catch{return null}}async addComponent(t){let n=await this.loadModel();n||(n={tokens:{},components:{},rules:[]}),(!n.components||typeof n.components!="object")&&(n.components={});let e=n.components;return e[t]?{added:!1,alreadyExists:!0}:(e[t]={description:""},await ce(this.modelPath,JSON.stringify(n,null,2)),console.log(`${te} Added component "${t}" to model`),{added:!0,alreadyExists:!1})}async updateToken(t,n){let e=await this.loadModel();e||(e={tokens:{},components:{},rules:[]});let s=t.split("."),l=e;for(let p=0;p<s.length-1;p++){let f=s[p];(!l[f]||typeof l[f]!="object")&&(l[f]={}),l=l[f]}let a=s[s.length-1],r;try{r=JSON.parse(n)}catch{r=null}if(r&&typeof r=="object"&&r!==null&&"value"in r)l[a]=r;else{let p=l[a];p&&typeof p=="object"&&p!==null&&"value"in p?p.value=n:l[a]=n}return await ce(this.modelPath,JSON.stringify(e,null,2)),console.log(`${te} Updated token "${t}" \u2192 "${n.slice(0,80)}"`),{updated:!0}}async removeToken(t){let n=await this.loadModel();if(!n)return{removed:!1};let e=t.split("."),s=n;for(let a=0;a<e.length-1;a++){let r=e[a];if(!s[r]||typeof s[r]!="object")return{removed:!1};s=s[r]}let l=e[e.length-1];return l in s?(delete s[l],await ce(this.modelPath,JSON.stringify(n,null,2)),console.log(`${te} Removed token "${t}" from model`),{removed:!0}):{removed:!1}}async removeComponent(t){let n=await this.loadModel();if(!n)return{removed:!1};let e=n.components;return!e||!e[t]?{removed:!1}:(delete e[t],await ce(this.modelPath,JSON.stringify(n,null,2)),console.log(`${te} Removed component "${t}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){let t=await this.loadIndex(),n=new Set(t.materializedIds),s=(await this.decisionStore.listDecisionIds()).filter(a=>!n.has(a));return s.length===0?[]:(await this.decisionStore.loadDecisions(s)).filter(a=>a.resolutions.some(r=>(r.finalScope??r.inferredScope)?.breadth==="pattern"))}async run(){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;try{let t=await this.getUnmaterializedPatternDecisions();if(t.length===0)return{processedIds:[],success:!0};let n=t.map(f=>f.id);console.log(`${te} Processing ${n.length} pattern-scoped decision(s): ${n.join(", ")}`),this.options.onEvent?.({type:"materialize_started",decisionIds:n});let e=await this.loadModel(),s=At(t,e),l=!0,a;try{let{result:f}=fe(`mat-${Date.now()}`,{prompt:s,projectRoot:this.projectRoot,maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"],claudePath:this.options.claudePath??"claude"}),N=await f;if(!N.success)l=!1,a=N.error,console.error(`${te} Claude spawn error:`,a);else{let U=_t(N.text);U?(await ce(this.modelPath,JSON.stringify(U,null,2)),console.log(`${te} Successfully materialized ${n.length} decision(s) \u2192 ${this.modelPath}`)):(l=!1,a="No <model> block found in response",console.error(`${te} ${a}`))}}catch(f){l=!1,a=f instanceof Error?f.message:String(f),console.error(`${te} Error:`,a)}let r=await this.loadIndex(),p=new Set(r.materializedIds);for(let f of n)p.add(f);return r.materializedIds=[...p],r.lastRunAt=Date.now(),r.lastRunDecisionIds=n,r.lastRunError=a??null,await this.persistIndex(r),this.options.onEvent?.({type:"materialize_done",decisionIds:n,success:l,error:a}),{processedIds:n,success:l,error:a}}finally{this.running=!1}}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let t=await Fe(this.indexPath,"utf-8"),n=JSON.parse(t);return this.cachedIndex=n,n}catch{return this.cachedIndex={...Ct,materializedIds:[],lastRunDecisionIds:[]},this.cachedIndex}}async persistIndex(t){this.cachedIndex=t;try{await ce(this.indexPath,JSON.stringify(t,null,2))}catch(n){console.error(`${te} Failed to write index:`,n)}}};function _t(i){let t=i.match(/<model>\s*([\s\S]*?)\s*<\/model>/);if(!t?.[1])return null;try{let n=JSON.parse(t[1]);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}function At(i,t){let n=i.map(s=>{let a=s.resolutions.filter(f=>(f.finalScope??f.inferredScope)?.breadth==="pattern").map(f=>{let U=(f.finalScope??f.inferredScope)?.target??"unknown",C=f.filesModified?.join(", ")??"none";return`- **${f.summary}** [scope: pattern/${U}]
|
|
31
|
-
Files modified: ${C}`}).join(`
|
|
32
|
-
`),r=s.annotations.map(f=>f.instruction).filter(Boolean).join(`
|
|
33
|
-
`),p=s.gitDiff?`
|
|
34
|
-
\`\`\`diff
|
|
35
|
-
${s.gitDiff.slice(0,2e3)}
|
|
36
|
-
\`\`\``:"";return`### Decision ${s.id} (${new Date(s.createdAt).toISOString()})
|
|
37
|
-
Page: ${s.url}
|
|
38
|
-
${a}
|
|
39
|
-
${p}
|
|
40
|
-
${r?`
|
|
41
|
-
Original instructions:
|
|
42
|
-
${r}`:""}`}).join(`
|
|
43
|
-
|
|
44
|
-
`);return`You are extracting a local design model from accumulated design decisions.
|
|
45
|
-
|
|
46
|
-
## Instructions
|
|
47
|
-
1. Review the current model (if any) and the new decisions below.
|
|
48
|
-
2. Determine what design tokens, component patterns, and rules to add or update.
|
|
49
|
-
3. Output the complete updated model as a JSON object inside <model> tags.
|
|
50
|
-
|
|
51
|
-
${t?`## Current Model
|
|
52
|
-
\`\`\`json
|
|
53
|
-
${JSON.stringify(t,null,2)}
|
|
54
|
-
\`\`\`
|
|
55
|
-
|
|
56
|
-
Merge the new decisions into the existing model. Preserve existing entries that are not contradicted by new decisions.`:"No model exists yet. Create one from scratch based on the decisions below."}
|
|
57
|
-
|
|
58
|
-
## Design Decisions to Materialize
|
|
59
|
-
${n}
|
|
60
|
-
|
|
61
|
-
## Output Format
|
|
62
|
-
Output the full model inside <model> tags. The model is a JSON object with these sections:
|
|
63
|
-
- \`tokens\`: Design tokens (colors, spacing, typography, etc.)
|
|
64
|
-
- \`components\`: Component-level patterns (e.g., button styles, card layouts)
|
|
65
|
-
- \`rules\`: Array of plain-language rules extracted from decisions
|
|
66
|
-
|
|
67
|
-
Example:
|
|
68
|
-
<model>
|
|
69
|
-
{
|
|
70
|
-
"tokens": {
|
|
71
|
-
"colors": { "primary": "#3b82f6" },
|
|
72
|
-
"spacing": {
|
|
73
|
-
"sm": "4px",
|
|
74
|
-
"md": "8px",
|
|
75
|
-
"section-gap": { "value": "32px", "property": "gap", "bindings": ["gap-8"] }
|
|
76
|
-
}
|
|
77
|
-
},
|
|
78
|
-
"components": {
|
|
79
|
-
"button": { "padding": "12px 24px", "borderRadius": "8px" }
|
|
80
|
-
},
|
|
81
|
-
"rules": [
|
|
82
|
-
"Buttons use 12px vertical padding and 24px horizontal padding",
|
|
83
|
-
"Primary actions use the primary color"
|
|
84
|
-
]
|
|
85
|
-
}
|
|
86
|
-
</model>
|
|
87
|
-
|
|
88
|
-
## Guidelines
|
|
89
|
-
- Map token-scoped decisions to \`tokens\`, component-scoped to \`components\`.
|
|
90
|
-
- Extract clear, enforceable rules into the \`rules\` array.
|
|
91
|
-
- When merging, new decisions override conflicting older values.
|
|
92
|
-
- Keep the model concise \u2014 only include patterns with clear evidence from decisions.
|
|
93
|
-
- Do NOT output resolution or question blocks. Just output the <model> block.
|
|
94
|
-
- Spacing tokens can be plain strings ("8px") or objects with code bindings:
|
|
95
|
-
{ "value": "8px", "property": "gap", "bindings": ["gap-2"] }
|
|
96
|
-
- property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
|
|
97
|
-
- bindings: Tailwind class names (without responsive prefixes) that use this token
|
|
98
|
-
Include property and bindings when the decision context has class-level evidence.`}import{readFile as je}from"fs/promises";import{homedir as ze}from"os";import{join as le}from"path";var Te=/popmelt/i;function ke(){return{found:!1,name:null,scope:null,disabled:!1}}function de(i,t,n=!1){return{found:!0,name:i,scope:t,disabled:n}}function ye(i){for(let t of Object.keys(i))if(Te.test(t))return t;return null}async function be(i){try{let t=await je(i,"utf-8");return JSON.parse(t)}catch{return null}}async function Ee(i){let t=ze(),n=await be(le(t,".claude.json"));if(n&&typeof n=="object"){let s=n;if(s.mcpServers&&typeof s.mcpServers=="object"){let l=ye(s.mcpServers);if(l)return de(l,"user")}if(s.projects&&typeof s.projects=="object"){let a=s.projects[i];if(a&&typeof a=="object"){let r=a;if(r.mcpServers&&typeof r.mcpServers=="object"){let p=ye(r.mcpServers);if(p){let f=Array.isArray(r.disabledMcpjsonServers)&&r.disabledMcpjsonServers.some(N=>Te.test(N));return de(p,"project",f)}}}}}let e=await be(le(i,".mcp.json"));if(e&&typeof e=="object"){let s=e;if(s.mcpServers&&typeof s.mcpServers=="object"){let a=ye(s.mcpServers);if(a){let r=await Le(i,a);return de(a,"mcp.json",r)}}let l=ye(s);if(l&&l!=="mcpServers"){let a=await Le(i,l);return de(l,"mcp.json",a)}}return ke()}async function Le(i,t){let n=le(i,".claude","settings.local.json"),e=await be(n);if(e&&typeof e=="object"){let s=e;if(Array.isArray(s.disabledMcpjsonServers))return s.disabledMcpjsonServers.some(l=>l===t)}return!1}var Dt=/^\[mcp_servers\.([^\]]+)\]/;function Nt(i){let t=i.split(`
|
|
99
|
-
`),n=[],e=null;for(let s of t){let l=s.match(Dt);l?(e&&n.push({name:e.name,body:e.bodyLines.join(`
|
|
100
|
-
`)}),e={name:l[1],bodyLines:[]}):s.startsWith("[")?e&&(n.push({name:e.name,body:e.bodyLines.join(`
|
|
101
|
-
`)}),e=null):e&&e.bodyLines.push(s)}return e&&n.push({name:e.name,body:e.bodyLines.join(`
|
|
102
|
-
`)}),n}function Bt(i){return/enabled\s*=\s*false/i.test(i)}async function Re(i){let t=process.env.CODEX_HOME||le(ze(),".codex"),n=await He(le(t,"config.toml"),"user");if(n.found)return n;let e=await He(le(i,".codex","config.toml"),"project");return e.found?e:ke()}async function He(i,t){try{let n=await je(i,"utf-8"),e=Nt(n);for(let s of e)if(Te.test(s.name)){let l=Bt(s.body);return de(s.name,t,l)}}catch{}return ke()}import{mkdir as Jt,readFile as We,writeFile as Ge}from"fs/promises";import{homedir as qe}from"os";import{dirname as Ut,join as $e}from"path";var Qe="https://mcp.popmelt.com/mcp";async function Xe(i=Qe){let t=$e(qe(),".claude.json"),n;try{let s=await We(t,"utf-8");n=JSON.parse(s)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let e=n.mcpServers;for(let s of Object.keys(e))if(/popmelt/i.test(s))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return e.popmelt={type:"http",url:i},await Ge(t,JSON.stringify(n,null,2)+`
|
|
103
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Ye(i=Qe){let t=process.env.CODEX_HOME||$e(qe(),".codex"),n=$e(t,"config.toml"),e;try{e=await We(n,"utf-8")}catch{e=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(e))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Jt(Ut(n),{recursive:!0});let s=`
|
|
104
|
-
[mcp_servers.popmelt]
|
|
105
|
-
url = "${i}"
|
|
106
|
-
`;return await Ge(n,e+s,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Me(i){let n=(i.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let e=n[1]||n[2],s=await Ft(i),l=Buffer.from(`--${e}`),a=Buffer.from(`--${e}--`),r,p,f,N,U,C,I,H,L,G,k,J,O=[],B=[],g=0,F=[];for(;g<s.length;){let y=s.indexOf(l,g);if(y===-1)break;let w=y+l.length;if(s.slice(y,y+a.length).equals(a))break;let S=w;s[S]===13&&s[S+1]===10&&(S+=2);let D=s.indexOf(`\r
|
|
107
|
-
\r
|
|
108
|
-
`,S);if(D===-1)break;let _=s.slice(S,D).toString("utf-8"),Z=D+4,R=s.indexOf(l,Z),ae=R!==-1?R-2:s.length;F.push({headers:_,body:s.slice(Z,ae)}),g=R!==-1?R:s.length}for(let y of F){let w=y.headers.match(/name="([^"]+)"/);if(!w)continue;let S=w[1];if(S==="screenshot")r=y.body;else if(S==="feedback")p=y.body.toString("utf-8");else if(S==="color")f=y.body.toString("utf-8");else if(S==="provider")N=y.body.toString("utf-8");else if(S==="model")U=y.body.toString("utf-8");else if(S==="goal")C=y.body.toString("utf-8");else if(S==="pageUrl")I=y.body.toString("utf-8");else if(S==="viewport")H=y.body.toString("utf-8");else if(S==="planId")L=y.body.toString("utf-8");else if(S==="manifest")G=y.body.toString("utf-8");else if(S==="tasks")k=y.body.toString("utf-8");else if(S==="sourceId")J=y.body.toString("utf-8");else if(S.startsWith("screenshot-")){let D=S.slice(11);try{let _=decodeURIComponent(D);B.push({pathname:_,data:y.body})}catch{}}else if(S.startsWith("image-")){let D=S.split("-"),_=parseInt(D[D.length-1],10),Z=D.slice(1,-1).join("-");Z&&!isNaN(_)&&O.push({annotationId:Z,index:_,data:y.body})}}if(!r)throw new Error("Missing screenshot field");return p||(p=""),{screenshot:r,feedback:p,color:f,provider:N,model:U,goal:C,pageUrl:I,viewport:H,planId:L,manifest:G,tasks:k,sourceId:J,pastedImages:O,pageScreenshots:B}}function Ft(i){return new Promise((t,n)=>{let e=[];i.on("data",s=>e.push(s)),i.on("end",()=>t(Buffer.concat(e))),i.on("error",n)})}function ue(i,t){let n=[];if(i.annotations.length>0){n.push("## Annotations");for(let e of i.annotations){let s=e.elements.map(r=>{let p=[r.selector];return r.reactComponent&&p.push(`(${r.reactComponent})`),p.join(" ")}).join(", "),l=e.instruction||"No text";n.push(`- id=${e.id} [${e.type}] ${l} \u2192 Elements: ${s||"none"}`);let a=t?.[e.id];if(a&&a.length>0)for(let r of a)n.push(` Attached image: use the Read tool to view ${r}`)}}if(i.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let e of i.styleModifications){let s=e.element?.reactComponent?`(${e.element.reactComponent})`:"";for(let l of e.changes)n.push(`- ${e.selector} ${s}: ${l.property} ${l.original} \u2192 ${l.modified}`)}}if(i.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let e of i.spacingTokenChanges){n.push(`
|
|
109
|
-
### ${e.tokenName}: ${e.originalPx}px \u2192 ${e.newPx}px`);for(let s of e.affectedElements){let l=s.reactComponent?` (${s.reactComponent})`:"";s.matchedClass&&s.suggestedClass?n.push(`- ${s.selector}${l}: \`${s.matchedClass}\` \u2192 \`${s.suggestedClass}\``):n.push(`- ${s.selector}${l}: ${s.property} ${e.originalPx}px \u2192 ${e.newPx}px`),n.push(` class="${s.className}"`)}}}if(i.inspectedElement){let e=i.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let s=[e.selector];e.reactComponent&&s.push(`(${e.reactComponent})`),e.context&&s.push(`in ${e.context}`),e.textContent&&s.push(`"${e.textContent.slice(0,80)}"`),n.push(`- ${s.join(" ")}`)}return n.join(`
|
|
110
|
-
`)}function Ve(i,t,n){let e=[],l=new Set(t.annotations.map(a=>a.pathname).filter(Boolean)).size>1;if(e.push("You are reviewing a UI screenshot with developer annotations."),e.push(""),!l&&n?.provider!=="codex"&&(e.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${i}`),e.push("")),e.push(`The developer annotated their running app at ${t.url} (${t.viewport.width}x${t.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){e.push(""),e.push("## Previous Conversation");let a=0;for(let r of n.threadHistory)if(r.role==="human")a++,r.replyToQuestion?(e.push(`### Round ${a} (human) \u2014 reply`),e.push(`"${r.replyToQuestion}"`)):(e.push(`### Round ${a} (human)`),r.feedbackSummary&&e.push(`Annotations: ${r.feedbackSummary}`),r.annotationIds&&r.annotationIds.length>0&&e.push(`Annotation IDs: ${r.annotationIds.join(", ")}`));else if(r.question)e.push(`### Round ${a} (assistant) \u2014 question`),e.push(`"${r.question}"`);else{if(e.push(`### Round ${a} (assistant)`),r.responseText&&e.push(`Response: ${r.responseText}`),r.resolutions&&r.resolutions.length>0)for(let p of r.resolutions){let f=p.finalScope??p.inferredScope,N=f?` [${f.breadth} ${f.target}]`:"";e.push(`- ${p.annotationId}: ${p.status}${N} \u2014 ${p.summary}`),p.filesModified&&p.filesModified.length>0&&e.push(` Files: ${p.filesModified.join(", ")}`)}r.toolsUsed&&r.toolsUsed.length>0&&e.push(`Tools used: ${r.toolsUsed.join(", ")}`)}e.push(""),e.push("The current round is shown in full below.")}if(n?.designModel){e.push(""),e.push("## Established Design Policies"),e.push("This project has an established design model (stored in .popmelt/model.json), extracted from the developer's previous design decisions. When making changes, follow these patterns unless the developer explicitly overrides them. When asked about design tokens, component patterns, or design decisions, reference this model as the authoritative source.");let a=n.designModel.rules;if(Array.isArray(a)&&a.length>0){e.push(""),e.push("Rules:");for(let f of a)typeof f=="string"&&e.push(`- ${f}`)}let r=n.designModel.tokens;r&&typeof r=="object"&&(e.push(""),e.push("Design tokens:"),e.push("```json"),e.push(JSON.stringify(r,null,2)),e.push("```"));let p=n.designModel.components;p&&typeof p=="object"&&(e.push(""),e.push("Component patterns:"),e.push("```json"),e.push(JSON.stringify(p,null,2)),e.push("```")),e.push(""),e.push("### Novel Pattern Detection"),e.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),e.push("<novel>"),e.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),e.push("</novel>"),e.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),e.push("- `element`: What you are styling or creating"),e.push("- `decision`: What you decided to do (specific values)"),e.push("- `reason`: Why this is novel (what is missing from the model)"),e.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(e.push(""),e.push("## Design Context"),e.push("This project uses Popmelt for design governance. Design decisions are stored in .popmelt/decisions/ (JSON files). A materialized design model may exist at .popmelt/model.json. When the developer asks about design tokens, patterns, or past decisions, check these files first before searching source code.")),l){let a=n?.screenshotPaths??{},r=new Map;for(let p of t.annotations){let f=p.pathname||new URL(t.url).pathname;r.has(f)||r.set(f,[]),r.get(f).push(p)}e.push(""),e.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[p,f]of r){e.push(""),e.push(`## Page: ${p}`);let N=a[p];N&&n?.provider!=="codex"?e.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${N}`):!N&&n?.provider!=="codex"&&(Object.keys(a).length===0?(e.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${i}`),e.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):e.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let U={...t,annotations:f,styleModifications:t.styleModifications},C=ue(U,n?.imagePaths);C&&(e.push(""),e.push(C))}}else{let a=ue(t,n?.imagePaths);a&&(e.push(""),e.push(a))}return e.push(""),e.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),e.push(""),e.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),e.push(""),e.push("## Resolution"),e.push("After completing all work, output a resolution block listing what you did for each annotation:"),e.push("<resolution>"),e.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),e.push("</resolution>"),e.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),e.push(""),e.push("### Scope classification"),e.push("Each resolution MUST include scope fields:"),e.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),e.push("- `inferredScope`: What scope the change actually has, based on what you modified."),e.push("Scope has two dimensions:"),e.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),e.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),e.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),e.push("If you cannot confidently determine scope, set it to null."),e.push(""),e.push("## Questions"),e.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),e.push('<question>What do you mean by "..."?</question>'),e.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),e.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),e.join(`
|
|
111
|
-
`)}function Ke(i){return i.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Ze(i,t,n,e){let s=[];s.push("You are continuing work on a UI based on the developer's reply to your question."),s.push(""),n!=="codex"&&s.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${i}`);let l=t.find(a=>a.role==="human"&&a.feedbackContext);if(l?.feedbackContext&&(s.push(""),s.push(l.feedbackContext)),t.length>0){s.push(""),s.push("## Conversation History");let a=0;for(let r of t)r.role==="human"?(a++,r.replyToQuestion?(s.push(`### Round ${a} (human) \u2014 reply`),s.push(`"${r.replyToQuestion}"`)):(s.push(`### Round ${a} (human)`),r.feedbackSummary&&s.push(`Annotations: ${r.feedbackSummary}`))):r.question?(s.push(`### Round ${a} (assistant) \u2014 question`),s.push(`"${r.question}"`)):(s.push(`### Round ${a} (assistant)`),r.responseText&&s.push(`Response: ${r.responseText}`))}if(s.push(""),s.push("The developer answered your question. Continue working based on their reply."),s.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),s.push(""),s.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),e&&e.length>0){s.push(""),s.push("## Attached Images"),s.push("The developer attached reference images with their reply:");for(let a of e)s.push(`Attached image: use the Read tool to view the image at: ${a}`)}return s.push(""),s.push("## Resolution"),s.push("After completing all work, output a resolution block listing what you did for each annotation:"),s.push("<resolution>"),s.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),s.push("</resolution>"),s.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),s.push(""),s.push("### Scope classification"),s.push("Each resolution MUST include scope fields:"),s.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),s.push("- `inferredScope`: What scope the change actually has, based on what you modified."),s.push("Scope has two dimensions:"),s.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),s.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),s.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),s.push("If you cannot confidently determine scope, set it to null."),s.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),s.push(""),s.push("## Questions"),s.push("If you still need clarification, output:"),s.push("<question>Your question here</question>"),s.push("You may output BOTH a <resolution> and a <question> in the same response."),s.join(`
|
|
112
|
-
`)}function Lt(i){if(typeof i!="object"||i===null)return!1;let t=i;return(t.breadth==="instance"||t.breadth==="pattern")&&(t.target==="element"||t.target==="component"||t.target==="token")}function Ht(i){if(typeof i!="object"||i===null||typeof i.annotationId!="string"||i.status!=="resolved"&&i.status!=="needs_review"||typeof i.summary!="string")return!1;let t=i;for(let n of["declaredScope","inferredScope","finalScope"])if(t[n]!==void 0&&t[n]!==null&&!Lt(t[n]))return!1;return!0}function et(i){let t=i.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!t||!t[1])return[];try{let n=JSON.parse(t[1]);return Array.isArray(n)?n.filter(Ht):[]}catch{return[]}}function tt(i){let t=i.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!t?.[1])return[];try{let n=JSON.parse(t[1]);return Array.isArray(n)?n.filter(e=>{if(typeof e!="object"||e===null)return!1;let s=e;return(s.category==="token"||s.category==="component"||s.category==="element")&&typeof s.element=="string"&&typeof s.decision=="string"&&typeof s.reason=="string"}):[]}catch{return[]}}var ve=class{constructor(t=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=t}setProcessor(t){this.processor=t}get active(){let t=this.activeJobs.values().next();return t.done?null:t.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(t,n){n?this.activeProcesses.set(t,n):this.activeProcesses.delete(t)}enqueue(t){return this.queue.push(t),this.processNext(),this.queue.length+this.activeJobs.size}addListener(t){return this.listeners.add(t),()=>this.listeners.delete(t)}broadcast(t,n,e){let s=this.bufferEvent(n,t);for(let l of this.listeners)l(s,n,e)}bufferEvent(t,n){let e=this.eventBuffers.get(t);e||(e={events:[],nextSeq:0},this.eventBuffers.set(t,e));let s={...n,seq:e.nextSeq++};return e.events.push(s),e.events.length>1e4&&e.events.splice(0,e.events.length-1e4),s}getBufferedEvents(t,n=-1){let e=this.eventBuffers.get(t),s=this.accumulators.get(t)??{response:"",thinking:""},l=this.activeJobs.has(t);if(!e)return null;let a=n<0?e.events:e.events.filter(r=>r.seq>n);return{jobId:t,events:a,currentSeq:e.nextSeq-1,accumulated:{...s},jobActive:l}}accumulateText(t,n,e){let s=this.accumulators.get(t);s||(s={response:"",thinking:""},this.accumulators.set(t,s)),s[n]+=e}getAccumulated(t){return this.accumulators.get(t)??null}scheduleBufferCleanup(t){let n=this.cleanupTimers.get(t);n&&clearTimeout(n);let e=setTimeout(()=>{this.eventBuffers.delete(t),this.accumulators.delete(t),this.cleanupTimers.delete(t)},6e4);this.cleanupTimers.set(t,e)}cancelJob(t){let n=this.activeProcesses.get(t),e=this.activeJobs.get(t);return!n||!e?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(t),this.activeJobs.delete(t),e.status="error",e.error="Cancelled by user",this.broadcast({type:"error",jobId:e.id,message:"Cancelled by user",cancelled:!0},e.id,e.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let t=Array.from(this.activeJobs.keys());for(let n of t)this.cancelJob(n);return!0}destroy(){for(let t of this.activeProcesses.values())t.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}async destroyAsync(t=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let e of n)try{e.kill("SIGTERM")}catch{}await Promise.all(n.map(e=>new Promise(s=>{let l=!1,a=()=>{l||(l=!0,s())};e.on("exit",a),e.on("error",a),setTimeout(()=>{if(!l){try{e.kill("SIGKILL")}catch{}setTimeout(a,500)}},t)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let t=this.queue.shift();this.activeJobs.set(t.id,t),t.status="running",this.broadcast({type:"job_started",jobId:t.id,position:0,threadId:t.threadId},t.id,t.sourceId),this.processor(t).catch(n=>{t.status="error",t.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:t.id,message:t.error},t.id,t.sourceId)}).finally(()=>{this.activeJobs.delete(t.id),this.activeProcesses.delete(t.id),this.scheduleBufferCleanup(t.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id)})}}};import{mkdir as jt,readFile as zt,writeFile as Wt}from"fs/promises";import{dirname as Gt,join as qt}from"path";var Qt={version:1,threads:{}},we=class{constructor(t){this.cache=null;this.writeChain=Promise.resolve();this.filePath=qt(t,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let t=await zt(this.filePath,"utf-8"),n=JSON.parse(t);if(n&&n.version===1&&n.threads)return this.cache=n,this.cache}catch{}return this.cache={...Qt,threads:{}},this.cache}async getThread(t){return(await this.load()).threads[t]??null}async findContinuationThread(t){if(t.length===0)return null;let n=await this.load(),e=new Set(t);for(let s of Object.values(n.threads))if(s.elementIdentifiers.some(a=>e.has(a)))return s;return null}async createThread(t,n){let e=await this.load(),s={id:t,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return e.threads[t]=s,await this.persist(),s}async appendMessage(t,n){let s=(await this.load()).threads[t];s&&(s.messages.push(n),s.updatedAt=Date.now(),await this.persist())}async addElementIdentifiers(t,n){let s=(await this.load()).threads[t];if(!s)return;let l=new Set(s.elementIdentifiers);for(let a of n)l.has(a)||s.elementIdentifiers.push(a);s.updatedAt=Date.now(),await this.persist()}async listRecent(t=5){let n=await this.load(),e=Object.values(n.threads);return e.sort((s,l)=>l.updatedAt-s.updatedAt),e.slice(0,t).map(s=>{let a=s.messages.find(r=>r.role==="human")?.feedbackSummary||"[thread]";return{id:s.id,createdAt:s.createdAt,updatedAt:s.updatedAt,preview:a,messageCount:s.messages.length,elementIdentifiers:s.elementIdentifiers}})}async getThreadHistory(t,n=6){let e=await this.getThread(t);return!e||e.messages.length===0?[]:e.messages.length<=n?e.messages:[e.messages[0],...e.messages.slice(-(n-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await jt(Gt(this.filePath),{recursive:!0}),await Wt(this.filePath,JSON.stringify(this.cache,null,2))}catch(t){console.error("[ThreadStore] Failed to persist:",t)}}),await this.writeChain}};var Se="0.6.6";var cn=1111,ln=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],dn=1800*1e3,un=3600*1e3;function ot(i){if(!i)return!1;try{let t=new URL(i);return t.hostname==="localhost"||t.hostname==="127.0.0.1"}catch{return!1}}function pn(i){let t=[];for(let n of i)if(n.type==="delta"){let e=n.text;if(!e)continue;let s=t[t.length-1];s&&s.kind==="text"?s.text+=e:t.push({kind:"text",text:e})}else if(n.type==="tool_use"){let e=n.tool||"",s=n.file??void 0,l=n.content??void 0,a=s?s.split("/").pop()??s:void 0,r;switch(e){case"Read":r=a?`Reading ${a}`:"Reading file";break;case"Edit":r=a?`Editing ${a}`:"Editing file";break;case"Write":r=a?`Writing ${a}`:"Writing file";break;case"Bash":r=l?l.split(`
|
|
113
|
-
`)[0].trim().slice(0,60):"Running command";break;case"Glob":r="Searching files";break;case"Grep":r="Searching code";break;case"WebFetch":r="Fetching page";break;case"WebSearch":r="Searching web";break;default:r=e?`Using ${e}`:"tool";break}let p=s??l??void 0,f=t[t.length-1];f&&f.kind==="tool_group"&&f.tool===e?f.items.push({label:r,detail:p}):t.push({kind:"tool_group",tool:e,items:[{label:r,detail:p}]})}return t}function hn(i,t){let n=i.headers.origin;ot(n)&&(t.setHeader("Access-Control-Allow-Origin",n),t.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type"))}function v(i,t,n){i.writeHead(t,{"Content-Type":"application/json"}),i.end(JSON.stringify(n))}function fn(i,t){if(!i)return t;let n=i.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return t;let[,e,s,l]=n;return`\x1B[38;2;${parseInt(e,16)};${parseInt(s,16)};${parseInt(l,16)}m${t}\x1B[0m`}function Ce(i,t){try{i.res.write(`event: ${t.type}
|
|
114
|
-
data: ${JSON.stringify(t)}
|
|
115
|
-
|
|
116
|
-
`)}catch{}}async function xe(i){try{let t=new AbortController,n=setTimeout(()=>t.abort(),500),e=await fetch(`http://127.0.0.1:${i}/status`,{signal:t.signal});return clearTimeout(n),e.ok?await e.json():null}catch{return null}}function mn(i,t){return new Promise((n,e)=>{let s=a=>{i.removeListener("listening",l),e(a)},l=()=>{i.removeListener("error",s),n()};i.once("error",s),i.once("listening",l),i.listen(t,"127.0.0.1")})}async function it(i={}){let t=i.port??cn,n=i.projectRoot??process.cwd(),e=Vt("sha256").update(n).digest("hex").slice(0,12),s=i.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),l=i.tempDir??ne(sn(),"popmelt-bridge"),a=i.maxTurns??40,r=i.maxBudgetUsd??1,p=[...i.allowedTools??ln],f=i.claudePath??"claude",N=i.provider??"claude",U=i.timeoutMs,C=t,I={};for(let o of["claude","codex"])try{let c=Xt("which",[o],{encoding:"utf-8"}).trim();I[o]={available:!0,path:c}}catch{I[o]={available:!1,path:null}}function H(o,c){return new Promise(h=>{let d=Yt(c,["--version"],{stdio:["ignore","ignore","ignore"]}),m=!1,u=$=>{m||(m=!0,h($))},b=setTimeout(()=>{d.kill("SIGTERM"),u(!0)},5e3);d.on("error",()=>{clearTimeout(b),u(!1)}),d.on("close",$=>{clearTimeout(b),u($===0)})})}let[L,G]=await Promise.all([Ee(n),Re(n)]);I.claude&&(I.claude.mcp=L),I.codex&&(I.codex.mcp=G),L.found&&L.name&&p.push(`mcp__${L.name}__*`),await Kt(l,{recursive:!0}),st(l).catch(()=>{});let k=new ve(1),J=new Set,O=new we(n),B=new me(n),g=new ge(n,B,{claudePath:f,onEvent:o=>{for(let c of J)Ce(c,o)}}),F=20,y=300*1e3,w=[],S=null,D;k.addListener((o,c,h)=>{for(let d of J)(!h||!d.sourceId||d.sourceId===h)&&Ce(d,o)}),k.setProcessor(async o=>{let c=o._replyPrompt,h=o._replyImagePaths,d=o.provider??N,m;if(o.threadId){let E=await O.getThread(o.threadId);if(E){for(let x=E.messages.length-1;x>=0;x--)if(E.messages[x].sessionId){m=E.messages[x].sessionId;break}}}let u;if(m&&c){let E=(await O.getThread(o.threadId))?.messages.filter(z=>z.role==="human").pop();if(u=E?.replyToQuestion||E?.feedbackSummary||"",h&&h.length>0){u+=`
|
|
117
|
-
|
|
118
|
-
The developer attached reference images with their reply:`;for(let z of h)u+=`
|
|
119
|
-
Attached image: use the Read tool to view the image at: ${z}`}u+=`
|
|
120
|
-
|
|
121
|
-
After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(m)u=ue(o.feedback,o.imagePaths)+`
|
|
122
|
-
|
|
123
|
-
Follow the developer's instructions. If they ask for changes, apply them to the source files.
|
|
124
|
-
|
|
125
|
-
After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(d!=="codex"?`
|
|
126
|
-
|
|
127
|
-
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${o.screenshotPath}`:"");else{let E=!c&&o.threadId?await O.getThreadHistory(o.threadId):void 0,x=c?null:await g.loadModel();u=c??Ve(o.screenshotPath,o.feedback,{threadHistory:E&&E.length>0?E:void 0,provider:d,imagePaths:o.imagePaths,designModel:x??void 0,screenshotPaths:o.screenshotPaths})}let b=fn(o.color,`[\u22B9 ${C}:${o.id}]`),$=o.screenshotPaths&&Object.keys(o.screenshotPaths).length>0?`${Object.keys(o.screenshotPaths).length} pages [${Object.keys(o.screenshotPaths).join(", ")}]`:o.screenshotPath;console.log(`${b} Reviewing ${$} (provider: ${d})${o.threadId?` (thread: ${o.threadId})`:""}${m?` (resuming: ${m.slice(0,8)})`:""}`);let X=(E,x)=>{E.type==="delta"&&"text"in E?k.accumulateText(x,"response",E.text):E.type==="thinking"&&"text"in E&&k.accumulateText(x,"thinking",E.text),k.broadcast(E,x,o.sourceId)},{process:K,result:q}=d==="codex"?Be(o.id,{prompt:u,projectRoot:n,screenshotPath:o.screenshotPath,resumeSessionId:m,model:o.model,onEvent:X}):fe(o.id,{prompt:u,projectRoot:n,maxTurns:a,maxBudgetUsd:r,allowedTools:p,claudePath:f,resumeSessionId:m,model:o.model,timeoutMs:U,onEvent:X});k.setActiveProcess(o.id,K);let P=await q;if(o.result=P.text,P.success){console.log(`${b} Iteration complete`),P.fileEdits&&P.fileEdits.length>0&&console.log(`${b} Captured ${P.fileEdits.length} file edit(s): ${P.fileEdits.map(j=>`${j.tool} ${j.file_path}`).join(", ")}`),o.status="done";let E=Ke(P.text),x=et(P.text);if(x.length>0&&o.annotationIds&&o.annotationIds.length>0){let j=new Set(o.annotationIds);x.every(M=>j.has(M.annotationId))||(x=x.map((M,W)=>({...M,annotationId:o.annotationIds[W%o.annotationIds.length]})))}let z=P.fileEdits&&P.fileEdits.length>0?P.fileEdits.map(j=>`${j.tool} ${j.file_path.split("/").pop()}`):P.toolsUsed,V=k.getBufferedEvents(o.id),se=V?pn(V.events):void 0;o.threadId&&await O.appendMessage(o.threadId,{role:"assistant",timestamp:Date.now(),jobId:o.id,responseText:P.text,resolutions:x.length>0?x:void 0,question:E??void 0,sessionId:P.sessionId,toolsUsed:z,segments:se&&se.length>0?se:void 0,model:o.model,provider:o.provider}),B.captureGitDiff(n).then(async j=>{let A=Date.now(),M=o.imagePaths?Object.values(o.imagePaths).flat():[],W=[];if(o.imagePaths)for(let[ie,T]of Object.entries(o.imagePaths))for(let Q=0;Q<T.length;Q++)W.push(`screenshots/p-${o.id}-${ie}-${Q}.png`);await B.persist({version:1,id:o.id,createdAt:o.createdAt,completedAt:A,durationMs:A-o.createdAt,url:o.feedback.url,viewport:o.feedback.viewport,screenshotPath:`screenshots/s-${o.id}.png`,pastedImagePaths:W,annotations:o.feedback.annotations,styleModifications:o.feedback.styleModifications,inspectedElement:o.feedback.inspectedElement,provider:o.provider,model:o.model,sessionId:P.sessionId,threadId:o.threadId,responseText:P.text,resolutions:x.length>0?x:[],question:E??void 0,fileEdits:P.fileEdits??[],toolsUsed:z,gitDiff:j},o.screenshotPath,M)}).catch(()=>{}),x.length>0&&x.some(A=>(A.finalScope??A.inferredScope)?.breadth==="pattern")&&g.run().catch(()=>{}),E&&(console.log(`${b} \u{1F4AC} Question detected: "${E.slice(0,120)}" \u2192 broadcasting to ${J.size} SSE clients (threadId=${o.threadId??o.id}, annotationIds=${o.annotationIds?.join(",")??"none"})`),k.broadcast({type:"question",jobId:o.id,threadId:o.threadId??o.id,question:E,annotationIds:o.annotationIds},o.id,o.sourceId));let ee=tt(P.text);ee.length>0&&(console.log(`${b} Novel pattern(s): ${ee.map(j=>`${j.category}/${j.element}`).join(", ")}`),k.broadcast({type:"novel_patterns",jobId:o.id,patterns:ee,threadId:o.threadId},o.id,o.sourceId)),k.broadcast({type:"done",jobId:o.id,success:!0,resolutions:x.length>0?x:void 0,responseText:P.text,threadId:o.threadId},o.id,o.sourceId),w.push({id:o.id,status:"done",completedAt:Date.now(),threadId:o.threadId,annotationIds:o.annotationIds})}else console.error(`${b} Error: ${P.error}`),o.status="error",o.error=P.error,o.threadId&&await O.appendMessage(o.threadId,{role:"assistant",timestamp:Date.now(),jobId:o.id,error:P.error||"Unknown error",model:o.model,provider:o.provider}),k.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:P.error||"Unknown error"},o.id,o.sourceId),w.push({id:o.id,status:"error",completedAt:Date.now(),error:P.error,threadId:o.threadId,annotationIds:o.annotationIds});let Y=Date.now()-y;for(;w.length>0&&(w[0].completedAt<Y||w.length>F);)w.shift()});let _=nn(async(o,c)=>{if(hn(o,c),o.method==="OPTIONS"){c.writeHead(204),c.end();return}let h=o.url||"/",d=h.split("?")[0],m=new URL(h,`http://127.0.0.1:${C}`),u=m.pathname;try{if(o.method==="POST"&&u==="/send")await Z(o,c);else if(o.method==="GET"&&u==="/events")ae(o,c);else if(o.method==="GET"&&u==="/status")pe(c);else if(o.method==="PATCH"&&u==="/config")await rt(o,c);else if(o.method==="POST"&&u==="/shutdown")v(c,200,{ok:!0}),setTimeout(()=>process.exit(0),100);else if(o.method==="GET"&&u==="/capabilities")v(c,200,{providers:I});else if(o.method==="POST"&&u==="/mcp/install")await lt(o,c);else if(o.method==="POST"&&u==="/reply")await R(o,c);else if(o.method==="POST"&&u==="/cancel")at(o,c);else if(o.method==="POST"&&u==="/materialize")await ct(c);else if(o.method==="POST"&&u==="/model/component")await dt(o,c);else if(o.method==="DELETE"&&u==="/model/component")await ut(o,c);else if(o.method==="PATCH"&&u==="/model/token")await pt(o,c);else if(o.method==="DELETE"&&u==="/model/token")await ht(o,c);else if(o.method==="GET"&&u==="/model"){let b=await g.loadModel();v(c,200,{model:b})}else if(o.method==="GET"&&u.startsWith("/jobs/")&&u.endsWith("/events")){let b=u.slice(6,u.length-7),$=parseInt(m.searchParams.get("afterSeq")??"-1",10),X=k.getBufferedEvents(b,isNaN($)?-1:$);X?v(c,200,X):v(c,404,{error:"Unknown job"})}else if(o.method==="GET"&&d.startsWith("/files/"))await yt(d.slice(7),c);else if(o.method==="GET"&&u==="/threads/recent"){let b=Math.min(Math.max(parseInt(m.searchParams.get("limit")??"5",10)||5,1),20),$=await O.listRecent(b);v(c,200,$)}else if(o.method==="GET"&&u.startsWith("/thread/")){let b=u.slice(8);await vt(b,c)}else o.method==="GET"&&(u==="/canvas"||u==="/canvas/")?ft(o,c):o.method==="GET"&&u==="/canvas/manifest"?await mt(c):o.method==="GET"&&u==="/canvas/app.mjs"?await gt(c):v(c,404,{error:"Not found"})}catch(b){console.error("[Bridge] Request error:",b),v(c,500,{error:b instanceof Error?b.message:"Internal error"})}});async function Z(o,c){let{screenshot:h,feedback:d,color:m,provider:u,model:b,sourceId:$,pastedImages:X,pageScreenshots:K}=await Me(o),q;try{q=JSON.parse(d)}catch{v(c,400,{error:"Invalid feedback JSON"});return}let P=Oe().slice(0,8),Y={};if(K.length>0)for(let T of K){let Q=encodeURIComponent(T.pathname),oe=ne(l,`screenshot-${P}-${Q}.png`);await Pe(oe,T.data),Y[T.pathname]=oe}let E=ne(l,`screenshot-${P}.png`);await Pe(E,h);let x={};if(X.length>0)for(let T of X){let Q=ne(l,`pasted-${P}-${T.annotationId}-${T.index}.png`);await Pe(Q,T.data),x[T.annotationId]||(x[T.annotationId]=[]),x[T.annotationId].push(Q)}let z=q.annotations.map(T=>T.linkedSelector?T.pathname?`${T.pathname}:${T.linkedSelector}`:T.linkedSelector:null).filter(T=>!!T),V;if(z.length>0){let T=await O.findContinuationThread(z);T?(V=T.id,await O.addElementIdentifiers(V,z)):V=(await O.createThread(P,z)).id}else V=(await O.createThread(P,[])).id;let se=q.annotations.map(T=>T.id),ee=Object.keys(Y).length>0,j={id:P,status:"queued",screenshotPath:E,feedback:q,createdAt:Date.now(),color:m,threadId:V,annotationIds:se,provider:u==="claude"||u==="codex"?u:void 0,model:b||void 0,...Object.keys(x).length>0?{imagePaths:x}:{},sourceId:$||void 0,...ee?{screenshotPaths:Y}:{}},A=new Set(q.annotations.map(T=>T.pathname).filter(Boolean)),M;if(A.size>1){let T=new Map;for(let Q of q.annotations){let oe=Q.pathname||"(unknown)";T.has(oe)||T.set(oe,[]),T.get(oe).push(Q.instruction||`[${Q.type}]`)}M=[...T.entries()].map(([Q,oe])=>`\`${Q}\`
|
|
128
|
-
${oe.map(St=>`- ${St}`).join(`
|
|
129
|
-
`)}`).join(`
|
|
130
|
-
`)}else M=q.annotations.map(T=>T.instruction||`[${T.type}]`).join("; ");let W=ue(q,Object.keys(x).length>0?x:void 0);await O.appendMessage(V,{role:"human",timestamp:Date.now(),jobId:P,screenshotPath:E,...ee?{screenshotPaths:Y}:{},...Object.keys(x).length>0?{imagePaths:x}:{},annotationIds:se,feedbackSummary:M,feedbackContext:W||void 0});let ie=k.enqueue(j);v(c,200,{jobId:P,position:ie,threadId:V})}async function R(o,c){let h=o.headers["content-type"]||"",d,m,u,b,$,X,K=[];if(h.includes("multipart/form-data")){let A=await Me(o),M=A.feedback?JSON.parse(A.feedback):{};d=M.threadId,m=M.reply,u=M.color,b=M.provider,$=M.model,X=M.sourceId||A.sourceId;for(let W of A.pastedImages)K.push(W.data)}else{let A=[];for await(let ie of o)A.push(typeof ie=="string"?Buffer.from(ie):ie);let M=Buffer.concat(A).toString("utf-8"),W;try{W=JSON.parse(M)}catch{v(c,400,{error:"Invalid JSON"});return}d=W.threadId,m=W.reply,u=W.color,b=W.provider,$=W.model,X=W.sourceId}if(!d||!m){v(c,400,{error:"Missing threadId or reply"});return}if(!await O.getThread(d)){v(c,404,{error:"Thread not found"});return}let P=Oe().slice(0,8),Y=[];for(let A=0;A<K.length;A++){let M=ne(l,`reply-${P}-${A}.png`);await Pe(M,K[A]),Y.push(M)}let E="";{let A=await O.getThreadHistory(d);for(let M=A.length-1;M>=0;M--)if(A[M].screenshotPath){E=A[M].screenshotPath;break}}if(!E){v(c,400,{error:"No screenshot available"});return}await O.appendMessage(d,{role:"human",timestamp:Date.now(),jobId:P,replyToQuestion:m,screenshotPath:E,...Y.length>0?{replyImagePaths:Y}:{}});let x=await O.getThreadHistory(d),z=[];for(let A of x)if(A.annotationIds)for(let M of A.annotationIds)z.includes(M)||z.push(M);let V=b==="claude"||b==="codex"?b:void 0,se=Ze(E,x,V,Y.length>0?Y:void 0),ee={id:P,status:"queued",screenshotPath:E,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:u,threadId:d,annotationIds:z.length>0?z:void 0,provider:V,model:$||void 0,sourceId:X||void 0};ee._replyPrompt=se,Y.length>0&&(ee._replyImagePaths=Y);let j=k.enqueue(ee);v(c,200,{jobId:P,position:j,threadId:d})}function ae(o,c){c.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),c.write(`event: connected
|
|
131
|
-
data: {"status":"connected"}
|
|
132
|
-
|
|
133
|
-
`),o.headers.origin&&ot(o.headers.origin)&&s!==o.headers.origin&&(s=o.headers.origin);let d=new URL(o.url||"/",`http://127.0.0.1:${C}`).searchParams.get("sourceId")||void 0,m={id:Oe().slice(0,8),res:c,sourceId:d};J.add(m),o.on("close",()=>{J.delete(m)})}function pe(o){let c=k.allActive;v(o,200,{ok:!0,version:Se,projectId:e,devOrigin:s,activeJob:c[0]?{id:c[0].id,status:c[0].status}:null,activeJobs:c.map(h=>({id:h.id,status:h.status,threadId:h.threadId,annotationIds:h.annotationIds,color:h.color})),queueDepth:k.depth,recentJobs:w})}async function rt(o,c){let h=await new Promise(d=>{let m="";o.on("data",u=>{m+=u.toString()}),o.on("end",()=>d(m))});try{let d=JSON.parse(h);typeof d.devOrigin=="string"&&(s=d.devOrigin||null),v(c,200,{ok:!0,devOrigin:s})}catch{v(c,400,{error:"Invalid JSON"})}}async function at(o,c){let d=new URL(o.url||"/",`http://127.0.0.1:${C}`).searchParams.get("jobId"),u=(d?k.allActive.filter($=>$.id===d):k.allActive).map($=>$.threadId).filter(Boolean),b=d?k.cancelJob(d):k.cancelActive();for(let $ of u)await O.appendMessage($,{role:"assistant",timestamp:Date.now(),jobId:d||"",cancelled:!0});v(c,200,{cancelled:b})}async function ct(o){if(g.isRunning){v(o,200,{skipped:!0,reason:"Already running"});return}let c=await g.getUnmaterializedPatternDecisions();if(c.length===0){v(o,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}g.run().catch(()=>{}),v(o,200,{started:!0,decisionCount:c.length,decisionIds:c.map(h=>h.id)})}async function lt(o,c){let h=[];for await(let $ of o)h.push(typeof $=="string"?Buffer.from($):$);let d;if(h.length>0)try{d=JSON.parse(Buffer.concat(h).toString("utf-8")).serverUrl}catch{}let m=[];I.claude?.available&&I.claude.mcp&&!I.claude.mcp.found&&m.push(await Xe(d)),I.codex?.available&&I.codex.mcp&&!I.codex.mcp.found&&m.push(await Ye(d));let[u,b]=await Promise.all([Ee(n),Re(n)]);I.claude&&(I.claude.mcp=u),I.codex&&(I.codex.mcp=b),v(c,200,{results:m,capabilities:{providers:I}})}async function dt(o,c){let h=[];for await(let u of o)h.push(typeof u=="string"?Buffer.from(u):u);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{v(c,400,{error:"Invalid JSON"});return}if(!d.name||typeof d.name!="string"){v(c,400,{error:"Missing or invalid name"});return}let m=await g.addComponent(d.name);v(c,200,m)}async function ut(o,c){let h=[];for await(let u of o)h.push(typeof u=="string"?Buffer.from(u):u);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{v(c,400,{error:"Invalid JSON"});return}if(!d.name||typeof d.name!="string"){v(c,400,{error:"Missing or invalid name"});return}let m=await g.removeComponent(d.name);v(c,200,m)}async function pt(o,c){let h=[];for await(let u of o)h.push(typeof u=="string"?Buffer.from(u):u);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{v(c,400,{error:"Invalid JSON"});return}if(!d.path||typeof d.path!="string"||typeof d.value!="string"){v(c,400,{error:"Missing or invalid path/value"});return}let m=await g.updateToken(d.path,d.value);v(c,200,m)}async function ht(o,c){let h=[];for await(let u of o)h.push(typeof u=="string"?Buffer.from(u):u);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{v(c,400,{error:"Invalid JSON"});return}if(!d.path||typeof d.path!="string"){v(c,400,{error:"Missing or invalid path"});return}let m=await g.removeToken(d.path);v(c,200,m)}function ft(o,c){let h=s??"http://localhost:3000";if(!s){let m=o.headers.referer||o.headers.origin;if(m)try{let u=new URL(typeof m=="string"?m:m[0]||"");(u.hostname==="localhost"||u.hostname==="127.0.0.1")&&(h=u.origin)}catch{}}let d=De(C,h);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(d)}async function mt(o){let c=Date.now();if(S&&c<S.expires){v(o,200,S.data);return}try{let{scanForComponents:h}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:d}=await import("./render-generator-HWFLZYC3.mjs"),m=await h(n);S={data:m,expires:c+5e3},d(m,n,D).then(u=>{D=u}).catch(u=>console.warn("[Bridge] Render generation failed:",u)),v(o,200,m)}catch(h){console.error("[Bridge] Scanner error:",h),v(o,500,{error:"Failed to scan components"})}}async function gt(o){let c=[ne(n,"node_modules","@popmelt.com","core","dist","canvas.mjs"),ne(n,"packages","popmelt","dist","canvas.mjs")];try{let h=an(import.meta.url);c.unshift(ne(rn(h),"canvas.mjs"))}catch{}for(let h of c)try{let d=await nt(h,"utf-8");o.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),o.end(d);return}catch{}console.error("[Bridge] Canvas bundle not found in:",c),v(o,404,{error:"Canvas bundle not found"})}async function yt(o,c){if(!o||o.includes("/")||o.includes("\\")||o.includes("..")){v(c,400,{error:"Invalid filename"});return}try{let h=await nt(ne(l,o)),d=o.split(".").pop()?.toLowerCase(),m=d==="png"?"image/png":d==="jpg"||d==="jpeg"?"image/jpeg":"application/octet-stream";c.writeHead(200,{"Content-Type":m,"Cache-Control":"public, max-age=3600"}),c.end(h)}catch{v(c,404,{error:"File not found"})}}function he(o){return`/files/${on(o)}`}async function vt(o,c){let h=await O.getThread(o);if(!h){v(c,404,{error:"Thread not found"});return}let d=h.messages.map(({screenshotPath:m,screenshotPaths:u,imagePaths:b,replyImagePaths:$,...X})=>({...X,...m?{screenshotUrl:he(m)}:{},...u?{screenshotUrls:Object.fromEntries(Object.entries(u).map(([K,q])=>[K,he(q)]))}:{},...b?{imageUrls:Object.fromEntries(Object.entries(b).map(([K,q])=>[K,q.map(he)]))}:{},...$?{replyImageUrls:$.map(he)}:{}}));v(c,200,{id:h.id,createdAt:h.createdAt,messages:d})}let _e=9,Ae=!1;for(let o=t;o<t+_e;o++)try{await mn(_,o),C=o,Ae=!0,console.log(`[\u22B9 is watching :${C}]`);break}catch(c){if(c.code==="EADDRINUSE"){let h=await xe(o);if(h&&h.projectId===e)return console.log(`[\u22B9 already watching :${o}]`),{port:o,projectId:e,close:async()=>{}};continue}throw c}if(!Ae)throw new Error(`[Bridge] All ports ${t}\u2013${t+_e-1} in use`);for(let[o,c]of Object.entries(I))!c.available||!c.path||H(o,c.path).then(h=>{if(h)console.log(`[Bridge] ${o} warmed up`);else{console.warn(`[Bridge] ${o} warm-up failed \u2014 marking unavailable`),c.available=!1,c.path=null;for(let d of J)Ce(d,{type:"capabilities_changed",data:{}})}});let wt=setInterval(()=>{st(l).catch(()=>{})},dn);return{port:C,projectId:e,close:async()=>{clearInterval(wt),await k.destroyAsync();for(let o of J)try{o.res.end()}catch{}return J.clear(),new Promise(o=>{_.close(()=>o())})}}}async function st(i){try{let t=await Zt(i),n=Date.now();for(let e of t){let s=ne(i,e);try{let l=await en(s);n-l.mtimeMs>un&&await tn(s)}catch{}}}catch{}}var Pn=1111;async function Ts(i){if(process.env.NODE_ENV==="production"&&!i?.force)throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");if(i?.detached)return xn(i);let t=await it(i);return process.env.POPMELT_BRIDGE_PORT=String(t.port),t}async function xn(i){let t=i.port??Pn,n=i.projectRoot??process.cwd(),e=yn("sha256").update(n).digest("hex").slice(0,12);for(let a=t;a<t+10;a++){let r=await xe(a);if(r&&r.projectId===e){if(r.version&&r.version!==Se){try{await fetch(`http://127.0.0.1:${a}/shutdown`,{method:"POST"})}catch{}await new Promise(f=>setTimeout(f,500));break}let p=i.devOrigin;if(p&&r.devOrigin!==p)try{await fetch(`http://127.0.0.1:${a}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:p})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(a),{port:a,projectId:e,close:async()=>{}}}}let s=wn(vn(Sn(import.meta.url)),"bridge-entry.mjs");gn(process.execPath,[s],{detached:!0,stdio:"ignore",env:{...process.env,POPMELT_PORT:String(t),POPMELT_PROJECT_ROOT:n,POPMELT_DEV_ORIGIN:i.devOrigin??""}}).unref();let l=Date.now()+3e3;for(;Date.now()<l;){await new Promise(a=>setTimeout(a,100));for(let a=t;a<t+10;a++){let r=await xe(a);if(r&&r.projectId===e)return process.env.POPMELT_BRIDGE_PORT=String(a),{port:a,projectId:e,close:async()=>{}}}}throw new Error(`[Bridge] Detached bridge failed to start within 3s (port ${t})`)}export{Ts as startPopmelt};
|