@popmelt.com/core 0.7.8 → 0.7.9
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/cli.mjs +1 -1
- package/dist/plugin-next.mjs +1 -1
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -415,4 +415,4 @@ ${u.summary}`}),y(c,200,{proposal:u})}async function Ln(r,c){let p=decodeURIComp
|
|
|
415
415
|
${u.title}`}),y(c,200,{proposal:u})}async function Wn(r,c,p){let u=decodeURIComponent(r),h=await g.findModelProposal(u);if(!h){y(p,404,{error:"Model proposal not found"});return}if(h.status!=="applied"){y(p,400,{error:"Only applied model proposals can be projected into evals"});return}let{provider:d,model:I}=await je(c),S=d??h.provider??O;if(S==="copilot"){y(p,400,{error:"Eval projection is not available for Copilot yet."});return}let j=await g.loadModel(),Q=await $.loadSuite(),U=Vt({proposal:h,currentModel:j,existingSuite:Q}),v=we().slice(0,8),E=h.threadId??(await m.createThread(v,[])).id;V.set(E,"synthesize_evals"),await m.appendMessage(E,{role:"human",timestamp:Date.now(),jobId:v,feedbackSummary:`Create eval drafts \u2014 ${h.title}`,feedbackContext:[`Model proposal: ${h.title}`,`Sources: ${h.decisionIds.length} decisions`,"Projection target: pending eval proposals"].join(`
|
|
416
416
|
`)});let C={id:v,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:"#111827",threadId:E,kind:"synthesize_evals",provider:S,model:I??h.model};C._replyPrompt=U,C._proposalId=h.id;let X=k.enqueue(C);y(p,200,{jobId:v,position:X,threadId:E})}async function je(r){try{let c=[];for await(let u of r)c.push(typeof u=="string"?Buffer.from(u):u);if(c.length===0)return{};let p=JSON.parse(Buffer.concat(c).toString());return{provider:ze(typeof p.provider=="string"?p.provider:void 0),model:typeof p.model=="string"&&p.model?p.model:void 0}}catch{return{}}}async function Hn(r,c){let p=await g.loadModel();if(!p){y(c,400,{error:"No model exists yet"});return}let u,h;try{let v=[];for await(let C of r)v.push(typeof C=="string"?Buffer.from(C):C);let E=JSON.parse(Buffer.concat(v).toString());u=E.provider,h=E.model}catch{}if(u==="copilot"){y(c,400,{error:"Rule synthesis is not available for Copilot yet."});return}let d=sn(p),I=we().slice(0,8),j=(await m.createThread(I,[])).id;V.set(j,"synthesize"),await m.appendMessage(j,{role:"human",timestamp:Date.now(),jobId:I,feedbackSummary:"Synthesize rules \u2014 review and propose improvements"});let Q={id:I,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),threadId:j,kind:"synthesize",provider:ze(u),model:h||void 0};Q._replyPrompt=d;let U=k.enqueue(Q);y(c,200,{jobId:I,position:U,threadId:j})}async function Gn(r,c){let{provider:p,model:u}=await je(r);if(p==="copilot"){y(c,400,{error:"Eval synthesis is not available for Copilot yet."});return}let h=await W.listDecisionIds(),d=await W.loadDecisions(h),I=await m.load(),S=await g.loadModel(),j=await $.loadSuite(),Q=Yt({decisions:d,threads:I,model:S,existingSuite:j}),U=we().slice(0,8),E=(await m.createThread(U,[])).id;V.set(E,"synthesize_evals"),await m.appendMessage(E,{role:"human",timestamp:Date.now(),jobId:U,feedbackSummary:"Synthesize evals \u2014 infer evals from design history"});let C={id:U,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:"#6b7280",threadId:E,kind:"synthesize_evals",provider:p,model:u||void 0};C._replyPrompt=Q;let X=k.enqueue(C);y(c,200,{jobId:U,position:X,threadId:E})}async function qn(r,c,p){let u=decodeURIComponent(r),h=await $.findCase(u);if(!h){y(p,404,{error:"Eval not found"});return}if(h.status!=="approved"){y(p,400,{error:"Only approved evals can be run"});return}let{screenshot:d,feedback:I,provider:S,model:j,sourceId:Q}=await Ze(c),U=ze(S)??O;if(U==="copilot"){y(p,400,{error:"Eval runs are not available for Copilot yet."});return}let v={};try{v=I?JSON.parse(I):{}}catch{y(p,400,{error:"Invalid eval run context JSON"});return}let E=we().slice(0,8),C=we().slice(0,8),X=me(a,`eval-run-${E}.webp`);await Je(X,d);let ce=await $.writeRunScreenshot(E,d),se=v.viewport,ae=se&&typeof se=="object"?se:{},le={type:"current_page",url:typeof v.url=="string"?v.url:"",viewport:{width:typeof ae.width=="number"?ae.width:0,height:typeof ae.height=="number"?ae.height:0}},N=await g.loadModel(),Z=U==="claude"?L.name:U==="codex"?q.name:null,B=U==="codex"?K.length>0:typeof Z=="string"&&/chrome|devtools/i.test(Z),H=Kt({evalCase:h,scope:le,model:N,screenshotPath:X,chromeDevtoolsAvailable:B}),_=(await m.createThread(C,[])).id;V.set(_,"run_eval");let re={timestamp:new Date().toISOString(),url:le.url,viewport:le.viewport,scrollPosition:{x:typeof v.scrollX=="number"?v.scrollX:0,y:typeof v.scrollY=="number"?v.scrollY:0},annotations:[],styleModifications:[]};await m.appendMessage(_,{role:"human",timestamp:Date.now(),jobId:C,screenshotPath:X,feedbackSummary:`Run eval \u2014 ${h.title}`,feedbackContext:[`Eval: ${h.title}`,"Scope: current page",`URL: ${le.url||"unknown"}`,"Assertions:",...h.assertions.map(as=>`- ${as}`)].join(`
|
|
417
417
|
`)});let de={id:C,status:"queued",screenshotPath:X,feedback:re,createdAt:Date.now(),color:"#111827",threadId:_,kind:"run_eval",evalId:u,evalRunId:E,provider:U,model:j||void 0,sourceId:Q||void 0};de._replyPrompt=H,de._evalRunScope=le,de._evalScreenshotPath=ce;let ct=k.enqueue(de);y(p,200,{jobId:C,runId:E,position:ct,threadId:_,screenshotPath:ce})}async function Qn(r,c,p){let u=decodeURIComponent(r),h={},d,I,S;try{let Q=[];for await(let v of c)Q.push(typeof v=="string"?Buffer.from(v):v);let U=JSON.parse(Buffer.concat(Q).toString());d=U.status,I=U.title,S=U.assertions}catch{y(p,400,{error:"Invalid JSON"});return}if(d!==void 0&&d!=="pending"&&d!=="approved"&&d!=="rejected"){y(p,400,{error:"Invalid status"});return}if(d&&(h.status=d),I!==void 0){if(typeof I!="string"||I.trim().length===0){y(p,400,{error:"Invalid title"});return}h.title=I.trim()}if(S!==void 0){if(!Array.isArray(S)){y(p,400,{error:"Invalid assertions"});return}let Q=S.filter(U=>typeof U=="string").map(U=>U.trim()).filter(Boolean);if(Q.length===0){y(p,400,{error:"Invalid assertions"});return}h.assertions=Q}if(!h.status&&!h.title&&!h.assertions){y(p,400,{error:"No eval changes provided"});return}let j=await $.updateCase(u,h);if(!j){y(p,404,{error:"Eval not found"});return}y(p,200,{eval:j})}async function Xn(r){let c=V.get(r);if(c)return c;let h=(await m.getThread(r))?.messages.find(d=>d.role==="human")?.feedbackSummary??"";if(h.startsWith("Synthesize evals"))return V.set(r,"synthesize_evals"),"synthesize_evals";if(h.startsWith("Synthesize rules"))return V.set(r,"synthesize"),"synthesize";if(h.startsWith("Run eval"))return V.set(r,"run_eval"),"run_eval";if(h.startsWith("Materialize model"))return V.set(r,"materialize_model"),"materialize_model"}async function Yn(r,c){let p=[];for await(let j of r)p.push(typeof j=="string"?Buffer.from(j):j);let u;if(p.length>0)try{u=JSON.parse(Buffer.concat(p).toString("utf-8")).serverUrl}catch{}let h=[];w.claude?.available&&w.claude.mcp&&!w.claude.mcp.found&&h.push(await mn(u)),w.codex?.available&&w.codex.mcp&&!w.codex.mcp.found&&h.push(await gn(u)),w.copilot?.available&&w.copilot.mcp&&!w.copilot.mcp.found&&h.push(await vn(u,w.copilot.path??M));let[d,I,S]=await Promise.all([yt(t),wt(t),St(t,w.copilot?.path??M)]);w.claude&&(w.claude.mcp=d),w.codex&&(w.codex.mcp=I),w.copilot&&(w.copilot.mcp=S),y(c,200,{results:h,capabilities:{providers:w}})}async function Kn(r,c){let p=[];for await(let d of r)p.push(typeof d=="string"?Buffer.from(d):d);let u;try{u=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(c,400,{error:"Invalid JSON"});return}if(!u.name||typeof u.name!="string"){y(c,400,{error:"Missing or invalid name"});return}let h=await g.addComponent(u.name);y(c,200,h)}async function Vn(r,c){let p=[];for await(let d of r)p.push(typeof d=="string"?Buffer.from(d):d);let u;try{u=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(c,400,{error:"Invalid JSON"});return}if(!u.name||typeof u.name!="string"){y(c,400,{error:"Missing or invalid name"});return}let h=await g.removeComponent(u.name);y(c,200,h)}async function Zn(r,c){let p=[];for await(let d of r)p.push(typeof d=="string"?Buffer.from(d):d);let u;try{u=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(c,400,{error:"Invalid JSON"});return}if(!u.path||typeof u.path!="string"||typeof u.value!="string"){y(c,400,{error:"Missing or invalid path/value"});return}let h=await g.updateToken(u.path,u.value);y(c,200,h)}async function es(r,c){let p=[];for await(let d of r)p.push(typeof d=="string"?Buffer.from(d):d);let u;try{u=JSON.parse(Buffer.concat(p).toString("utf-8"))}catch{y(c,400,{error:"Invalid JSON"});return}if(!u.path||typeof u.path!="string"){y(c,400,{error:"Missing or invalid path"});return}let h=await g.removeToken(u.path);y(c,200,h)}function ts(r,c){let p=i??"http://localhost:3000";if(!i){let h=r.headers.referer||r.headers.origin;if(h)try{let d=new URL(typeof h=="string"?h:h[0]||"");(d.hostname==="localhost"||d.hostname==="127.0.0.1")&&(p=d.origin)}catch{}}let u=Rt(z,p);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(u)}async function ns(r){let c=Date.now();if(ne&&c<ne.expires){y(r,200,ne.data);return}try{let{scanForComponents:p}=await import("./react-scanner-ZXYS5M3Y.mjs"),{generateRenderFiles:u}=await import("./render-generator-EANIDD2E.mjs"),h=await p(t);ne={data:h,expires:c+5e3},u(h,t,ke).then(d=>{ke=d}).catch(d=>console.warn("[Bridge] Render generation failed:",d)),y(r,200,h)}catch(p){console.error("[Bridge] Scanner error:",p),y(r,500,{error:"Failed to scan components"})}}async function ss(r){let c=[me(t,"node_modules","@popmelt.com","core","dist","canvas.mjs"),me(t,"packages","popmelt","dist","canvas.mjs")];try{let p=Ko(import.meta.url);c.unshift(me(Yo(p),"canvas.mjs"))}catch{}for(let p of c)try{let u=await $n(p,"utf-8");r.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),r.end(u);return}catch{}console.error("[Bridge] Canvas bundle not found in:",c),y(r,404,{error:"Canvas bundle not found"})}async function os(r,c){if(!r||r.includes("/")||r.includes("\\")||r.includes("..")){y(c,400,{error:"Invalid filename"});return}try{let p=await $n(me(a,r)),u=r.split(".").pop()?.toLowerCase(),h=u==="png"?"image/png":u==="webp"?"image/webp":u==="jpg"||u==="jpeg"?"image/jpeg":"application/octet-stream";c.writeHead(200,{"Content-Type":h,"Cache-Control":"public, max-age=3600"}),c.end(p)}catch{y(c,404,{error:"File not found"})}}function Be(r){return`/files/${rt(r)}`}async function rs(r,c){let p=await m.getThread(r);if(!p){y(c,404,{error:"Thread not found"});return}let u=(await $.loadRuns()).runs.filter(S=>S.threadId===r).sort((S,j)=>j.completedAt-S.completedAt)[0],h=u?await $.findCase(u.evalId):null,d=await g.findModelProposalByThread(r),I=p.messages.map(({screenshotPath:S,screenshotPaths:j,imagePaths:Q,replyImagePaths:U,...v})=>({...v,...v.role==="assistant"&&u?{evalRun:{...u,title:h?.title}}:{},...S?{screenshotUrl:Be(S)}:{},...j?{screenshotUrls:Object.fromEntries(Object.entries(j).map(([E,C])=>[E,Be(C)]))}:{},...Q?{imageUrls:Object.fromEntries(Object.entries(Q).map(([E,C])=>[E,C.map(Be)]))}:{},...U?{replyImageUrls:U.map(Be)}:{}}));y(c,200,{id:p.id,createdAt:p.createdAt,messages:I,modelProposal:d})}let Mt=9,Et=!1;for(let r=e;r<e+Mt;r++)try{await lr(lt,r),z=r,Et=!0,console.log(`[\u22B9 is watching :${z}]`);break}catch(c){if(c.code==="EADDRINUSE"){let p=await ar(r);if(p&&p.projectId===o)return console.log(`[\u22B9 already watching :${r}]`),{port:r,projectId:o,close:async()=>{}};continue}throw c}if(!Et)throw new Error(`[Bridge] All ports ${e}\u2013${e+Mt-1} in use`);for(let[r,c]of Object.entries(w))!c.available||!c.path||Y(r,c.path).then(p=>{if(p)console.log(`[Bridge] ${r} warmed up`);else{console.warn(`[Bridge] ${r} warm-up failed \u2014 marking unavailable`),c.available=!1,c.path=null;for(let u of P)it(u,{type:"capabilities_changed",data:{}})}});let is=setInterval(()=>{_n(a).catch(()=>{})},er);return{port:z,projectId:o,close:async()=>{clearInterval(is),await k.destroyAsync();for(let r of P)try{r.res.end()}catch{}return P.clear(),new Promise(r=>{lt.close(()=>r())})}}}async function _n(s){try{let e=await Wo(s),n=Date.now();for(let t of e){let o=me(s,t);try{let i=await Go(o);n-i.mtimeMs>tr&&await qo(o)}catch{}}}catch{}}var he="\x1B[35m[popmelt]\x1B[0m";async function hr(){let s=process.argv.slice(2);if(s[0]==="wrap"){let e=s.indexOf("--");(e===-1||e===s.length-1)&&(console.error(`${he} Usage: popmelt wrap -- <dev command>`),console.error(`${he} Example: popmelt wrap -- next dev`),console.error(`${he} Example: popmelt wrap -- astro dev`),process.exit(1));let n=s.slice(e+1);await gr(n);return}if(s[0]==="bridge"){await fr();return}if(s[0]==="stop"){await mr();return}console.log(`${he} Popmelt \u2014 design collaboration for AI coding agents`),console.log(""),console.log(" popmelt wrap -- <command> Start bridge + dev server together"),console.log(" popmelt bridge Start the bridge server standalone"),console.log(" popmelt stop Stop a detached bridge"),console.log(""),console.log("Examples:"),console.log(" popmelt wrap -- next dev"),console.log(" popmelt wrap -- astro dev"),console.log(" popmelt wrap -- vite"),console.log(""),console.log("In package.json:"),console.log(' "scripts": { "dev": "popmelt wrap -- next dev" }')}async function fr(){let s=await kt({projectRoot:process.cwd()});console.log(`${he} Bridge running on http://localhost:${s.port}`),await new Promise(e=>{let n=async()=>{console.log(`
|
|
418
|
-
${he} Shutting down bridge...`),await s.close(),e()};process.on("SIGINT",n),process.on("SIGTERM",n)})}async function mr(){let s=pr(process.cwd(),".popmelt","bridge.lock"),e;try{e=JSON.parse(await dr(s,"utf8"))}catch{console.log(`${he} No bridge running (no .popmelt/bridge.lock found)`);return}try{process.kill(e.pid,"SIGTERM"),console.log(`${he} Sent SIGTERM to bridge (pid ${e.pid}, port ${e.port})`)}catch(n){if(n.code==="ESRCH")console.log(`${he} Bridge process ${e.pid} already dead`);else throw n}try{await ur(s)}catch{}}async function gr(s){let e=await kt({projectRoot:process.cwd()});console.log(`${he} Bridge running on http://localhost:${e.port}`);let[n,...t]=s;console.log(`${he} Starting: ${s.join(" ")}`);let o=cr(n,t,{stdio:"inherit",shell:!0,env:{...process.env,POPMELT_BRIDGE_URL:`http://localhost:${e.port}`,POPMELT_PROJECT_ID:e.projectId}}),i=a=>{o.kill(a)};process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),o.on("exit",async(a,l)=>{await e.close(),l?process.kill(process.pid,l):process.exit(a??0)})}hr().catch(s=>{console.error(`${he} Fatal:`,s),process.exit(1)});
|
|
418
|
+
${he} Shutting down bridge...`),await s.close(),e()};process.on("SIGINT",n),process.on("SIGTERM",n)})}async function mr(){let s=pr(process.cwd(),".popmelt","bridge.lock"),e;try{e=JSON.parse(await dr(s,"utf8"))}catch{console.log(`${he} No bridge running (no .popmelt/bridge.lock found)`);return}try{process.kill(e.pid,"SIGTERM"),console.log(`${he} Sent SIGTERM to bridge (pid ${e.pid}, port ${e.port})`)}catch(n){if(n.code==="ESRCH")console.log(`${he} Bridge process ${e.pid} already dead`);else throw n}try{await ur(s)}catch{}}async function gr(s){let e=await kt({projectRoot:process.cwd()});console.log(`${he} Bridge running on http://localhost:${e.port}`);let[n,...t]=s;console.log(`${he} Starting: ${s.join(" ")}`);let o=cr(n,t,{stdio:"inherit",shell:!0,env:{...process.env,POPMELT_BRIDGE_URL:`http://localhost:${e.port}`,POPMELT_BRIDGE_PORT:String(e.port),POPMELT_PROJECT_ID:e.projectId}}),i=a=>{o.kill(a)};process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),o.on("exit",async(a,l)=>{await e.close(),l?process.kill(process.pid,l):process.exit(a??0)})}hr().catch(s=>{console.error(`${he} Fatal:`,s),process.exit(1)});
|
package/dist/plugin-next.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var H=Object.defineProperty,V=Object.defineProperties;var W=Object.getOwnPropertyDescriptors;var
|
|
1
|
+
var H=Object.defineProperty,V=Object.defineProperties;var W=Object.getOwnPropertyDescriptors;var A=Object.getOwnPropertySymbols;var J=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable;var D=(t,e,r)=>e in t?H(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,v=(t,e)=>{for(var r in e||(e={}))J.call(e,r)&&D(t,r,e[r]);if(A)for(var r of A(e))K.call(e,r)&&D(t,r,e[r]);return t},j=(t,e)=>V(t,W(e));import{NextResponse as N}from"next/server";function B(t){return z(t).slice(0,12)}var X=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function z(t){let e=typeof TextEncoder!="undefined"?Array.from(new TextEncoder().encode(t)):Q(t),r=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let b=7;b>=0;b--)e.push(r/Math.pow(2,b*8)&255);let n=1779033703,s=3144134277,u=1013904242,l=2773480762,i=1359893119,a=2600822924,x=528734635,f=1541459225,o=new Array(64);for(let b=0;b<e.length;b+=64){for(let c=0;c<16;c++){let h=b+c*4;o[c]=(e[h]<<24|e[h+1]<<16|e[h+2]<<8|e[h+3])>>>0}for(let c=16;c<64;c++){let h=d(o[c-15],7)^d(o[c-15],18)^o[c-15]>>>3,_=d(o[c-2],17)^d(o[c-2],19)^o[c-2]>>>10;o[c]=o[c-16]+h+o[c-7]+_>>>0}let p=n,P=s,w=u,E=l,m=i,R=a,y=x,I=f;for(let c=0;c<64;c++){let h=d(m,6)^d(m,11)^d(m,25),_=m&R^~m&y,U=I+h+_+X[c]+o[c]>>>0,G=d(p,2)^d(p,13)^d(p,22),F=p&P^p&w^P&w,k=G+F>>>0;I=y,y=R,R=m,m=E+U>>>0,E=w,w=P,P=p,p=U+k>>>0}n=n+p>>>0,s=s+P>>>0,u=u+w>>>0,l=l+E>>>0,i=i+m>>>0,a=a+R>>>0,x=x+y>>>0,f=f+I>>>0}return[n,s,u,l,i,a,x,f].map(b=>b.toString(16).padStart(8,"0")).join("")}function d(t,e){return t>>>e|t<<32-e}function Q(t){let e=[];for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);n<128?e.push(n):n<2048?e.push(192|n>>6,128|n&63):e.push(224|n>>12,128|n>>6&63,128|n&63)}return e}function L(){if(process.env.POPMELT_BRIDGE_URL)try{let t=new URL(process.env.POPMELT_BRIDGE_URL).port;if(t)return parseInt(t,10)}catch(t){}return parseInt(process.env.POPMELT_BRIDGE_PORT||"1111",10)}var Y=1111,Z=10,O=1e3,g=null;function T(){try{return typeof process!="undefined"&&typeof process.cwd=="function"?process.cwd():null}catch(t){return null}}function M(t=(e=>(e=T())!=null?e:void 0)()){return process.env.POPMELT_PROJECT_ID||(t?B(t):null)}async function $(t,e){let r=new AbortController,n=setTimeout(()=>r.abort(),350);try{let s=new URL("/status",`http://localhost:${t}`);e&&s.searchParams.set("projectId",e);let u=await fetch(s,{signal:r.signal,cache:"no-store"});if(!u.ok)return null;let l=await u.json();return e&&l.projectId!==e?null:l}catch(s){return null}finally{clearTimeout(n)}}async function S(t,e){let r=Date.now();if(g&&g.preferredPort===t&&g.projectId===e&&g.expiresAt>r)return g.port;if(await $(t,e))return g={preferredPort:t,projectId:e,port:t,expiresAt:r+O},t;if(!e)return t;let s=Array.from({length:Z},(a,x)=>Y+x).filter(a=>a!==t),l=(await Promise.all(s.map(async a=>await $(a,e)?a:null))).find(a=>a!==null),i=l!=null?l:t;return g={preferredPort:t,projectId:e,port:i,expiresAt:r+O},i}async function C(t,e,r){let n=await S(e,r),s=new URL(t,`http://localhost:${n}`);return r&&s.searchParams.set("projectId",r),N.rewrite(s)}function ne(t,e){var u,l,i,a,x;let r=(u=e==null?void 0:e.basePath)!=null?u:"/popmelt",n=(l=e==null?void 0:e.port)!=null?l:L(),s=(x=e==null?void 0:e.projectId)!=null?x:M((a=(i=e==null?void 0:e.projectRoot)!=null?i:T())!=null?a:void 0);if(t.nextUrl.searchParams.get("popmelt")==="canvas"){if(process.env.NODE_ENV==="production")return null;let f=new Headers(t.headers);return f.set("x-popmelt-canvas","1"),N.next({request:{headers:f}})}if(t.nextUrl.pathname.startsWith(r+"/render")){if(process.env.NODE_ENV==="production")return null;let f=new Headers(t.headers);return f.set("x-popmelt-canvas","1"),N.next({request:{headers:f}})}if(t.nextUrl.pathname===r||t.nextUrl.pathname.startsWith(r+"/")){if(t.nextUrl.pathname===`${r}/status`)return C("/status",n,s);let f="/canvas"+t.nextUrl.pathname.slice(r.length);return C(f||"/canvas",n,s)}return null}function ce(t,e){var u,l,i,a;if(process.env.NODE_ENV==="production")return t;let r=(u=e==null?void 0:e.port)!=null?u:L(),n=(a=e==null?void 0:e.projectId)!=null?a:M((i=(l=e==null?void 0:e.projectRoot)!=null?l:T())!=null?i:void 0),s=t.rewrites;return j(v({},t),{async rewrites(){let x=s?await s():[],o=`http://localhost:${await S(r,n)}`,b=[{source:"/popmelt/status",destination:n?`${o}/status?projectId=${encodeURIComponent(n)}`:`${o}/status`},{source:"/popmelt",destination:n?`${o}/canvas?projectId=${encodeURIComponent(n)}`:`${o}/canvas`},{source:"/popmelt/:path*",destination:n?`${o}/canvas/:path*?projectId=${encodeURIComponent(n)}`:`${o}/canvas/:path*`}];return Array.isArray(x)?{beforeFiles:b,afterFiles:x,fallback:[]}:j(v({},x),{beforeFiles:[...x.beforeFiles||[],...b]})}})}export{M as getPopmeltProjectId,ne as popmeltMiddleware,ce as withPopmelt};
|
package/package.json
CHANGED