notemend 0.1.27 → 0.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
- import{readFileSync as lt,existsSync as Y,statSync as jt,readdirSync as Nt,watch as Ot}from"node:fs";import{mask as kt}from"../store/mask.mjs";import{join as _,isAbsolute as $t}from"node:path";import{isIP as ut}from"node:net";import{pathToFileURL as At}from"node:url";import{openStore as It,retry as Bt,retryThread as Et,CABINET as ft,session as tt}from"../store/cloud.mjs";import{mentionsIn as Tt,cleanAssignee as et,cleanEmoji as bt,MAX_REACTIONS as Pt,STAGES as dt,toAgent as nt}from"../store/thread.mjs";import{fileFrame as rt,react as Ct,shotName as Dt}from"../store/comments.mjs";import{stateOf as _t}from"../store/status.mjs";import{CATEGORIES as Lt,categoryOf as Ft}from"../store/categories.mjs";import{BREAKPOINTS as Mt,DEVICES as Rt,ICONS as mt,SHELLS as pt,BROWSERS as gt}from"../presets.mjs";const zt={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",webm:"video/webm",m4a:"audio/mp4",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},ht=t=>t.split(".").slice(0,2).map(Number).reduce((e,f)=>e*100+(Number.isNaN(f)?9999:f),0),Ht=(t,e)=>{try{const p=lt($t(e)?e:_(t,e),"utf8").match(/title="([^"]+)"|\btitle:\s*["'`]([^"'`]+)["'`]/);return(p?.[1]??p?.[2])?.split("\u2014").pop()?.trim()||null}catch{return null}};function ie(t){const e=["app","src/app"].map(c=>_(/* turbopackIgnore: true */ t,c)).find(Y),f=[],p=(c,y)=>{for(const l of Nt(c,{withFileTypes:!0})){const u=l.name;if(l.isDirectory()){if(/^[_@]|^\(\./.test(u))continue;p(_(c,u),/^\(.+\)$/.test(u)?y:[...y,u])}else/^page\.(jsx?|tsx?|mdx?)$/.test(u)&&f.push({origin:"project",type:"page",pattern:"/"+y.join("/"),entrypoint:_(c,u)})}};return e&&p(e,[]),f}const Gt=t=>t[0].toUpperCase()+t.slice(1).replace(/[-_]+/g," ");function Jt({root:t,options:e,routes:f}){const p=e.pages??{},c=(n,w,L)=>({route:n,name:w,label:w.replace(/^[\d.]+[A-Z]?\.\s*/,""),group:L}),y=f.filter(n=>n.origin==="project"&&n.type==="page"&&!n.pattern.includes("[")).map(n=>({route:n.pattern.replace(/\/+$/,"")||"/",entrypoint:n.entrypoint})),l=new Set(y.map(n=>n.route)),u=[...y,...Object.keys(p).filter(n=>!l.has(n)).map(n=>({route:n}))],T={};for(const{route:n}of u){const w=n.split("/")[1];w&&(T[w]=(T[w]||0)+1)}const B=n=>{const w=n.split("/")[1];return w&&T[w]>1?Gt(w):"Pages"},C=e.groups?()=>e.groups[e.groups.length-1]:B,E=u.map(({route:n,entrypoint:w})=>{const[L,U]=p[n]??[];return c(n,L??(w&&Ht(t,w))??n,U??C(n))}),H=e.groups??[...new Set([...Object.values(p).map(([,n])=>n).filter(Boolean),"Pages",...E.map(n=>n.group).sort()])],G=E.sort((n,w)=>H.indexOf(n.group)-H.indexOf(w.group)||ht(n.name)-ht(w.name)||n.route.localeCompare(w.route)),J=(e.breakpoints??Mt).map(n=>({id:n.id,label:n.label,min:n.min,ideal:n.ideal,max:Number.isFinite(n.max)?n.max:null,icon:n.icon??mt[n.id]??mt.desktop})),Z=(e.devices??Rt).filter(n=>n.w>0&&n.h>0&&pt.includes(n.shell)&&gt.includes(n.browser)?!0:(console.warn(`[notemend] device "${n.id}" skipped: it needs w and h, shell (${pt.join(", ")}) and browser (${gt.join(", ")})${n.frame?"; `frame` pictures were replaced by shell + browser in 0.3":""}`),!1));return{pages:G,groups:H.filter(n=>G.some(w=>w.group===n)),breakpoints:J,devices:Z,categories:Lt,sanity:!!e.sanity,shortcuts:e.shortcuts!==!1,ignore:e.ignore??[],grid:{container:"container",grid:"grid",columns:12,...e.grid},zIndex:e.zIndex??2000000020}}const Ut=t=>{const e=_(t,"notemend.config.mjs");let f=0,p={};return async()=>{if(!Y(e))return{};const c=jt(e).mtimeMs;if(c===f)return p;f=c;try{const{default:y,...l}=await import(/* webpackIgnore: true */ /* turbopackIgnore: true */ `${At(e).href}?t=${c}`);p={...l,...y}}catch(y){console.warn(`[notemend] notemend.config.mjs: ${y.message}`)}return p}},Wt=t=>{const e=String(t.headers.host||"").toLowerCase(),f=e.startsWith("[")?e.slice(1,e.indexOf("]")):e.replace(/:\d+$/,"");return f.includes(":")?ut(f)===6:!f||!f.includes(".")||ut(f)===4||/\.(localhost|local|test|internal|lan|home\.arpa)$/.test(f)},x=(t,e)=>String(t??"").replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,e),Vt=t=>({route:x(t.route,500),text:String(t.text??"").slice(0,1e4),selector:x(t.selector,2e3),rx:Number.isFinite(t.rx)?t.rx:0,ry:Number.isFinite(t.ry)?t.ry:0,label:x(t.label,200),ctx:x(t.ctx,120),breakpoint:x(t.breakpoint,40),browser:x(t.browser,80),device:x(t.device,80),tag:x(t.tag,40),classes:Array.isArray(t.classes)?t.classes.slice(0,20).map(e=>x(e,80)):[],nth:Number.isInteger(t.nth)?t.nth:null,category:x(t.category,40),...["urgent","high","normal","low"].includes(t.priority)?{priority:t.priority}:{},...t.shared===!0?{shared:!0}:{},...Number.isInteger(t.from?.id)&&t.from.id>0?{from:{id:t.from.id}}:{},viewport:t.viewport&&Number.isFinite(t.viewport.w)&&Number.isFinite(t.viewport.h)?{w:t.viewport.w,h:t.viewport.h}:null,...et(t.assignee)?{assignee:et(t.assignee)}:{},...dt.includes(t.stage)?{stage:t.stage}:{},...typeof t.host=="string"&&/^[a-z0-9.-]{1,120}(:\d{1,5})?$/i.test(t.host)?{host:t.host.toLowerCase()}:{},...Array.isArray(t.logs)&&t.logs.length?{logs:t.logs.slice(-20).map(e=>({at:x(e?.at,30),kind:["console","error","rejection","network"].includes(e?.kind)?e.kind:"console",text:kt(x(e?.text,500))})).filter(e=>e.text)}:{},...t.suggest&&typeof t.suggest.from=="string"&&typeof t.suggest.to=="string"&&t.suggest.to.trim()?{suggest:{from:t.suggest.from.slice(0,2e3),to:t.suggest.to.slice(0,2e3)}}:{}}),Kt=t=>{const e={};if((t.status==="open"||t.status==="done")&&(e.status=t.status),t.status==="open"&&Object.assign(e,{reopenedAt:new Date().toISOString(),reopenedBy:"you"}),"doneBy"in t&&(e.doneBy=t.doneBy==="you"?"you":null),typeof t.category=="string"&&(e.category=Ft(t.category).id),"priority"in t&&(e.priority=["urgent","high","normal","low"].includes(t.priority)?t.priority:null),typeof t.shared=="boolean"&&(e.shared=t.shared||null),t.client===!1&&(e.client=null),"assignee"in t&&(e.assignee=et(t.assignee)),"stage"in t&&(e.stage=dt.includes(t.stage)?t.stage:null),typeof t.archived=="boolean"&&(e.archived=t.archived),t.move&&typeof t.move=="object"&&typeof t.move.selector=="string"){const f=t.move,p=c=>Number.isFinite(c)?Math.min(1,Math.max(0,c)):.5;Object.assign(e,{selector:x(f.selector,2e3),rx:p(f.rx),ry:p(f.ry),label:x(f.label,200),ctx:x(f.ctx,120),tag:x(f.tag,40),classes:Array.isArray(f.classes)?f.classes.slice(0,20).map(c=>x(c,80)):[],nth:Number.isInteger(f.nth)?f.nth:null})}return e},ot=t=>{const e=t.headers.origin;if(!e)return!1;try{return new URL(e).host!==t.headers.host}catch{return!0}};function Xt({root:t,options:e,routes:f,open:p=()=>It(t),crossOrigin:c=!1}){const y=Ut(t),l=(o,h=200)=>({status:h,type:"application/json",body:JSON.stringify(o)}),u=(o,h)=>({status:o,type:"text/plain; charset=utf-8",body:h}),T=async o=>{const h=await o.body();if(h.length>45e5)throw Object.assign(new Error("too large"),{status:413});try{return h.length?JSON.parse(h.toString("utf8")):{}}catch{throw Object.assign(new Error("not JSON"),{status:400})}},B=async(o,h,r)=>{const s=async d=>{const a=await h(d);if(a.status>=400)throw Object.assign(new Error("not written"),{out:a});return a};try{if(o.cloud)return await(r!=null&&o.thread?Et(o,r,s):Bt(o,s));const d=o.load(),a=await s(d);return o.save(d),a}catch(d){if(d.out)return d.out;throw d}finally{E=null,L++,U()&&V()}},C=new Set;let E=null,H=0,G=!1,J=!1,Z=null,n=null,w=0,L=0;const U=()=>C.size>0||Date.now()-w<3e4,V=async()=>{if(c)return;if(G){J=!0;return}G=!0,clearTimeout(Z);let o=!1;try{const h=await p();o=!!h.cloud;const r=L,s=h.version?String(await h.version()):null;if(r!==L)J=!0;else if(H=Date.now(),s!==E){E=s;for(const d of C)d(s)}if(!o&&!n&&U()&&Y(_(t,"feedback")))try{n=Ot(_(t,"feedback"),(d,a)=>{String(a).startsWith("comments.json")&&V()}),n.on("error",()=>{n?.close(),n=null})}catch{n=null}}catch{}if(G=!1,J)return J=!1,V();U()?Z=setTimeout(V,o?1500:n?1e3:250):(n?.close(),n=null)},yt=o=>(C.add(o),E!=null&&o(E),V(),()=>{C.delete(o),w=Date.now()}),wt=()=>U()&&E!=null&&Date.now()-H<3e3?E:null,st=new Map,vt=async(o,h)=>{if(o.method!=="GET"&&!c&&ot(o))return u(403,"Cross-origin write refused");const r=await p();if(o.method==="GET"){const i=h.searchParams.get("route"),A=h.searchParams.get("since"),I=wt();if(A!=null&&r.version&&A===(I??String(await r.version())))return{status:204,type:"text/plain",body:""};const R=h.searchParams.get("open")==="1",k=`${i??""}|${R}`,b=I!=null&&st.get(k);if(b&&b.v===I)return b.res;const $=await r.load(R?{open:!0}:void 0);let N=i?$.comments.filter(W=>W.route===i):$.comments;R&&(N=N.filter(W=>_t(W)!=="done")),N=N.map(({logs:W,...z})=>z);const D=r.versionOf?r.versionOf($):null,Q=l({version:D==null?null:String(D),comments:N,listening:$.listening??null,turbo:$.turbo??null});return!c&&D!=null&&st.set(k,{v:String(D),res:Q}),Q}const s=o.method==="DELETE"?null:await T(o);let d=null,a=null;const F=o.method==="POST"||!!s?.reply?.trim?.(),M=r.cloud&&s?(F?r.people():r.me().then(i=>({me:i,team:[]}))).then(i=>{d=i,a=i.me}).catch(i=>i):Promise.resolve(),at=async()=>{const i=await M;if(i instanceof Error)throw i},it=i=>{if(a&&i){i.by=a.email,i.byName=a.name;const A=Tt(i.text,d.team.filter(I=>I.email!==a.email));A.length&&(i.mentions=A)}return i};if(o.method==="POST"){const{image:i,images:A,before:I,...R}=s,k=Vt(R);return k.text.trim()?/^\/(?![\/\\])/.test(k.route)?B(r,async b=>{await at(),d?.client&&(k.client=!0,nt(k.assignee)&&delete k.assignee,k.stage==="approved"&&delete k.stage);const $=it(r.add(b,k));a&&nt($.assignee)&&($.handedBy=a.email);for(const N of[].concat(A??i??[]))await r.attach(b,$.id,N);return await rt(r,b,$.id,I,"before"),l($,201)}):l({error:"route must be a path"},400):l({error:"empty comment"},400)}if(o.method==="PATCH"){const i=s;if(i.turbo==="on"||i.turbo==="off")return B(r,async g=>(g.turbo={paused:i.turbo==="off",at:new Date().toISOString()},l({turbo:g.turbo})));if(Array.isArray(i.push)||Array.isArray(i.unpush)){const g=j=>(Array.isArray(j)?j:[]).map(Number).filter(m=>Number.isInteger(m)&&m>0).slice(0,500);return B(r,async j=>{const m=new Set(j.turbo?.push?.ids??[]);for(const P of g(i.push))m.add(P);for(const P of g(i.unpush))m.delete(P);const O=P=>j.comments.some(ct=>ct.id===P&&ct.status!=="done"),K=new Set((j.turbo?.batch?.ids??[]).filter(O)),X=!K.size;for(const P of g(i.push))K.add(P);for(const P of g(i.unpush))K.delete(P);const q=new Date().toISOString();return j.turbo={...j.turbo??{paused:!0},push:{at:q,ids:[...m]},batch:{at:X?q:j.turbo?.batch?.at??q,ids:[...K]}},l({turbo:j.turbo})})}const{id:A,reply:I,image:R,images:k,removeImage:b,uploaded:$,edit:N,unsay:D,before:Q,after:W,react:z,...xt}=i,v=Number(A);if(!Number.isInteger(v))return l({error:"bad id"},400);if(z){const g=bt(z.emoji),j=typeof z.at=="string"&&z.at?z.at:null;return g?r.cloud?r.react(v,j,g).then(l,m=>l({error:m.message},m.status>=400&&m.status<500?m.status:500)):B(r,async m=>{const O=Ct(m,v,j,g,"you");return O===!1?l({error:`${Pt} kinds of reaction at most`},400):O?l(O):l({error:`no message to react to in #${v}`},404)},v):l({error:"not an emoji"},400)}const S=Kt(xt);return B(r,async g=>{if(await at(),N){const m=g.comments.find(X=>X.id===Number(v)),O=N.at?m?.replies?.find(X=>X.at===N.at):m;if(a&&O?.by&&O.by!==a.email||!(N.text?.trim?.()&&r.edit(g,v,N.at??null,N.text.trim().slice(0,1e4))))return l({error:`no message of yours to edit in #${v}`},404)}if(typeof D=="string"){const m=g.comments.find(O=>O.id===v)?.replies?.find(O=>O.at===D);return!m||a&&m.by&&m.by!==a.email||!r.unsay(g,v,D)?l({error:`no reply of yours to delete in #${v}`},404):l(g.comments.find(O=>O.id===v))}I?.trim?.()&&it(r.reply(g,v,"you",I.trim().slice(0,1e4))?.replies.at(-1));for(const m of[].concat(k??R??[]))await r.attach(g,v,m);for(const m of[].concat($??[]))if(r.adopt&&!await r.adopt(g,v,m))return l({error:`${m} did not arrive`},400);for(const m of[].concat(b||[]))await r.detach(g,v,m);if(await rt(r,g,v,Q,"before"),await rt(r,g,v,W,"after"),a&&S.status==="done"&&Object.assign(S,{confirmedBy:a.email,confirmedAt:new Date().toISOString()}),a&&S.status==="open"&&Object.assign(S,{confirmedBy:null,confirmedAt:null,reopenedBy:a.email}),"archived"in S){const m=S.archived;delete S.archived,Object.assign(S,m?{archivedAt:new Date().toISOString(),archivedBy:a?.email??null}:{archivedAt:null,archivedBy:null})}S.status==="open"&&Object.assign(S,{archivedAt:null,archivedBy:null}),a&&S.stage==="review"&&(S.stageBy=a.email),a&&"assignee"in S&&(S.handedBy=nt(S.assignee)?a.email:null);const j=Object.keys(S).length||!I?r.patch(g,v,S):g.comments.find(m=>m.id===Number(v));return j?l(j):l({error:`no comment #${v}`},404)},v)}if(o.method==="DELETE"){const i=Number(h.searchParams.get("id"));return B(r,async A=>await r.remove(A,i)?l({ok:!0,id:i}):l({error:`no comment #${i}`},404))}return u(405,"Method not allowed")},St=(o,h)=>{const r=h.replace(/^.*[/\\]/,""),s=r.split(".").pop()?.toLowerCase()??"",d=zt[s]??(Dt(r)?"application/octet-stream":null);if(!/^[\w.-]+$/.test(r)||!d)return u(400,"Bad name");const a=_(o,r);return Y(a)?{status:200,type:d,body:lt(a)}:u(404,"Not found")};return async o=>{const h=new URL(o.url,"http://devbar"),r=h.pathname.slice(10);if(!c&&!Wt(o))return u(403,"Notemend answers local addresses only");try{if(r==="config"){const s=Jt({root:t,options:{...await y(),...e},routes:f()}),d=await p();return d.cloud&&Object.assign(s,await d.people().catch(a=>{if(a.said)throw a;return{}})),(d.cloud||await tt().catch(()=>null))&&(s.voice=!0),l(s)}if(r==="transcribe"&&o.method==="POST"){if(!c&&ot(o))return u(403,"Cross-origin write refused");const s=await p(),d=s.cloud?await s.token():(await tt().catch(()=>null))?.access_token;if(!d)return u(401,"Voice replies need Notemend \u2014 run `npx notemend login`.");const{audio:a}=await T(o),F=/^data:(audio\/(?:webm|mp4))(?:;[\w=.-]+)*;base64,(.+)$/s.exec(String(a||""));if(!F)return u(400,"Not a recording");const M=await fetch(`${ft}/api/transcribe`,{method:"POST",body:Buffer.from(F[2],"base64"),headers:{authorization:`Bearer ${d}`,"content-type":F[1]}});return{status:M.status,type:"application/json",body:await M.text()}}if(r==="translate"&&o.method==="POST"){if(!c&&ot(o))return u(403,"Cross-origin write refused");const s=await p(),d=s.cloud?await s.token():(await tt().catch(()=>null))?.access_token;if(!d)return u(401,"Translating needs Notemend \u2014 run `npx notemend login`.");const{text:a,to:F}=await T(o),M=await fetch(`${ft}/api/translate`,{method:"POST",body:JSON.stringify({text:a,to:F}),headers:{authorization:`Bearer ${d}`,"content-type":"application/json"}});return{status:M.status,type:"application/json",body:await M.text()}}if(r==="comments")return await vt(o,h);if(r==="events"&&!c)return{status:200,type:"text/event-stream",body:"",stream:yt};if(r==="image"){const s=await p(),d=(h.searchParams.get("name")||"").replace(/^.*[/\\]/,"");return s.cloud&&/^[\w.-]+$/.test(d)&&await s.fetchImage(d).catch(()=>null),St(s.imageDir,d)}return u(404,"Not found")}catch(s){return s.status===400||s.status===413?u(s.status,s.message):s.said?u(s.status,s.said):s.status===403?u(403,String(s.message).replace(/^notemend: /,"").replace(/ \(403\)$/,"")):(console.error("[notemend]",s),u(500,"Something went wrong on our side. Try again in a moment."))}}}function ce(t){const e=Xt(t),f=p=>new Promise((c,y)=>{const l=[];p.on("data",u=>l.push(u)),p.on("end",()=>c(Buffer.concat(l))),p.on("error",y)});return async function(c,y,l){if(!c.url||!c.url.startsWith("/__devbar/"))return l();const u=await e({method:c.method,url:c.url,headers:c.headers,body:()=>f(c)});if(u.stream){y.writeHead(200,{"content-type":u.type,"cache-control":"no-store",connection:"keep-alive"}),y.write(`retry: 1000
1
+ import{readFileSync as dt,existsSync as et,statSync as bt,readdirSync as Bt,watch as It}from"node:fs";import{mask as Tt}from"../store/mask.mjs";import{join as z,isAbsolute as Et}from"node:path";import{isIP as mt}from"node:net";import{pathToFileURL as Ct}from"node:url";import{openStore as Pt,retry as _t,retryThread as Dt,CABINET as rt,session as ot}from"../store/cloud.mjs";import{mentionsIn as Lt,clashOf as Ft,cleanAssignee as st,cleanBox as Ht,cleanEmoji as Mt,cut as Z,MAX_REACTIONS as Rt,STAGES as pt,threadOf as zt,toAgent as at}from"../store/thread.mjs";import{fileFrame as it,react as Gt,shotName as gt}from"../store/comments.mjs";import{stateOf as Jt}from"../store/status.mjs";import{CATEGORIES as Ut,categoryOf as Wt}from"../store/categories.mjs";import{BREAKPOINTS as Vt,DEVICES as Kt,ICONS as ht,SHELLS as yt,BROWSERS as wt}from"../presets.mjs";const Xt={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",webm:"video/webm",m4a:"audio/mp4",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},vt=t=>t.split(".").slice(0,2).map(Number).reduce((e,c)=>e*100+(Number.isNaN(c)?9999:c),0),xt=(t,e)=>{try{const c=dt(Et(e)?e:z(t,e),"utf8"),u=c.match(/\bmetadata\b[^=]*=\s*\{[^}]*?\btitle:\s*["'`]([^"'`$]+)["'`]/)??c.match(/<title>([^<{]+)<\/title>/)??(/\.[jt]sx?$/.test(e)?c.match(/<h1\b[^>]*>\s*([^<{]+?)\s*<\/h1>/):c.match(/title="([^"]+)"|\btitle:\s*["'`]([^"'`]+)["'`]/));return(u?.[1]??u?.[2])?.trim()||null}catch{return null}},St=t=>t.split(/\s+[—–|]\s+/).map(e=>e.trim()).filter(Boolean),Zt=(t,e,c)=>{const u=xt(t,e);if(!u)return null;const s=St(u);return(c?s.filter(m=>m!==c)[0]:s.pop())||null},Qt=t=>{const e={};for(const u of t){const s=u?St(u):[];if(s.length>1)for(const m of new Set([s[0],s.at(-1)]))e[m]=(e[m]||0)+1}const[c]=Object.entries(e).sort((u,s)=>s[1]-u[1]);return c?.[1]>1?c[0]:void 0};function ge(t){const e=["app","src/app"].map(s=>z(/* turbopackIgnore: true */ t,s)).find(et),c=[],u=(s,m)=>{for(const f of Bt(s,{withFileTypes:!0})){const l=f.name;if(f.isDirectory()){if(/^[_@]|^\(\./.test(l))continue;u(z(s,l),/^\(.+\)$/.test(l)?m:[...m,l])}else/^page\.(jsx?|tsx?|mdx?)$/.test(l)&&c.push({origin:"project",type:"page",pattern:"/"+m.join("/"),entrypoint:z(s,l)})}};return e&&u(e,[]),c}const jt=t=>t[0].toUpperCase()+t.slice(1).replace(/[-_]+/g," ");function Yt({root:t,options:e,routes:c}){const u=e.pages??{},s=(n,w,H)=>({route:n,name:w,label:w.replace(/^[\d.]+[A-Z]?\.\s*/,""),group:H}),m=c.filter(n=>n.origin==="project"&&n.type==="page"&&!n.pattern.includes("[")).map(n=>({route:n.pattern.replace(/\/+$/,"")||"/",entrypoint:n.entrypoint})),f=new Set(m.map(n=>n.route)),l=[...m,...Object.keys(u).filter(n=>!f.has(n)).map(n=>({route:n}))],C={};for(const{route:n}of l){const w=n.split("/")[1];w&&(C[w]=(C[w]||0)+1)}const B=n=>{const w=n.split("/")[1];return w&&C[w]>1?jt(w):"Pages"},F=e.groups?()=>e.groups[e.groups.length-1]:B,_=Qt(l.map(({entrypoint:n})=>n&&xt(t,n))),Q=l.map(({route:n,entrypoint:w})=>{const[H,U]=u[n]??[];return s(n,H??(w&&Zt(t,w,_))??(n==="/"?"Home":jt(n.split("/").pop())),U??F(n))}),G=e.groups??[...new Set([...Object.values(u).map(([,n])=>n).filter(Boolean),"Pages",...Q.map(n=>n.group).sort()])],J=Q.sort((n,w)=>G.indexOf(n.group)-G.indexOf(w.group)||vt(n.name)-vt(w.name)||n.route.localeCompare(w.route)),Y=(e.breakpoints??Vt).map(n=>({id:n.id,label:n.label,min:n.min,ideal:n.ideal,max:Number.isFinite(n.max)?n.max:null,icon:n.icon??ht[n.id]??ht.desktop})),I=(e.devices??Kt).filter(n=>n.w>0&&n.h>0&&yt.includes(n.shell)&&wt.includes(n.browser)?!0:(console.warn(`[notemend] device "${n.id}" skipped: it needs w and h, shell (${yt.join(", ")}) and browser (${wt.join(", ")})${n.frame?"; `frame` pictures were replaced by shell + browser in 0.3":""}`),!1));return{pages:J,groups:G.filter(n=>J.some(w=>w.group===n)),breakpoints:Y,devices:I,categories:Ut,sanity:!!e.sanity,shortcuts:e.shortcuts!==!1,ignore:e.ignore??[],grid:{container:"container",grid:"grid",columns:12,...e.grid},zIndex:e.zIndex??2000000020}}const qt=t=>{const e=z(t,"notemend.config.mjs");let c=0,u={};return async()=>{if(!et(e))return{};const s=bt(e).mtimeMs;if(s===c)return u;c=s;try{const{default:m,...f}=await import(/* webpackIgnore: true */ /* turbopackIgnore: true */ `${Ct(e).href}?t=${s}`);u={...f,...m}}catch(m){console.warn(`[notemend] notemend.config.mjs: ${m.message}`)}return u}},te=t=>{const e=String(t.headers.host||"").toLowerCase(),c=e.startsWith("[")?e.slice(1,e.indexOf("]")):e.replace(/:\d+$/,"");return c.includes(":")?mt(c)===6:!c||!c.includes(".")||mt(c)===4||/\.(localhost|local|test|internal|lan|home\.arpa)$/.test(c)},O=(t,e)=>Z(String(t??"").replace(/[\u0000-\u001f\u007f]+/g," ").trim(),e),ee=t=>({route:O(t.route,500),text:Z(t.text,1e4),selector:O(t.selector,2e3),rx:Number.isFinite(t.rx)?t.rx:0,ry:Number.isFinite(t.ry)?t.ry:0,label:O(t.label,200),ctx:O(t.ctx,120),breakpoint:O(t.breakpoint,40),browser:O(t.browser,80),device:O(t.device,80),tag:O(t.tag,40),classes:Array.isArray(t.classes)?t.classes.slice(0,20).map(e=>O(e,80)):[],nth:Number.isInteger(t.nth)?t.nth:null,category:O(t.category,40),...["urgent","high","normal","low"].includes(t.priority)?{priority:t.priority}:{},...t.shared===!0?{shared:!0}:{},...Number.isInteger(t.from?.id)&&t.from.id>0?{from:{id:t.from.id}}:{},viewport:t.viewport&&Number.isFinite(t.viewport.w)&&Number.isFinite(t.viewport.h)?{w:t.viewport.w,h:t.viewport.h}:null,...st(t.assignee)?{assignee:st(t.assignee)}:{},...pt.includes(t.stage)?{stage:t.stage}:{},...typeof t.host=="string"&&/^[a-z0-9.-]{1,120}(:\d{1,5})?$/i.test(t.host)?{host:t.host.toLowerCase()}:{},...Array.isArray(t.logs)&&t.logs.length?{logs:t.logs.slice(-20).map(e=>({at:O(e?.at,30),kind:["console","error","rejection","network"].includes(e?.kind)?e.kind:"console",text:Tt(O(e?.text,500))})).filter(e=>e.text)}:{},...t.suggest&&typeof t.suggest.from=="string"&&typeof t.suggest.to=="string"&&t.suggest.to.trim()?{suggest:{from:Z(t.suggest.from,2e3),to:Z(t.suggest.to,2e3)}}:{}}),ne=t=>{const e={};if((t.status==="open"||t.status==="done")&&(e.status=t.status),t.status==="open"&&Object.assign(e,{reopenedAt:new Date().toISOString(),reopenedBy:"you"}),"doneBy"in t&&(e.doneBy=t.doneBy==="you"?"you":null),typeof t.category=="string"&&(e.category=Wt(t.category).id),"priority"in t&&(e.priority=["urgent","high","normal","low"].includes(t.priority)?t.priority:null),typeof t.shared=="boolean"&&(e.shared=t.shared||null),t.client===!1&&(e.client=null),"assignee"in t&&(e.assignee=st(t.assignee)),"stage"in t&&(e.stage=pt.includes(t.stage)?t.stage:null),typeof t.archived=="boolean"&&(e.archived=t.archived),"box"in t&&(e.box=Ht(t.box)),t.move&&typeof t.move=="object"&&typeof t.move.selector=="string"){const c=t.move,u=s=>Number.isFinite(s)?Math.min(1,Math.max(0,s)):.5;Object.assign(e,{selector:O(c.selector,2e3),rx:u(c.rx),ry:u(c.ry),label:O(c.label,200),ctx:O(c.ctx,120),tag:O(c.tag,40),classes:Array.isArray(c.classes)?c.classes.slice(0,20).map(s=>O(s,80)):[],nth:Number.isInteger(c.nth)?c.nth:null})}return e},nt=t=>{const e=t.headers.origin;if(!e)return!1;try{return new URL(e).host!==t.headers.host}catch{return!0}};function re({root:t,options:e,routes:c,open:u=()=>Pt(t),crossOrigin:s=!1}){const m=qt(t),f=(i,h=200)=>({status:h,type:"application/json",body:JSON.stringify(i)}),l=(i,h)=>({status:i,type:"text/plain; charset=utf-8",body:h}),C=async i=>{const h=await i.body();if(h.length>(s?45e5:8e7))throw Object.assign(new Error("too large"),{status:413});try{return h.length?JSON.parse(h.toString("utf8")):{}}catch{throw Object.assign(new Error("not JSON"),{status:400})}},B=async(i,h,r)=>{const j=async a=>{const o=await h(a);if(o.status>=400)throw Object.assign(new Error("not written"),{out:o});return o};try{return i.cloud&&r!=null&&i.thread?await Dt(i,r,j):await _t(i,j)}catch(a){if(a.out)return a.out;throw a}finally{_=null,w++,H()&&U()}},F=new Set;let _=null,Q=0,G=!1,J=!1,Y=null,I=null,n=0,w=0;const H=()=>F.size>0||Date.now()-n<3e4,U=async()=>{if(s)return;if(G){J=!0;return}G=!0,clearTimeout(Y);let i=!1;try{const h=await u();i=!!h.cloud;const r=w,j=h.version?String(await h.version()):null;if(r!==w)J=!0;else if(Q=Date.now(),j!==_){_=j;for(const a of F)a(j)}if(!i&&!I&&H()&&et(z(t,"feedback")))try{I=It(z(t,"feedback"),(a,o)=>{String(o).startsWith("comments.json")&&U()}),I.on("error",()=>{I?.close(),I=null})}catch{I=null}}catch{}if(G=!1,J)return J=!1,U();H()?Y=setTimeout(U,i?1500:I?1e3:250):(I?.close(),I=null)},Ot=i=>(F.add(i),_!=null&&i(_),U(),()=>{F.delete(i),n=Date.now()}),Nt=()=>H()&&_!=null&&Date.now()-Q<3e3?_:null,ct=new Map,$t=async(i,h)=>{if(i.method!=="GET"&&!s&&nt(i))return l(403,"Cross-origin write refused");const r=await u();if(i.method==="GET"){const d=h.searchParams.get("route"),T=h.searchParams.get("since"),P=Nt();if(T!=null&&r.version&&T===(P??String(await r.version())))return{status:204,type:"text/plain",body:""};const V=h.searchParams.get("open")==="1",$=`${d??""}|${V}`,D=P!=null&&ct.get($);if(D&&D.v===P)return D.res;const k=await r.load(V?{open:!0}:void 0);let N=d?k.comments.filter(X=>X.route===d):k.comments;V&&(N=N.filter(X=>Jt(X)!=="done")),N=N.map(({logs:X,...K})=>K);const L=r.versionOf?r.versionOf(k):null,q=f({version:L==null?null:String(L),comments:N,listening:k.listening??null,turbo:k.turbo??null});return!s&&L!=null&&ct.set($,{v:String(L),res:q}),q}const j=i.method==="DELETE"?null:await C(i);let a=null,o=null;const M=i.method==="POST"||!!j?.reply?.trim?.()||j?.stage!==void 0,W=r.cloud&&j?(M?r.people():r.me().then(d=>({me:d,team:[]}))).then(d=>{a=d,o=d.me}).catch(d=>d):Promise.resolve(),R=async()=>{const d=await W;if(d instanceof Error)throw d},lt=d=>{if(o&&d){d.by=o.email,d.byName=o.name;const T=Lt(d.text,a.team.filter(P=>P.email!==o.email));T.length&&(d.mentions=T)}return d};if(i.method==="POST"){const{image:d,images:T,before:P,...V}=j,$=ee(V);return $.text.trim()?/^\/(?![\/\\])/.test($.route)?B(r,async D=>{await R(),a?.client&&($.client=!0,at($.assignee)&&delete $.assignee,$.stage==="approved"&&delete $.stage);const k=lt(r.add(D,$));o&&at(k.assignee)&&(k.handedBy=o.email);for(const N of[].concat(T??d??[]))await r.attach(D,k.id,N);return await it(r,D,k.id,P,"before"),f(k,201)}):f({error:"route must be a path"},400):f({error:"empty comment"},400)}if(i.method==="PATCH"){const d=j;if(d.turbo==="on"||d.turbo==="off")return B(r,async p=>(p.turbo={paused:d.turbo==="off",at:new Date().toISOString()},f({turbo:p.turbo})));if(Array.isArray(d.push)||Array.isArray(d.unpush)){const p=S=>(Array.isArray(S)?S:[]).map(Number).filter(v=>Number.isInteger(v)&&v>0).slice(0,500);return B(r,async S=>{const v=new Set(S.turbo?.push?.ids??[]);for(const A of p(d.push))v.add(A);for(const A of p(d.unpush))v.delete(A);const b=A=>S.comments.some(ft=>ft.id===A&&ft.status!=="done"),y=new Set((S.turbo?.batch?.ids??[]).filter(b)),E=!y.size;for(const A of p(d.push))y.add(A);for(const A of p(d.unpush))y.delete(A);const tt=new Date().toISOString();return S.turbo={...S.turbo??{paused:!0},push:{at:tt,ids:[...v]},batch:{at:E?tt:S.turbo?.batch?.at??tt,ids:[...y]}},f({turbo:S.turbo})})}const{id:T,reply:P,image:V,images:$,removeImage:D,uploaded:k,edit:N,unsay:L,before:q,after:X,react:K,seen:At,...ut}=d,g=Number(T);if(!Number.isInteger(g))return f({error:"bad id"},400);if(K){const p=Mt(K.emoji),S=typeof K.at=="string"&&K.at?K.at:null;return p?r.cloud?r.react(g,S,p).then(f,v=>f({error:v.message},v.status>=400&&v.status<500?v.status:500)):B(r,async v=>{const b=Gt(v,g,S,p,"you");return b===!1?f({error:`${Rt} kinds of reaction at most`},400):b?f(b):f({error:`no message to react to in #${g}`},404)},g):f({error:"not an emoji"},400)}if(typeof L=="string"){let p=[];const S=await B(r,async v=>{const b=v.comments.find(E=>E.id===g),y=b?.replies?.find(E=>E.at===L);return!y||o&&y.by&&y.by!==o.email?f({error:`no reply of yours to delete in #${g}`},404):(p=zt(b).find(E=>E.at===L&&E.author==="you")?.images??[],r.unsay(v,g,L)?f(b):f({error:`no reply of yours to delete in #${g}`},404))},g);if(S.status<400)for(const v of p)await r.forget(gt(v));return S}const x=ne(ut);return B(r,async p=>{await R();const S=p.comments.find(y=>y.id===g),v=Ft(S,At,x,o?.email);if(v)return f({error:`#${g} was just changed by someone else`,...v,thread:S},409);if(N){const y=p.comments.find(A=>A.id===Number(g)),E=N.at?y?.replies?.find(A=>A.at===N.at):y;if(o&&E?.by&&E.by!==o.email||!(N.text?.trim?.()&&r.edit(p,g,N.at??null,Z(N.text.trim(),1e4))))return f({error:`no message of yours to edit in #${g}`},404)}P?.trim?.()&&lt(r.reply(p,g,"you",Z(P.trim(),1e4))?.replies.at(-1));for(const y of[].concat($??V??[]))await r.attach(p,g,y);for(const y of[].concat(k??[]))if(r.adopt&&!await r.adopt(p,g,y))return f({error:`${y} did not arrive`},400);for(const y of[].concat(D||[]))await r.detach(p,g,y);if(await it(r,p,g,q,"before"),await it(r,p,g,X,"after"),o&&x.status==="done"&&Object.assign(x,{confirmedBy:o.email,confirmedAt:new Date().toISOString()}),o&&x.status==="open"&&Object.assign(x,{confirmedBy:null,confirmedAt:null,reopenedBy:o.email}),"archived"in x){const y=x.archived;delete x.archived,Object.assign(x,y?{archivedAt:new Date().toISOString(),archivedBy:o?.email??null}:{archivedAt:null,archivedBy:null})}x.status==="open"&&Object.assign(x,{archivedAt:null,archivedBy:null}),ut.approve===!0&&Object.assign(x,{approvedBy:o?.email??"you",approvedAt:new Date().toISOString()}),o&&(x.stage==="review"||x.stage!==void 0&&!a?.client)&&(x.stageBy=o.email),o&&"assignee"in x&&(x.handedBy=at(x.assignee)?o.email:null);const b=Object.keys(x).length?r.patch(p,g,x):p.comments.find(y=>y.id===Number(g));return b?f(b):f({error:`no comment #${g}`},404)},g)}if(i.method==="DELETE"){const d=Number(h.searchParams.get("id"));return B(r,async T=>await r.remove(T,d)?f({ok:!0,id:d}):f({error:`no comment #${d}`},404))}return l(405,"Method not allowed")},kt=(i,h)=>{const r=h.replace(/^.*[/\\]/,""),j=r.split(".").pop()?.toLowerCase()??"",a=Xt[j]??(gt(r)?"application/octet-stream":null);if(!/^[\w.-]+$/.test(r)||!a)return l(400,"Bad name");const o=z(i,r);return et(o)?{status:200,type:a,body:dt(o)}:l(404,"Not found")};return async i=>{const h=new URL(i.url,"http://devbar"),r=h.pathname.slice(10);if(!s&&!te(i))return l(403,"Notemend answers local addresses only");const j=i.headers["sec-fetch-site"];if(!s&&j&&j!=="same-origin")return l(403,"Notemend answers its own pages only");try{if(r==="config"&&i.method==="PATCH"){if(!s&&nt(i))return l(403,"Cross-origin write refused");const a=await u();if(!a.cloud)return l(400,"Link the site to a project to set its grid");const{grid:o}=await C(i);return f({grid:await a.setGrid(o??null)})}if(r==="config"){const a=Yt({root:t,options:{...await m(),...e},routes:c()}),o=await u();return o.cloud&&Object.assign(a,await o.people({fresh:!0}).catch(M=>{if(M.said)throw M;return{}})),(o.cloud||await ot().catch(()=>null))&&(a.voice=!0),o.cloud&&!s&&(a.cabinet=rt),f(a)}if(r==="transcribe"&&i.method==="POST"){if(!s&&nt(i))return l(403,"Cross-origin write refused");const a=await u(),o=a.cloud?await a.token():(await ot().catch(()=>null))?.access_token;if(!o)return l(401,"Voice replies need Notemend \u2014 run `npx notemend login`.");const{audio:M}=await C(i),W=/^data:(audio\/(?:webm|mp4))(?:;[\w=.-]+)*;base64,(.+)$/s.exec(String(M||""));if(!W)return l(400,"Not a recording");const R=await fetch(`${rt}/api/transcribe`,{method:"POST",body:Buffer.from(W[2],"base64"),headers:{authorization:`Bearer ${o}`,"content-type":W[1]}});return{status:R.status,type:"application/json",body:await R.text()}}if(r==="translate"&&i.method==="POST"){if(!s&&nt(i))return l(403,"Cross-origin write refused");const a=await u(),o=a.cloud?await a.token():(await ot().catch(()=>null))?.access_token;if(!o)return l(401,"Translating needs Notemend \u2014 run `npx notemend login`.");const{text:M,to:W}=await C(i),R=await fetch(`${rt}/api/translate`,{method:"POST",body:JSON.stringify({text:M,to:W}),headers:{authorization:`Bearer ${o}`,"content-type":"application/json"}});return{status:R.status,type:"application/json",body:await R.text()}}if(r==="comments")return await $t(i,h);if(r==="events"&&!s)return{status:200,type:"text/event-stream",body:"",stream:Ot};if(r==="image"){const a=await u(),o=(h.searchParams.get("name")||"").replace(/^.*[/\\]/,"");return a.cloud&&/^[\w.-]+$/.test(o)&&await a.fetchImage(o).catch(()=>null),kt(a.imageDir,o)}return l(404,"Not found")}catch(a){return a.status===400||a.status===413?l(a.status,a.message):a.said?l(a.status,a.said):a.status===403?l(403,String(a.message).replace(/^notemend: /,"").replace(/ \(403\)$/,"")):(console.error("[notemend]",a),l(500,"Something went wrong on our side. Try again in a moment."))}}}function he(t){const e=re(t),c=u=>new Promise((s,m)=>{const f=[];u.on("data",l=>f.push(l)),u.on("end",()=>s(Buffer.concat(f))),u.on("error",m)});return async function(s,m,f){if(!s.url||!s.url.startsWith("/__devbar/"))return f();const l=await e({method:s.method,url:s.url,headers:s.headers,body:()=>c(s)});if(l.stream){m.writeHead(200,{"content-type":l.type,"cache-control":"no-store",connection:"keep-alive"}),m.write(`retry: 1000
2
2
 
3
- `);const T=setInterval(()=>y.write(`: ping
3
+ `);const C=setInterval(()=>m.write(`: ping
4
4
 
5
- `),25e3),B=u.stream(C=>y.write(`data: ${C}
5
+ `),25e3),B=l.stream(F=>m.write(`data: ${F}
6
6
 
7
- `));c.on("close",()=>{clearInterval(T),B()});return}y.statusCode=u.status,y.setHeader("content-type",u.type),y.setHeader("cache-control","no-store"),y.end(u.body)}}export{Jt as buildConfig,Xt as notemendHandler,ce as notemendMiddleware,ie as scanApp,Ht as titleOf,Gt as titled};
7
+ `));s.on("close",()=>{clearInterval(C),B()});return}m.statusCode=l.status,m.setHeader("content-type",l.type),m.setHeader("cache-control","no-store"),m.end(l.body)}}export{Yt as buildConfig,re as notemendHandler,he as notemendMiddleware,ge as scanApp,Zt as titleOf,jt as titled};
@@ -1,3 +1,3 @@
1
- import{readFileSync as P,writeFileSync as b,existsSync as I,mkdirSync as A,rmSync as D}from"node:fs";import{homedir as se}from"node:os";import{dirname as H,join as y}from"node:path";import{createStore as oe,add as ae,reply as ce,edit as ie,unsay as ue,patch as le,shotName as v,mediaOf as de,mediaName as L}from"./comments.mjs";const z=process.env.NOTEMEND_APP||"https://app.notemend.com",j={url:process.env.NOTEMEND_SUPABASE_URL||"https://xzhnjldvkirrydbyrdnm.supabase.co",key:process.env.NOTEMEND_SUPABASE_KEY||"sb_publishable_b8h8jTHZ9KtbPvMuroLhqA_-yBqZwd6"},N=y(process.env.NOTEMEND_HOME||y(se(),".config","notemend"),"session.json"),q=e=>y(e,".notemend.json"),he=e=>{try{return JSON.parse(P(q(e),"utf8")).project||null}catch{return null}},Ne=(e,t)=>b(q(e),JSON.stringify({project:t},null,2)+`
2
- `),Oe=e=>D(q(e),{force:!0}),fe=()=>{try{const e=JSON.parse(P(N,"utf8"));return e.url===j.url?e:null}catch{return null}},me=e=>{A(H(N),{recursive:!0}),b(N,JSON.stringify(e,null,2)+`
3
- `,{mode:384})},$e=()=>D(N,{force:!0});async function k(e,{method:t="GET",token:l,body:u,headers:i={},raw:d=!1}={}){const m=await fetch(`${j.url}${e}`,{method:t,headers:{apikey:j.key,authorization:`Bearer ${l||j.key}`,...u&&!d?{"content-type":"application/json"}:{},...i},body:d?u:u&&JSON.stringify(u),signal:AbortSignal.timeout(d?12e4:15e3)});if(!m.ok){const h=await m.text();let w=h;try{const _=JSON.parse(h);w=_.msg||_.message||_.error_description||_.error||h}catch{}const O=new Error(`${w} (${m.status})`);throw O.status=m.status,O}return m}const J=e=>{const t={url:j.url,email:e.user.email,user:e.user.id,access_token:e.access_token,refresh_token:e.refresh_token,expires_at:e.expires_at??Math.floor(Date.now()/1e3)+e.expires_in};return me(t),t},xe=e=>k("/auth/v1/otp",{method:"POST",body:{email:e,create_user:!0}}),Ee=async(e,t)=>J(await(await k("/auth/v1/verify",{method:"POST",body:{email:e,token:t,type:"email"}})).json());async function Te(e){const t=await fetch(`${z}/api/cli/device`,{method:"POST"}),l=await t.json().catch(()=>({}));if(!t.ok)throw new Error(l.error||`The cabinet said ${t.status}`);console.log(`Your code: ${l.code}`),e(l.url);const u=Date.now()+l.expires_in*1e3;for(;Date.now()<u;){await new Promise(h=>setTimeout(h,l.interval*1e3));const i=await fetch(`${z}/api/cli/device`,{headers:{authorization:`Bearer ${l.device}`}}).catch(()=>null);if(!i||i.status===202)continue;const d=await i.json().catch(()=>({}));if(!i.ok)throw new Error(d.error||`The cabinet said ${i.status}`);const m=await(await k("/auth/v1/user",{token:d.access_token})).json();return J({user:m,access_token:d.access_token,refresh_token:d.refresh_token,expires_at:Number(d.expires_at)})}throw new Error("No answer from the browser in 10 minutes.")}async function Pe(e,t){const l=await $();if(!l)throw new Error("Sign in first: npx notemend login");return(await(await k("/rest/v1/projects",{method:"POST",token:l.access_token,headers:{prefer:"return=representation"},body:{name:e,...t?{site_url:t}:{}}})).json())[0]}async function $(){const e=fe();if(!e)return null;if(e.expires_at-60>Date.now()/1e3)return e;try{const t=await k("/auth/v1/token?grant_type=refresh_token",{method:"POST",body:{refresh_token:e.refresh_token}});return J(await t.json())}catch(t){if(t.status===400||t.status===401)return null;throw t}}async function Ae(e,t,l){const u=y(H(N),"seen.json");let i={};try{i=JSON.parse(P(u,"utf8"))}catch{}const d=`${e}|${t}|${l}`;if(Date.now()-(i[d]||0)<6*36e5)return;const m=await $();m&&(await k("/rest/v1/rpc/agent_seen",{method:"POST",token:m.access_token,body:{p_agent:e,p_version:t,p_via:l}}),b(u,JSON.stringify({...i,[d]:Date.now()})))}class x extends Error{}const E=new Map;function pe(e,t,l=null){const u=y(e,"feedback","images"),i=n=>`feedback/images/${n}`,d=new WeakMap,m=l?async()=>l:async()=>{const n=await $();if(!n)throw new Error("Not signed in to Notemend \u2014 run `npx notemend login`.");return n},h=async(n,o={})=>k(`/rest/v1/${n}`,{...o,token:(await m()).access_token}),w=async(n,o={})=>k(`/storage/v1/object/shots/${t}/${n}`,{...o,token:(await m()).access_token}),O=`Project ${t} is not there, or you are not in it. Check \`npx notemend link\`.`,_=()=>Object.assign(new Error(O),{status:403,said:"You are not in this project any more \u2014 ask its owner to add you again."}),K="or=(data->>status.neq.done,data->>doneBy.eq.claude)",Y=async({open:n=!1}={})=>{if(!n){const a=await(await h(`stores?project_id=eq.${t}&select=doc,version`)).json();if(!a.length)throw _();const r=a[0].doc;return d.set(r,a[0].version),r}const[o,s]=await Promise.all([h(`stores_meta?project_id=eq.${t}&select=doc,version`).then(a=>a.json()),h(`threads?project_id=eq.${t}&${K}&select=data&order=id`).then(a=>a.json())]);if(!o.length)throw _();const c={...o[0].doc,comments:s.map(a=>a.data)};return d.set(c,o[0].version),c},R=n=>d.get(n)??null,W=async()=>(await(await h(`stores_meta?project_id=eq.${t}&select=version`)).json())[0]?.version??null,Z=async n=>{const o=d.get(n),s=await(await h(`stores?project_id=eq.${t}&version=eq.${o}&select=version`,{method:"PATCH",body:{doc:n},headers:{prefer:"return=representation"}})).json();if(!s.length)throw new x("Someone else wrote first");d.set(n,s[0].version)},G=async n=>(await(await h(`threads?project_id=eq.${t}&id=eq.${Number(n)}&select=data,v`)).json())[0]??null,Q=async(n,o,s,c)=>{const a={};for(const r of new Set([...Object.keys(o),...Object.keys(s)]))JSON.stringify(o[r])!==JSON.stringify(s[r])&&(a[r]=s[r]??null);if(Object.keys(a).length)try{await h("rpc/patch_thread",{method:"POST",body:{p_project:t,p_id:Number(n),p_patch:a,p_version:c}})}catch(r){throw r.status===409||r.status===404?new x(r.message):r}},U=async(n,o,s)=>(await(await h("rpc/react",{method:"POST",body:{p_project:t,p_id:Number(n),p_at:o,p_emoji:s}})).json()).thread,V=async()=>(await(await h(`threads?project_id=eq.${t}&select=route:data->>route`)).json()).map(n=>n.route),X=async()=>({email:(await m()).email}),B=new Map,ee=async(n,o,s,c)=>{const a=n.comments.find(g=>g.id===Number(o)),r=de(s);if(!a||!r)return null;const f=`${a.id}:${c??""}:${s.length}:${s.slice(-48)}`;let p=B.get(f);if(!p||a.images?.includes(i(p))){let g=Date.now();for(;I(y(u,L(a.id,g,r,c)));)g++;p=L(a.id,g,r,c),B.set(f,p)}const S=Buffer.from(r.base64,"base64");return await w(p,{method:"POST",body:S,raw:!0,headers:{"content-type":r.type,"x-upsert":"true"}}),A(u,{recursive:!0}),b(y(u,p),S),(a.images||=[]).push(i(p)),a.updatedAt=new Date().toISOString(),i(p)},te=async(n,o,s)=>{const c=n.comments.find(r=>r.id===Number(o));return!c||v(s)!==s||!s.startsWith(`${c.id}-`)?null:c.images?.includes(i(s))?i(s):await w(s,{method:"HEAD"}).then(()=>!0,()=>!1)?((c.images||=[]).push(i(s)),c.updatedAt=new Date().toISOString(),i(s)):null},M=async n=>{v(n)&&(D(y(u,n),{force:!0}),await w(n,{method:"DELETE"}).catch(()=>{}))};return{cloud:!0,project:t,root:e,imageDir:u,load:Y,versionOf:R,version:W,save:Z,thread:G,patchThread:Q,react:U,routes:V,me:X,attach:ee,adopt:te,detach:async(n,o,s)=>{const c=n.comments.find(f=>f.id===Number(o)),a=v(s),r=a&&c?.images?.find(f=>v(f)===a);return r?(await M(a),c.images=c.images.filter(f=>f!==r),c.updatedAt=new Date().toISOString(),!0):!1},remove:async(n,o)=>{const s=n.comments.find(c=>c.id===Number(o));if(!s)return!1;for(const c of s.images||[])await M(v(c));return n.comments=n.comments.filter(c=>c.id!==Number(o)),!0},fetchImage:async n=>{if(!v(n)||v(n)!==n)return null;const o=y(u,n);if(I(o))return o;const s=await w(n).catch(()=>null);return s?(A(u,{recursive:!0}),b(o,Buffer.from(await s.arrayBuffer())),o):null},people:async()=>{const n=await m(),o=`${t}|${n.email}`,s=E.get(o);if(s&&Date.now()-s.at<6e4)return s.p;const c=r=>h(`rpc/${r}`,{method:"POST",body:{p:t}}).then(f=>f.json()).catch(()=>null),a=Promise.all([h("profiles?select=email,name,nickname,avatar_url,agent_name,agent_avatar_url").then(r=>r.json()),c("project_people"),c("is_staff").then(r=>r??!0),c("project_staff"),c("project_lead"),h(`projects?id=eq.${t}&select=auto_archive_days,team_id`).then(r=>r.json()).then(async([r])=>{const[f]=r?.team_id?await h(`teams?id=eq.${r.team_id}&select=brand_color,brand_logo`).then(p=>p.json()).catch(()=>[]):[];return{autoArchive:r?.auto_archive_days??null,...f&&(f.brand_color||f.brand_logo)?{brand:{color:f.brand_color,logo:f.brand_logo}}:{}}}).catch(()=>({}))]).then(([r,f,p,S,g,ne])=>{if(Array.isArray(f)&&!f.length)throw _();const C=Array.isArray(f)?new Set(f):null,re=C?r.filter(T=>C.has(T.email)):r;return{me:r.find(T=>T.email===n.email)??{email:n.email,name:"",avatar_url:null},team:re,client:p===!1,...Array.isArray(S)?{studio:S}:{},...typeof g=="string"?{lead:g}:{},...ne}});return E.set(o,{at:Date.now(),p:a}),a.catch(()=>{E.get(o)?.p===a&&E.delete(o)}),a},add:ae,reply:ce,edit:ie,unsay:ue,patch:le,token:async()=>(await m()).access_token}}let F=!1;async function De(e){const t=he(e);return t&&await $()?pe(e,t):(t&&!F&&(F=!0,console.warn("[notemend] this site is linked to a Notemend project, but this computer is not signed in \u2014 comments stay in feedback/ until you run `npx notemend login`.")),oe(e))}async function qe(e,t,l){for(let u=0;;u++){const i=await e.thread(t);if(!i)return l({comments:[]});const d=JSON.parse(JSON.stringify(i.data)),m={comments:[i.data]},h=await l(m);try{return await e.patchThread(t,d,m.comments[0],i.v),h}catch(w){if(!(w instanceof x)||u>=4)throw w}}}async function Je(e,t){for(let l=0;;l++){const u=await e.load(),i=await t(u);try{return await e.save(u),i}catch(d){if(!(d instanceof x)||l>=4)throw d}}}export{j as BACKEND,z as CABINET,x as Conflict,pe as cloudStore,Pe as createProject,Te as deviceLogin,Ne as link,he as linkedProject,$e as logout,De as openStore,Je as retry,qe as retryThread,Ae as seen,xe as sendCode,$ as session,Oe as unlink,Ee as verifyCode};
1
+ import{readFileSync as A,writeFileSync as j,existsSync as G,mkdirSync as D,rmSync as q}from"node:fs";import{homedir as ce}from"node:os";import{dirname as L,join as g}from"node:path";import{createStore as ue,add as de,reply as le,edit as he,unsay as me,patch as fe,shotName as S,mediaOf as pe,mediaName as F,Conflict as $}from"./comments.mjs";import{changedFields as we}from"./thread.mjs";const R=process.env.NOTEMEND_APP||"https://app.notemend.com",N={url:process.env.NOTEMEND_SUPABASE_URL||"https://xzhnjldvkirrydbyrdnm.supabase.co",key:process.env.NOTEMEND_SUPABASE_KEY||"sb_publishable_b8h8jTHZ9KtbPvMuroLhqA_-yBqZwd6"},O=g(process.env.NOTEMEND_HOME||g(ce(),".config","notemend"),"session.json"),B=t=>g(t,".notemend.json"),ye=t=>{try{return JSON.parse(A(B(t),"utf8")).project||null}catch{return null}},Ae=(t,e)=>j(B(t),JSON.stringify({project:e},null,2)+`
2
+ `),De=t=>q(B(t),{force:!0}),_e=()=>{try{const t=JSON.parse(A(O,"utf8"));return t.url===N.url?t:null}catch{return null}},ge=t=>{D(L(O),{recursive:!0}),j(O,JSON.stringify(t,null,2)+`
3
+ `,{mode:384})},qe=()=>q(O,{force:!0});async function v(t,{method:e="GET",token:u,body:c,headers:i={},raw:d=!1}={}){const f=await fetch(`${N.url}${t}`,{method:e,headers:{apikey:N.key,authorization:`Bearer ${u||N.key}`,...c&&!d?{"content-type":"application/json"}:{},...i},body:d?c:c&&JSON.stringify(c),signal:AbortSignal.timeout(d?12e4:15e3)});if(!f.ok){const h=await f.text();let y=h;try{const k=JSON.parse(h);y=k.msg||k.message||k.error_description||k.error||h}catch{}const x=new Error(`${y} (${f.status})`);throw x.status=f.status,x}return f}const M=t=>{const e={url:N.url,email:t.user.email,user:t.user.id,access_token:t.access_token,refresh_token:t.refresh_token,expires_at:t.expires_at??Math.floor(Date.now()/1e3)+t.expires_in};return ge(e),e},Be=t=>v("/auth/v1/otp",{method:"POST",body:{email:t,create_user:!0}}),Me=async(t,e)=>M(await(await v("/auth/v1/verify",{method:"POST",body:{email:t,token:e,type:"email"}})).json());async function Ce(t){const e=await fetch(`${R}/api/cli/device`,{method:"POST"}),u=await e.json().catch(()=>({}));if(!e.ok)throw new Error(u.error||`The cabinet said ${e.status}`);console.log(`Your code: ${u.code}`),t(u.url);const c=Date.now()+u.expires_in*1e3;for(;Date.now()<c;){await new Promise(h=>setTimeout(h,u.interval*1e3));const i=await fetch(`${R}/api/cli/device`,{headers:{authorization:`Bearer ${u.device}`}}).catch(()=>null);if(!i||i.status===202)continue;const d=await i.json().catch(()=>({}));if(!i.ok)throw new Error(d.error||`The cabinet said ${i.status}`);const f=await(await v("/auth/v1/user",{token:d.access_token})).json();return M({user:f,access_token:d.access_token,refresh_token:d.refresh_token,expires_at:Number(d.expires_at)})}throw new Error("No answer from the browser in 10 minutes.")}async function Je(t,e){const u=await E();if(!u)throw new Error("Sign in first: npx notemend login");return(await(await v("/rest/v1/projects",{method:"POST",token:u.access_token,headers:{prefer:"return=representation"},body:{name:t,...e?{site_url:e}:{}}})).json())[0]}async function E(){const t=_e();if(!t)return null;if(t.expires_at-60>Date.now()/1e3)return t;try{const e=await v("/auth/v1/token?grant_type=refresh_token",{method:"POST",body:{refresh_token:t.refresh_token}});return M(await e.json())}catch(e){if(e.status===400||e.status===401)return null;throw e}}async function Ie(t,e,u){const c=g(L(O),"seen.json");let i={};try{i=JSON.parse(A(c,"utf8"))}catch{}const d=`${t}|${e}|${u}`;if(Date.now()-(i[d]||0)<6*36e5)return;const f=await E();f&&(await v("/rest/v1/rpc/agent_seen",{method:"POST",token:f.access_token,body:{p_agent:t,p_version:e,p_via:u}}),j(c,JSON.stringify({...i,[d]:Date.now()})))}const z="Not saved \u2014 columns 1\u201324, gutter and margin 0\u2013200, max width 320\u20134000 or empty.",b=new Map;function ke(t,e,u=null){const c=g(t,"feedback","images"),i=n=>`feedback/images/${n}`,d=new WeakMap,f=u?async()=>u:async()=>{const n=await E();if(!n)throw new Error("Not signed in to Notemend \u2014 run `npx notemend login`.");return n},h=async(n,s={})=>v(`/rest/v1/${n}`,{...s,token:(await f()).access_token}),y=async(n,s={})=>v(`/storage/v1/object/shots/${e}/${n}`,{...s,token:(await f()).access_token}),x=`Project ${e} is not there, or you are not in it. Check \`npx notemend link\`.`,k=()=>Object.assign(new Error(x),{status:403,said:"You are not in this project any more \u2014 ask its owner to add you again."}),W="or=(data->>status.neq.done,data->>doneBy.eq.claude)",Y=async({open:n=!1}={})=>{if(!n){const o=await(await h(`stores?project_id=eq.${e}&select=doc,version`)).json();if(!o.length)throw k();const m=o[0].doc;return d.set(m,o[0].version),m}const[s,r]=await Promise.all([h(`stores_meta?project_id=eq.${e}&select=doc,version`).then(o=>o.json()),h(`threads?project_id=eq.${e}&${W}&select=data&order=id`).then(o=>o.json())]);if(!s.length)throw k();const a={...s[0].doc,comments:r.map(o=>o.data)};return d.set(a,s[0].version),a},Z=n=>d.get(n)??null,U=async()=>(await(await h(`stores_meta?project_id=eq.${e}&select=version`)).json())[0]?.version??null,Q=async n=>{const s=d.get(n),r=await(await h(`stores?project_id=eq.${e}&version=eq.${s}&select=version`,{method:"PATCH",body:{doc:n},headers:{prefer:"return=representation"}})).json();if(!r.length)throw new $("Someone else wrote first");d.set(n,r[0].version)},V=async n=>(await(await h(`threads?project_id=eq.${e}&id=eq.${Number(n)}&select=data,v`)).json())[0]??null,X=async(n,s,r,a)=>{const o=we(s,r);if(Object.keys(o).length)try{await h("rpc/patch_thread",{method:"POST",body:{p_project:e,p_id:Number(n),p_patch:o,p_version:a}})}catch(m){throw m.status===409||m.status===404?new $(m.message):m}},ee=async(n,s,r)=>(await(await h("rpc/react",{method:"POST",body:{p_project:e,p_id:Number(n),p_at:s,p_emoji:r}})).json()).thread,te=async()=>(await(await h(`threads?project_id=eq.${e}&select=route:data->>route`)).json()).map(n=>n.route),ne=async()=>({email:(await f()).email}),C=new Map,re=async(n,s,r,a)=>{const o=n.comments.find(_=>_.id===Number(s)),m=pe(r);if(!o||!m)return null;const w=`${o.id}:${a??""}:${r.length}:${r.slice(-48)}`;let l=C.get(w);if(!l||o.images?.includes(i(l))){let _=Date.now();for(;G(g(c,F(o.id,_,m,a)));)_++;l=F(o.id,_,m,a),C.set(w,l)}const p=Buffer.from(m.base64,"base64");return await y(l,{method:"POST",body:p,raw:!0,headers:{"content-type":m.type,"x-upsert":"true"}}),D(c,{recursive:!0}),j(g(c,l),p),(o.images||=[]).push(i(l)),o.updatedAt=new Date().toISOString(),i(l)},se=async(n,s,r)=>{const a=n.comments.find(m=>m.id===Number(s));return!a||S(r)!==r||!r.startsWith(`${a.id}-`)?null:a.images?.includes(i(r))?i(r):await y(r,{method:"HEAD"}).then(()=>!0,()=>!1)?((a.images||=[]).push(i(r)),a.updatedAt=new Date().toISOString(),i(r)):null},T=async n=>{S(n)&&(q(g(c,n),{force:!0}),await y(n,{method:"DELETE"}).catch(()=>{}))};return{cloud:!0,setGrid:async n=>{const s=await(await h(`projects?id=eq.${e}&select=grid`,{method:"PATCH",body:{grid:n},headers:{prefer:"return=representation"}}).catch(r=>{throw/23514|check constraint/.test(r.message)?Object.assign(new Error(z),{status:400,said:z}):r})).json();if(!s.length)throw Object.assign(new Error("Only the project\u2019s admins change its grid."),{status:403,said:"Only the project\u2019s admins change its grid."});for(const r of b.keys())r.startsWith(`${e}|`)&&b.delete(r);return s[0].grid},project:e,root:t,imageDir:c,load:Y,versionOf:Z,version:U,save:Q,thread:V,patchThread:X,react:ee,routes:te,me:ne,attach:re,adopt:se,detach:async(n,s,r)=>{const a=n.comments.find(w=>w.id===Number(s)),o=S(r),m=o&&a?.images?.find(w=>S(w)===o);return m?(await T(o),a.images=a.images.filter(w=>w!==m),a.updatedAt=new Date().toISOString(),!0):!1},forget:T,remove:async(n,s)=>{const r=n.comments.find(a=>a.id===Number(s));if(!r)return!1;for(const a of r.images||[])await T(S(a));return n.comments=n.comments.filter(a=>a.id!==Number(s)),!0},fetchImage:async n=>{if(!S(n)||S(n)!==n)return null;const s=g(c,n);if(G(s))return s;const r=await y(n).catch(()=>null);return r?(D(c,{recursive:!0}),j(s,Buffer.from(await r.arrayBuffer())),s):null},people:async({fresh:n=!1}={})=>{const s=await f(),r=`${e}|${s.email}`,a=b.get(r);if(!n&&a&&Date.now()-a.at<6e4)return a.p;const o=l=>h(`rpc/${l}`,{method:"POST",body:{p:e}}).then(p=>p.json()).catch(()=>null);let m=!1;const w=Promise.all([h("profiles?select=email,name,nickname,avatar_url,agent_name,agent_avatar_url").then(l=>l.json()),o("project_people"),o("is_staff"),o("project_staff"),o("project_lead"),h(`projects?id=eq.${e}&select=auto_archive_days,grid,team_id`).then(l=>l.json()).then(async([l])=>{const[p]=l?.team_id?await h(`teams?id=eq.${l.team_id}&select=brand_color,brand_logo`).then(_=>_.json()).catch(()=>[]):[];return{autoArchive:l?.auto_archive_days??null,projectGrid:l?.grid??null,...p&&(p.brand_color||p.brand_logo)?{brand:{color:p.brand_color,logo:p.brand_logo}}:{}}}).catch(()=>({})),o("runs_project")]).then(([l,p,_,J,I,oe,ae])=>{if(Array.isArray(p)&&!p.length)throw k();m=typeof _!="boolean";const H=Array.isArray(p)?new Set(p):null,ie=H?l.filter(P=>H.has(P.email)):l;return{me:l.find(P=>P.email===s.email)??{email:s.email,name:"",avatar_url:null},team:ie,client:_!==!0,...Array.isArray(J)?{studio:J}:{},...typeof I=="string"?{lead:I}:{},...oe,project:e,gridAdmin:ae===!0}});return b.set(r,{at:Date.now(),p:w}),w.then(()=>{m&&b.get(r)?.p===w&&b.delete(r)},()=>{b.get(r)?.p===w&&b.delete(r)}),w},add:de,reply:le,edit:he,unsay:me,patch:fe,token:async()=>(await f()).access_token}}let K=!1;async function He(t){const e=ye(t);return e&&await E()?ke(t,e):(e&&!K&&(K=!0,console.warn("[notemend] this site is linked to a Notemend project, but this computer is not signed in \u2014 comments stay in feedback/ until you run `npx notemend login`.")),ue(t))}async function Ge(t,e,u){for(let c=0;;c++){const i=await t.thread(e);if(!i)return u({comments:[]});const d=structuredClone(i.data),f={comments:[i.data]},h=await u(f);try{return await t.patchThread(e,d,f.comments[0],i.v),h}catch(y){if(!(y instanceof $)||c>=4)throw y}}}async function Le(t,e){for(let u=0;;u++){const c=await t.load(),i=await e(c);try{return await t.save(c),i}catch(d){if(!(d instanceof $)||u>=4)throw d}}}export{N as BACKEND,R as CABINET,$ as Conflict,ke as cloudStore,Je as createProject,Ce as deviceLogin,Ae as link,ye as linkedProject,qe as logout,He as openStore,Le as retry,Ge as retryThread,Ie as seen,Be as sendCode,E as session,De as unlink,Me as verifyCode};
@@ -1,3 +1,3 @@
1
- import{readFileSync as B,writeFileSync as D,existsSync as y,mkdirSync as A,renameSync as J,rmSync as z,statSync as T}from"node:fs";import{dirname as G,join as g}from"node:path";import{categoryOf as K}from"./categories.mjs";import{BLOCKED as W,DOCS as C,FRAMES as _,docSlug as q,fileExt as H,frameOf as P,toggledReaction as Q}from"./thread.mjs";import{CATEGORIES as ue,categoryIcon as fe,categoryOf as le}from"./categories.mjs";import{stateOf as pe,STATE_LABEL as ge}from"./status.mjs";const $=n=>{const t=String(n??"").split(/[/\\]/).pop(),e=/^[\w-][\w.-]*\.([a-z0-9]{1,8})$/i.exec(t);return e&&!W.test(e[1])?t:""},V=n=>{const t=/^data:(image|video|audio)\/(png|jpeg|webp|gif|webm|mp4)(?:;[\w=.-]+)*;base64,(.+)$/s.exec(String(n||""));if(t&&!/^data:[^,]*;ext=/.test(String(n).slice(0,300))){const[,i,s,m]=t;return(i==="image"?!/^(png|jpeg|webp|gif)$/.test(s):i==="video"?s!=="webm":!/^(webm|mp4)$/.test(s))?null:{base64:m,voice:i==="audio",ext:s==="jpeg"?"jpg":s==="mp4"?"m4a":s,type:`${i}/${s}`}}const e=/^data:([\w.+-]+\/[\w.+-]+)((?:;[\w=.-]+)*);base64,(.+)$/s.exec(String(n||""));if(!e)return null;const o=/;ext=([a-z0-9]{1,8})(?:;|$)/i.exec(e[2])?.[1],r=o?H(`x.${o}`):Object.keys(C).find(i=>C[i]===e[1]);return r?{base64:e[3],voice:!1,ext:r,type:r==="pdf"?"application/pdf":"application/octet-stream",slug:q(/;name=([\w.-]+)/.exec(e[2])?.[1])||"file"}:null},L=(n,t,e,o)=>`${e.voice?"voice-":_.includes(o)?`${o}-`:""}${n}-${t}${e.slug?`.${e.slug}`:""}.${e.ext}`,oe=async(n,t,e,o,r)=>{if(typeof o!="string")return null;const i=t.comments.find(m=>m.id===Number(e))?.images?.filter(m=>P(m)===r)??[],s=await n.attach(t,e,o,r);if(s)for(const m of i)await n.detach(t,e,m);return s},j=n=>Math.max(n.nextId||0,n.comments.reduce((t,e)=>Math.max(t,e.id),0)+1);function X(n,{route:t,selector:e,rx:o,ry:r,text:i,label:s,viewport:m,breakpoint:x,browser:I,device:v,tag:k,classes:E,nth:N,category:M,suggest:c,assignee:l,ctx:S,logs:a,host:u,priority:f,shared:d,stage:w,from:h,client:p}){const b={id:j(n),route:t,selector:e,rx:o,ry:r,text:i,tag:k||"",classes:E||[],nth:Number.isInteger(N)?N:null,label:s||"",ctx:S||"",viewport:m||null,breakpoint:x||"desktop",browser:I||"",device:v||"",category:K(M).id,status:"open",note:"",replies:[],doneBy:null,images:[],...c?{suggest:c}:{},...l?{assignee:l}:{},...f?{priority:f}:{},...w?{stage:w}:{},...d?{shared:!0}:{},...p?{client:!0}:{},...Number.isInteger(h?.id)?{from:{id:h.id}}:{},...u?{host:u}:{},...a?.length?{logs:a}:{},createdAt:new Date().toISOString(),updatedAt:null};return n.comments.push(b),n.nextId=b.id+1,b}function Y(n,t,e,o,r,i){const s=n.comments.find(m=>m.id===Number(t));return s?((s.replies||=[]).push({author:e,text:o,at:new Date().toISOString(),...r&&r!=="claude"?{agent:r}:{},...i?{by:i}:{}}),s.updatedAt=new Date().toISOString(),s):null}function Z(n,t,e,o){const r=n.comments.find(s=>s.id===Number(t)),i=e?r?.replies?.find(s=>s.at===e&&s.author==="you"):r;return i?(i.text=o,r.updatedAt=new Date().toISOString(),r):null}function U(n,t,e){const o=n.comments.find(i=>i.id===Number(t)),r=o?.replies?.find(i=>i.at===e&&i.author==="you");return r?(r.text="",r.deleted=!0,delete r.mentions,o.updatedAt=new Date().toISOString(),o):null}function ie(n,t,e,o,r){const i=n.comments.find(x=>x.id===Number(t)),s=e?i?.replies?.find(x=>x.at===e&&!x.deleted):i;if(!s)return null;const m=Q(s.reactions,o,r);return m===null?!1:(m?s.reactions=m:delete s.reactions,i)}function ee(n,t,e){const o=n.comments.find(r=>r.id===Number(t));return o?(Object.assign(o,e,{updatedAt:new Date().toISOString()}),o):null}function ce(n){const t=g(n,"feedback","comments.json"),e=g(n,"feedback","images"),o=g(n,"feedback","archive"),r=g(o,"images"),i=c=>`feedback/images/${c}`,s=new WeakMap,m=()=>{const c=y(t)?JSON.parse(B(t,"utf8")):{comments:[]};return s.set(c,v()),c},x=c=>s.get(c)??v(),I=c=>{A(G(t),{recursive:!0});const l=`${t}.${process.pid}.${Date.now()}.tmp`;D(l,JSON.stringify(c,null,2)+`
2
- `),J(l,t)},v=()=>{try{const c=T(t);return`${c.mtimeMs}-${c.size}`}catch{return"0"}};return{root:n,file:t,imageDir:e,archiveDir:o,archiveImageDir:r,load:m,version:v,versionOf:x,save:I,attach:(c,l,S,a)=>{const u=c.comments.find(h=>h.id===Number(l)),f=V(S);if(!u||!f)return null;A(e,{recursive:!0});let d=Date.now();for(;y(g(e,L(u.id,d,f,a)));)d++;const w=L(u.id,d,f,a);return D(g(e,w),Buffer.from(f.base64,"base64")),(u.images||=[]).push(i(w)),u.updatedAt=new Date().toISOString(),i(w)},detach:(c,l,S)=>{const a=c.comments.find(d=>d.id===Number(l)),u=$(S),f=u&&a?.images?.find(d=>$(d)===u);return f?(z(g(e,u),{force:!0}),a.images=a.images.filter(d=>d!==f),a.updatedAt=new Date().toISOString(),!0):!1},remove:(c,l)=>{const S=c.comments.find(a=>a.id===Number(l));if(!S)return!1;for(const a of S.images||[])$(a)&&z(g(e,$(a)),{force:!0});return c.comments=c.comments.filter(a=>a.id!==Number(l)),!0},add:X,patch:ee,reply:Y,edit:Z,unsay:U,nextId:j,prune:(c,{dry:l=!1,date:S=new Date().toISOString().slice(0,10)}={})=>{const a=c.comments.filter(p=>p.status==="done"),u=c.comments.filter(p=>p.status!=="done"),f=g(o,`comments-${S}.json`);if(l||!a.length)return{moving:a,keeping:u,archiveFile:f,images:a.flatMap(p=>p.images||[])};A(r,{recursive:!0});const d=[];for(const p of a)p.images=(p.images||[]).map(b=>{const O=$(b);if(!O)return b;const F=g(e,O),R=g(r,O);return y(F)&&J(F,R),d.push(O),`feedback/archive/images/${O}`});const w=y(f)?JSON.parse(B(f,"utf8")).comments||[]:[],h=new Set(w.map(p=>p.id));return D(f,JSON.stringify({comments:[...w,...a.filter(p=>!h.has(p.id))]},null,2)+`
3
- `),c.nextId=j(c),c.comments=u,{moving:a,keeping:u,archiveFile:f,images:d}}}}export{ue as CATEGORIES,ge as STATE_LABEL,X as add,fe as categoryIcon,le as categoryOf,ce as createStore,Z as edit,oe as fileFrame,L as mediaName,V as mediaOf,j as nextId,ee as patch,ie as react,Y as reply,$ as shotName,pe as stateOf,U as unsay};
1
+ import{readFileSync as J,writeFileSync as D,existsSync as b,mkdirSync as A,renameSync as z,rmSync as j,statSync as G}from"node:fs";import{dirname as K,join as S}from"node:path";import{categoryOf as W}from"./categories.mjs";import{BLOCKED as _,DOCS as L,FRAMES as q,docSlug as H,fileExt as P,frameOf as Q,toggledReaction as V}from"./thread.mjs";import{CATEGORIES as le,categoryIcon as de,categoryOf as pe}from"./categories.mjs";import{stateOf as Se,STATE_LABEL as xe}from"./status.mjs";class X extends Error{}const v=t=>{const n=String(t??"").split(/[/\\]/).pop(),e=/^[\w-][\w.-]*\.([a-z0-9]{1,8})$/i.exec(n);return e&&!_.test(e[1])?n:""},Y=t=>{const n=/^data:(image|video|audio)\/(png|jpeg|webp|gif|webm|mp4)(?:;[\w=.-]+)*;base64,(.+)$/s.exec(String(t||""));if(n&&!/^data:[^,]*;ext=/.test(String(t).slice(0,300))){const[,c,r,m]=n;return(c==="image"?!/^(png|jpeg|webp|gif)$/.test(r):c==="video"?r!=="webm":!/^(webm|mp4)$/.test(r))?null:{base64:m,voice:c==="audio",ext:r==="jpeg"?"jpg":r==="mp4"?"m4a":r,type:`${c}/${r}`}}const e=/^data:([\w.+-]+\/[\w.+-]+)((?:;[\w=.-]+)*);base64,(.+)$/s.exec(String(t||""));if(!e)return null;const i=/;ext=([a-z0-9]{1,8})(?:;|$)/i.exec(e[2])?.[1],s=i?P(`x.${i}`):Object.keys(L).find(c=>L[c]===e[1]);return s?{base64:e[3],voice:!1,ext:s,type:s==="pdf"?"application/pdf":"application/octet-stream",slug:H(/;name=([\w.-]+)/.exec(e[2])?.[1])||"file"}:null},R=(t,n,e,i)=>`${e.voice?"voice-":q.includes(i)?`${i}-`:""}${t}-${n}${e.slug?`.${e.slug}`:""}.${e.ext}`,ce=async(t,n,e,i,s)=>{if(typeof i!="string")return null;const c=n.comments.find(m=>m.id===Number(e))?.images?.filter(m=>Q(m)===s)??[],r=await t.attach(n,e,i,s);if(r)for(const m of c)await t.detach(n,e,m);return r},k=t=>Math.max(t.nextId||0,t.comments.reduce((n,e)=>Math.max(n,e.id),0)+1);function Z(t,{route:n,selector:e,rx:i,ry:s,text:c,label:r,viewport:m,breakpoint:x,browser:y,device:h,tag:E,classes:M,nth:I,category:F,suggest:N,assignee:o,ctx:u,logs:g,host:a,priority:f,shared:d,stage:p,from:w,client:O}){const l={id:k(t),route:n,selector:e,rx:i,ry:s,text:c,tag:E||"",classes:M||[],nth:Number.isInteger(I)?I:null,label:r||"",ctx:u||"",viewport:m||null,breakpoint:x||"desktop",browser:y||"",device:h||"",category:W(F).id,status:"open",note:"",replies:[],doneBy:null,images:[],...N?{suggest:N}:{},...o?{assignee:o}:{},...f?{priority:f}:{},...p?{stage:p}:{},...d?{shared:!0}:{},...O?{client:!0}:{},...Number.isInteger(w?.id)?{from:{id:w.id}}:{},...a?{host:a}:{},...g?.length?{logs:g}:{},createdAt:new Date().toISOString(),updatedAt:null};return t.comments.push(l),t.nextId=l.id+1,l}function U(t,n,e,i,s,c){const r=t.comments.find(m=>m.id===Number(n));return r?((r.replies||=[]).push({author:e,text:i,at:new Date().toISOString(),...s&&s!=="claude"?{agent:s}:{},...c?{by:c}:{}}),r.updatedAt=new Date().toISOString(),r):null}function ee(t,n,e,i){const s=t.comments.find(r=>r.id===Number(n)),c=e?s?.replies?.find(r=>r.at===e&&r.author==="you"):s;return c?(c.text=i,s.updatedAt=new Date().toISOString(),s):null}function te(t,n,e){const i=t.comments.find(c=>c.id===Number(n)),s=i?.replies?.find(c=>c.at===e&&c.author==="you");return s?(s.text="",s.deleted=!0,delete s.mentions,i.updatedAt=new Date().toISOString(),i):null}function ae(t,n,e,i,s){const c=t.comments.find(x=>x.id===Number(n)),r=e?c?.replies?.find(x=>x.at===e&&!x.deleted):c;if(!r)return null;const m=V(r.reactions,i,s);return m===null?!1:(m?r.reactions=m:delete r.reactions,c)}function ne(t,n,e){const i=t.comments.find(s=>s.id===Number(n));return i?(Object.assign(i,e,{updatedAt:new Date().toISOString()}),i):null}function me(t){const n=S(t,"feedback","comments.json"),e=S(t,"feedback","images"),i=S(t,"feedback","archive"),s=S(i,"images"),c=o=>`feedback/images/${o}`,r=new WeakMap,m=()=>{const o=h(),u=b(n)?JSON.parse(J(n,"utf8")):{comments:[]};return r.set(u,o),u},x=o=>r.get(o)??h(),y=o=>{const u=r.get(o);if(u!==void 0&&u!==h())throw new X("Someone else wrote first");A(K(n),{recursive:!0});const g=`${n}.${process.pid}.${Date.now()}.tmp`;D(g,JSON.stringify(o,null,2)+`
2
+ `),z(g,n),u!==void 0&&r.set(o,h())},h=()=>{try{const o=G(n);return`${o.mtimeMs}-${o.size}`}catch{return"0"}};return{root:t,file:n,imageDir:e,archiveDir:i,archiveImageDir:s,load:m,version:h,versionOf:x,save:y,attach:(o,u,g,a)=>{const f=o.comments.find(O=>O.id===Number(u)),d=Y(g);if(!f||!d)return null;A(e,{recursive:!0});let p=Date.now();for(;b(S(e,R(f.id,p,d,a)));)p++;const w=R(f.id,p,d,a);return D(S(e,w),Buffer.from(d.base64,"base64")),(f.images||=[]).push(c(w)),f.updatedAt=new Date().toISOString(),c(w)},detach:(o,u,g)=>{const a=o.comments.find(p=>p.id===Number(u)),f=v(g),d=f&&a?.images?.find(p=>v(p)===f);return d?(j(S(e,f),{force:!0}),a.images=a.images.filter(p=>p!==d),a.updatedAt=new Date().toISOString(),!0):!1},forget:o=>{v(o)&&j(S(e,v(o)),{force:!0})},remove:(o,u)=>{const g=o.comments.find(a=>a.id===Number(u));if(!g)return!1;for(const a of g.images||[])v(a)&&j(S(e,v(a)),{force:!0});return o.comments=o.comments.filter(a=>a.id!==Number(u)),!0},add:Z,patch:ne,reply:U,edit:ee,unsay:te,nextId:k,prune:(o,{dry:u=!1,date:g=new Date().toISOString().slice(0,10)}={})=>{const a=o.comments.filter(l=>l.status==="done"),f=o.comments.filter(l=>l.status!=="done"),d=S(i,`comments-${g}.json`);if(u||!a.length)return{moving:a,keeping:f,archiveFile:d,images:a.flatMap(l=>l.images||[])};A(s,{recursive:!0});const p=[];for(const l of a)l.images=(l.images||[]).map(B=>{const $=v(B);if(!$)return B;const C=S(e,$),T=S(s,$);return b(C)&&z(C,T),p.push($),`feedback/archive/images/${$}`});const w=b(d)?JSON.parse(J(d,"utf8")).comments||[]:[],O=new Set(w.map(l=>l.id));return D(d,JSON.stringify({comments:[...w,...a.filter(l=>!O.has(l.id))]},null,2)+`
3
+ `),o.nextId=k(o),o.comments=f,{moving:a,keeping:f,archiveFile:d,images:p}}}}export{le as CATEGORIES,X as Conflict,xe as STATE_LABEL,Z as add,de as categoryIcon,pe as categoryOf,me as createStore,ee as edit,ce as fileFrame,R as mediaName,Y as mediaOf,k as nextId,ne as patch,ae as react,U as reply,v as shotName,Se as stateOf,te as unsay};
@@ -1 +1 @@
1
- const j=["before","after"],u=e=>/(?:^|\/)(before|after)-[^/]*$/.exec(String(e))?.[1]??null,z=e=>{const t={};for(const n of e?.images||[]){const o=u(n);o&&(t[o]=n)}return t},g={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},w=/^(exe|msi|msp|dmg|pkg|mpkg|app|sh|bash|zsh|command|bat|cmd|com|scr|cpl|ps1|psm1|vbs|vbe|js[e]?|wsf|wsh|hta|jar|apk|ipa|deb|rpm|bin|run|reg|lnk|inf|gadget|appimage)$/i,b=/^(png|jpe?g|webp|gif|webm)$/i,k=[["PDF","#e5484d","pdf"],["DOC","#0d99ff","doc docx rtf odt pages"],["XLS","#30a46c","xls xlsx csv tsv numbers ods"],["PPT","#f76b15","ppt pptx key odp"],["ZIP","#ffb224","zip rar 7z tar gz tgz bz2"],["FIG","#7c6cf2","fig sketch psd ai xd indd eps"],["TXT","#12a594","txt md json html htm css ts tsx jsx xml yml yaml svg log"],["MP3","#d6409f","mp3 wav m4a ogg flac aac"],["MP4","#e93d82","mp4 mov avi mkv m4v"]],T=e=>{const t=String(e??"").split(".").pop().toLowerCase(),n=k.find(([,,o])=>o.split(" ").includes(t));return n?{label:n[0],color:n[1]}:{label:"FILE",color:"#717171"}},B=e=>/\.(pdf|png|jpe?g|webp|gif|mp4|mov|webm|mp3|wav|m4a)$/i.test(String(e??"").split("?")[0]),L=Object.fromEntries([..."\u0430\u0431\u0432\u0433\u0491\u0434\u0435\u0454\u0436\u0437\u0438\u0456\u0457\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044C\u044E\u044F\u044B\u044D\u0451\u044A"].map((e,t)=>[e,["a","b","v","h","g","d","e","ie","zh","z","y","i","i","i","k","l","m","n","o","p","r","s","t","u","f","kh","ts","ch","sh","shch","","iu","ia","y","e","io",""][t]])),F=e=>String(e??"").replace(/\.[^.]*$/,"").toLowerCase().replace(/[а-яёєіїґ]/g,t=>L[t]??"").normalize("NFKD").replace(/[^\w-]+/g,"-").replace(/^[-_]+|-+$/g,"").slice(0,60),W=e=>{const t=/\.([a-z0-9]{1,8})$/i.exec(String(e??""));return t&&!w.test(t[1])?t[1].toLowerCase():""},G=e=>{const t=String(e??"");if(t.startsWith("data:")){const r=/^data:([^;,]+)((?:;[^;,]*)*)[;,]/.exec(t);if(!r)return null;const s=/;ext=([a-z0-9]{1,8})/i.exec(r[2])?.[1]?.toLowerCase()??Object.keys(g).find(a=>g[a]===r[1]);return s?`${/;name=([\w-]+)/.exec(r[2])?.[1]||"document"}.${s}`:null}const n=t.split("/").pop().split("?")[0];if(/^(voice|before|after)-/.test(n))return null;const o=/-\d+(?:\.([\w-]+))?\.([a-z0-9]{1,8})$/i.exec(n);return o&&!b.test(o[2])?`${o[1]||"document"}.${o[2].toLowerCase()}`:null},S=e=>{const t=[{author:"you",text:e.text,at:e.createdAt,by:e.by,byName:e.byName,images:[],...e.reactions?{reactions:e.reactions}:{}},...e.note?[{author:"claude",text:e.note,at:e.updatedAt,images:[]}]:[],...(e.replies||[]).map(n=>({...n,images:[]}))];for(const n of e.images||[]){if(u(n))continue;const o=Number(/-(\d+)(?:\.[\w-]+)?\.\w+$/.exec(n)?.[1]);let r=0;t.forEach((s,a)=>{Date.parse(s.at)<=o&&(r=a)}),t[r].images.push(n)}return t.filter(n=>!n.deleted)},H=["\u{1F44D}","\u2764\uFE0F","\u{1F602}","\u{1F389}","\u{1F440}","\u{1F525}"],K=["\u{1F44D}","\u{1F44E}","\u{1F44F}","\u{1F64C}","\u{1F64F}","\u{1F4AA}","\u{1F44C}","\u270C\uFE0F","\u{1F91D}","\u{1F44B}","\u2764\uFE0F","\u{1F525}","\u{1F389}","\u2728","\u2B50","\u2705","\u274C","\u26A0\uFE0F","\u{1F4AF}","\u{1F680}","\u{1F600}","\u{1F602}","\u{1F60A}","\u{1F60D}","\u{1F914}","\u{1F605}","\u{1F60E}","\u{1F973}","\u{1F622}","\u{1F62E}","\u{1F648}","\u{1F92F}","\u{1F62C}","\u{1F643}","\u{1F440}","\u{1F4A1}","\u{1F4CC}","\u{1F41B}","\u{1F3A8}","\u2615"],y=/^(?:\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Regional_Indicator}|\u200d|\ufe0f)+$/u,U=e=>typeof e!="string"||!e||e.length>16||!y.test(e)?null:[...new Intl.Segmenter().segment(e)].length===1?e:null,A=20,V=(e,t,n)=>{const o={...e||{}},r=o[t]||[];if(!r.length&&Object.keys(o).length>=A)return null;const s=r.includes(n)?r.filter(a=>a!==n):[...r,n];return s.length?o[t]=s:delete o[t],Object.keys(o).length?o:void 0},X=e=>e.nickname||e.name||e.email,m=(e,t)=>{const n="@"+t.toLowerCase();let o=-1;for(let r=e.indexOf(n);r!==-1;r=e.indexOf(n,r+1))/[\p{L}\p{N}_.-]/u.test(e[r+n.length]??"")||(o=r);return o},Y=(e,t)=>{const n=String(e||"").toLowerCase();return n.includes("@")?[...new Set(t.filter(o=>[o.name,o.nickname,o.email].some(r=>r&&m(n,r)!==-1)).map(o=>o.email))]:[]},C=/https?:\/\/[^\s<>"']+/g,f=e=>{const t=e.filter(Boolean).pop();try{return t?decodeURIComponent(t):""}catch{return t}},M=e=>{let t;try{t=new URL(e)}catch{return{label:String(e),kind:"link"}}const n=t.hostname.replace(/^www\./,""),o=t.pathname.split("/").filter(Boolean);if(/(^|\.)figma\.com$/.test(n))return{label:o[2]?`Figma \xB7 ${f([o[2]]).replace(/-/g," ")}`:"Figma",kind:"link"};if(n==="github.com"&&o.length){const[s,a,c,d]=o;return{label:`GitHub \xB7 ${a??s}${/^(pull|issues)$/.test(c??"")&&d?` #${d}`:""}`,kind:c==="pull"?"pr":"github"}}if(/(^|\.)loom\.com$/.test(n))return{label:"Loom",kind:"link"};const r=f(o);return{label:r?`${n} \xB7 ${r.length>32?r.slice(0,31)+"\u2026":r}`:n,kind:"link"}},O=e=>{const t=String(e??""),n=[];let o=0;for(const r of t.matchAll(C)){const s=r[0].replace(/[.,;:!?)\]]+$/,"");r.index>o&&n.push(t.slice(o,r.index)),n.push({url:s,...M(s)}),o=r.index+s.length}return o<t.length&&n.push(t.slice(o)),n},q=e=>O(e).map(t=>typeof t=="string"?t:t.label).join(""),$={claude:"Claude",codex:"Codex",gemini:"Gemini",cursor:"Cursor",copilot:"Copilot",windsurf:"Windsurf",amp:"Amp",aider:"Aider",opencode:"OpenCode",agent:"AI agent"},I=e=>$[e]||(e?"AI agent":"Claude"),J="3.6 3.6 10.8 10.8",E="M10.116 9H13.883M9.966 9.558L12.222 10.86M9.558 9.966L11.441 13.228M9 10.116V12.72M8.442 9.966L6.559 13.228M8.034 9.558L5.778 10.86M7.884 9H4.118M8.034 8.442L5.778 7.14M8.442 8.034L6.559 4.772M9 7.884V5.28M9.558 8.034L11.441 4.772M9.966 8.442L12.222 7.14",i=e=>typeof e=="string"&&e.startsWith("agent:")?e.slice(6):null,l=e=>e==="claude"||i(e)!=null,D=/^[^\s@]+@[^\s@]+$/,Q=e=>{if(e==="claude")return e;if(typeof e!="string"||e.length>210)return null;const t=e.toLowerCase();return D.test(i(t)??t)?t:null},v=["new","approved","progress","review","waiting"],x=e=>v.includes(e?.stage)?e.stage:e?.stage==="accepted"?"review":l(e?.assignee)?"approved":"new",N=e=>e?.client===!0||e?.shared===!0,Z=(e,t)=>{const n=i(e.assignee);return!N(e)&&x(e)==="approved"&&(!e.assignee||e.assignee==="claude"||n!=null&&(t===void 0||n===t))&&!p(e)},_=()=>[{assignee:"claude",handle:"Claude",owner:null}],ee=(e,t=[])=>{const n=String(e||"").toLowerCase();let o=null,r=-1;for(const s of _()){const a=m(n,s.handle);a>r&&(r=a,o=s.assignee)}return o},te=(e,t,n=o=>o)=>I(e)+(t?` \xB7 ${n(t)}`:""),P=2*36e5,h=(e,t=Date.now())=>e?.working&&e.status!=="done"&&t-Date.parse(e.working.at)<P?e.working:null,ne=(e,t,n=Date.now())=>{const o=String(e?.by||e?.byName||"").toLowerCase();if(!o||t==="done")return null;const r=t==="claude"||l(e.assignee),s=p(e)?"":r?h(e,n)?.by||e.doneFor||e.handedBy||i(e.assignee)||o:e.assignee||"";return{writer:o,taker:String(s).toLowerCase(),claude:r}},R=e=>/@guest\.notemend\.com$/i.test(String(e||"")),p=e=>R(e.by)&&!e.approvedBy,oe=(e,t=Date.now())=>{if(!e)return null;if(e.status==="done")return e.doneBy==="claude"?"review":l(e.assignee)?"done":null;if(p(e))return"held";if(!l(e.assignee))return null;const n=S(e),o=n[n.length-1];return n.length>1&&o.author==="claude"&&!(e.reopenedAt&&Date.parse(e.reopenedAt)>=Date.parse(o.at))?"asks":h(e,t)?"working":e.working?"stuck":x(e)==="approved"?"queued":null},re={held:0,queued:2,asks:6,working:6,stuck:6,review:10,done:12},se=E.split("M").filter(Boolean).map(e=>{const t=e.match(/[\d.]+/g).map(Number),[n,o]=/H/.test(e)?[t[2],t[1]]:/V/.test(e)?[t[0],t[2]]:[t[2],t[3]];return{d:"M"+e,a:(Math.atan2(n-9,9-o)+2*Math.PI)%(2*Math.PI)}}).sort((e,t)=>e.a-t.a).map(e=>e.d),ae={plugin:"Claude Code: /plugin \u2192 Installed \u2192 notemend \u2192 Update now, then /reload-plugins",npx:'run it as npx -y notemend@latest (npx keeps an old copy of plain "notemend"), then restart the agent',project:"npm i -D notemend@latest in the site, then restart the agent",desktop:"Claude Desktop: download app.notemend.com/notemend.mcpb again and open it",source:"pull the notemend repository"},ie=(e,t)=>{const n=String(e).split(".").map(Number),o=String(t).split(".").map(Number);for(let r=0;r<3;r++)if((n[r]||0)!==(o[r]||0))return(n[r]||0)>(o[r]||0);return!1},le=(e,t)=>{if(e.archivedAt)return!0;if(!t||e.status!=="done"||e.doneBy==="claude")return!1;const n=Math.max(Date.parse(e.confirmedAt||e.updatedAt||"")||0,...(e.replies||[]).filter(o=>!o.deleted).map(o=>Date.parse(o.at||"")||0));return!!n&&Date.now()-n>t*864e5};export{$ as AGENTS,J as AI_BOX,E as AI_RAYS,se as AI_RAYS_CW,w as BLOCKED,g as DOCS,K as EMOJI,k as FILE_KINDS,j as FRAMES,A as MAX_REACTIONS,H as QUICK,v as STAGES,re as STEP_RAYS,ae as UPDATE_HOW,P as WORKING_TTL,_ as agentHandles,te as agentLabel,ee as agentMentioned,I as agentName,i as agentOwner,oe as agentStep,le as archivedOf,Q as cleanAssignee,U as cleanEmoji,N as clientSpace,G as docOf,F as docSlug,W as fileExt,T as fileKind,Z as forAgentOf,u as frameOf,z as framesOf,X as handleOf,p as held,R as isGuest,M as linkLabel,O as linkParts,q as linkWords,Y as mentionsIn,ie as newer,B as opensInTab,ne as pinWho,x as stageOf,S as threadOf,l as toAgent,V as toggledReaction,h as workingOn};
1
+ const H=["before","after"],m=e=>/(?:^|\/)(before|after)-[^/]*$/.exec(String(e))?.[1]??null,U=e=>{const t={};for(const n of e?.images||[]){const o=m(n);o&&(t[o]=n)}return t},x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},y=/^(exe|msi|msp|dmg|pkg|mpkg|app|sh|bash|zsh|command|bat|cmd|com|scr|cpl|ps1|psm1|vbs|vbe|js[e]?|wsf|wsh|hta|jar|apk|ipa|deb|rpm|bin|run|reg|lnk|inf|gadget|appimage)$/i,S=/^(png|jpe?g|webp|gif|webm)$/i,c=typeof Intl<"u"&&Intl.Segmenter?new Intl.Segmenter:null,O=(e,t)=>{const n=String(e??"");if(n.length<=t)return n;let o="";if(c)for(const{segment:r}of c.segment(n)){if(o.length+r.length>t)break;o+=r}else for(const r of n){if(o.length+r.length>t)break;o+=r}return o},L=[["PDF","#e5484d","pdf"],["DOC","#0d99ff","doc docx rtf odt pages"],["XLS","#30a46c","xls xlsx csv tsv numbers ods"],["PPT","#f76b15","ppt pptx key odp"],["ZIP","#ffb224","zip rar 7z tar gz tgz bz2"],["FIG","#7c6cf2","fig sketch psd ai xd indd eps"],["TXT","#12a594","txt md json html htm css ts tsx jsx xml yml yaml svg log"],["MP3","#d6409f","mp3 wav m4a ogg flac aac"],["MP4","#e93d82","mp4 mov avi mkv m4v"]],J=e=>{const t=String(e??"").split(".").pop().toLowerCase(),n=L.find(([,,o])=>o.split(" ").includes(t));return n?{label:n[0],color:n[1]}:{label:"FILE",color:"#717171"}},K=e=>/\.(pdf|png|jpe?g|webp|gif|mp4|mov|webm|mp3|wav|m4a)$/i.test(String(e??"").split("?")[0]),A=Object.fromEntries([..."\u0430\u0431\u0432\u0433\u0491\u0434\u0435\u0454\u0436\u0437\u0438\u0456\u0457\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044C\u044E\u044F\u044B\u044D\u0451\u044A"].map((e,t)=>[e,["a","b","v","h","g","d","e","ie","zh","z","y","i","i","i","k","l","m","n","o","p","r","s","t","u","f","kh","ts","ch","sh","shch","","iu","ia","y","e","io",""][t]])),X=e=>String(e??"").replace(/\.[^.]*$/,"").toLowerCase().replace(/[а-яёєіїґ]/g,t=>A[t]??"").normalize("NFKD").replace(/[^\w-]+/g,"-").replace(/^[-_]+|-+$/g,"").slice(0,60),V=e=>{const t=/\.([a-z0-9]{1,8})$/i.exec(String(e??""));return t&&!y.test(t[1])?t[1].toLowerCase():""},Y=e=>Number(/^(?:before-|after-|voice-)?(\d+)-\d+(?:\.[\w-]+)?\.\w+$/i.exec(String(e??"").split("/").pop())?.[1])||null,q=e=>["","before-","after-","voice-"].map(t=>`${t}${Number(e)}-`),Q=e=>{const t=String(e??"");if(t.startsWith("data:")){const r=/^data:([^;,]+)((?:;[^;,]*)*)[;,]/.exec(t);if(!r)return null;const s=/;ext=([a-z0-9]{1,8})/i.exec(r[2])?.[1]?.toLowerCase()??Object.keys(x).find(a=>x[a]===r[1]);return s?`${/;name=([\w-]+)/.exec(r[2])?.[1]||"document"}.${s}`:null}const n=t.split("/").pop().split("?")[0];if(/^(voice|before|after)-/.test(n))return null;const o=/-\d+(?:\.([\w-]+))?\.([a-z0-9]{1,8})$/i.exec(n);return o&&!S.test(o[2])?`${o[1]||"document"}.${o[2].toLowerCase()}`:null},$=e=>{const t=[{author:"you",text:e.text,at:e.createdAt,by:e.by,byName:e.byName,images:[],...e.reactions?{reactions:e.reactions}:{}},...e.note?[{author:"claude",text:e.note,at:e.updatedAt,images:[]}]:[],...(e.replies||[]).map(n=>({...n,images:[]}))];for(const n of e.images||[]){if(m(n))continue;const o=Number(/-(\d+)(?:\.[\w-]+)?\.\w+$/.exec(n)?.[1]?.slice(0,13));let r=0;t.forEach((s,a)=>{Date.parse(s.at)<=o&&(r=a)}),t[r].images.push(n)}return t.filter(n=>!n.deleted)},Z=["\u{1F44D}","\u2764\uFE0F","\u{1F602}","\u{1F389}","\u{1F440}","\u{1F525}"],ee=["\u{1F44D}","\u{1F44E}","\u{1F44F}","\u{1F64C}","\u{1F64F}","\u{1F4AA}","\u{1F44C}","\u270C\uFE0F","\u{1F91D}","\u{1F44B}","\u2764\uFE0F","\u{1F525}","\u{1F389}","\u2728","\u2B50","\u2705","\u274C","\u26A0\uFE0F","\u{1F4AF}","\u{1F680}","\u{1F600}","\u{1F602}","\u{1F60A}","\u{1F60D}","\u{1F914}","\u{1F605}","\u{1F60E}","\u{1F973}","\u{1F622}","\u{1F62E}","\u{1F648}","\u{1F92F}","\u{1F62C}","\u{1F643}","\u{1F440}","\u{1F4A1}","\u{1F4CC}","\u{1F41B}","\u{1F3A8}","\u2615"],I=/^(?:\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Regional_Indicator}|\u200d|\ufe0f)+$/u,te=e=>typeof e!="string"||!e||e.length>16||!I.test(e)?null:[...new Intl.Segmenter().segment(e)].length===1?e:null,ne=e=>{if(!e||typeof e!="object")return null;const t=[e.x,e.y,e.w,e.h].map(Number);if(!t.every(Number.isFinite))return null;const n=i=>Math.min(1,Math.max(0,i)),o=i=>Math.round(i*1e4)/1e4,r=n(t[0]),s=n(t[1]),a=n(t[0]+t[2])-r,p=n(t[1]+t[3])-s;return a>0&&p>0?{x:o(r),y:o(s),w:o(a),h:o(p)}:null},C=20,oe=(e,t,n)=>{const o={...e||{}},r=o[t]||[];if(!r.length&&Object.keys(o).length>=C)return null;const s=r.includes(n)?r.filter(a=>a!==n):[...r,n];return s.length?o[t]=s:delete o[t],Object.keys(o).length?o:void 0},re=e=>e.nickname||e.name||e.email,D="(?![\\p{L}\\p{N}_]|[.-][\\p{L}\\p{N}_])",M=new RegExp("^"+D,"u"),h=(e,t)=>{const n="@"+t.toLowerCase();let o=-1;for(let r=e.indexOf(n);r!==-1;r=e.indexOf(n,r+1))M.test(e.slice(r+n.length))&&(o=r);return o},se=(e,t)=>{const n=String(e||"").toLowerCase();return n.includes("@")?[...new Set(t.filter(o=>[o.name,o.nickname,o.email].some(r=>r&&h(n,r)!==-1)).map(o=>o.email))]:[]},N=/https?:\/\/[^\s<>"']+/g,w=e=>{const t=e.filter(Boolean).pop();try{return t?decodeURIComponent(t):""}catch{return t}},E=e=>{let t;try{t=new URL(e)}catch{return{label:String(e),kind:"link"}}const n=t.hostname.replace(/^www\./,""),o=t.pathname.split("/").filter(Boolean);if(/(^|\.)figma\.com$/.test(n))return{label:o[2]?`Figma \xB7 ${w([o[2]]).replace(/-/g," ")}`:"Figma",kind:"link"};if(n==="github.com"&&o.length){const[s,a,p,i]=o;return{label:`GitHub \xB7 ${a??s}${/^(pull|issues)$/.test(p??"")&&i?` #${i}`:""}`,kind:p==="pull"?"pr":"github"}}if(/(^|\.)loom\.com$/.test(n))return{label:"Loom",kind:"link"};const r=w(o);return{label:r?`${n} \xB7 ${r.length>32?O(r,31)+"\u2026":r}`:n,kind:"link"}},v=e=>{const t=String(e??""),n=[];let o=0;for(const r of t.matchAll(N)){const s=r[0].replace(/[.,;:!?)\]]+$/,"");r.index>o&&n.push(t.slice(o,r.index)),n.push({url:s,...E(s)}),o=r.index+s.length}return o<t.length&&n.push(t.slice(o)),n},ae=e=>v(e).map(t=>typeof t=="string"?t:t.label).join(""),j={claude:"Claude",codex:"Codex",gemini:"Gemini",cursor:"Cursor",copilot:"Copilot",windsurf:"Windsurf",amp:"Amp",aider:"Aider",opencode:"OpenCode",agent:"AI agent"},B=e=>j[e]||(e?"AI agent":"Claude"),ie="3.6 3.6 10.8 10.8",_="M10.116 9H13.883M9.966 9.558L12.222 10.86M9.558 9.966L11.441 13.228M9 10.116V12.72M8.442 9.966L6.559 13.228M8.034 9.558L5.778 10.86M7.884 9H4.118M8.034 8.442L5.778 7.14M8.442 8.034L6.559 4.772M9 7.884V5.28M9.558 8.034L11.441 4.772M9.966 8.442L12.222 7.14",d=e=>typeof e=="string"&&e.startsWith("agent:")?e.slice(6):null,u=e=>e==="claude"||d(e)!=null,F=/^[^\s@]+@[^\s@]+$/,le=e=>{if(e==="claude")return e;if(typeof e!="string"||e.length>210)return null;const t=e.toLowerCase();return F.test(d(t)??t)?t:null},R=["new","approved","progress","review","waiting"],b=e=>R.includes(e?.stage)?e.stage:e?.stage==="accepted"?"review":u(e?.assignee)?"approved":"new",l=e=>e?.client===!0||e?.shared===!0,pe=(e,t,n="")=>`Duplicated from ${n?n==="you"?"your":`${n}\u2019s`:"a"} ${(t?l(t):!l(e))?"client":"studio"} thread`,ue=e=>l(e)?"Duplicated for the client":"Duplicated to the workspace",ce="Fixed \u2014 please check.",de=e=>e?.status==="done"&&!l(e)&&Number.isInteger(e.from?.id)?e.from.id:null,ge=(e,t)=>!l(e)||e.status==="done"?!1:((e.replies||=[]).push(t),Object.assign(e,{status:"done",doneBy:"you",updatedAt:t.at}),!0),fe=(e,t)=>{const n=d(e.assignee);return!l(e)&&b(e)==="approved"&&(!e.assignee||e.assignee==="claude"||n!=null&&(t===void 0||n===t))&&!f(e)},T=()=>[{assignee:"claude",handle:"Claude",owner:null}],me=(e,t=[])=>{const n=String(e||"").toLowerCase();let o=null,r=-1;for(const s of T()){const a=h(n,s.handle);a>r&&(r=a,o=s.assignee)}return o},xe=(e,t,n=o=>o)=>B(e)+(t?` \xB7 ${n(t)}`:""),P=2*36e5,g=(e,t=Date.now())=>e?.working&&e.status!=="done"&&t-Date.parse(e.working.at)<P?e.working:null,he=(e,t)=>({status:"done",doneBy:"claude",working:null,doneAgent:e!=="claude"?e:null,doneFor:t??null}),we=(e,t=new Date().toISOString())=>({status:"open",doneBy:null,doneAgent:null,doneFor:null,working:null,reopenedAt:t,...u(e?.assignee)?{stage:"approved"}:{}}),be=(e,t)=>{const n={};for(const o of new Set([...Object.keys(e),...Object.keys(t)]))JSON.stringify(e[o])!==JSON.stringify(t[o])&&(n[o]=t[o]??null);return n},z={status:e=>e.status!=="done"?e.reopenedBy:e.doneBy==="claude"?"claude":e.confirmedBy??e.archivedBy,stage:e=>e.stageBy,assignee:e=>e.handedBy},ke=(e,t,n,o)=>{if(!e||!t||typeof t!="object")return null;const r=(s,a)=>JSON.stringify(s??null)===JSON.stringify(a??null);for(const s of["stage","status","priority","assignee"]){if(!(s in t)||r(e[s],t[s])||s in n&&r(e[s],n[s]))continue;const a=z[s]?.(e)??null;if(!(a&&o&&String(a).toLowerCase()===o.toLowerCase()))return{field:s==="stage"?"status":s,by:a}}return null},ye=(e,t,n=Date.now())=>{const o=String(e?.by||e?.byName||"").toLowerCase();if(!o||t==="done")return null;const r=t==="claude"||u(e.assignee),s=f(e)?"":r?g(e,n)?.by||e.doneFor||e.handedBy||d(e.assignee)||o:e.assignee||"";return{writer:o,taker:String(s).toLowerCase(),claude:r}},W=e=>/@guest\.notemend\.com$/i.test(String(e||"")),f=e=>W(e.by)&&!e.approvedBy,Se=(e,t=Date.now())=>{if(!e)return null;if(e.status==="done")return e.doneBy==="claude"?"review":u(e.assignee)?"done":null;if(f(e))return"held";if(!u(e.assignee))return null;const n=$(e),o=n[n.length-1],r=g(e,t);return n.length>1&&o.author==="claude"&&!(e.reopenedAt&&Date.parse(e.reopenedAt)>=Date.parse(o.at))&&(!r||String(o.text??"").includes("?"))?"asks":r?r.step&&t-Date.parse(r.at)>G?"stuck":"working":e.working?"stuck":b(e)==="approved"?"queued":null},G=10*6e4,k=(e,t=Date.now())=>{const n=Math.floor((t-Date.parse(e??""))/6e4);return n>=1?n<60?`${n} min`:`${Math.floor(n/60)} h`:"now"},Oe=(e,t=31)=>{const n=c?[...c.segment(String(e??""))].map(s=>s.segment):[...String(e??"")];if(n.length<=t)return n.join("");const o=n.join("").match(/\.\w{1,8}$/)?.[0],r=o?o.length+3:0;return n.slice(0,t-1-r).join("")+"\u2026"+(r?n.slice(-r).join(""):"")},Le=(e,t=Date.now())=>{const n=e?.status!=="done"?e?.working:null;return n?.at?{step:n.step?String(n.step):null,elapsed:k(n.since??n.at,t),silent:k(n.at,t),stale:!g(e,t)}:null},Ae={held:0,queued:2,asks:6,working:6,stuck:6,review:10,done:12},$e=_.split("M").filter(Boolean).map(e=>{const t=e.match(/[\d.]+/g).map(Number),[n,o]=/H/.test(e)?[t[2],t[1]]:/V/.test(e)?[t[0],t[2]]:[t[2],t[3]];return{d:"M"+e,a:(Math.atan2(n-9,9-o)+2*Math.PI)%(2*Math.PI)}}).sort((e,t)=>e.a-t.a).map(e=>e.d),Ie={plugin:"Claude Code: /plugin \u2192 Installed \u2192 notemend \u2192 Update now, then /reload-plugins",npx:'run it as npx -y notemend@latest (npx keeps an old copy of plain "notemend"), then restart the agent',project:"npm i -D notemend@latest in the site, then restart the agent",desktop:"Claude Desktop: download app.notemend.com/notemend.mcpb again and open it",source:"pull the notemend repository"},Ce=(e,t)=>{const n=String(e).split(".").map(Number),o=String(t).split(".").map(Number);for(let r=0;r<3;r++)if((n[r]||0)!==(o[r]||0))return(n[r]||0)>(o[r]||0);return!1},De=(e,t)=>{if(e.archivedAt)return!0;if(!t||e.status!=="done"||e.doneBy==="claude")return!1;const n=Math.max(Date.parse(e.confirmedAt||e.updatedAt||"")||0,...(e.replies||[]).filter(o=>!o.deleted).map(o=>Date.parse(o.at||"")||0));return!!n&&Date.now()-n>t*864e5};export{j as AGENTS,ie as AI_BOX,_ as AI_RAYS,$e as AI_RAYS_CW,y as BLOCKED,x as DOCS,ee as EMOJI,L as FILE_KINDS,ce as FIXED_NOTICE,H as FRAMES,D as HANDLE_END,C as MAX_REACTIONS,Z as QUICK,G as QUIET,R as STAGES,Ae as STEP_RAYS,Ie as UPDATE_HOW,P as WORKING_TTL,he as agentDone,T as agentHandles,xe as agentLabel,me as agentMentioned,B as agentName,d as agentOwner,we as agentReopen,Se as agentStep,De as archivedOf,be as changedFields,ke as clashOf,le as cleanAssignee,ne as cleanBox,te as cleanEmoji,l as clientSpace,O as cut,Q as docOf,X as docSlug,pe as duplicatedFrom,ue as duplicatedTo,k as elapsed,V as fileExt,J as fileKind,q as filePrefixes,Y as fileThread,fe as forAgentOf,m as frameOf,U as framesOf,re as handleOf,f as held,W as isGuest,E as linkLabel,v as linkParts,ae as linkWords,Le as liveStep,se as mentionsIn,Ce as newer,K as opensInTab,de as originOf,ye as pinWho,b as stageOf,Oe as stepWords,ge as tellFixed,$ as threadOf,u as toAgent,oe as toggledReaction,g as workingOn};
package/store.d.ts CHANGED
@@ -27,13 +27,17 @@ export interface Comment {
27
27
  from?: { id: number };
28
28
  reactions?: Reactions;
29
29
  /** put away by a person */
30
- archivedAt?: string | null;
30
+ archivedAt?: string | null; archivedBy?: string | null;
31
31
  /** a person sent it back: the agent's last word before this is no question */
32
- reopenedAt?: string; acceptedAt?: string;
32
+ reopenedAt?: string; reopenedBy?: string | null; acceptedAt?: string;
33
+ /** who sent it to review */
34
+ stageBy?: string | null;
33
35
  /** who ticked it as fixed, in a team */
34
36
  confirmedBy?: string | null; confirmedAt?: string | null;
35
37
  /** the person the agent ran as when it resolved it */
36
38
  doneFor?: string | null;
39
+ /** where the element sat in the before frame, as fractions of the frame (0–1): the drawer outlines it there */
40
+ box?: { x: number; y: number; w: number; h: number } | null;
37
41
  /** who handed it to an agent — whose Claude its pin shows (the server sets it) */
38
42
  handedBy?: string | null;
39
43
  /** a guest's thread, approved by the studio */
package/thread.d.ts CHANGED
@@ -1,8 +1,23 @@
1
1
  export type Mentionable = { email: string; name?: string | null; nickname?: string | null };
2
2
  /** What a pick from the @ list writes: the nickname, else the name, else the email */
3
3
  export function handleOf(p: Mentionable): string;
4
+ type Spaced = { client?: boolean; shared?: boolean; by?: string; byName?: string };
5
+ /** A copy's line: «Duplicated from Sarah's client thread» — the original's space and writer when seen */
6
+ export function duplicatedFrom(copy: Spaced, orig?: Spaced | null, who?: string): string;
7
+ /** The original's line: where its copy is now */
8
+ export function duplicatedTo(copy: Spaced): string;
9
+ /** What the client's original hears when the studio's copy of it is resolved */
10
+ export const FIXED_NOTICE: string;
11
+ /** The id of the client's original a resolved studio copy tells, or null */
12
+ export function originOf(copy: { status?: string; client?: boolean; shared?: boolean; from?: { id: number } } | undefined): number | null;
13
+ /** The original told: the reply added and resolved in place; false when it has nothing to hear */
14
+ export function tellFixed(orig: { status?: string; client?: boolean; shared?: boolean; replies?: unknown[]; [k: string]: unknown }, reply: { author: string; text: string; at: string; [k: string]: unknown }): boolean;
15
+ /** A regex lookahead source: what may not follow a handle for the @mention to be whole */
16
+ export const HANDLE_END: string;
4
17
  /** Everyone a text @mentions, by email */
5
18
  export function mentionsIn(text: string, people: Mentionable[]): string[];
19
+ /** At most `n` UTF-16 units of a text, never cutting an emoji or a joined character in half */
20
+ export function cut(text: string | null | undefined, n: number): string;
6
21
  /** A link named the way a message shows it: "Figma · Notemend", "GitHub · notemend #42", or the host and the last part */
7
22
  export function linkLabel(url: string): { label: string; kind: "link" | "github" | "pr" };
8
23
  /** A text cut into its words and its links, in order */
@@ -25,12 +40,18 @@ export function cleanAssignee(v: unknown): string | null;
25
40
  /** Where a thread stands: new, approved for an agent, in progress (a person on it), waiting for a person's review, or waiting on someone */
26
41
  export const STAGES: string[];
27
42
  export function stageOf(c: { stage?: string | null; assignee?: string | null } | null | undefined): "new" | "approved" | "progress" | "review" | "waiting" | "accepted";
43
+ /** A change made on a stale look: the field someone else changed since `seen` (a stage and the status are one), and who when the thread keeps it — else null */
44
+ export function clashOf(c: Record<string, unknown> | null | undefined, seen: Record<string, unknown> | null | undefined, sent: Record<string, unknown>, me?: string | null): { field: "status" | "priority" | "assignee"; by: string | null } | null;
28
45
  /** A thread for the agent running as `me` (null: a CI key, the shared queue only; undefined: a local store, all) */
29
46
  export function forAgentOf(c: { assignee?: string | null; stage?: string | null; by?: string | null; approvedBy?: string | null; shared?: boolean | null; client?: boolean | null }, me?: string | null): boolean;
30
47
  export function clientSpace(c: { shared?: boolean | null; client?: boolean | null } | null | undefined): boolean;
31
48
  /** "Claude · Ann": the agent, and the person it ran as */
32
49
  export function agentLabel(agent?: string | null, owner?: string | null, nameOf?: (email: string) => string): string;
33
- export type Working = { agent: string; by?: string | null; at: string; v?: string };
50
+ export type Working = { agent: string; by?: string | null; at: string; v?: string;
51
+ /** what the agent is doing right now, for the bar's banner ("Editing Hero.astro") */
52
+ step?: string;
53
+ /** when the agent took the thread; `at` is its last step */
54
+ since?: string };
34
55
  /** How long a "working" mark holds before it counts as left behind, in ms */
35
56
  export const WORKING_TTL: number;
36
57
  /** The agent working on an open thread now, or null when nobody is or the mark is stale */
@@ -41,6 +62,12 @@ export function pinWho(c: Record<string, any>, st: 'open' | 'done' | 'claude', n
41
62
  export function isGuest(email?: string | null): boolean;
42
63
  /** A guest's thread the studio has not approved yet: no agent takes it */
43
64
  export function held(c: { by?: string | null; approvedBy?: string | null }): boolean;
65
+ /** What an agent's done writes on a thread: resolved by it, for `by`, its working mark cleared */
66
+ export function agentDone(agent: string, by?: string | null): { status: "done"; doneBy: "claude"; working: null; doneAgent: string | null; doneFor: string | null };
67
+ /** What an agent's reopen writes: open, stamped, back in the agent's queue when it is the agent's */
68
+ export function agentReopen(c: { assignee?: string | null } | null | undefined, at?: string): { status: "open"; doneBy: null; doneAgent: null; doneFor: null; working: null; reopenedAt: string; stage?: "approved" };
69
+ /** The fields that differ between two copies of a thread, a field taken away as null (patch_thread.sql) */
70
+ export function changedFields(was: Record<string, unknown>, now: Record<string, unknown>): Record<string, unknown>;
44
71
  /** The agent a message can @mention: one, Claude */
45
72
  export function agentHandles(): { assignee: string; handle: string; owner: string | null }[];
46
73
  /** The agent a text hands its thread to: the last one it @mentions, else null */
@@ -48,6 +75,14 @@ export function agentMentioned(text: string, people?: { email: string; name?: st
48
75
  export type AgentStep = "held" | "queued" | "asks" | "working" | "stuck" | "review" | "done";
49
76
  /** Where a thread is on an agent's way; null when no agent is in it */
50
77
  export function agentStep(c: Record<string, any> | null | undefined, now?: number): AgentStep | null;
78
+ /** No step for this long (ms) and a run that steps went quiet */
79
+ export const QUIET: number;
80
+ /** «now», «4 min», «2 h» since an ISO time */
81
+ export function elapsed(iso?: string | null, now?: number): string;
82
+ /** A step cut in the middle to `max` characters (31), keeping the file's extension */
83
+ export function stepWords(text?: string | null, max?: number): string;
84
+ /** Claude's live step: its words (null without the hook), time since taken, time since the last step, the mark gone stale */
85
+ export function liveStep(c: Record<string, any> | null | undefined, now?: number): { step: string | null; elapsed: string; silent: string; stale: boolean } | null;
51
86
  /** How far along each step is: rays of the agent mark lit, of 12 */
52
87
  export const STEP_RAYS: Record<AgentStep, number>;
53
88
  /** The agent mark's rays one by one, clockwise from the top (viewBox AI_BOX) */
@@ -62,6 +97,8 @@ export const DOCS: { pdf: string; doc: string; docx: string };
62
97
  export function docSlug(name: string): string;
63
98
  /** What to call a document — "brief.pdf" — by its path or data: URL; null when it is not one */
64
99
  export function docOf(path: string): string | null;
100
+ export function fileThread(name: string): number | null;
101
+ export function filePrefixes(id: number): string[];
65
102
  /** Programs, installers and scripts a double-click runs: never taken. */
66
103
  export const BLOCKED: RegExp;
67
104
  export const FILE_KINDS: [label: string, color: string, extensions: string][];
@@ -84,6 +121,8 @@ export const QUICK: string[];
84
121
  export const EMOJI: string[];
85
122
  /** One emoji (a single grapheme of emoji code points), else null */
86
123
  export function cleanEmoji(v: unknown): string | null;
124
+ /** Where the element sat in its before frame, as fractions of the frame (0–1), clipped to it; else null */
125
+ export function cleanBox(v: unknown): { x: number; y: number; w: number; h: number } | null;
87
126
  /** The most kinds of reaction a message holds */
88
127
  export const MAX_REACTIONS: number;
89
128
  /** The reactions with `who`'s `emoji` toggled — undefined when none is left, null past MAX_REACTIONS kinds */