conformtools 0.6.10 → 0.6.11
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/README.md +53 -22
- package/dist/{account-GFIQC77T.js → account-IUWNSDG5.js} +1 -1
- package/dist/{analysis-engine-4K5K6L53.js → analysis-engine-M7W32RRC.js} +1 -1
- package/dist/bridge-SV7PCLQY.js +3 -0
- package/dist/browser/timeline_core_bg.wasm +0 -0
- package/dist/{chunk-56EEBHP2.js → chunk-2CY2OOOJ.js} +1 -1
- package/dist/chunk-2QT5MMBP.js +499 -0
- package/dist/chunk-2WBGXD27.js +8 -0
- package/dist/chunk-5YULBQJX.js +3 -0
- package/dist/chunk-5YWO2LBG.js +3 -0
- package/dist/chunk-64X5DLH5.js +6 -0
- package/dist/{chunk-XJNWAQON.js → chunk-6NLB5TZ2.js} +1 -1
- package/dist/chunk-6VP6G7CY.js +10 -0
- package/dist/chunk-G3SZDPDS.js +3 -0
- package/dist/chunk-IK6RKNS5.js +3 -0
- package/dist/chunk-IN6XVTUS.js +3 -0
- package/dist/{chunk-NQNS4Y2B.js → chunk-LVGGCRDW.js} +1 -1
- package/dist/chunk-N34DQ6MH.js +14 -0
- package/dist/chunk-NSQP6CTA.js +20 -0
- package/dist/chunk-QTFFVLVJ.js +8 -0
- package/dist/chunk-RKIRHMON.js +5 -0
- package/dist/chunk-ROPKSAFP.js +6 -0
- package/dist/{chunk-GM262EDM.js → chunk-S6KP52OG.js} +1 -1
- package/dist/chunk-THVX57I3.js +4 -0
- package/dist/chunk-VE423Z2L.js +132 -0
- package/dist/chunk-XF3YMBI7.js +3 -0
- package/dist/{chunk-E5ENIKNR.js → chunk-XIAG7ACN.js} +2 -2
- package/dist/chunk-YU3SUSK3.js +3 -0
- package/dist/claude-setup-REU4AOKX.js +13 -0
- package/dist/cli.js +8 -8
- package/dist/emscripten-module-Q67P5WYC-HW3D2R5O.js +2161 -0
- package/dist/ffi-7KTOX2T4.js +3 -0
- package/dist/framing-ZTMYZR2S.js +3 -0
- package/dist/gfx-worker.js +1 -1
- package/dist/host-relink-FHNXXMHW.js +10 -0
- package/dist/hosted-BWAYLJXR.js +3 -0
- package/dist/hosts-Y6HGDRLM.js +3 -0
- package/dist/http.js +3 -3
- package/dist/{inspect-D3WEYL2W.js → inspect-RJFJQSHZ.js} +1 -1
- package/dist/mcp.js +7 -7
- package/dist/{media-3YMIZSSF.js → media-22VAJIVT.js} +1 -1
- package/dist/module-ES6BEMUI-L6VQ7K3J.js +3 -0
- package/dist/module-asyncify-2EFITU5U-Z4EEM6X7.js +3 -0
- package/dist/{probe-COWUTQGN.js → probe-72QZKMCC.js} +1 -1
- package/dist/{sequence-patch-JVEZW24V.js → sequence-patch-CN4VC5W3.js} +1 -1
- package/dist/{store-SZKXADGI.js → store-H676BOKI.js} +1 -1
- package/dist/timeline-5TGA5HBY.js +3 -0
- package/package.json +10 -1
- package/dist/bridge-73XMEZLH.js +0 -3
- package/dist/chunk-2MJAQROY.js +0 -5
- package/dist/chunk-7QUSVHO2.js +0 -10
- package/dist/chunk-CJYLQ3UM.js +0 -5
- package/dist/chunk-DFDXSIMI.js +0 -39
- package/dist/chunk-DNS4ZYIO.js +0 -3
- package/dist/chunk-JHTMYXJM.js +0 -20
- package/dist/chunk-QHXX5GDD.js +0 -440
- package/dist/chunk-TDIY4NRQ.js +0 -3
- package/dist/chunk-UGVGRL5M.js +0 -3
- package/dist/chunk-Y2QHZUGL.js +0 -5
- package/dist/chunk-YC7QDS5U.js +0 -19
- package/dist/chunk-ZVUKOFUX.js +0 -6
- package/dist/claude-setup-OKOPPDMB.js +0 -5
- package/dist/conformtools-analyze +0 -0
- package/dist/conformtools-decode +0 -0
- package/dist/framing-BKTUEUZO.js +0 -3
- package/dist/host-relink-PTV44KXF.js +0 -10
- package/dist/hosts-D3TR2QEV.js +0 -3
- package/dist/i2o-transfer +0 -0
- package/dist/timeline-PEUC3G7K.js +0 -3
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
var o=Object.defineProperty,p=(e,r,i)=>r in e?o(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i,_=(e,r,i)=>(p(e,typeof r!="symbol"?r+"":r,i),i);export{_ as a};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
import{kc as d}from"./chunk-VE423Z2L.js";import{$ as f,A as p,C as m,m as c,x as u,z as l}from"./chunk-G3SZDPDS.js";import o from"node:process";import{readFileSync as g,rmSync as h}from"node:fs";import{createConnection as w}from"node:net";var x=new Set(["tool_run","app","tool"]),s=()=>f(c(),"engine.json");async function I(e,r){await p(c()),await l(s(),JSON.stringify({port:e,token:r||void 0,pid:o.pid})),await m(s(),384);for(let t of["SIGINT","SIGTERM"])o.on(t,()=>o.exit(0));o.on("exit",()=>{try{JSON.parse(g(s(),"utf8")).pid===o.pid&&h(s())}catch{}})}function S(e,r=1500){return new Promise(t=>{let n=w({host:"127.0.0.1",port:e}),i=y=>{clearTimeout(a),n.destroy(),t(y)},a=setTimeout(()=>i(!1),r);n.once("connect",()=>i(!0)).once("error",()=>i(!1))})}async function O(e,r){if(!x.has(e))return null;let t;try{t=JSON.parse(await u(s()))}catch{return null}if(t.pid===o.pid||!await S(t.port))return null;let n;try{n=await fetch(`http://127.0.0.1:${t.port}/verbs/${e}`,{method:"POST",body:JSON.stringify(r),headers:{"content-type":"application/json","x-conform-client":d()??"mcp",...t.token?{authorization:`Bearer ${t.token}`}:{}}})}catch{return null}if(n.status===401||n.status===404)return null;let{text:i,...a}=await n.json();return{content:[{type:"text",text:i??""}],structuredContent:a,isError:!n.ok}}export{I as a,O as b};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
import{a as E}from"./chunk-PHAMF4JF.js";import{Q as x,b as y,f as g,g as f,j as w,k as h,r as p,u as b}from"./chunk-G3SZDPDS.js";async function k(){let e=f()==="win32"?"conformtools-analyze.exe":"conformtools-analyze",r=[y("CONFORM_ANALYZE"),w(e),p(new URL(`./${e}`,import.meta.url)),p(new URL(`../../rust/target/release/${e}`,import.meta.url))].filter(Boolean);for(let n of r)if(await b(n))return n;return null}var R=e=>e.code==="not_entitled"?new E("not_entitled",String(e.why)):void 0;async function A(e){let r=await P(),n=await r.ask({op:"job",reference:e.reference,clips:e.clips,lite:e.lite??!0,display:!!e.display});if(!n.ok)throw r.close(),R(n)??new Error(`analysis engine: ${n.why}`);return r}async function N(e,r,n){let i=await P(),t=()=>i.close();n?.addEventListener("abort",t);let s;try{s=await i.ask(e,r)}finally{n?.removeEventListener("abort",t),i.close()}if(n?.aborted)throw new Error("cancelled");if(!s.ok)throw R(s)??new Error(s.why??`the analysis engine could not run ${e.op}`);return s}async function P(){let e=await k();if(!e)throw new Error(h("the analysis engine (conformtools-analyze)"));let r="",n=null,i=[],t=x(e,["serve"],o=>{r+=new TextDecoder().decode(o);let a;for(;(a=r.indexOf(`
|
|
4
|
+
`))>=0;){let c=r.slice(0,a);r=r.slice(a+1);let l=JSON.parse(c);if(l.progress){n?.progress?.(l.progress[0],l.progress[1],l.phase??"");continue}let d=n;n=null,d?.done(l)}},o=>{console.error(o.trimEnd()),i=[...i,...o.split(`
|
|
5
|
+
`).filter(a=>a.trim())].slice(-3)}),s=null;t.exited.then(o=>{s={ok:!1,why:`the analysis engine exited${o==null?"":` (code ${o})`}${i.length?`: ${i.join(" | ").slice(0,400)}`:""}`},n?.done(s)});let m=Promise.resolve();return{ask:(o,a)=>{let c=m.then(async()=>{t.hold(!0);try{if(s)return s;let l=new Promise(v=>{n={done:v,progress:a}}),u=await t.write(new TextEncoder().encode(JSON.stringify(o)+`
|
|
6
|
+
`)).then(()=>!0,()=>!1)?await l:await Promise.race([l,t.exited.then(()=>s??{ok:!1,why:"the analysis engine exited"})]);return u.miss&&(console.error(`[mirror] MISS \u2014 ${u.miss} is not in the mirror. Replay never reads the source drive; record this case again with the drive mounted (CONFORM_MIRROR_MODE=record).`),g(75)),u}finally{t.hold(!1)}});return m=c.catch(()=>{}),c},close:()=>t.close()}}export{k as a,A as b,N as c,P as d};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{a as z}from"./chunk-
|
|
3
|
+
import{a as z}from"./chunk-64X5DLH5.js";import{a as w}from"./chunk-PHAMF4JF.js";import{$ as o,A as C,B as y,C as G,K as F,N as J,R as K,S as X,b as s,g as E,m as u,n as B,t as j,x as d,z as N}from"./chunk-G3SZDPDS.js";var Y={transferGB:2e3},f={payg:{id:"payg",name:"Pay As You Go",monthly:0,yearly:0,stripe:{},includes:{web:!0,mcp:!1,app:!1}},web:{id:"web",name:"Web",monthly:10,yearly:100,stripe:{},includes:{web:!0,mcp:!1,app:!1},allowance:{transferGB:50}},indie:{id:"indie",name:"MCP",monthly:49,yearly:490,stripe:{monthly:"price_1T5XDXJ5lnla0aaLasKq49tm",yearly:"price_1T5XDXJ5lnla0aaL2MdMSuI9"},includes:{web:!0,mcp:!0,app:!1},allowance:{transferGB:250}},pro:{id:"pro",name:"App",monthly:199,yearly:1990,stripe:{monthly:"price_1T5X8oJ5lnla0aaLyNJa93H0",yearly:"price_1T5X8oJ5lnla0aaL3dh7b1el"},includes:{web:!0,mcp:!0,app:!0},allowance:Y},studio:{id:"studio",name:"Studio",monthly:"custom",yearly:"custom",stripe:{monthly:"price_1T5X7xJ5lnla0aaLoeE1aBlL",yearly:"price_1T5X7xJ5lnla0aaLeBiYo3Di"},includes:{web:!0,mcp:!0,app:!0},allowance:Y}};var H={web:!0,mcp:!1,app:!1};var Ie=Object.fromEntries(Object.values(f).flatMap(e=>Object.values(e.stripe).map(t=>[t,e.id])));import{createPrivateKey as Oe,createPublicKey as le,sign as Ee,verify as ue}from"node:crypto";import{Buffer as m}from"node:buffer";var pe="CONFORMTOOLS_LICENSE_V1",q=/^[0-9A-F]{8}(-[0-9A-F]{8}){3}$/,V=e=>JSON.stringify({dev_mode:e.dev_mode??!1,email:e.email,expires_at:e.expires_at,features:e.features,issued_at:e.issued_at,machine_fingerprint:e.machine_fingerprint,tier:e.tier});function Z(e){let t=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r&&!r.startsWith("#")&&!r.startsWith("-----")).join(""),n=JSON.parse(m.from(t,"base64").toString("utf8"));if(n?.magic!==pe||!n.payload?.data)throw new Error("not a conform.tools licence");return n.payload}function W(e,t){let n=m.from(e.signature,"base64"),r=m.from(V(e.data));return n.length!==64?!1:t.some(i=>ue(null,r,le({key:m.concat([m.from("302a300506032b6570032100","hex"),m.from(i)]),format:"der",type:"spki"}),n))}var de=["cMwVBrEYKMzlG6pC7FF2lNKIoEqGz2xB5yph6clNnTg=","qnheqkkDU09l1oI6h2CFh4uQ97bY/hkTA5niGKH0+X8="],fe=de.map(e=>Uint8Array.from(atob(e),t=>t.charCodeAt(0)));function L(){let e=s("CONFORM_RECORDS_DIR");if(e)return e;let t=B(),n=E()==="darwin"?o(t,"Library/Application Support"):E()==="win32"?s("LOCALAPPDATA")??o(t,"AppData/Local"):s("XDG_DATA_HOME")??o(t,".local/share");return o(n,"conform.tools")}var me=()=>s("CONFORM_LICENSE_PATH")??o(L(),"license.lic"),I=()=>o(L(),"grant.lic"),ge=null;function T(){return ge??=(async()=>{let e=await z();if(!e)return[];let t=await J(e,["machine"],{timeoutMs:15e3}).catch(()=>null);try{return JSON.parse(t?.stdout??"").machines.filter(n=>q.test(n))}catch{return[]}})()}function he(e,t,n=Date.now()){if(!W(e,fe))return{ok:!1,reason:"invalid licence signature"};let r=Date.parse(e.data.expires_at);return!Number.isFinite(r)||r<n?{ok:!1,reason:`licence expired ${e.data.expires_at}`}:[t??[]].flat().includes(e.data.machine_fingerprint)?{ok:!0,data:e.data}:{ok:!1,reason:"licence is for another machine"}}async function Q(){let e;try{e=await d(me())}catch{return null}try{return he(Z(e),await T())}catch(t){return{ok:!1,reason:t.message}}}var _e={production:{supabaseUrl:"https://sttpwvjbpsetzbhrkohl.supabase.co",anonKey:"sb_publishable_cyuIPsrQa5Ye7lqFxjnknQ_ozDuwwzp",appBase:"https://conform.tools"},staging:{supabaseUrl:"https://slxggvbvgzkiwojcgykx.supabase.co",anonKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InNseGdndmJ2Z3praXdvamNneWt4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzEyODUzMTksImV4cCI6MjA4Njg2MTMxOX0.b18iDsWftny0k9VmOCcbN6kLlyZsZ7GULn_jRH9CE9I",appBase:"https://beta.conform.tools"}};function a(){let e=s("CONFORM_ENV")==="staging"?"staging":"production",t=_e[e];return{env:e,supabaseUrl:s("CONFORM_SUPABASE_URL")??t.supabaseUrl,anonKey:s("CONFORM_SUPABASE_ANON_KEY")??t.anonKey,appBase:s("CONFORM_APP_BASE")??t.appBase}}var ye=600*1e3,ee=72*3600*1e3,we=300*1e3,x=()=>o(u(),a().env==="production"?"auth.json":`auth-${a().env}.json`);async function $(){for(let e of new Set([x(),o(u(),"auth.json")]))try{let t=JSON.parse(await d(e));if(t.env===a().env&&t.access_token)return t}catch{}return null}async function be(){try{for await(let e of F(u())){if(!/^auth(?:-(\w+))?\.json$/.exec(e.name))continue;let n=JSON.parse(await d(o(u(),e.name)));if(n.access_token&&n.env&&n.env!==a().env)return{other_env:n.env}}}catch{}return{}}async function D(e){await C(u()),await N(x(),JSON.stringify(e)),await G(x(),384)}var ne=6e3,v=0,re=()=>Date.now()<v,ie=()=>{v=Date.now()+6e4};function Fe(){v=0}async function ae(e){if(e.expires_at-60>Date.now()/1e3)return e.access_token;if(re())return null;let t=a();try{let n=await fetch(`${t.supabaseUrl}/auth/v1/token?grant_type=refresh_token`,{method:"POST",headers:{apikey:t.anonKey,"content-type":"application/json"},body:JSON.stringify({refresh_token:e.refresh_token}),signal:AbortSignal.timeout(ne)}).catch(i=>{throw ie(),i});if(!n.ok)return n.status===400||n.status===401?"":null;let r=await n.json();return e.access_token=r.access_token,r.refresh_token&&(e.refresh_token=r.refresh_token),e.expires_at=r.expires_at??Math.floor(Date.now()/1e3)+(r.expires_in??3600),await D(e),e.access_token}catch{return null}}async function Je(){let e=await $();return e&&await ae(e)||null}var g=null;function te(e,t){return{signed_in:!0,entitled:e.entitled,env:a().env,email:e.email,access:e.access,tier:e.tier,trial_days_remaining:e.trial_days_remaining,source:t,...e.entitled?{}:{reason:"not_entitled"},...e.invite_only?{invite_only:!0}:{}}}async function oe(e={}){let t=await Q();if(t?.ok)return{signed_in:!!await $().catch(()=>null),entitled:!0,env:a().env,email:t.data.email,access:"licence",tier:t.data.tier,source:"licence"};let n=await xe(e);return t&&!n.entitled?{...n,licence_error:t.reason}:n}async function xe(e){if(!e.force&&g&&Date.now()-g.at<ye)return{...g.status,source:"cache"};let t=a(),n=await $();if(!n)return{signed_in:!1,entitled:!1,env:t.env,reason:"not_signed_in",...await be()};let r=await ae(n);if(r==="")return{signed_in:!0,entitled:!1,env:t.env,reason:"auth_rejected"};if(r&&!re())try{let i=(await T())[0],c=await fetch(`${t.supabaseUrl}/functions/v1/v1-billing/v1/billing/entitlement${i?`?machine=${i}`:""}`,{headers:{authorization:`Bearer ${r}`,apikey:t.anonKey},signal:AbortSignal.timeout(ne)}).catch(l=>{throw ie(),l});if(c.status===401||c.status===403)return{signed_in:!0,entitled:!1,env:t.env,reason:"auth_rejected"};if(c.ok){let{grant:l,...S}=(await c.json()).data;i&&await ve(l),n.last_entitlement=S,n.last_entitlement_at=Date.now(),await D(n);let A=te(S,"live");return g={at:Date.now(),status:A},A}}catch{}if(n.last_entitlement&&n.last_entitlement_at&&Date.now()-n.last_entitlement_at<ee){let i=ee-(Date.now()-n.last_entitlement_at);return{...te(n.last_entitlement,"grace"),grace_remaining_h:Math.round(i/36e4)/10}}return{signed_in:!0,entitled:!1,env:t.env,reason:"offline_grace_expired"}}async function ve(e){try{if(!e)return await y(I());await C(L()),await N(I(),e)}catch{}}function Se(e){return e.source==="licence"?`${e.email} \xB7 machine licence (${e.tier}) \u2014 runs offline, no account check`:Ae(e)+(e.licence_error?`
|
|
4
4
|
(the machine licence was not used: ${e.licence_error})`:"")}function Ae(e){let t=a();if(!e.signed_in)return`not signed in (${t.env})${e.other_env?`; you are signed in to ${e.other_env} only (each server keeps its own sign-in)`:""}. Run the account_login tool, or \`npx -y conformtools@latest login\` in a terminal.`;if(e.reason==="auth_rejected")return"signed-in session was rejected (expired or revoked) \u2014 sign in again with account_login.";if(e.reason==="offline_grace_expired")return"offline for more than 72 h since the last account check \u2014 reconnect and run account_status.";let n=`${e.email??"(unknown email)"} \xB7 ${t.env}`;if(!e.entitled&&e.invite_only)return`${n}
|
|
5
5
|
the conform.tools engine (the MCP and the app) is invite-only for now, and ${e.email??"this account"} is not on the list. If that is the wrong Google account, run account_logout, then account_login with the invited one.`;if(!e.entitled)return`${n}
|
|
6
6
|
no active plan on ${e.email??"this account"}: the trial has ended and there is no subscription. If that is the wrong Google account, run account_logout, then account_login and pick the account with the plan; otherwise choose a plan at ${t.appBase}/pricing, then run account_status.`;let r=e.access==="trial"?`trial, ${e.trial_days_remaining??"?"} day(s) left`:e.access==="allowlist"?"invited (early access)":`subscribed${e.tier?` (${e.tier})`:""}`,i=P(e),c=i?` \xB7 includes ${[i.web&&"the web tools",i.mcp&&"the MCP",i.app&&"the app"].filter(Boolean).join(", ")||"the web tools"}`:"";return`${n}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
import{a as M}from"./chunk-PFZVET7S.js";import{b as he,c as be,f as ge}from"./chunk-6V4OEOOX.js";import{f as K,h as fe}from"./chunk-XDI6CPPV.js";import{a as pe}from"./chunk-DGXZB7MO.js";import{i as D}from"./chunk-JXTRQ3UG.js";import{b as C,d as J,f as R}from"./chunk-NU3X7P4N.js";import{Ia as de,ea as se,fa as ae,ja as ce,oa as le,wa as ue,xa as me}from"./chunk-DPA26AOI.js";import{a as ie}from"./chunk-PHAMF4JF.js";import{$ as _,A as j,E as W,K as v,L as A,M as ne,P as oe,Y as b,Z as y,_ as L,b as E,c as Z,d as Q,g as q,j as ee,k as re,r as I,s as H,u as te,v as O,y as B}from"./chunk-G3SZDPDS.js";var V=!1;var F=8,Pe=0,Ee=3,z=2;async function Oe(e){let t=new Uint8Array(await e.slice(0,16).arrayBuffer()),o=s=>String.fromCharCode(t[s],t[s+1],t[s+2],t[s+3]);if(t[0]===6&&t[1]===14&&t[2]===43&&t[3]===52)return"mxf";if(o(4)==="RED1"||o(4)==="RED2")return"r3d";let r=t[0]<<24|t[1]<<16|t[2]<<8|t[3],i=o(4);return/^[A-Za-z0-9 ]{4}$/.test(i)&&(r>=8||r===1)&&r<=e.size?"isobmff":null}function Ae(e){let t=e.toLowerCase();return t.endsWith(".braw")?"braw":t.endsWith(".crm")?"crm":"mov"}function Ce(e){return async(t,o)=>new Uint8Array(await e.slice(t,Math.min(t+o,e.size)).arrayBuffer())}function we(e){let t=e.timecode;return!t||!t.fps_denominator?null:t.fps_numerator/t.fps_denominator}async function ir(e){return await de(),_e?_e.clip(e,V?"rec709":"",()=>ye(e)):ye(e)}var _e=null;async function ye(e){let t=await Oe(e),o=[];if(t==="r3d"){let r=e,i=r.parts&&r.bases?r.parts:[{name:e.name,size:e.size}],n=r.bases??[0],s=async(u,m,d)=>{let f=n[u]+m;return new Uint8Array(await e.slice(f,Math.min(f+d,n[u]+i[u].size)).arrayBuffer())},a=JSON.stringify(i.map(u=>({name:u.name,size:u.size}))),c=JSON.parse(await me(s,a)),l=JSON.parse(await ce(s,a));return i.length===1&&/_\d{3}\.r3d$/i.test(e.name)&&!/_001\.r3d$/i.test(e.name)&&o.push("spanned R3D part \u2014 only this part's frames are indexed"),{frames:l.map(u=>({offset:n[u.part??0]+u.essenceOffset,size:u.essenceLength})),w:c.width??0,h:c.height??0,fps:we(c),startFrame:c.timecode?.start_frame??0,dropFrame:c.timecode?.drop_frame??!1,label:"R3D",spec:{codec:"r3d",subbands:Pe},geometrySpec:{codec:"r3d",subbands:Ee},index:null,warnings:o}}if(t==="mxf"){let r=Ce(e),i=JSON.parse(await ue(r,e.size));if(!i)throw new Error(`${e.name}: MXF index unreadable`);let n=JSON.parse(await le(r,e.size)),s=[];for(let f=0;f<n.frame_count;f++)s.push({offset:n.frames[f*2],size:n.frames[f*2+1]});let a=s.filter(f=>f.size===0).length;a&&o.push(`${a} frame(s) had no locatable picture KLV`);let c=i.width??0,l=i.height??0,u=(i.inner_codec??"").toLowerCase(),m=null,d="MXF";return u==="arriraw"?(m={codec:"arriraw",w:c,h:l,scale:F},d="ARRIRAW"):u==="xocn"?(m={codec:"xocn",scale:F,...V?{display:"rec709"}:{}},d="X-OCN"):await ae(r,e.size)?(m={codec:"vc3",scale:F},d="DNxHR"):await se(r,e.size)?(m={codec:"prores"},d="ProRes"):o.push(`MXF inner codec ${u||"unknown"} not wired to the fingerprint pool`),{frames:m?s:[],w:c,h:l,fps:we(i),startFrame:i.timecode?.start_frame??0,dropFrame:i.timecode?.drop_frame??!1,label:d,spec:m,geometrySpec:m&&m.codec==="arriraw"?{...m,scale:z}:m&&m.codec==="xocn"?{codec:"xocn",scale:z,...V?{display:"rec709"}:{}}:m&&m.codec==="vc3"?{codec:"vc3",scale:z}:null,index:null,warnings:o}}if(t==="isobmff"){let r=await fe(e),i=Ae(e.name);if(r.kind==="prores")return{frames:r.offs,w:r.w,h:r.h,fps:r.fps,startFrame:r.startFrame,dropFrame:r.dropFrame,label:K(r.kind),spec:{codec:"prores"},geometrySpec:null,index:r,warnings:o};if(r.kind==="h264"||r.kind==="hevc")return{frames:r.offs,w:r.w,h:r.h,fps:r.fps,startFrame:r.startFrame,dropFrame:r.dropFrame,label:K(r.kind),spec:null,geometrySpec:null,index:r,warnings:o};let n=i==="braw"?{codec:"braw",scale:F}:r.codec==="aprh"||r.codec==="aprn"?{codec:"proresraw",scale:F}:null;return n||o.push(`codec ${r.codec} not wired to the fingerprint pool`),{frames:n?r.offs:[],w:r.w,h:r.h,fps:r.fps,startFrame:r.startFrame,dropFrame:r.dropFrame,label:n?i==="braw"?"BRAW":"ProRes RAW":`unsupported (${r.codec})`,spec:n,geometrySpec:n?{...n,scale:z}:null,index:r,warnings:o}}throw new Error(`${e.name}: unrecognised container`)}var De=Number(E("CONFORM_DECODERS")??0)||Math.max(2,Math.min(Math.floor(Q()/2),Math.floor(Z()/2**31))),X=0,xe=[],ze=async(...e)=>{X>=De?await new Promise(t=>xe.push(t)):X++;try{return await oe(...e)}finally{let t=xe.shift();t?t():X--}};async function Ne(){let e=q()==="win32"?"conformtools-decode.exe":"conformtools-decode",t=[E("CONFORM_NATIVE_DECODE"),ee(e),I(new URL(`./${e}`,import.meta.url)),I(new URL(`../../rust/target/release/${e}`,import.meta.url))].filter(Boolean);for(let o of t)if(await te(o))return o;return null}var $=class extends Error{constructor(o,r){super(r);this.why=o}};function Pr(e){let t=null;try{t=JSON.parse(e.trim().split(`
|
|
4
|
+
`).pop())}catch{}if(t?.why==="not_entitled")throw new ie("not_entitled",t.detail??"this machine is not licensed");return t?.detail??e.trim()}function Te(e,t){try{let o=JSON.parse(e.trim().split(`
|
|
5
|
+
`).pop()??"");return new $(o.why,o.detail)}catch{return new $("decoder",`the native decoder exited ${t}: ${e.trim().slice(-300)}`)}}function Ue(e){let t=e.reduce((i,n)=>i+n.length,0),o=new Uint8Array(t),r=0;for(let i of e)o.set(i,r),r+=i.length;return o}async function $e(e,t,o,r,i){let n=await Ne();if(!n)throw new $("missing",re("the native decoder (conformtools-decode)"));let s=null,a=[],c=0,l=d=>{let f=new Uint8Array(d),p=0;for(;p<d;){let h=a[0],g=Math.min(h.length,d-p);f.set(h.subarray(0,g),p),p+=g,g===h.length?a.shift():a[0]=h.subarray(g)}return c-=d,f},u=[e,t,"--width",String(i.width??32768)];i.from!=null&&u.push("--from",String(i.from)),i.count!=null&&u.push("--count",String(i.count)),i.range&&u.push("--range",i.range);let m=await ze(n,u,d=>{if(a.push(d),c+=d.length,!s){let p=Ue(a.splice(0));a.push(p);let h=p.indexOf(10);if(h<0)return;s=JSON.parse(new TextDecoder().decode(p.subarray(0,h))),l(h+1),o(s)}let f=4+s.w*s.h*(s.bpp??(e==="rgb16"?6:4));for(;c>=f;){let p=l(f);r(new DataView(p.buffer).getUint32(0,!0),p.subarray(4))}},{signal:i.signal});if(m.code!==0||!s)throw Te(m.stderr,m.code)}function ve(e,t,o,r={}){return $e("bgra",e,t,o,r)}function Se(e,t,o,r={}){return $e("rgb16",e,t,(i,n)=>o(i,new Uint16Array(n.buffer,n.byteOffset,n.length>>1)),r)}var ke=["none","rle","zips","zip","piz","pxr24","b44","b44a","dwaa","dwab","htj2k"],N=e=>(e>>4)*10+(e&15);function Ie(e){let t=N(e&63),o=N(e>>>8&127),r=N(e>>>16&127),i=N(e>>>24&63),n=s=>String(s).padStart(2,"0");return`${n(i)}:${n(r)}:${n(o)}${e&64?";":":"}${n(t)}`}function He(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.length<8||t.getUint32(0,!0)!==20000630)return null;let o={fps:null,timecode:null,width:0,height:0,display:null,compression:null,attributes:[]},r=8,i=()=>{let s=r;for(;r<e.length&&e[r]!==0;)r++;let a=new TextDecoder().decode(e.subarray(s,r));return r++,a},n=s=>({width:t.getInt32(s+8,!0)-t.getInt32(s,!0)+1,height:t.getInt32(s+12,!0)-t.getInt32(s+4,!0)+1});for(;r<e.length;){let s=i();if(!s)break;let a=i();if(r+4>e.length)return null;let c=t.getInt32(r,!0);if(r+=4,c<0||r+c>e.length)return null;if(o.attributes.push(`${s}:${a}`),s==="framesPerSecond"&&a==="rational"&&c>=8){let l=t.getInt32(r,!0),u=t.getUint32(r+4,!0);o.fps=u?l/u:null}else s==="timeCode"&&a==="timecode"&&c>=8?o.timecode=Ie(t.getUint32(r,!0)):s==="dataWindow"&&a==="box2i"&&c>=16?{width:o.width,height:o.height}=n(r):s==="displayWindow"&&a==="box2i"&&c>=16?o.display=n(r):s==="compression"&&c>=1&&(o.compression=ke[e[r]]??`type ${e[r]}`);r+=c}return o}async function Be(e){let t=e,o=null,r=/^(.*?)\[(\d+)-(\d+)\](.*)$/.exec(b(e));if(await O(e))o=/^(.*?)(\d+)(\.exr)$/i;else{t=y(e);let n=r?[null,r[1],r[2],r[4]]:/^(.*?)(\d+)(\.exr)$/i.exec(b(e));if(!n)return{frames:[e],numbers:[]};let s=a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");o=new RegExp(`^${s(n[1])}(\\d{${n[2].length}})${s(n[3])}$`,"i")}let i=[];for await(let n of v(t)){let s=n.isFile?o.exec(n.name):null;s&&i.push({n:Number(s[s.length===4?2:1]),f:_(t,n.name)})}return i.sort((n,s)=>n.n-s.n),{frames:i.map(n=>n.f),numbers:i.map(n=>n.n)}}async function Re(e){let t=await Be(e),o=t.frames[0];if(!o)throw new Error(`no .exr frames for '${b(e)}'`);let r=await A(o),i;try{i=He(await r.readAt(0,Math.min(r.size,1<<20)))}finally{await r.close()}if(!i)throw new Error(`'${b(o)}' is not an OpenEXR file`);let n=Math.max(1,t.frames.length),s=t.numbers.length>1?t.numbers[t.numbers.length-1]-t.numbers[0]+1-t.numbers.length:0,a=i.fps??0;return{id:b(o),kind:"external",target_url:o,local_path:o,content_kind:n>1?"video":"still",source_fps:i.fps??void 0,source_timecode:i.timecode??void 0,source_resolution_w:i.width,source_resolution_h:i.height,available_range:{start:{value:0,rate:a},duration:{value:n,rate:a}},streams:[{kind:"video",codec:"exr",width:i.width,height:i.height,rate:i.fps??void 0,codec_specific:{compression:i.compression}}],vendor_metadata:{exr:{frames:n,first_frame:t.numbers[0]??null,last_frame:t.numbers[t.numbers.length-1]??null,missing_frames:s,display_window:i.display,attributes:i.attributes,fps_source:i.fps!=null?"header framesPerSecond":"not in the header",timecode_source:i.timecode?"header timeCode (first frame)":"not in the header"}}}}var G=new Set([".mov",".mp4",".m4v",".mxf",".wav",".braw",".crm",".r3d",".aif",".aiff"]);async function je(e){let t=await A(e);return{path:e,file:t,size:t.size}}function We(e){return(t,o)=>e.file.readAt(t,o)}async function Le(e){let t=M(b(e));if(!t)return[e];let o=y(e),r=[];for await(let i of v(o)){if(!i.isFile)continue;let n=M(i.name);n&&n.clipBase===t.clipBase&&r.push({n:n.partNumber,p:_(o,i.name)})}return r.sort((i,n)=>i.n-n.n).map(i=>i.p)}async function Y(e){if(await O(e)){let n=[];for await(let s of v(e))s.isFile&&M(s.name)&&n.push(_(e,s.name));if(!n.length)throw new Error(`'${b(e)}' is a folder with no .R3D parts`);e=n.sort()[0]}let t=be(b(e));if(!t)throw new Error(`unsupported media file '${b(e)}' (supported: ${[...G].join(" ")})`);let o=await Le(e),r=await Promise.all(o.map(je));return{source:ge(t,r.map(n=>he(b(n.path),{fileSize:n.size,read:We(n)}))),parts:r,format:t,anchor:o[0],close:()=>r.forEach(n=>n.file.close())}}async function Je(e,t,o,r){if(!/h264|avc|hevc|h265/.test(o)){let i=null,n=await Y(e);try{return await D(n.source,{verb:"decode",index:t,intent:"park"})}catch(s){i=s}finally{n.close()}try{return await Me(e,t,r)}catch(s){throw/no decoder/.test(String(i))?s:i instanceof Error?i:new Error(String(i))}}return Me(e,t,r)}async function Hr(e,t,o,r={}){if(/\.mxf$/i.test(e)&&(!o||/h264|avc|mxf/.test(o))){let a=null,c=null;try{await Se(e,l=>{a=l},(l,u)=>{l===t&&(c=u.slice())},{from:t,count:1,range:r.range})}catch(l){if(!(l instanceof $)||!/unsupported|missing/.test(l.why))throw l}if(c&&a){let l=a;return{rgb:c,width:l.w,height:l.h,bits:l.bit_depth??16,decoder:"media-core",full_range:l.full_range??null}}}let i=await Je(e,t,o),n=i.width*i.height,s=new Uint16Array(n*3);for(let a=0;a<n;a++)s[a*3]=i.rgba[a*4]*257,s[a*3+1]=i.rgba[a*4+1]*257,s[a*3+2]=i.rgba[a*4+2]*257;return{rgb:s,width:i.width,height:i.height,bits:8,decoder:"8-bit",full_range:null}}async function Me(e,t,o){t=Math.round(t);let r=0,i=0,n=null;if(await ve(e,a=>{r=a.w,i=a.h},(a,c)=>{a===t&&(n=c)},{from:t,count:1,width:o}),!n)throw new Error(`the OS decoder returned no frame ${t} of ${b(e)}`);let s=n;for(let a=0;a<s.length;a+=4){let c=s[a];s[a]=s[a+2],s[a+2]=c}return{rgba:s,width:r,height:i}}async function P(e){if(/\.exr$/i.test(e))return Re(e);let t=await Y(e);try{let o=await D(t.source,{verb:"inspect"});if(!o)throw new Error(`could not read '${b(e)}' as ${t.format}`);return o.target_url=t.anchor,o.local_path=t.anchor,o.id=o.id||b(t.anchor),t.parts.length>1&&((o.vendor_metadata??={}).spanned_parts=t.parts.map(r=>b(r.path))),o.size_bytes=t.parts.reduce((r,i)=>r+i.size,0),o}finally{t.close()}}function Ke(e,t,o,r){let i=Math.abs(r*1001-Math.round(r*1001/1e3)*1e3)<1?Math.round(r)*1e3/1001:r,n=Math.floor(e*i/t+1e-6);return{tc:C(n,r),frames:Math.round(o*i/t)}}var Ve=e=>String(Math.round(e*1e3)/1e3);function Br(e,t){let o=e.streams?.find(m=>m.kind==="video"),r=e.streams?.filter(m=>m.kind==="audio")??[],i=e.vendor_metadata?.bext;if(!o&&e.available_range&&r[0]?.rate){let m=r[0].rate,d=e.available_range.duration.value,p=(t?[t]:[24e3/1001,24]).map(h=>{let g=Ke(i?.time_reference??0,i?.sample_rate||m,d,h);return`${i?`start TC ${g.tc}, `:""}${g.frames} frames @ ${Ve(h)} fps`});return[e.target_url??"",`audio only; ${d} samples (${(d/m).toFixed(3)} s)${i?`; BWF time_reference ${i.time_reference}`:"; no BWF timecode"}`,...p,...t?[]:["(pass fps for the project's rate)"],...r.map((h,g)=>`audio ${r.length>1?`${g+1}: `:""}${h.codec??"pcm"} ${h.channels??"?"}ch ${h.rate} Hz ${h.bit_depth??"?"}-bit`)].join(`
|
|
6
|
+
`)}let n=e.available_range?.duration?.value??e.declared_duration?.value??null,s=e.source_fps??o?.rate??null,a=e.size_bytes,c=e.vendor_metadata?.spanned_parts,l=o?.codec_specific??{},u=[l.profile?`${l.profile} (${l.fourcc})`:l.fourcc,l.pixel_format,o?.bit_depth?`${o.bit_depth}-bit`:null,l.colr?`color ${l.colr.primaries}/${l.colr.transfer}/${l.colr.matrix} (primaries/transfer/matrix)`:null].filter(Boolean).join(", ");return[e.target_url??"",o?`${o.codec??"?"} ${o.width??"?"}x${o.height??"?"}${s?` @ ${Math.round(s*1e3)/1e3} fps`:""}${u?`; ${u}`:""}`:"no video track",`start TC ${e.source_timecode??"none"}; ${n!=null?`${n} frames`:"length unknown"}${n!=null&&s?` (${(n/s).toFixed(2)} s)`:""}`,r.length?r.map((m,d)=>{let f=m.codec_specific?.channel_layout;return`audio ${r.length>1?`${d+1}: `:""}${m.codec??"pcm"} ${m.channels??"?"}ch${f?` (${f})`:""} ${m.rate??"?"} Hz ${m.bit_depth??"?"}-bit`}).join(`
|
|
7
|
+
`):"no audio",`${e.reel_name?`reel ${e.reel_name}; `:""}${a!=null?`${(a/1e6).toFixed(1)} MB`:""}${c?`; spanned ${c.length} parts`:""}`].join(`
|
|
8
|
+
`)}var Xe=8*1024*1024,T=e=>Uint8Array.from(atob(e),t=>t.charCodeAt(0));async function Ge(e,t,o){if(e.executable_locally===!1)throw new Error("this trim plan is server-side only");let r=new Map(t.parts.map(n=>[b(n.path),n]));await j(y(o));let i=await ne(o);try{await i.truncate(e.total_size),await i.writeAt(0,T(e.dest_header_bytes_base64));for(let n of e.src_byte_ranges){let s=n.src_file_name?r.get(b(n.src_file_name)):t.parts[0];if(!s)throw new Error(`plan references unknown source part '${n.src_file_name}'`);let a=0;for(;a<n.length;){let c=Math.min(Xe,n.length-a),l=await s.file.readAt(n.offset+a,c);if(l.length<c)throw new Error(`short read in ${b(s.path)} at ${n.offset+a}`);await i.writeAt(n.write_to_dest_offset+a,l),a+=c}}e.dest_footer_bytes_base64&&e.dest_footer_offset!=null&&await i.writeAt(e.dest_footer_offset,T(e.dest_footer_bytes_base64));for(let n of e.dest_patches??[])await i.writeAt(n.offset,T(n.bytes_base64))}finally{await i.close()}for(let n of e.dest_sidecar_writes??[])await B(_(y(o),n.name),T(n.bytes_base64))}function Ye(e,t){let o=[];for(let r of e){if(r.kind!=="clip"||!r.source_range)continue;let i=r.source_range.start.value,n=r.source_range.duration.value,s=Math.max(0,Math.floor(i)-t),a=Math.floor(i+n-1)+t;a>=s&&o.push({first_frame:s,last_frame:a})}return pe(o)}async function Ze(e,t,o,r,i){let n=await Y(e);try{let s=Ye(t,o);if(!s.length)throw new Error("no usable frame ranges (items need kind=clip with source_range)");let a=await D(n.source,{verb:"trim",selection:{items:t,handles:o}}),c=L(n.anchor),l=n.format==="r3d",u=l?M(b(n.anchor))?.clipBase??b(n.anchor,c):b(n.anchor,c),m=[];for(let[d,f]of a.entries()){let p=f.output_clip_number??(s.length>1?d+1:void 0),h=s[(p??1)-1]??s[0],g=p&&(f.output_clip_count??s.length)>1?`_S${String(p).padStart(3,"0")}`:"",w;if(l){let x=f.output_part_number??d+1;w=_(r,`${u}${g}.RDC`,`${u}_${String(x).padStart(3,"0")}.R3D`),m.push({path:w,bytes:f.total_size,island:h,part:x,clip:p})}else{let x=i&&a.length===1?i:`${u}${g||`_trim_${h.first_frame}-${h.last_frame}`}${c}`;w=_(r,x),m.push({path:w,bytes:f.total_size,island:h,clip:p})}await Ge(f,n,w)}return l||await Qe(e,m,!!i&&a.length===1),{outputs:m,islands:s,format:n.format}}finally{n.close()}}async function Qe(e,t,o){let r=await P(e).catch(()=>null),i=r?.source_fps??r?.streams?.find(n=>n.kind==="video")?.rate??null;if(!(!r?.source_timecode||!i))for(let n of t){if(!n.island)continue;let s=await P(n.path).catch(()=>null),a=s?.available_range?.duration?.value??s?.declared_duration?.value;if(!s?.source_timecode||!a)continue;let c=R(s.source_timecode,i,r.source_timecode);if(c===n.island.first_frame&&c+a-1===n.island.last_frame||(n.island={first_frame:c,last_frame:c+a-1},o))continue;let l=n.path.replace(/_trim_\d+-\d+(\.[^./\\]+)$/,`_trim_${c}-${c+a-1}$1`);l!==n.path&&(await W(n.path,l),n.path=l)}}async function jr(e){let t=await P(e.path),o=t.source_fps??t.streams?.find(p=>p.kind==="video")?.rate??null,r=t.available_range?.duration?.value??t.declared_duration?.value??null;if(!o)throw new Error("cannot trim: no frame rate / timecode track on this file");let i=R(e.in,o,t.source_timecode??null),n=R(e.out,o,t.source_timecode??null);if(e.out_exclusive&&(n-=1),n<i)throw new Error(`out (${n}) is before in (${i})`);if(i<0)throw new Error(`in (${i}) is before the file start (TC ${t.source_timecode})`);if(r!=null&&n>r-1)throw new Error(`out (${n}) is past the last frame (${r-1})`);let s={id:"trim",kind:"clip",source_range:{start:{value:i,rate:o},duration:{value:n-i+1,rate:o}}},a=y(e.path),c;if(e.out_path)try{(await H(e.out_path)).isDirectory?a=e.out_path:(a=y(e.out_path),c=b(e.out_path))}catch{a=y(e.out_path),c=b(e.out_path)}let l=await Ze(e.path,[s],Math.max(0,Math.floor(e.handles??0)),a,c),u=l.islands[0],m=l.outputs.length===1&&l.outputs[0].island?l.outputs[0].island:u,d=m.first_frame,f=m.last_frame;return{outputs:l.outputs,first_frame:d,last_frame:f,frames:f-d+1,fps:o,facts:t,...d!==u.first_frame||f!==u.last_frame?{asked:{first_frame:u.first_frame,last_frame:u.last_frame}}:{}}}function Fe(e){let t=[...G].map(o=>o.slice(1)).join("|");return e.toLowerCase().replace(new RegExp(`\\.(${t})(?=[._\\s-]|$)`,"g"),"").replace(/[^a-z0-9]/g,"")}function qe(e,t){let o=Fe(e),r=Fe(t);if(r&&o.includes(r))return"name";let i=t.toLowerCase().split(/[^a-z0-9]+/).filter(n=>/\d/.test(n)&&n.length>=3);return i.length&&i.every(n=>o.includes(n))?"id":null}async function Wr(e,t,o){let r=[],i=0,n=null,s=Date.now()+o.time_limit_s*1e3,a=async(c,l)=>{try{for await(let u of v(c)){if(n&&!n.startsWith("folders"))return;if(++i>o.max_entries){n=`stopped after ${o.max_entries} entries (max_entries)`;return}if(Date.now()>s){n=`stopped after ${o.time_limit_s} s (time_limit_s)`;return}if(u.name.startsWith("."))continue;let m=_(c,u.name);if(u.isDirectory)l<o.max_depth?await a(m,l+1):n??=`folders deeper than max_depth=${o.max_depth} not searched (e.g. ${m})`;else if(u.isFile&&G.has(L(u.name).toLowerCase())){let d=qe(u.name,t);d&&r.push({path:m,match:d,size:(await H(m).catch(()=>({size:0}))).size})}}}catch{}};if(await a(e,0),o.probe)for(let c=0;c<r.length;c+=8)await Promise.all(r.slice(c,c+8).map(async l=>{try{l.facts=await P(l.path)}catch(u){l.error=u.message}}));return r.sort((c,l)=>c.path.localeCompare(l.path)),{hits:r,scanned:i,truncated:n}}function er(e){let t=e.streams?.find(a=>a.kind==="video"),o=e.source_fps??t?.rate??null,r=e.available_range?.duration?.value??e.declared_duration?.value??null,i=t?.codec_specific??{},n=e.source_timecode&&o?J(e.source_timecode,o):null,s=n!=null&&r!=null&&o?C((n+r)%(Math.round(o)*86400),o,e.source_timecode.includes(";")):null;return`${t?`${t.codec??"?"}${i.profile?` ${i.profile}`:""} ${t.width??"?"}x${t.height??"?"}`:"no video"}${o?` @ ${Math.round(o*1e3)/1e3} fps`:""}; TC ${e.source_timecode??"none"}${s?`\u2013${s}`:""}; ${r??"?"} fr${r!=null&&o?` (${(r/o).toFixed(2)} s)`:""}`}function Lr(e,t,o,r){let i=e.hits.slice(0,r),n=[];e.truncated&&n.push(`TRUNCATED: ${e.truncated} \u2014 the search did NOT cover all of ${t}; the matches below may be incomplete.`),e.hits.length>i.length&&n.push(`TRUNCATED: showing ${i.length} of ${e.hits.length} matches. Pass limit=${e.hits.length} or narrow the query.`),n.push(`${e.hits.length} file${e.hits.length===1?"":"s"} match "${o}" under ${t} (${e.scanned} entries scanned)`);let s=new Map;for(let c of e.hits)s.set(b(c.path).toLowerCase(),(s.get(b(c.path).toLowerCase())??0)+1);let a=[...s].filter(([,c])=>c>1);a.length&&n.push(`same name in several folders: ${a.map(([c,l])=>`${c} \xD7${l}`).join(", ")} \u2014 they can be DIFFERENT clips; match by TC + duration, never by name alone`);for(let c of i)n.push(`- ${c.path}${c.match==="id"?" (id match)":""}
|
|
9
|
+
${c.facts?er(c.facts):c.error?`probe failed: ${c.error}`:`${(c.size/1e6).toFixed(1)} MB`}`);return n.join(`
|
|
10
|
+
`)}async function Jr(e,t,o=0){let r=await P(e),i=r.source_fps??r.streams?.find(d=>d.kind==="video")?.rate??null,n=r.available_range?.duration?.value??r.declared_duration?.value??null;if(!i||n==null)throw new Error(`cannot check coverage: ${b(e)} has no frame rate or length`);let s=Math.round(i)*86400,a=r.source_timecode?J(r.source_timecode,i)??0:0,c=!!r.source_timecode?.includes(";"),l=d=>{let f=R(d,i,r.source_timecode??null);return typeof d=="number"||/^\d+$/.test(d.trim())?f:f<-s/2?f+s:f>s/2?f-s:f},u=d=>C(((a+d)%s+s)%s,i,c),m=t.map((d,f)=>{let p=l(d.in),h=l(d.out),g=p,w=n-h,x=g>=0&&w>=0&&h>p,U=Math.max(0,-g),k=Math.max(0,-w),S=[];return h<=p?S.push("out is not after in"):x?S.push(`covered; handles head ${g} / tail ${w} fr`):S.push(`NOT covered: short ${[U?`${U} fr at head`:"",k?`${k} fr at tail`:""].filter(Boolean).join(", ")}`),x&&o&&(g<o||w<o)&&S.push(`handles short of ${o}: ${[g<o?`head by ${o-g}`:"",w<o?`tail by ${o-w}`:""].filter(Boolean).join(", ")}`),{label:d.label??`range ${f+1}`,in_tc:u(p),out_tc:u(h),frames:h-p,covered:x,head:g,tail:w,short_head:U,short_tail:k,note:S.join("; ")}});return{facts:r,rows:m}}export{ir as a,Ne as b,Pr as c,ve as d,Be as e,G as f,Le as g,Y as h,Je as i,Hr as j,P as k,Ke as l,Br as m,Ye as n,Ze as o,jr as p,Fe as q,qe as r,Wr as s,er as t,Lr as u,Jr as v};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
import{readFile as A,writeFile as N,appendFile as J,stat as W,readdir as q,mkdir as G,open as k,copyFile as Y,mkdtemp as K,rm as M,chmod as Q,rename as _,cp as V,statfs as X,realpath as Z}from"node:fs/promises";import{execFile as ee,spawn as B}from"node:child_process";import{createHash as te}from"node:crypto";import{createReadStream as re,chmodSync as ne,cpSync as oe,existsSync as D,statSync as E}from"node:fs";import{homedir as se,tmpdir as ie,platform as ae,release as ce,arch as le,totalmem as ue,availableParallelism as de}from"node:os";import{fileURLToPath as S}from"node:url";import me from"node:http";import fe from"node:http2";import f from"node:process";import{Buffer as P}from"node:buffer";import{basename as pe,dirname as ge,join as b,resolve as C,sep as v}from"node:path";import{createRequire as ye}from"node:module";import{basename as Rt,dirname as At,extname as kt,join as St,relative as Ut,resolve as Ft}from"node:path";{let e=globalThis.fetch,t=typeof globalThis.Deno<"u";e&&!t&&(globalThis.fetch=(async(n,o)=>{let r=typeof n=="string"?n:n instanceof URL?n.href:n.url;if(r.startsWith("file:")){let s=await A(S(r)),i=r.endsWith(".wasm")?"application/wasm":"application/octet-stream";return new Response(s,{status:200,headers:{"content-type":i}})}return e(n,o)}))}var h=e=>f.env[e],Ce=()=>Number(h("CONFORM_MEMORY_GB")??0)*2**30||ue(),He=()=>de(),Ie=()=>f.argv.slice(2),Ne=e=>f.exit(e),we=()=>f.platform,We=()=>h("CONFORM_PYTHON")??(we()==="win32"?"python":"python3"),Me=()=>f.arch,j=()=>`${f.platform}-${f.arch}`;function _e(e){try{return b(ge(ye(import.meta.url).resolve(`${be(j())}/package.json`)),e)}catch{return null}}var be=e=>`conformtools-${e==="win32-x64"?"windows-x64":e}`,Be=e=>`${e} is not in this package for ${j()} (conform.tools builds it for darwin-arm64, darwin-x64, linux-x64 and win32-x64)`;function je(){let e=f.versions.deno;return{platform:`${ae()} ${ce()} ${le()}`,runtime:e?`deno ${e}`:`node ${f.version}`}}var he=()=>h("CONFORM_MCP_HOME")??b(R(),".conform-mcp"),R=()=>h("HOME")??se();function ze(e){let t=e.trim();if(t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1)),/^file:\/\//i.test(t))try{t=S(t)}catch{}return t==="~"?t=R():(t.startsWith("~/")||t.startsWith("~\\"))&&(t=b(R(),t.slice(2))),t&&C(t)+(/[\\/]$/.test(t)&&!/[\\/]$/.test(C(t))?v:"")}async function Le(e,t){let n=await import("node:sqlite").catch(()=>null);if(n?.DatabaseSync){let r=new n.DatabaseSync(e,{readOnly:!0});try{let s=r.prepare(t);return s.setReadBigInts(!0),s.all().map(i=>Object.fromEntries(Object.entries(i).map(([c,a])=>[c,typeof a=="bigint"?Number(a):a])))}finally{r.close()}}let o=await F("sqlite3",["-readonly","-json",e,t]);if(!o.success)throw new Error(`sqlite3 ${pe(e)}: ${o.stderr.trim()||o.stdout.trim()}`);return o.stdout.trim()?JSON.parse(o.stdout):[]}var Je=(e,t)=>e?`${e.replace(/[\\/]+$/,"")}${e.includes("\\")&&!e.includes("/")?"\\":"/"}${t}`:t;function qe(e){let t=S(e),n=t.indexOf(`${v}deno-compile-`);if(n<0||!D(t))return t;let o=t.slice(n+1).split(v).slice(1).join(v),r=b(he(),"bin",o);try{let s=E(t),i=D(r)?E(r):null;return(!i||s.isFile()&&(i.size!==s.size||i.mtimeMs<s.mtimeMs))&&(oe(t,r,{recursive:!0,force:!0}),s.isFile()&&ne(r,493)),r}catch{return t}}var H=null;var x=e=>H?.owns(e)?H:null;async function I(e){let t=await W(e);return{isFile:t.isFile(),isDirectory:t.isDirectory(),size:t.size,mtimeMs:t.mtimeMs}}function U(e){return x(e)?.stat(e,()=>I(e))??I(e)}async function Ge(e){try{return await U(e),!0}catch{return!1}}async function Ye(e){try{return(await U(e)).isFile}catch{return!1}}async function Ke(e){try{return(await U(e)).isDirectory}catch{return!1}}async function Qe(e){x(e)?.guard(e,"read whole file");let t=await A(e);return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}var Ve=e=>A(e,"utf8"),Xe=(e,t)=>N(e,t),Ze=(e,t,n)=>n?.append?J(e,t):N(e,t);async function et(e){await G(e,{recursive:!0})}var tt=e=>M(e,{force:!0}),rt=(e,t)=>Q(e,t).catch(()=>{}),nt=(e,t)=>Y(e,t),ot=(e,t)=>_(e,t),st=e=>M(e,{recursive:!0,force:!0}),it=(e,t)=>V(e,t,{recursive:!0,verbatimSymlinks:!0});async function at(e){try{let t=await X(e);return Number(t.bavail)*Number(t.bsize)}catch{return null}}async function ct(e){try{return await Z(e)}catch{return null}}var lt=(e="conform-")=>K(b(ie(),e));async function*ut(e){let t=async()=>(await q(e,{withFileTypes:!0})).map(n=>({name:n.name,isFile:n.isFile(),isDirectory:n.isDirectory()}));yield*await(x(e)?.readDir(e,t)??t())}async function dt(e){x(e)?.guard(e,"read bytes");let t=await k(e,"r"),n=(await t.stat()).size;return{path:e,size:n,async readAt(o,r){let s=new Uint8Array(r),i=0;for(;i<r;){let{bytesRead:c}=await t.read(s,i,r-i,o+i);if(!c)break;i+=c}return i===r?s:s.subarray(0,i)},close:()=>t.close()}}async function mt(e){let t=await k(e,"w");return{async writeAt(n,o){let r=0;for(;r<o.length;){let{bytesWritten:s}=await t.write(o,r,o.length-r,n+r);r+=s}},truncate:n=>t.truncate(n),close:()=>t.close()}}var z=(e,t)=>{for(let n of t)x(n)?.guard(n,`${e.split(/[\\/]/).pop()} ${t[0]}`)};function F(e,t,n={}){return z(e,t),new Promise(o=>{ee(e,t,{maxBuffer:1<<30,env:n.env?{...f.env,...n.env}:void 0,timeout:n.timeoutMs},(r,s,i)=>{let c=r?.code??0;o({success:!r,code:c,stdout:String(s),stderr:String(i)})})})}var xe="[Console]::OutputEncoding=[Text.Encoding]::UTF8;$t=@{};Get-Process|?{$_.MainWindowTitle}|%{$t[$_.Id]=$_.MainWindowTitle};ConvertTo-Json -Compress -InputObject @(Get-CimInstance Win32_Process|%{[pscustomobject]@{pid=[int]$_.ProcessId;exe=$_.ExecutablePath;cmd=$_.CommandLine;title=$t[[int]$_.ProcessId]}})";async function ft(){let e=await F("powershell.exe",["-NoProfile","-NonInteractive","-Command",xe],{timeoutMs:3e4});return ve(e.stdout)}function ve(e){let t;try{t=JSON.parse(e.replace(/^/,"").trim()||"[]")}catch{return[]}return(Array.isArray(t)?t:[t]).flatMap(n=>{let o=n??{},r=Number(o.pid);return!Number.isInteger(r)||r<=0?[]:[{pid:r,args:String(o.cmd||o.exe||""),title:typeof o.title=="string"?o.title:""}]})}function pt(e,t,n,o={}){return z(e,t),new Promise((r,s)=>{let i=B(e,t,{env:o.env?{...f.env,...o.env}:void 0,stdio:["ignore","pipe","pipe"]}),c="";i.stdout.on("data",a=>n(a)),i.stderr.on("data",a=>{c+=new TextDecoder().decode(a)}),i.on("error",s),i.on("close",a=>r({code:a,stderr:c})),o.signal?.addEventListener("abort",()=>i.kill(),{once:!0})})}function gt(e,t,n,o){let r=B(e,t,{stdio:["pipe","pipe","pipe"]});r.stdin.on("error",()=>{}),r.stdout.on("data",a=>n(a)),r.stderr.on("data",a=>o?.(new TextDecoder().decode(a)));let s=new Promise(a=>{r.on("close",l=>a(l)),r.on("error",()=>a(null))}),i=[r,r.stdout,r.stderr,r.stdin],c=a=>{for(let l of i)(a?l.ref:l.unref)?.call(l)};return c(!1),{write:a=>new Promise((l,d)=>{r.stdin.write(a,m=>m?d(m):l())}),hold:c,close:()=>{try{r.stdin.end(),r.kill()}catch{}},exited:s}}async function yt(e){if(h("CONFORM_NO_BROWSER"))return!1;let[t,n]=f.platform==="darwin"?["open",[e]]:f.platform==="win32"?["cmd",["/c","start","",e.replace(/&/g,"^&")]]:["xdg-open",[e]];return(await F(t,n)).success}function wt(e,t){let n=me.createServer(async(o,r)=>{try{let s=[];if(o.method!=="GET"&&o.method!=="HEAD")for await(let m of o)s.push(m);let i=s.length>0,c=new Headers;for(let[m,p]of Object.entries(o.headers))p!=null&&c.set(m,Array.isArray(p)?p.join(", "):p);let a=`http://${o.headers.host??`${e.hostname}:${e.port}`}${o.url??"/"}`,l=new AbortController;r.on("close",()=>{r.writableEnded||l.abort()});let d=await t(new Request(a,{method:o.method,headers:c,body:i?P.concat(s):void 0,signal:l.signal}));if(r.statusCode=d.status,d.headers.forEach((m,p)=>r.setHeader(p,m)),d.body&&d.headers.get("content-type")?.startsWith("text/event-stream")){r.flushHeaders();let m=d.body.getReader();for(l.signal.addEventListener("abort",()=>void m.cancel(),{once:!0});;){let{value:p,done:g}=await m.read();if(g)break;r.write(p)}r.end();return}r.end(P.from(await d.arrayBuffer()))}catch(s){r.statusCode=500,r.end(JSON.stringify({ok:!1,code:"internal",message:s instanceof Error?s.message:String(s)}))}});return n.listen(e.port,e.hostname,()=>{let o=n.address();e.onListen?.(typeof o=="object"&&o?o.port:e.port)}),{close:()=>n.close()}}var y=class extends Error{constructor(n,o,r){super(o);this.code=n;this.grpcStatus=r}};function bt(e,t,n,o,r){return new Promise((s,i)=>{let c=fe.connect(`http://${e}:${t}`),a=!1,l=(u,L)=>{a||(a=!0,clearTimeout(m),c.destroy(),u?i(u):s(L))},d=!1;c.on("connect",()=>{d=!0});let m=setTimeout(()=>l(d?new y("deadline",`no answer from ${e}:${t} in ${r} ms`):new y("unavailable",`${e}:${t}: no connection in ${r} ms`)),r);c.on("error",u=>l(new y("unavailable",`${e}:${t}: ${u.message}`)));let p=P.alloc(5+o.length);p.writeUInt32BE(o.length,1),p.set(o,5);let g=c.request({":method":"POST",":path":n,"content-type":"application/grpc",te:"trailers"}),O=[],w,$="",T=u=>{u["grpc-status"]!=null&&(w=String(u["grpc-status"]),$=decodeURIComponent(String(u["grpc-message"]??"")))};g.on("response",T),g.on("trailers",T),g.on("data",u=>O.push(u)),g.on("error",u=>l(new y("unavailable",`${e}:${t}: ${u.message}`))),g.on("end",()=>{if(w!=="0")return l(new y("grpc",`grpc-status ${w??"missing"}${$?`: ${$}`:""}`,w==null?void 0:Number(w)));let u=P.concat(O);if(u.length<5||u[0]!==0)return l(new y("grpc","reply is not one uncompressed gRPC message"));l(null,new Uint8Array(u.subarray(5,5+u.readUInt32BE(1))))}),g.end(p)})}async function ht(e){let t=te("sha256");for await(let n of re(e))t.update(n);return t.digest("hex")}async function xt(e,t,n){let o=`${t}.part`;for(let r=0;;r++){let s=0;try{s=(await W(o)).size}catch{}try{let i=await fetch(e,{headers:s?{Range:`bytes=${s}-`}:{}});if(i.status===416)break;if(!i.ok||!i.body)throw new Error(`${e} answered ${i.status}`);s&&i.status!==206&&(s=0);let c=s+Number(i.headers.get("content-length")??0),a=await k(o,s?"a":"w");try{let l=s;for await(let d of i.body)await a.write(d),l+=d.length,n?.(l,c)}finally{await a.close()}break}catch(i){if(r>=4)throw i;await new Promise(c=>setTimeout(c,2e3*(r+1)))}}await _(o,t)}function vt(e){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}export{S as a,h as b,Ce as c,He as d,Ie as e,Ne as f,we as g,We as h,Me as i,_e as j,Be as k,je as l,he as m,R as n,ze as o,Le as p,Je as q,qe as r,U as s,Ge as t,Ye as u,Ke as v,Qe as w,Ve as x,Xe as y,Ze as z,et as A,tt as B,rt as C,nt as D,ot as E,st as F,it as G,at as H,ct as I,lt as J,ut as K,dt as L,mt as M,F as N,ft as O,pt as P,gt as Q,yt as R,wt as S,y as T,bt as U,ht as V,xt as W,vt as X,Rt as Y,At as Z,kt as _,St as $,Ut as aa,Ft as ba};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
import{b as s}from"./chunk-G3SZDPDS.js";var l="0.6.11";function a(t,i){let n=t.split("-")[0].split(".").map(Number),o=i.split("-")[0].split(".").map(Number);for(let e=0;e<Math.max(n.length,o.length);e++){let r=(n[e]||0)-(o[e]||0);if(r)return r>0}return!1}var u=null;function p(){return s("CONFORM_UPDATE_CHECK")==="off"?Promise.resolve(null):u??=fetch("https://registry.npmjs.org/conformtools/latest",{signal:AbortSignal.timeout(2e3)}).then(t=>t.ok?t.json():null).then(t=>typeof t?.version=="string"?t.version:null).catch(()=>null)}var c="run npx -y conformtools@latest setup claude (or setup codex) once: it registers the server so every new session runs the newest version (npx --prefer-online), then restart the MCP client; if an old global install is shadowing it: npm rm -g conformtools";async function f(){let t=await p();return`conformtools ${l}`+(t&&a(t,l)?` \u2014 update available: ${t} \u2192 ${c}`:"")}export{l as a,a as b,p as c,c as d,f as e};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
var e={reelName:!1,fileName:!0,fileNameMode:"loose",fileExtensions:"",totalDuration:!1,resolution:!1,bitDepth:!1,fileFormat:!1,codec:!1,mediaUmid:!1};export{e as a};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{G as
|
|
3
|
+
import{G as g,S as f}from"./chunk-C2ESM27Z.js";var m={prproj:"prproj","resolve-drt":"drt",aaf:"aaf",avb:"avb",otio:"otio",capcut:"capcut","flame-archive":"flame","resolve-fcpxml":"fcpxml","finalcut-fcpxml":"fcpxml","fcp-xml":"xmeml","premiere-xml":"xmeml","resolve-xml":"xmeml","baselight-blscene":"blscene"};function R(e){return e in m}var l=null;function c(){return l||(l=b()),l}async function b(){let e=await import("./timeline_core-ZKQQHUA2.js"),r=(await import("./timeline_core_bg-JW42YM3G.js")).default;return await e.default({module_or_path:r}),e}async function S(e,r){let o=m[r];if(!o)throw new Error(`timelineInspect: no Rust engine for format '${r}'`);let n=await c(),s=e.name.replace(/\.[^.]+$/,""),t=(y,..._)=>n[y](..._),i;switch(o){case"prproj":i=t("inspect_prproj_json",await a(e));break;case"aaf":i=t("inspect_aaf_json",await a(e));break;case"avb":i=t("inspect_avb_json",await a(e));break;case"flame":i=t("inspect_flame_json",await a(e),s);break;case"drt":i=t("inspect_drt_json",await w(e));break;case"otio":i=t("inspect_otio_json",await e.text(),s);break;case"capcut":i=t("inspect_capcut_json",await e.text(),s);break;case"fcpxml":i=t("inspect_fcpxml_json",await e.text(),s);break;case"xmeml":i=t("inspect_xmeml_json",await e.text(),s);break;case"blscene":i=t("inspect_blscene_json",await a(e),s);break}return v(i)}var d=12*1024*1024,p=!1;function j(e){p=e}var x=null,h=8e3;async function I(){!x||p||await Promise.race([x,new Promise(e=>setTimeout(e,h))])}function u(e,r,o){if(p||e.length<=d)return e;let n=(e.length/1048576).toFixed(0),s=o?.length??0;throw s===1?new Error(`This ${r.toUpperCase()} timeline extracts to ${n} MB, past what our conversion server can hold in one pass (the ceiling is ours, not your file \u2014 a single long timeline can exceed it on its own). Get in touch and we will convert it for you while we lift the limit.`):new Error(`This ${r.toUpperCase()} selection${s?` (${s} sequences)`:""} extracts to ${n} MB, past what our conversion server can hold in one pass. Convert a few sequences at a time \u2014 one long timeline is usually about ${(d/1048576).toFixed(0)} MB. If a single timeline still will not go through, get in touch and we will convert it for you.`)}async function W(e,r,o){let n=m[r];if(!n)throw new Error(`timelineExtract: no Rust engine for format '${r}'`);switch(await I(),n){case"otio":case"capcut":case"fcpxml":case"xmeml":return{fmt:n,extract:await e.text()};case"blscene":{let t=(await c()).extract_blscene_json(await a(e));return{fmt:n,extract:u(t,n,o)}}case"drt":{let t=(await c()).extract_drt_json(await w(e));return{fmt:n,extract:u(t,n,o)}}case"prproj":{let s=await c(),t=JSON.stringify(o??[]),i=s.extract_prproj_json(await a(e),t);return{fmt:n,extract:u(i,n,o)}}case"avb":{let s=await c(),t=JSON.stringify(o??[]),i=s.extract_avb_json(await a(e),t);return{fmt:n,extract:u(i,n,o)}}case"aaf":case"flame":{let t=(await c())[`extract_${n}_json`](await a(e));return{fmt:n,extract:u(t,n,o)}}}}async function a(e){return new Uint8Array(await e.arrayBuffer())}async function w(e){let r=f(await a(e)),o={};for(let[n,s]of Object.entries(r))n.toLowerCase().endsWith(".xml")&&(o[n]=g(s));return JSON.stringify(o)}function v(e){let r=JSON.parse(e),o=Array.isArray(r)?r:r?.timelines??r?.sequences??[],n=o.filter(t=>typeof t=="object"&&t!==null),s=o.map(t=>{if(typeof t=="string")return t;let i=t;return i?.name??i?.title??i?.id??""}).filter(t=>!!t);return{names:Array.from(new Set(s)),timelines:n}}async function A(e){let r=await c();return JSON.parse(r.drx_grade_tree(e))}var T="X-Write-Issues";var C=8*1024;function U(e){if(!e)return[];try{let r=JSON.parse(decodeURIComponent(e));return Array.isArray(r)?r:[]}catch{return[]}}export{R as a,S as b,j as c,W as d,A as e,T as f,U as g};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
var S=["family","style","stagger","ease","plate","radiusLu","padLu","uppercase","tracking"],C=["accent","primary","secondary"],_=[...C,...S],F={family:"inter",accent:"#0a84ff",primary:"#ffffff",secondary:"#cfe0ff",style:"slide",stagger:.06,ease:"outBack",plate:"tick",radiusLu:1.2,padLu:2.4,uppercase:!1,tracking:0},j=[{id:"studio",label:"Studio",note:"The house default \u2014 a gradient slab with an accent rule.",look:{...F}},{id:"broadcast",label:"Broadcast",note:"Hard-edged scrim, no radius, tracked caps. Reads at any size.",look:{family:"condensed",accent:"#e11d2e",primary:"#ffffff",secondary:"#c9ced6",style:"wipe",stagger:.05,ease:"outExpo",plate:"scrim",radiusLu:0,padLu:2.2,uppercase:!0,tracking:.08}},{id:"editorial",label:"Editorial",note:"Serif on a hairline outline. Nothing shouts.",look:{family:"instrument",accent:"#e8e2d4",primary:"#f7f4ec",secondary:"#b3ab99",style:"fade",stagger:.12,ease:"outSine",plate:"outline",radiusLu:.2,padLu:2.8,uppercase:!1,tracking:.01}},{id:"social",label:"Social",note:"Fat pill, bright fill, springs in. Built for a small screen.",look:{family:"inter",accent:"#7c3aed",primary:"#ffffff",secondary:"#ddd0ff",style:"pop",stagger:.06,ease:"outSpring",plate:"solid",radiusLu:3.2,padLu:2.8,uppercase:!1,tracking:0}},{id:"documentary",label:"Documentary",note:"A rule and nothing else. The type carries it.",look:{family:"inter",accent:"#f5c451",primary:"#ffffff",secondary:"#b8b2a4",style:"rise",stagger:.14,ease:"outQuart",plate:"rule",radiusLu:0,padLu:1.6,uppercase:!1,tracking:.015}},{id:"terminal",label:"Terminal",note:"Mono caps in a boxed outline. Technical, deliberate.",look:{family:"jetmono",accent:"#31e07f",primary:"#d8ffe9",secondary:"#5f8f76",style:"wipeUp",stagger:.04,ease:"outCirc",plate:"outline",radiusLu:0,padLu:2,uppercase:!0,tracking:.06}},{id:"minimal",label:"Minimal",note:"No plate at all. Drifts on, drifts off.",look:{family:"inter",accent:"#ffffff",primary:"#ffffff",secondary:"#9aa2ad",style:"drift",stagger:.1,ease:"outSine",plate:"none",radiusLu:0,padLu:0,uppercase:!1,tracking:.02}},{id:"noir",label:"Noir",note:"Condensed caps, deep scrim, slow. For titles over picture.",look:{family:"condensed",accent:"#c8a24a",primary:"#f4efe3",secondary:"#9b917c",style:"expand",stagger:.2,ease:"inOutCubic",plate:"scrim",radiusLu:.4,padLu:3,uppercase:!0,tracking:.12}}],Q=Object.fromEntries(j.map(e=>[e.id,e]));function Z(e,o,t,a={}){let s=new Set(a.skip??[]),r=new Set(e?.takes??S),l={...o};for(let i of S)s.has(i)||!r.has(i)||t[i]!==void 0&&(l[i]=t[i]);let n=e?.look??{};for(let i of C)if(!(s.has(i)||t[i]===void 0))for(let c of n[i]??[])l[c]=t[i];return l}function ee(e,o={}){let t={kind:"gfx.look",version:1,...o};for(let a of _)e[a]!==void 0&&(t[a]=e[a]);return t}function te(e){let o=typeof e=="string"?JSON.parse(e):e;if(!o||typeof o!="object")throw new Error("not a look");if(o.kind!==void 0&&o.kind!=="gfx.look")throw new Error(`not a look (kind: ${JSON.stringify(o.kind)})`);let t={};for(let a of _)o[a]!==void 0&&(t[a]=o[a]);if(!Object.keys(t).length)throw new Error("that look file carries no recognised fields");return{look:t,label:typeof o.label=="string"?o.label:void 0}}var R=e=>e.includes("left")?"left":e.includes("right")?"right":"center",u=(e,o,t)=>[{t:0,v:0},{t:o,v:1,ease:"outCubic"},{t:e-t,v:1},{t:e,v:0,ease:"linear"}],k=(e,o,t,a,s,r="outBack",l="outCubic")=>[{t:0,v:a},{t:o,v:0,ease:r},{t:e-t,v:0},{t:e,v:s,ease:l}],w={slide:({duration:e,anchor:o,inT:t,outT:a,dist:s})=>{let r=R(o);if(r==="center")return{opacity:u(e,t,a),riseLu:k(e,t,a,s*.7,s*.4)};let l=r==="right"?1:-1;return{opacity:u(e,t,a),slideLu:k(e,t,a,l*s,l*s*.6)}},fade:({duration:e,inT:o,outT:t})=>({opacity:u(e,o,t)}),rise:({duration:e,inT:o,outT:t,dist:a})=>({opacity:u(e,o,t),riseLu:k(e,o,t,a*.7,a*.4)}),pop:({duration:e,inT:o,outT:t})=>({opacity:u(e,o,t),scale:[{t:0,v:.72},{t:o,v:1,ease:"outBack"},{t:e-t,v:1},{t:e,v:.88,ease:"outCubic"}]}),wipe:({duration:e,inT:o,outT:t})=>({opacity:[{t:0,v:1},{t:e-t,v:1},{t:e,v:1}],reveal:[{t:0,v:0},{t:o,v:1,ease:"outCubic"},{t:e-t,v:1},{t:e,v:0,ease:"inOutCubic"}],revealAxis:"x"}),wipeUp:({duration:e,inT:o,outT:t})=>({opacity:[{t:0,v:1},{t:e-t,v:1},{t:e,v:1}],reveal:[{t:0,v:0},{t:o,v:1,ease:"outCubic"},{t:e-t,v:1},{t:e,v:0,ease:"inOutCubic"}],revealAxis:"y"}),expand:({duration:e,inT:o,outT:t})=>({opacity:u(e,o*.6,t*.6),reveal:[{t:0,v:.12},{t:o,v:1,ease:"outCubic"},{t:e-t,v:1},{t:e,v:.12,ease:"outCubic"}],revealAxis:"x"}),none:()=>({}),drift:({duration:e,anchor:o,inT:t,outT:a,dist:s})=>{let r=R(o),n=r==="center"?0:(r==="right"?1:-1)*s*.5;return{opacity:u(e,t,a),[r==="center"?"riseLu":"slideLu"]:k(e,t,a,n||s*.5,(n||s*.5)*1.6,"outCubic","linear")}}},ae=(()=>{let e=new Set,o=t=>{if(Array.isArray(t)){for(let a of t)o(a);return}if(t&&typeof t=="object"){typeof t.ease=="string"&&e.add(t.ease);for(let a of Object.values(t))o(a)}};for(let t of Object.values(w))for(let a of["bottom-left","bottom","bottom-right"])o(t({duration:6,anchor:a,inT:.5,outT:.5,dist:4}));return[...e]})(),re=[{id:"slide",label:"Slide"},{id:"fade",label:"Fade"},{id:"rise",label:"Rise"},{id:"pop",label:"Pop"},{id:"drift",label:"Drift"},{id:"wipe",label:"Wipe"},{id:"wipeUp",label:"Wipe up"},{id:"expand",label:"Expand"},{id:"none",label:"None (hold)"}],U=[{id:"none",label:"Together",seconds:0},{id:"subtle",label:"Subtle",seconds:.06},{id:"clear",label:"Clear",seconds:.12},{id:"slow",label:"Slow",seconds:.2}],ie=Object.fromEntries(U.map(e=>[e.id,e]));function L(e,{duration:o,anchor:t="bottom-left",inT:a=.55,outT:s=.5,dist:r=3.5,ease:l}={}){let n=(w[e]||w.slide)({duration:o,anchor:t,inT:a,outT:s,dist:r});if(!l)return n;let i={};for(let[c,f]of Object.entries(n)){if(!Array.isArray(f)){i[c]=f;continue}i[c]=f.map((d,p)=>p===1&&d.ease?{...d,ease:l}:d)}return i}var b={solid:(e,{radiusLu:o,padLu:t})=>({color:e,padLu:t,radiusLu:o}),gradient:(e,{radiusLu:o,padLu:t})=>({color:e,colorB:`${e}00`,padLu:t,radiusLu:o}),tick:(e,{radiusLu:o,padLu:t})=>({color:e,colorB:`${e}00`,accent:e,padLu:t,radiusLu:o}),outline:(e,{radiusLu:o,padLu:t})=>({stroke:e,strokeLu:.28,padLu:t,radiusLu:o}),scrim:(e,{radiusLu:o,padLu:t})=>({color:"#000000a6",accent:e,accentLu:.55,padLu:t,radiusLu:o}),rule:(e,{padLu:o})=>({accent:e,accentLu:.9,padLu:o,radiusLu:0}),none:()=>{}},le=Object.keys(b).map(e=>({id:e,label:e[0].toUpperCase()+e.slice(1)})),E=(e,o)=>o?String(e).toUpperCase():e;function M({name:e="Ava Reyes",title:o="Director of Photography",duration:t=6,anchor:a="bottom-left",color:s="#0a84ff",nameColor:r="#ffffff",titleColor:l="#cfe0ff",nameLu:n=5.4,titleLu:i=3.2,family:c="system",center:f=!1,style:d="slide",stagger:p=0,plate:m="tick",radiusLu:x=1.2,padLu:g=2.4,uppercase:h=!1,tracking:y=0,ease:B}={}){let v={type:"group",anchor:a,inset:{x:4,y:5},gapLu:1.1,maxWidthLu:62,stagger:p,plate:(b[m]??b.tick)(s,{radiusLu:x,padLu:g}),anim:L(d,{duration:t,anchor:a,ease:B}),children:[{text:E(e,h),sizeLu:n,weight:700,color:r,family:c,lineHeight:1.1,tracking:y},{text:o,sizeLu:i,weight:500,color:l,family:c,lineHeight:1.15,tracking:y}]};if(f){let D=a.startsWith("top")?"top":a.startsWith("bottom")?"bottom":"center",A=(O,I,N)=>({anchor:D,inset:{y:I},maxWidthLu:N,plate:{accent:null},children:[{sizeLu:n+O,align:"center"},{sizeLu:i+O*.5,align:"center"}]});v.variants={square:A(.6,8,76),portrait:A(1,11,80)}}return{duration:t,elements:[v]}}function W({text:e="*Terms and conditions apply. Offer ends 12/31/26. Financing from 3.9% APR for qualified buyers. See dealer for details. \xA92026 Acme Corp.",duration:o=6,anchor:t="bottom",align:a="left",color:s="#ffffff",sizeLu:r=2,minLu:l=1.6,sizeHpct:n=null,family:i="system",scrim:c=!1,style:f="fade"}={}){return{duration:o,elements:[{type:"group",anchor:t,inset:{x:5,y:5},gapLu:.4,plate:c?{color:"#00000073",padLu:1.6,radiusLu:.5}:void 0,anim:L(f,{duration:o,anchor:t,inT:.35,outT:.35,dist:1.2}),children:[{text:e,sizeLu:r,minLu:l,sizeHpct:n,weight:500,color:s,family:i,lineHeight:1.28,align:a}]}]}}function Y({location:e="PARIS, FRANCE",sub:o="EXT. \u2014 DAY",duration:t=5,anchor:a="top-left",color:s="#000000cc",locColor:r="#ffffff",subColor:l="#a8b3bf",locLu:n=3.6,subLu:i=2.4,family:c="mono",style:f="slide",stagger:d=0,plate:p="solid",radiusLu:m=.8,padLu:x=1.8,uppercase:g=!1,tracking:h=.04,ease:y}={}){return{duration:t,elements:[{type:"group",anchor:a,inset:{x:3,y:3},gapLu:.6,maxWidthLu:50,stagger:d,plate:(b[p]??b.solid)(s,{radiusLu:m,padLu:x}),anim:L(f,{duration:t,anchor:a,inT:.4,outT:.4,dist:2.2,ease:y}),children:[{text:E(e,g),sizeLu:n,weight:700,color:r,family:c,tracking:h},...o?[{text:E(o,g),sizeLu:i,weight:400,color:l,family:c,tracking:h}]:[]]}]}}var z=`# Directed By
|
|
4
|
+
Director | Ava Reyes
|
|
5
|
+
# Cast
|
|
6
|
+
Lead | Jordan Blake
|
|
7
|
+
Support | Sam Okafor
|
|
8
|
+
# Post Production
|
|
9
|
+
Editor | Dana Liu
|
|
10
|
+
Colorist | Priya Nair
|
|
11
|
+
VFX | Marco Vitale
|
|
12
|
+
# Music
|
|
13
|
+
Composer | Th\xE9o Marchand`;function H(e,o={}){let t=/[\t|]/,a=String(e??"").split(`
|
|
14
|
+
`),s=o.capsHeads??a.some(l=>t.test(l)&&!l.trim().startsWith("#")),r=[];for(let l of a){let n=l.trim();if(!n){if(!r.length)continue;let i=r[r.length-1];i.gap!=null?i.gap+=.5:r.push({gap:.5});continue}if(n.startsWith("#")){r.push({head:n.slice(1).trim()});continue}if(n.startsWith(">")){r.push({para:n.slice(1).trim()});continue}if(n.startsWith("@image")){let i=n.slice(6).trim(),c=i.match(/^(.*?)(?:\s+(\d+(?:\.\d+)?))?$/),f=(c?.[1]??i).trim(),d=c?.[2]?Number(c[2]):void 0,p=f.split("|").map(m=>m.trim()).filter(Boolean);p.length===1?r.push({image:{src:p[0],heightLu:d}}):p.length>1&&r.push({images:{srcs:p,heightLu:d}});continue}if(t.test(n)){let i=n.split(t).map(c=>c.trim());r.push({role:i[0]||"",name:i.slice(1).filter(Boolean).join(" ")});continue}if(s&&n===n.toUpperCase()&&/[A-Z]/.test(n)){r.push({head:n});continue}r.push({text:n})}for(;r.length&&r[r.length-1].gap!=null;)r.pop();return r}function K({credits:e=z,duration:o=12,lineLu:t=5.2,colGapLu:a=3,gutterFrac:s=.5,paraWidthFrac:r=.8,paraLineHeight:l=1.35,headColor:n="#ffffff",nameColor:i="#ffffff",roleColor:c="#b9c2cc",family:f="system"}={}){let d=Array.isArray(e)?e:H(e);return{duration:o,elements:[{type:"crawl",rows:d,lineLu:t,colGapLu:a,gutterFrac:s,paraWidthFrac:r,paraLineHeight:l,headColor:n,nameColor:i,roleColor:c,family:f}]}}var G=[{id:"lowerThird",label:"Lower Third",base:"lower_third",make:M,fan:"positions",defaultPositions:["bottom-left","bottom","bottom-right"],look:{accent:["color"],primary:["nameColor"],secondary:["titleColor"]},takes:["family","style","stagger","plate","radiusLu","padLu","uppercase","tracking","ease"]},{id:"locator",label:"Locator",base:"locator",make:Y,fan:"positions",defaultPositions:["top-left","top-right"],look:{accent:["color"],primary:["locColor"],secondary:["subColor"]},takes:["family","style","stagger","plate","radiusLu","padLu","uppercase","tracking","ease"]},{id:"legalLine",label:"Legal Line",base:"legal",make:W,fan:"positions",defaultPositions:["bottom"],look:{primary:["color"]},takes:["family","style"]},{id:"endCrawl",label:"End Crawl",base:"end_crawl",make:K,fan:"none",defaultPositions:[],look:{primary:["headColor","nameColor"],secondary:["roleColor"]},takes:["family"]}],$=Object.fromEntries(G.map(e=>[e.id,e])),q=[{id:"top-left",label:"Left",slug:"top_left",band:"top"},{id:"top",label:"Center",slug:"top_center",band:"top"},{id:"top-right",label:"Right",slug:"top_right",band:"top"},{id:"left",label:"Left",slug:"middle_left",band:"middle"},{id:"center",label:"Center",slug:"middle_center",band:"middle"},{id:"right",label:"Right",slug:"middle_right",band:"middle"},{id:"bottom-left",label:"Left",slug:"bottom_left",band:"bottom"},{id:"bottom",label:"Center",slug:"bottom_center",band:"bottom"},{id:"bottom-right",label:"Right",slug:"bottom_right",band:"bottom"}],T=Object.fromEntries(q.map(e=>[e.id,e]));function ce(e,o={},t){let a=$[e];if(!a)throw new Error(`unknown graphic type: ${e}`);if(a.fan!=="positions")return[{key:"main",scene:a.make(o)}];let s=(t??a.defaultPositions).filter(r=>T[r]);return s.length?s.map(r=>({position:T[r],scene:a.make({...o,anchor:r})})):[{key:"main",scene:a.make(o)}]}var J=[{id:"16x9",label:"16 : 9 \xB7 Landscape master",w:1920,h:1080,group:"landscape"},{id:"9x16",label:"9 : 16 \xB7 Reels / Stories / Shorts",w:1080,h:1920,group:"portrait",chrome:{right:.14,bottom:.18}},{id:"1x1",label:"1 : 1 \xB7 Square feed",w:1080,h:1080,group:"square"},{id:"4x5",label:"4 : 5 \xB7 Portrait feed",w:1080,h:1350,group:"portrait"},{id:"2x3",label:"2 : 3 \xB7 Portrait / Pinterest",w:1080,h:1620,group:"portrait"},{id:"4x3",label:"4 : 3 \xB7 Broadcast / legacy",w:1440,h:1080,group:"landscape"},{id:"239x1",label:"2.39 : 1 \xB7 Scope / cinema",w:2048,h:858,group:"landscape"}],V=Object.fromEntries(J.map(e=>[e.id,e])),de=V["16x9"],X=[{id:"hd",label:"HD (1080)",factor:1},{id:"uhd",label:"UHD (2160)",factor:2}],pe=Object.fromEntries(X.map(e=>[e.id,e])),P=e=>2*Math.round(e/2);function ue(e,o){return o===1?e:{...e,w:P(e.w*o),h:P(e.h*o)}}export{F as a,j as b,Q as c,Z as d,ee as e,te as f,re as g,le as h,G as i,$ as j,q as k,T as l,ce as m,J as n,V as o,X as p,pe as q,ue as r};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
import{a as L}from"./chunk-IK6RKNS5.js";import{$ as P,A as R,B as W,C as I,m as _,r as C,x as N,z as O}from"./chunk-G3SZDPDS.js";import X from"node:http";import{connect as Y}from"node:net";import{createHash as M,randomBytes as U}from"node:crypto";import{Buffer as d}from"node:buffer";var j="258EAFA5-E914-47DA-95CA-C5AB0DC85B11";function A(a,e,c=!1){let n=e.length,r=c?128:0,s=n<126?d.from([128|a,r|n]):n<65536?d.from([128|a,r|126,n>>8,n&255]):(()=>{let o=d.alloc(10);return o[0]=128|a,o[1]=r|127,o.writeBigUInt64BE(BigInt(n),2),o})();if(!c)return d.concat([s,d.from(e)]);let t=U(4),i=d.from(e);for(let o=0;o<i.length;o++)i[o]^=t[o&3];return d.concat([s,t,i])}function D(a,e,c,n=!1){let r=d.alloc(0),s=[],t=0,i=!1,o=[],p=[],u=()=>{i||(i=!0,p.forEach(l=>l()))},f=(l=1e3,g="")=>{if(i)return;let h=d.from(g),m=d.alloc(2+h.length);m.writeUInt16BE(l,0),h.copy(m,2);try{a.write(A(8,m,n))}catch{}a.end(),u()};return a.on("data",l=>{for(r=d.concat([r,l]);r.length>=2;){let g=(r[0]&128)!==0,h=r[0]&15,m=(r[1]&128)!==0,v=r[1]&127,w=2;if(v===126){if(r.length<4)return;v=r.readUInt16BE(2),w=4}else if(v===127){if(r.length<10)return;let b=r.readBigUInt64BE(2);if(b>BigInt(c))return f(1009,"too big");v=Number(b),w=10}if(m===n)return f(1002,n?"server frames must not be masked":"client frames must be masked");if(v>c||t+v>c)return f(1009,"message too big");let T=m?4:0;if(r.length<w+T+v)return;let S=d.from(r.subarray(w+T,w+T+v));if(m){let b=r.subarray(w,w+4);for(let x=0;x<S.length;x++)S[x]^=b[x&3]}if(r=r.subarray(w+T+v),h===8)return f(1e3);if(h===9){a.write(A(10,S,n));continue}if(h!==10){if(h===1||h===0){if(s.push(S),t+=S.length,g){let b=d.concat(s).toString("utf8");s=[],t=0,o.forEach(x=>x(b))}continue}return f(1003,"text frames only")}}}),a.on("close",u),a.on("error",u),{origin:e,send:l=>{i||a.write(A(1,d.from(l,"utf8"),n))},close:f,onMessage:l=>{o.push(l)},onClose:l=>{p.push(l)}}}function J(a,e){let c=new Set,n=X.createServer((r,s)=>{let t=n.address();a.onHttp?.(r,s,typeof t=="object"&&t?t.port:a.port)||(s.writeHead(426,{"content-type":"text/plain"}),s.end("websocket only"))});return n.on("upgrade",(r,s)=>{let t=r.headers["sec-websocket-key"];if(r.url?.split("?")[0]!==a.path||typeof t!="string"||String(r.headers.upgrade).toLowerCase()!=="websocket"){s.end(`HTTP/1.1 400 Bad Request\r
|
|
4
|
+
\r
|
|
5
|
+
`);return}let i=M("sha1").update(t+j).digest("base64");s.write(`HTTP/1.1 101 Switching Protocols\r
|
|
6
|
+
Upgrade: websocket\r
|
|
7
|
+
Connection: Upgrade\r
|
|
8
|
+
Sec-WebSocket-Accept: ${i}\r
|
|
9
|
+
\r
|
|
10
|
+
`),c.add(s),s.on("close",()=>c.delete(s));let o=typeof r.headers.origin=="string"?r.headers.origin:null;e(D(s,o,a.maxBytes))}),new Promise((r,s)=>{n.once("error",s),n.listen(a.port,a.hostname,()=>{let t=n.address();r({port:typeof t=="object"&&t?t.port:a.port,close:()=>new Promise(i=>{for(let o of c)o.destroy();n.close(()=>i())})})})})}function le(a,e){let c=new URL(a);if(c.protocol!=="ws:")return Promise.reject(new Error(`only ws:// URLs: ${a}`));let n=U(16).toString("base64"),r=M("sha1").update(n+j).digest("base64");return new Promise((s,t)=>{let i=Y({host:c.hostname,port:Number(c.port||80)}),o=f=>{i.destroy(),t(f)};i.setTimeout(e.timeoutMs,()=>o(new Error(`no answer from ${c.host} within ${e.timeoutMs} ms`))),i.once("error",o),i.once("connect",()=>i.write(`GET ${c.pathname}${c.search} HTTP/1.1\r
|
|
11
|
+
Host: ${c.host}\r
|
|
12
|
+
Upgrade: websocket\r
|
|
13
|
+
Connection: Upgrade\r
|
|
14
|
+
Sec-WebSocket-Key: ${n}\r
|
|
15
|
+
Sec-WebSocket-Version: 13\r
|
|
16
|
+
\r
|
|
17
|
+
`));let p=d.alloc(0),u=f=>{p=d.concat([p,f]);let l=p.indexOf(`\r
|
|
18
|
+
\r
|
|
19
|
+
`);if(l<0)return;i.off("data",u);let g=p.subarray(0,l).toString("latin1").split(`\r
|
|
20
|
+
`),h=g.find(w=>/^sec-websocket-accept:/i.test(w))?.split(":")[1]?.trim();if(!/^HTTP\/1\.1 101/.test(g[0])||h!==r)return o(new Error(`${c.host} refused the WebSocket upgrade: ${g[0]}`));i.setTimeout(0),i.off("error",o);let m=p.subarray(l+4),v=D(i,null,e.maxBytes,!0);m.length&&i.emit("data",m),s(v)};i.on("data",u)})}import{existsSync as K,readFileSync as Q}from"node:fs";var k=1,Z=[48127,48128,48129,48130,48131,48132,48133,48134],q=5e3,F=4,ee=8*1024*1024,y=class extends Error{constructor(c,n){super(n);this.code=c}},$=()=>P(_(),"host-bridge","pairing.json"),B="/avid-panel/",te="/avid-panel/pairing",G="avid",z={"index.html":"text/html; charset=utf-8","panel.js":"text/javascript; charset=utf-8","panel.css":"text/css; charset=utf-8","icon.svg":"image/svg+xml"},ne="default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' ws://localhost:{port} ws://127.0.0.1:{port} http://localhost:* http://127.0.0.1:* https://localhost:* https://127.0.0.1:*; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",V=a=>[`http://localhost:${a}`,`http://127.0.0.1:${a}`];function re(){for(let a of["./avid/panel/web-dist/","./avid-panel/"]){let e=C(new URL(a,import.meta.url));if(K(P(e,"index.html")))return e}return null}function oe(){let a=new Uint8Array(32);return crypto.getRandomValues(a),Array.from(a,e=>e.toString(16).padStart(2,"0")).join("")}var H=class{constructor(){this.token=oe();this.port=0;this.live=new Map;this.waiters=[];this.seq=0;this.events=[]}async start(e=Z){let c;for(let n of e)try{this.server=await J({hostname:"127.0.0.1",port:n,path:"/host-bridge",maxBytes:ee,onHttp:(r,s,t)=>this.servePanel(r,s,t)},r=>this.accept(r)),this.port=this.server.port;break}catch(r){c=r}if(!this.server)throw new y("no_port",`every host-bridge port (${e.join(", ")}) is taken: ${c}`);await R(P(_(),"host-bridge")),await O($(),JSON.stringify({protocol:k,url:`ws://127.0.0.1:${this.port}/host-bridge`,port:this.port,token:this.token})),await I($(),384)}async stop(){for(let e of this.live.values())e.conn.close(1001,"engine stopping");this.live.clear(),await this.server?.close();try{JSON.parse(await N($())).token===this.token&&await W($())}catch{}}peers(){return[...this.live.values()].map(e=>e.peer)}peer(e){return this.live.get(e)?.peer}async waitFor(e,c){return this.live.has(e)?this.peer(e):(await Promise.race([new Promise(n=>this.waiters.push({host:e,resolve:n})),new Promise(n=>setTimeout(n,c))]),this.peer(e))}request(e,c,n={},r=3e4){let s=this.live.get(e);if(!s)return Promise.reject(new y("not_connected",`${e}: its panel is not connected`));let t=`r${++this.seq}`;return new Promise((i,o)=>{let p=setTimeout(()=>{s.pending.delete(t),o(new y("timeout",`${e}: no answer to ${c} within ${Math.round(r/1e3)} s`))},r);s.pending.set(t,{resolve:i,reject:o,timer:p}),s.conn.send(JSON.stringify({type:"request",id:t,method:c,params:n}))})}servePanel(e,c,n){let r=(e.url??"").split("?")[0];if(!r.startsWith(B)&&r!==B.slice(0,-1))return!1;let s=(f,l,g,h=!1)=>{let m=typeof g=="string"?new TextEncoder().encode(g):g;return c.writeHead(f,{"content-type":l,"content-length":String(m.length),"cache-control":"no-store","x-content-type-options":"nosniff","referrer-policy":"no-referrer","cross-origin-resource-policy":"same-origin","x-frame-options":"DENY","content-security-policy":ne.replaceAll("{port}",String(n))}),c.end(h?void 0:m),!0},t=(f,l)=>s(f,"text/plain; charset=utf-8",l),i=f=>{let l=e.headers[f];return typeof l=="string"?l:void 0},o=(i("host")??"").toLowerCase();if(o!==`localhost:${n}`&&o!==`127.0.0.1:${n}`)return t(421,"misdirected request");if(r===te)return e.method==="POST"&&V(n).includes(i("origin")??"")&&(i("sec-fetch-site")??"same-origin")==="same-origin"&&i("x-ct-panel")==="1"&&(i("content-length")??"0").trim()==="0"?s(200,"application/json",JSON.stringify({protocol:k,url:`ws://localhost:${n}/host-bridge`,port:n,token:this.token})):t(403,"forbidden");if(e.method!=="GET"&&e.method!=="HEAD")return t(405,"method not allowed");let p=r.slice(B.length)||"index.html",u=re();return!z[p]||!u?t(404,"not found"):s(200,z[p],Q(P(u,p)),e.method==="HEAD")}accept(e){let c=!!e.origin&&V(this.port).includes(e.origin);if(e.origin&&/^https?:/i.test(e.origin)&&!c){e.send(JSON.stringify({type:"error",code:"origin_refused",message:"web pages may not use the host bridge"})),e.close(1008,"origin");return}let n=null,r=setTimeout(()=>{n||(e.send(JSON.stringify({type:"error",code:"hello_timeout",message:"no hello"})),e.close(1008,"hello"))},q);e.onMessage(s=>{let t;try{t=JSON.parse(s)}catch{return}if(!n){let o=(l,g)=>{clearTimeout(r),e.send(JSON.stringify({type:"error",code:l,message:g})),e.close(1008,l)};if(t.type!=="hello")return o("hello_expected","the first frame must be hello");if(t.protocol!==k)return o("protocol_mismatch",`this engine speaks protocol ${k}`);if(t.token!==this.token)return o("bad_token","the pairing token does not match: re-read the pairing file");let p=t.host??{},u=String(p.id??"");if(!/^[a-z][a-z0-9_-]{1,31}$/.test(u))return o("bad_host","host.id is missing or malformed");if(c&&u!==G)return o("origin_mismatch",`a connection from the panel page may only be host ${G}`);if(!this.live.has(u)&&this.live.size>=F)return o("too_many_peers",`at most ${F} panels`);clearTimeout(r),this.live.get(u)?.conn.close(1e3,"replaced by a newer connection"),n=u;let f={id:u,name:String(p.name??u),version:String(p.version??""),platform:String(p.platform??""),capabilities:Array.isArray(t.capabilities)?t.capabilities.map(String):[],optional_verbs:Array.isArray(t.optional_verbs)?t.optional_verbs.map(String):[]};this.live.set(u,{peer:f,conn:e,pending:new Map}),e.send(JSON.stringify({type:"welcome",protocol:k,app:{name:"conformtools",version:L}})),this.waiters=this.waiters.filter(l=>l.host===u?(l.resolve(),!1):!0);return}let i=this.live.get(n);if(!(!i||i.conn!==e))if(t.type==="response"){let o=i.pending.get(String(t.id));if(!o)return;if(i.pending.delete(String(t.id)),clearTimeout(o.timer),t.ok)o.resolve(t.result??null);else{let p=t.error??{};o.reject(new y(p.code??"peer_error",`${n}: ${p.message??p.code??"error"}`))}}else t.type==="event"&&(this.events.push({host:n,name:String(t.name),data:t.data}),this.events.length>200&&this.events.shift())}),e.onClose(()=>{if(clearTimeout(r),!n)return;let s=this.live.get(n);if(s?.conn===e){for(let t of s.pending.values())clearTimeout(t.timer),t.reject(new y("disconnected",`${n}: the panel disconnected`));this.live.delete(n)}})}},E=null;function me(){return E??=(async()=>{let a=new H;return await a.start(),a})(),E.catch(()=>{E=null}),E}function he(){E=null}export{le as a,k as b,Z as c,y as d,$ as e,B as f,V as g,H as h,me as i,he as j};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
var p={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},A={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},x={Pending:0,Fulfilled:1,Rejected:2},y={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},_={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2};var te=Object.defineProperty,re=(e,t)=>{for(var r in t)te(e,r,{get:t[r],enumerable:!0})},J=!1;function b(...e){J&&console.log("quickjs-emscripten:",...e)}var ie={};re(ie,{QuickJSAsyncifyError:()=>D,QuickJSAsyncifySuspended:()=>$,QuickJSEmptyGetOwnPropertyNames:()=>Y,QuickJSEmscriptenModuleError:()=>ne,QuickJSHostRefInvalid:()=>d,QuickJSHostRefRangeExceeded:()=>q,QuickJSMemoryLeakDetected:()=>se,QuickJSNotImplemented:()=>U,QuickJSPromisePending:()=>K,QuickJSUnknownIntrinsic:()=>z,QuickJSUnwrapError:()=>M,QuickJSUseAfterFree:()=>R,QuickJSWrongOwner:()=>G});var M=class extends Error{constructor(e,t){let r=typeof e=="object"&&e&&"message"in e?String(e.message):String(e);super(r),this.cause=e,this.context=t,this.name="QuickJSUnwrapError"}},G=class extends Error{constructor(){super(...arguments),this.name="QuickJSWrongOwner"}},R=class extends Error{constructor(){super(...arguments),this.name="QuickJSUseAfterFree"}},U=class extends Error{constructor(){super(...arguments),this.name="QuickJSNotImplemented"}},D=class extends Error{constructor(){super(...arguments),this.name="QuickJSAsyncifyError"}},$=class extends Error{constructor(){super(...arguments),this.name="QuickJSAsyncifySuspended"}},se=class extends Error{constructor(){super(...arguments),this.name="QuickJSMemoryLeakDetected"}},ne=class extends Error{constructor(){super(...arguments),this.name="QuickJSEmscriptenModuleError"}},z=class extends TypeError{constructor(){super(...arguments),this.name="QuickJSUnknownIntrinsic"}},K=class extends Error{constructor(){super(...arguments),this.name="QuickJSPromisePending"}},Y=class extends Error{constructor(){super(...arguments),this.name="QuickJSEmptyGetOwnPropertyNames"}},q=class extends Error{constructor(){super(...arguments),this.name="QuickJSHostRefRangeExceeded"}},d=class extends Error{constructor(){super(...arguments),this.name="QuickJSHostRefInvalid"}};function*W(e){return yield e}function oe(e){return W(I(e))}var C=W;C.of=oe;function N(e,t){return(...r)=>{let i=t.call(e,C,...r);return I(i)}}function ue(e,t){let r=t.call(e,C);return I(r)}function I(e){function t(r){return r.done?r.value:r.value instanceof Promise?r.value.then(i=>t(e.next(i)),i=>t(e.throw(i))):t(e.next(r.value))}return t(e.next())}var m=class{[Symbol.dispose](){return this.dispose()}},k=Symbol.dispose??Symbol.for("Symbol.dispose"),O=m.prototype;O[k]||(O[k]=function(){return this.dispose()});var h=class Z extends m{constructor(t,r,i,s){super(),this._value=t,this.copier=r,this.disposer=i,this._owner=s,this._alive=!0,this._constructorStack=J?new Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw new Error("Non-dupable lifetime");return new Z(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(t){this.assertAlive();let r=t(this);return this.dispose(),r}map(t){return this.assertAlive(),t(this)}tap(t){return t(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new R(`Lifetime not alive
|
|
4
|
+
${this._constructorStack}
|
|
5
|
+
Lifetime used`):new R("Lifetime not alive")}},v=class extends h{constructor(e,t){super(e,void 0,void 0,t)}get dupable(){return!0}dup(){return this}dispose(){}},V=class extends h{constructor(e,t,r,i){super(e,t,r,i)}dispose(){this._alive=!1}};function Q(e,t){let r;try{e.dispose()}catch(i){r=i}if(t&&r)throw Object.assign(t,{message:`${t.message}
|
|
6
|
+
Then, failed to dispose scope: ${r.message}`,disposeError:r}),t;if(t||r)throw t||r}var c=class P extends m{constructor(){super(...arguments),this._disposables=new h(new Set),this.manage=t=>(this._disposables.value.add(t),t)}static withScope(t){let r=new P,i;try{return t(r)}catch(s){throw i=s,s}finally{Q(r,i)}}static withScopeMaybeAsync(t,r){return ue(void 0,function*(i){let s=new P,n;try{return yield*i.of(r.call(t,i,s))}catch(u){throw n=u,u}finally{Q(s,n)}})}static async withScopeAsync(t){let r=new P,i;try{return await t(r)}catch(s){throw i=s,s}finally{Q(r,i)}}get alive(){return this._disposables.alive}dispose(){let t=Array.from(this._disposables.value.values()).reverse();for(let r of t)r.alive&&r.dispose();this._disposables.dispose()}};function ae(e){let t=e?Array.from(e):[];function r(){return t.forEach(s=>s.alive?s.dispose():void 0)}function i(){return t.some(s=>s.alive)}return Object.defineProperty(t,k,{configurable:!0,enumerable:!1,value:r}),Object.defineProperty(t,"dispose",{configurable:!0,enumerable:!1,value:r}),Object.defineProperty(t,"alive",{configurable:!0,enumerable:!1,get:i}),t}function T(e){return!!(e&&(typeof e=="object"||typeof e=="function")&&"alive"in e&&typeof e.alive=="boolean"&&"dispose"in e&&typeof e.dispose=="function")}var L=class X extends m{static success(t){return new le(t)}static fail(t,r){return new he(t,r)}static is(t){return t instanceof X}},le=class extends L{constructor(e){super(),this.value=e}get alive(){return T(this.value)?this.value.alive:!0}dispose(){T(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(e){return this.value}},he=class extends L{constructor(e,t){super(),this.error=e,this.onUnwrap=t}get alive(){return T(this.error)?this.error.alive:!0}dispose(){T(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(e){return e}},w=L,ce=class extends m{constructor(e){super(),this.resolve=t=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,t||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.reject=t=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,t||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()},this.context=e.context,this.owner=e.context.runtime,this.handle=e.promiseHandle,this.settled=new Promise(t=>{this.onSettled=t}),this.resolveHandle=e.resolveHandle,this.rejectHandle=e.rejectHandle}get alive(){return this.handle.alive||this.resolveHandle.alive||this.rejectHandle.alive}disposeResolvers(){this.resolveHandle.alive&&this.resolveHandle.dispose(),this.rejectHandle.alive&&this.rejectHandle.dispose()}},ee=class{constructor(e){this.module=e}toPointerArray(e){let t=new Int32Array(e.map(s=>s.value)),r=t.length*t.BYTES_PER_ELEMENT,i=this.module._malloc(r);return new Uint8Array(this.module.HEAPU8.buffer,i,r).set(new Uint8Array(t.buffer)),new h(i,void 0,s=>this.module._free(s))}newTypedArray(e,t){let r=new e(new Array(t).fill(0)),i=r.length*r.BYTES_PER_ELEMENT,s=this.module._malloc(i),n=new e(this.module.HEAPU8.buffer,s,t);return n.set(r),new h({typedArray:n,ptr:s},void 0,u=>this.module._free(u.ptr))}newMutablePointerArray(e){return this.newTypedArray(Int32Array,e)}newHeapCharPointer(e){let t=this.module.lengthBytesUTF8(e),r=t+1,i=this.module._malloc(r);return this.module.stringToUTF8(e,i,r),new h({ptr:i,strlen:t},void 0,s=>this.module._free(s.ptr))}newHeapBufferPointer(e){let t=e.byteLength,r=this.module._malloc(t);return this.module.HEAPU8.set(e,r),new h({pointer:r,numBytes:t},void 0,i=>this.module._free(i.pointer))}consumeHeapCharPointer(e){let t=this.module.UTF8ToString(e);return this.module._free(e),t}},Qe=Symbol("Unstable"),He=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});function me(e){if(!e)return 0;let t=0;for(let[r,i]of Object.entries(e)){if(!(r in A))throw new z(r);i&&(t|=A[r])}return t}function de(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{type:t,strict:r,strip:i,compileOnly:s,backtraceBarrier:n}=e,u=0;return t==="global"&&(u|=p.JS_EVAL_TYPE_GLOBAL),t==="module"&&(u|=p.JS_EVAL_TYPE_MODULE),r&&(u|=p.JS_EVAL_FLAG_STRICT),i&&(u|=p.JS_EVAL_FLAG_STRIP),s&&(u|=p.JS_EVAL_FLAG_COMPILE_ONLY),n&&(u|=p.JS_EVAL_FLAG_BACKTRACE_BARRIER),u}function fe(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{strings:t,symbols:r,quickjsPrivate:i,onlyEnumerable:s,numbers:n,numbersAsStrings:u}=e,o=0;return t&&(o|=y.JS_GPN_STRING_MASK),r&&(o|=y.JS_GPN_SYMBOL_MASK),i&&(o|=y.JS_GPN_PRIVATE_MASK),s&&(o|=y.JS_GPN_ENUM_ONLY),n&&(o|=y.QTS_GPN_NUMBER_MASK),u&&(o|=y.QTS_STANDARD_COMPLIANT_NUMBER),o}function pe(...e){let t=[];for(let r of e)r!==void 0&&(t=t.concat(r));return t}var ye=class extends m{constructor(e,t){super(),this.handle=e,this.context=t,this._isDone=!1,this.owner=t.runtime}[Symbol.iterator](){return this}next(e){if(!this.alive||this._isDone)return{done:!0,value:void 0};let t=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod(t,e)}return(e){if(!this.alive)return{done:!0,value:void 0};let t=this.context.getProp(this.handle,"return");if(t===this.context.undefined&&e===void 0)return this.dispose(),{done:!0,value:void 0};let r=this.callIteratorMethod(t,e);return t.dispose(),this.dispose(),r}throw(e){if(!this.alive)return{done:!0,value:void 0};let t=e instanceof h?e:this.context.newError(e),r=this.context.getProp(this.handle,"throw"),i=this.callIteratorMethod(r,e);return t.alive&&t.dispose(),r.dispose(),this.dispose(),i}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(e,t){let r=t?this.context.callFunction(e,this.handle,t):this.context.callFunction(e,this.handle);if(r.error)return this.dispose(),{value:r};let i=this.context.getProp(r.value,"done").consume(n=>this.context.dump(n)),s=this.context.getProp(r.value,"value");return r.value.dispose(),i&&this.dispose(),{value:w.success(s),done:i}}},F=-2147483648,B=2147483647,E=0;function H(e){return e>>8}var ve=class{constructor(){this.nextId=F,this.freelist=[],this.groups=new Map}put(e){let t=this.allocateId(),r=H(t),i=this.groups.get(r);return i||(i=new Map,this.groups.set(r,i)),i.set(t,e),t}get(e){if(e===E)throw new d("no host reference id defined");let t=H(e),r=this.groups.get(t);if(!r)throw new d(`host reference id ${e} is not defined`);let i=r.get(e);if(!i)throw new d(`host reference id ${e} is not defined`);return i}delete(e){if(e===E)throw new d("no host reference id defined");let t=H(e),r=this.groups.get(t);if(!r)throw new d(`host reference id ${e} is not defined`);r.delete(e),r.size===0&&this.groups.delete(t),this.freelist.push(e)}allocateId(){if(this.freelist.length>0)return this.freelist.shift();if(this.nextId===E&&this.nextId++,this.nextId>B)throw new q(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${B-F}`);return this.nextId++}},j=class extends m{constructor(e,t,r){if(r===E)throw new d("cannot create HostRef with undefined id");super(),this.runtime=e,this.handle=t,this.id=r}get alive(){return this.handle.alive}dispose(){this.handle.dispose()}get value(){return this.runtime.hostRefs.get(this.id)}},Se=class extends ee{constructor(e){super(e.module),this.scope=new c,this.copyJSValue=t=>this.ffi.QTS_DupValuePointer(this.ctx.value,t),this.freeJSValue=t=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,t)},e.ownedLifetimes?.forEach(t=>this.scope.manage(t)),this.owner=e.owner,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=this.scope.manage(e.ctx)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(e){return this.scope.manage(e)}consumeJSCharPointer(e){let t=this.module.UTF8ToString(e);return this.ffi.QTS_FreeCString(this.ctx.value,e),t}heapValueHandle(e,t){let r=t?i=>{t(),this.freeJSValue(i)}:this.freeJSValue;return new h(e,this.copyJSValue,r,this.owner)}staticHeapValueHandle(e){return this.manage(this.heapValueHandle(e)),new v(e,this.owner)}},we=class extends m{constructor(e){super(),this._undefined=void 0,this._null=void 0,this._false=void 0,this._true=void 0,this._global=void 0,this._BigInt=void 0,this._Symbol=void 0,this._SymbolIterator=void 0,this._SymbolAsyncIterator=void 0,this.cToHostCallbacks={callFunction:(t,r,i,s,n)=>{if(t!==this.ctx.value)throw new Error("QuickJSContext instance received C -> JS call with mismatched ctx");let u=this.getFunction(n);return c.withScopeMaybeAsync(this,function*(o,a){let f=a.manage(new V(r,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),S=new Array(i);for(let l=0;l<i;l++){let g=this.ffi.QTS_ArgvGetJSValueConstPointer(s,l);S[l]=a.manage(new V(g,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let l=yield*o(u.apply(f,S));if(l){if("error"in l&&l.error)throw this.runtime.debugLog("throw error",l.error),l.error;let g=a.manage(l instanceof h?l:l.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,g.value)}return 0}catch(l){return this.errorToHandle(l).consume(g=>this.ffi.QTS_Throw(this.ctx.value,g.value))}})}},this.runtime=e.runtime,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=e.ctx,this.memory=new Se({...e,owner:this.runtime}),e.callbacks.setContextCallbacks(this.ctx.value,this.cToHostCallbacks),this.dump=this.dump.bind(this),this.getString=this.getString.bind(this),this.getNumber=this.getNumber.bind(this),this.resolvePromise=this.resolvePromise.bind(this),this.uint32Out=this.memory.manage(this.memory.newTypedArray(Uint32Array,1))}get alive(){return this.memory.alive}dispose(){this.memory.dispose()}get undefined(){if(this._undefined)return this._undefined;let e=this.ffi.QTS_GetUndefined();return this._undefined=new v(e)}get null(){if(this._null)return this._null;let e=this.ffi.QTS_GetNull();return this._null=new v(e)}get true(){if(this._true)return this._true;let e=this.ffi.QTS_GetTrue();return this._true=new v(e)}get false(){if(this._false)return this._false;let e=this.ffi.QTS_GetFalse();return this._false=new v(e)}get global(){if(this._global)return this._global;let e=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(e),this._global}newNumber(e){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,e))}newString(e){let t=this.memory.newHeapCharPointer(e).consume(r=>this.ffi.QTS_NewString(this.ctx.value,r.value.ptr));return this.memory.heapValueHandle(t)}newUniqueSymbol(e){let t=(typeof e=="symbol"?e.description:e)??"",r=this.memory.newHeapCharPointer(t).consume(i=>this.ffi.QTS_NewSymbol(this.ctx.value,i.value.ptr,0));return this.memory.heapValueHandle(r)}newSymbolFor(e){let t=(typeof e=="symbol"?e.description:e)??"",r=this.memory.newHeapCharPointer(t).consume(i=>this.ffi.QTS_NewSymbol(this.ctx.value,i.value.ptr,1));return this.memory.heapValueHandle(r)}getWellKnownSymbol(e){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,e)}newBigInt(e){if(!this._BigInt){let i=this.getProp(this.global,"BigInt");this.memory.manage(i),this._BigInt=new v(i.value,this.runtime)}let t=this._BigInt,r=String(e);return this.newString(r).consume(i=>this.unwrapResult(this.callFunction(t,this.undefined,i)))}newObject(e){e&&this.runtime.assertOwned(e);let t=e?this.ffi.QTS_NewObjectProto(this.ctx.value,e.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle(t)}newArray(){let e=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(e)}newArrayBuffer(e){let t=new Uint8Array(e),r=this.memory.newHeapBufferPointer(t),i=this.ffi.QTS_NewArrayBuffer(this.ctx.value,r.value.pointer,t.length);return this.memory.heapValueHandle(i)}newPromise(e){let t=c.withScope(r=>{let i=r.manage(this.memory.newMutablePointerArray(2)),s=this.ffi.QTS_NewPromiseCapability(this.ctx.value,i.value.ptr),n=this.memory.heapValueHandle(s),[u,o]=Array.from(i.value.typedArray).map(a=>this.memory.heapValueHandle(a));return new ce({context:this,promiseHandle:n,resolveHandle:u,rejectHandle:o})});return e&&typeof e=="function"&&(e=new Promise(e)),e&&Promise.resolve(e).then(t.resolve,r=>r instanceof h?t.reject(r):this.newError(r).consume(t.reject)),t}newFunction(e,t){let r=typeof e=="function"?e:t;if(!r)throw new TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:r.length,isConstructor:!1,fn:r})}newConstructorFunction(e,t){let r=typeof e=="function"?e:t;if(!r)throw new TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:r.length,isConstructor:!0,fn:r})}newFunctionWithOptions(e){let{name:t,length:r,isConstructor:i,fn:s}=e,n=this.runtime.hostRefs.put(s);try{return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,t??"",r,i,n))}catch(u){throw this.runtime.hostRefs.delete(n),u}}newError(e){let t=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return e&&typeof e=="object"?(e.name!==void 0&&this.newString(e.name).consume(r=>this.setProp(t,"name",r)),e.message!==void 0&&this.newString(e.message).consume(r=>this.setProp(t,"message",r))):typeof e=="string"?this.newString(e).consume(r=>this.setProp(t,"message",r)):e!==void 0&&this.newString(String(e)).consume(r=>this.setProp(t,"message",r)),t}newHostRef(e){let t=this.runtime.hostRefs.put(e);try{let r=this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value,t));return new j(this.runtime,r,t)}catch(r){throw this.runtime.hostRefs.delete(t),r}}toHostRef(e){let t=this.ffi.QTS_GetHostRefId(e.value);if(t!==0)return this.runtime.hostRefs.get(t),new j(this.runtime,e.dup(),t)}unwrapHostRef(e){let t=this.ffi.QTS_GetHostRefId(e.value);if(t===0)throw new d("handle is not a HostRef");return this.runtime.hostRefs.get(t)}typeof(e){return this.runtime.assertOwned(e),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,e.value))}getNumber(e){return this.runtime.assertOwned(e),this.ffi.QTS_GetFloat64(this.ctx.value,e.value)}getString(e){return this.runtime.assertOwned(e),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,e.value))}getSymbol(e){this.runtime.assertOwned(e);let t=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,e.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,e.value)?Symbol.for(t):Symbol(t)}getBigInt(e){this.runtime.assertOwned(e);let t=this.getString(e);return BigInt(t)}getArrayBuffer(e){this.runtime.assertOwned(e);let t=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,e.value),r=this.ffi.QTS_GetArrayBuffer(this.ctx.value,e.value);if(!r)throw new Error("Couldn't allocate memory to get ArrayBuffer");return new h(this.module.HEAPU8.subarray(r,r+t),void 0,()=>this.module._free(r))}getPromiseState(e){this.runtime.assertOwned(e);let t=this.ffi.QTS_PromiseState(this.ctx.value,e.value);if(t<0)return{type:"fulfilled",value:e,notAPromise:!0};if(t===x.Pending)return{type:"pending",get error(){return new K("Cannot unwrap a pending promise")}};let r=this.ffi.QTS_PromiseResult(this.ctx.value,e.value),i=this.memory.heapValueHandle(r);if(t===x.Fulfilled)return{type:"fulfilled",value:i};if(t===x.Rejected)return{type:"rejected",error:i};throw i.dispose(),new Error(`Unknown JSPromiseStateEnum: ${t}`)}resolvePromise(e){this.runtime.assertOwned(e);let t=c.withScope(r=>{let i=r.manage(this.getProp(this.global,"Promise")),s=r.manage(this.getProp(i,"resolve"));return this.callFunction(s,i,e)});return t.error?Promise.resolve(t):new Promise(r=>{c.withScope(i=>{let s=i.manage(this.newFunction("resolve",a=>{r(this.success(a&&a.dup()))})),n=i.manage(this.newFunction("reject",a=>{r(this.fail(a&&a.dup()))})),u=i.manage(t.value),o=i.manage(this.getProp(u,"then"));this.callFunction(o,u,s,n).unwrap().dispose()})})}isEqual(e,t,r=_.IsStrictlyEqual){if(e===t)return!0;this.runtime.assertOwned(e),this.runtime.assertOwned(t);let i=this.ffi.QTS_IsEqual(this.ctx.value,e.value,t.value,r);if(i===-1)throw new U("WASM variant does not expose equality");return!!i}eq(e,t){return this.isEqual(e,t,_.IsStrictlyEqual)}sameValue(e,t){return this.isEqual(e,t,_.IsSameValue)}sameValueZero(e,t){return this.isEqual(e,t,_.IsSameValueZero)}getProp(e,t){this.runtime.assertOwned(e);let r;return typeof t=="number"&&t>=0?r=this.ffi.QTS_GetPropNumber(this.ctx.value,e.value,t):r=this.borrowPropertyKey(t).consume(i=>this.ffi.QTS_GetProp(this.ctx.value,e.value,i.value)),this.memory.heapValueHandle(r)}getLength(e){if(this.runtime.assertOwned(e),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,e.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(e,t={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(e),e.value;let r=fe(t);if(r===0)throw new Y("No options set, will return an empty array");return c.withScope(i=>{let s=i.manage(this.memory.newMutablePointerArray(1)),n=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,s.value.ptr,this.uint32Out.value.ptr,e.value,r);if(n)return this.fail(this.memory.heapValueHandle(n));let u=this.uint32Out.value.typedArray[0],o=s.value.typedArray[0],a=new Uint32Array(this.module.HEAP8.buffer,o,u),f=Array.from(a).map(S=>this.memory.heapValueHandle(S));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,o),this.success(ae(f))})}getIterator(e){let t=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return c.withScope(r=>{let i=r.manage(this.getProp(e,t)),s=this.callFunction(i,e);return s.error?s:this.success(new ye(s.value,this))})}setProp(e,t,r){this.runtime.assertOwned(e),this.borrowPropertyKey(t).consume(i=>this.ffi.QTS_SetProp(this.ctx.value,e.value,i.value,r.value))}defineProp(e,t,r){this.runtime.assertOwned(e),c.withScope(i=>{let s=i.manage(this.borrowPropertyKey(t)),n=r.value||this.undefined,u=!!r.configurable,o=!!r.enumerable,a=!!r.value,f=r.get?i.manage(this.newFunction(r.get.name,r.get)):this.undefined,S=r.set?i.manage(this.newFunction(r.set.name,r.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,e.value,s.value,n.value,f.value,S.value,u,o,a)})}callFunction(e,t,...r){this.runtime.assertOwned(e);let i,s=r[0];s===void 0||Array.isArray(s)?i=s??[]:i=r;let n=this.memory.toPointerArray(i).consume(o=>this.ffi.QTS_Call(this.ctx.value,e.value,t.value,i.length,o.value)),u=this.ffi.QTS_ResolveException(this.ctx.value,n);return u?(this.ffi.QTS_FreeValuePointer(this.ctx.value,n),this.fail(this.memory.heapValueHandle(u))):this.success(this.memory.heapValueHandle(n))}callMethod(e,t,r=[]){return this.getProp(e,t).consume(i=>this.callFunction(i,e,r))}evalCode(e,t="eval.js",r){let i=r===void 0?1:0,s=de(r),n=this.memory.newHeapCharPointer(e).consume(o=>this.ffi.QTS_Eval(this.ctx.value,o.value.ptr,o.value.strlen,t,i,s)),u=this.ffi.QTS_ResolveException(this.ctx.value,n);return u?(this.ffi.QTS_FreeValuePointer(this.ctx.value,n),this.fail(this.memory.heapValueHandle(u))):this.success(this.memory.heapValueHandle(n))}throw(e){return this.errorToHandle(e).consume(t=>this.ffi.QTS_Throw(this.ctx.value,t.value))}borrowPropertyKey(e){return typeof e=="number"?this.newNumber(e):typeof e=="string"?this.newString(e):new v(e.value,this.runtime)}getMemory(e){if(e===this.rt.value)return this.memory;throw new Error("Private API. Cannot get memory from a different runtime")}dump(e){this.runtime.assertOwned(e);let t=this.typeof(e);if(t==="string")return this.getString(e);if(t==="number")return this.getNumber(e);if(t==="bigint")return this.getBigInt(e);if(t==="undefined")return;if(t==="symbol")return this.getSymbol(e);let r=this.getPromiseState(e);if(r.type==="fulfilled"&&!r.notAPromise)return e.dispose(),{type:r.type,value:r.value.consume(this.dump)};if(r.type==="pending")return e.dispose(),{type:r.type};if(r.type==="rejected")return e.dispose(),{type:r.type,error:r.error.consume(this.dump)};let i=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,e.value));try{return JSON.parse(i)}catch{return i}}unwrapResult(e){if(e.error){let t="context"in e.error?e.error.context:this,r=e.error.consume(i=>this.dump(i));if(r&&typeof r=="object"&&typeof r.message=="string"){let{message:i,name:s,stack:n,...u}=r,o=new M(r,t);typeof s=="string"&&(o.name=r.name),o.message=i;let a=o.stack;throw typeof n=="string"&&(o.stack=`${s}: ${i}
|
|
7
|
+
${r.stack}Host: ${a}`),Object.assign(o,u),o}throw new M(r)}return e.value}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getFunction(e){let t=this.runtime.hostRefs.get(e);if(typeof t!="function")throw new Error(`Host reference ${e} is not a function`);return t}errorToHandle(e){return e instanceof h?e:this.newError(e)}encodeBinaryJSON(e){let t=this.ffi.QTS_bjson_encode(this.ctx.value,e.value);return this.memory.heapValueHandle(t)}decodeBinaryJSON(e){let t=this.ffi.QTS_bjson_decode(this.ctx.value,e.value);return this.memory.heapValueHandle(t)}success(e){return w.success(e)}fail(e){return w.fail(e,t=>this.unwrapResult(t))}},ge=class extends m{constructor(e){super(),this.scope=new c,this.contextMap=new Map,this.hostRefs=new ve,this._debugMode=!1,this.cToHostCallbacks={freeHostRef:(t,r)=>{if(t!==this.rt.value)throw new Error("Runtime pointer mismatch");this.hostRefs.delete(r)},shouldInterrupt:t=>{if(t!==this.rt.value)throw new Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let r=this.interruptHandler;if(!r)throw new Error("QuickJSContext had no interrupt handler");return r(this)?1:0},loadModuleSource:N(this,function*(t,r,i,s){let n=this.moduleLoader;if(!n)throw new Error("Runtime has no module loader");if(r!==this.rt.value)throw new Error("Runtime pointer mismatch");let u=this.contextMap.get(i)??this.newContext({contextPointer:i});try{let o=yield*t(n(s,u));if(typeof o=="object"&&"error"in o&&o.error)throw this.debugLog("cToHostLoadModule: loader returned error",o.error),o.error;let a=typeof o=="string"?o:"value"in o?o.value:o;return this.memory.newHeapCharPointer(a).value.ptr}catch(o){return this.debugLog("cToHostLoadModule: caught error",o),u.throw(o),0}}),normalizeModule:N(this,function*(t,r,i,s,n){let u=this.moduleNormalizer;if(!u)throw new Error("Runtime has no module normalizer");if(r!==this.rt.value)throw new Error("Runtime pointer mismatch");let o=this.contextMap.get(i)??this.newContext({contextPointer:i});try{let a=yield*t(u(s,n,o));if(typeof a=="object"&&"error"in a&&a.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",a.error),a.error;let f=typeof a=="string"?a:a.value;return o.getMemory(this.rt.value).newHeapCharPointer(f).value.ptr}catch(a){return this.debugLog("normalizeModule: caught error",a),o.throw(a),0}})},e.ownedLifetimes?.forEach(t=>this.scope.manage(t)),this.module=e.module,this.memory=new ee(this.module),this.ffi=e.ffi,this.rt=e.rt,this.callbacks=e.callbacks,this.scope.manage(this.rt),this.callbacks.setRuntimeCallbacks(this.rt.value,this.cToHostCallbacks),this.executePendingJobs=this.executePendingJobs.bind(this),J&&this.setDebugMode(!0)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}newContext(e={}){let t=me(e.intrinsics),r=new h(e.contextPointer||this.ffi.QTS_NewContext(this.rt.value,t),void 0,s=>{this.contextMap.delete(s),this.callbacks.deleteContext(s),this.ffi.QTS_FreeContext(s)}),i=new we({module:this.module,ctx:r,ffi:this.ffi,rt:this.rt,ownedLifetimes:e.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(r.value,i),i}setModuleLoader(e,t){this.moduleLoader=e,this.moduleNormalizer=t,this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value,this.moduleNormalizer?1:0)}removeModuleLoader(){this.moduleLoader=void 0,this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value)}hasPendingJob(){return!!this.ffi.QTS_IsJobPending(this.rt.value)}setInterruptHandler(e){let t=this.interruptHandler;this.interruptHandler=e,t||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0)}executePendingJobs(e=-1){let t=this.memory.newMutablePointerArray(1),r=this.ffi.QTS_ExecutePendingJob(this.rt.value,e??-1,t.value.ptr),i=t.value.typedArray[0];if(t.dispose(),i===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,r),w.success(0);let s=this.contextMap.get(i)??this.newContext({contextPointer:i}),n=s.getMemory(this.rt.value).heapValueHandle(r);if(s.typeof(n)==="number"){let u=s.getNumber(n);return n.dispose(),w.success(u)}else{let u=Object.assign(n,{context:s});return w.fail(u,o=>s.unwrapResult(o))}}setMemoryLimit(e){if(e<0&&e!==-1)throw new Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,e)}computeMemoryUsage(){let e=this.getSystemContext().getMemory(this.rt.value);return e.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,e.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(e){if(e<0)throw new Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,e)}assertOwned(e){if(e.owner&&e.owner.rt!==this.rt)throw new G(`Handle is not owned by this runtime: ${e.owner.rt.value} != ${this.rt.value}`)}setDebugMode(e){this._debugMode=e,this.ffi.DEBUG&&this.rt.alive&&this.ffi.QTS_SetDebugLogEnabled(this.rt.value,e?1:0)}isDebugMode(){return this._debugMode}debugLog(...e){this._debugMode&&console.log("quickjs-emscripten:",...e)}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getSystemContext(){return this.context||(this.context=this.scope.manage(this.newContext())),this.context}},_e=class{constructor(e){this.freeHostRef=e.freeHostRef,this.callFunction=e.callFunction,this.shouldInterrupt=e.shouldInterrupt,this.loadModuleSource=e.loadModuleSource,this.normalizeModule=e.normalizeModule}},be=class{constructor(e){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new _e({freeHostRef:(t,r,i)=>{let s=this.runtimeCallbacks.get(r);if(!s)throw new Error(`QuickJSRuntime(rt = ${r}) not found when trying to free HostRef(id = ${i})`);s.freeHostRef(r,i)},callFunction:(t,r,i,s,n,u)=>this.handleAsyncify(t,()=>{try{let o=this.contextCallbacks.get(r);if(!o)throw new Error(`QuickJSContext(ctx = ${r}) not found for C function call "${u}"`);return o.callFunction(r,i,s,n,u)}catch(o){return console.error("[C to host error: returning null]",o),0}}),shouldInterrupt:(t,r)=>this.handleAsyncify(t,()=>{try{let i=this.runtimeCallbacks.get(r);if(!i)throw new Error(`QuickJSRuntime(rt = ${r}) not found for C interrupt`);return i.shouldInterrupt(r)}catch(i){return console.error("[C to host interrupt: returning error]",i),1}}),loadModuleSource:(t,r,i,s)=>this.handleAsyncify(t,()=>{try{let n=this.runtimeCallbacks.get(r);if(!n)throw new Error(`QuickJSRuntime(rt = ${r}) not found for C module loader`);let u=n.loadModuleSource;if(!u)throw new Error(`QuickJSRuntime(rt = ${r}) does not support module loading`);return u(r,i,s)}catch(n){return console.error("[C to host module loader error: returning null]",n),0}}),normalizeModule:(t,r,i,s,n)=>this.handleAsyncify(t,()=>{try{let u=this.runtimeCallbacks.get(r);if(!u)throw new Error(`QuickJSRuntime(rt = ${r}) not found for C module loader`);let o=u.normalizeModule;if(!o)throw new Error(`QuickJSRuntime(rt = ${r}) does not support module loading`);return o(r,i,s,n)}catch(u){return console.error("[C to host module loader error: returning null]",u),0}})}),this.module=e,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(e,t){this.runtimeCallbacks.set(e,t)}deleteRuntime(e){this.runtimeCallbacks.delete(e)}setContextCallbacks(e,t){this.contextCallbacks.set(e,t)}deleteContext(e){this.contextCallbacks.delete(e)}handleAsyncify(e,t){if(e)return e.handleSleep(i=>{try{let s=t();if(!(s instanceof Promise)){b("asyncify.handleSleep: not suspending:",s),i(s);return}if(this.suspended)throw new D(`Already suspended at: ${this.suspended.stack}
|
|
8
|
+
Attempted to suspend at:`);this.suspended=new $(`(${this.suspendedCount++})`),b("asyncify.handleSleep: suspending:",this.suspended),s.then(n=>{this.suspended=void 0,b("asyncify.handleSleep: resolved:",n),i(n)},n=>{b("asyncify.handleSleep: rejected:",n),console.error("QuickJS: cannot handle error in suspended function",n),this.suspended=void 0})}catch(s){throw b("asyncify.handleSleep: error:",s),this.suspended=void 0,s}});let r=t();if(r instanceof Promise)throw new Error("Promise return value not supported in non-asyncify context.");return r}};function xe(e,t){t.interruptHandler&&e.setInterruptHandler(t.interruptHandler),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes)}function Pe(e,t){t.moduleLoader&&e.setModuleLoader(t.moduleLoader),t.shouldInterrupt&&e.setInterruptHandler(t.shouldInterrupt),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes)}var Me=class{constructor(e,t){this.module=e,this.ffi=t,this.callbacks=new be(e)}newRuntime(e={}){let t=new h(this.ffi.QTS_NewRuntime(),void 0,i=>{this.ffi.QTS_FreeRuntime(i),this.callbacks.deleteRuntime(i)}),r=new ge({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:t});return xe(r,e),e.moduleLoader&&r.setModuleLoader(e.moduleLoader),r}newContext(e={}){let t=this.newRuntime(),r=t.newContext({...e,ownedLifetimes:pe(t,e.ownedLifetimes)});return t.context=r,r}evalCode(e,t={}){return c.withScope(r=>{let i=r.manage(this.newContext());Pe(i.runtime,t);let s=i.evalCode(e,"eval.js");if(t.memoryLimitBytes!==void 0&&i.runtime.setMemoryLimit(-1),s.error)throw i.dump(r.manage(s.error));return i.dump(r.manage(s.value))})}getWasmMemory(){let e=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!e)throw new Error("Variant does not support getting WebAssembly.Memory");return e}getFFI(){return this.ffi}};export{U as a,h as b,c,me as d,de as e,we as f,ge as g,be as h,xe as i,Pe as j,Me as k};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
import{Wa as C,hb as R,ib as S,jb as E,kb as L,lb as A,mb as P,nb as T,ob as M,pb as D,qb as N,rb as z}from"./chunk-VE423Z2L.js";import{Y as l,s as j}from"./chunk-G3SZDPDS.js";async function H(r,t){let d=t.media_root?[t.media_root]:await D();if(!d.length)throw new Error("no media_root given and no remembered locations \u2014 pass the folder to link from");for(let e of d)try{if(!(await j(e)).isDirectory)throw 0}catch{throw new Error(`media_root is not a folder on this machine: ${e}`)}let i=S(r,{ref_ids:t.ref_ids,lane:t.lane,reset:t.reset});if(!i.length)return{session:r,changed:!1,note:"",text:"nothing in scope: every reference in scope is already linked (use reset=true to re-point) or the ids/lane matched nothing"};if(t.reset)for(let e of i)e.binding_state="unbound",delete e.coverage_reason;let g=[],w=!1,m=[];for(let e of d)if(t.gather==="path")for(let n of i){let c=n.local_path??n.target_url??"",o=c?await L(e,c):null;o?g.push(o):m.push(`${n.id} ${l(c)}: not at its recorded path under ${e}`)}else{let n=await E(e,i,t.cap);g.push(...n.paths),w||=n.capped}let{refs:_,failed:u}=await A([...new Set(g)]);t.remember&&t.media_root&&await N(t.media_root);let b=new Set(i.map(e=>e.id)),p=C(r,_,b);if(p.splits.length){r=p.session;let e=new Set([...b,...p.splits.flatMap(n=>n.into)]);i=(r.media_references??[]).filter(n=>e.has(n.id));for(let n of p.splits){let c=o=>l(i.find(q=>q.id===o)?.target_url??o);m.push(`split ${n.ref_id} across ${n.into.length} section file(s): ${n.into.map(c).join(", ")}`)}}let a=R(t.criteria),s=P(r,i,_,a,t.tolerances),I=t.criteria?.picture?await T(r,s):[],k=[`scope: ${i.length} reference(s)${t.lane!=="both"?` (${t.lane} lane)`:""}${t.ref_ids?` (zone of ${t.ref_ids.length})`:""}; gather=${t.gather} under ${d.join(", ")}: ${_.length} candidate clip(s)${w?` (CAPPED at ${t.cap} \u2014 narrow the folder)`:""}`,`criteria: ${[...Object.entries(a).filter(([,e])=>e===!0).map(([e])=>e),...t.criteria?.picture?["picture"]:[]].join(", ")}${a.fileName?` (${a.fileNameMode})`:""}${a.fileExtensions?`; ext ${a.fileExtensions}`:""}; timecode containment + fps always on`,...u.length?[`could not probe ${u.length}: ${u.slice(0,5).join("; ")}`]:[],...m.slice(0,20),...I.slice(0,40)];if(t.dry_run)return{session:r,changed:!1,note:"",text:[...k,z(r,s,{compare:t.compare}),"(dry run \u2014 nothing changed; pass accept=[{ref_id,candidate_id}] to commit chosen rows, or run again without dry_run to apply every matched row)"].join(`
|
|
4
|
+
`)};let f,h=[];if(t.accept?.length){f=[];for(let e of t.accept){let n=s.rows.find(o=>o.ref_id===e.ref_id);n&&(n.candidate?.id===e.candidate_id||n.alternatives.some(o=>o.id===e.candidate_id))?f.push(e):h.push(`${e.ref_id} \u2192 ${e.candidate_id}: not a proposed match or alternative for that reference`)}}else f=s.rows.filter(e=>e.status==="matched"&&e.candidate).map(e=>({ref_id:e.ref_id,candidate_id:e.candidate.id}));let $=M(r,s,f),y=$.session.media_references??[],v=y.filter(e=>i.some(n=>n.id===e.id)&&e.binding_state==="linked").length,O=$.applied,x=y.filter(e=>i.some(n=>n.id===e.id)&&e.binding_state!=="linked").map(e=>` - ${e.id} ${l(e.target_url??"")}: ${e.coverage_reason??(s.rows.find(n=>n.ref_id===e.id)?.status==="ambiguous"?"ambiguous \u2014 pick one with accept":"no file matched")}`),U=[...k,`Linked ${v} of ${i.length}${h.length?`; ${h.length} pick(s) vetoed`:""}`,...O.map(e=>`- ${e.ref_id}: ${l(e.before.path??"?")} \u2192 ${e.after.path}${e.warning?` \u26A0 ${e.warning}`:""}`),...h.map(e=>` \u2717 ${e}`),...x.length?["unresolved:",...x]:[]].join(`
|
|
5
|
+
`);return{session:$.session,changed:!0,note:`relink ${t.gather} ${d[0]} (${v}/${i.length})`,text:U}}export{H as a};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
import{pc as D,qc as F,rc as N}from"./chunk-VE423Z2L.js";import{i as j}from"./chunk-NSQP6CTA.js";import{$ as _,A as M,D as C,F as R,G as T,J as q,K as L,N as w,Y as b,_ as k,ba as I,g as y,m as O,r as S,s as A,t as x,u as P,x as H,z as E}from"./chunk-G3SZDPDS.js";var B=16e3,h=class extends Error{constructor(t,i){super(i);this.code=t}},$=class d{constructor(e,t=j,i=B){this.spec=e;this.bridge=t;this.waitMs=i;this.renders=new Map;this.host=e.host,e.items&&(this.items=n=>this.modelItems(n??{}))}async peer(){let e=await(await this.bridge()).waitFor(this.host,this.waitMs);if(!e)throw new h("not_connected",`${this.host}: the conform.tools plugin in ${this.spec.label} is not connected. ${this.spec.setup}`);return e}async needs(e){let t=await this.peer();if(!t.capabilities.includes(e))throw new h("panel_old",`${this.host}: the conform.tools plugin open in ${this.spec.label} ${t.version||""} has no ${e} (an older plugin); update it (${this.spec.setup})`);return t}async ask(e,t={},i){return await this.peer(),await(await this.bridge()).request(this.host,e,t,i)}static{this.announced=(e,t)=>e.optional_verbs.includes(t)}async support(){let e={ok:!1,reason:"the renderplugin is a DaVinci Resolve plugin"},t;try{t=await(await this.bridge()).waitFor(this.host,Math.min(3e3,this.waitMs))}catch(s){let a={ok:!1,reason:s instanceof Error?s.message:String(s)};return{export:a,open:a,render:a,markers:a,renderplugin:e}}if(!t){let s={ok:!1,reason:`the conform.tools plugin in ${this.spec.label} is not connected`,setup:this.spec.setup};return{export:s,open:s,render:s,markers:s,renderplugin:e}}let i=(s,a)=>s?{ok:!0}:{ok:!1,reason:`this plugin version has no ${a}`},n=t.capabilities;return{export:i(n.includes("timeline_read")||n.includes("timeline_write"),"timeline_read"),open:i(d.announced(t,"timeline_write.import_file"),"timeline_write.import_file"),render:i(n.includes("render"),"render"),markers:i(n.includes("markers"),"markers"),renderplugin:e}}async current(){let e=await this.ask("session.current_project");if(!e)return{project:"",timelines:[],timeline:""};let t=await this.ask("session.timeline_count",{project:e}),i=[];for(let s=1;s<=t;s++){let a=await this.ask("session.timeline_by_index",{project:e,index:s});a&&i.push(await this.ask("session.name",{handle:a}))}let n=await this.ask("session.current_timeline",{project:e});return{project:await this.ask("session.name",{handle:e}),timelines:i,timeline:n?await this.ask("session.name",{handle:n}):""}}async project(e={}){let t=await this.current();return{project:t.project,timeline:e.timeline??t.timeline,timelines:t.timelines,tracks:[],jobs:[],found:{},pool:{path:"",clips:0,folders:[]}}}async sequence(e){let t=await this.ask("session.current_project");if(!t)throw new h("no_project",`${this.host}: no project is open`);if(!e){let s=await this.ask("session.current_timeline",{project:t});if(!s)throw new h("no_timeline",`${this.host}: no timeline is active`);return{project:t,seq:s,name:await this.ask("session.name",{handle:s})}}let i=await this.ask("session.timeline_count",{project:t}),n=[];for(let s=1;s<=i;s++){let a=await this.ask("session.timeline_by_index",{project:t,index:s});if(!a)continue;let p=await this.ask("session.name",{handle:a});if(p===e)return{project:t,seq:a,name:p};n.push(p)}throw new h("not_found",`${this.host}: no timeline named "${e}" (have: ${n.join(", ")})`)}async model(e){let{project:t,seq:i}=await this.sequence(e);return await this.ask("timeline_read.model",{timeline:i,project:t},12e4)}async export(e){if(!e.out_path)throw new h("usage",`${this.host}: export needs out_path`);let t=await this.peer(),{project:i,seq:n,name:s}=await this.sequence(e.timeline),a=await this.ask("session.name",{handle:i}),p=r=>d.announced(t,r),m=e.out_path,c,l=[];if(p("timeline_write.export_otio")||p("timeline_write.export_xml")){let r=p("timeline_write.export_otio"),o=await this.ask(r?"timeline_write.export_otio":"timeline_write.export_xml",{project:i,timeline:n,path:e.out_path},12e4);if(c=o.format??(r?"otio":"xmeml"),o.ok===!1)throw new h("export_failed",`${this.host}: ${this.spec.label} did not write ${e.out_path}${o.errors?.length?` (${o.errors.join("; ")})`:""}`);o.path&&o.path!==e.out_path&&(m=await this.adopt(o.path,e.out_path)),l=o.warnings??[]}else if(p("timeline_read.export_file")){let r=await this.ask("timeline_read.export_file",{timeline:n,fmt:"otio",path:e.out_path},12e4);if(!r)throw new h("export_failed",`${this.host}: ${this.spec.label} exported no OTIO`);c="otio",r!==e.out_path&&(m=await this.adopt(r,e.out_path))}else{await this.needs("timeline_read");let r=await this.ask("timeline_read.model",{timeline:n,project:i},12e4),o=J(r);await E(e.out_path,JSON.stringify(o.otio)),c="otio",l=o.notes}if(!D.includes(c))throw new h("export_failed",`${this.host}: ${this.spec.label} exported ${c}, which the engine does not read (${m})`);if(!await P(m)||(await A(m)).size===0)throw new h("export_failed",`${this.host}: ${this.spec.label} did not write ${m}`);return{path:m,format:c,project:a,timeline:s,...l.length?{notes:l}:{}}}async adopt(e,t){let i=k(e)&&k(e)!==k(t)?t.slice(0,t.length-k(t).length)+k(e):t;if(await C(e,i),!F(i))throw new h("export_failed",`${this.host}: ${this.spec.label} exported ${b(e)}, which the engine does not read`);return i}async open(e){if(e.into==="scratch")throw new h("unsupported",`${this.host}: opening into a scratch project is not supported; the import lands in the open project`);let t=await this.peer();if(!d.announced(t,"timeline_write.import_file"))throw new h("unsupported",`${this.host}: this conform.tools plugin cannot import timelines (${this.spec.setup})`);let i=await this.ask("session.current_project");if(!i)throw new h("no_project",`${this.host}: no project is open`);let n=await this.ask("timeline_write.import_file",{project:i,path:e.path,sequences:null},3e5);if(!n.ok)throw new h("import_failed",`${this.host}: ${this.spec.label} did not import ${e.path}${n.issues?.length?` (${n.issues.join("; ")})`:""}`);let s=[...n.issues??[]];return n.imported.length>1&&s.push(`imported ${n.imported.length} timelines: ${n.imported.map(a=>a.name).join(", ")}`),e.name&&s.push(`${this.spec.label} names imported timelines after the file's own; name was not applied`),e.media_dirs?.length&&s.push(`${this.spec.label} links media from the paths in the file; media_dirs was not used (relink with timeline_relink before writing)`),{project:await this.ask("session.name",{handle:i}),timeline:n.imported[0]?.name??b(e.path),notes:s,restored:!e.stay,...n.bin?{folder:n.bin}:{}}}async modelItems(e){let t=await this.model(e.timeline),i=[...e.kind==="audio"?[]:t.items.map(n=>({kind:"video",track:n.track,start:n.start-t.start_frame,end:n.end-t.start_frame,id:n.handle?.$h??n.clip_id??"",name:n.name??"",color:n.color??"",flags:n.flags??[],enabled:n.enabled??!0,file:n.file_path})),...e.kind==="video"?[]:(t.audio_items??[]).map(n=>({kind:"audio",track:n.track,start:n.start-t.start_frame,end:n.end-t.start_frame,id:"",name:n.name??"",file:n.file_path??""}))].filter(n=>e.track===void 0||n.track===e.track);return{project:(await this.current()).project,timeline:t.timeline,start_frame:t.start_frame,fps:t.fps,items:i,color_groups:[],layers:1}}async apply(e){let t=e.ops.length>0&&e.ops.every(l=>l.op==="timeline_rename"&&(l.timeline||l.guid)),{project:i,seq:n,name:s}=await this.sequence(t?void 0:e.timeline),a=[],p=[],m=l=>l.op.startsWith("marker_")&&!l.item;for(let l=0;l<e.ops.length;){let r=l;for(;r<e.ops.length&&m(e.ops[r])===m(e.ops[l]);)r++;let o=e.ops.slice(l,r),u=m(o[0])?await this.markerOps(n,o):await this.clipOps(n,o,e.timeline);a.push(...u.results),p.unshift(...u.undo),l=r}let c=a.filter(l=>l.ok).length;return{project:await this.ask("session.name",{handle:i}),timeline:s,results:a,undo:p,applied:c,failed:a.length-c}}async clipOps(e,t,i){let n=await this.peer();if(n.capabilities.includes("edit"))return await this.ask("edit.apply",{timeline:e,ops:t},6e4+t.length*500);let s=(l,r)=>({op:l.op,ok:!1,detail:r});if(!n.capabilities.includes("item_meta"))return{results:t.map(l=>s(l,`${this.host}: clip edits are not reachable over this plugin`)),undo:[]};let a=await this.model(i),p=l=>l?"id"in l?{$h:l.id}:(l.kind??"video")!=="video"?null:a.items.find(r=>r.track===l.track&&r.start-a.start_frame===l.start)?.handle??null:null,m=[],c=[];for(let l of t){let r=p(l.item);try{if(!r)m.push(s(l,`no video item at ${JSON.stringify(l.item??null)}`));else if(l.op==="clip_color"){let o=await this.ask("item_meta.color",{handle:r}),u=l.color?await this.ask("item_meta.set_color",{handle:r,color:l.color}):await this.ask("item_meta.clear_color",{handle:r});m.push({op:l.op,ok:u}),u&&c.unshift({op:"clip_color",item:l.item,color:o})}else if(l.op==="enabled"&&d.announced(n,"item_meta.set_enabled")){let o=a.items.find(f=>f.handle?.$h===r.$h)?.enabled??!0,u=await this.ask("item_meta.set_enabled",{item:r,enabled:!!l.on});m.push({op:l.op,ok:u}),u&&c.unshift({op:"enabled",item:l.item,on:o})}else m.push(s(l,`${this.host}: '${l.op}' is not reachable over this plugin`))}catch(o){m.push(s(l,o instanceof Error?o.message:String(o)))}}return{results:m,undo:c}}async markerOps(e,t){let i=await this.peer(),n=r=>d.announced(i,r),s=new Map((await this.ask("markers.list",{target:e})).map(r=>[r.frame,r])),a=[],p=[],m=async r=>{let o=await this.ask("markers.add",{target:e,frame:r.frame,color:r.color??"",name:r.name??"",note:r.note??"",duration:r.duration??1,custom_data:r.custom_data??""});return o&&s.set(r.frame,{color:"",name:"",note:"",duration:1,...r}),o},c=async r=>{let o=await this.ask("markers.delete_at",{target:e,frame:r});return o&&s.delete(r),o},l=r=>({op:"marker_add",frame:r.frame,color:r.color,name:r.name,note:r.note,duration:r.duration,...r.custom_data?{data:r.custom_data}:{}});for(let r of t){let o=Number(r.frame);try{if(r.op==="marker_add"){let u=s.get(o);u&&await c(o);let f=await m({frame:o,color:r.color,name:r.name,note:r.note,duration:Number(r.duration??1),custom_data:r.data});a.push({op:r.op,ok:f}),f&&p.unshift(...u?[l(u)]:[],{op:"marker_delete",frame:o})}else if(r.op==="marker_update"){let u=s.get(o);if(!u){a.push({op:r.op,ok:!1,detail:`no marker at frame ${o}`});continue}let f=r.to_frame!==void 0?Number(r.to_frame):o,v={...u,frame:f,...r.color!==void 0?{color:String(r.color)}:{},...r.name!==void 0?{name:String(r.name)}:{},...r.note!==void 0?{note:String(r.note)}:{}},g=!0;n("markers.set_color")&&n("markers.set_text")&&n("markers.move")?(r.color!==void 0&&(g=await this.ask("markers.set_color",{target:e,frame:o,color:r.color})&&g),(r.name!==void 0||r.note!==void 0)&&(g=await this.ask("markers.set_text",{target:e,frame:o,name:r.name,note:r.note})&&g),f!==o&&(g=await this.ask("markers.move",{target:e,frame:o,to_frame:f})&&g),s.delete(o),s.set(f,v)):g=await c(o)&&await m(v),a.push({op:r.op,ok:g}),p.unshift({op:"marker_update",frame:f,color:u.color,name:u.name,note:u.note,...f!==o?{to_frame:o}:{}})}else if(r.op==="marker_delete"){let u=s.get(o),f=!!u&&await c(o);a.push({op:r.op,ok:f,...u?{}:{detail:`no marker at frame ${o}`}}),f&&u&&p.unshift(l(u))}else a.push({op:r.op,ok:!1,detail:`${this.host}: '${r.op}' is not reachable over this plugin`})}catch(u){a.push({op:r.op,ok:!1,detail:u instanceof Error?u.message:String(u)})}}return{results:a,undo:p}}async renderStart(e){if(await this.needs("render"),e.renderplugin)throw new h("unsupported","the renderplugin is a DaVinci Resolve plugin");if(e.disable_tracks?.length||e.audio_tracks?.length)throw new h("unsupported",`${this.host}: disable_tracks / audio_tracks are DaVinci Resolve's; pick a preset that renders what you need`);if(!e.preset)throw new h("usage",`${this.host}: preset is required: one of ${this.spec.label}'s export presets by name`);let{seq:t,name:i}=await this.sequence(e.timeline),n=e.name??i,s={purpose:"deliver",format:"preset",preset:e.preset,target_dir:e.target_dir,name:n,...e.range?{range:[e.range.in,e.range.out]}:{}},a=await this.ask("render.submit",{timeline:t,job:s});if(!a?.id)throw new h("render_refused",`${this.host}: ${a?.error??`${this.spec.label} refused the render`}`);if(!await this.ask("render.start",{job_ids:[a.id]}))throw new h("render_refused",`${this.host}: ${this.spec.label} did not start job ${a.id}`);return this.renders.set(a.id,{dir:e.target_dir,name:n}),{job_id:a.id,state:"queued",percent:0}}async renderStatus(e){let t=await this.ask("render.status",{job_id:e});if(!t)return{job_id:e,state:"failed",percent:0,error:`${this.host}: no render job ${e}`};let i={done:"complete",rendering:"rendering",queued:"queued",failed:"failed",cancelled:"cancelled"}[t.state]??"rendering",n={job_id:e,state:i,percent:Math.round(t.progress??(i==="complete"?100:0)),...t.error?{error:t.error}:{}};if(i==="complete"||i==="failed"||i==="cancelled"){let s=this.renders.get(e);i==="complete"&&s&&(n.outputs=await W(s.dir,s.name)),await this.ask("render.remove",{job_id:e}).catch(()=>!1),this.renders.delete(e)}return n}async renderCancel(e){return await this.ask("render.cancel",{job_id:e})?{job_id:e,state:"cancelled",percent:0}:{...await this.renderStatus(e),error:`${this.spec.label}'s running export cannot be cancelled from here; stop it in ${this.spec.label}`}}};async function W(d,e){let t=[];try{for await(let i of L(d))i.isFile&&i.name.startsWith(`${e}.`)&&t.push(_(d,i.name))}catch{}return t.sort()}function J(d){let e=(c,l)=>({OTIO_SCHEMA:"RationalTime.1",value:c,rate:l}),t=(c,l,r,o=r)=>({OTIO_SCHEMA:"TimeRange.1",start_time:e(c,r),duration:e(l,o)}),i=d.fps,n=d.tracks?.length?d.tracks:[...new Set(d.items.map(c=>c.track))].sort((c,l)=>c-l).map(c=>({index:c,enabled:!0,name:"",items:d.items.filter(l=>l.track===c)})),s=c=>(c.reversed?-1:1)*(c.speed||1)/(c.fps_factor||1),a=new Map;for(let c of d.items)if(c.file_path&&c.start_tc!=null&&c.src_abs_in!=null){let l=c.src_abs_in-c.start_tc+Math.ceil((c.end-c.start)*Math.abs(s(c))*(c.fps_factor||1));a.set(c.file_path,Math.max(a.get(c.file_path)??0,l))}let p=n.map(c=>{let l=d.start_frame,r=[];for(let o of[...c.items].sort((u,f)=>u.start-f.start)){if(o.start<l)continue;o.start>l&&r.push({OTIO_SCHEMA:"Gap.1",name:"",source_range:t(0,o.start-l,i)});let u=o.src_fps||i,f=o.start_tc!=null&&a.has(o.file_path)?o.start_tc:null,v=f!=null?o.src_abs_in:o.src_in??o.src_abs_in??0,g=s(o);r.push({OTIO_SCHEMA:"Clip.2",name:o.name??b(o.file_path||""),enabled:o.enabled!==!1,source_range:t(v,o.end-o.start,u,i),media_references:{DEFAULT_MEDIA:{OTIO_SCHEMA:"ExternalReference.1",name:b(o.file_path||""),target_url:o.file_path?`file://${o.file_path}`:"",...f!=null?{available_range:t(f,a.get(o.file_path),u)}:{},metadata:{}}},active_media_reference_key:"DEFAULT_MEDIA",effects:Math.abs(g-1)>1e-6?[{OTIO_SCHEMA:"LinearTimeWarp.1",name:"",effect_name:"LinearTimeWarp",time_scalar:g}]:[],markers:[],metadata:o.reel?{cmx_3600:{reel:o.reel}}:{}}),l=o.end}return{OTIO_SCHEMA:"Track.1",name:c.name||`V${c.index}`,kind:"Video",enabled:c.enabled!==!1,children:r,effects:[],markers:[],metadata:{}}}),m=[];return d.audio_items?.length&&m.push(`${d.audio_items.length} audio clip(s) not carried: the host's plugin reports no audio source times`),d.transitions?.length&&m.push(`${d.transitions.length} transition(s) not carried (cuts in their place)`),{otio:{OTIO_SCHEMA:"Timeline.1",name:d.timeline,global_start_time:e(d.start_frame,i),metadata:{},tracks:{OTIO_SCHEMA:"Stack.1",name:"tracks",children:p,effects:[],markers:[],metadata:{}}},notes:m}}var X=16e3;var G="Install the conform.tools panel (host_setup host=premiere action=install_panel), then in Premiere open Window > UXP Plugins > conform.tools. It connects by itself from then on.";var U=class extends ${constructor(t=j,i=X){super({host:"premiere",label:"Premiere Pro",setup:G},t,i);this.items=async(t={})=>{await this.needs("edit");let{seq:i}=await this.sequence(t.timeline),n=await this.ask("edit.items",{timeline:i,kind:t.kind,track:t.track},12e4),s=n.project_path?await K(n.project_path,n.timeline).catch(p=>({error:p instanceof Error?p.message:String(p)})):{error:"the project has never been saved"},a=0;if(!("error"in s))for(let p of n.items){let m=s.get(`${p.kind}:${p.track}:${p.start}:${Number(p.end)-Number(p.start)}`);m?Object.assign(p,m,{saved:!0}):(p.saved=!1,a++)}return{...n,color_groups:[],layers:1,..."error"in s?{saved_note:`saved project not read: ${s.error}`}:{unsaved_items:a}}};this.premiereRenders=new Map}async current(){let t=await this.ask("session.describe");return{project:t.project,timelines:t.timelines,timeline:t.current}}async liveMarkers(t){if(!$.announced(await this.peer(),"edit.markers"))return null;let{seq:i}=await this.sequence(t);return await this.ask("edit.markers",{timeline:i},12e4)}async model(t){return await super.model(t)}async projectClips(){return await this.needs("edit"),await this.ask("edit.project_clips",{},12e4)}async relinkClips(t){return await this.needs("edit"),await this.ask("edit.relink_clips",{items:t},6e4+t.length*2e3)}async cutIn(t,i){await this.needs("edit");let{seq:n}=await this.sequence(t);return await this.ask("edit.cut_in",{timeline:n,cuts:i},12e4+i.length*3e3)}async renderStart(t){if(t.range)throw new h("unsupported","premiere: a frame range is not supported yet; set in/out on the sequence in Premiere");if(!t.preset||!/\.epr$/i.test(t.preset))throw new h("usage","premiere: preset must be the path of a Media Encoder preset (.epr)");let{seq:i,name:n}=await this.sequence(t.timeline);await M(t.target_dir);let s=_(t.target_dir,`${t.name??n}.mov`),a=await this.ask("render.export_sequence",{timeline:i,output_path:s,preset_path:t.preset,queue:!1},6e4);if(!a.ok)throw new h("render_refused","premiere: Premiere refused the export");let p=a.job||`ppro-${Date.now()}`;return this.premiereRenders.set(p,s),{job_id:p,state:"rendering",percent:0}}async renderStatus(t){let i=await this.ask("render.progress"),n=i[t]??i.last,s=this.premiereRenders.get(t);return n?.event==="error"||n?.event==="onEncodeError"?{job_id:t,state:"failed",percent:0,error:String(n.data??"encode error")}:n?.event==="complete"||n?.event==="onEncodeComplete"||s&&await x(s)&&!n?{job_id:t,state:"complete",percent:100,...s?{outputs:[s]}:{}}:{job_id:t,state:"rendering",percent:typeof n?.data=="number"?Math.round(Number(n.data)*100):0}}async renderCancel(t){return{job_id:t,state:"cancelled",percent:0,error:"Premiere's export cannot be cancelled from here; cancel it in Premiere / Media Encoder"}}};async function K(d,e){let{session:t}=await N(d,"prproj"),i=t.timelines.find(s=>s.name===e),n=new Map;if(!i)throw new Error(`the saved project has no sequence "${e}" (saved before it was made?)`);for(let s of i.tracks)if(!(s.kind!=="Video"&&s.kind!=="Audio"))for(let a of s.items){if(a.kind==="gap"||a.kind==="transition")continue;let p=a;n.set(`${s.kind==="Video"?"video":"audio"}:${s.track_index}:${a.timeline_range.start.value}:${a.timeline_range.duration.value}`,{saved_id:a.id,...p.speed_factor!=null&&p.speed_factor!==1?{retime:p.speed_factor}:{},...p.speed_ramped?{ramped:!0}:{},...p.speed_reverse?{reversed:!0}:{},...a.kind==="nested"?{nested:!0}:{},...p.is_multicam?{multicam:!0}:{},...p.effects?.some(m=>/stabiliz/i.test(m.kind??""))?{stabilized:!0}:{},...p.effects?.length?{saved_effects:p.effects.map(m=>m.name??m.kind??"")}:{}})}return n}function z(d=y()){return d==="darwin"?"/Library/Application Support/Adobe/Adobe Desktop Common/RemoteComponents/UPI/UnifiedPluginInstallerAgent/UnifiedPluginInstallerAgent.app/Contents/MacOS/UnifiedPluginInstallerAgent":d==="win32"?"C:\\Program Files\\Common Files\\Adobe\\Adobe Desktop Common\\RemoteComponents\\UPI\\UnifiedPluginInstallerAgent\\UnifiedPluginInstallerAgent.exe":null}async function V(){for(let d of["./uxp-plugin/","./premiere-uxp/"]){let e=S(new URL(d,import.meta.url));if(await P(_(e,"manifest.json")))return e}throw new Error("premiere: the conform.tools panel is missing from this install")}async function Q(){return JSON.parse(await H(_(await V(),"manifest.json"))).version}async function oe(d=y()){let e=z(d);if(!e||!await x(e))return{installed:!1,listing:"Creative Cloud's plugin installer is not on this machine"};let t=await w(e,d==="win32"?["/list","all"]:["--list","all"],{timeoutMs:6e4}),i=t.stdout.split(`
|
|
4
|
+
`).find(n=>/CONFORM\.TOOLS|conformtools/i.test(n));return{installed:!!i&&/enabled|installed/i.test(i),version:i?.match(/(\d+\.\d+\.\d+)\s*$/)?.[1],listing:t.stdout.trim()}}async function ae(d=y()){let e=z(d);if(!e||!await x(e))throw new Error("premiere: Creative Cloud's plugin installer (UnifiedPluginInstallerAgent) is not on this machine; install Creative Cloud");let t=await V(),i=await Q(),n=await q("conform-ccx-");for(let l of["manifest.json","index.html","index.js","lib","icons"])await T(_(t,l),_(n,l));let s=_(O(),"premiere");await M(s);let a=I(_(s,`conformtools-premiere-${i}.ccx`));await R(a);let p=d==="darwin"?await w("sh",["-c",`cd '${n.replace(/'/g,"'\\''")}' && zip -r -q -X '${a.replace(/'/g,"'\\''")}' manifest.json index.html index.js lib icons`]):await w("powershell",["-NoProfile","-Command",`Compress-Archive -Path '${n}\\*' -DestinationPath '${a.replace(/\.ccx$/,".zip")}' -Force; Move-Item -Force '${a.replace(/\.ccx$/,".zip")}' '${a}'`]);if(await R(n),!p.success)throw new Error(`premiere: could not package the panel: ${p.stderr.trim()}`);await w(e,d==="win32"?["/remove","conform.tools"]:["--remove","conform.tools"],{timeoutMs:12e4});let m=await w(e,d==="win32"?["/install",a]:["--install",a],{timeoutMs:18e4}),c=`${m.stdout}
|
|
5
|
+
${m.stderr}`.trim();if(!m.success||!/Installation Successful/i.test(c))throw new Error(`premiere: Adobe's installer refused the panel: ${c.split(`
|
|
6
|
+
`).pop()}`);return{version:i,ccx:a,output:c}}export{$ as a,U as b,K as c,Q as d,oe as e,ae as f};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{a as K,d as pt}from"./chunk-XJNWAQON.js";import{a as j}from"./chunk-PHAMF4JF.js";import{I as gt,Z as y,k as R,v as S,x as T,y as P}from"./chunk-DNS4ZYIO.js";import{createHash as Yt}from"node:crypto";import{open as qt}from"node:fs/promises";var Dt=new Uint16Array(256);for(let e=0;e<256;e++){let t=0,n=e<<8;for(let r=0;r<8;r++)(t^n)&32768?t=t<<1^4129:t=t<<1,n=n<<1;Dt[e]=t&65535}var Q=0,mt=2;var ee=Date.UTC(2020,0,1,0,0,0);function yt(e,t,n,r,o,s,i,a,g,c,u,_,p,w,d,b){let F=z(o,l.__wbindgen_export3,l.__wbindgen_export4),A=x,v=nt(i,l.__wbindgen_export3),W=x,Ot=l.udf_add_file_stream(f(e),f(t),f(n),f(r),F,A,s,v,W,a,g,c,u,_,p,w,d,b);return M(Ot)}function re(e,t,n,r){let o,s;try{let p=l.__wbindgen_add_to_stack_pointer(-16),w=z(e,l.__wbindgen_export3,l.__wbindgen_export4),d=x,b=z(t,l.__wbindgen_export3,l.__wbindgen_export4),F=x,A=z(n,l.__wbindgen_export3,l.__wbindgen_export4),v=x;l.udf_build_layout(p,w,d,b,F,A,v,r);var i=h().getInt32(p+0,!0),a=h().getInt32(p+4,!0),g=h().getInt32(p+8,!0),c=h().getInt32(p+12,!0),u=i,_=a;if(c)throw u=0,_=0,M(g);return o=u,s=_,C(u,_)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export5(o,s,1)}}function ht(e,t,n,r,o,s,i){let a=z(o,l.__wbindgen_export3,l.__wbindgen_export4),g=x,c=nt(i,l.__wbindgen_export3),u=x,_=l.udf_fill_sparse_stream(f(e),f(t),f(n),f(r),a,g,s,c,u);return M(_)}function oe(){let e,t;try{let o=l.__wbindgen_add_to_stack_pointer(-16);l.udf_last_panic(o);var n=h().getInt32(o+0,!0),r=h().getInt32(o+4,!0);return e=n,t=r,C(n,r)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export5(e,t,1)}}function xt(e,t){let n=l.udf_parse_stream(f(e),f(t));return M(n)}function ie(e){let t,n;try{let s=l.__wbindgen_add_to_stack_pointer(-16),i=nt(e,l.__wbindgen_export3),a=x;l.udf_read_conform_iuvd(s,i,a);var r=h().getInt32(s+0,!0),o=h().getInt32(s+4,!0);return t=r,n=o,C(r,o)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export5(t,n,1)}}function Mt(){return{__proto__:null,"./udf_bg.js":{__proto__:null,__wbg___wbindgen_is_function_acc5528be2b923f2:function(t){return typeof m(t)=="function"},__wbg___wbindgen_is_undefined_721f8decd50c87a3:function(t){return m(t)===void 0},__wbg___wbindgen_number_get_1cc01dd708740256:function(t,n){let r=m(n),o=typeof r=="number"?r:void 0;h().setFloat64(t+8,O(o)?0:o,!0),h().setInt32(t+0,!O(o),!0)},__wbg___wbindgen_throw_ea4887a5f8f9a9db:function(t,n){throw new Error(C(t,n))},__wbg__wbg_cb_unref_33c39e13d73b25f6:function(t){m(t)._wbg_cb_unref()},__wbg_call_0e855b388e315e17:function(){return tt(function(t,n,r,o){let s=m(t).call(m(n),m(r),m(o));return f(s)},arguments)},__wbg_call_5575218572ead796:function(){return tt(function(t,n,r){let o=m(t).call(m(n),m(r));return f(o)},arguments)},__wbg_call_8e98ed2f3c86c4b5:function(){return tt(function(t,n){let r=m(t).call(m(n));return f(r)},arguments)},__wbg_error_2b5d73c4c4804cfd:function(t,n){console.error(C(t,n))},__wbg_length_589238bdcf171f0e:function(t){return m(t).length},__wbg_new_81880fb5002cb255:function(t){let n=new Uint8Array(m(t));return f(n)},__wbg_new_from_slice_543b875b27789a8f:function(t,n){let r=new Uint8Array(bt(t,n));return f(r)},__wbg_new_no_args_2d7333de60de5ac7:function(t,n){let r=new Function(C(t,n));return f(r)},__wbg_new_typed_00a409eb4ec4f2d9:function(t,n){try{var r={a:t,b:n},o=(i,a)=>{let g=r.a;r.a=0;try{return jt(g,r.b,i,a)}finally{r.a=g}};let s=new Promise(o);return f(s)}finally{r.a=0}},__wbg_prototypesetcall_d721637c7ca66eb8:function(t,n,r){Uint8Array.prototype.set.call(bt(t,n),m(r))},__wbg_queueMicrotask_1c9b3800e321a967:function(t){let n=m(t).queueMicrotask;return f(n)},__wbg_queueMicrotask_311744e534a929a3:function(t){queueMicrotask(m(t))},__wbg_resolve_d82363d90af6928a:function(t){let n=Promise.resolve(m(t));return f(n)},__wbg_static_accessor_GLOBAL_THIS_2fee5048bcca5938:function(){let t=typeof globalThis>"u"?null:globalThis;return O(t)?0:f(t)},__wbg_static_accessor_GLOBAL_ce44e66a4935da8c:function(){let t=typeof global>"u"?null:global;return O(t)?0:f(t)},__wbg_static_accessor_SELF_44f6e0cb5e67cdad:function(){let t=typeof self>"u"?null:self;return O(t)?0:f(t)},__wbg_static_accessor_WINDOW_168f178805d978fe:function(){let t=typeof window>"u"?null:window;return O(t)?0:f(t)},__wbg_then_05edfc8a4fea5106:function(t,n,r){let o=m(t).then(m(n),m(r));return f(o)},__wbg_then_591b6b3a75ee817a:function(t,n){let r=m(t).then(m(n));return f(r)},__wbindgen_cast_0000000000000001:function(t,n){let r=Nt(t,n,Lt);return f(r)},__wbindgen_cast_0000000000000002:function(t){return f(t)},__wbindgen_cast_0000000000000003:function(t,n){let r=C(t,n);return f(r)},__wbindgen_object_clone_ref:function(t){let n=m(t);return f(n)},__wbindgen_object_drop_ref:function(t){M(t)}}}}function Lt(e,t,n){try{let s=l.__wbindgen_add_to_stack_pointer(-16);l.__wasm_bindgen_func_elem_252(s,e,t,f(n));var r=h().getInt32(s+0,!0),o=h().getInt32(s+4,!0);if(o)throw M(r)}finally{l.__wbindgen_add_to_stack_pointer(16)}}function jt(e,t,n,r){l.__wasm_bindgen_func_elem_266(e,t,f(n),f(r))}function f(e){N===E.length&&E.push(E.length+1);let t=N;return N=E[t],E[t]=e,t}var wt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>l.__wbindgen_export2(e.a,e.b));function $t(e){e<1028||(E[e]=N,N=e)}function bt(e,t){return e=e>>>0,D().subarray(e/1,e/1+t)}var U=null;function h(){return(U===null||U.buffer.detached===!0||U.buffer.detached===void 0&&U.buffer!==l.memory.buffer)&&(U=new DataView(l.memory.buffer)),U}function C(e,t){return Bt(e>>>0,t)}var $=null;function D(){return($===null||$.byteLength===0)&&($=new Uint8Array(l.memory.buffer)),$}function m(e){return E[e]}function tt(e,t){try{return e.apply(this,t)}catch(n){l.__wbindgen_export(f(n))}}var E=new Array(1024).fill(void 0);E.push(void 0,null,!0,!1);var N=E.length;function O(e){return e==null}function Nt(e,t,n){let r={a:e,b:t,cnt:1},o=(...s)=>{r.cnt++;let i=r.a;r.a=0;try{return n(i,r.b,...s)}finally{r.a=i,o._wbg_cb_unref()}};return o._wbg_cb_unref=()=>{--r.cnt===0&&(l.__wbindgen_export2(r.a,r.b),r.a=0,wt.unregister(r))},wt.register(o,r,r),o}function nt(e,t){let n=t(e.length*1,1)>>>0;return D().set(e,n/1),x=e.length,n}function z(e,t,n){if(n===void 0){let a=B.encode(e),g=t(a.length,1)>>>0;return D().subarray(g,g+a.length).set(a),x=a.length,g}let r=e.length,o=t(r,1)>>>0,s=D(),i=0;for(;i<r;i++){let a=e.charCodeAt(i);if(a>127)break;s[o+i]=a}if(i!==r){i!==0&&(e=e.slice(i)),o=n(o,r,r=i+e.length*3,1)>>>0;let a=D().subarray(o+i,o+r),g=B.encodeInto(e,a);i+=g.written,o=n(o,r,i,1)>>>0}return x=i,o}function M(e){let t=m(e);return $t(e),t}var H=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});H.decode();var zt=2146435072,et=0;function Bt(e,t){return et+=t,et>=zt&&(H=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),H.decode(),et=t),H.decode(D().subarray(e,e+t))}var B=new TextEncoder;"encodeInto"in B||(B.encodeInto=function(e,t){let n=B.encode(e);return t.set(n),{read:e.length,written:n.length}});var x=0,Wt,Ht,l;function Gt(e,t){return Ht=e,l=e.exports,Wt=t,U=null,$=null,l.__wbindgen_start(),l}async function Jt(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{let r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function G(e){if(l!==void 0)return l;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL("udf_bg.wasm",import.meta.url));let t=Mt();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await Jt(await e,t);return Gt(n,r)}var rt=null;function Vt(e){return rt||(rt=(async()=>{if(e!==void 0)return G(e);if(typeof process<"u"&&process.versions?.node){let n="node:fs/promises",{readFile:r}=await import(n),o=await r(new URL("./wasm/udf_bg.wasm",import.meta.url));return G({module_or_path:o})}let{default:t}=await import("./udf_bg-B37GKRIH.js");return G({module_or_path:t})})()),rt}function J(){return Vt()}function V(e){return(t,n)=>e.read(t,n)}function ot(e){return(t,n)=>e.write(t,n)}function X(e){return()=>e.getSize()}function it(e){return t=>e.setSize?e.setSize(t):Promise.resolve()}async function St(e){await J();let t=JSON.parse(await xt(V(e),X(e)));if(t.error)throw new Error(t.error);let n=null;if(t.iuvdPayload)try{n=JSON.parse(t.iuvdPayload)}catch{}let r=null,o=t.files.find(s=>s.name===".i2o-manifest.json");if(o&&o.extents.length>0&&o.extents[0].type===Q){let s=o.extents[0].position,i=await e.read((t.partitionStartSector+s)*2048,o.totalSize);try{r=JSON.parse(new TextDecoder().decode(i))}catch{}}return{totalSectors:t.totalSectors,partitionStartSector:t.partitionStartSector,partitionLength:t.partitionLength,volumeName:t.volumeName,files:t.files,manifest:r,iuvdPayload:n,rootIcbSector:t.rootIcbSector,rootDataSector:t.rootDataSector,rootDataLength:t.rootDataLength,rootDataSectors:t.rootDataSectors,vdsStartSector:t.vdsStartSector,partitionDescVdsSector:t.partitionDescVdsSector}}function pe(e){let t=[],n=0;for(let r of e.extents)r.type===mt&&t.push({offset:n,length:r.length}),n+=r.length;return t}function It(e){let t=[],n=0;for(let r of e.extents)r.type===Q&&t.push({offset:n,length:r.length,imageSector:r.position}),n+=r.length;return t}async function me(e,t,n,r,o){return await J(),await ht(V(e),ot(e),X(e),it(e),n,r,o),St(e)}async function we(e,t,n,r,o,s=0){await J();let i=new Date,a=!!(o&&o.length>0);return await yt(V(e),ot(e),X(e),it(e),n,r,a?o:new Uint8Array(0),a,s,i.getFullYear(),i.getMonth()+1,i.getDate(),i.getHours(),i.getMinutes(),i.getSeconds(),-i.getTimezoneOffset()),St(e)}var Y=1<<20,k=5*Y,At=5*1024*Y,st=1e4,at=8*Y,Zt=2048;function Ie(e,t,n=Math.max(16*Y,Math.ceil(e/(st-500)))){let r=[...t].filter(c=>c.len>0).sort((c,u)=>c.at-u.at),o=[];for(let c of r){let u=o[o.length-1];u&&c.at<u.at+u.len||(u&&u.at+u.len===c.at&&u.key===c.key&&u.offset+u.len===c.offset?u.len+=c.len:o.push({...c}))}let s=[],i=0;for(let c of o.filter(u=>u.len>=k))c.at>i&&s.push({at:i,len:c.at-i}),s.push({at:c.at,len:c.len,copy:c}),i=c.at+c.len;i<e&&s.push({at:i,len:e-i});let a=c=>c.reduce((u,_)=>{let p=u[u.length-1];return p&&!p.copy&&!_.copy?p.len+=_.len:u.push({..._}),u},[]);for(let c=!0;c;){c=!1,s=a(s);for(let u=0;u<s.length-1;u++){let _=s[u];if(_.len>=k)continue;let p=k-_.len,w=s[u+1],d=s[u-1];if(_.copy){delete _.copy,c=!0;break}w?.copy&&w.len-p>=k?(_.len+=p,w.at+=p,w.len-=p,w.copy={...w.copy,at:w.at,len:w.len,offset:w.copy.offset+p}):d?.copy&&d.len-p>=k?(d.len-=p,d.copy={...d.copy,len:d.len},_.at-=p,_.len+=p):w?.copy?delete w.copy:d?.copy&&delete d.copy,c=!0;break}}let g=[];for(let c of s){let u=c.copy?Math.min(At,Math.max(n,k)):n;for(let _=c.at,p=c.at+c.len;_<p;){let w=Math.min(u,p-_);p-(_+w)>0&&p-(_+w)<k&&(w=p-_<=At?p-_:w-k),g.push(c.copy?{kind:"copy",at:_,len:w,key:c.copy.key,offset:c.copy.offset+(_-c.at)}:{kind:"upload",at:_,len:w}),_+=w}}if(g.length>st)throw new Error(`the image needs ${g.length} pieces (S3 allows ${st})`);return g}function Ae(e,t,n,r){let o=[...r].sort((a,g)=>a.offset-g.offset),s=[],i=0;for(let a of o){let g=Math.min(a.offset,t);g>i&&s.push({at:i,len:g-i,key:e,offset:i}),i=Math.max(i,a.offset+a.length)}return i<Math.min(t,n)&&s.push({at:i,len:Math.min(t,n)-i,key:e,offset:i}),s}async function Ee(e,t,n,r,o){let s=[];for(let i of t.files)for(let a of It(i)){let g=(t.partitionStartSector+a.imageSector)*Zt;for(let c=a.offset;c<a.offset+a.length;){let u=Math.min(a.offset+a.length,(Math.floor(c/at)+1)*at),_=g+(c-a.offset);s.push(o?.(_,u-c)??[Yt("sha256").update(await e.read(_,u-c)).digest("hex"),_,u-c]),r?.(u-c),c=u}}return{v:1,block:at,size:n,blocks:s}}function ve(e,t){let n=new Map;for(let o of t)for(let[s,i,a]of o.index.blocks)n.set(`${s}:${a}`,{key:o.key,offset:i});let r=[];for(let[o,s,i]of e.blocks){let a=n.get(`${o}:${i}`);a&&r.push({at:s,len:i,key:a.key,offset:a.offset})}return r}var Et=(e,t)=>`${K().supabaseUrl}/functions/v1/${e}${t}`;async function ut(e,t,n={}){let r=await pt();if(!r)throw new Error("not signed in to conform.tools \u2014 run account_login");let o=await fetch(Et(e,t),{method:n.method??(n.body?"POST":"GET"),headers:{authorization:`Bearer ${r}`,apikey:K().anonKey,...n.body?{"content-type":"application/json"}:{}},...n.body?{body:JSON.stringify(n.body)}:{},signal:AbortSignal.timeout(2e4)}),s=await o.text();if(!o.ok){let i=s;try{let a=JSON.parse(s);i=a.error?.message??a.message??a.error??s}catch{}throw o.status===404&&/Requested function was not found/i.test(String(i))?new Error(`${e} isn't deployed on ${new URL(Et(e,t)).host}: this server doesn't have that feature yet (an older server, or a staging/production mismatch)`):new Error(`${n.method??"GET"} ${t}: ${o.status} ${i}`)}return s?JSON.parse(s):{}}function Te(e,t="org"){let n=`/v1/sessions/${e}/storage/multipart`,r=(o,s,i)=>ut("v1-sessions",o,{body:s,method:i});return{start:async o=>String((await r(`${n}/start`,{key:o,content_type:"application/x-iso9660-image"})).upload_id),partUrls:async(o,s,i,a)=>(await r(`${n}/${s}/part-urls`,{key:o,first_part:i,count:a})).parts,copyPart:async(o,s,i,a)=>String((await r(`${n}/${s}/copy-part`,{key:o,part_number:i,source_ref:{scheme:t,bucket:"i2o",key:a.key},byte_range:{offset:a.offset,length:a.length}})).etag),complete:async(o,s,i)=>{await r(`${n}/${s}/complete`,{key:o,parts:i})},abort:async(o,s)=>{await r(`${n}/${encodeURIComponent(s)}?key=${encodeURIComponent(o)}`,void 0,"DELETE")},readUrl:async o=>String((await r(`/v1/sessions/${e}/download-url`,{storage_path:o})).download_url)}}async function ct(e,t,n=4){for(let r=1;;r++)try{return await t()}catch(o){if(r>=n)throw new Error(`${e} failed after ${n} tries: ${o instanceof Error?o.message:o}`);await new Promise(s=>setTimeout(s,500*2**r))}}async function Pe(e,t,n,r,o={}){let s=o.fetchFn??fetch,i=await e.start(t),a=n.reduce((d,b)=>d+b.len,0),g=new Array(n.length),c=0,u=0,_=new Map,p=async d=>(_.has(d)||(await e.partUrls(t,i,d+1,Math.min(100,n.length-d))).forEach((F,A)=>_.set(d+A,F)),_.get(d)),w=async d=>{let b=n[d];if(b.kind==="copy")g[d]=await ct(`copy piece ${d+1}`,()=>e.copyPart(t,i,d+1,{key:b.key,offset:b.offset,length:b.len}));else{let F=await r(b.at,b.len);g[d]=await ct(`upload piece ${d+1}`,async()=>{let A=await p(d),v=await s(A.upload_url,{method:A.method,headers:A.headers,body:F,signal:o.signal});if(!v.ok)throw _.delete(d),new Error(`${v.status} ${(await v.text()).slice(0,200)}`);let W=v.headers.get("etag");if(!W)throw new Error("the bucket returned no ETag (expose it in the bucket's CORS / response headers)");return W})}c+=b.len,o.onProgress?.(c,a)};try{await Promise.all(Array.from({length:Math.min(6,n.length)},async()=>{for(;u<n.length;)o.signal?.throwIfAborted(),await w(u++)})),await ct("complete",()=>e.complete(t,i,g.map((d,b)=>({part_number:b+1,etag:d}))))}catch(d){throw await e.abort(t,i).catch(()=>{}),d}return{uploaded:n.filter(d=>d.kind==="upload").reduce((d,b)=>d+b.len,0),copied:n.filter(d=>d.kind==="copy").reduce((d,b)=>d+b.len,0),pieces:n.length}}function ke(e){let t=qt(e,"r");return{read:async(n,r)=>{let o=new Uint8Array(r);return await(await t).read(o,0,r,n),o},close:async()=>{await(await t).close()}}}var ft="local",Tt=/^[A-Za-z0-9_-]{1,64}$/,I=e=>{if(!Tt.test(e))throw new j("invalid_args",`bad project_id '${e}'`);return y(R(),"projects",e)},lt=(e,t={})=>ut("v1-projects",e,t),Pt=e=>Number(/: (\d{3}) /.exec(String(e?.message))?.[1]??0);async function kt(e){let t="",n={base:null,by:null};try{t=await S(y(I(e),"CONTEXT.md"))}catch{}try{n=JSON.parse(await S(y(I(e),"context.json")))}catch{}return{text:t,meta:n}}async function dt(e,t,n){await P(I(e)),await T(y(I(e),"CONTEXT.md"),t),await T(y(I(e),"context.json"),JSON.stringify(n))}var _t=async(e,t)=>(await dt(e,t.context,{base:t.context_updated_at,by:t.context_updated_by_name??null}),{text:t.context,updated_at:t.context_updated_at,updated_by:t.context_updated_by_name??null});async function De(e){I(e);let t=await kt(e);if(e===ft)return{text:t.text,updated_at:null,updated_by:null};if(t.meta.pending)try{return await vt(e,t.text,t.meta.base)}catch(n){if(!(n instanceof j&&n.code==="context_conflict"))return{text:t.text,updated_at:t.meta.base,updated_by:t.meta.by,offline:!0,pending:!0};let r=n.data?.current??{context:"",context_updated_at:null},o=`${r.context.trimEnd()}
|
|
3
|
+
import{a as K,d as pt}from"./chunk-6NLB5TZ2.js";import{a as j}from"./chunk-PHAMF4JF.js";import{$ as y,A as P,K as gt,m as R,x as S,z as T}from"./chunk-G3SZDPDS.js";import{createHash as Yt}from"node:crypto";import{open as qt}from"node:fs/promises";var Dt=new Uint16Array(256);for(let e=0;e<256;e++){let t=0,n=e<<8;for(let r=0;r<8;r++)(t^n)&32768?t=t<<1^4129:t=t<<1,n=n<<1;Dt[e]=t&65535}var Q=0,mt=2;var ee=Date.UTC(2020,0,1,0,0,0);function yt(e,t,n,r,o,s,i,a,g,c,u,_,p,w,d,b){let F=z(o,l.__wbindgen_export3,l.__wbindgen_export4),A=x,v=nt(i,l.__wbindgen_export3),W=x,Ot=l.udf_add_file_stream(f(e),f(t),f(n),f(r),F,A,s,v,W,a,g,c,u,_,p,w,d,b);return M(Ot)}function re(e,t,n,r){let o,s;try{let p=l.__wbindgen_add_to_stack_pointer(-16),w=z(e,l.__wbindgen_export3,l.__wbindgen_export4),d=x,b=z(t,l.__wbindgen_export3,l.__wbindgen_export4),F=x,A=z(n,l.__wbindgen_export3,l.__wbindgen_export4),v=x;l.udf_build_layout(p,w,d,b,F,A,v,r);var i=h().getInt32(p+0,!0),a=h().getInt32(p+4,!0),g=h().getInt32(p+8,!0),c=h().getInt32(p+12,!0),u=i,_=a;if(c)throw u=0,_=0,M(g);return o=u,s=_,C(u,_)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export5(o,s,1)}}function ht(e,t,n,r,o,s,i){let a=z(o,l.__wbindgen_export3,l.__wbindgen_export4),g=x,c=nt(i,l.__wbindgen_export3),u=x,_=l.udf_fill_sparse_stream(f(e),f(t),f(n),f(r),a,g,s,c,u);return M(_)}function oe(){let e,t;try{let o=l.__wbindgen_add_to_stack_pointer(-16);l.udf_last_panic(o);var n=h().getInt32(o+0,!0),r=h().getInt32(o+4,!0);return e=n,t=r,C(n,r)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export5(e,t,1)}}function xt(e,t){let n=l.udf_parse_stream(f(e),f(t));return M(n)}function ie(e){let t,n;try{let s=l.__wbindgen_add_to_stack_pointer(-16),i=nt(e,l.__wbindgen_export3),a=x;l.udf_read_conform_iuvd(s,i,a);var r=h().getInt32(s+0,!0),o=h().getInt32(s+4,!0);return t=r,n=o,C(r,o)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export5(t,n,1)}}function Mt(){return{__proto__:null,"./udf_bg.js":{__proto__:null,__wbg___wbindgen_is_function_acc5528be2b923f2:function(t){return typeof m(t)=="function"},__wbg___wbindgen_is_undefined_721f8decd50c87a3:function(t){return m(t)===void 0},__wbg___wbindgen_number_get_1cc01dd708740256:function(t,n){let r=m(n),o=typeof r=="number"?r:void 0;h().setFloat64(t+8,O(o)?0:o,!0),h().setInt32(t+0,!O(o),!0)},__wbg___wbindgen_throw_ea4887a5f8f9a9db:function(t,n){throw new Error(C(t,n))},__wbg__wbg_cb_unref_33c39e13d73b25f6:function(t){m(t)._wbg_cb_unref()},__wbg_call_0e855b388e315e17:function(){return tt(function(t,n,r,o){let s=m(t).call(m(n),m(r),m(o));return f(s)},arguments)},__wbg_call_5575218572ead796:function(){return tt(function(t,n,r){let o=m(t).call(m(n),m(r));return f(o)},arguments)},__wbg_call_8e98ed2f3c86c4b5:function(){return tt(function(t,n){let r=m(t).call(m(n));return f(r)},arguments)},__wbg_error_2b5d73c4c4804cfd:function(t,n){console.error(C(t,n))},__wbg_length_589238bdcf171f0e:function(t){return m(t).length},__wbg_new_81880fb5002cb255:function(t){let n=new Uint8Array(m(t));return f(n)},__wbg_new_from_slice_543b875b27789a8f:function(t,n){let r=new Uint8Array(bt(t,n));return f(r)},__wbg_new_no_args_2d7333de60de5ac7:function(t,n){let r=new Function(C(t,n));return f(r)},__wbg_new_typed_00a409eb4ec4f2d9:function(t,n){try{var r={a:t,b:n},o=(i,a)=>{let g=r.a;r.a=0;try{return jt(g,r.b,i,a)}finally{r.a=g}};let s=new Promise(o);return f(s)}finally{r.a=0}},__wbg_prototypesetcall_d721637c7ca66eb8:function(t,n,r){Uint8Array.prototype.set.call(bt(t,n),m(r))},__wbg_queueMicrotask_1c9b3800e321a967:function(t){let n=m(t).queueMicrotask;return f(n)},__wbg_queueMicrotask_311744e534a929a3:function(t){queueMicrotask(m(t))},__wbg_resolve_d82363d90af6928a:function(t){let n=Promise.resolve(m(t));return f(n)},__wbg_static_accessor_GLOBAL_THIS_2fee5048bcca5938:function(){let t=typeof globalThis>"u"?null:globalThis;return O(t)?0:f(t)},__wbg_static_accessor_GLOBAL_ce44e66a4935da8c:function(){let t=typeof global>"u"?null:global;return O(t)?0:f(t)},__wbg_static_accessor_SELF_44f6e0cb5e67cdad:function(){let t=typeof self>"u"?null:self;return O(t)?0:f(t)},__wbg_static_accessor_WINDOW_168f178805d978fe:function(){let t=typeof window>"u"?null:window;return O(t)?0:f(t)},__wbg_then_05edfc8a4fea5106:function(t,n,r){let o=m(t).then(m(n),m(r));return f(o)},__wbg_then_591b6b3a75ee817a:function(t,n){let r=m(t).then(m(n));return f(r)},__wbindgen_cast_0000000000000001:function(t,n){let r=Nt(t,n,Lt);return f(r)},__wbindgen_cast_0000000000000002:function(t){return f(t)},__wbindgen_cast_0000000000000003:function(t,n){let r=C(t,n);return f(r)},__wbindgen_object_clone_ref:function(t){let n=m(t);return f(n)},__wbindgen_object_drop_ref:function(t){M(t)}}}}function Lt(e,t,n){try{let s=l.__wbindgen_add_to_stack_pointer(-16);l.__wasm_bindgen_func_elem_252(s,e,t,f(n));var r=h().getInt32(s+0,!0),o=h().getInt32(s+4,!0);if(o)throw M(r)}finally{l.__wbindgen_add_to_stack_pointer(16)}}function jt(e,t,n,r){l.__wasm_bindgen_func_elem_266(e,t,f(n),f(r))}function f(e){N===E.length&&E.push(E.length+1);let t=N;return N=E[t],E[t]=e,t}var wt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>l.__wbindgen_export2(e.a,e.b));function $t(e){e<1028||(E[e]=N,N=e)}function bt(e,t){return e=e>>>0,D().subarray(e/1,e/1+t)}var U=null;function h(){return(U===null||U.buffer.detached===!0||U.buffer.detached===void 0&&U.buffer!==l.memory.buffer)&&(U=new DataView(l.memory.buffer)),U}function C(e,t){return Bt(e>>>0,t)}var $=null;function D(){return($===null||$.byteLength===0)&&($=new Uint8Array(l.memory.buffer)),$}function m(e){return E[e]}function tt(e,t){try{return e.apply(this,t)}catch(n){l.__wbindgen_export(f(n))}}var E=new Array(1024).fill(void 0);E.push(void 0,null,!0,!1);var N=E.length;function O(e){return e==null}function Nt(e,t,n){let r={a:e,b:t,cnt:1},o=(...s)=>{r.cnt++;let i=r.a;r.a=0;try{return n(i,r.b,...s)}finally{r.a=i,o._wbg_cb_unref()}};return o._wbg_cb_unref=()=>{--r.cnt===0&&(l.__wbindgen_export2(r.a,r.b),r.a=0,wt.unregister(r))},wt.register(o,r,r),o}function nt(e,t){let n=t(e.length*1,1)>>>0;return D().set(e,n/1),x=e.length,n}function z(e,t,n){if(n===void 0){let a=B.encode(e),g=t(a.length,1)>>>0;return D().subarray(g,g+a.length).set(a),x=a.length,g}let r=e.length,o=t(r,1)>>>0,s=D(),i=0;for(;i<r;i++){let a=e.charCodeAt(i);if(a>127)break;s[o+i]=a}if(i!==r){i!==0&&(e=e.slice(i)),o=n(o,r,r=i+e.length*3,1)>>>0;let a=D().subarray(o+i,o+r),g=B.encodeInto(e,a);i+=g.written,o=n(o,r,i,1)>>>0}return x=i,o}function M(e){let t=m(e);return $t(e),t}var H=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});H.decode();var zt=2146435072,et=0;function Bt(e,t){return et+=t,et>=zt&&(H=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),H.decode(),et=t),H.decode(D().subarray(e,e+t))}var B=new TextEncoder;"encodeInto"in B||(B.encodeInto=function(e,t){let n=B.encode(e);return t.set(n),{read:e.length,written:n.length}});var x=0,Wt,Ht,l;function Gt(e,t){return Ht=e,l=e.exports,Wt=t,U=null,$=null,l.__wbindgen_start(),l}async function Jt(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{let r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function G(e){if(l!==void 0)return l;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL("udf_bg.wasm",import.meta.url));let t=Mt();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await Jt(await e,t);return Gt(n,r)}var rt=null;function Vt(e){return rt||(rt=(async()=>{if(e!==void 0)return G(e);if(typeof process<"u"&&process.versions?.node){let n="node:fs/promises",{readFile:r}=await import(n),o=await r(new URL("./wasm/udf_bg.wasm",import.meta.url));return G({module_or_path:o})}let{default:t}=await import("./udf_bg-B37GKRIH.js");return G({module_or_path:t})})()),rt}function J(){return Vt()}function V(e){return(t,n)=>e.read(t,n)}function ot(e){return(t,n)=>e.write(t,n)}function X(e){return()=>e.getSize()}function it(e){return t=>e.setSize?e.setSize(t):Promise.resolve()}async function St(e){await J();let t=JSON.parse(await xt(V(e),X(e)));if(t.error)throw new Error(t.error);let n=null;if(t.iuvdPayload)try{n=JSON.parse(t.iuvdPayload)}catch{}let r=null,o=t.files.find(s=>s.name===".i2o-manifest.json");if(o&&o.extents.length>0&&o.extents[0].type===Q){let s=o.extents[0].position,i=await e.read((t.partitionStartSector+s)*2048,o.totalSize);try{r=JSON.parse(new TextDecoder().decode(i))}catch{}}return{totalSectors:t.totalSectors,partitionStartSector:t.partitionStartSector,partitionLength:t.partitionLength,volumeName:t.volumeName,files:t.files,manifest:r,iuvdPayload:n,rootIcbSector:t.rootIcbSector,rootDataSector:t.rootDataSector,rootDataLength:t.rootDataLength,rootDataSectors:t.rootDataSectors,vdsStartSector:t.vdsStartSector,partitionDescVdsSector:t.partitionDescVdsSector}}function pe(e){let t=[],n=0;for(let r of e.extents)r.type===mt&&t.push({offset:n,length:r.length}),n+=r.length;return t}function It(e){let t=[],n=0;for(let r of e.extents)r.type===Q&&t.push({offset:n,length:r.length,imageSector:r.position}),n+=r.length;return t}async function me(e,t,n,r,o){return await J(),await ht(V(e),ot(e),X(e),it(e),n,r,o),St(e)}async function we(e,t,n,r,o,s=0){await J();let i=new Date,a=!!(o&&o.length>0);return await yt(V(e),ot(e),X(e),it(e),n,r,a?o:new Uint8Array(0),a,s,i.getFullYear(),i.getMonth()+1,i.getDate(),i.getHours(),i.getMinutes(),i.getSeconds(),-i.getTimezoneOffset()),St(e)}var Y=1<<20,k=5*Y,At=5*1024*Y,st=1e4,at=8*Y,Zt=2048;function Ie(e,t,n=Math.max(16*Y,Math.ceil(e/(st-500)))){let r=[...t].filter(c=>c.len>0).sort((c,u)=>c.at-u.at),o=[];for(let c of r){let u=o[o.length-1];u&&c.at<u.at+u.len||(u&&u.at+u.len===c.at&&u.key===c.key&&u.offset+u.len===c.offset?u.len+=c.len:o.push({...c}))}let s=[],i=0;for(let c of o.filter(u=>u.len>=k))c.at>i&&s.push({at:i,len:c.at-i}),s.push({at:c.at,len:c.len,copy:c}),i=c.at+c.len;i<e&&s.push({at:i,len:e-i});let a=c=>c.reduce((u,_)=>{let p=u[u.length-1];return p&&!p.copy&&!_.copy?p.len+=_.len:u.push({..._}),u},[]);for(let c=!0;c;){c=!1,s=a(s);for(let u=0;u<s.length-1;u++){let _=s[u];if(_.len>=k)continue;let p=k-_.len,w=s[u+1],d=s[u-1];if(_.copy){delete _.copy,c=!0;break}w?.copy&&w.len-p>=k?(_.len+=p,w.at+=p,w.len-=p,w.copy={...w.copy,at:w.at,len:w.len,offset:w.copy.offset+p}):d?.copy&&d.len-p>=k?(d.len-=p,d.copy={...d.copy,len:d.len},_.at-=p,_.len+=p):w?.copy?delete w.copy:d?.copy&&delete d.copy,c=!0;break}}let g=[];for(let c of s){let u=c.copy?Math.min(At,Math.max(n,k)):n;for(let _=c.at,p=c.at+c.len;_<p;){let w=Math.min(u,p-_);p-(_+w)>0&&p-(_+w)<k&&(w=p-_<=At?p-_:w-k),g.push(c.copy?{kind:"copy",at:_,len:w,key:c.copy.key,offset:c.copy.offset+(_-c.at)}:{kind:"upload",at:_,len:w}),_+=w}}if(g.length>st)throw new Error(`the image needs ${g.length} pieces (S3 allows ${st})`);return g}function Ae(e,t,n,r){let o=[...r].sort((a,g)=>a.offset-g.offset),s=[],i=0;for(let a of o){let g=Math.min(a.offset,t);g>i&&s.push({at:i,len:g-i,key:e,offset:i}),i=Math.max(i,a.offset+a.length)}return i<Math.min(t,n)&&s.push({at:i,len:Math.min(t,n)-i,key:e,offset:i}),s}async function Ee(e,t,n,r,o){let s=[];for(let i of t.files)for(let a of It(i)){let g=(t.partitionStartSector+a.imageSector)*Zt;for(let c=a.offset;c<a.offset+a.length;){let u=Math.min(a.offset+a.length,(Math.floor(c/at)+1)*at),_=g+(c-a.offset);s.push(o?.(_,u-c)??[Yt("sha256").update(await e.read(_,u-c)).digest("hex"),_,u-c]),r?.(u-c),c=u}}return{v:1,block:at,size:n,blocks:s}}function ve(e,t){let n=new Map;for(let o of t)for(let[s,i,a]of o.index.blocks)n.set(`${s}:${a}`,{key:o.key,offset:i});let r=[];for(let[o,s,i]of e.blocks){let a=n.get(`${o}:${i}`);a&&r.push({at:s,len:i,key:a.key,offset:a.offset})}return r}var Et=(e,t)=>`${K().supabaseUrl}/functions/v1/${e}${t}`;async function ut(e,t,n={}){let r=await pt();if(!r)throw new Error("not signed in to conform.tools \u2014 run account_login");let o=await fetch(Et(e,t),{method:n.method??(n.body?"POST":"GET"),headers:{authorization:`Bearer ${r}`,apikey:K().anonKey,...n.body?{"content-type":"application/json"}:{}},...n.body?{body:JSON.stringify(n.body)}:{},signal:AbortSignal.timeout(2e4)}),s=await o.text();if(!o.ok){let i=s;try{let a=JSON.parse(s);i=a.error?.message??a.message??a.error??s}catch{}throw o.status===404&&/Requested function was not found/i.test(String(i))?new Error(`${e} isn't deployed on ${new URL(Et(e,t)).host}: this server doesn't have that feature yet (an older server, or a staging/production mismatch)`):new Error(`${n.method??"GET"} ${t}: ${o.status} ${i}`)}return s?JSON.parse(s):{}}function Te(e,t="org"){let n=`/v1/sessions/${e}/storage/multipart`,r=(o,s,i)=>ut("v1-sessions",o,{body:s,method:i});return{start:async o=>String((await r(`${n}/start`,{key:o,content_type:"application/x-iso9660-image"})).upload_id),partUrls:async(o,s,i,a)=>(await r(`${n}/${s}/part-urls`,{key:o,first_part:i,count:a})).parts,copyPart:async(o,s,i,a)=>String((await r(`${n}/${s}/copy-part`,{key:o,part_number:i,source_ref:{scheme:t,bucket:"i2o",key:a.key},byte_range:{offset:a.offset,length:a.length}})).etag),complete:async(o,s,i)=>{await r(`${n}/${s}/complete`,{key:o,parts:i})},abort:async(o,s)=>{await r(`${n}/${encodeURIComponent(s)}?key=${encodeURIComponent(o)}`,void 0,"DELETE")},readUrl:async o=>String((await r(`/v1/sessions/${e}/download-url`,{storage_path:o})).download_url)}}async function ct(e,t,n=4){for(let r=1;;r++)try{return await t()}catch(o){if(r>=n)throw new Error(`${e} failed after ${n} tries: ${o instanceof Error?o.message:o}`);await new Promise(s=>setTimeout(s,500*2**r))}}async function Pe(e,t,n,r,o={}){let s=o.fetchFn??fetch,i=await e.start(t),a=n.reduce((d,b)=>d+b.len,0),g=new Array(n.length),c=0,u=0,_=new Map,p=async d=>(_.has(d)||(await e.partUrls(t,i,d+1,Math.min(100,n.length-d))).forEach((F,A)=>_.set(d+A,F)),_.get(d)),w=async d=>{let b=n[d];if(b.kind==="copy")g[d]=await ct(`copy piece ${d+1}`,()=>e.copyPart(t,i,d+1,{key:b.key,offset:b.offset,length:b.len}));else{let F=await r(b.at,b.len);g[d]=await ct(`upload piece ${d+1}`,async()=>{let A=await p(d),v=await s(A.upload_url,{method:A.method,headers:A.headers,body:F,signal:o.signal});if(!v.ok)throw _.delete(d),new Error(`${v.status} ${(await v.text()).slice(0,200)}`);let W=v.headers.get("etag");if(!W)throw new Error("the bucket returned no ETag (expose it in the bucket's CORS / response headers)");return W})}c+=b.len,o.onProgress?.(c,a)};try{await Promise.all(Array.from({length:Math.min(6,n.length)},async()=>{for(;u<n.length;)o.signal?.throwIfAborted(),await w(u++)})),await ct("complete",()=>e.complete(t,i,g.map((d,b)=>({part_number:b+1,etag:d}))))}catch(d){throw await e.abort(t,i).catch(()=>{}),d}return{uploaded:n.filter(d=>d.kind==="upload").reduce((d,b)=>d+b.len,0),copied:n.filter(d=>d.kind==="copy").reduce((d,b)=>d+b.len,0),pieces:n.length}}function ke(e){let t=qt(e,"r");return{read:async(n,r)=>{let o=new Uint8Array(r);return await(await t).read(o,0,r,n),o},close:async()=>{await(await t).close()}}}var ft="local",Tt=/^[A-Za-z0-9_-]{1,64}$/,I=e=>{if(!Tt.test(e))throw new j("invalid_args",`bad project_id '${e}'`);return y(R(),"projects",e)},lt=(e,t={})=>ut("v1-projects",e,t),Pt=e=>Number(/: (\d{3}) /.exec(String(e?.message))?.[1]??0);async function kt(e){let t="",n={base:null,by:null};try{t=await S(y(I(e),"CONTEXT.md"))}catch{}try{n=JSON.parse(await S(y(I(e),"context.json")))}catch{}return{text:t,meta:n}}async function dt(e,t,n){await P(I(e)),await T(y(I(e),"CONTEXT.md"),t),await T(y(I(e),"context.json"),JSON.stringify(n))}var _t=async(e,t)=>(await dt(e,t.context,{base:t.context_updated_at,by:t.context_updated_by_name??null}),{text:t.context,updated_at:t.context_updated_at,updated_by:t.context_updated_by_name??null});async function De(e){I(e);let t=await kt(e);if(e===ft)return{text:t.text,updated_at:null,updated_by:null};if(t.meta.pending)try{return await vt(e,t.text,t.meta.base)}catch(n){if(!(n instanceof j&&n.code==="context_conflict"))return{text:t.text,updated_at:t.meta.base,updated_by:t.meta.by,offline:!0,pending:!0};let r=n.data?.current??{context:"",context_updated_at:null},o=`${r.context.trimEnd()}
|
|
4
4
|
|
|
5
5
|
## Saved offline on this machine (merge into the notes above)
|
|
6
6
|
|