@vcp-dev/site-edit-bridge 0.10.58 → 0.10.60

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.
@@ -2,6 +2,6 @@ import Ce from"node:http";import{existsSync as U,readFileSync as F}from"node:fs"
2
2
  Connection: close\r
3
3
  \r
4
4
  `),r.destroy();return}h.authenticatedByHeader&&n.add(o),t.handleUpgrade(o,r,a,c=>{t.emit("connection",c,o)})};return e.server.on("upgrade",s),t.on("connection",(o,r)=>{if(n.has(r)){i(o);return}jt(o,e.sessionKey,()=>{i(o)})}),t.stop=()=>{e.server.off("upgrade",s);for(let o of t.clients)o.close(1001,"bridge stopped");t.close()},t}var ge=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===Me.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>kt){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function Dt(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function Bt(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let i=pe(e.headers["x-vcp-site-edit-key"]),s=Ue(i,t.sessionKey),o=pe(e.headers.host),r=pe(e.headers.origin);return o&&!Ft(o,t.host,r)?null:r?Vt(r,o,t.allowedOrigins)?{authenticatedByHeader:s}:null:s?{authenticatedByHeader:!0}:null}function jt(e,t,n){let i=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},Tt),s,o=()=>{clearTimeout(i),e.off("message",s),e.off("close",o)},r=()=>{o(),e.close(1008,"bridge authentication failed")};s=a=>{try{let h=b.parseMessage(a.toString());if(h.type!=="auth"||!Ue(h.payload.key,t)){r();return}o(),e.readyState===Me.OPEN&&e.send(b.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{r()}},e.on("message",s),e.on("close",o)}function Ue(e,t){if(!e)return!1;let n=Buffer.from(e),i=Buffer.from(t);return n.length===i.length&&gt(n,i)}function Ft(e,t,n){let i=Oe(e),s=Oe(t);return i===s||He(s)&&He(i)&&(!n||me(n,e))||Ut(s)&&(!n||me(n,e))}function Ut(e){return e==="0.0.0.0"||e==="::"}function He(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Vt(e,t,n){return n.includes(e)||(t?me(e,t):!1)}function me(e,t){try{return new URL(e).host===Ve(t)}catch{return!1}}function Oe(e){let t=Ve(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function Ve(e){return e.trim().toLowerCase()}function pe(e){return Array.isArray(e)?e[0]:e}function Kt(){return ft(32).toString("base64url")}function Ke(e){let t=e.replaceAll("\\","/");return t===he||t.endsWith(`/${he}`)}function Wt(e){let t=e.replaceAll("\\","/");return Ke(e)||t===".vcp/workspace-state.json"||t.startsWith(".vcp/snapshot-store/")}var zt="SITE_EDIT_ENGINE_UNAVAILABLE",Jt=5e3,Gt=1024,Qt="VCP_SITE_EDIT_ENGINE_MAX_HEAP_MB",Xt=3,Yt=10*6e4,Zt=1012;function Ie(e,t,n={}){let i=je(t),{onSnapshotIdChanged:s,onHealthChanged:o,...r}=i,a={options:r},h=n.maxHeapMb??tn(process.env[Qt])??Gt,c=n.maxRestarts??Xt,l=n.restartWindowMs??Yt,u="starting",S,d=0,f=[],y=null,x=0,w=new Map,E=new Set,V,D,K=new Promise((p,g)=>{V=p,D=g});K.catch(()=>{});let C=p=>{let g=new Error(`VCP site edit preview bridge runtime is not ready: ${p}`);return g.code=zt,g},W=p=>{for(let g of w.values())g.reject(p);w.clear()},k=p=>{switch(p.type){case"ready":y=p.health,u==="starting"?(u="ready",V()):u==="restarting"&&(u="ready",console.warn("[vcp-site-edit] engine worker restarted"));return;case"start-failed":u==="starting"&&T(ne(p.error));return;case"result":{let g=w.get(p.id);if(!g)return;w.delete(p.id),p.ok?g.resolve(p.value):g.reject(ne(p.error));return}case"event":for(let g of E)try{g(p.event)}catch(I){console.warn(`[vcp-site-edit] engine event listener failed: ${I instanceof Error?I.message:String(I)}`)}return;case"health":y=p.health;return;case"snapshot-id-changed":a.options.snapshotId=p.next;try{s?.(p.next,p.previous)}catch(g){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${g instanceof Error?g.message:String(g)}`)}return}},B=()=>{let p=d+=1,g=n.workerUrl??new URL("./engine-worker.js",import.meta.url),I=new qt(en(g),{workerData:a,resourceLimits:{maxOldGenerationSizeMb:h},...n.execArgv?{execArgv:n.execArgv}:{}});I.unref();let A=()=>p===d;I.on("message",v=>{A()&&k(v)}),I.on("error",v=>{A()&&T(v instanceof Error?v:new Error(String(v)))}),I.on("exit",v=>{A()&&T(new Error(`engine worker exited with code ${v}`))}),S=I,n.onWorker?.(I)},T=p=>{if(u==="stopped"||u==="failed")return;if(W(C(p.message)),y=null,u==="starting"){u="failed",console.error(`[vcp-site-edit] engine worker failed to start: ${p.message}`),D(p);return}let g=Date.now();for(;f.length>0&&g-f[0]>l;)f.shift();if(f.length>=c){u="failed",console.error(`[vcp-site-edit] engine worker stopped unexpectedly and exhausted ${c} restarts: ${p.message}`);return}f.push(g),u="restarting";for(let I of P.clients)I.close(Zt,"site edit engine restarting");console.error(`[vcp-site-edit] engine worker stopped unexpectedly, restarting (${f.length}/${c}): ${p.message}`),B()},$=(p,g)=>{if(u==="failed"||u==="stopped"||u==="restarting")return Promise.reject(C(u));let I=x+=1;return new Promise((A,v)=>{w.set(I,{resolve:A,reject:v});let et={type:"call",id:I,method:p,args:g};S.postMessage(et)})},j=Object.fromEntries(Re.map(p=>[p,(...g)=>$(p,g)])),P=Se({server:e,path:i.path,sessionKey:i.sessionKey,host:i.host,allowedOrigins:i.allowedOrigins,engine:{...j,subscribe(p){return E.add(p),()=>E.delete(p)}}});return B(),{getHealth(){return u==="ready"&&y?y:{ok:!1,bridgePath:i.path,runtimeReady:!1,routesIndexed:y?.routesIndexed??0,sessionRequired:!!i.sessionKey}},stop(){if(u==="stopped")return;let p=u==="starting";u="stopped",P.stop(),p&&D(C("bridge stopped")),W(C("bridge stopped")),E.clear();let g=S,I={type:"stop"};g.postMessage(I);let A=setTimeout(()=>{g.terminate()},Jt);A.unref(),g.once("exit",()=>clearTimeout(A))},whenReady(){return K},eventListeners:E}}function en(e){if(!e.pathname.endsWith(".ts"))return e;let t=Lt($t(import.meta.url).resolve("tsx/esm/api")).href,n=[`import { tsImport } from ${JSON.stringify(t)};`,`await tsImport(${JSON.stringify(e.href)}, ${JSON.stringify(e.href)});`].join(`
5
- `);return new URL(`data:text/javascript,${encodeURIComponent(n)}`)}function tn(e){if(!e||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}var sn="next",on="VCP_SITE_EDIT_ENGINE_IN_PROCESS",Ge="127.0.0.1",rn=3e3,ee="/__vcp/site-edit/bridge",Qe="/__vcp/site-edit/health",an="probe",cn="render",$e="/_error",te="/__vcp/site-edit/client/",un=`${te}auto-bootstrap.js`,Xe='data-vcp-site-edit-bootstrap="true"',dn=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],pn="@vcp-dev/site-edit-engine/webpack-loader",hn=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,ln=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],fn=new Set(["auto-bootstrap.js","client.js","composition-key.js","designer-trace.js","document-codec.js","property-preview.js","protocol.js","window-message.js"]);async function Hi(e={},t={}){let n=t.process??process,i=t.createServer??Ce.createServer,s=t.attachBridgeServer??(n.env[on]==="1"?Be:Ie),o=t.loadNext??Ln,r=z.resolve(e.projectRoot??process.cwd()),a=e.host??Ge,h=e.port??Gn(n.env.PORT)??rn,c=e.bridgePath??ee,l=En(c),u=Un(),S=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",d=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,f=await o(r),y=gn(r),x=f({dev:!0,dir:r,hostname:a,port:h,...mn(y)}),w=x.getRequestHandler(),E=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",V=e.snapshotId??n.env.VCP_SNAPSHOT_ID??Jn(r),D=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,K=D?.trim()?z.resolve(D):void 0,C=null,W={launchId:nn(),pid:process.pid,snapshotId:V},k=i((P,p)=>{kn({basePath:S,bridgePath:c,bridgeHealthPath:l,bridgeSessionKey:u,getBridgeHealth:()=>C?.getHealth()??On(c),launch:W,runRenderProbe:()=>An(x),handle:w,request:P,response:p}).catch(g=>{console.error(g),p.headersSent||(p.statusCode=500),p.end("site edit preview request failed")})}),B=null,T=null,$=()=>T||(Z(()=>n.off("SIGINT",j)),Z(()=>n.off("SIGTERM",j)),Z(()=>B?.()),B=null,Z(()=>C?.stop()),C=null,T=Promise.allSettled([Xn(k),Yn(()=>x.close())]).then(()=>{}),T),j=()=>{$()};try{return await x.prepare(),C=s(k,{...d?{tenantId:d}:{},siteId:E,snapshotId:V,projectRoot:r,basePath:S,host:a,port:h,path:c,sessionKey:u,...K?{historyRoot:K}:{},onSnapshotIdChanged:P=>{W.snapshotId=P}}),B=In({server:k,bridgePath:c,handleUpgrade:x.getUpgradeHandler()}),n.on("SIGINT",j),n.on("SIGTERM",j),await C.whenReady?.(),await Qn(k,h,a),{bundler:y,close:$,host:a,port:Zn(k,h),server:k}}catch(P){throw await $(),P}}function gn(e){let t=yn(e);return t&&Sn(t)?"webpack":"turbopack"}function mn(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function yn(e){for(let t of dn){let n=G(e,t);if(U(n))return F(n,"utf8")}return null}function Sn(e){return e.includes(pn)?!0:hn.test(e)&&ln.some(t=>t.test(e))}function In(e){let t=(n,i,s)=>{wn(n.url,e.bridgePath)||e.handleUpgrade(n,i,s).catch(o=>{console.error(o),i.destroyed||i.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function wn(e,t){return new URL(e??"/","http://localhost").pathname===t}function En(e=ee){if(e===ee)return Qe;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function xn(e){let t=JSON.stringify({basePath:e.basePath,launch_id:e.launch?.launchId,snapshot_id:e.launch?.snapshotId,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??Cn()});return`<script type="module" ${Xe}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(un)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Cn(){return{bridge:we("@vcp-dev/site-edit-bridge"),contracts:we("@vcp-dev/contracts"),engine:we("@vcp-dev/site-edit-engine")}}function we(e){let t=qe(import.meta.url);try{let n=t.resolve(e),i=bn(n,e);if(!i)return;let s=JSON.parse(F(i,"utf8"));return typeof s.version=="string"?s.version:void 0}catch{return}}function bn(e,t){let n=z.parse(e).root,i=J(e);for(;i&&i!==n;){let s=G(i,"package.json");if(U(s))try{if(JSON.parse(F(s,"utf8")).name===t)return s}catch{return}i=J(i)}}function Rn(e,t){if(e.includes(Xe))return e;let n=xn(t),i=/<\/body\s*>/i.exec(e);return i?`${e.slice(0,i.index)}${n}${e.slice(i.index)}`:`${e}${n}`}function Oi(e,t=J(Je(import.meta.url)),n=U){return Ye(e,t,n)?.path??null}function Ye(e,t=J(Je(import.meta.url)),n=U){let i=new URL(e??"/","http://localhost").pathname;if(!i.startsWith(te))return null;let s=i.slice(te.length);if(!fn.has(s))return null;let o=be(qn(t),s);if(ze(t)!=="src")return{path:o,requiresTranspile:!1};let r=be(t,s.replace(/\.js$/,".ts"));return n(r)?{path:r,requiresTranspile:!0}:{path:o,requiresTranspile:!1}}async function vn(e,t){let n=Ye(e.url);if(!n)return!1;if(!U(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let i=n.requiresTranspile?await _n(F(n.path,"utf8")):F(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(i),!0}async function _n(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function kn({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:i,getBridgeHealth:s,launch:o,runRenderProbe:r,handle:a,request:h,response:c}){if(Tn(h.url,e)){c.statusCode=404,c.end();return}if(await Hn(h,c,n,s,o,r)||await vn(h,c))return;let l=Mn(h),u=Dn(h),S=l||u?Fn(c,{basePath:e,bridgePath:t,bridgeSessionKey:i,patchNextDevChunk:u,launch:{...o}}):()=>{};try{await a(h,c)}catch(d){throw S(),d}}function Tn(e,t){let n=(e??"/").split(/[?#]/,1)[0]??"/";if(!/(\\|\/\/)/.test(n))return!1;let i;try{i=decodeURIComponent(n).replace(/\\/g,"/").replace(/\/{2,}/g,"/")}catch{return!1}let s=new URL(i,"http://namespace.invalid").pathname,o=t.replace(/\/+$/,"");return(o&&(s===o||s.startsWith(o+"/"))?s.slice(o.length)||"/":s).startsWith("/.vcp")}function Pn(e){let t=e instanceof Error?e.message:String(e),n=e&&typeof e=="object"&&"code"in e?e.code:void 0;return/\.next[/\\]/.test(t)||/chunks[/\\]ssr[/\\]/.test(t)?n==="ENOENT"||n==="MODULE_NOT_FOUND"?{verdict:"artifact_broken",detail:t}:t.includes("Cannot find module")?{verdict:"artifact_broken",detail:t}:{verdict:"inconclusive",detail:t}:{verdict:"inconclusive",detail:t}}async function An(e){let t=new Ce.IncomingMessage(new We);t.method="GET",t.url=$e,t.headers={host:Ge};let n=new Ce.ServerResponse(t);n.assignSocket(new We);try{return await e.renderToHTML(t,n,$e,{}),{verdict:"ok"}}catch(i){return Pn(i)}finally{try{let i=n.socket;i&&(n.detachSocket(i),i.destroy())}catch{}}}function Nn(e){return new URL(e??"/","http://localhost").searchParams.get(an)===cn}async function Hn(e,t,n,i,s,o){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let a=i(),h=Nn(e.url)?await o():void 0,c={...a,launch:s,...h?{render:h}:{}};return t.writeHead(a.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(c)),!0}function On(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Mn(e){return Bn(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Dn(e){return jn(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Bn(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost");if(e.headers["x-template-id"]!==void 0&&!t.searchParams.has("template_id"))return!1;let n=t.pathname;if(n.startsWith("/_next/")||n.startsWith(te)||n===ee||n===Qe)return!1;let i=e.headers.accept??"";return i===""||i.includes("text/html")}function jn(e){if(e.method!=="GET"||!String(e.headers["user-agent"]??"").includes("Firefox"))return!1;let n=new URL(e.url??"/","http://localhost").pathname;return n.startsWith("/_next/static/chunks/")&&n.endsWith(".js")}function Fn(e,t){let n=[],i=e,s=i.flushHeaders.bind(e),o=i.write.bind(e),r=i.end.bind(e),a=!1;i.flushHeaders=()=>{};let h=()=>{if(t.patchNextDevChunk||a)return!1;let c=Buffer.concat(n);if(!/<body\b[^>]*>/iu.test(c.toString("utf8")))return!1;let l=Le(e,c,t);return l!==c&&!e.headersSent&&e.removeHeader("content-length"),o(l),n.length=0,a=!0,!0};return i.write=(c,l,u)=>a?(c!==void 0&&o(Ee(c,xe(l))),Y(l),Y(u),!0):(c!==void 0&&(n.push(Ee(c,xe(l))),h()),Y(l),Y(u),!0),i.end=(c,l,u)=>{let S=typeof c=="function"?void 0:c;if(a)return i.write=o,i.end=r,i.flushHeaders=s,S===void 0?typeof c=="function"?r(c):typeof l=="function"?r(l):typeof u=="function"?r(u):r():typeof l=="function"?r(S,l):typeof u=="function"?r(S,l,u):r(S,l);S!==void 0&&n.push(Ee(S,xe(l))),i.write=o,i.end=r,i.flushHeaders=s;let d=Buffer.concat(n),f=Le(e,d,t);f!==d&&!e.headersSent&&e.removeHeader("content-length");let y=typeof c=="function"?c:typeof l=="function"?l:typeof u=="function"?u:void 0;return y?r(f,y):r(f)},()=>{i.write=o,i.end=r,i.flushHeaders=s}}function Le(e,t,n){if(Vn(e,t))return Buffer.from(Rn(t.toString("utf8"),n));if(n.patchNextDevChunk&&Kn(e)){let i=t.toString("utf8"),s=Wn(i);if(s!==i)return Buffer.from(s)}return t}function Un(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function Vn(e,t){if(e.statusCode<200||e.statusCode>=300)return!1;let n=e.getHeader("content-type"),i=Array.isArray(n)?n.join(";"):String(n??"");return t.toString("utf8",0,256).includes("<html")&&(i===""||i.includes("text/html"))}function Kn(e){if(e.statusCode<200||e.statusCode>=300)return!1;let t=e.getHeader("content-type"),n=Array.isArray(t)?t.join(";"):String(t??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function Wn(e){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
5
+ `);return new URL(`data:text/javascript,${encodeURIComponent(n)}`)}function tn(e){if(!e||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}var sn="next",on="VCP_SITE_EDIT_ENGINE_IN_PROCESS",Ge="127.0.0.1",rn=3e3,ee="/__vcp/site-edit/bridge",Qe="/__vcp/site-edit/health",an="probe",cn="render",$e="/_error",te="/__vcp/site-edit/client/",un=`${te}auto-bootstrap.js`,Xe='data-vcp-site-edit-bootstrap="true"',dn=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],pn="@vcp-dev/site-edit-engine/webpack-loader",hn=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,ln=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],fn=new Set(["auto-bootstrap.js","client.js","composition-key.js","designer-trace.js","document-codec.js","frame-scroll-session.js","frame-text-commit-preview.js","property-preview.js","protocol.js","window-message.js"]);async function Hi(e={},t={}){let n=t.process??process,i=t.createServer??Ce.createServer,s=t.attachBridgeServer??(n.env[on]==="1"?Be:Ie),o=t.loadNext??Ln,r=z.resolve(e.projectRoot??process.cwd()),a=e.host??Ge,h=e.port??Gn(n.env.PORT)??rn,c=e.bridgePath??ee,l=En(c),u=Un(),S=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",d=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,f=await o(r),y=gn(r),x=f({dev:!0,dir:r,hostname:a,port:h,...mn(y)}),w=x.getRequestHandler(),E=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",V=e.snapshotId??n.env.VCP_SNAPSHOT_ID??Jn(r),D=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,K=D?.trim()?z.resolve(D):void 0,C=null,W={launchId:nn(),pid:process.pid,snapshotId:V},k=i((P,p)=>{kn({basePath:S,bridgePath:c,bridgeHealthPath:l,bridgeSessionKey:u,getBridgeHealth:()=>C?.getHealth()??On(c),launch:W,runRenderProbe:()=>An(x),handle:w,request:P,response:p}).catch(g=>{console.error(g),p.headersSent||(p.statusCode=500),p.end("site edit preview request failed")})}),B=null,T=null,$=()=>T||(Z(()=>n.off("SIGINT",j)),Z(()=>n.off("SIGTERM",j)),Z(()=>B?.()),B=null,Z(()=>C?.stop()),C=null,T=Promise.allSettled([Xn(k),Yn(()=>x.close())]).then(()=>{}),T),j=()=>{$()};try{return await x.prepare(),C=s(k,{...d?{tenantId:d}:{},siteId:E,snapshotId:V,projectRoot:r,basePath:S,host:a,port:h,path:c,sessionKey:u,...K?{historyRoot:K}:{},onSnapshotIdChanged:P=>{W.snapshotId=P}}),B=In({server:k,bridgePath:c,handleUpgrade:x.getUpgradeHandler()}),n.on("SIGINT",j),n.on("SIGTERM",j),await C.whenReady?.(),await Qn(k,h,a),{bundler:y,close:$,host:a,port:Zn(k,h),server:k}}catch(P){throw await $(),P}}function gn(e){let t=yn(e);return t&&Sn(t)?"webpack":"turbopack"}function mn(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function yn(e){for(let t of dn){let n=G(e,t);if(U(n))return F(n,"utf8")}return null}function Sn(e){return e.includes(pn)?!0:hn.test(e)&&ln.some(t=>t.test(e))}function In(e){let t=(n,i,s)=>{wn(n.url,e.bridgePath)||e.handleUpgrade(n,i,s).catch(o=>{console.error(o),i.destroyed||i.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function wn(e,t){return new URL(e??"/","http://localhost").pathname===t}function En(e=ee){if(e===ee)return Qe;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function xn(e){let t=JSON.stringify({basePath:e.basePath,launch_id:e.launch?.launchId,snapshot_id:e.launch?.snapshotId,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??Cn()});return`<script type="module" ${Xe}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(un)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Cn(){return{bridge:we("@vcp-dev/site-edit-bridge"),contracts:we("@vcp-dev/contracts"),engine:we("@vcp-dev/site-edit-engine")}}function we(e){let t=qe(import.meta.url);try{let n=t.resolve(e),i=bn(n,e);if(!i)return;let s=JSON.parse(F(i,"utf8"));return typeof s.version=="string"?s.version:void 0}catch{return}}function bn(e,t){let n=z.parse(e).root,i=J(e);for(;i&&i!==n;){let s=G(i,"package.json");if(U(s))try{if(JSON.parse(F(s,"utf8")).name===t)return s}catch{return}i=J(i)}}function Rn(e,t){if(e.includes(Xe))return e;let n=xn(t),i=/<\/body\s*>/i.exec(e);return i?`${e.slice(0,i.index)}${n}${e.slice(i.index)}`:`${e}${n}`}function Oi(e,t=J(Je(import.meta.url)),n=U){return Ye(e,t,n)?.path??null}function Ye(e,t=J(Je(import.meta.url)),n=U){let i=new URL(e??"/","http://localhost").pathname;if(!i.startsWith(te))return null;let s=i.slice(te.length);if(!fn.has(s))return null;let o=be(qn(t),s);if(ze(t)!=="src")return{path:o,requiresTranspile:!1};let r=be(t,s.replace(/\.js$/,".ts"));return n(r)?{path:r,requiresTranspile:!0}:{path:o,requiresTranspile:!1}}async function vn(e,t){let n=Ye(e.url);if(!n)return!1;if(!U(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let i=n.requiresTranspile?await _n(F(n.path,"utf8")):F(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(i),!0}async function _n(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function kn({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:i,getBridgeHealth:s,launch:o,runRenderProbe:r,handle:a,request:h,response:c}){if(Tn(h.url,e)){c.statusCode=404,c.end();return}if(await Hn(h,c,n,s,o,r)||await vn(h,c))return;let l=Mn(h),u=Dn(h),S=l||u?Fn(c,{basePath:e,bridgePath:t,bridgeSessionKey:i,patchNextDevChunk:u,launch:{...o}}):()=>{};try{await a(h,c)}catch(d){throw S(),d}}function Tn(e,t){let n=(e??"/").split(/[?#]/,1)[0]??"/";if(!/(\\|\/\/)/.test(n))return!1;let i;try{i=decodeURIComponent(n).replace(/\\/g,"/").replace(/\/{2,}/g,"/")}catch{return!1}let s=new URL(i,"http://namespace.invalid").pathname,o=t.replace(/\/+$/,"");return(o&&(s===o||s.startsWith(o+"/"))?s.slice(o.length)||"/":s).startsWith("/.vcp")}function Pn(e){let t=e instanceof Error?e.message:String(e),n=e&&typeof e=="object"&&"code"in e?e.code:void 0;return/\.next[/\\]/.test(t)||/chunks[/\\]ssr[/\\]/.test(t)?n==="ENOENT"||n==="MODULE_NOT_FOUND"?{verdict:"artifact_broken",detail:t}:t.includes("Cannot find module")?{verdict:"artifact_broken",detail:t}:{verdict:"inconclusive",detail:t}:{verdict:"inconclusive",detail:t}}async function An(e){let t=new Ce.IncomingMessage(new We);t.method="GET",t.url=$e,t.headers={host:Ge};let n=new Ce.ServerResponse(t);n.assignSocket(new We);try{return await e.renderToHTML(t,n,$e,{}),{verdict:"ok"}}catch(i){return Pn(i)}finally{try{let i=n.socket;i&&(n.detachSocket(i),i.destroy())}catch{}}}function Nn(e){return new URL(e??"/","http://localhost").searchParams.get(an)===cn}async function Hn(e,t,n,i,s,o){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let a=i(),h=Nn(e.url)?await o():void 0,c={...a,launch:s,...h?{render:h}:{}};return t.writeHead(a.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(c)),!0}function On(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Mn(e){return Bn(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Dn(e){return jn(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Bn(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost");if(e.headers["x-template-id"]!==void 0&&!t.searchParams.has("template_id"))return!1;let n=t.pathname;if(n.startsWith("/_next/")||n.startsWith(te)||n===ee||n===Qe)return!1;let i=e.headers.accept??"";return i===""||i.includes("text/html")}function jn(e){if(e.method!=="GET"||!String(e.headers["user-agent"]??"").includes("Firefox"))return!1;let n=new URL(e.url??"/","http://localhost").pathname;return n.startsWith("/_next/static/chunks/")&&n.endsWith(".js")}function Fn(e,t){let n=[],i=e,s=i.flushHeaders.bind(e),o=i.write.bind(e),r=i.end.bind(e),a=!1;i.flushHeaders=()=>{};let h=()=>{if(t.patchNextDevChunk||a)return!1;let c=Buffer.concat(n);if(!/<body\b[^>]*>/iu.test(c.toString("utf8")))return!1;let l=Le(e,c,t);return l!==c&&!e.headersSent&&e.removeHeader("content-length"),o(l),n.length=0,a=!0,!0};return i.write=(c,l,u)=>a?(c!==void 0&&o(Ee(c,xe(l))),Y(l),Y(u),!0):(c!==void 0&&(n.push(Ee(c,xe(l))),h()),Y(l),Y(u),!0),i.end=(c,l,u)=>{let S=typeof c=="function"?void 0:c;if(a)return i.write=o,i.end=r,i.flushHeaders=s,S===void 0?typeof c=="function"?r(c):typeof l=="function"?r(l):typeof u=="function"?r(u):r():typeof l=="function"?r(S,l):typeof u=="function"?r(S,l,u):r(S,l);S!==void 0&&n.push(Ee(S,xe(l))),i.write=o,i.end=r,i.flushHeaders=s;let d=Buffer.concat(n),f=Le(e,d,t);f!==d&&!e.headersSent&&e.removeHeader("content-length");let y=typeof c=="function"?c:typeof l=="function"?l:typeof u=="function"?u:void 0;return y?r(f,y):r(f)},()=>{i.write=o,i.end=r,i.flushHeaders=s}}function Le(e,t,n){if(Vn(e,t))return Buffer.from(Rn(t.toString("utf8"),n));if(n.patchNextDevChunk&&Kn(e)){let i=t.toString("utf8"),s=Wn(i);if(s!==i)return Buffer.from(s)}return t}function Un(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function Vn(e,t){if(e.statusCode<200||e.statusCode>=300)return!1;let n=e.getHeader("content-type"),i=Array.isArray(n)?n.join(";"):String(n??"");return t.toString("utf8",0,256).includes("<html")&&(i===""||i.includes("text/html"))}function Kn(e){if(e.statusCode<200||e.statusCode>=300)return!1;let t=e.getHeader("content-type"),n=Array.isArray(t)?t.join(";"):String(t??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function Wn(e){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
6
6
  `),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join(`
7
7
  `)],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join("\\n"),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join("\\n")],["debugChannel: createDebugChannel && createDebugChannel(requestHeaders)","debugChannel: undefined"],["debugChannel: createDebugChannel && createDebugChannel(headers)","debugChannel: undefined"]].reduce((n,[i,s])=>$n(n,i,s),e)}function $n(e,t,n){if(n.length>t.length)throw new Error("Replacement must not be longer than the search string.");return e.replaceAll(t,n.padEnd(t.length," "))}function Ee(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function xe(e){return typeof e=="string"?e:void 0}function Y(e){typeof e=="function"&&e()}async function Ln(e){let n=qe(G(e,"package.json"))(sn);return n.default??n}function qn(e){return ze(e)!=="src"?e:be(zn(e),"dist")}function zn(e){return Ze(e)?z.posix.dirname(e):J(e)}function be(e,t){return Ze(e)?z.posix.join(e,t):G(e,t)}function Ze(e){return e.includes("/")&&!e.includes("\\")}function Jn(e){let t=G(e,".vcp/current-snapshot.json");if(!U(t))return"sandbox_worktree";try{let n=JSON.parse(F(t,"utf8"));return typeof n.snapshot_id=="string"&&n.snapshot_id?n.snapshot_id:typeof n.snapshotId=="string"&&n.snapshotId?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function Gn(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function Qn(e,t,n){return new Promise((i,s)=>{e.once("error",s),e.listen(t,n,()=>{e.off("error",s),i()})})}function Xn(e){return new Promise(t=>{e.close(()=>t())})}function Z(e){try{e()}catch{}}function Yn(e){try{return e()}catch(t){return Promise.reject(t)}}function Zn(e,t){let n=e.address();return typeof n=="object"&&n?n.port:t}export{In as attachNextDevUpgradeHandler,Ie as attachSiteEditBridgeServerInWorker,Pn as classifySiteEditRenderProbeError,xn as createSiteEditAutoBootstrapHtmlSnippet,Rn as injectSiteEditAutoBootstrap,Nn as isSiteEditRenderProbeRequested,Wn as patchNextFirefoxDevChunk,Dn as prepareFirefoxNextDevChunkPatchRequest,Mn as prepareSiteEditHtmlInjectionRequest,En as resolveSiteEditBridgeHealthPath,Ye as resolveSiteEditClientAsset,Oi as resolveSiteEditClientAssetPath,gn as resolveSiteEditNextDevBundler,An as runSiteEditRenderProbe,Hi as startSiteEditNextDevServer,_n as transpileSiteEditClientSource};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vcp-dev/site-edit-bridge",
3
- "version": "0.10.58",
3
+ "version": "0.10.60",
4
4
  "type": "module",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -79,8 +79,8 @@
79
79
  "typecheck": "tsc -p tsconfig.json --noEmit"
80
80
  },
81
81
  "dependencies": {
82
- "@vcp-dev/contracts": "0.10.58",
83
- "@vcp-dev/site-edit-engine": "0.10.58",
82
+ "@vcp-dev/contracts": "0.10.60",
83
+ "@vcp-dev/site-edit-engine": "0.10.60",
84
84
  "@types/ws": "^8.18.1",
85
85
  "ws": "^8.20.1"
86
86
  },