notemend 0.1.35 → 0.1.36
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/bin/notemend.mjs +15 -15
- package/package.json +1 -1
- package/src/client/index.js +121 -121
- package/src/server/middleware.mjs +4 -4
- package/src/store/cloud.mjs +3 -3
|
@@ -1,7 +1,7 @@
|
|
|
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
|
|
1
|
+
import{readFileSync as xe,existsSync as ie,statSync as Fe,readdirSync as Le,watch as He}from"node:fs";import{mask as Re}from"../store/mask.mjs";import{join as J,isAbsolute as ze}from"node:path";import{isIP as ve}from"node:net";import{pathToFileURL as Ge}from"node:url";import{openStore as Je,retry as Ue,retryThread as We,CABINET as he,session as ce,deviceLogin as Ve}from"../store/cloud.mjs";import{mentionsIn as Ke,clashOf as Xe,clientSpace as Se,cleanAssignee as ye,cleanBox as Ze,cleanEmoji as Qe,cut as ee,MAX_REACTIONS as Ye,STAGES as je,threadOf as qe,toAgent as oe}from"../store/thread.mjs";import{fileFrame as le,react as et,shotName as be}from"../store/comments.mjs";import{stateOf as tt}from"../store/status.mjs";import{CATEGORIES as nt,categoryOf as rt}from"../store/categories.mjs";import{BREAKPOINTS as ot,DEVICES as st,ICONS as Oe,SHELLS as Ne,BROWSERS as $e}from"../presets.mjs";const at={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"},ke=e=>e.split(".").slice(0,2).map(Number).reduce((t,a)=>t*100+(Number.isNaN(a)?9999:a),0),Ae=(e,t)=>{try{const a=xe(ze(t)?t:J(e,t),"utf8"),d=a.match(/\bmetadata\b[^=]*=\s*\{[^}]*?\btitle:\s*["'`]([^"'`$]+)["'`]/)??a.match(/<title>([^<{]+)<\/title>/)??(/\.[jt]sx?$/.test(t)?a.match(/<h1\b[^>]*>\s*([^<{]+?)\s*<\/h1>/):a.match(/title="([^"]+)"|\btitle:\s*["'`]([^"'`]+)["'`]/));return(d?.[1]??d?.[2])?.trim()||null}catch{return null}},Be=e=>e.split(/\s+[—–|]\s+/).map(t=>t.trim()).filter(Boolean),it=(e,t,a)=>{const d=Ae(e,t);if(!d)return null;const i=Be(d);return(a?i.filter(m=>m!==a)[0]:i.pop())||null},ct=e=>{const t={};for(const d of e){const i=d?Be(d):[];if(i.length>1)for(const m of new Set([i[0],i.at(-1)]))t[m]=(t[m]||0)+1}const[a]=Object.entries(t).sort((d,i)=>i[1]-d[1]);return a?.[1]>1?a[0]:void 0};function At(e){const t=["app","src/app"].map(i=>J(/* turbopackIgnore: true */ e,i)).find(ie),a=[],d=(i,m)=>{for(const l of Le(i,{withFileTypes:!0})){const u=l.name;if(l.isDirectory()){if(/^[_@]|^\(\./.test(u))continue;d(J(i,u),/^\(.+\)$/.test(u)?m:[...m,u])}else/^page\.(jsx?|tsx?|mdx?)$/.test(u)&&a.push({origin:"project",type:"page",pattern:"/"+m.join("/"),entrypoint:J(i,u)})}};return t&&d(t,[]),a}const Te=e=>e[0].toUpperCase()+e.slice(1).replace(/[-_]+/g," ");function lt({root:e,options:t,routes:a}){const d=t.pages??{},i=(r,j,V)=>({route:r,name:j,label:j.replace(/^[\d.]+[A-Z]?\.\s*/,""),group:V}),m=a.filter(r=>r.origin==="project"&&r.type==="page"&&!r.pattern.includes("[")).map(r=>({route:r.pattern.replace(/\/+$/,"")||"/",entrypoint:r.entrypoint})),l=new Set(m.map(r=>r.route)),u=[...m,...Object.keys(d).filter(r=>!l.has(r)).map(r=>({route:r}))].filter(({route:r})=>d[r]!==null),P={};for(const{route:r}of u){const j=r.split("/")[1];j&&(P[j]=(P[j]||0)+1)}const T=r=>{const j=r.split("/")[1];return j&&P[j]>1?Te(j):"Pages"},U=t.groups?()=>t.groups[t.groups.length-1]:T,Z=ct(u.map(({entrypoint:r})=>r&&Ae(e,r))),L=u.map(({route:r,entrypoint:j})=>{const[V,ne]=d[r]??[];return i(r,V??(j&&it(e,j,Z))??(r==="/"?"Home":Te(r.split("/").pop())),ne??U(r))}),Q=t.groups??[...new Set([...Object.values(d).filter(Boolean).map(([,r])=>r).filter(Boolean),"Pages",...L.map(r=>r.group).sort()])],W=L.sort((r,j)=>Q.indexOf(r.group)-Q.indexOf(j.group)||ke(r.name)-ke(j.name)||r.route.localeCompare(j.route)),Y=(t.breakpoints??ot).map(r=>({id:r.id,label:r.label,min:r.min,ideal:r.ideal,max:Number.isFinite(r.max)?r.max:null,icon:r.icon??Oe[r.id]??Oe.desktop})),se=(t.devices??st).filter(r=>r.w>0&&r.h>0&&Ne.includes(r.shell)&&$e.includes(r.browser)?!0:(console.warn(`[notemend] device "${r.id}" skipped: it needs w and h, shell (${Ne.join(", ")}) and browser (${$e.join(", ")})${r.frame?"; `frame` pictures were replaced by shell + browser in 0.3":""}`),!1));return{pages:W,groups:Q.filter(r=>W.some(j=>j.group===r)),breakpoints:Y,devices:se,categories:nt,sanity:!!t.sanity,shortcuts:t.shortcuts!==!1,ignore:t.ignore??[],grid:{container:"container",grid:"grid",columns:12,...t.grid},zIndex:t.zIndex??2000000020}}const ut=e=>{const t=J(e,"notemend.config.mjs");let a=0,d={};return async()=>{if(!ie(t))return{};const i=Fe(t).mtimeMs;if(i===a)return d;a=i;try{const{default:m,...l}=await import(/* webpackIgnore: true */ /* turbopackIgnore: true */ `${Ge(t).href}?t=${i}`);d={...l,...m}}catch(m){console.warn(`[notemend] notemend.config.mjs: ${m.message}`)}return d}},ft=e=>{const t=String(e.headers.host||"").toLowerCase(),a=t.startsWith("[")?t.slice(1,t.indexOf("]")):t.replace(/:\d+$/,"");return a.includes(":")?ve(a)===6:!a||!a.includes(".")||ve(a)===4||/\.(localhost|local|test|internal|lan|home\.arpa)$/.test(a)},v=(e,t)=>ee(String(e??"").replace(/[\u0000-\u001f\u007f]+/g," ").trim(),t),dt=["id","data","aria","alt","title","src","href","head","sib"],te=e=>{if(!e||typeof e!="object")return;const t=Object.fromEntries(dt.filter(a=>typeof e[a]=="string"&&e[a].trim()).map(a=>[a,v(e[a],120)]));return Object.keys(t).length?t:void 0},ue=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,Ie=e=>e&&typeof e=="object"&&typeof e.selector=="string"?{selector:v(e.selector,2e3),label:v(e.label,200),ctx:v(e.ctx,120),tag:v(e.tag,40),classes:Array.isArray(e.classes)?e.classes.slice(0,20).map(t=>v(t,80)):[],nth:Number.isInteger(e.nth)?e.nth:null,rx:.5,ry:.5,...te(e.fp)?{fp:te(e.fp)}:{}}:void 0,mt=e=>({...te(e.fp)?{fp:te(e.fp)}:{},...ue(e.spot)?{spot:ue(e.spot)}:{},...Ie(e.opener)?{opener:Ie(e.opener)}:{}}),pt=e=>({route:v(e.route,500),text:ee(e.text,1e4),selector:v(e.selector,2e3),rx:Number.isFinite(e.rx)?e.rx:0,ry:Number.isFinite(e.ry)?e.ry:0,label:v(e.label,200),ctx:v(e.ctx,120),breakpoint:v(e.breakpoint,40),browser:v(e.browser,80),device:v(e.device,80),tag:v(e.tag,40),classes:Array.isArray(e.classes)?e.classes.slice(0,20).map(t=>v(t,80)):[],nth:Number.isInteger(e.nth)?e.nth:null,category:v(e.category,40),...mt(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,...ye(e.assignee)?{assignee:ye(e.assignee)}:{},...je.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:v(t?.at,30),kind:["console","error","rejection","network"].includes(t?.kind)?t.kind:"console",text:Re(v(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:ee(e.suggest.from,2e3),to:ee(e.suggest.to,2e3)}}:{}}),gt=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=rt(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=ye(e.assignee)),"stage"in e&&(t.stage=je.includes(e.stage)?e.stage:null),typeof e.archived=="boolean"&&(t.archived=e.archived),"box"in e&&(t.box=Ze(e.box)),e.move&&typeof e.move=="object"&&typeof e.move.selector=="string"){const a=e.move,d=i=>Number.isFinite(i)?Math.min(1,Math.max(0,i)):.5;Object.assign(t,{selector:v(a.selector,2e3),rx:d(a.rx),ry:d(a.ry),label:v(a.label,200),ctx:v(a.ctx,120),tag:v(a.tag,40),classes:Array.isArray(a.classes)?a.classes.slice(0,20).map(i=>v(i,80)):[],nth:Number.isInteger(a.nth)?a.nth:null,...te(a.fp)?{fp:te(a.fp)}:{},...ue(a.spot)?{spot:ue(a.spot)}:{}}),typeof e.repin=="string"&&e.repin.trim()&&Object.assign(t,{repinnedAt:new Date().toISOString(),repinnedBy:"you",repinnedFrom:v(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},fe=e=>{const t=e.headers.origin;if(!t)return!1;try{return new URL(t).host!==e.headers.host}catch{return!0}};function ht({root:e,options:t,routes:a,open:d=()=>Je(e),crossOrigin:i=!1}){const m=ut(e),l=(c,w=200)=>({status:w,type:"application/json",body:JSON.stringify(c)}),u=(c,w)=>({status:c,type:"text/plain; charset=utf-8",body:w}),P=async c=>{const w=await c.body();if(w.length>(i?45e5:8e7))throw Object.assign(new Error("too large"),{status:413});try{return w.length?JSON.parse(w.toString("utf8")):{}}catch{throw Object.assign(new Error("not JSON"),{status:400})}},T=async(c,w,n)=>{const k=async s=>{const o=await w(s);if(o.status>=400)throw Object.assign(new Error("not written"),{out:o});return o};try{return c.cloud&&n!=null&&c.thread?await We(c,n,k,c.row?.(n)):await Ue(c,k)}catch(s){if(s.out)return s.out;throw s}finally{U()}},U=()=>{L=null,V++,re()&&q()},Z=new Set;let L=null,Q=0,W=!1,Y=!1,se=null,r=null,j=0,V=0,ne=0,ae=0;const re=()=>Z.size>0||Date.now()-j<3e4,q=async()=>{if(i)return;if(W){Y=!0;return}W=!0,clearTimeout(se);let c=!1;try{const n=await d();c=!!n.cloud;const k=V,s=n.sync?`${await n.sync()}~${n.stepsSeen?.()??0}`:n.version?String(await n.version()):null;if(k!==V)Y=!0;else if(Q=Date.now(),s!==L){L=s;for(const o of Z)o(s)}if(!c&&!r&&re()&&ie(J(e,"feedback")))try{r=He(J(e,"feedback"),(o,I)=>{String(I).startsWith("comments.json")&&q()}),r.on("error",()=>{r?.close(),r=null})}catch{r=null}ae=0}catch{ae++}if(W=!1,Y)return Y=!1,q();const w=c?Date.now()<ne?1500:5e3:r?1e3:250;re()?se=setTimeout(q,ae?Math.min(3e4,w*2**ae)*(.5+Math.random()):w):(r?.close(),r=null)},Ee=c=>(Z.add(c),L!=null&&c(L),q(),()=>{Z.delete(c),j=Date.now()}),Pe=()=>re()&&L!=null&&Date.now()-Q<3e3?L:null,we=new Map,Ce=async(c,w)=>{if(c.method!=="GET"&&!i&&fe(c))return u(403,"Cross-origin write refused");const n=await d();if(c.method==="GET"){const f=w.searchParams.get("route"),C=w.searchParams.get("since"),E=Pe();if(C!=null&&n.version&&C===(E??String(await n.version())))return{status:204,type:"text/plain",body:""};const G=w.searchParams.get("open")==="1",g=`${f??""}|${G}`,A=E!=null&&we.get(g);if(A&&A.v===E)return A.res;const h=n.view?await n.view({open:G,fresh:E!=null?3e3:0}):await n.load(G?{open:!0}:void 0);let $=f?h.comments.filter(z=>z.route===f):h.comments;G&&($=$.filter(z=>tt(z)!=="done")),$=$.map(({logs:z,...X})=>X);const O=n.versionOf?n.versionOf(h):null,B=l({version:O==null?null:String(O),comments:$,listening:h.listening??null,turbo:h.turbo??null});return!i&&O!=null&&we.set(g,{v:String(O),res:B}),B}const k=c.method==="DELETE"?null:await P(c);let s=null,o=null;const I=c.method==="POST"||!!k?.reply?.trim?.()||k?.stage!==void 0,H=n.cloud&&k?(I?n.people():n.me().then(f=>({me:f,team:[]}))).then(f=>{s=f,o=f.me}).catch(f=>f):Promise.resolve(),R=async()=>{const f=await H;if(f instanceof Error)throw f},me=f=>{if(o&&f){f.by=o.email,f.byName=o.name;const C=Ke(f.text,s.team.filter(E=>E.email!==o.email));C.length&&(f.mentions=C)}return f};if(c.method==="POST"){const{image:f,images:C,before:E,...G}=k,g=pt(G);if(!g.text.trim())return l({error:"empty comment"},400);if(!/^\/(?![\/\\])/.test(g.route))return l({error:"route must be a path"},400);if(n.addThread&&!(g.from&&!g.shared&&!g.client)){await R(),s?.client&&(g.client=!0,oe(g.assignee)&&delete g.assignee,g.stage==="approved"&&delete g.stage);const A=me(n.add({comments:[],nextId:1},g));o&&oe(A.assignee)&&(A.handedBy=o.email);let h;try{h=await n.addThread(A)}finally{U()}const $=[].concat(C??f??[]);return $.length||E?(h=await T(n,async O=>{for(const B of $)await n.attach(O,h.id,B);return await le(n,O,h.id,E,"before"),l(O.comments.find(B=>B.id===h.id)??h,201)},h.id),h):l(h,201)}return T(n,async A=>{await R(),s?.client&&(g.client=!0,oe(g.assignee)&&delete g.assignee,g.stage==="approved"&&delete g.stage);const h=g.from&&!g.shared&&!g.client?A.comments.find(B=>B.id===g.from.id):null,$=!!h&&Se(h);if($){const B=A.comments.find(z=>z.from?.id===h.id&&!Se(z));if(B)return l(B,200)}const O=me(n.add(A,g));$&&(O.from={id:h.id,...h.by?{by:h.by}:{},...h.byName?{byName:h.byName}:{}}),o&&oe(O.assignee)&&(O.handedBy=o.email);for(const B of[].concat(C??f??[]))await n.attach(A,O.id,B);return await le(n,A,O.id,E,"before"),l(O,201)})}if(c.method==="PATCH"){const f=k;if(f.turbo==="on"||f.turbo==="off"){if(n.setMeta)try{return l({turbo:(await n.setMeta({turbo:{paused:f.turbo==="off",at:new Date().toISOString()}}))?.turbo})}finally{U()}return T(n,async p=>(p.turbo={paused:f.turbo==="off",at:new Date().toISOString()},l({turbo:p.turbo})))}if(Array.isArray(f.push)||Array.isArray(f.unpush)){const p=N=>(Array.isArray(N)?N:[]).map(Number).filter(b=>Number.isInteger(b)&&b>0).slice(0,500);return T(n,async N=>{const b=new Set(N.turbo?.push?.ids??[]);for(const D of p(f.push))b.add(D);for(const D of p(f.unpush))b.delete(D);const M=D=>N.comments.some(pe=>pe.id===D&&pe.status!=="done"),_=new Set((N.turbo?.batch?.ids??[]).filter(M)),F=!_.size;for(const D of p(f.push))_.add(D);for(const D of p(f.unpush))_.delete(D);const S=new Date().toISOString();return N.turbo={...N.turbo??{paused:!0},push:{at:S,ids:[...b]},batch:{at:F?S:N.turbo?.batch?.at??S,ids:[..._]}},l({turbo:N.turbo})})}const{id:C,reply:E,image:G,images:g,removeImage:A,uploaded:h,edit:$,unsay:O,before:B,after:z,react:X,seen:Me,..._e}=f,y=Number(C);if(!Number.isInteger(y))return l({error:"bad id"},400);if(X){const p=Qe(X.emoji),N=typeof X.at=="string"&&X.at?X.at:null;return p?n.cloud?n.react(y,N,p).then(l,b=>l({error:b.message},b.status>=400&&b.status<500?b.status:500)):T(n,async b=>{const M=et(b,y,N,p,"you");return M===!1?l({error:`${Ye} kinds of reaction at most`},400):M?l(M):l({error:`no message to react to in #${y}`},404)},y):l({error:"not an emoji"},400)}if(typeof O=="string"){let p=[];const N=await T(n,async b=>{const M=b.comments.find(F=>F.id===y),_=M?.replies?.find(F=>F.at===O);return!_||o&&_.by&&_.by!==o.email?l({error:`no reply of yours to delete in #${y}`},404):(p=qe(M).find(F=>F.at===O&&F.author==="you")?.images??[],n.unsay(b,y,O)?l(M):l({error:`no reply of yours to delete in #${y}`},404))},y);if(N.status<400)for(const b of p)await n.forget(be(b));return N}const x=gt(_e);return T(n,async p=>{await R();const N=p.comments.find(S=>S.id===y),b=Xe(N,Me,x,o?.email);if(b)return l({error:`#${y} was just changed by someone else`,...b,thread:N},409);if($){const S=p.comments.find(ge=>ge.id===Number(y)),D=$.at?S?.replies?.find(ge=>ge.at===$.at):S;if(o&&D?.by&&D.by!==o.email||!($.text?.trim?.()&&n.edit(p,y,$.at??null,ee($.text.trim(),1e4))))return l({error:`no message of yours to edit in #${y}`},404)}E?.trim?.()&&me(n.reply(p,y,"you",ee(E.trim(),1e4))?.replies.at(-1));for(const S of[].concat(g??G??[]))await n.attach(p,y,S);for(const S of[].concat(h??[]))if(n.adopt&&!await n.adopt(p,y,S))return l({error:`${S} did not arrive`},400);for(const S of[].concat(A||[]))await n.detach(p,y,S);if(await le(n,p,y,B,"before"),await le(n,p,y,z,"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}),o&&x.repinnedBy&&(x.repinnedBy=o.email),"archived"in x){const S=x.archived;delete x.archived,Object.assign(x,S?{archivedAt:new Date().toISOString(),archivedBy:o?.email??null}:{archivedAt:null,archivedBy:null})}x.status==="open"&&Object.assign(x,{archivedAt:null,archivedBy:null}),o&&(x.stage==="review"||x.stage!==void 0&&!s?.client)&&(x.stageBy=o.email),o&&"assignee"in x&&(x.handedBy=oe(x.assignee)?o.email:null);const M=Object.keys(x).length&&Object.keys(x).every(S=>S==="anchor"),_=p.comments.find(S=>S.id===Number(y)),F=M?_&&Object.assign(_,x):Object.keys(x).length?n.patch(p,y,x):p.comments.find(S=>S.id===Number(y));return F?l(F):l({error:`no comment #${y}`},404)},y)}if(c.method==="DELETE"){const f=Number(w.searchParams.get("id"));return T(n,async C=>await n.remove(C,f)?l({ok:!0,id:f}):l({error:`no comment #${f}`},404))}return u(405,"Method not allowed")},De=(c,w)=>{const n=w.replace(/^.*[/\\]/,""),k=n.split(".").pop()?.toLowerCase()??"",s=at[k]??(be(n)?"application/octet-stream":null);if(!/^[\w.-]+$/.test(n)||!s)return u(400,"Bad name");const o=J(c,n);return ie(o)?{status:200,type:s,body:xe(o)}:u(404,"Not found")};let de=!1,K=null;return async c=>{const w=new URL(c.url,"http://devbar"),n=w.pathname.slice(10);if(!i&&!ft(c))return u(403,"Notemend answers local addresses only");const k=c.headers["sec-fetch-site"];if(!i&&k&&k!=="same-origin")return u(403,"Notemend answers its own pages only");try{if(n==="config"&&c.method==="PATCH"){if(!i&&fe(c))return u(403,"Cross-origin write refused");const s=await d(),o=await P(c)??{};return"folders"in o?s.setFolders?l({folders:await s.setFolders(Array.isArray(o.folders)&&o.folders.length?o.folders:null)}):u(400,"Link the site to a project to keep its folders"):s.cloud?l({grid:await s.setGrid(o.grid??null)}):u(400,"Link the site to a project to set its grid")}if(n==="config"){const s=lt({root:e,options:{...await m(),...t},routes:a()}),o=await d();return o.cloud?Object.assign(s,await o.people({fresh:!0}).catch(I=>{if(I.said)throw I;return{}})):o.folders&&Object.assign(s,{folders:o.folders(),arrange:!0}),(o.cloud||await ce().catch(()=>null))&&(s.voice=!0),o.cloud&&!i&&(s.cabinet=he),l(s)}if(n==="transcribe"&&c.method==="POST"){if(!i&&fe(c))return u(403,"Cross-origin write refused");const s=await d(),o=s.cloud?await s.token():(await ce().catch(()=>null))?.access_token;if(!o)return u(401,"Voice replies need Notemend \u2014 run `npx notemend login`.");const{audio:I}=await P(c),H=/^data:(audio\/(?:webm|mp4))(?:;[\w=.-]+)*;base64,(.+)$/s.exec(String(I||""));if(!H)return u(400,"Not a recording");const R=await fetch(`${he}/api/transcribe`,{method:"POST",body:Buffer.from(H[2],"base64"),headers:{authorization:`Bearer ${o}`,"content-type":H[1]}});return{status:R.status,type:"application/json",body:await R.text()}}if(n==="translate"&&c.method==="POST"){if(!i&&fe(c))return u(403,"Cross-origin write refused");const s=await d(),o=s.cloud?await s.token():(await ce().catch(()=>null))?.access_token;if(!o)return u(401,"Translating needs Notemend \u2014 run `npx notemend login`.");const{text:I,to:H}=await P(c),R=await fetch(`${he}/api/translate`,{method:"POST",body:JSON.stringify({text:I,to:H}),headers:{authorization:`Bearer ${o}`,"content-type":"application/json"}});return{status:R.status,type:"application/json",body:await R.text()}}if(n==="signin"&&!i){if(w.searchParams.has("code"))return l({code:K?.code??null,done:!!await ce().catch(()=>null)});K||(K={},K.go=new Promise(o=>{Ve((I,H)=>{K.code=H,o(I)}).catch(I=>{console.warn(`[notemend] sign-in from the bar: ${I.message}`),o(null)}).finally(()=>{K=null,de=!1})}));const s=await K.go;return s?{status:302,type:"text/plain",body:"",headers:{location:`${s}&from=bar`}}:u(502,"The cabinet did not answer. Try again in a moment.")}if(n==="comments")return await Ce(c,w);if(n==="events"&&!i)return{status:200,type:"text/event-stream",body:"",stream:Ee};if(n==="active"&&c.method==="POST"&&!i){const s=Date.now()<ne;return ne=Date.now()+3e4,!s&&re()&&!W&&q(),{status:204,type:"text/plain",body:""}}if(n==="image"){const s=await d(),o=(w.searchParams.get("name")||"").replace(/^.*[/\\]/,"");return s.cloud&&/^[\w.-]+$/.test(o)&&await s.fetchImage(o).catch(()=>null),De(s.imageDir,o)}return u(404,"Not found")}catch(s){return s.status===400||s.status===413?u(s.status,s.message):s.signin?(de||(de=!0,console.warn(`[notemend] ${s.said}`)),u(401,s.said)):s.said?u(s.status,s.said):s.status===403?u(403,String(s.message).replace(/^notemend: /,"").replace(/ \(403\)$/,"")):(console.error("[notemend]",s),u(500,"Something went wrong on our side. Try again in a moment."))}}}function Bt(e){const t=ht(e),a=d=>new Promise((i,m)=>{const l=[];d.on("data",u=>l.push(u)),d.on("end",()=>i(Buffer.concat(l))),d.on("error",m)});return async function(i,m,l){if(!i.url||!i.url.startsWith("/__devbar/"))return l();const u=await t({method:i.method,url:i.url,headers:i.headers,body:()=>a(i)});if(u.stream){m.writeHead(200,{"content-type":u.type,"cache-control":"no-store",connection:"keep-alive"}),m.write(`retry: 1000
|
|
2
2
|
|
|
3
|
-
`);const
|
|
3
|
+
`);const P=setInterval(()=>m.write(`: ping
|
|
4
4
|
|
|
5
|
-
`),25e3),
|
|
5
|
+
`),25e3),T=u.stream(U=>m.write(`data: ${U}
|
|
6
6
|
|
|
7
|
-
`));i.on("close",()=>{clearInterval(
|
|
7
|
+
`));i.on("close",()=>{clearInterval(P),T()});return}m.statusCode=u.status,m.setHeader("content-type",u.type),m.setHeader("cache-control","no-store");for(const[P,T]of Object.entries(u.headers??{}))m.setHeader(P,T);m.end(u.body)}}export{lt as buildConfig,ht as notemendHandler,Bt as notemendMiddleware,At as scanApp,it as titleOf,Te as titled};
|
package/src/store/cloud.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{readFileSync as
|
|
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};
|
|
1
|
+
import{readFileSync as B,writeFileSync as E,existsSync as te,mkdirSync as C,rmSync as F,renameSync as Ae}from"node:fs";import{createHash as xe}from"node:crypto";import{homedir as Pe}from"node:os";import{dirname as J,join as k}from"node:path";import{createStore as De,add as Me,reply as qe,edit as Be,unsay as Ce,patch as Je,shotName as T,mediaOf as Le,mediaName as se,Conflict as P}from"./comments.mjs";import{changedFields as He}from"./thread.mjs";const ne=process.env.NOTEMEND_APP||"https://app.notemend.com",O={url:process.env.NOTEMEND_SUPABASE_URL||"https://xzhnjldvkirrydbyrdnm.supabase.co",key:process.env.NOTEMEND_SUPABASE_KEY||"sb_publishable_b8h8jTHZ9KtbPvMuroLhqA_-yBqZwd6"},A=k(process.env.NOTEMEND_HOME||k(Pe(),".config","notemend"),"session.json"),G=r=>k(r,".notemend.json"),Fe=r=>{try{return JSON.parse(B(G(r),"utf8")).project||null}catch{return null}},rt=(r,n)=>E(G(r),JSON.stringify({project:n},null,2)+`
|
|
2
|
+
`),at=r=>F(G(r),{force:!0}),re=()=>{try{const r=JSON.parse(B(A,"utf8"));return r.url===O.url?r:null}catch{return null}},Ge=r=>{C(J(A),{recursive:!0}),E(A,JSON.stringify(r,null,2)+`
|
|
3
|
+
`,{mode:384})},ot=()=>F(A,{force:!0});async function $(r,{method:n="GET",token:l,body:m,headers:h={},raw:d=!1}={}){const w=await fetch(`${O.url}${r}`,{method:n,headers:{apikey:O.key,authorization:`Bearer ${l||O.key}`,...m&&!d?{"content-type":"application/json"}:{},...h},body:d?m:m&&JSON.stringify(m),signal:AbortSignal.timeout(d?12e4:15e3)});if(!w.ok){const y=await w.text();let p=y;try{const S=JSON.parse(y);p=S.msg||S.message||S.error_description||S.error||y}catch{}const v=new Error(`${p} (${w.status})`);throw v.status=w.status,v}return w}const R=r=>{const n={url:O.url,email:r.user.email,user:r.user.id,access_token:r.access_token,refresh_token:r.refresh_token,expires_at:r.expires_at??Math.floor(Date.now()/1e3)+r.expires_in};return Ge(n),n},it=r=>$("/auth/v1/otp",{method:"POST",body:{email:r,create_user:!0}}),ct=async(r,n)=>R(await(await $("/auth/v1/verify",{method:"POST",body:{email:r,token:n,type:"email"}})).json());async function lt(r){const n=await fetch(`${ne}/api/cli/device`,{method:"POST"}),l=await n.json().catch(()=>({}));if(!n.ok)throw new Error(l.error||`The cabinet said ${n.status}`);console.log(`Your code: ${l.code}`),r(l.url,l.code);const m=Date.now()+l.expires_in*1e3;for(;Date.now()<m;){await new Promise(y=>setTimeout(y,l.interval*1e3));const h=await fetch(`${ne}/api/cli/device`,{headers:{authorization:`Bearer ${l.device}`}}).catch(()=>null);if(!h||h.status===202)continue;const d=await h.json().catch(()=>({}));if(!h.ok)throw new Error(d.error||`The cabinet said ${h.status}`);const w=await(await $("/auth/v1/user",{token:d.access_token})).json();return R({user:w,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 dt(r,n){const l=await D();if(!l)throw new Error("Sign in first: npx notemend login");return(await(await $("/rest/v1/projects",{method:"POST",token:l.access_token,headers:{prefer:"return=representation"},body:{name:r,...n?{site_url:n}:{}}})).json())[0]}async function D(){const r=re();if(!r)return null;if(r.expires_at-60>Date.now()/1e3)return r;try{const n=await $("/auth/v1/token?grant_type=refresh_token",{method:"POST",body:{refresh_token:r.refresh_token}});return R(await n.json())}catch(n){if(n.status===400||n.status===401)return null;throw n}}async function ut(r,n,l){const m=k(J(A),"seen.json");let h={};try{h=JSON.parse(B(m,"utf8"))}catch{}const d=`${r}|${n}|${l}`;if(Date.now()-(h[d]||0)<6*36e5)return;const w=await D();w&&(await $("/rest/v1/rpc/agent_seen",{method:"POST",token:w.access_token,body:{p_agent:r,p_version:n,p_via:l}}),E(m,JSON.stringify({...h,[d]:Date.now()})))}const ae="Not saved \u2014 up to 50 folders, a name of 1\u201360 characters.",oe="Not saved \u2014 columns 1\u201324, gutter and margin 0\u2013200, max width 320\u20134000 or empty.",j=new Map;function Re(r,n,l=null,{keepDir:m=l?null:J(A)}={}){const h=k(r,"feedback","images"),d=e=>`feedback/images/${e}`,w=new WeakMap,y=l?async()=>l:async()=>{const e=await D();if(!e)throw new Error("Not signed in to Notemend \u2014 run `npx notemend login`.");return e},p=async(e,s={})=>$(`/rest/v1/${e}`,{...s,token:(await y()).access_token}),v=async(e,s={})=>$(`/storage/v1/object/shots/${n}/${e}`,{...s,token:(await y()).access_token}),S=`Project ${n} is not there, or you are not in it. Check \`npx notemend link\`.`,M=()=>Object.assign(new Error(S),{status:403,said:"You are not in this project any more \u2014 ask its owner to add you again."}),ie="or=(data->>status.neq.done,data->>doneBy.eq.claude)",ce=async({open:e=!1}={})=>{if(!e){const a=await(await p(`stores?project_id=eq.${n}&select=doc,version`)).json();if(!a.length)throw M();const u=a[0].doc;return w.set(u,a[0].version),u}const[s,t]=await Promise.all([p(`stores_meta?project_id=eq.${n}&select=doc,version`).then(a=>a.json()),p(`threads?project_id=eq.${n}&${ie}&select=data&order=id`).then(a=>a.json())]);if(!s.length)throw M();const i={...s[0].doc,comments:t.map(a=>a.data)};return w.set(i,s[0].version),i},le=e=>w.get(e)??null;let o=null,x=null,I=!1,W=0;const N=m?k(m,`mirror-${xe("sha1").update(`${O.url}|${n}|${l?.email??re()?.email??""}`).digest("hex").slice(0,16)}.json`):null,de=async()=>{if(!N||I)return null;I=!0;try{const e=JSON.parse(B(N,"utf8"));return e.url!==O.url||e.email!==(await y()).email||!Array.isArray(e.threads)?null:{meta:e.meta??{},threads:new Map(e.threads.map(s=>[s.data.id,s])),version:e.version,steps:new Map(e.steps??[]),stepsAt:e.stepsAt??null,complete:!!e.complete,staff:e.staff,email:e.email,at:0}}catch{return null}},z=()=>{if(!(!N||!o?.email))try{C(J(N),{recursive:!0});const e=`${N}.${process.pid}.tmp`;E(e,JSON.stringify({url:O.url,email:o.email,version:o.version,meta:o.meta,threads:[...o.threads.values()],steps:[...o.steps],stepsAt:o.stepsAt,complete:o.complete,staff:o.staff}),{mode:384}),Ae(e,N),W=Date.now()}catch{}},K=async(e,s=!1)=>(await p("rpc/changes",{method:"POST",body:{p_project:n,p_v:e,p_steps:o?.stepsAt??"1970-01-01T00:00:00Z",p_open:s}}).catch(t=>{throw t.status===403?M():t})).json(),Y=(e,s)=>{e.version=Math.max(e.version,s.version),typeof s.staff=="boolean"&&(e.staff=s.staff),s.meta&&(e.meta=s.meta);for(const t of s.threads??[]){const i=e.threads.get(t.data.id);(!i||i.v<=t.v)&&e.threads.set(t.data.id,t)}for(const t of s.hidden??[])e.threads.delete(t);for(const t of s.gone??[]){const i=e.threads.get(t.id);i&&i.v<t.v&&e.threads.delete(t.id)}for(const t of s.steps??[])e.steps.set(t.id,t),U++,(!e.stepsAt||t.at>e.stepsAt)&&(e.stepsAt=t.at);e.at=Date.now()},Z=({complete:e=!1}={})=>{const s=e&&!o?.complete;if(x&&!s)return x;const t=(async()=>{o||(o=await de());const i=o?.staff;if(o&&!(e&&!o.complete)){const u=o.version;if(Y(o,await K(o.version)),o.version!==u&&N&&Date.now()-W>6e4&&z(),o.staff===i)return o.version}const a={meta:{},threads:new Map,version:-1,steps:o?.steps??new Map,stepsAt:o?.stepsAt??null,complete:e||!!o?.complete,email:(await y()).email};return Y(a,await K(-1,!a.complete)),o=a,o.version})();return x=t,t.finally(()=>{x===t&&(x=null)}).catch(()=>{}),t},ue=e=>{const s=o.steps.get(e.id),t=e.working;return!s||!t||t.agent!==s.agent||(t.by??null)!==(s.by??null)||Date.parse(s.at)<=Date.parse(t.at)?e:{...e,working:{...t,step:s.step||null,at:s.at,since:t.since??t.at}}};let U=0;const he=()=>U,pe=e=>{const s=o?.threads.get(Number(e));return s?{data:structuredClone(s.data),v:s.v}:null},fe=async({open:e=!1,fresh:s=0}={})=>{(!o||!e&&!o.complete||Date.now()-o.at>s)&&await Z({complete:!e});const t=[...o.threads.values()].map(a=>ue(a.data)).sort((a,u)=>a.id-u.id),i={...o.meta,comments:e?t.filter(a=>a.status!=="done"||a.doneBy==="claude"):t};return w.set(i,o.version),i},Q=(e,s)=>{if(!o||!e||typeof s!="number")return;const t=o.threads.get(e.id);(!t||t.v<=s)&&o.threads.set(e.id,{data:e,v:s})},me=async()=>(await(await p(`stores_meta?project_id=eq.${n}&select=version`)).json())[0]?.version??null,we=async e=>{const s=w.get(e),t=await(await p(`stores?project_id=eq.${n}&version=eq.${s}&select=version`,{method:"PATCH",body:{doc:e},headers:{prefer:"return=representation"}})).json();if(!t.length)throw new P("Someone else wrote first");w.set(e,t[0].version)},ye=async e=>(await(await p(`threads?project_id=eq.${n}&id=eq.${Number(e)}&select=data,v`)).json())[0]??null,_e=async(e,s,t,i)=>{const a=He(s,t);if(Object.keys(a).length)try{const u=await(await p("rpc/patch_thread",{method:"POST",body:{p_project:n,p_id:Number(e),p_patch:a,p_version:i}})).json();Q(u?.thread,u?.v)}catch(u){throw u.status===409||u.status===404?new P(u.message):u}},ge=async e=>{const s=await(await p("rpc/add_thread",{method:"POST",body:{p_project:n,p_thread:e}})).json();return Q(s.thread,s.v),s.thread},ve=async e=>{const s=await(await p("rpc/set_meta",{method:"POST",body:{p_project:n,p_patch:e}})).json();return o&&s?.meta&&(o.meta=s.meta),s?.meta},ke=async(e,s,t)=>(await p("rpc/step_threads",{method:"POST",body:{p_project:n,p_ids:e.slice(0,50).map(Number),p_agent:s,p_step:t}})).json(),je=async(e,s,t)=>(await(await p("rpc/react",{method:"POST",body:{p_project:n,p_id:Number(e),p_at:s,p_emoji:t}})).json()).thread,be=async()=>(await(await p(`threads?project_id=eq.${n}&select=route:data->>route`)).json()).map(e=>e.route),Se=async()=>({email:(await y()).email}),V=new Map,Oe=async(e,s,t,i)=>{const a=e.comments.find(f=>f.id===Number(s)),u=Le(t);if(!a||!u)return null;const b=`${a.id}:${i??""}:${t.length}:${t.slice(-48)}`;let _=V.get(b);if(!_||a.images?.includes(d(_))){let f=Date.now();for(;te(k(h,se(a.id,f,u,i)));)f++;_=se(a.id,f,u,i),V.set(b,_)}const c=Buffer.from(u.base64,"base64");return await v(_,{method:"POST",body:c,raw:!0,headers:{"content-type":u.type,"x-upsert":"true"}}),C(h,{recursive:!0}),E(k(h,_),c),(a.images||=[]).push(d(_)),a.updatedAt=new Date().toISOString(),d(_)},$e=async(e,s,t)=>{const i=e.comments.find(u=>u.id===Number(s));return!i||T(t)!==t||!t.startsWith(`${i.id}-`)?null:i.images?.includes(d(t))?d(t):await v(t,{method:"HEAD"}).then(()=>!0,()=>!1)?((i.images||=[]).push(d(t)),i.updatedAt=new Date().toISOString(),d(t)):null},L=async e=>{T(e)&&(F(k(h,e),{force:!0}),await v(e,{method:"DELETE"}).catch(()=>{}))};return{cloud:!0,setGrid:async e=>{const s=await(await p(`projects?id=eq.${n}&select=grid`,{method:"PATCH",body:{grid:e},headers:{prefer:"return=representation"}}).catch(t=>{throw/23514|check constraint/.test(t.message)?Object.assign(new Error(oe),{status:400,said:oe}):t})).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 t of j.keys())t.startsWith(`${n}|`)&&j.delete(t);return s[0].grid},setFolders:async e=>{const s=await(await p(`projects?id=eq.${n}&select=page_folders`,{method:"PATCH",body:{page_folders:e},headers:{prefer:"return=representation"}}).catch(t=>{throw/23514|check constraint/.test(t.message)?Object.assign(new Error(ae),{status:400,said:ae}):t})).json();if(!s.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 t of j.keys())t.startsWith(`${n}|`)&&j.delete(t);return s[0].page_folders??[]},project:n,root:r,imageDir:h,load:ce,versionOf:le,version:me,sync:Z,view:fe,row:pe,stepsSeen:he,keep:z,save:we,thread:ye,patchThread:_e,addThread:ge,setMeta:ve,stepThreads:ke,react:je,routes:be,me:Se,attach:Oe,adopt:$e,detach:async(e,s,t)=>{const i=e.comments.find(b=>b.id===Number(s)),a=T(t),u=a&&i?.images?.find(b=>T(b)===a);return u?(await L(a),i.images=i.images.filter(b=>b!==u),i.updatedAt=new Date().toISOString(),!0):!1},forget:L,remove:async(e,s)=>{const t=e.comments.find(i=>i.id===Number(s));if(!t)return!1;for(const i of t.images||[])await L(T(i));return e.comments=e.comments.filter(i=>i.id!==Number(s)),!0},fetchImage:async e=>{if(!T(e)||T(e)!==e)return null;const s=k(h,e);if(te(s))return s;const t=await v(e).catch(()=>null);return t?(C(h,{recursive:!0}),E(s,Buffer.from(await t.arrayBuffer())),s):null},people:async({fresh:e=!1}={})=>{const s=await y(),t=`${n}|${s.email}`,i=j.get(t);if(!e&&i&&Date.now()-i.at<6e4)return i.p;const a=c=>p(`rpc/${c}`,{method:"POST",body:{p:n}}).then(f=>f.json()).catch(()=>null);let u=!1;const _=p("rpc/bar_people",{method:"POST",body:{p:n}}).then(c=>c.json()).then(c=>[c.profiles,c.here,c.staff,c.studio,c.lead,{autoArchive:c.project?.auto_archive_days??null,projectGrid:c.project?.grid??null,folders:c.project?.page_folders??[],...c.team?.name?{studioName:c.team.name}:{},...c.team&&(c.team.brand_color||c.team.brand_logo)?{brand:{color:c.team.brand_color,logo:c.team.brand_logo}}:{}},c.admin],c=>{if(c.status===404)return null;throw c}).then(c=>c??Promise.all([p("profiles?select=email,name,nickname,avatar_url,agent_name,agent_avatar_url,avatar_hue").then(f=>f.ok?f.json():p("profiles?select=email,name,nickname,avatar_url,agent_name,agent_avatar_url").then(g=>g.json())),a("project_people"),a("is_staff"),a("project_staff"),a("project_lead"),p(`projects?id=eq.${n}&select=auto_archive_days,grid,page_folders,team_id`).then(f=>f.json()).then(async([f])=>{const[g]=f?.team_id?await p(`teams?id=eq.${f.team_id}&select=name,brand_color,brand_logo`).then(q=>q.json()).catch(()=>[]):[];return{autoArchive:f?.auto_archive_days??null,projectGrid:f?.grid??null,folders:f?.page_folders??[],...g?.name?{studioName:g.name}:{},...g&&(g.brand_color||g.brand_logo)?{brand:{color:g.brand_color,logo:g.brand_logo}}:{}}}).catch(()=>({})),a("runs_project")])).then(([c,f,g,q,X,Ne,Te])=>{if(Array.isArray(f)&&!f.length)throw M();u=typeof g!="boolean";const ee=Array.isArray(f)?new Set(f):null,Ee=ee?c.filter(H=>ee.has(H.email)):c;return{me:c.find(H=>H.email===s.email)??{email:s.email,name:"",avatar_url:null},team:Ee,client:g!==!0,...Array.isArray(q)?{studio:q}:{},...typeof X=="string"?{lead:X}:{},...Ne,project:n,gridAdmin:Te===!0}});return j.set(t,{at:Date.now(),p:_}),_.then(()=>{u&&j.get(t)?.p===_&&j.delete(t)},()=>{j.get(t)?.p===_&&j.delete(t)}),_},add:Me,reply:qe,edit:Be,unsay:Ce,patch:Je,token:async()=>(await y()).access_token}}const Ie=()=>process.env.NOTEMEND_LOCAL==="1";async function ht(r){const n=Fe(r);if(n&&await D())return Re(r,n);if(Ie())return De(r);const l=await D().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(l),{status:401,said:l,signin:!0})}async function pt(r,n,l,m=null){for(let h=0;;h++){const d=h===0&&m?m:await r.thread(n);if(!d)return l({comments:[]});const w=structuredClone(d.data),y={comments:[d.data]},p=await l(y);try{return await r.patchThread(n,w,y.comments[0],d.v),p}catch(v){if(!(v instanceof P)||h>=4)throw v;await new Promise(S=>setTimeout(S,300*(h+1)+Math.random()*300))}}}async function ft(r,n){for(let l=0;;l++){const m=await r.load(),h=await n(m);try{return await r.save(m),h}catch(d){if(!(d instanceof P)||l>=4)throw d}}}export{O as BACKEND,ne as CABINET,P as Conflict,Re as cloudStore,dt as createProject,lt as deviceLogin,rt as link,Fe as linkedProject,Ie as localOnly,ot as logout,ht as openStore,ft as retry,pt as retryThread,ut as seen,it as sendCode,D as session,at as unlink,ct as verifyCode};
|