notemend 0.1.28 → 0.1.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +17 -13
- package/bin/init.mjs +21 -21
- package/bin/notemend.mjs +15 -16
- package/bin/step.mjs +1 -1
- package/package.json +1 -1
- package/src/client/index.js +196 -164
- package/src/client/notemend.css +1 -1
- package/src/integration.mjs +2 -1
- package/src/next.mjs +1 -1
- package/src/server/middleware.mjs +4 -4
- package/src/store/cloud.mjs +3 -3
- package/src/store/comments.mjs +4 -3
- package/src/store/thread.mjs +1 -1
- package/store.d.ts +1 -3
- package/thread.d.ts +26 -9
package/src/integration.mjs
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
import{fileURLToPath as
|
|
1
|
+
import{readFileSync as g}from"node:fs";import{fileURLToPath as m}from"node:url";import{notemendMiddleware as w}from"./server/middleware.mjs";const v=m(new URL("..",import.meta.url));function _(s={}){let n=[];const r=new Map;return{name:"notemend",hooks:{"astro:config:setup":({command:e,config:t,injectScript:i,updateConfig:l})=>{if(e!=="dev"||s.enabled===!1)return;const d=m(t.root);i("page",'import "notemend/client";'),i("head-inline","document.addEventListener('readystatechange',()=>{if(document.readyState==='interactive'&&!window.__notemendPage)window.__notemendPage=document.implementation.createHTMLDocument('').importNode(document.body,true)});"),i("head-inline","window.__notemendEarly=Object.fromEntries(['config',(()=>{let c='comments';try{if(localStorage.getItem('dt-resolved')==='0'&&localStorage.getItem('dt-archived')!=='1')c+='?open=1'}catch{}return c})()].map((p)=>[p,fetch('/__devbar/'+p).catch(()=>null)]));"),l({vite:{optimizeDeps:{exclude:["notemend"]},server:{fs:{allow:[d,v]}},plugins:[{name:"notemend",enforce:"pre",transform(o,c){if(c.endsWith(".astro"))try{r.set(c,u(g(c,"utf8")))}catch{}},hotUpdate:{order:"pre",async handler({file:o,modules:c,read:f}){if(this.environment.name!=="client"||!o.endsWith(".astro"))return;const a=u(await f()),p=r.get(o);if(r.set(o,a),p===a)return c.filter(h=>!h.id?.includes("type=script"))}},configureServer(o){o.middlewares.use(w({root:d,options:s,routes:()=>n})),b(o)}}]}})},"astro:routes:resolved":({routes:e})=>{n=e}}}}function b(s){const n=s.ws,r=n.send.bind(n);let e=0;n.on("notemend:refreshed",()=>{clearTimeout(e),e=0}),n.send=(t,...i)=>t&&typeof t=="object"&&t.type==="full-reload"&&!t.triggeredBy&&!t.path?(clearTimeout(e),e=setTimeout(()=>{e=0,r(t)},1500),r({type:"custom",event:"notemend:refresh",data:{}})):r(t,...i)}const u=s=>(s.match(/<script\b[\s\S]*?<\/script>/gi)??[]).join(`
|
|
2
|
+
`);export{_ as default};
|
package/src/next.mjs
CHANGED
|
@@ -4,4 +4,4 @@ let d;async function o(n){if(process.env.NODE_ENV!=="development")return new Res
|
|
|
4
4
|
|
|
5
5
|
`),25e3),a=e.stream(c=>r(`data: ${c}
|
|
6
6
|
|
|
7
|
-
`)),n.signal.addEventListener("abort",()=>{t();try{l.close()}catch{}})},cancel:t});return new Response(u,{headers:{"content-type":e.type,"cache-control":"no-store, no-transform"}})}return new Response(e.status===204||e.status===304?null:e.body,{status:e.status,headers:{"content-type":e.type,"cache-control":"no-store"}})}export{o as DELETE,o as GET,o as PATCH,o as POST};
|
|
7
|
+
`)),n.signal.addEventListener("abort",()=>{t();try{l.close()}catch{}})},cancel:t});return new Response(u,{headers:{"content-type":e.type,"cache-control":"no-store, no-transform"}})}return new Response(e.status===204||e.status===304?null:e.body,{status:e.status,headers:{"content-type":e.type,"cache-control":"no-store",...e.headers}})}export{o as DELETE,o as GET,o as PATCH,o as POST};
|
|
@@ -1,7 +1,7 @@
|
|
|
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?.()&<(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
|
|
1
|
+
import{readFileSync as he,existsSync as re,statSync as Fe,readdirSync as _e,watch as De}from"node:fs";import{mask as Me}from"../store/mask.mjs";import{join as W,isAbsolute as Le}from"node:path";import{isIP as ye}from"node:net";import{pathToFileURL as He}from"node:url";import{openStore as Re,retry as ze,retryThread as Ge,CABINET as ue,session as oe,deviceLogin as Je}from"../store/cloud.mjs";import{mentionsIn as Ue,clashOf as We,clientSpace as we,cleanAssignee as fe,cleanBox as Ve,cleanEmoji as Ke,cut as q,MAX_REACTIONS as Xe,STAGES as xe,threadOf as Ze,toAgent as de}from"../store/thread.mjs";import{fileFrame as me,react as Qe,shotName as ve}from"../store/comments.mjs";import{stateOf as Ye}from"../store/status.mjs";import{CATEGORIES as qe,categoryOf as et}from"../store/categories.mjs";import{BREAKPOINTS as tt,DEVICES as nt,ICONS as Se,SHELLS as je,BROWSERS as Oe}from"../presets.mjs";const rt={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"},Ne=e=>e.split(".").slice(0,2).map(Number).reduce((t,s)=>t*100+(Number.isNaN(s)?9999:s),0),be=(e,t)=>{try{const s=he(Le(t)?t:W(e,t),"utf8"),f=s.match(/\bmetadata\b[^=]*=\s*\{[^}]*?\btitle:\s*["'`]([^"'`$]+)["'`]/)??s.match(/<title>([^<{]+)<\/title>/)??(/\.[jt]sx?$/.test(t)?s.match(/<h1\b[^>]*>\s*([^<{]+?)\s*<\/h1>/):s.match(/title="([^"]+)"|\btitle:\s*["'`]([^"'`]+)["'`]/));return(f?.[1]??f?.[2])?.trim()||null}catch{return null}},ke=e=>e.split(/\s+[—–|]\s+/).map(t=>t.trim()).filter(Boolean),ot=(e,t,s)=>{const f=be(e,t);if(!f)return null;const i=ke(f);return(s?i.filter(m=>m!==s)[0]:i.pop())||null},st=e=>{const t={};for(const f of e){const i=f?ke(f):[];if(i.length>1)for(const m of new Set([i[0],i.at(-1)]))t[m]=(t[m]||0)+1}const[s]=Object.entries(t).sort((f,i)=>i[1]-f[1]);return s?.[1]>1?s[0]:void 0};function bt(e){const t=["app","src/app"].map(i=>W(/* turbopackIgnore: true */ e,i)).find(re),s=[],f=(i,m)=>{for(const u of _e(i,{withFileTypes:!0})){const l=u.name;if(u.isDirectory()){if(/^[_@]|^\(\./.test(l))continue;f(W(i,l),/^\(.+\)$/.test(l)?m:[...m,l])}else/^page\.(jsx?|tsx?|mdx?)$/.test(l)&&s.push({origin:"project",type:"page",pattern:"/"+m.join("/"),entrypoint:W(i,l)})}};return t&&f(t,[]),s}const $e=e=>e[0].toUpperCase()+e.slice(1).replace(/[-_]+/g," ");function at({root:e,options:t,routes:s}){const f=t.pages??{},i=(n,x,J)=>({route:n,name:x,label:x.replace(/^[\d.]+[A-Z]?\.\s*/,""),group:J}),m=s.filter(n=>n.origin==="project"&&n.type==="page"&&!n.pattern.includes("[")).map(n=>({route:n.pattern.replace(/\/+$/,"")||"/",entrypoint:n.entrypoint})),u=new Set(m.map(n=>n.route)),l=[...m,...Object.keys(f).filter(n=>!u.has(n)).map(n=>({route:n}))].filter(({route:n})=>f[n]!==null),B={};for(const{route:n}of l){const x=n.split("/")[1];x&&(B[x]=(B[x]||0)+1)}const A=n=>{const x=n.split("/")[1];return x&&B[x]>1?$e(x):"Pages"},G=t.groups?()=>t.groups[t.groups.length-1]:A,H=st(l.map(({entrypoint:n})=>n&&be(e,n))),te=l.map(({route:n,entrypoint:x})=>{const[J,X]=f[n]??[];return i(n,J??(x&&ot(e,x,H))??(n==="/"?"Home":$e(n.split("/").pop())),X??G(n))}),V=t.groups??[...new Set([...Object.values(f).filter(Boolean).map(([,n])=>n).filter(Boolean),"Pages",...te.map(n=>n.group).sort()])],K=te.sort((n,x)=>V.indexOf(n.group)-V.indexOf(x.group)||Ne(n.name)-Ne(x.name)||n.route.localeCompare(x.route)),ne=(t.breakpoints??tt).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??Se[n.id]??Se.desktop})),E=(t.devices??nt).filter(n=>n.w>0&&n.h>0&&je.includes(n.shell)&&Oe.includes(n.browser)?!0:(console.warn(`[notemend] device "${n.id}" skipped: it needs w and h, shell (${je.join(", ")}) and browser (${Oe.join(", ")})${n.frame?"; `frame` pictures were replaced by shell + browser in 0.3":""}`),!1));return{pages:K,groups:V.filter(n=>K.some(x=>x.group===n)),breakpoints:ne,devices:E,categories:qe,sanity:!!t.sanity,shortcuts:t.shortcuts!==!1,ignore:t.ignore??[],grid:{container:"container",grid:"grid",columns:12,...t.grid},zIndex:t.zIndex??2000000020}}const it=e=>{const t=W(e,"notemend.config.mjs");let s=0,f={};return async()=>{if(!re(t))return{};const i=Fe(t).mtimeMs;if(i===s)return f;s=i;try{const{default:m,...u}=await import(/* webpackIgnore: true */ /* turbopackIgnore: true */ `${He(t).href}?t=${i}`);f={...u,...m}}catch(m){console.warn(`[notemend] notemend.config.mjs: ${m.message}`)}return f}},ct=e=>{const t=String(e.headers.host||"").toLowerCase(),s=t.startsWith("[")?t.slice(1,t.indexOf("]")):t.replace(/:\d+$/,"");return s.includes(":")?ye(s)===6:!s||!s.includes(".")||ye(s)===4||/\.(localhost|local|test|internal|lan|home\.arpa)$/.test(s)},w=(e,t)=>q(String(e??"").replace(/[\u0000-\u001f\u007f]+/g," ").trim(),t),lt=["id","data","aria","alt","title","src","href","head","sib"],ee=e=>{if(!e||typeof e!="object")return;const t=Object.fromEntries(lt.filter(s=>typeof e[s]=="string"&&e[s].trim()).map(s=>[s,w(e[s],120)]));return Object.keys(t).length?t:void 0},se=e=>e&&Number.isFinite(e.x)&&Number.isFinite(e.y)?{x:Math.round(Math.min(Math.max(e.x,0),1e5)),y:Math.round(Math.min(Math.max(e.y,0),1e6))}:void 0,Ae=e=>e&&typeof e=="object"&&typeof e.selector=="string"?{selector:w(e.selector,2e3),label:w(e.label,200),ctx:w(e.ctx,120),tag:w(e.tag,40),classes:Array.isArray(e.classes)?e.classes.slice(0,20).map(t=>w(t,80)):[],nth:Number.isInteger(e.nth)?e.nth:null,rx:.5,ry:.5,...ee(e.fp)?{fp:ee(e.fp)}:{}}:void 0,ut=e=>({...ee(e.fp)?{fp:ee(e.fp)}:{},...se(e.spot)?{spot:se(e.spot)}:{},...Ae(e.opener)?{opener:Ae(e.opener)}:{}}),ft=e=>({route:w(e.route,500),text:q(e.text,1e4),selector:w(e.selector,2e3),rx:Number.isFinite(e.rx)?e.rx:0,ry:Number.isFinite(e.ry)?e.ry:0,label:w(e.label,200),ctx:w(e.ctx,120),breakpoint:w(e.breakpoint,40),browser:w(e.browser,80),device:w(e.device,80),tag:w(e.tag,40),classes:Array.isArray(e.classes)?e.classes.slice(0,20).map(t=>w(t,80)):[],nth:Number.isInteger(e.nth)?e.nth:null,category:w(e.category,40),...ut(e),...["urgent","high","normal","low"].includes(e.priority)?{priority:e.priority}:{},...e.shared===!0?{shared:!0}:{},...Number.isInteger(e.from?.id)&&e.from.id>0?{from:{id:e.from.id}}:{},viewport:e.viewport&&Number.isFinite(e.viewport.w)&&Number.isFinite(e.viewport.h)?{w:e.viewport.w,h:e.viewport.h}:null,...fe(e.assignee)?{assignee:fe(e.assignee)}:{},...xe.includes(e.stage)?{stage:e.stage}:{},...typeof e.host=="string"&&/^[a-z0-9.-]{1,120}(:\d{1,5})?$/i.test(e.host)?{host:e.host.toLowerCase()}:{},...Array.isArray(e.logs)&&e.logs.length?{logs:e.logs.slice(-20).map(t=>({at:w(t?.at,30),kind:["console","error","rejection","network"].includes(t?.kind)?t.kind:"console",text:Me(w(t?.text,500))})).filter(t=>t.text)}:{},...e.suggest&&typeof e.suggest.from=="string"&&typeof e.suggest.to=="string"&&e.suggest.to.trim()?{suggest:{from:q(e.suggest.from,2e3),to:q(e.suggest.to,2e3)}}:{}}),dt=e=>{const t={};if((e.status==="open"||e.status==="done")&&(t.status=e.status),e.status==="open"&&Object.assign(t,{reopenedAt:new Date().toISOString(),reopenedBy:"you"}),"doneBy"in e&&(t.doneBy=e.doneBy==="you"?"you":null),typeof e.category=="string"&&(t.category=et(e.category).id),"priority"in e&&(t.priority=["urgent","high","normal","low"].includes(e.priority)?e.priority:null),typeof e.shared=="boolean"&&(t.shared=e.shared||null),e.client===!1&&(t.client=null),"assignee"in e&&(t.assignee=fe(e.assignee)),"stage"in e&&(t.stage=xe.includes(e.stage)?e.stage:null),typeof e.archived=="boolean"&&(t.archived=e.archived),"box"in e&&(t.box=Ve(e.box)),e.move&&typeof e.move=="object"&&typeof e.move.selector=="string"){const s=e.move,f=i=>Number.isFinite(i)?Math.min(1,Math.max(0,i)):.5;Object.assign(t,{selector:w(s.selector,2e3),rx:f(s.rx),ry:f(s.ry),label:w(s.label,200),ctx:w(s.ctx,120),tag:w(s.tag,40),classes:Array.isArray(s.classes)?s.classes.slice(0,20).map(i=>w(i,80)):[],nth:Number.isInteger(s.nth)?s.nth:null,...ee(s.fp)?{fp:ee(s.fp)}:{},...se(s.spot)?{spot:se(s.spot)}:{}}),typeof e.repin=="string"&&e.repin.trim()&&Object.assign(t,{repinnedAt:new Date().toISOString(),repinnedBy:"you",repinnedFrom:w(e.repin,120)}),e.repin===!1&&Object.assign(t,{repinnedAt:null,repinnedBy:null,repinnedFrom:null})}return"anchor"in e&&(t.anchor=["moved","probably","gone"].includes(e.anchor)?e.anchor:null),t},ae=e=>{const t=e.headers.origin;if(!t)return!1;try{return new URL(t).host!==e.headers.host}catch{return!0}};function mt({root:e,options:t,routes:s,open:f=()=>Re(e),crossOrigin:i=!1}){const m=it(e),u=(c,h=200)=>({status:h,type:"application/json",body:JSON.stringify(c)}),l=(c,h)=>({status:c,type:"text/plain; charset=utf-8",body:h}),B=async c=>{const h=await c.body();if(h.length>(i?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})}},A=async(c,h,a)=>{const O=async o=>{const r=await h(o);if(r.status>=400)throw Object.assign(new Error("not written"),{out:r});return r};try{return c.cloud&&a!=null&&c.thread?await Ge(c,a,O):await ze(c,O)}catch(o){if(o.out)return o.out;throw o}finally{H=null,x++,J()&&X()}},G=new Set;let H=null,te=0,V=!1,K=!1,ne=null,E=null,n=0,x=0;const J=()=>G.size>0||Date.now()-n<3e4,X=async()=>{if(i)return;if(V){K=!0;return}V=!0,clearTimeout(ne);let c=!1;try{const h=await f();c=!!h.cloud;const a=x,O=h.version?String(await h.version()):null;if(a!==x)K=!0;else if(te=Date.now(),O!==H){H=O;for(const o of G)o(O)}if(!c&&!E&&J()&&re(W(e,"feedback")))try{E=De(W(e,"feedback"),(o,r)=>{String(r).startsWith("comments.json")&&X()}),E.on("error",()=>{E?.close(),E=null})}catch{E=null}}catch{}if(V=!1,K)return K=!1,X();J()?ne=setTimeout(X,c?1500:E?1e3:250):(E?.close(),E=null)},Be=c=>(G.add(c),H!=null&&c(H),X(),()=>{G.delete(c),n=Date.now()}),Ie=()=>J()&&H!=null&&Date.now()-te<3e3?H:null,pe=new Map,Te=async(c,h)=>{if(c.method!=="GET"&&!i&&ae(c))return l(403,"Cross-origin write refused");const a=await f();if(c.method==="GET"){const d=h.searchParams.get("route"),P=h.searchParams.get("since"),L=Ie();if(P!=null&&a.version&&P===(L??String(await a.version())))return{status:204,type:"text/plain",body:""};const Q=h.searchParams.get("open")==="1",N=`${d??""}|${Q}`,C=L!=null&&pe.get(N);if(C&&C.v===L)return C.res;const b=await a.load(Q?{open:!0}:void 0);let $=d?b.comments.filter(z=>z.route===d):b.comments;Q&&($=$.filter(z=>Ye(z)!=="done")),$=$.map(({logs:z,...Y})=>Y);const k=a.versionOf?a.versionOf(b):null,F=u({version:k==null?null:String(k),comments:$,listening:b.listening??null,turbo:b.turbo??null});return!i&&k!=null&&pe.set(N,{v:String(k),res:F}),F}const O=c.method==="DELETE"?null:await B(c);let o=null,r=null;const I=c.method==="POST"||!!O?.reply?.trim?.()||O?.stage!==void 0,R=a.cloud&&O?(I?a.people():a.me().then(d=>({me:d,team:[]}))).then(d=>{o=d,r=d.me}).catch(d=>d):Promise.resolve(),U=async()=>{const d=await R;if(d instanceof Error)throw d},ge=d=>{if(r&&d){d.by=r.email,d.byName=r.name;const P=Ue(d.text,o.team.filter(L=>L.email!==r.email));P.length&&(d.mentions=P)}return d};if(c.method==="POST"){const{image:d,images:P,before:L,...Q}=O,N=ft(Q);return N.text.trim()?/^\/(?![\/\\])/.test(N.route)?A(a,async C=>{await U(),o?.client&&(N.client=!0,de(N.assignee)&&delete N.assignee,N.stage==="approved"&&delete N.stage);const b=N.from&&!N.shared&&!N.client?C.comments.find(F=>F.id===N.from.id):null,$=!!b&&we(b);if($){const F=C.comments.find(z=>z.from?.id===b.id&&!we(z));if(F)return u(F,200)}const k=ge(a.add(C,N));$&&(k.from={id:b.id,...b.by?{by:b.by}:{},...b.byName?{byName:b.byName}:{}}),r&&de(k.assignee)&&(k.handedBy=r.email);for(const F of[].concat(P??d??[]))await a.attach(C,k.id,F);return await me(a,C,k.id,L,"before"),u(k,201)}):u({error:"route must be a path"},400):u({error:"empty comment"},400)}if(c.method==="PATCH"){const d=O;if(d.turbo==="on"||d.turbo==="off")return A(a,async p=>(p.turbo={paused:d.turbo==="off",at:new Date().toISOString()},u({turbo:p.turbo})));if(Array.isArray(d.push)||Array.isArray(d.unpush)){const p=j=>(Array.isArray(j)?j:[]).map(Number).filter(S=>Number.isInteger(S)&&S>0).slice(0,500);return A(a,async j=>{const S=new Set(j.turbo?.push?.ids??[]);for(const T of p(d.push))S.add(T);for(const T of p(d.unpush))S.delete(T);const _=T=>j.comments.some(ce=>ce.id===T&&ce.status!=="done"),D=new Set((j.turbo?.batch?.ids??[]).filter(_)),M=!D.size;for(const T of p(d.push))D.add(T);for(const T of p(d.unpush))D.delete(T);const v=new Date().toISOString();return j.turbo={...j.turbo??{paused:!0},push:{at:v,ids:[...S]},batch:{at:M?v:j.turbo?.batch?.at??v,ids:[...D]}},u({turbo:j.turbo})})}const{id:P,reply:L,image:Q,images:N,removeImage:C,uploaded:b,edit:$,unsay:k,before:F,after:z,react:Y,seen:Pe,...Ce}=d,g=Number(P);if(!Number.isInteger(g))return u({error:"bad id"},400);if(Y){const p=Ke(Y.emoji),j=typeof Y.at=="string"&&Y.at?Y.at:null;return p?a.cloud?a.react(g,j,p).then(u,S=>u({error:S.message},S.status>=400&&S.status<500?S.status:500)):A(a,async S=>{const _=Qe(S,g,j,p,"you");return _===!1?u({error:`${Xe} kinds of reaction at most`},400):_?u(_):u({error:`no message to react to in #${g}`},404)},g):u({error:"not an emoji"},400)}if(typeof k=="string"){let p=[];const j=await A(a,async S=>{const _=S.comments.find(M=>M.id===g),D=_?.replies?.find(M=>M.at===k);return!D||r&&D.by&&D.by!==r.email?u({error:`no reply of yours to delete in #${g}`},404):(p=Ze(_).find(M=>M.at===k&&M.author==="you")?.images??[],a.unsay(S,g,k)?u(_):u({error:`no reply of yours to delete in #${g}`},404))},g);if(j.status<400)for(const S of p)await a.forget(ve(S));return j}const y=dt(Ce);return A(a,async p=>{await U();const j=p.comments.find(v=>v.id===g),S=We(j,Pe,y,r?.email);if(S)return u({error:`#${g} was just changed by someone else`,...S,thread:j},409);if($){const v=p.comments.find(le=>le.id===Number(g)),T=$.at?v?.replies?.find(le=>le.at===$.at):v;if(r&&T?.by&&T.by!==r.email||!($.text?.trim?.()&&a.edit(p,g,$.at??null,q($.text.trim(),1e4))))return u({error:`no message of yours to edit in #${g}`},404)}L?.trim?.()&&ge(a.reply(p,g,"you",q(L.trim(),1e4))?.replies.at(-1));for(const v of[].concat(N??Q??[]))await a.attach(p,g,v);for(const v of[].concat(b??[]))if(a.adopt&&!await a.adopt(p,g,v))return u({error:`${v} did not arrive`},400);for(const v of[].concat(C||[]))await a.detach(p,g,v);if(await me(a,p,g,F,"before"),await me(a,p,g,z,"after"),r&&y.status==="done"&&Object.assign(y,{confirmedBy:r.email,confirmedAt:new Date().toISOString()}),r&&y.status==="open"&&Object.assign(y,{confirmedBy:null,confirmedAt:null,reopenedBy:r.email}),r&&y.repinnedBy&&(y.repinnedBy=r.email),"archived"in y){const v=y.archived;delete y.archived,Object.assign(y,v?{archivedAt:new Date().toISOString(),archivedBy:r?.email??null}:{archivedAt:null,archivedBy:null})}y.status==="open"&&Object.assign(y,{archivedAt:null,archivedBy:null}),r&&(y.stage==="review"||y.stage!==void 0&&!o?.client)&&(y.stageBy=r.email),r&&"assignee"in y&&(y.handedBy=de(y.assignee)?r.email:null);const _=Object.keys(y).length&&Object.keys(y).every(v=>v==="anchor"),D=p.comments.find(v=>v.id===Number(g)),M=_?D&&Object.assign(D,y):Object.keys(y).length?a.patch(p,g,y):p.comments.find(v=>v.id===Number(g));return M?u(M):u({error:`no comment #${g}`},404)},g)}if(c.method==="DELETE"){const d=Number(h.searchParams.get("id"));return A(a,async P=>await a.remove(P,d)?u({ok:!0,id:d}):u({error:`no comment #${d}`},404))}return l(405,"Method not allowed")},Ee=(c,h)=>{const a=h.replace(/^.*[/\\]/,""),O=a.split(".").pop()?.toLowerCase()??"",o=rt[O]??(ve(a)?"application/octet-stream":null);if(!/^[\w.-]+$/.test(a)||!o)return l(400,"Bad name");const r=W(c,a);return re(r)?{status:200,type:o,body:he(r)}:l(404,"Not found")};let ie=!1,Z=null;return async c=>{const h=new URL(c.url,"http://devbar"),a=h.pathname.slice(10);if(!i&&!ct(c))return l(403,"Notemend answers local addresses only");const O=c.headers["sec-fetch-site"];if(!i&&O&&O!=="same-origin")return l(403,"Notemend answers its own pages only");try{if(a==="config"&&c.method==="PATCH"){if(!i&&ae(c))return l(403,"Cross-origin write refused");const o=await f(),r=await B(c)??{};return"folders"in r?o.setFolders?u({folders:await o.setFolders(Array.isArray(r.folders)&&r.folders.length?r.folders:null)}):l(400,"Link the site to a project to keep its folders"):o.cloud?u({grid:await o.setGrid(r.grid??null)}):l(400,"Link the site to a project to set its grid")}if(a==="config"){const o=at({root:e,options:{...await m(),...t},routes:s()}),r=await f();return r.cloud?Object.assign(o,await r.people({fresh:!0}).catch(I=>{if(I.said)throw I;return{}})):r.folders&&Object.assign(o,{folders:r.folders(),arrange:!0}),(r.cloud||await oe().catch(()=>null))&&(o.voice=!0),r.cloud&&!i&&(o.cabinet=ue),u(o)}if(a==="transcribe"&&c.method==="POST"){if(!i&&ae(c))return l(403,"Cross-origin write refused");const o=await f(),r=o.cloud?await o.token():(await oe().catch(()=>null))?.access_token;if(!r)return l(401,"Voice replies need Notemend \u2014 run `npx notemend login`.");const{audio:I}=await B(c),R=/^data:(audio\/(?:webm|mp4))(?:;[\w=.-]+)*;base64,(.+)$/s.exec(String(I||""));if(!R)return l(400,"Not a recording");const U=await fetch(`${ue}/api/transcribe`,{method:"POST",body:Buffer.from(R[2],"base64"),headers:{authorization:`Bearer ${r}`,"content-type":R[1]}});return{status:U.status,type:"application/json",body:await U.text()}}if(a==="translate"&&c.method==="POST"){if(!i&&ae(c))return l(403,"Cross-origin write refused");const o=await f(),r=o.cloud?await o.token():(await oe().catch(()=>null))?.access_token;if(!r)return l(401,"Translating needs Notemend \u2014 run `npx notemend login`.");const{text:I,to:R}=await B(c),U=await fetch(`${ue}/api/translate`,{method:"POST",body:JSON.stringify({text:I,to:R}),headers:{authorization:`Bearer ${r}`,"content-type":"application/json"}});return{status:U.status,type:"application/json",body:await U.text()}}if(a==="signin"&&!i){if(h.searchParams.has("code"))return u({code:Z?.code??null,done:!!await oe().catch(()=>null)});Z||(Z={},Z.go=new Promise(r=>{Je((I,R)=>{Z.code=R,r(I)}).catch(I=>{console.warn(`[notemend] sign-in from the bar: ${I.message}`),r(null)}).finally(()=>{Z=null,ie=!1})}));const o=await Z.go;return o?{status:302,type:"text/plain",body:"",headers:{location:`${o}&from=bar`}}:l(502,"The cabinet did not answer. Try again in a moment.")}if(a==="comments")return await Te(c,h);if(a==="events"&&!i)return{status:200,type:"text/event-stream",body:"",stream:Be};if(a==="image"){const o=await f(),r=(h.searchParams.get("name")||"").replace(/^.*[/\\]/,"");return o.cloud&&/^[\w.-]+$/.test(r)&&await o.fetchImage(r).catch(()=>null),Ee(o.imageDir,r)}return l(404,"Not found")}catch(o){return o.status===400||o.status===413?l(o.status,o.message):o.signin?(ie||(ie=!0,console.warn(`[notemend] ${o.said}`)),l(401,o.said)):o.said?l(o.status,o.said):o.status===403?l(403,String(o.message).replace(/^notemend: /,"").replace(/ \(403\)$/,"")):(console.error("[notemend]",o),l(500,"Something went wrong on our side. Try again in a moment."))}}}function kt(e){const t=mt(e),s=f=>new Promise((i,m)=>{const u=[];f.on("data",l=>u.push(l)),f.on("end",()=>i(Buffer.concat(u))),f.on("error",m)});return async function(i,m,u){if(!i.url||!i.url.startsWith("/__devbar/"))return u();const l=await t({method:i.method,url:i.url,headers:i.headers,body:()=>s(i)});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
|
|
3
|
+
`);const B=setInterval(()=>m.write(`: ping
|
|
4
4
|
|
|
5
|
-
`),25e3),
|
|
5
|
+
`),25e3),A=l.stream(G=>m.write(`data: ${G}
|
|
6
6
|
|
|
7
|
-
`));
|
|
7
|
+
`));i.on("close",()=>{clearInterval(B),A()});return}m.statusCode=l.status,m.setHeader("content-type",l.type),m.setHeader("cache-control","no-store");for(const[B,A]of Object.entries(l.headers??{}))m.setHeader(B,A);m.end(l.body)}}export{at as buildConfig,mt as notemendHandler,kt as notemendMiddleware,bt as scanApp,ot as titleOf,$e as titled};
|
package/src/store/cloud.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{readFileSync as A,writeFileSync as
|
|
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
|
+
import{readFileSync as A,writeFileSync as S,existsSync as H,mkdirSync as D,rmSync as q}from"node:fs";import{homedir as ce}from"node:os";import{dirname as I,join as k}from"node:path";import{createStore as ue,add as de,reply as le,edit as he,unsay as me,patch as fe,shotName as j,mediaOf as pe,mediaName as R,Conflict as $}from"./comments.mjs";import{changedFields as we}from"./thread.mjs";const G=process.env.NOTEMEND_APP||"https://app.notemend.com",E={url:process.env.NOTEMEND_SUPABASE_URL||"https://xzhnjldvkirrydbyrdnm.supabase.co",key:process.env.NOTEMEND_SUPABASE_KEY||"sb_publishable_b8h8jTHZ9KtbPvMuroLhqA_-yBqZwd6"},N=k(process.env.NOTEMEND_HOME||k(ce(),".config","notemend"),"session.json"),M=t=>k(t,".notemend.json"),ye=t=>{try{return JSON.parse(A(M(t),"utf8")).project||null}catch{return null}},qe=(t,e)=>S(M(t),JSON.stringify({project:e},null,2)+`
|
|
2
|
+
`),Me=t=>q(M(t),{force:!0}),_e=()=>{try{const t=JSON.parse(A(N,"utf8"));return t.url===E.url?t:null}catch{return null}},ge=t=>{D(I(N),{recursive:!0}),S(N,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,{mode:384})},Be=()=>q(N,{force:!0});async function b(t,{method:e="GET",token:i,body:u,headers:c={},raw:h=!1}={}){const f=await fetch(`${E.url}${t}`,{method:e,headers:{apikey:E.key,authorization:`Bearer ${i||E.key}`,...u&&!h?{"content-type":"application/json"}:{},...c},body:h?u:u&&JSON.stringify(u),signal:AbortSignal.timeout(h?12e4:15e3)});if(!f.ok){const l=await f.text();let y=l;try{const v=JSON.parse(l);y=v.msg||v.message||v.error_description||v.error||l}catch{}const O=new Error(`${y} (${f.status})`);throw O.status=f.status,O}return f}const B=t=>{const e={url:E.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},Ce=t=>b("/auth/v1/otp",{method:"POST",body:{email:t,create_user:!0}}),Le=async(t,e)=>B(await(await b("/auth/v1/verify",{method:"POST",body:{email:t,token:e,type:"email"}})).json());async function Je(t){const e=await fetch(`${G}/api/cli/device`,{method:"POST"}),i=await e.json().catch(()=>({}));if(!e.ok)throw new Error(i.error||`The cabinet said ${e.status}`);console.log(`Your code: ${i.code}`),t(i.url,i.code);const u=Date.now()+i.expires_in*1e3;for(;Date.now()<u;){await new Promise(l=>setTimeout(l,i.interval*1e3));const c=await fetch(`${G}/api/cli/device`,{headers:{authorization:`Bearer ${i.device}`}}).catch(()=>null);if(!c||c.status===202)continue;const h=await c.json().catch(()=>({}));if(!c.ok)throw new Error(h.error||`The cabinet said ${c.status}`);const f=await(await b("/auth/v1/user",{token:h.access_token})).json();return B({user:f,access_token:h.access_token,refresh_token:h.refresh_token,expires_at:Number(h.expires_at)})}throw new Error("No answer from the browser in 10 minutes.")}async function Fe(t,e){const i=await x();if(!i)throw new Error("Sign in first: npx notemend login");return(await(await b("/rest/v1/projects",{method:"POST",token:i.access_token,headers:{prefer:"return=representation"},body:{name:t,...e?{site_url:e}:{}}})).json())[0]}async function x(){const t=_e();if(!t)return null;if(t.expires_at-60>Date.now()/1e3)return t;try{const e=await b("/auth/v1/token?grant_type=refresh_token",{method:"POST",body:{refresh_token:t.refresh_token}});return B(await e.json())}catch(e){if(e.status===400||e.status===401)return null;throw e}}async function He(t,e,i){const u=k(I(N),"seen.json");let c={};try{c=JSON.parse(A(u,"utf8"))}catch{}const h=`${t}|${e}|${i}`;if(Date.now()-(c[h]||0)<6*36e5)return;const f=await x();f&&(await b("/rest/v1/rpc/agent_seen",{method:"POST",token:f.access_token,body:{p_agent:t,p_version:e,p_via:i}}),S(u,JSON.stringify({...c,[h]:Date.now()})))}const W="Not saved \u2014 up to 50 folders, a name of 1\u201360 characters.",z="Not saved \u2014 columns 1\u201324, gutter and margin 0\u2013200, max width 320\u20134000 or empty.",g=new Map;function ke(t,e,i=null){const u=k(t,"feedback","images"),c=n=>`feedback/images/${n}`,h=new WeakMap,f=i?async()=>i:async()=>{const n=await x();if(!n)throw new Error("Not signed in to Notemend \u2014 run `npx notemend login`.");return n},l=async(n,r={})=>b(`/rest/v1/${n}`,{...r,token:(await f()).access_token}),y=async(n,r={})=>b(`/storage/v1/object/shots/${e}/${n}`,{...r,token:(await f()).access_token}),O=`Project ${e} is not there, or you are not in it. Check \`npx notemend link\`.`,v=()=>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 o=await(await l(`stores?project_id=eq.${e}&select=doc,version`)).json();if(!o.length)throw v();const m=o[0].doc;return h.set(m,o[0].version),m}const[r,s]=await Promise.all([l(`stores_meta?project_id=eq.${e}&select=doc,version`).then(o=>o.json()),l(`threads?project_id=eq.${e}&${K}&select=data&order=id`).then(o=>o.json())]);if(!r.length)throw v();const a={...r[0].doc,comments:s.map(o=>o.data)};return h.set(a,r[0].version),a},U=n=>h.get(n)??null,Z=async()=>(await(await l(`stores_meta?project_id=eq.${e}&select=version`)).json())[0]?.version??null,Q=async n=>{const r=h.get(n),s=await(await l(`stores?project_id=eq.${e}&version=eq.${r}&select=version`,{method:"PATCH",body:{doc:n},headers:{prefer:"return=representation"}})).json();if(!s.length)throw new $("Someone else wrote first");h.set(n,s[0].version)},V=async n=>(await(await l(`threads?project_id=eq.${e}&id=eq.${Number(n)}&select=data,v`)).json())[0]??null,X=async(n,r,s,a)=>{const o=we(r,s);if(Object.keys(o).length)try{await l("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,r,s)=>(await(await l("rpc/react",{method:"POST",body:{p_project:e,p_id:Number(n),p_at:r,p_emoji:s}})).json()).thread,te=async()=>(await(await l(`threads?project_id=eq.${e}&select=route:data->>route`)).json()).map(n=>n.route),ne=async()=>({email:(await f()).email}),C=new Map,se=async(n,r,s,a)=>{const o=n.comments.find(_=>_.id===Number(r)),m=pe(s);if(!o||!m)return null;const w=`${o.id}:${a??""}:${s.length}:${s.slice(-48)}`;let d=C.get(w);if(!d||o.images?.includes(c(d))){let _=Date.now();for(;H(k(u,R(o.id,_,m,a)));)_++;d=R(o.id,_,m,a),C.set(w,d)}const p=Buffer.from(m.base64,"base64");return await y(d,{method:"POST",body:p,raw:!0,headers:{"content-type":m.type,"x-upsert":"true"}}),D(u,{recursive:!0}),S(k(u,d),p),(o.images||=[]).push(c(d)),o.updatedAt=new Date().toISOString(),c(d)},re=async(n,r,s)=>{const a=n.comments.find(m=>m.id===Number(r));return!a||j(s)!==s||!s.startsWith(`${a.id}-`)?null:a.images?.includes(c(s))?c(s):await y(s,{method:"HEAD"}).then(()=>!0,()=>!1)?((a.images||=[]).push(c(s)),a.updatedAt=new Date().toISOString(),c(s)):null},T=async n=>{j(n)&&(q(k(u,n),{force:!0}),await y(n,{method:"DELETE"}).catch(()=>{}))};return{cloud:!0,setGrid:async n=>{const r=await(await l(`projects?id=eq.${e}&select=grid`,{method:"PATCH",body:{grid:n},headers:{prefer:"return=representation"}}).catch(s=>{throw/23514|check constraint/.test(s.message)?Object.assign(new Error(z),{status:400,said:z}):s})).json();if(!r.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 s of g.keys())s.startsWith(`${e}|`)&&g.delete(s);return r[0].grid},setFolders:async n=>{const r=await(await l(`projects?id=eq.${e}&select=page_folders`,{method:"PATCH",body:{page_folders:n},headers:{prefer:"return=representation"}}).catch(s=>{throw/23514|check constraint/.test(s.message)?Object.assign(new Error(W),{status:400,said:W}):s})).json();if(!r.length)throw Object.assign(new Error("Only the project\u2019s admins change its folders."),{status:403,said:"Only the project\u2019s admins change its folders."});for(const s of g.keys())s.startsWith(`${e}|`)&&g.delete(s);return r[0].page_folders??[]},project:e,root:t,imageDir:u,load:Y,versionOf:U,version:Z,save:Q,thread:V,patchThread:X,react:ee,routes:te,me:ne,attach:se,adopt:re,detach:async(n,r,s)=>{const a=n.comments.find(w=>w.id===Number(r)),o=j(s),m=o&&a?.images?.find(w=>j(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,r)=>{const s=n.comments.find(a=>a.id===Number(r));if(!s)return!1;for(const a of s.images||[])await T(j(a));return n.comments=n.comments.filter(a=>a.id!==Number(r)),!0},fetchImage:async n=>{if(!j(n)||j(n)!==n)return null;const r=k(u,n);if(H(r))return r;const s=await y(n).catch(()=>null);return s?(D(u,{recursive:!0}),S(r,Buffer.from(await s.arrayBuffer())),r):null},people:async({fresh:n=!1}={})=>{const r=await f(),s=`${e}|${r.email}`,a=g.get(s);if(!n&&a&&Date.now()-a.at<6e4)return a.p;const o=d=>l(`rpc/${d}`,{method:"POST",body:{p:e}}).then(p=>p.json()).catch(()=>null);let m=!1;const w=Promise.all([l("profiles?select=email,name,nickname,avatar_url,agent_name,agent_avatar_url,avatar_hue").then(d=>d.ok?d.json():l("profiles?select=email,name,nickname,avatar_url,agent_name,agent_avatar_url").then(p=>p.json())),o("project_people"),o("is_staff"),o("project_staff"),o("project_lead"),l(`projects?id=eq.${e}&select=auto_archive_days,grid,page_folders,team_id`).then(d=>d.json()).then(async([d])=>{const[p]=d?.team_id?await l(`teams?id=eq.${d.team_id}&select=name,brand_color,brand_logo`).then(_=>_.json()).catch(()=>[]):[];return{autoArchive:d?.auto_archive_days??null,projectGrid:d?.grid??null,folders:d?.page_folders??[],...p?.name?{studioName:p.name}:{},...p&&(p.brand_color||p.brand_logo)?{brand:{color:p.brand_color,logo:p.brand_logo}}:{}}}).catch(()=>({})),o("runs_project")]).then(([d,p,_,L,J,oe,ae])=>{if(Array.isArray(p)&&!p.length)throw v();m=typeof _!="boolean";const F=Array.isArray(p)?new Set(p):null,ie=F?d.filter(P=>F.has(P.email)):d;return{me:d.find(P=>P.email===r.email)??{email:r.email,name:"",avatar_url:null},team:ie,client:_!==!0,...Array.isArray(L)?{studio:L}:{},...typeof J=="string"?{lead:J}:{},...oe,project:e,gridAdmin:ae===!0}});return g.set(s,{at:Date.now(),p:w}),w.then(()=>{m&&g.get(s)?.p===w&&g.delete(s)},()=>{g.get(s)?.p===w&&g.delete(s)}),w},add:de,reply:le,edit:he,unsay:me,patch:fe,token:async()=>(await f()).access_token}}const ve=()=>process.env.NOTEMEND_LOCAL==="1";async function Ie(t){const e=ye(t);if(e&&await x())return ke(t,e);if(ve())return ue(t);const i=await x().catch(()=>null)?"Link this site to a project: run `npx notemend link <project-id>` in the site\u2019s folder.":"Sign in to comment: run `npx notemend login` in the site\u2019s folder.";throw Object.assign(new Error(i),{status:401,said:i,signin:!0})}async function Re(t,e,i){for(let u=0;;u++){const c=await t.thread(e);if(!c)return i({comments:[]});const h=structuredClone(c.data),f={comments:[c.data]},l=await i(f);try{return await t.patchThread(e,h,f.comments[0],c.v),l}catch(y){if(!(y instanceof $)||u>=4)throw y;await new Promise(O=>setTimeout(O,300*(u+1)+Math.random()*300))}}}async function Ge(t,e){for(let i=0;;i++){const u=await t.load(),c=await e(u);try{return await t.save(u),c}catch(h){if(!(h instanceof $)||i>=4)throw h}}}export{E as BACKEND,G as CABINET,$ as Conflict,ke as cloudStore,Fe as createProject,Je as deviceLogin,qe as link,ye as linkedProject,ve as localOnly,Be as logout,Ie as openStore,Ge as retry,Re as retryThread,He as seen,Ce as sendCode,x as session,Me as unlink,Le as verifyCode};
|
package/src/store/comments.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
import{readFileSync as
|
|
2
|
-
`),
|
|
3
|
-
`),
|
|
1
|
+
import{readFileSync as M,writeFileSync as I,existsSync as A,mkdirSync as D,renameSync as T,rmSync as B,statSync as H}from"node:fs";import{dirname as G,join as S}from"node:path";import{categoryOf as P}from"./categories.mjs";import{BLOCKED as Q,DOCS as K,FRAMES as V,docSlug as X,fileExt as Y,frameOf as Z,toggledReaction as U}from"./thread.mjs";import{CATEGORIES as Se,categoryIcon as he,categoryOf as we}from"./categories.mjs";import{stateOf as ve,STATE_LABEL as be}from"./status.mjs";class ee extends Error{}const v=n=>{const e=String(n??"").split(/[/\\]/).pop(),t=/^[\w-][\w.-]*\.([a-z0-9]{1,8})$/i.exec(e);return t&&!Q.test(t[1])?e:""},te=n=>{const e=/^data:(image|video|audio)\/(png|jpeg|webp|gif|webm|mp4)(?:;[\w=.-]+)*;base64,(.+)$/s.exec(String(n||""));if(e&&!/^data:[^,]*;ext=/.test(String(n).slice(0,300))){const[,c,s,m]=e;return(c==="image"?!/^(png|jpeg|webp|gif)$/.test(s):c==="video"?s!=="webm":!/^(webm|mp4)$/.test(s))?null:{base64:m,voice:c==="audio",ext:s==="jpeg"?"jpg":s==="mp4"?"m4a":s,type:`${c}/${s}`}}const t=/^data:([\w.+-]+\/[\w.+-]+)((?:;[\w=.-]+)*);base64,(.+)$/s.exec(String(n||""));if(!t)return null;const i=/;ext=([a-z0-9]{1,8})(?:;|$)/i.exec(t[2])?.[1],o=i?Y(`x.${i}`):Object.keys(K).find(c=>K[c]===t[1]);return o?{base64:t[3],voice:!1,ext:o,type:o==="pdf"?"application/pdf":"application/octet-stream",slug:X(/;name=([\w.-]+)/.exec(t[2])?.[1])||"file"}:null},W=(n,e,t,i)=>`${t.voice?"voice-":V.includes(i)?`${i}-`:""}${n}-${e}${t.slug?`.${t.slug}`:""}.${t.ext}`,fe=async(n,e,t,i,o)=>{if(typeof i!="string")return null;const c=e.comments.find(m=>m.id===Number(t))?.images?.filter(m=>Z(m)===o)??[],s=await n.attach(e,t,i,o);if(s)for(const m of c)await n.detach(e,t,m);return s},C=n=>Math.max(n.nextId||0,n.comments.reduce((e,t)=>Math.max(e,t.id),0)+1);function ne(n,{route:e,selector:t,rx:i,ry:o,text:c,label:s,viewport:m,breakpoint:h,browser:j,device:y,tag:k,classes:E,nth:$,category:F,suggest:N,assignee:b,ctx:z,logs:J,host:r,priority:u,shared:g,stage:a,from:f,client:d,fp:p,spot:w,opener:O}){const l={id:C(n),route:e,selector:t,rx:i,ry:o,text:c,tag:k||"",classes:E||[],nth:Number.isInteger($)?$:null,label:s||"",ctx:z||"",viewport:m||null,...p?{fp:p}:{},...w?{spot:w}:{},...O?{opener:O}:{},breakpoint:h||"desktop",browser:j||"",device:y||"",category:P(F).id,status:"open",note:"",replies:[],doneBy:null,images:[],...N?{suggest:N}:{},...b?{assignee:b}:{},...u?{priority:u}:{},...a?{stage:a}:{},...g?{shared:!0}:{},...d?{client:!0}:{},...Number.isInteger(f?.id)?{from:{id:f.id}}:{},...r?{host:r}:{},...J?.length?{logs:J}:{},createdAt:new Date().toISOString(),updatedAt:null};return n.comments.push(l),n.nextId=l.id+1,l}function re(n,e,t,i,o,c){const s=n.comments.find(m=>m.id===Number(e));return s?((s.replies||=[]).push({author:t,text:i,at:new Date().toISOString(),...o&&o!=="claude"?{agent:o}:{},...c?{by:c}:{}}),s.updatedAt=new Date().toISOString(),s):null}function se(n,e,t,i){const o=n.comments.find(s=>s.id===Number(e)),c=t?o?.replies?.find(s=>s.at===t&&s.author==="you"):o;return c?(c.text=i,o.updatedAt=new Date().toISOString(),o):null}function oe(n,e,t){const i=n.comments.find(c=>c.id===Number(e)),o=i?.replies?.find(c=>c.at===t&&c.author==="you");return o?(o.text="",o.deleted=!0,delete o.mentions,i.updatedAt=new Date().toISOString(),i):null}function le(n,e,t,i,o){const c=n.comments.find(h=>h.id===Number(e)),s=t?c?.replies?.find(h=>h.at===t&&!h.deleted):c;if(!s)return null;const m=U(s.reactions,i,o);return m===null?!1:(m?s.reactions=m:delete s.reactions,c)}function ie(n,e,t){const i=n.comments.find(o=>o.id===Number(e));return i?(Object.assign(i,t,{updatedAt:new Date().toISOString()}),i):null}const _=n=>Array.isArray(n)&&n.length<=50&&n.every(e=>e&&typeof e=="object"&&Object.keys(e).every(t=>["id","name","pages","parent"].includes(t))&&(e.parent==null||typeof e.parent=="string"&&e.parent.length<=40)&&typeof e.id=="string"&&e.id.length>=1&&e.id.length<=40&&typeof e.name=="string"&&e.name.trim().length>=1&&e.name.trim().length<=60&&Array.isArray(e.pages)&&e.pages.length<=500&&e.pages.every(t=>typeof t=="string"&&t.length>=1&&t.length<=500))?n:null;function de(n){const e=S(n,"feedback","comments.json"),t=S(n,"feedback","images"),i=S(n,"feedback","archive"),o=S(i,"images"),c=r=>`feedback/images/${r}`,s=new WeakMap,m=()=>{const r=y(),u=A(e)?JSON.parse(M(e,"utf8")):{comments:[]};return s.set(u,r),u},h=r=>s.get(r)??y(),j=r=>{const u=s.get(r);if(u!==void 0&&u!==y())throw new ee("Someone else wrote first");D(G(e),{recursive:!0});const g=`${e}.${process.pid}.${Date.now()}.tmp`;I(g,JSON.stringify(r,null,2)+`
|
|
2
|
+
`),T(g,e),u!==void 0&&s.set(r,y())},y=()=>{try{const r=H(e);return`${r.mtimeMs}-${r.size}`}catch{return"0"}},k=(r,u,g,a)=>{const f=r.comments.find(O=>O.id===Number(u)),d=te(g);if(!f||!d)return null;D(t,{recursive:!0});let p=Date.now();for(;A(S(t,W(f.id,p,d,a)));)p++;const w=W(f.id,p,d,a);return I(S(t,w),Buffer.from(d.base64,"base64")),(f.images||=[]).push(c(w)),f.updatedAt=new Date().toISOString(),c(w)},E=r=>{v(r)&&B(S(t,v(r)),{force:!0})},$=(r,u,g)=>{const a=r.comments.find(p=>p.id===Number(u)),f=v(g),d=f&&a?.images?.find(p=>v(p)===f);return d?(B(S(t,f),{force:!0}),a.images=a.images.filter(p=>p!==d),a.updatedAt=new Date().toISOString(),!0):!1},F=(r,{dry:u=!1,date:g=new Date().toISOString().slice(0,10)}={})=>{const a=r.comments.filter(l=>l.status==="done"),f=r.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||[])};D(o,{recursive:!0});const p=[];for(const l of a)l.images=(l.images||[]).map(L=>{const x=v(L);if(!x)return L;const R=S(t,x),q=S(o,x);return A(R)&&T(R,q),p.push(x),`feedback/archive/images/${x}`});const w=A(d)?JSON.parse(M(d,"utf8")).comments||[]:[],O=new Set(w.map(l=>l.id));return I(d,JSON.stringify({comments:[...w,...a.filter(l=>!O.has(l.id))]},null,2)+`
|
|
3
|
+
`),r.nextId=C(r),r.comments=f,{moving:a,keeping:f,archiveFile:d,images:p}},N=(r,u)=>{const g=r.comments.find(a=>a.id===Number(u));if(!g)return!1;for(const a of g.images||[])v(a)&&B(S(t,v(a)),{force:!0});return r.comments=r.comments.filter(a=>a.id!==Number(u)),!0},b=S(n,"feedback","folders.json");return{root:n,file:e,imageDir:t,archiveDir:i,archiveImageDir:o,load:m,version:y,versionOf:h,save:j,attach:k,detach:$,forget:E,remove:N,add:ne,patch:ie,reply:re,edit:se,unsay:oe,nextId:C,prune:F,folders:()=>{try{return _(JSON.parse(M(b,"utf8")))??[]}catch{return[]}},setFolders:r=>{const u=r==null?[]:_(r);if(!u)throw Object.assign(new Error("bad folders"),{status:400,said:"Not saved \u2014 up to 50 folders, a name of 1\u201360 characters."});return D(G(b),{recursive:!0}),I(b,JSON.stringify(u,null,2)+`
|
|
4
|
+
`),u}}}export{Se as CATEGORIES,ee as Conflict,be as STATE_LABEL,ne as add,he as categoryIcon,we as categoryOf,de as createStore,se as edit,fe as fileFrame,W as mediaName,te as mediaOf,C as nextId,ie as patch,le as react,re as reply,_ as saneFolders,v as shotName,ve as stateOf,oe as unsay};
|
package/src/store/thread.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
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};
|
|
1
|
+
const K=["before","after"],x=e=>/(?:^|\/)(before|after)-[^/]*$/.exec(String(e))?.[1]??null,J=e=>{const t={};for(const n of e?.images||[]){const o=x(n);o&&(t[o]=n)}return t},h={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},C=/^(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,I=/^(png|jpe?g|webp|gif|webm)$/i,d=typeof Intl<"u"&&Intl.Segmenter?new Intl.Segmenter:null,A=(e,t)=>{const n=String(e??"");if(n.length<=t)return n;let o="";if(d)for(const{segment:r}of d.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},N=[["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"]],V=e=>{const t=String(e??"").split(".").pop().toLowerCase(),n=N.find(([,,o])=>o.split(" ").includes(t));return n?{label:n[0],color:n[1]}:{label:"FILE",color:"#717171"}},X=e=>/\.(pdf|png|jpe?g|webp|gif|mp4|mov|webm|mp3|wav|m4a)$/i.test(String(e??"").split("?")[0]),O=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]])),Y=e=>String(e??"").replace(/\.[^.]*$/,"").toLowerCase().replace(/[а-яёєіїґ]/g,t=>O[t]??"").normalize("NFKD").replace(/[^\w-]+/g,"-").replace(/^[-_]+|-+$/g,"").slice(0,60),q=e=>{const t=/\.([a-z0-9]{1,8})$/i.exec(String(e??""));return t&&!C.test(t[1])?t[1].toLowerCase():""},Q=e=>Number(/^(?:before-|after-|voice-)?(\d+)-\d+(?:\.[\w-]+)?\.\w+$/i.exec(String(e??"").split("/").pop())?.[1])||null,Z=e=>["","before-","after-","voice-"].map(t=>`${t}${Number(e)}-`),ee=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(h).find(a=>h[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&&!I.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(x(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)},te=["\u{1F44D}","\u2764\uFE0F","\u{1F602}","\u{1F389}","\u{1F440}","\u{1F525}"],ne=["\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"],M=/^(?:\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Regional_Indicator}|\u200d|\ufe0f)+$/u,oe=e=>typeof e!="string"||!e||e.length>16||!M.test(e)?null:[...new Intl.Segmenter().segment(e)].length===1?e:null,re=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=l=>Math.min(1,Math.max(0,l)),o=l=>Math.round(l*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},E=20,se=(e,t,n)=>{const o={...e||{}},r=o[t]||[];if(!r.length&&Object.keys(o).length>=E)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},ae=e=>e.nickname||e.name||e.email,D="(?![\\p{L}\\p{N}_]|[.-][\\p{L}\\p{N}_])",v=new RegExp("^"+D,"u"),w=(e,t)=>{const n="@"+t.toLowerCase();let o=-1;for(let r=e.indexOf(n);r!==-1;r=e.indexOf(n,r+1))v.test(e.slice(r+n.length))&&(o=r);return o},ie=(e,t)=>{const n=String(e||"").toLowerCase();return n.includes("@")?[...new Set(t.filter(o=>[o.name,o.nickname,o.email].some(r=>r&&w(n,r)!==-1)).map(o=>o.email))]:[]},_=/https?:\/\/[^\s<>"']+/g,b=e=>{const t=e.filter(Boolean).pop();try{return t?decodeURIComponent(t):""}catch{return t}},j=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 ${b([o[2]]).replace(/-/g," ")}`:"Figma",kind:"link"};if(n==="github.com"&&o.length){const[s,a,p,l]=o;return{label:`GitHub \xB7 ${a??s}${/^(pull|issues)$/.test(p??"")&&l?` #${l}`:""}`,kind:p==="pull"?"pr":"github"}}if(/(^|\.)loom\.com$/.test(n))return{label:"Loom",kind:"link"};const r=b(o);return{label:r?`${n} \xB7 ${r.length>32?A(r,31)+"\u2026":r}`:n,kind:"link"}},T=e=>{const t=String(e??""),n=[];let o=0;for(const r of t.matchAll(_)){const s=r[0].replace(/[.,;:!?)\]]+$/,"");r.index>o&&n.push(t.slice(o,r.index)),n.push({url:s,...j(s)}),o=r.index+s.length}return o<t.length&&n.push(t.slice(o)),n},le=e=>T(e).map(t=>typeof t=="string"?t:t.label).join(""),y={claude:"Claude",codex:"Codex",gemini:"Gemini",cursor:"Cursor",copilot:"Copilot",windsurf:"Windsurf",amp:"Amp",aider:"Aider",opencode:"OpenCode",agent:"AI agent"},k=new Map,pe=(e=[])=>{for(const t of e)t?.email&&k.set(t.email.toLowerCase(),t.agent_name?.trim()||"")},F=(e,t)=>t&&k.get(String(c(t)??t).toLowerCase())||"Agent",ce=e=>!e||e==="claude"?"via Claude Code":e==="agent"||!y[e]?"":`via ${y[e]}`,ue="3.6 3.6 10.8 10.8",B="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",c=e=>typeof e=="string"&&e.startsWith("agent:")?e.slice(6):null,u=e=>e==="claude"||c(e)!=null,R=/^[^\s@]+@[^\s@]+$/,de=e=>{if(e==="claude")return e;if(typeof e!="string"||e.length>210)return null;const t=e.toLowerCase();return R.test(c(t)??t)?t:null},P=["new","approved","progress","review","waiting"],f=e=>P.includes(e?.stage)?e.stage:e?.stage==="accepted"?"review":u(e?.assignee)?"approved":"new",i=e=>e?.client===!0||e?.shared===!0,ge=(e,t,n="")=>`Duplicated from ${n?n==="you"?"your":`${n}\u2019s`:"a"} ${(t?i(t):!i(e))?"client":"studio"} thread`,fe=e=>i(e)?"Duplicated for the client":"Mirrored to Team",me=e=>Number.isInteger(e?.from?.id)&&!i(e),xe=(e="")=>`Mirrored from Client${e?` by ${e}`:""}`,m={new:"Received",progress:"In progress",review:"In progress",waiting:"In progress",done:"Fixed \u2014 please check"},he=(e,t=Date.now())=>e?.status==="done"?m.done:g(e,t)||["progress","review","waiting"].includes(f(e))?m.progress:m.new,we="Fixed \u2014 please check.",be=e=>e?.status==="done"&&!i(e)&&Number.isInteger(e.from?.id)?e.from.id:null,ye=(e,t)=>!i(e)||e.status==="done"?!1:((e.replies||=[]).push(t),Object.assign(e,{status:"done",doneBy:"you",updatedAt:t.at}),!0),ke=(e,t)=>{const n=c(e.assignee);return!i(e)&&f(e)==="approved"&&(!e.assignee||e.assignee==="claude"||n!=null&&(t===void 0||n===t))},S=["agent","claude","codex","gemini"],Se=()=>[{assignee:"claude",handle:"agent",owner:null}],Le=(e,t=[])=>{const n=String(e||"").toLowerCase();return S.some(o=>w(n,o)!==-1)?"claude":null},Ce=(e,t=[],n="")=>{const o=String(e||"").replace(/^@/,"").toLowerCase();if(S.includes(o))return"agent";const r=t.find(s=>[s.name,s.nickname,s.email].some(a=>a&&a.toLowerCase()===o));return r&&n&&r.email?.toLowerCase()===n.toLowerCase()?"you":"person"},Ie=(e,t,n=o=>o)=>F(e,t)+(t?` \xB7 ${n(t)}`:""),z=2*36e5,g=(e,t=Date.now())=>e?.working&&e.status!=="done"&&t-Date.parse(e.working.at)<z?e.working:null,Ae=(e,t)=>({status:"done",doneBy:"claude",working:null,doneAgent:e!=="claude"?e:null,doneFor:t??null}),Ne=(e,t=new Date().toISOString())=>({status:"open",doneBy:null,doneAgent:null,doneFor:null,working:null,reopenedAt:t,...u(e?.assignee)?{stage:"approved"}:{}}),Oe=(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},W={status:e=>e.status!=="done"?e.reopenedBy:e.doneBy==="claude"?"claude":e.confirmedBy??e.archivedBy,stage:e=>e.stageBy,assignee:e=>e.handedBy},$e=(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=W[s]?.(e)??null;if(!(a&&o&&String(a).toLowerCase()===o.toLowerCase()))return{field:s==="stage"?"status":s,by:a}}return null},Me=(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=r?g(e,n)?.by||e.doneFor||e.handedBy||c(e.assignee)||o:e.assignee||"";return{writer:o,taker:String(s).toLowerCase(),claude:r}},Ee=e=>/@guest\.notemend\.com$/i.test(String(e||"")),De=(e,t=Date.now())=>{if(!e)return null;if(e.status==="done")return e.doneBy==="claude"?"review":u(e.assignee)?"done":null;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":f(e)==="approved"?"queued":null},G=10*6e4,L=(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"},ve=(e,t=31)=>{const n=d?[...d.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(""):"")},_e=(e,t=Date.now())=>{const n=e?.status!=="done"?e?.working:null;return n?.at?{step:n.step?String(n.step):null,elapsed:L(n.since??n.at,t),silent:L(n.at,t),stale:!g(e,t)}:null},je={queued:2,asks:6,working:6,stuck:6,review:10,done:12},Te=B.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),Fe={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"},Be=(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},Re=(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},H=["uk","ru","en"],Pe=e=>{try{const t=new Intl.DisplayNames([e],{type:"language"}).of(e)??e;return t[0].toUpperCase()+t.slice(1)}catch{return e}},ze=e=>{try{return new Intl.DisplayNames(["en"],{type:"language"}).of(e)??e}catch{return e}},U=e=>/[іїєґІЇЄҐ]/.test(e)?"uk":/[ыэъёЫЭЪЁ]/.test(e)?"ru":/\p{Script=Cyrillic}/u.test(e)?"":/\p{L}/u.test(e)&&!/[^\p{Script=Latin}\P{L}]/u.test(e)?"en":"",We=(e,t="en")=>{const n=U(e),o=t.split("-")[0].toLowerCase();return[...new Set([o,...H])].filter(r=>r!==n)};export{y as AGENTS,S as AGENT_ALIASES,ue as AI_BOX,B as AI_RAYS,Te as AI_RAYS_CW,C as BLOCKED,m as CLIENT_SEES,h as DOCS,ne as EMOJI,N as FILE_KINDS,we as FIXED_NOTICE,K as FRAMES,D as HANDLE_END,E as MAX_REACTIONS,te as QUICK,G as QUIET,P as STAGES,je as STEP_RAYS,H as TR_LANGS,Fe as UPDATE_HOW,z as WORKING_TTL,Ae as agentDone,Se as agentHandles,Ie as agentLabel,Le as agentMentioned,F as agentName,c as agentOwner,Ne as agentReopen,De as agentStep,ce as agentVia,Re as archivedOf,Oe as changedFields,$e as clashOf,de as cleanAssignee,re as cleanBox,oe as cleanEmoji,i as clientSpace,he as clientWord,A as cut,ee as docOf,Y as docSlug,ge as duplicatedFrom,fe as duplicatedTo,L as elapsed,q as fileExt,V as fileKind,Z as filePrefixes,Q as fileThread,ke as forAgentOf,x as frameOf,J as framesOf,ae as handleOf,me as isMirror,Ee as isOldGuest,Pe as langName,ze as langNameEn,j as linkLabel,T as linkParts,le as linkWords,_e as liveStep,Ce as mentionKind,ie as mentionsIn,xe as mirroredFrom,Be as newer,X as opensInTab,be as originOf,Me as pinWho,pe as setAgentNames,f as stageOf,ve as stepWords,ye as tellFixed,$ as threadOf,u as toAgent,se as toggledReaction,We as trTargets,g as workingOn,U as writtenIn};
|
package/store.d.ts
CHANGED
|
@@ -21,7 +21,7 @@ export interface Comment {
|
|
|
21
21
|
priority?: 'urgent' | 'high' | 'normal' | 'low';
|
|
22
22
|
/** the project's clients see it too */
|
|
23
23
|
shared?: boolean;
|
|
24
|
-
/** written by a client
|
|
24
|
+
/** written by a client: the clients' space */
|
|
25
25
|
client?: boolean;
|
|
26
26
|
/** a copy of this thread, in the other space */
|
|
27
27
|
from?: { id: number };
|
|
@@ -40,8 +40,6 @@ export interface Comment {
|
|
|
40
40
|
box?: { x: number; y: number; w: number; h: number } | null;
|
|
41
41
|
/** who handed it to an agent — whose Claude its pin shows (the server sets it) */
|
|
42
42
|
handedBy?: string | null;
|
|
43
|
-
/** a guest's thread, approved by the studio */
|
|
44
|
-
approvedBy?: string | null;
|
|
45
43
|
/** the copy of the site it was written on — live, staging, localhost — as host[:port] */
|
|
46
44
|
host?: string;
|
|
47
45
|
by?: string; byName?: string; createdAt: string; updatedAt: string | null;
|
package/thread.d.ts
CHANGED
|
@@ -6,6 +6,12 @@ type Spaced = { client?: boolean; shared?: boolean; by?: string; byName?: string
|
|
|
6
6
|
export function duplicatedFrom(copy: Spaced, orig?: Spaced | null, who?: string): string;
|
|
7
7
|
/** The original's line: where its copy is now */
|
|
8
8
|
export function duplicatedTo(copy: Spaced): string;
|
|
9
|
+
/** A mirror: a client's thread as the Team works on it — the copy `from` it outside the clients' space. */
|
|
10
|
+
export function isMirror(c: { client?: boolean | null; shared?: boolean | null; from?: { id: number } } | null | undefined): boolean;
|
|
11
|
+
export function mirroredFrom(who?: string): string;
|
|
12
|
+
/** The client's word for each of the Team's statuses on a mirror. */
|
|
13
|
+
export const CLIENT_SEES: { new: string; progress: string; review: string; waiting: string; done: string };
|
|
14
|
+
export function clientWord(orig: { status?: string; stage?: string; assignee?: string; working?: unknown } | null | undefined, now?: number): string;
|
|
9
15
|
/** What the client's original hears when the studio's copy of it is resolved */
|
|
10
16
|
export const FIXED_NOTICE: string;
|
|
11
17
|
/** The id of the client's original a resolved studio copy tells, or null */
|
|
@@ -26,8 +32,15 @@ export function linkParts(text: string | null | undefined): (string | { url: str
|
|
|
26
32
|
export function linkWords(text: string | null | undefined): string;
|
|
27
33
|
/** Display names of the coding agents, by id */
|
|
28
34
|
export const AGENTS: Record<string, string>;
|
|
29
|
-
/** The name
|
|
30
|
-
export function agentName(id?: string | null): string;
|
|
35
|
+
/** The name every agent shows under: «Agent» (one name since 03.11; the id is ignored) */
|
|
36
|
+
export function agentName(id?: string | null, owner?: string | null): string;
|
|
37
|
+
export function setAgentNames(people?: { email?: string | null; agent_name?: string | null }[] | null): void;
|
|
38
|
+
/** The tool behind an agent, as a subtitle: «via Claude Code», «via Codex», or '' */
|
|
39
|
+
export function agentVia(id?: string | null): string;
|
|
40
|
+
/** The handles that @mention the agent: agent, and the names it went by before (claude, codex, gemini) */
|
|
41
|
+
export const AGENT_ALIASES: string[];
|
|
42
|
+
/** Whose an @mention is: the agent, you (`me`), or another person */
|
|
43
|
+
export function mentionKind(handle: string, people?: { name?: string | null; nickname?: string | null; email?: string | null }[], me?: string | null): "agent" | "you" | "person";
|
|
31
44
|
/** The agent mark: twelve rays drawn with a stroke, in viewBox AI_BOX. */
|
|
32
45
|
export const AI_BOX: string;
|
|
33
46
|
export const AI_RAYS: string;
|
|
@@ -43,9 +56,9 @@ export function stageOf(c: { stage?: string | null; assignee?: string | null } |
|
|
|
43
56
|
/** 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
57
|
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;
|
|
45
58
|
/** A thread for the agent running as `me` (null: a CI key, the shared queue only; undefined: a local store, all) */
|
|
46
|
-
export function forAgentOf(c: { assignee?: string | null; stage?: string | null; by?: string | null;
|
|
59
|
+
export function forAgentOf(c: { assignee?: string | null; stage?: string | null; by?: string | null; shared?: boolean | null; client?: boolean | null }, me?: string | null): boolean;
|
|
47
60
|
export function clientSpace(c: { shared?: boolean | null; client?: boolean | null } | null | undefined): boolean;
|
|
48
|
-
/** "
|
|
61
|
+
/** "Agent · Ann": the agent, and the person it ran as */
|
|
49
62
|
export function agentLabel(agent?: string | null, owner?: string | null, nameOf?: (email: string) => string): string;
|
|
50
63
|
export type Working = { agent: string; by?: string | null; at: string; v?: string;
|
|
51
64
|
/** what the agent is doing right now, for the bar's banner ("Editing Hero.astro") */
|
|
@@ -58,10 +71,8 @@ export const WORKING_TTL: number;
|
|
|
58
71
|
export function workingOn(c: { working?: Working | null; status?: string } | null | undefined, now?: number): Working | null;
|
|
59
72
|
/** Who is on a thread, for its pin: its writer and whoever has it ('' nobody yet); null when resolved or no writer is known. `st` as stateOf gives it */
|
|
60
73
|
export function pinWho(c: Record<string, any>, st: 'open' | 'done' | 'claude', now?: number): { writer: string; taker: string; claude: boolean } | null;
|
|
61
|
-
/**
|
|
62
|
-
export function
|
|
63
|
-
/** A guest's thread the studio has not approved yet: no agent takes it */
|
|
64
|
-
export function held(c: { by?: string | null; approvedBy?: string | null }): boolean;
|
|
74
|
+
/** An address a guest link made before links were removed: left out of the people to pick */
|
|
75
|
+
export function isOldGuest(email?: string | null): boolean;
|
|
65
76
|
/** What an agent's done writes on a thread: resolved by it, for `by`, its working mark cleared */
|
|
66
77
|
export function agentDone(agent: string, by?: string | null): { status: "done"; doneBy: "claude"; working: null; doneAgent: string | null; doneFor: string | null };
|
|
67
78
|
/** What an agent's reopen writes: open, stamped, back in the agent's queue when it is the agent's */
|
|
@@ -72,7 +83,7 @@ export function changedFields(was: Record<string, unknown>, now: Record<string,
|
|
|
72
83
|
export function agentHandles(): { assignee: string; handle: string; owner: string | null }[];
|
|
73
84
|
/** The agent a text hands its thread to: the last one it @mentions, else null */
|
|
74
85
|
export function agentMentioned(text: string, people?: { email: string; name?: string | null; agent_name?: string | null }[]): string | null;
|
|
75
|
-
export type AgentStep = "
|
|
86
|
+
export type AgentStep = "queued" | "asks" | "working" | "stuck" | "review" | "done";
|
|
76
87
|
/** Where a thread is on an agent's way; null when no agent is in it */
|
|
77
88
|
export function agentStep(c: Record<string, any> | null | undefined, now?: number): AgentStep | null;
|
|
78
89
|
/** No step for this long (ms) and a run that steps went quiet */
|
|
@@ -132,3 +143,9 @@ export type ThreadMessage = { author: string; text: string; at?: string | null;
|
|
|
132
143
|
export function threadOf(c: { text: string; reactions?: Reactions; createdAt?: string; by?: string; byName?: string; note?: string; updatedAt?: string | null; replies?: Record<string, any>[]; images?: string[] }): ThreadMessage[];
|
|
133
144
|
/** Put away: archived by a person, or resolved by one `days` ago with nobody saying a word since (the project's auto-archive). */
|
|
134
145
|
export function archivedOf(c: { archivedAt?: string | null; status?: string; doneBy?: string | null; confirmedAt?: string | null; updatedAt?: string | null; replies?: { at?: string; deleted?: boolean }[] }, days?: number | null): boolean;
|
|
146
|
+
/** Translate's menu: the languages offered, a language's own name and its English name, the language a text is written in ('' unknown), and the targets with yours first. */
|
|
147
|
+
export const TR_LANGS: string[];
|
|
148
|
+
export function langName(tag: string): string;
|
|
149
|
+
export function langNameEn(tag: string): string;
|
|
150
|
+
export function writtenIn(text: string): string;
|
|
151
|
+
export function trTargets(text: string, yours?: string): string[];
|