notemend 0.1.18 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{readFileSync as z,existsSync as D,statSync as q,readdirSync as tt}from"node:fs";import{mask as et}from"../store/mask.mjs";import{join as I,isAbsolute as nt}from"node:path";import{isIP as G}from"node:net";import{pathToFileURL as rt}from"node:url";import{openStore as ot,retry as st,CABINET as J,session as F}from"../store/cloud.mjs";import{mentionsIn as at,cleanAssignee as R,STAGES as M,frameOf as it}from"../store/thread.mjs";import{CATEGORIES as ct,categoryOf as ut}from"../store/categories.mjs";import{BREAKPOINTS as lt,DEVICES as mt,ICONS as U,SHELLS as W,BROWSERS as V}from"../presets.mjs";const K={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",svg:"image/svg+xml",webm:"video/webm",m4a:"audio/mp4",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},Z=t=>t.split(".").slice(0,2).map(Number).reduce((n,m)=>n*100+(Number.isNaN(m)?9999:m),0),ft=(t,n)=>{try{const l=z(nt(n)?n:I(t,n),"utf8").match(/title="([^"]+)"|\btitle:\s*["'`]([^"'`]+)["'`]/);return(l?.[1]??l?.[2])?.split("\u2014").pop()?.trim()||null}catch{return null}};function At(t){const n=["app","src/app"].map(u=>I(t,u)).find(D),m=[],l=(u,p)=>{for(const a of tt(u,{withFileTypes:!0})){const c=a.name;if(a.isDirectory()){if(/^[_@]|^\(\./.test(c))continue;l(I(u,c),/^\(.+\)$/.test(c)?p:[...p,c])}else/^page\.(jsx?|tsx?|mdx?)$/.test(c)&&m.push({origin:"project",type:"page",pattern:"/"+p.join("/"),entrypoint:I(u,c)})}};return n&&l(n,[]),m}const dt=t=>t[0].toUpperCase()+t.slice(1).replace(/[-_]+/g," ");function pt({root:t,options:n,routes:m}){const l=n.pages??{},u=(e,f,w)=>({route:e,name:f,label:f.replace(/^[\d.]+[A-Z]?\.\s*/,""),group:w}),p=m.filter(e=>e.origin==="project"&&e.type==="page"&&!e.pattern.includes("[")).map(e=>({route:e.pattern.replace(/\/+$/,"")||"/",entrypoint:e.entrypoint})),a=new Set(p.map(e=>e.route)),c=[...p,...Object.keys(l).filter(e=>!a.has(e)).map(e=>({route:e}))],j={};for(const{route:e}of c){const f=e.split("/")[1];f&&(j[f]=(j[f]||0)+1)}const k=e=>{const f=e.split("/")[1];return f&&j[f]>1?dt(f):"Pages"},L=n.groups?()=>n.groups[n.groups.length-1]:k,P=c.map(({route:e,entrypoint:f})=>{const[w,N]=l[e]??[];return u(e,w??(f&&ft(t,f))??e,N??L(e))}),r=n.groups??[...new Set([...Object.values(l).map(([,e])=>e).filter(Boolean),"Pages",...P.map(e=>e.group).sort()])],d=P.sort((e,f)=>r.indexOf(e.group)-r.indexOf(f.group)||Z(e.name)-Z(f.name)||e.route.localeCompare(f.route)),s=(n.breakpoints??lt).map(e=>({id:e.id,label:e.label,min:e.min,ideal:e.ideal,max:Number.isFinite(e.max)?e.max:null,icon:e.icon??U[e.id]??U.desktop})),o=(n.devices??mt).filter(e=>e.w>0&&e.h>0&&W.includes(e.shell)&&V.includes(e.browser)?!0:(console.warn(`[notemend] device "${e.id}" skipped: it needs w and h, shell (${W.join(", ")}) and browser (${V.join(", ")})${e.frame?"; `frame` pictures were replaced by shell + browser in 0.3":""}`),!1));return{pages:d,groups:r.filter(e=>d.some(f=>f.group===e)),breakpoints:s,devices:o,categories:ct,sanity:!!n.sanity,shortcuts:n.shortcuts!==!1,ignore:n.ignore??[],grid:{container:"container",grid:"grid",columns:12,...n.grid},zIndex:n.zIndex??2000000020}}const gt=t=>{const n=I(t,"notemend.config.mjs");let m=0,l={};return async()=>{if(!D(n))return{};const u=q(n).mtimeMs;if(u===m)return l;m=u;try{const{default:p,...a}=await import(/* webpackIgnore: true */ /* turbopackIgnore: true */ `${rt(n).href}?t=${u}`);l={...a,...p}}catch(p){console.warn(`[notemend] notemend.config.mjs: ${p.message}`)}return l}},ht=t=>{const n=String(t.headers.host||"").toLowerCase(),m=n.startsWith("[")?n.slice(1,n.indexOf("]")):n.replace(/:\d+$/,"");return m.includes(":")?G(m)===6:!m||!m.includes(".")||G(m)===4||/\.(localhost|local|test|internal|lan|home\.arpa)$/.test(m)},v=(t,n)=>String(t??"").replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,n),wt=t=>({route:v(t.route,500),text:String(t.text??"").slice(0,1e4),selector:v(t.selector,2e3),rx:Number.isFinite(t.rx)?t.rx:0,ry:Number.isFinite(t.ry)?t.ry:0,label:v(t.label,200),ctx:v(t.ctx,120),breakpoint:v(t.breakpoint,40),browser:v(t.browser,80),device:v(t.device,80),tag:v(t.tag,40),classes:Array.isArray(t.classes)?t.classes.slice(0,20).map(n=>v(n,80)):[],nth:Number.isInteger(t.nth)?t.nth:null,category:v(t.category,40),...["urgent","high","normal","low"].includes(t.priority)?{priority:t.priority}:{},...t.shared===!0?{shared:!0}:{},viewport:t.viewport&&Number.isFinite(t.viewport.w)&&Number.isFinite(t.viewport.h)?{w:t.viewport.w,h:t.viewport.h}:null,...R(t.assignee)?{assignee:R(t.assignee)}:{},...M.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(n=>({at:v(n?.at,30),kind:["console","error","rejection","network"].includes(n?.kind)?n.kind:"console",text:et(v(n?.text,500))})).filter(n=>n.text)}:{},...t.suggest&&typeof t.suggest.from=="string"&&typeof t.suggest.to=="string"&&t.suggest.to.trim()?{suggest:{from:t.suggest.from.slice(0,2e3),to:t.suggest.to.slice(0,2e3)}}:{}}),yt=t=>{const n={};return(t.status==="open"||t.status==="done")&&(n.status=t.status),t.status==="open"&&(n.reopenedAt=new Date().toISOString()),"doneBy"in t&&(n.doneBy=t.doneBy==="you"?"you":null),typeof t.category=="string"&&(n.category=ut(t.category).id),"priority"in t&&(n.priority=["urgent","high","normal","low"].includes(t.priority)?t.priority:null),typeof t.shared=="boolean"&&(n.shared=t.shared||null),"assignee"in t&&(n.assignee=R(t.assignee)),"stage"in t&&(n.stage=M.includes(t.stage)?t.stage:null),t.stage==="accepted"&&(n.acceptedAt=new Date().toISOString()),n},Q=async(t,n,m,l,u)=>{if(typeof l!="string")return;const p=n.comments.find(a=>a.id===Number(m))?.images?.filter(a=>it(a)===u)??[];if(await t.attach(n,m,l,u))for(const a of p)await t.detach(n,m,a)},H=t=>{const n=t.headers.origin;if(!n)return!1;try{return new URL(n).host!==t.headers.host}catch{return!0}};function xt({root:t,options:n,routes:m,open:l=()=>ot(t),crossOrigin:u=!1}){const p=gt(t),a=(r,d=200)=>({status:d,type:"application/json",body:JSON.stringify(r)}),c=(r,d)=>({status:r,type:"text/plain",body:d}),j=async r=>{const d=await r.body();if(d.length>45e5)throw Object.assign(new Error("too large"),{status:413});try{return d.length?JSON.parse(d.toString("utf8")):{}}catch{throw Object.assign(new Error("not JSON"),{status:400})}},k=async(r,d)=>{const s=async o=>{const e=await d(o);if(e.status>=400)throw Object.assign(new Error("not written"),{out:e});return e};try{if(r.cloud)return await st(r,s);const o=r.load(),e=await s(o);return r.save(o),e}catch(o){if(o.out)return o.out;throw o}},L=async(r,d)=>{if(r.method!=="GET"&&!u&&H(r))return c(403,"Cross-origin write refused");const s=await l();if(r.method==="GET"){const i=d.searchParams.get("route"),y=s.version?String(await s.version()):null;if(y&&d.searchParams.get("since")===y)return{status:204,type:"text/plain",body:""};const x=await s.load();return a({version:y,comments:i?x.comments.filter(T=>T.route===i):x.comments,listening:x.listening??null,turbo:x.turbo??null})}let o=null,e=null;const f=s.cloud&&r.method!=="DELETE"?s.people().then(i=>{o=i,e=i.me},i=>{throw i}).catch(i=>i):Promise.resolve(),w=async()=>{const i=await f;if(i instanceof Error)throw i},N=i=>{if(e&&i){i.by=e.email,i.byName=e.name;const y=at(i.text,o.team.filter(x=>x.email!==e.email));y.length&&(i.mentions=y)}return i};if(r.method==="POST"){const{image:i,images:y,before:x,...T}=await j(r),A=wt(T);return A.text.trim()?/^\/(?![\/\\])/.test(A.route)?k(s,async B=>{await w();const O=N(s.add(B,A));for(const C of[].concat(y??i??[]))await s.attach(B,O.id,C);return await Q(s,B,O.id,x,"before"),a(O,201)}):a({error:"route must be a path"},400):a({error:"empty comment"},400)}if(r.method==="PATCH"){const i=await j(r);if(i.turbo==="on"||i.turbo==="off")return k(s,async h=>(h.turbo={paused:i.turbo==="off",at:new Date().toISOString()},a({turbo:h.turbo})));const{id:y,reply:x,image:T,images:A,removeImage:B,edit:O,unsay:C,after:X,...Y}=i,g=Number(y);if(!Number.isInteger(g))return a({error:"bad id"},400);const E=yt(Y);return k(s,async h=>{if(await w(),O){const S=h.comments.find(_=>_.id===Number(g)),$=O.at?S?.replies?.find(_=>_.at===O.at):S;if(e&&$?.by&&$.by!==e.email||!(O.text?.trim?.()&&s.edit(h,g,O.at??null,O.text.trim().slice(0,1e4))))return a({error:`no message of yours to edit in #${g}`},404)}if(typeof C=="string"){const S=h.comments.find($=>$.id===g)?.replies?.find($=>$.at===C);return!S||e&&S.by&&S.by!==e.email||!s.unsay(h,g,C)?a({error:`no reply of yours to delete in #${g}`},404):a(h.comments.find($=>$.id===g))}x?.trim?.()&&N(s.reply(h,g,"you",x.trim().slice(0,1e4))?.replies.at(-1));for(const S of[].concat(A??T??[]))await s.attach(h,g,S);for(const S of[].concat(B||[]))await s.detach(h,g,S);await Q(s,h,g,X,"after"),e&&E.status==="done"&&Object.assign(E,{confirmedBy:e.email,confirmedAt:new Date().toISOString()}),e&&E.status==="open"&&Object.assign(E,{confirmedBy:null,confirmedAt:null});const b=Object.keys(E).length||!x?s.patch(h,g,E):h.comments.find(S=>S.id===Number(g));return b?a(b):a({error:`no comment #${g}`},404)})}if(r.method==="DELETE"){const i=Number(d.searchParams.get("id"));return k(s,async y=>await s.remove(y,i)?a({ok:!0,id:i}):a({error:`no comment #${i}`},404))}return c(405,"Method not allowed")},P=(r,d)=>{const s=d.replace(/^.*[/\\]/,""),o=s.split(".").pop()?.toLowerCase()??"";if(!/^[\w.-]+$/.test(s)||!K[o])return c(400,"Bad name");const e=I(r,s);return D(e)?{status:200,type:K[o],body:z(e)}:c(404,"Not found")};return async r=>{const d=new URL(r.url,"http://devbar"),s=d.pathname.slice(10);if(!u&&!ht(r))return c(403,"Notemend answers local addresses only");try{if(s==="config"){const o=pt({root:t,options:{...await p(),...n},routes:m()}),e=await l();return e.cloud&&Object.assign(o,await e.people().catch(()=>({}))),(e.cloud||await F().catch(()=>null))&&(o.voice=!0),a(o)}if(s==="transcribe"&&r.method==="POST"){if(!u&&H(r))return c(403,"Cross-origin write refused");const o=await l(),e=o.cloud?await o.token():(await F().catch(()=>null))?.access_token;if(!e)return c(401,"Voice replies need Notemend \u2014 run `npx notemend login`.");const{audio:f}=await j(r),w=/^data:(audio\/(?:webm|mp4))(?:;[\w=.-]+)*;base64,(.+)$/s.exec(String(f||""));if(!w)return c(400,"Not a recording");const N=await fetch(`${J}/api/transcribe`,{method:"POST",body:Buffer.from(w[2],"base64"),headers:{authorization:`Bearer ${e}`,"content-type":w[1]}});return{status:N.status,type:"application/json",body:await N.text()}}if(s==="translate"&&r.method==="POST"){if(!u&&H(r))return c(403,"Cross-origin write refused");const o=await l(),e=o.cloud?await o.token():(await F().catch(()=>null))?.access_token;if(!e)return c(401,"Translating needs Notemend \u2014 run `npx notemend login`.");const{text:f,to:w}=await j(r),N=await fetch(`${J}/api/translate`,{method:"POST",body:JSON.stringify({text:f,to:w}),headers:{authorization:`Bearer ${e}`,"content-type":"application/json"}});return{status:N.status,type:"application/json",body:await N.text()}}if(s==="comments")return await L(r,d);if(s==="image"){const o=await l(),e=(d.searchParams.get("name")||"").replace(/^.*[/\\]/,"");return o.cloud&&/^[\w.-]+$/.test(e)&&await o.fetchImage(e).catch(()=>null),P(o.imageDir,e)}return c(404,"Not found")}catch(o){return o.status===400||o.status===413?c(o.status,o.message):(console.error("[notemend]",o),c(500,"Something went wrong \u2014 the dev server log says what."))}}}function Bt(t){const n=xt(t),m=l=>new Promise((u,p)=>{const a=[];l.on("data",c=>a.push(c)),l.on("end",()=>u(Buffer.concat(a))),l.on("error",p)});return async function(u,p,a){if(!u.url||!u.url.startsWith("/__devbar/"))return a();const c=await n({method:u.method,url:u.url,headers:u.headers,body:()=>m(u)});p.statusCode=c.status,p.setHeader("content-type",c.type),p.setHeader("cache-control","no-store"),p.end(c.body)}}export{pt as buildConfig,xt as notemendHandler,Bt as notemendMiddleware,At as scanApp,ft as titleOf,dt as titled};
1
+ import{readFileSync as z,existsSync as D,statSync as q,readdirSync as tt}from"node:fs";import{mask as et}from"../store/mask.mjs";import{join as I,isAbsolute as nt}from"node:path";import{isIP as G}from"node:net";import{pathToFileURL as rt}from"node:url";import{openStore as ot,retry as st,CABINET as J,session as F}from"../store/cloud.mjs";import{mentionsIn as at,cleanAssignee as R,STAGES as M}from"../store/thread.mjs";import{fileFrame as U}from"../store/comments.mjs";import{CATEGORIES as it,categoryOf as ct}from"../store/categories.mjs";import{BREAKPOINTS as ut,DEVICES as lt,ICONS as W,SHELLS as V,BROWSERS as K}from"../presets.mjs";const Z={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",svg:"image/svg+xml",webm:"video/webm",m4a:"audio/mp4",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},Q=t=>t.split(".").slice(0,2).map(Number).reduce((n,d)=>n*100+(Number.isNaN(d)?9999:d),0),mt=(t,n)=>{try{const m=z(nt(n)?n:I(t,n),"utf8").match(/title="([^"]+)"|\btitle:\s*["'`]([^"'`]+)["'`]/);return(m?.[1]??m?.[2])?.split("\u2014").pop()?.trim()||null}catch{return null}};function At(t){const n=["app","src/app"].map(u=>I(t,u)).find(D),d=[],m=(u,p)=>{for(const c of tt(u,{withFileTypes:!0})){const i=c.name;if(c.isDirectory()){if(/^[_@]|^\(\./.test(i))continue;m(I(u,i),/^\(.+\)$/.test(i)?p:[...p,i])}else/^page\.(jsx?|tsx?|mdx?)$/.test(i)&&d.push({origin:"project",type:"page",pattern:"/"+p.join("/"),entrypoint:I(u,i)})}};return n&&m(n,[]),d}const dt=t=>t[0].toUpperCase()+t.slice(1).replace(/[-_]+/g," ");function ft({root:t,options:n,routes:d}){const m=n.pages??{},u=(e,l,w)=>({route:e,name:l,label:l.replace(/^[\d.]+[A-Z]?\.\s*/,""),group:w}),p=d.filter(e=>e.origin==="project"&&e.type==="page"&&!e.pattern.includes("[")).map(e=>({route:e.pattern.replace(/\/+$/,"")||"/",entrypoint:e.entrypoint})),c=new Set(p.map(e=>e.route)),i=[...p,...Object.keys(m).filter(e=>!c.has(e)).map(e=>({route:e}))],j={};for(const{route:e}of i){const l=e.split("/")[1];l&&(j[l]=(j[l]||0)+1)}const k=e=>{const l=e.split("/")[1];return l&&j[l]>1?dt(l):"Pages"},L=n.groups?()=>n.groups[n.groups.length-1]:k,P=i.map(({route:e,entrypoint:l})=>{const[w,N]=m[e]??[];return u(e,w??(l&&mt(t,l))??e,N??L(e))}),r=n.groups??[...new Set([...Object.values(m).map(([,e])=>e).filter(Boolean),"Pages",...P.map(e=>e.group).sort()])],f=P.sort((e,l)=>r.indexOf(e.group)-r.indexOf(l.group)||Q(e.name)-Q(l.name)||e.route.localeCompare(l.route)),s=(n.breakpoints??ut).map(e=>({id:e.id,label:e.label,min:e.min,ideal:e.ideal,max:Number.isFinite(e.max)?e.max:null,icon:e.icon??W[e.id]??W.desktop})),o=(n.devices??lt).filter(e=>e.w>0&&e.h>0&&V.includes(e.shell)&&K.includes(e.browser)?!0:(console.warn(`[notemend] device "${e.id}" skipped: it needs w and h, shell (${V.join(", ")}) and browser (${K.join(", ")})${e.frame?"; `frame` pictures were replaced by shell + browser in 0.3":""}`),!1));return{pages:f,groups:r.filter(e=>f.some(l=>l.group===e)),breakpoints:s,devices:o,categories:it,sanity:!!n.sanity,shortcuts:n.shortcuts!==!1,ignore:n.ignore??[],grid:{container:"container",grid:"grid",columns:12,...n.grid},zIndex:n.zIndex??2000000020}}const pt=t=>{const n=I(t,"notemend.config.mjs");let d=0,m={};return async()=>{if(!D(n))return{};const u=q(n).mtimeMs;if(u===d)return m;d=u;try{const{default:p,...c}=await import(/* webpackIgnore: true */ /* turbopackIgnore: true */ `${rt(n).href}?t=${u}`);m={...c,...p}}catch(p){console.warn(`[notemend] notemend.config.mjs: ${p.message}`)}return m}},gt=t=>{const n=String(t.headers.host||"").toLowerCase(),d=n.startsWith("[")?n.slice(1,n.indexOf("]")):n.replace(/:\d+$/,"");return d.includes(":")?G(d)===6:!d||!d.includes(".")||G(d)===4||/\.(localhost|local|test|internal|lan|home\.arpa)$/.test(d)},v=(t,n)=>String(t??"").replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,n),ht=t=>({route:v(t.route,500),text:String(t.text??"").slice(0,1e4),selector:v(t.selector,2e3),rx:Number.isFinite(t.rx)?t.rx:0,ry:Number.isFinite(t.ry)?t.ry:0,label:v(t.label,200),ctx:v(t.ctx,120),breakpoint:v(t.breakpoint,40),browser:v(t.browser,80),device:v(t.device,80),tag:v(t.tag,40),classes:Array.isArray(t.classes)?t.classes.slice(0,20).map(n=>v(n,80)):[],nth:Number.isInteger(t.nth)?t.nth:null,category:v(t.category,40),...["urgent","high","normal","low"].includes(t.priority)?{priority:t.priority}:{},...t.shared===!0?{shared:!0}:{},viewport:t.viewport&&Number.isFinite(t.viewport.w)&&Number.isFinite(t.viewport.h)?{w:t.viewport.w,h:t.viewport.h}:null,...R(t.assignee)?{assignee:R(t.assignee)}:{},...M.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(n=>({at:v(n?.at,30),kind:["console","error","rejection","network"].includes(n?.kind)?n.kind:"console",text:et(v(n?.text,500))})).filter(n=>n.text)}:{},...t.suggest&&typeof t.suggest.from=="string"&&typeof t.suggest.to=="string"&&t.suggest.to.trim()?{suggest:{from:t.suggest.from.slice(0,2e3),to:t.suggest.to.slice(0,2e3)}}:{}}),wt=t=>{const n={};return(t.status==="open"||t.status==="done")&&(n.status=t.status),t.status==="open"&&(n.reopenedAt=new Date().toISOString()),"doneBy"in t&&(n.doneBy=t.doneBy==="you"?"you":null),typeof t.category=="string"&&(n.category=ct(t.category).id),"priority"in t&&(n.priority=["urgent","high","normal","low"].includes(t.priority)?t.priority:null),typeof t.shared=="boolean"&&(n.shared=t.shared||null),"assignee"in t&&(n.assignee=R(t.assignee)),"stage"in t&&(n.stage=M.includes(t.stage)?t.stage:null),t.stage==="accepted"&&(n.acceptedAt=new Date().toISOString()),n},b=t=>{const n=t.headers.origin;if(!n)return!1;try{return new URL(n).host!==t.headers.host}catch{return!0}};function yt({root:t,options:n,routes:d,open:m=()=>ot(t),crossOrigin:u=!1}){const p=pt(t),c=(r,f=200)=>({status:f,type:"application/json",body:JSON.stringify(r)}),i=(r,f)=>({status:r,type:"text/plain",body:f}),j=async r=>{const f=await r.body();if(f.length>45e5)throw Object.assign(new Error("too large"),{status:413});try{return f.length?JSON.parse(f.toString("utf8")):{}}catch{throw Object.assign(new Error("not JSON"),{status:400})}},k=async(r,f)=>{const s=async o=>{const e=await f(o);if(e.status>=400)throw Object.assign(new Error("not written"),{out:e});return e};try{if(r.cloud)return await st(r,s);const o=r.load(),e=await s(o);return r.save(o),e}catch(o){if(o.out)return o.out;throw o}},L=async(r,f)=>{if(r.method!=="GET"&&!u&&b(r))return i(403,"Cross-origin write refused");const s=await m();if(r.method==="GET"){const a=f.searchParams.get("route"),y=s.version?String(await s.version()):null;if(y&&f.searchParams.get("since")===y)return{status:204,type:"text/plain",body:""};const x=await s.load();return c({version:y,comments:a?x.comments.filter(T=>T.route===a):x.comments,listening:x.listening??null,turbo:x.turbo??null})}let o=null,e=null;const l=s.cloud&&r.method!=="DELETE"?s.people().then(a=>{o=a,e=a.me},a=>{throw a}).catch(a=>a):Promise.resolve(),w=async()=>{const a=await l;if(a instanceof Error)throw a},N=a=>{if(e&&a){a.by=e.email,a.byName=e.name;const y=at(a.text,o.team.filter(x=>x.email!==e.email));y.length&&(a.mentions=y)}return a};if(r.method==="POST"){const{image:a,images:y,before:x,...T}=await j(r),A=ht(T);return A.text.trim()?/^\/(?![\/\\])/.test(A.route)?k(s,async B=>{await w();const O=N(s.add(B,A));for(const C of[].concat(y??a??[]))await s.attach(B,O.id,C);return await U(s,B,O.id,x,"before"),c(O,201)}):c({error:"route must be a path"},400):c({error:"empty comment"},400)}if(r.method==="PATCH"){const a=await j(r);if(a.turbo==="on"||a.turbo==="off")return k(s,async h=>(h.turbo={paused:a.turbo==="off",at:new Date().toISOString()},c({turbo:h.turbo})));const{id:y,reply:x,image:T,images:A,removeImage:B,edit:O,unsay:C,after:X,...Y}=a,g=Number(y);if(!Number.isInteger(g))return c({error:"bad id"},400);const E=wt(Y);return k(s,async h=>{if(await w(),O){const S=h.comments.find(_=>_.id===Number(g)),$=O.at?S?.replies?.find(_=>_.at===O.at):S;if(e&&$?.by&&$.by!==e.email||!(O.text?.trim?.()&&s.edit(h,g,O.at??null,O.text.trim().slice(0,1e4))))return c({error:`no message of yours to edit in #${g}`},404)}if(typeof C=="string"){const S=h.comments.find($=>$.id===g)?.replies?.find($=>$.at===C);return!S||e&&S.by&&S.by!==e.email||!s.unsay(h,g,C)?c({error:`no reply of yours to delete in #${g}`},404):c(h.comments.find($=>$.id===g))}x?.trim?.()&&N(s.reply(h,g,"you",x.trim().slice(0,1e4))?.replies.at(-1));for(const S of[].concat(A??T??[]))await s.attach(h,g,S);for(const S of[].concat(B||[]))await s.detach(h,g,S);await U(s,h,g,X,"after"),e&&E.status==="done"&&Object.assign(E,{confirmedBy:e.email,confirmedAt:new Date().toISOString()}),e&&E.status==="open"&&Object.assign(E,{confirmedBy:null,confirmedAt:null});const H=Object.keys(E).length||!x?s.patch(h,g,E):h.comments.find(S=>S.id===Number(g));return H?c(H):c({error:`no comment #${g}`},404)})}if(r.method==="DELETE"){const a=Number(f.searchParams.get("id"));return k(s,async y=>await s.remove(y,a)?c({ok:!0,id:a}):c({error:`no comment #${a}`},404))}return i(405,"Method not allowed")},P=(r,f)=>{const s=f.replace(/^.*[/\\]/,""),o=s.split(".").pop()?.toLowerCase()??"";if(!/^[\w.-]+$/.test(s)||!Z[o])return i(400,"Bad name");const e=I(r,s);return D(e)?{status:200,type:Z[o],body:z(e)}:i(404,"Not found")};return async r=>{const f=new URL(r.url,"http://devbar"),s=f.pathname.slice(10);if(!u&&!gt(r))return i(403,"Notemend answers local addresses only");try{if(s==="config"){const o=ft({root:t,options:{...await p(),...n},routes:d()}),e=await m();return e.cloud&&Object.assign(o,await e.people().catch(()=>({}))),(e.cloud||await F().catch(()=>null))&&(o.voice=!0),c(o)}if(s==="transcribe"&&r.method==="POST"){if(!u&&b(r))return i(403,"Cross-origin write refused");const o=await m(),e=o.cloud?await o.token():(await F().catch(()=>null))?.access_token;if(!e)return i(401,"Voice replies need Notemend \u2014 run `npx notemend login`.");const{audio:l}=await j(r),w=/^data:(audio\/(?:webm|mp4))(?:;[\w=.-]+)*;base64,(.+)$/s.exec(String(l||""));if(!w)return i(400,"Not a recording");const N=await fetch(`${J}/api/transcribe`,{method:"POST",body:Buffer.from(w[2],"base64"),headers:{authorization:`Bearer ${e}`,"content-type":w[1]}});return{status:N.status,type:"application/json",body:await N.text()}}if(s==="translate"&&r.method==="POST"){if(!u&&b(r))return i(403,"Cross-origin write refused");const o=await m(),e=o.cloud?await o.token():(await F().catch(()=>null))?.access_token;if(!e)return i(401,"Translating needs Notemend \u2014 run `npx notemend login`.");const{text:l,to:w}=await j(r),N=await fetch(`${J}/api/translate`,{method:"POST",body:JSON.stringify({text:l,to:w}),headers:{authorization:`Bearer ${e}`,"content-type":"application/json"}});return{status:N.status,type:"application/json",body:await N.text()}}if(s==="comments")return await L(r,f);if(s==="image"){const o=await m(),e=(f.searchParams.get("name")||"").replace(/^.*[/\\]/,"");return o.cloud&&/^[\w.-]+$/.test(e)&&await o.fetchImage(e).catch(()=>null),P(o.imageDir,e)}return i(404,"Not found")}catch(o){return o.status===400||o.status===413?i(o.status,o.message):(console.error("[notemend]",o),i(500,"Something went wrong \u2014 the dev server log says what."))}}}function Bt(t){const n=yt(t),d=m=>new Promise((u,p)=>{const c=[];m.on("data",i=>c.push(i)),m.on("end",()=>u(Buffer.concat(c))),m.on("error",p)});return async function(u,p,c){if(!u.url||!u.url.startsWith("/__devbar/"))return c();const i=await n({method:u.method,url:u.url,headers:u.headers,body:()=>d(u)});p.statusCode=i.status,p.setHeader("content-type",i.type),p.setHeader("cache-control","no-store"),p.end(i.body)}}export{ft as buildConfig,yt as notemendHandler,Bt as notemendMiddleware,At as scanApp,mt as titleOf,dt as titled};
@@ -1,3 +1,3 @@
1
- import{readFileSync as E,writeFileSync as y,existsSync as $,mkdirSync as I,renameSync as F,rmSync as J}from"node:fs";import{dirname as C,join as l}from"node:path";import{categoryOf as L}from"./categories.mjs";import{DOCS as M,FRAMES as R,docSlug as G}from"./thread.mjs";import{CATEGORIES as ee,categoryOf as te}from"./categories.mjs";import{stateOf as re,STATE_LABEL as oe}from"./status.mjs";const v=r=>{const e=String(r??"").split(/[/\\]/).pop();return/^[\w-][\w.-]*\.(png|jpe?g|webp|gif|webm|m4a|pdf|docx?)$/i.test(e)?e:""},_=r=>{const e=/^data:(application\/[\w.+-]+)((?:;[\w=.-]+)*);base64,(.+)$/s.exec(String(r||""));if(e){const x=Object.keys(M).find(O=>M[O]===e[1]);return x?{base64:e[3],voice:!1,ext:x,type:e[1],slug:G(/;name=([\w.-]+)/.exec(e[2])?.[1])}:null}const n=/^data:(image|video|audio)\/(png|jpeg|webp|gif|webm|mp4)(?:;[\w=.-]+)*;base64,(.+)$/s.exec(String(r||""));if(!n)return null;const[,o,t,c]=n;return(o==="image"?!/^(png|jpeg|webp|gif)$/.test(t):o==="video"?t!=="webm":!/^(webm|mp4)$/.test(t))?null:{base64:c,voice:o==="audio",ext:t==="jpeg"?"jpg":t==="mp4"?"m4a":t,type:`${o}/${t}`}},B=(r,e,n,o)=>`${n.voice?"voice-":R.includes(o)?`${o}-`:""}${r}-${e}${n.slug?`.${n.slug}`:""}.${n.ext}`,N=r=>Math.max(r.nextId||0,r.comments.reduce((e,n)=>Math.max(e,n.id),0)+1);function q(r,{route:e,selector:n,rx:o,ry:t,text:c,label:d,viewport:x,breakpoint:O,browser:D,device:A,tag:j,classes:i,nth:p,category:g,suggest:s,assignee:a,ctx:m,logs:u,host:S,priority:b,shared:f,stage:h}){const w={id:N(r),route:e,selector:n,rx:o,ry:t,text:c,tag:j||"",classes:i||[],nth:Number.isInteger(p)?p:null,label:d||"",ctx:m||"",viewport:x||null,breakpoint:O||"desktop",browser:D||"",device:A||"",category:L(g).id,status:"open",note:"",replies:[],doneBy:null,images:[],...s?{suggest:s}:{},...a?{assignee:a}:{},...b?{priority:b}:{},...h?{stage:h}:{},...f?{shared:!0}:{},...S?{host:S}:{},...u?.length?{logs:u}:{},createdAt:new Date().toISOString(),updatedAt:null};return r.comments.push(w),r.nextId=w.id+1,w}function z(r,e,n,o,t,c){const d=r.comments.find(x=>x.id===Number(e));return d?((d.replies||=[]).push({author:n,text:o,at:new Date().toISOString(),...t&&t!=="claude"?{agent:t}:{},...c?{by:c}:{}}),d.updatedAt=new Date().toISOString(),d):null}function H(r,e,n,o){const t=r.comments.find(d=>d.id===Number(e)),c=n?t?.replies?.find(d=>d.at===n&&d.author==="you"):t;return c?(c.text=o,t.updatedAt=new Date().toISOString(),t):null}function K(r,e,n){const o=r.comments.find(c=>c.id===Number(e)),t=o?.replies?.find(c=>c.at===n&&c.author==="you");return t?(t.text="",t.deleted=!0,delete t.mentions,o.updatedAt=new Date().toISOString(),o):null}function P(r,e,n){const o=r.comments.find(t=>t.id===Number(e));return o?(Object.assign(o,n,{updatedAt:new Date().toISOString()}),o):null}function Y(r){const e=l(r,"feedback","comments.json"),n=l(r,"feedback","images"),o=l(r,"feedback","archive"),t=l(o,"images"),c=i=>`feedback/images/${i}`;return{root:r,file:e,imageDir:n,archiveDir:o,archiveImageDir:t,load:()=>$(e)?JSON.parse(E(e,"utf8")):{comments:[]},save:i=>{I(C(e),{recursive:!0}),y(`${e}.tmp`,JSON.stringify(i,null,2)+`
2
- `),F(`${e}.tmp`,e)},attach:(i,p,g,s)=>{const a=i.comments.find(b=>b.id===Number(p)),m=_(g);if(!a||!m)return null;I(n,{recursive:!0});let u=Date.now();for(;$(l(n,B(a.id,u,m,s)));)u++;const S=B(a.id,u,m,s);return y(l(n,S),Buffer.from(m.base64,"base64")),(a.images||=[]).push(c(S)),a.updatedAt=new Date().toISOString(),c(S)},detach:(i,p,g)=>{const s=i.comments.find(u=>u.id===Number(p)),a=v(g),m=a&&s?.images?.find(u=>v(u)===a);return m?(J(l(n,a),{force:!0}),s.images=s.images.filter(u=>u!==m),s.updatedAt=new Date().toISOString(),!0):!1},remove:(i,p)=>{const g=i.comments.find(s=>s.id===Number(p));if(!g)return!1;for(const s of g.images||[])v(s)&&J(l(n,v(s)),{force:!0});return i.comments=i.comments.filter(s=>s.id!==Number(p)),!0},add:q,patch:P,reply:z,edit:H,unsay:K,nextId:N,prune:(i,{dry:p=!1,date:g=new Date().toISOString().slice(0,10)}={})=>{const s=i.comments.filter(f=>f.status==="done"),a=i.comments.filter(f=>f.status!=="done"),m=l(o,`comments-${g}.json`);if(p||!s.length)return{moving:s,keeping:a,archiveFile:m,images:s.flatMap(f=>f.images||[])};I(t,{recursive:!0});const u=[];for(const f of s)f.images=(f.images||[]).map(h=>{const w=v(h);if(!w)return h;const k=l(n,w),T=l(t,w);return $(k)&&F(k,T),u.push(w),`feedback/archive/images/${w}`});const S=$(m)?JSON.parse(E(m,"utf8")).comments||[]:[],b=new Set(S.map(f=>f.id));return y(m,JSON.stringify({comments:[...S,...s.filter(f=>!b.has(f.id))]},null,2)+`
3
- `),i.nextId=N(i),i.comments=a,{moving:s,keeping:a,archiveFile:m,images:u}}}}export{ee as CATEGORIES,oe as STATE_LABEL,q as add,te as categoryOf,Y as createStore,H as edit,B as mediaName,_ as mediaOf,N as nextId,P as patch,z as reply,v as shotName,re as stateOf,K as unsay};
1
+ import{readFileSync as F,writeFileSync as y,existsSync as $,mkdirSync as I,renameSync as M,rmSync as J,statSync as L}from"node:fs";import{dirname as R,join as S}from"node:path";import{categoryOf as z}from"./categories.mjs";import{DOCS as B,FRAMES as G,docSlug as _,frameOf as q}from"./thread.mjs";import{CATEGORIES as oe,categoryOf as se}from"./categories.mjs";import{stateOf as ce,STATE_LABEL as ae}from"./status.mjs";const b=r=>{const e=String(r??"").split(/[/\\]/).pop();return/^[\w-][\w.-]*\.(png|jpe?g|webp|gif|webm|m4a|pdf|docx?)$/i.test(e)?e:""},H=r=>{const e=/^data:(application\/[\w.+-]+)((?:;[\w=.-]+)*);base64,(.+)$/s.exec(String(r||""));if(e){const l=Object.keys(B).find(O=>B[O]===e[1]);return l?{base64:e[3],voice:!1,ext:l,type:e[1],slug:_(/;name=([\w.-]+)/.exec(e[2])?.[1])}:null}const t=/^data:(image|video|audio)\/(png|jpeg|webp|gif|webm|mp4)(?:;[\w=.-]+)*;base64,(.+)$/s.exec(String(r||""));if(!t)return null;const[,o,n,c]=t;return(o==="image"?!/^(png|jpeg|webp|gif)$/.test(n):o==="video"?n!=="webm":!/^(webm|mp4)$/.test(n))?null:{base64:c,voice:o==="audio",ext:n==="jpeg"?"jpg":n==="mp4"?"m4a":n,type:`${o}/${n}`}},T=(r,e,t,o)=>`${t.voice?"voice-":G.includes(o)?`${o}-`:""}${r}-${e}${t.slug?`.${t.slug}`:""}.${t.ext}`,ee=async(r,e,t,o,n)=>{if(typeof o!="string")return null;const c=e.comments.find(l=>l.id===Number(t))?.images?.filter(l=>q(l)===n)??[],a=await r.attach(e,t,o,n);if(a)for(const l of c)await r.detach(e,t,l);return a},N=r=>Math.max(r.nextId||0,r.comments.reduce((e,t)=>Math.max(e,t.id),0)+1);function K(r,{route:e,selector:t,rx:o,ry:n,text:c,label:a,viewport:l,breakpoint:O,browser:D,device:A,tag:j,classes:k,nth:i,category:d,suggest:g,assignee:s,ctx:u,logs:m,host:f,priority:w,shared:h,stage:p}){const x={id:N(r),route:e,selector:t,rx:o,ry:n,text:c,tag:j||"",classes:k||[],nth:Number.isInteger(i)?i:null,label:a||"",ctx:u||"",viewport:l||null,breakpoint:O||"desktop",browser:D||"",device:A||"",category:z(d).id,status:"open",note:"",replies:[],doneBy:null,images:[],...g?{suggest:g}:{},...s?{assignee:s}:{},...w?{priority:w}:{},...p?{stage:p}:{},...h?{shared:!0}:{},...f?{host:f}:{},...m?.length?{logs:m}:{},createdAt:new Date().toISOString(),updatedAt:null};return r.comments.push(x),r.nextId=x.id+1,x}function P(r,e,t,o,n,c){const a=r.comments.find(l=>l.id===Number(e));return a?((a.replies||=[]).push({author:t,text:o,at:new Date().toISOString(),...n&&n!=="claude"?{agent:n}:{},...c?{by:c}:{}}),a.updatedAt=new Date().toISOString(),a):null}function Q(r,e,t,o){const n=r.comments.find(a=>a.id===Number(e)),c=t?n?.replies?.find(a=>a.at===t&&a.author==="you"):n;return c?(c.text=o,n.updatedAt=new Date().toISOString(),n):null}function V(r,e,t){const o=r.comments.find(c=>c.id===Number(e)),n=o?.replies?.find(c=>c.at===t&&c.author==="you");return n?(n.text="",n.deleted=!0,delete n.mentions,o.updatedAt=new Date().toISOString(),o):null}function W(r,e,t){const o=r.comments.find(n=>n.id===Number(e));return o?(Object.assign(o,t,{updatedAt:new Date().toISOString()}),o):null}function te(r){const e=S(r,"feedback","comments.json"),t=S(r,"feedback","images"),o=S(r,"feedback","archive"),n=S(o,"images"),c=i=>`feedback/images/${i}`;return{root:r,file:e,imageDir:t,archiveDir:o,archiveImageDir:n,load:()=>$(e)?JSON.parse(F(e,"utf8")):{comments:[]},version:()=>{try{const i=L(e);return`${i.mtimeMs}-${i.size}`}catch{return"0"}},save:i=>{I(R(e),{recursive:!0});const d=`${e}.${process.pid}.${Date.now()}.tmp`;y(d,JSON.stringify(i,null,2)+`
2
+ `),M(d,e)},attach:(i,d,g,s)=>{const u=i.comments.find(h=>h.id===Number(d)),m=H(g);if(!u||!m)return null;I(t,{recursive:!0});let f=Date.now();for(;$(S(t,T(u.id,f,m,s)));)f++;const w=T(u.id,f,m,s);return y(S(t,w),Buffer.from(m.base64,"base64")),(u.images||=[]).push(c(w)),u.updatedAt=new Date().toISOString(),c(w)},detach:(i,d,g)=>{const s=i.comments.find(f=>f.id===Number(d)),u=b(g),m=u&&s?.images?.find(f=>b(f)===u);return m?(J(S(t,u),{force:!0}),s.images=s.images.filter(f=>f!==m),s.updatedAt=new Date().toISOString(),!0):!1},remove:(i,d)=>{const g=i.comments.find(s=>s.id===Number(d));if(!g)return!1;for(const s of g.images||[])b(s)&&J(S(t,b(s)),{force:!0});return i.comments=i.comments.filter(s=>s.id!==Number(d)),!0},add:K,patch:W,reply:P,edit:Q,unsay:V,nextId:N,prune:(i,{dry:d=!1,date:g=new Date().toISOString().slice(0,10)}={})=>{const s=i.comments.filter(p=>p.status==="done"),u=i.comments.filter(p=>p.status!=="done"),m=S(o,`comments-${g}.json`);if(d||!s.length)return{moving:s,keeping:u,archiveFile:m,images:s.flatMap(p=>p.images||[])};I(n,{recursive:!0});const f=[];for(const p of s)p.images=(p.images||[]).map(x=>{const v=b(x);if(!v)return x;const E=S(t,v),C=S(n,v);return $(E)&&M(E,C),f.push(v),`feedback/archive/images/${v}`});const w=$(m)?JSON.parse(F(m,"utf8")).comments||[]:[],h=new Set(w.map(p=>p.id));return y(m,JSON.stringify({comments:[...w,...s.filter(p=>!h.has(p.id))]},null,2)+`
3
+ `),i.nextId=N(i),i.comments=u,{moving:s,keeping:u,archiveFile:m,images:f}}}}export{oe as CATEGORIES,ae as STATE_LABEL,K as add,se as categoryOf,te as createStore,Q as edit,ee as fileFrame,T as mediaName,H as mediaOf,N as nextId,W as patch,P as reply,b as shotName,ce as stateOf,V as unsay};
@@ -1 +1 @@
1
- const O=["before","after"],d=e=>/(?:^|\/)(before|after)-[^/]*$/.exec(String(e))?.[1]??null,y=e=>{const t={};for(const n of e?.images||[]){const o=d(n);o&&(t[o]=n)}return t},u={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},f=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]])),b=e=>String(e??"").replace(/\.[^.]*$/,"").toLowerCase().replace(/[а-яёєіїґ]/g,t=>f[t]??"").normalize("NFKD").replace(/[^\w-]+/g,"-").replace(/^[-_]+|-+$/g,"").slice(0,60),N=e=>{const t=String(e??"");if(t.startsWith("data:")){const o=/^data:([^;,]+)((?:;[^;,]*)*)[;,]/.exec(t),r=o&&Object.keys(u).find(s=>u[s]===o[1]);return r?`${/;name=([\w-]+)/.exec(o[2])?.[1]||"document"}.${r}`:null}const n=/-\d+(?:\.([\w-]+))?\.(pdf|docx?)(?:\?|$)/i.exec(t.split("/").pop());return n?`${n[1]||"document"}.${n[2].toLowerCase()}`:null},m=e=>{const t=[{author:"you",text:e.text,at:e.createdAt,by:e.by,byName:e.byName,images:[]},...e.note?[{author:"claude",text:e.note,at:e.updatedAt,images:[]}]:[],...(e.replies||[]).map(n=>({...n,images:[]}))];for(const n of e.images||[]){if(d(n))continue;const o=Number(/-(\d+)(?:\.[\w-]+)?\.\w+$/.exec(n)?.[1]);let r=0;t.forEach((s,i)=>{Date.parse(s.at)<=o&&(r=i)}),t[r].images.push(n)}return t.filter(n=>!n.deleted)},I=e=>e.nickname||e.name||e.email,$=(e,t)=>{const n=String(e||"").toLowerCase();return n.includes("@")?[...new Set(t.filter(o=>[o.name,o.nickname,o.email].some(r=>{if(!r)return!1;const s=n.indexOf("@"+r.toLowerCase());return s!==-1&&!/[\p{L}\p{N}_.-]/u.test(n[s+r.length+1]??"")})).map(o=>o.email))]:[]},x={claude:"Claude",codex:"Codex",gemini:"Gemini",cursor:"Cursor",copilot:"Copilot",windsurf:"Windsurf",amp:"Amp",aider:"Aider",opencode:"OpenCode",agent:"AI agent"},h=e=>x[e]||(e?"AI agent":"Claude"),D="3.6 3.6 10.8 10.8",w="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",l=e=>typeof e=="string"&&e.startsWith("agent:")?e.slice(6):null,p=e=>e==="claude"||l(e)!=null,A=/^[^\s@]+@[^\s@]+$/,_=e=>{if(e==="claude")return e;if(typeof e!="string"||e.length>210)return null;const t=e.toLowerCase();return A.test(l(t)??t)?t:null},L=["new","approved","progress","review","waiting","accepted"],c=e=>L.includes(e?.stage)?e.stage:p(e?.assignee)?"approved":"new",E=(e,t)=>{const n=l(e.assignee);return c(e)==="approved"&&(!e.assignee||e.assignee==="claude"||n!=null&&(t===void 0||n===t))&&!g(e)},k=()=>[{assignee:"claude",handle:"Claude",owner:null}],T=(e,t=[])=>{const n=String(e||"").toLowerCase();let o=null,r=-1;for(const s of k()){const i="@"+s.handle.toLowerCase();for(let a=n.indexOf(i);a!==-1;a=n.indexOf(i,a+1))!/[\p{L}\p{N}_.-]/u.test(n[a+i.length]??"")&&a>r&&(r=a,o=s.assignee)}return o},v=(e,t,n=o=>o)=>h(e)+(t?` \xB7 ${n(t)}`:""),M=2*36e5,S=(e,t=Date.now())=>e?.working&&e.status!=="done"&&t-Date.parse(e.working.at)<M?e.working:null,C=e=>/@guest\.notemend\.com$/i.test(String(e||"")),g=e=>C(e.by)&&!e.approvedBy,W=(e,t=Date.now())=>{if(!e)return null;if(e.status==="done")return e.doneBy==="claude"?"review":p(e.assignee)?"done":null;if(e.stage==="accepted")return p(e.assignee)?"done":null;if(g(e))return"held";if(!p(e.assignee))return null;const n=m(e),o=n[n.length-1];return n.length>1&&o.author==="claude"&&!(e.reopenedAt&&Date.parse(e.reopenedAt)>=Date.parse(o.at))?"asks":S(e,t)?"working":e.working?"stuck":c(e)==="approved"?"queued":null},G={held:0,queued:2,asks:6,working:6,stuck:6,review:10,done:12},H=w.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),R={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"},B=(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};export{x as AGENTS,D as AI_BOX,w as AI_RAYS,H as AI_RAYS_CW,u as DOCS,O as FRAMES,L as STAGES,G as STEP_RAYS,R as UPDATE_HOW,M as WORKING_TTL,k as agentHandles,v as agentLabel,T as agentMentioned,h as agentName,l as agentOwner,W as agentStep,_ as cleanAssignee,N as docOf,b as docSlug,E as forAgentOf,d as frameOf,y as framesOf,I as handleOf,g as held,C as isGuest,$ as mentionsIn,B as newer,c as stageOf,m as threadOf,p as toAgent,S as workingOn};
1
+ const C=["before","after"],l=e=>/(?:^|\/)(before|after)-[^/]*$/.exec(String(e))?.[1]??null,O=e=>{const t={};for(const n of e?.images||[]){const o=l(n);o&&(t[o]=n)}return t},d={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},m=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]])),b=e=>String(e??"").replace(/\.[^.]*$/,"").toLowerCase().replace(/[а-яёєіїґ]/g,t=>m[t]??"").normalize("NFKD").replace(/[^\w-]+/g,"-").replace(/^[-_]+|-+$/g,"").slice(0,60),I=e=>{const t=String(e??"");if(t.startsWith("data:")){const o=/^data:([^;,]+)((?:;[^;,]*)*)[;,]/.exec(t),r=o&&Object.keys(d).find(s=>d[s]===o[1]);return r?`${/;name=([\w-]+)/.exec(o[2])?.[1]||"document"}.${r}`:null}const n=/-\d+(?:\.([\w-]+))?\.(pdf|docx?)(?:\?|$)/i.exec(t.split("/").pop());return n?`${n[1]||"document"}.${n[2].toLowerCase()}`:null},f=e=>{const t=[{author:"you",text:e.text,at:e.createdAt,by:e.by,byName:e.byName,images:[]},...e.note?[{author:"claude",text:e.note,at:e.updatedAt,images:[]}]:[],...(e.replies||[]).map(n=>({...n,images:[]}))];for(const n of e.images||[]){if(l(n))continue;const o=Number(/-(\d+)(?:\.[\w-]+)?\.\w+$/.exec(n)?.[1]);let r=0;t.forEach((s,a)=>{Date.parse(s.at)<=o&&(r=a)}),t[r].images.push(n)}return t.filter(n=>!n.deleted)},N=e=>e.nickname||e.name||e.email,u=(e,t)=>{const n="@"+t.toLowerCase();let o=-1;for(let r=e.indexOf(n);r!==-1;r=e.indexOf(n,r+1))/[\p{L}\p{N}_.-]/u.test(e[r+n.length]??"")||(o=r);return o},$=(e,t)=>{const n=String(e||"").toLowerCase();return n.includes("@")?[...new Set(t.filter(o=>[o.name,o.nickname,o.email].some(r=>r&&u(n,r)!==-1)).map(o=>o.email))]:[]},x={claude:"Claude",codex:"Codex",gemini:"Gemini",cursor:"Cursor",copilot:"Copilot",windsurf:"Windsurf",amp:"Amp",aider:"Aider",opencode:"OpenCode",agent:"AI agent"},h=e=>x[e]||(e?"AI agent":"Claude"),D="3.6 3.6 10.8 10.8",w="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",p=e=>typeof e=="string"&&e.startsWith("agent:")?e.slice(6):null,i=e=>e==="claude"||p(e)!=null,A=/^[^\s@]+@[^\s@]+$/,_=e=>{if(e==="claude")return e;if(typeof e!="string"||e.length>210)return null;const t=e.toLowerCase();return A.test(p(t)??t)?t:null},k=["new","approved","progress","review","waiting","accepted"],c=e=>k.includes(e?.stage)?e.stage:i(e?.assignee)?"approved":"new",E=(e,t)=>{const n=p(e.assignee);return c(e)==="approved"&&(!e.assignee||e.assignee==="claude"||n!=null&&(t===void 0||n===t))&&!g(e)},M=()=>[{assignee:"claude",handle:"Claude",owner:null}],T=(e,t=[])=>{const n=String(e||"").toLowerCase();let o=null,r=-1;for(const s of M()){const a=u(n,s.handle);a>r&&(r=a,o=s.assignee)}return o},v=(e,t,n=o=>o)=>h(e)+(t?` \xB7 ${n(t)}`:""),S=2*36e5,L=(e,t=Date.now())=>e?.working&&e.status!=="done"&&t-Date.parse(e.working.at)<S?e.working:null,y=e=>/@guest\.notemend\.com$/i.test(String(e||"")),g=e=>y(e.by)&&!e.approvedBy,W=(e,t=Date.now())=>{if(!e)return null;if(e.status==="done")return e.doneBy==="claude"?"review":i(e.assignee)?"done":null;if(e.stage==="accepted")return i(e.assignee)?"done":null;if(g(e))return"held";if(!i(e.assignee))return null;const n=f(e),o=n[n.length-1];return n.length>1&&o.author==="claude"&&!(e.reopenedAt&&Date.parse(e.reopenedAt)>=Date.parse(o.at))?"asks":L(e,t)?"working":e.working?"stuck":c(e)==="approved"?"queued":null},G={held:0,queued:2,asks:6,working:6,stuck:6,review:10,done:12},H=w.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),R={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"},B=(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};export{x as AGENTS,D as AI_BOX,w as AI_RAYS,H as AI_RAYS_CW,d as DOCS,C as FRAMES,k as STAGES,G as STEP_RAYS,R as UPDATE_HOW,S as WORKING_TTL,M as agentHandles,v as agentLabel,T as agentMentioned,h as agentName,p as agentOwner,W as agentStep,_ as cleanAssignee,I as docOf,b as docSlug,E as forAgentOf,l as frameOf,O as framesOf,N as handleOf,g as held,y as isGuest,$ as mentionsIn,B as newer,c as stageOf,f as threadOf,i as toAgent,L as workingOn};
package/store.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import type { Working } from './thread.js';
2
2
 
3
3
  /** One reply in a thread: `author: 'claude'` is any agent, `agent` says which */
4
- export interface Reply { author: 'you' | 'claude'; text: string; at: string; by?: string; byName?: string; agent?: string; mentions?: string[] }
4
+ export interface Reply { author: 'you' | 'claude'; text: string; at: string; by?: string; byName?: string; agent?: string; mentions?: string[];
5
+ /** taken back by its writer: kept in place, emptied */
6
+ deleted?: boolean }
5
7
  /** A line the page logged before the comment was written (the bar's logs) */
6
8
  export interface LogLine { at: string; kind: 'console' | 'error' | 'rejection' | 'network'; text: string }
7
9
 
@@ -15,6 +17,18 @@ export interface Comment {
15
17
  doneBy: string | null; doneAgent?: string | null;
16
18
  images: string[]; suggest?: { from: string; to: string }; assignee?: string;
17
19
  working?: Working | null; logs?: LogLine[];
20
+ stage?: 'new' | 'approved' | 'progress' | 'review' | 'waiting' | 'accepted';
21
+ priority?: 'urgent' | 'high' | 'normal' | 'low';
22
+ /** the project's clients see it too */
23
+ shared?: boolean;
24
+ /** a person sent it back: the agent's last word before this is no question */
25
+ reopenedAt?: string; acceptedAt?: string;
26
+ /** who ticked it as fixed, in a team */
27
+ confirmedBy?: string | null; confirmedAt?: string | null;
28
+ /** the person the agent ran as when it resolved it */
29
+ doneFor?: string | null;
30
+ /** a guest's thread, approved by the studio */
31
+ approvedBy?: string | null;
18
32
  /** the copy of the site it was written on — live, staging, localhost — as host[:port] */
19
33
  host?: string;
20
34
  by?: string; byName?: string; createdAt: string; updatedAt: string | null;
@@ -36,21 +50,32 @@ export function shotName(path: string): string;
36
50
  /** The next thread's number: never one a deleted or archived thread had */
37
51
  export function nextId(db: Db): number;
38
52
  export function add(db: Db, comment: NewComment): Comment;
39
- export function reply(db: Db, id: number | string, author: 'you' | 'claude', text: string, agent?: string): Comment | null;
53
+ export function reply(db: Db, id: number | string, author: 'you' | 'claude', text: string, agent?: string, by?: string): Comment | null;
40
54
  /** Reword the comment (`at` null) or one of your replies (by when it was written) */
41
55
  export function edit(db: Db, id: number | string, at: string | null, text: string): Comment | null;
56
+ /** Take back one of your replies, found by when it was written */
57
+ export function unsay(db: Db, id: number | string, at: string): Comment | null;
42
58
  export function patch(db: Db, id: number | string, changes: Partial<Comment>): Comment | null;
59
+ export type Media = { base64: string; voice: boolean; ext: string; type: string; slug?: string };
60
+ /** What a data: URL files as — a screenshot, a recording, a voice note or a document — else null */
61
+ export function mediaOf(dataUrl: string): Media | null;
62
+ /** The filed name: <id>-<ms>.<ext>, voice-…, or before-… / after-… for a frame */
63
+ export function mediaName(id: number, ms: number, media: Media, kind?: 'before' | 'after'): string;
64
+ /** File a frame of the element, dropping the older one of its kind; either store */
65
+ export function fileFrame(store: { attach: Function; detach: Function }, db: Db, id: number | string, dataUrl: unknown, kind: 'before' | 'after'): Promise<string | null>;
43
66
 
44
67
  /** One project's store on disk: <root>/feedback/comments.json and feedback/images/ */
45
68
  export function createStore(root: string): {
46
69
  root: string; file: string; imageDir: string; archiveDir: string; archiveImageDir: string;
47
70
  load(): Db;
48
71
  save(db: Db): void;
49
- /** file a data: URL screenshot (or webm) under the comment; returns its path or null */
50
- attach(db: Db, id: number | string, dataUrl: string): string | null;
72
+ /** the file's stamp, for ?since= polls: '0' when there is no file yet */
73
+ version(): string;
74
+ /** file a data: URL screenshot (or webm) under the comment — `kind` makes it a frame; returns its path or null */
75
+ attach(db: Db, id: number | string, dataUrl: string, kind?: 'before' | 'after'): string | null;
51
76
  detach(db: Db, id: number | string, name: string): boolean;
52
77
  remove(db: Db, id: number | string): boolean;
53
78
  /** move resolved threads to feedback/archive/, leaving the id floor behind */
54
79
  prune(db: Db, opts?: { dry?: boolean; date?: string }): { moving: Comment[]; keeping: Comment[]; archiveFile: string; images: string[] };
55
- add: typeof add; patch: typeof patch; reply: typeof reply; edit: typeof edit; nextId: typeof nextId;
80
+ add: typeof add; patch: typeof patch; reply: typeof reply; edit: typeof edit; unsay: typeof unsay; nextId: typeof nextId;
56
81
  };
package/thread.d.ts CHANGED
@@ -10,7 +10,7 @@ export function agentName(id?: string | null): string;
10
10
  /** The agent mark: twelve rays drawn with a stroke, in viewBox AI_BOX. */
11
11
  export const AI_BOX: string;
12
12
  export const AI_RAYS: string;
13
- /** Whose agent a thread is for: the email in 'agent:<email>', else null */
13
+ /** Whose agent a thread is for: the email in 'agent:<email>' (legacy, before one agent in 0.1.15), else null */
14
14
  export function agentOwner(assignee?: string | null): string | null;
15
15
  /** Given to an agent: the shared queue ('claude') or a person's own ('agent:<email>') */
16
16
  export function toAgent(assignee?: string | null): boolean;
@@ -32,8 +32,8 @@ export function workingOn(c: { working?: Working | null; status?: string } | nul
32
32
  export function isGuest(email?: string | null): boolean;
33
33
  /** A guest's thread the studio has not approved yet: no agent takes it */
34
34
  export function held(c: { by?: string | null; approvedBy?: string | null }): boolean;
35
- /** The agents a message can @mention: the shared queue, and each person's own */
36
- export function agentHandles(people?: { email: string; name?: string | null; agent_name?: string | null }[]): { assignee: string; handle: string; owner: string | null }[];
35
+ /** The agent a message can @mention: one, Claude */
36
+ export function agentHandles(): { assignee: string; handle: string; owner: string | null }[];
37
37
  /** The agent a text hands its thread to: the last one it @mentions, else null */
38
38
  export function agentMentioned(text: string, people?: { email: string; name?: string | null; agent_name?: string | null }[]): string | null;
39
39
  export type AgentStep = "held" | "queued" | "asks" | "working" | "stuck" | "review" | "done";
@@ -53,3 +53,12 @@ export const DOCS: { pdf: string; doc: string; docx: string };
53
53
  export function docSlug(name: string): string;
54
54
  /** What to call a document — "brief.pdf" — by its path or data: URL; null when it is not one */
55
55
  export function docOf(path: string): string | null;
56
+ /** The element's frames a thread keeps above its conversation */
57
+ export const FRAMES: ('before' | 'after')[];
58
+ /** Which frame a filed path is — before-… or after-… — else null */
59
+ export function frameOf(path: string): 'before' | 'after' | null;
60
+ /** A thread's latest frame of each kind */
61
+ export function framesOf(c: { images?: string[] } | null | undefined): { before?: string; after?: string };
62
+ export type ThreadMessage = { author: string; text: string; at?: string | null; by?: string; byName?: string; agent?: string; deleted?: boolean; images: string[] };
63
+ /** The comment, the note and the replies in order, each with the screenshots sent with it; deleted replies left out */
64
+ export function threadOf(c: { text: string; createdAt?: string; by?: string; byName?: string; note?: string; updatedAt?: string | null; replies?: Record<string, any>[]; images?: string[] }): ThreadMessage[];