@aiquants/daily-report 0.30.0 → 0.32.0
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/CHANGELOG.md +129 -0
- package/README.md +162 -95
- package/dist/client.d.mts +49 -18
- package/dist/client.d.ts +49 -18
- package/dist/client.js +4 -4
- package/dist/client.mjs +4 -4
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/server.d.mts +40 -22
- package/dist/server.d.ts +40 -22
- package/dist/server.js +4 -4
- package/dist/server.mjs +4 -4
- package/dist/styles/daily-report.standalone.css +1 -1
- package/package.json +5 -5
package/dist/server.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var Bt=Object.defineProperty;var Ea=Object.getOwnPropertyDescriptor;var Ia=Object.getOwnPropertyNames;var xa=Object.prototype.hasOwnProperty;var mr=e=>{throw TypeError(e)};var Ca=(e,t)=>{for(var r in t)Bt(e,r,{get:t[r],enumerable:!0})},Ma=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ia(t))!xa.call(e,a)&&a!==r&&Bt(e,a,{get:()=>t[a],enumerable:!(n=Ea(t,a))||n.enumerable});return e};var va=e=>Ma(Bt({},"__esModule",{value:!0}),e);var pr=(e,t,r)=>t.has(e)||mr("Cannot "+r);var Ke=(e,t,r)=>(pr(e,t,"read from private field"),r?r.call(e):t.get(e)),Ut=(e,t,r)=>t.has(e)?mr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Ht=(e,t,r,n)=>(pr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var vi={};Ca(vi,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>At,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>St,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>sr,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>at,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>lr,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>Mt,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>ir,DailyReportSseReader:()=>je,DailyReportViewerScope:()=>pe,SqlResultCache:()=>He,createDailyReportHandlers:()=>vt,createDailyReportServer:()=>Mi,createDailyReportService:()=>Pt,createEpochStore:()=>ut,createSharpThumbnailRenderer:()=>ma,defineDailyReportSchema:()=>Xn,generateETag:()=>Ve,isStreamIdLte:()=>we,jsonResponseWithETag:()=>ce,predictSharpThumbnailWorkingSetBytes:()=>da,transformJsonArray:()=>Kn});module.exports=va(vi);var ee=()=>Math.floor(performance.now());var ut=e=>({async getEpoch(t){try{let r=await e?.getClient();if(!r)return null;let n=await r.get(t);return n?Number(n):0}catch{return null}},async incrementEpoch(t){try{let r=await e?.getClient();if(!r)return;await r.incr(t)}catch{}}}),He=class{constructor(t,r){this.config=t;this.epochStore=r;this.buckets=new Map;this.inFlight=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,a=this.buckets.get(n);if(!a)return;let o=t.ttlMsOverride??this.config.defaultTtlMs;if(o-(a.expireAt-ee())<o*r||this.inFlight.has(n))return;let i;i=(async()=>{let R=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=await t.fetcher();return this.inFlight.get(n)===i&&this.buckets.set(n,{records:s,expireAt:ee()+o,epoch:R}),s})(),this.inFlight.set(n,i),i.catch(()=>{}).finally(()=>{this.inFlight.get(n)===i&&this.inFlight.delete(n)})};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:a}=t,o=this.buckets.get(r);if(n&&(this.buckets.delete(r),this.inFlight.delete(r)),!n&&o&&o.expireAt>ee())if(t.epochKey){let i=await this.epochStore.getEpoch(t.epochKey);if(i===null||o.epoch===i)return this.maybeRefreshAhead(t),a?o.records.map(R=>structuredClone(R)):o.records;this.buckets.delete(r)}else return this.maybeRefreshAhead(t),a?o.records.map(i=>structuredClone(i)):o.records;if(!n&&this.inFlight.has(r)){let i=await this.inFlight.get(r);return a?i.map(R=>structuredClone(R)):i}let l;l=(async()=>{let i=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null;t.onFetchStart?.();let R=await t.fetcher();if(n||this.inFlight.get(r)===l){let s=ee()+(t.ttlMsOverride??this.config.defaultTtlMs);this.buckets.set(r,{records:R,expireAt:s,epoch:i}),this.buckets.size>500&&this.cleanExpired()}return R})(),n||this.inFlight.set(r,l);try{let i=await l;return a?i.map(R=>structuredClone(R)):i}finally{this.inFlight.get(r)===l&&this.inFlight.delete(r)}};this.clearAll=()=>{this.buckets.clear(),this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.buckets.delete(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)}}cleanExpired(){let t=ee();for(let[r,n]of this.buckets.entries())n.expireAt<=t&&this.buckets.delete(r)}};var Pa=/^\d{4}-\d{2}-\d{2}$/,ka=/^\d{4}\/\d{2}\/\d{2}$/,yr=e=>e<10?`0${e}`:`${e}`,hr=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=yr(e.getMonth()+1),n=yr(e.getDate());return`${t}-${r}-${n}`};var ie=e=>{if(e==null)return null;if(e instanceof Date)return hr(e);let t=e.trim();if(t==="")return null;if(Pa.test(t))return t;if(ka.test(t))return t.replaceAll("/","-");let r=new Date(t);return hr(r)};var ct="ids-stream";var $t=e=>{let t=2166136261,r=-624069552;for(let n of e){let a=n.reportHubId;t^=a&255,t=Math.imul(t,16777619),t^=a>>>8&255,t=Math.imul(t,16777619),t^=a>>>16&255,t=Math.imul(t,16777619),t^=a>>>24&255,t=Math.imul(t,16777619),r^=a>>>24&255,r=Math.imul(r,16777619),r^=a>>>16&255,r=Math.imul(r,16777619),r^=a>>>8&255,r=Math.imul(r,16777619),r^=a&255,r=Math.imul(r,16777619);let o=n.businessDate;if(o===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let l=0;l<o.length;l++){let i=o.charCodeAt(l);t^=i&255,t=Math.imul(t,16777619),r^=i&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},dt=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,fr=e=>{for(let t=1;t<e.length;t++)if(dt(e[t-1],e[t])>0)return!1;return!0};var Rr=(e,t)=>{let r=e.findIndex(n=>dt({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var ue=(e,t,r=console)=>{let n=a=>typeof a=="string"?[`${t} ${a}`]:[t,a];return{debug:(a,...o)=>{e<=0&&r.debug(...n(a),...o)},info:(a,...o)=>{e<=1&&r.info(...n(a),...o)},warn:(a,...o)=>{e<=2&&r.warn(...n(a),...o)},error:(a,...o)=>{e<=3&&r.error(...n(a),...o)}}};var Ft=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),gr=e=>Object.hasOwn(Ft,e);var La="download",Na="thumbnail",Oa="1";var qt=e=>{let t=e.getAll(Na),r=e.getAll(La);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&gr(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Oa?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var he=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var mt=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,a=new Map,o=l=>{let i={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(s=>[s,0]))};a.set(l,i),he(()=>{a.delete(l),i.count>0&&n(l,i)},t)};return{record:(l,i,R)=>{let s=a.get(l);if(s!==void 0){s.count+=1,s.tallies[i]+=1;return}R(),o(l)}}};var Yt="Cross-site request rejected",Ba="Not Found",Ua=new Set(["same-origin","none"]),Ha=new Set(["GET","HEAD","OPTIONS"]),Sr=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}}),$a=()=>Sr(403,Yt),pt=()=>Sr(404,Ba),$e=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:$a}),Ar=e=>new URL(e.url).pathname.endsWith(".data"),Fa=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},Tr=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(Ha.has(e.method)||Fa(e)):Ua.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},br=["api","action","sse","attachment"],qa=6e4,Va="refusals",Ya=32,za=/^[a-z-]+$/,Vt=e=>{if(e===null)return"-";let t=e.slice(0,Ya);return za.test(t)&&t===e?e:JSON.stringify(t)},Dr=e=>{let t=mt({windowMs:qa,tallies:br,writeSuppressed:(r,{count:n,since:a,tallies:o})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${a} routes=${br.map(l=>`${l}:${o[l]}`).join(",")}`)}});return(r,n)=>{let a=()=>{let{headers:o}=n;e.warn(`cross_site_rejected route=${r} site=${Vt(o.get("Sec-Fetch-Site"))} mode=${Vt(o.get("Sec-Fetch-Mode"))} dest=${Vt(o.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(Va,r,a)}};var wr=(e,t)=>(r,n)=>{let a=n?"markAttachmentPresent":"markAttachmentMissing";e[a](r).catch(o=>{t.error(`${a} failed attachment=${r} message=${o instanceof Error?o.message:"unknown"}`)})};var ja=6e4/1e3,Wa=5e3/1e3,Ja=new Map([[429,ja],[503,Wa]]),xe=e=>{let t=Ja.get(e);return t===void 0?{}:{"Retry-After":String(t)}},Er="Too many requests",Ga="same-origin",Ka="SAMEORIGIN",Fe=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Ga,"X-Frame-Options":Ka}),yt=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Fe});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Ir=(e,t)=>{if(e===null)return!1;for(let r of e.split(",")){let n=r.trim();if((n.startsWith("W/")?n.slice(2):n)===t)return!0}return!1},xr=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Xa=/^[\x20-\x7E]+$/,Qa=/^[\w.+-]+\/[\w.+-]+/,zt=e=>e&&Xa.test(e)&&Qa.test(e)?e:null,Cr=e=>encodeURIComponent(e).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Mr=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),ht={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},vr={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},ft=e=>typeof e=="string"&&Object.hasOwn(vr,e),Rt=e=>vr[e],Ce="Attachment request failed";var Za=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,qe=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Za(r)}`),gt=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`);var Pr=32*1024*1024,eo=60,to=4,ro=120,no=2,ao=8*1024*1024,ye=(e,t,r)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r)return t;throw qe(e,`an integer >= ${r}`,t)},Me=(e,t,r,n)=>t===void 0?n:ye(e,t,r),oo=[["attachmentThumbnailRenderer",["readAttachment","attachmentIdCodec"]],["readAttachment",["attachmentIdCodec"]],["attachmentIdCodec",["readAttachment"]],["attachmentMaxBytes",["readAttachment"]],["attachmentRateLimitPerMinute",["readAttachment"]],["attachmentConcurrency",["readAttachment"]],["attachmentThumbnailRateLimitPerMinute",["attachmentThumbnailRenderer"]],["attachmentThumbnailConcurrency",["attachmentThumbnailRenderer"]],["attachmentThumbnailCacheBytes",["attachmentThumbnailRenderer"]]],jt=e=>{for(let[t,r]of oo){if(e[t]===void 0)continue;let n=r.find(a=>e[a]===void 0);if(n!==void 0)throw gt(n,`injected when ${t} is given`)}},kr=(e,t)=>(jt({attachmentIdCodec:t.idCodec,readAttachment:t.readAttachment,attachmentThumbnailRenderer:t.thumbnailRenderer,attachmentRateLimitPerMinute:e.attachmentRateLimitPerMinute,attachmentConcurrency:e.attachmentConcurrency,attachmentThumbnailRateLimitPerMinute:e.attachmentThumbnailRateLimitPerMinute,attachmentThumbnailConcurrency:e.attachmentThumbnailConcurrency,attachmentThumbnailCacheBytes:e.attachmentThumbnailCacheBytes}),Object.freeze({originalRateLimitPerMinute:Me("attachmentRateLimitPerMinute",e.attachmentRateLimitPerMinute,1,eo),originalConcurrency:Me("attachmentConcurrency",e.attachmentConcurrency,1,to),thumbnailRateLimitPerMinute:Me("attachmentThumbnailRateLimitPerMinute",e.attachmentThumbnailRateLimitPerMinute,1,ro),thumbnailConcurrency:Me("attachmentThumbnailConcurrency",e.attachmentThumbnailConcurrency,1,no),thumbnailCacheBytes:Me("attachmentThumbnailCacheBytes",e.attachmentThumbnailCacheBytes,0,ao)}));var bt=e=>{let t=ye("limit",e.limit,1),r=ye("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ye("queue.max",e.queue.max,0),maxPerOwner:ye("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ye("queue.maxWaitMs",e.queue.maxWaitMs,1)},a=0,o=[],l=new Map,i=new Map,R=(m,T)=>m.get(T)??0,s=(m,T,A)=>{let S=R(m,T)+A;S<=0?m.delete(T):m.set(T,S)},_=m=>R(i,m)<r,y=m=>(a+=1,s(i,m,1),h(m)),I=()=>{for(;a<t;){let m=o.findIndex(A=>_(A.owner));if(m<0)return;let[T]=o.splice(m,1);s(l,T.owner,-1),T.grant(y(T.owner))}},h=m=>{let T=!1;return()=>{T||(T=!0,a-=1,s(i,m,-1),I())}};return{acquire:(m,T)=>{if(T.aborted)return Promise.resolve(null);if(a<t&&_(m))return Promise.resolve(y(m));if(n===null||o.length>=n.max||R(l,m)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:A}=n,S=x=>{let H=()=>{let B=o.indexOf(v);B<0||(o.splice(B,1),s(l,m,-1),U(),x(null))},D=he(H,A),U=()=>{clearTimeout(D),T.removeEventListener("abort",H)},v={owner:m,grant:B=>{U(),x(B)}};o.push(v),s(l,m,1),T.addEventListener("abort",H,{once:!0})};return new Promise(S)}}};var io=1024,so=6e4,lo=e=>{ye("limitPerMinute",e,1);let t=new Map,r=(a,o)=>{o<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(o-a.lastRefillMs)*e/6e4),a.lastRefillMs=o)},n=(a,o)=>{let l=t.get(a);l&&t.delete(a);let i=l??{tokens:e,lastRefillMs:o};r(i,o),t.set(a,i);for(let R of t.keys()){if(t.size<=io)break;t.delete(R)}return i};return{consume:(a,o)=>{let l=n(a,o);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,o,l)=>{let i=t.get(a);i&&(r(i,o),i.tokens=Math.min(e,i.tokens+l))}}},Xe=e=>{let{reason:t,logger:r}=e,n=lo(e.limitPerMinute),a=e.variant===null?"":` variant=${e.variant}`,o=mt({windowMs:so,tallies:[t],writeSuppressed:(l,{count:i,since:R})=>{r.warn(`${t}_suppressed count=${i} since=${R} viewer=${l}${a}`)}});return{spend:({attachmentId:l,internalUserId:i,fail:R})=>n.consume(i,ee())?null:(o.record(i,t,()=>r.warn(`429 attachment=${l} viewer=${i}${a} reason=${t}`)),R(429,Er,xe(429))),refund:(l,i)=>{n.refund(l,ee(),i)}}};var uo=256*1024,Lr=6e4,co=e=>Math.ceil(e/2),mo=new Uint8Array(new ArrayBuffer(0)),po=(e,t)=>{let r=e,n=0,a,o=()=>{clearTimeout(a),r=mo,t()},l=i=>{clearTimeout(a),a=he(()=>{i.error(new Error(`attachment body idle for ${Lr} ms`)),o()},Lr)};return new ReadableStream({start(i){l(i)},pull(i){let R=Math.min(n+uo,r.byteLength);if(R>n&&i.enqueue(r.slice(n,R)),n=R,n>=r.byteLength){i.close(),o();return}l(i)},cancel(){o()}},{highWaterMark:0})},Nr=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:a,recordObjectState:o}=e,l=t.attachmentDelivery,i=Xe({reason:"rate_limit",limitPerMinute:e.rateLimitPerMinute,logger:a,variant:null}),R=bt({limit:e.concurrency,maxHeldPerOwner:co(e.concurrency),queue:null});return async s=>{let{request:_,delivery:y,attachmentId:I,internalUserId:h,readAttachment:m,cookie:T,fail:A}=s,S=l.maxBytes,x=i.spend(s);if(x)return x;let H=await n(_),D=await t.getAttachmentForUser(H,I,h);if(!D)return a.warn(`404 attachment=${I} viewer=${h} reason=not_visible`),A(404,"Attachment not found");if(D.fileSize!=null&&D.fileSize>S)return a.warn(`413 attachment=${I} viewer=${h} reason=db_size`),A(413,"Attachment too large");let U=await R.acquire(h,_.signal);if(!U)return _.signal.aborted?(a.info(`503 attachment=${I} viewer=${h} reason=aborted`),A(503,"Attachment request aborted")):(a.warn(`503 attachment=${I} viewer=${h} reason=concurrency`),A(503,"Too many concurrent downloads",xe(503)));let v=!1;try{let B=_.method==="HEAD",k=await m(D.filePath,{maxBytes:S,head:B,principal:r(h),signal:_.signal});if(_.signal.aborted)return a.info(`503 attachment=${I} viewer=${h} reason=aborted`),A(503,"Attachment request aborted");if(!k.ok){if(!ft(k.reason))return a.error(`500 attachment=${I} viewer=${h} reason=port_contract code=failure_reason`),A(500,Ce);let V=Rt(k.reason);return k.reason==="not_found"&&o(I,!1),a.warn(`${V} attachment=${I} viewer=${h} reason=${k.reason} code=${k.code??"-"}`),A(V,ht[V],xe(V))}if(k.bytes.byteLength>S)return a.error(`500 attachment=${I} viewer=${h} reason=port_contract code=over_max_bytes`),A(500,Ce);let F=zt(D.fileType)??zt(k.contentType),C=F!==null&&xr.has(F),P=C?F:"application/octet-stream",$=C&&y.kind!=="download"?"inline":"attachment",M=k.size??k.bytes.byteLength,L=new Headers({"Content-Type":P,"Content-Length":String(M),"Content-Disposition":`${$}; filename="${Mr(D.fileName)}"; filename*=UTF-8''${Cr(D.fileName)}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Fe});return T&&L.append("Set-Cookie",T),o(I,!0),a.info(`200 attachment=${I} viewer=${h} type=${P} disposition=${$} bytes=${M}`),B?new Response(null,{status:200,headers:L}):(v=!0,new Response(po(k.bytes,U),{status:200,headers:L}))}finally{v||U()}}};var me=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Rs=me.queueWaitMs+me.readMs+me.renderMs+me.transferMarginMs;var Or=require("crypto"),Ve=e=>{let t=JSON.stringify(e);return`"${(0,Or.createHash)("sha256").update(t).digest("hex")}"`};var Hr=require("buffer"),$r=new Set([194,198,202,206]),yo=new Set([192,193,194,195]),Fr=216,ho=217,qr=218,fo=4,Ro=64,go=2,Br=8,Ur=28,De=12,Wt=8,bo=20,Vr=De+Wt+10,So=2,Se=(e,t)=>e[t]<<8|e[t+1],Ye=(e,t,r)=>{let n=0;for(let a=r-1;a>=0;a-=1)n=n*256+e[t+a];return n},fe=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},Yr=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,zr=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),jr=e=>(e.stepsLeft-=1,e.stepsLeft>=0),Wr=e=>e[0]===255&&e[1]===Fr,Jr=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!jr(r))return null;n+=1}while(n<e.byteLength&&e[n]===255);if(n>=e.byteLength)return null;let a=e[n];if(n+=1,a===ho)return"eoi";if(a===0||a===Fr)return null;if(a===1||a>=208&&a<=215)continue;if(n+2>e.byteLength)return null;let o=Se(e,n),l=n+o;return o<2||l>e.byteLength?null:(r.marker=a,r.body=n+2,r.length=o,r.end=l,"segment")}},Ao=(e,t,r)=>{let n=e.byteLength,a=t;for(;;){let o=e.indexOf(255,a);if(o<0)return n;for(;;){if(!jr(r))return null;if(o+1>=n)return n;let l=e[o+1];if(l===255)o+=1;else if(l===0||l>=208&&l<=215){if(o+=2,o>=n||e[o]!==255)break}else return o}a=o}},Gr=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let a=Se(e,r+1),o=Se(e,r+3),l=e[r+5];if(o===0||a===0||l===0||n!==8+3*l)return null;let i=[];for(let R=0;R<l;R+=1){let s=e[r+7+3*R],_=s>>4,y=s&15;if(_<1||_>4||y<1||y>4)return null;i.push({id:e[r+6+3*R],horizontal:_,vertical:y})}return{marker:t,width:o,height:a,components:i}},Kr=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>fo||r!==6+2*n?null:Array.from({length:n},(a,o)=>e[t+1+2*o])},Xr=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:$r.has(e.marker)||t<e.components.length}),Jt=e=>{if(!Wr(e))return null;let t=zr(e.byteLength),r=null;for(let n=2;;){if(Jr(e,n,t)!=="segment")return null;if(Yr(t.marker)){if(r!==null||(r=Gr(e,t),r===null))return null}else if(t.marker===qr){if(r===null)return null;let a=Kr(e,t);return a===null?null:Xr(r,a.length)}n=t.end}},Qr=e=>{let t=Math.max(...e.components.map(n=>n.horizontal)),r=Math.max(...e.components.map(n=>n.vertical));return e.components.map(({horizontal:n,vertical:a})=>{let o=Math.ceil(e.width*n/(t*Br)),l=Math.ceil(e.height*a/(r*Br));return Math.ceil(o/n)*n*Math.ceil(l/a)*a})},Zr=e=>e.multiScan?Qr(e).reduce((r,n)=>r+n,0)*Ro*go:0,To=896,en=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!Wr(e))return null;let n=Hr.Buffer.from(e.buffer,e.byteOffset,e.byteLength),a=zr(r),o=null,l=null,i=new Map,R=0,s=0,_=0;for(let y=2;;){let I=Jr(e,y,a);if(I===null)return null;if(I==="eoi")return l===null?null:{header:l,blockVisits:s};if(y=a.end,Yr(a.marker)){if(o!==null||!yo.has(a.marker)||(o=Gr(e,a),o===null))return null;let h=Qr(o);i=new Map;for(let[m,T]of o.components.entries()){let A=i.get(T.id);i.set(T.id,A===void 0?h[m]:Math.max(A,h[m]))}R=o.components.length*($r.has(o.marker)?To:1)}else if(a.marker===qr){if(o===null||_===R)return null;let h=Kr(e,a);if(h===null)return null;for(let T of h){let A=i.get(T);if(A===void 0)return null;s+=A}if(_+=1,l===null&&(l=Xr(o,h.length)),s>t||!l.multiScan)return{header:l,blockVisits:s};let m=Ao(n,a.end,a);if(m===null)return null;y=m}}},tn=e=>{if(e.byteLength<24||Se(e,8)!==0||Se(e,10)!==13||!fe(e,12,"IHDR"))return null;let t=Se(e,16)*65536+Se(e,18),r=Se(e,20)*65536+Se(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Do=e=>{if(fe(e,De,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Ye(e,26,2)&16383,r=Ye(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(fe(e,De,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Ye(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return fe(e,De,"VP8X")?e.byteLength<Vr?null:{width:Ye(e,24,3)+1,height:Ye(e,27,3)+1}:null},rn=e=>{if(tn(e)===null||e.byteLength<=Ur)return null;switch(e[Ur]){case 0:return!1;case 1:return!0;default:return null}},nn=(e,t)=>{if(fe(e,De,"VP8 "))return"lossy";if(fe(e,De,"VP8L"))return"lossless";if(!fe(e,De,"VP8X")||e.byteLength<Vr)return null;if((e[bo]&So)!==0)return"animated";let r=!1,n=t;for(let a=De;a+Wt<=e.byteLength;){if(n-=1,n<0)return null;if(fe(e,a,"VP8L"))return"lossless";if(fe(e,a,"VP8 "))return r?"lossy-alpha":"lossy";fe(e,a,"ALPH")&&(r=!0);let o=Ye(e,a+4,4);a+=Wt+o+o%2}return null},an={png:tn,jpeg:Jt,webp:Do};var St=Object.freeze(["image/webp","image/jpeg","image/png"]),At=1024*1024;var wo=new Set(["image/png","image/jpeg","image/gif","image/webp"]),_o={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Eo=new Set(St),Io=e=>typeof e=="string"&&Eo.has(e),xo=256,Tt=(e,t)=>e.fileType===null||!wo.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Co=[137,80,78,71,13,10,26,10],Mo=[255,216,255],vo=[[71,73,70,56,55,97],[71,73,70,56,57,97]],Po=[82,73,70,70],ko=[87,69,66,80],Qe=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,a]of t.entries())if(e[r+n]!==a)return!1;return!0},Gt=e=>{if(Qe(e,Co,0))return"png";if(Qe(e,Mo,0))return"jpeg";for(let t of vo)if(Qe(e,t,0))return"gif";return Qe(e,Po,0)&&Qe(e,ko,8)?"webp":null},on=e=>{let t=JSON.stringify([e.rendererId,e.box.maxWidth,e.box.maxHeight,e.attachmentId,e.filePath,e.fileType,e.fileSize]);return{key:t,etag:Ve([t])}},sn=(e,t)=>{if(!Io(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>At)return"too_large";let r=_o[e.contentType];if(Gt(e.bytes)!==r)return"signature";let n=an[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},ln=e=>{ye("maxBytes",e.maxBytes,0),ye("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=a=>{let o=t.get(a);o&&(t.delete(a),r-=o.weight)};return{get:a=>{let o=t.get(a);if(o)return t.delete(a),t.set(a,o),o.entry},set:(a,o)=>{n(a);let l=(o.kind==="thumbnail"?o.bytes.byteLength:0)+xo;if(l>e.maxBytes||e.maxEntries===0)return;let i=o.kind==="thumbnail"?{kind:"thumbnail",bytes:o.bytes.slice(),contentType:o.contentType}:o;t.set(a,{entry:i,weight:l}),r+=l;for(let R of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(R)}}}};var un=()=>{let e=new Map;return{join:(t,r,n)=>{let a=()=>{let R=new AbortController,s=()=>{e.get(t)?.controller===R&&e.delete(t)},y={promise:n(R.signal).finally(s),controller:R,waiters:0};return e.set(t,y),y},o=e.get(t)??a();o.waiters+=1;let l=()=>{o.waiters-=1,!(o.waiters>0)&&(o.controller.abort(),e.get(t)===o&&e.delete(t))};r.aborted?l():r.addEventListener("abort",l,{once:!0});let i=()=>{r.removeEventListener("abort",l)};return o.promise.finally(i)}}};var Kt=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:a,onStuck:o}=e,l=ee(),i=new AbortController,R=!1,s,_,y=()=>{o(ee()-l)},I=D=>{s=he(()=>{R=!0,D({timedOut:!0}),_=he(y,t),i.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},h=new Promise(I),m=AbortSignal.any([r,i.signal]),T=D=>{D(n(m))},A=new Promise(T),S=D=>(clearTimeout(s),clearTimeout(_),R&&a(ee()-l,D.kind==="error"?{error:D.error}:null),D),x=A.then(D=>S({kind:"value",value:D}),D=>S({kind:"error",error:D}));return{outcome:Promise.race([A.then(D=>({timedOut:!1,value:D})),h]),settled:x}};var ve={404:"Attachment not found",500:Ce,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},cn=(e,t)=>{if(typeof e!="object"||e===null)return{failure:{kind:"failure",status:500,reason:"port_contract",code:"result"}};let r=e;if(!r.ok)return r.reason==="unsupported"?{entry:{kind:"unrenderable",reason:"unsupported"}}:r.reason==="failed"?{failure:{kind:"failure",status:502,reason:"render_failed"}}:{failure:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"}};let n=sn(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Lo=e=>{let t=new AbortController,r=()=>{t.abort()},n=he(r,me.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},dn=()=>{},No=(e,t)=>t.aborted?Promise.resolve():new Promise(r=>{let n=()=>{t.removeEventListener("abort",n),r()};t.addEventListener("abort",n,{once:!0}),e.then(n)}),mn=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:a,recordObjectState:o,logger:l}=e,i=new Map,R=(h,m)=>{let T=m.then(dn,dn);i.set(h,T);let A=()=>{i.get(h)===T&&i.delete(h)};T.then(A)},s=async(h,m)=>{let T=i.get(h.key);if(T===void 0)return t.acquire(h.owner,m);let A=Lo(m);try{if(await No(T,A.signal),A.signal.aborted)return null;let S=r.get(h.key);return S!==void 0?{...S,identity:"verified"}:await t.acquire(h.owner,A.signal)}finally{A.end()}},_=(h,m)=>{if(h.fileSize===null)return m.kind==="exact"?"verified":"unrecorded";if(m.kind==="exact"?m.bytes===h.fileSize:h.fileSize>m.maxBytes)return"verified";let A=m.kind==="exact"?String(m.bytes):`>${m.maxBytes}`;return l.warn(`size_mismatch expected=${h.fileSize} got=${A} attachment=${h.attachmentId} viewer=${h.owner} variant=thumbnail`),"unverified"},y=(h,m)=>(T,A)=>{let S=A===null?"":` message=${A.error instanceof Error?A.error.message:"unknown"}`;l.warn(`${h}_overrun ms=${T} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail${S}`)},I=(h,m)=>T=>{l.warn(`${h}_stuck ms=${T} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`)};return async(h,m)=>{let T=await s(h,m);if(T===null)return{kind:"failure",status:503,reason:m.aborted?"aborted":"queue"};if(typeof T!="function")return T;let A=T,S=null;try{if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let x=r.get(h.key);if(x!==void 0)return{...x,identity:"verified"};let H=Kt({budgetMs:me.readMs,flightSignal:m,call:Y=>h.readAttachment(h.filePath,{maxBytes:n,head:!1,principal:a(h.owner),signal:Y}),onOverrun:y("read",h),onStuck:I("read",h)}),D=await H.outcome;if(D.timedOut)return S=H.settled,m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let U=D.value;if(!U.ok&&U.reason!=="too_large")return ft(U.reason)?(U.reason==="not_found"&&o(h.attachmentId,!1),{kind:"failure",status:Rt(U.reason),reason:U.reason,code:U.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(U.ok&&U.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let v=_(h,U.ok?{kind:"exact",bytes:U.bytes.byteLength}:{kind:"over",maxBytes:n}),B=Y=>{v==="verified"&&r.set(h.key,Y)},k=Y=>(B(Y),{...Y,identity:v});if(!U.ok)return k({kind:"unrenderable",reason:"too_large"});let F=Gt(U.bytes);if(F===null)return k({kind:"unrenderable",reason:"signature"});let C=Kt({budgetMs:me.renderMs,flightSignal:m,call:Y=>h.renderer.render(U.bytes,{format:F,maxWidth:h.box.maxWidth,maxHeight:h.box.maxHeight,signal:Y}),onOverrun:y("render",h),onStuck:I("render",h)}),P=Y=>{if(Y.kind==="error")return;let te=cn(Y.value,h.box);"entry"in te&&B(te.entry)},$=null,M=()=>($===null&&($=C.settled.then(P),R(h.key,$)),$);m.addEventListener("abort",M,{once:!0});let L=await C.outcome.finally(()=>m.removeEventListener("abort",M));if(L.timedOut||m.aborted)return S=M(),m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let V=cn(L.value,h.box);return"entry"in V?k(V.entry):V.failure}finally{S===null?A():S.then(A,A)}}};var hn=10,Oo=1/hn,pn=1-Oo,Bo=1024,Uo=64,Ho=8,yn="private, no-cache",$o="no-store",Fo=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),qo=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},fn=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:a,recordObjectState:o}=e,l=t.attachmentDelivery,i=Xe({reason:"rate_limit",limitPerMinute:e.rateLimitPerMinute,logger:a,variant:"thumbnail"}),R=Xe({reason:"revalidation_rate_limit",limitPerMinute:e.rateLimitPerMinute*hn,logger:a,variant:"thumbnail"}),s=bt({limit:e.concurrency,maxHeldPerOwner:e.concurrency,queue:{max:Uo,maxPerOwner:Ho,maxWaitMs:me.queueWaitMs}}),_=ln({maxBytes:e.cacheBytes,maxEntries:Bo}),y=un(),I=mn({gate:s,cache:_,maxBytes:l.maxBytes,encodeUserId:r,recordObjectState:o,logger:a}),h=(A,S,x,H)=>{let D=`attachment=${A.attachmentId} viewer=${A.internalUserId} variant=thumbnail cache=${H}`;if(S.kind==="failure")return a[qo(S)](`${S.status} ${D} reason=${S.reason} code=${S.code??"-"}`),A.fail(S.status,ve[S.status],xe(S.status));let U=Fo[S.identity];if(S.kind==="unrenderable")return a.info(`404 ${D} reason=${S.reason}${U}`),A.fail(404,ve[404]);let v=S.identity==="verified"?{"Cache-Control":yn,ETag:x}:{"Cache-Control":$o},B=new Headers({"Content-Type":S.contentType,"Content-Length":String(S.bytes.byteLength),...v,"Content-Security-Policy":"default-src 'none'; sandbox",...Fe});return A.cookie&&B.append("Set-Cookie",A.cookie),a.info(`200 ${D} type=${S.contentType} bytes=${S.bytes.byteLength}${U}`),new Response(S.bytes,{status:200,headers:B})},m=A=>i.spend(A),T=(A,S)=>S?R.spend(A):m(A);return async(A,S)=>{let{request:x,attachmentId:H,internalUserId:D,readAttachment:U,cookie:v,fail:B}=A,k=Ft[S],F=l.thumbnailRenderer;if(!F)return B(404,ve[404]);let C=x.headers.get("If-None-Match"),P=C!==null,$=T(A,P);if($)return $;let M=await n(x),L=await t.getAttachmentForUser(M,H,D),Y=L!==null&&Tt(L,l.maxBytes)?on({rendererId:F.id,box:k,attachmentId:H,filePath:L.filePath,fileType:L.fileType,fileSize:L.fileSize}):null;if(Y&&Ir(C,Y.etag)){let re=new Headers({"Cache-Control":yn,ETag:Y.etag,...Fe});return v&&re.append("Set-Cookie",v),a.info(`304 attachment=${H} viewer=${D} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:re})}if(P){let re=m(A);if(re)return re}if(!L)return a.warn(`404 attachment=${H} viewer=${D} variant=thumbnail reason=not_visible`),B(404,ve[404]);if(!Y)return i.refund(D,pn),a.info(`404 attachment=${H} viewer=${D} variant=thumbnail reason=not_eligible`),B(404,ve[404]);let{key:te,etag:G}=Y,de=_.get(te);if(de)return i.refund(D,pn),h(A,{...de,identity:"verified"},G,"hit");let Ee=re=>I({key:te,attachmentId:H,filePath:L.filePath,fileSize:L.fileSize,box:k,owner:D,readAttachment:U,renderer:F},re),Q;try{Q=await y.join(te,x.signal,Ee)}catch(re){return a.error(`500 attachment=${H} viewer=${D} variant=thumbnail cache=miss reason=port_exception message=${re instanceof Error?re.message:"unknown"}`),B(500,ve[500])}return h(A,Q,G,"miss")}};var Vo='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Yo=()=>yt(403,Yt,{cookie:null}),Rn=Object.freeze({navigable:e=>{let{kind:t}=qt(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>yt(404,ht[404],{cookie:null}),crossSiteRejection:Yo}),gn=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:a,logger:o}=e,l=r.attachmentDelivery,i=kr(e.tuning,l),R={service:r,encodeUserId:n,resolveViewerScope:a,logger:o,recordObjectState:wr(r,o)},s=Nr({...R,rateLimitPerMinute:i.originalRateLimitPerMinute,concurrency:i.originalConcurrency}),_=fn({...R,rateLimitPerMinute:i.thumbnailRateLimitPerMinute,concurrency:i.thumbnailConcurrency,cacheBytes:i.thumbnailCacheBytes});return async({request:y,params:I})=>{let h=null,m=(T,A,S={})=>yt(T,A,{cookie:h,extraHeaders:S});try{let{user:T,cookie:A}=await t(y,{failureRedirect:null});if(h=A??null,!T)return m(401,"Unauthorized");let S=qt(new URL(y.url).searchParams);if(S.kind==="invalid")return m(400,"Invalid attachment request");if(S.kind==="thumbnail"&&y.method!=="GET")return m(405,"Method not allowed",{Allow:"GET"});if(y.method!=="GET"&&y.method!=="HEAD")return m(405,"Method not allowed",{Allow:"GET, HEAD"});let{idCodec:x,readAttachment:H}=l;if(!(x&&H))return m(404,"Attachment not found");if(I.token===void 0)throw new Error(Vo);let D=x.decode(I.token);if(D===null||!Number.isSafeInteger(D)||D<=0)return m(400,"Invalid attachment token");let U=await r.getUserIdByExternalId(T.id);if(!U)return m(403,"Forbidden");let v={request:y,delivery:S,attachmentId:D,internalUserId:U,readAttachment:H,cookie:h,fail:m};return S.kind==="thumbnail"?await _(v,S.variant):await s(v)}catch(T){if(T instanceof Response)throw T;return o.error(`500 attachment=? viewer=? reason=unexpected message=${T instanceof Error?T.message:"unknown"}`),m(500,Ce)}}};var zo=ue(1,"[Response]"),ce=(e,t,r,n=200,a=zo)=>{let o=Ve(r),l=e.headers.get("If-None-Match");a.info(`[jsonResponseWithETag] ETag: ${o}, If-None-Match: ${l}`);let i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'",ETag:o});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&l===o?new Response(null,{status:304,headers:i}):new Response(JSON.stringify(r),{status:n,headers:i})};var wt=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,bn=Object.freeze(["GET","HEAD"]);var _t=30,Dn=4e3,jo="stream interrupted by server error",Wo=/^\d{4}-\d{2}-\d{2}$/,Jo=15e3,wn=Symbol("ids-stream-heartbeat"),Sn=()=>{},Et=e=>e.return(void 0).then(Sn,Sn),Go=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(wn),Jo)}),stop:()=>clearTimeout(e)}},Ko=/^[0-9a-f]{1,16}$/,_n=Object.freeze({...$e,frameworkDataRefusal:({params:e})=>e.endpoint===ct?pt():null}),Xo=e=>{let t=e.searchParams.get("cursor_report_hub_id"),r=e.searchParams.get("cursor_business_date"),n=e.searchParams.get("cursor_snapshot"),a=n!==null&&Ko.test(n)?n:null;if(t===null)return r===null?{cursor:null,snapshot:a}:{invalid:!0};let o=Number.parseInt(t,10);return!Number.isSafeInteger(o)||String(o)!==t||o<=0?{invalid:!0}:r===null?{cursor:{businessDate:null,reportHubId:o},snapshot:a}:Wo.test(r)?{cursor:{businessDate:r,reportHubId:o},snapshot:a}:{invalid:!0}};async function*An(e,t,r,n){let a=t?Rr(e,t):0,o=!0;for(;;){let l=e.slice(a,a+(o?r:Dn));a+=l.length;let i=a>=e.length,R=l[l.length-1];if(yield{kind:"chunk",items:l,nextCursor:i||!R?null:{businessDate:R.businessDate,reportHubId:R.reportHubId},isLast:i,...o?{total:e.length}:{},...o?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...o&&n.restarted?{restarted:!0}:{}},o=!1,i)return}}var En=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform","X-Content-Type-Options":"nosniff"});return e&&t.append("Set-Cookie",e),t},Tn=(e,t,r,n)=>{let a=new TextEncoder,o=!1,l=null,i=new ReadableStream({async pull(R){if(o||r.aborted){await Et(t);try{R.close()}catch{}return}let s=Go();try{l===null&&(l=t.next());let _=await Promise.race([l,s.fired]);if(s.stop(),_===wn){if(o||r.aborted){await Et(t);try{R.close()}catch{}return}R.enqueue(a.encode(`
|
|
2
|
-
`));return}l=null;let{value:
|
|
3
|
-
`))}catch(
|
|
4
|
-
`)),R.close()}catch{}}},cancel(){o=!0,Et(t)}});return new Response(i,{status:200,headers:En(e)})},In=e=>{let{service:t,logger:r}=e;return{methods:bn,handle:async(n,a,o,l,i)=>{let R=Xo(n);if("invalid"in R)return ce(o,a,{error:{message:"Invalid cursor"}},400);let s=wt(o);if(s.aborted)return new Response(null,{status:200,headers:En(a)});let _=n.searchParams.get("forceRefresh")==="true",y=!1,I=null,h=null,m=new Promise((S,x)=>{I=S,h=x});m.catch(()=>{});let T=t.getDailyReportIdsByExternalId(i,l.id,{forceRefresh:_,onFetchStart:R.cursor?void 0:()=>{y=!0,t.readSseStreamAnchor().then(S=>t.getDailyReportIdsFirstPageByExternalId(i,l.id,_t).then(x=>({items:x,streamAnchor:S}))).then(S=>I?.(S),S=>h?.(S))}});if(T.catch(()=>{}),R.cursor){let{items:S,streamAnchor:x}=await T,H=$t(S),D=R.snapshot!==null&&R.snapshot===H;return Tn(a,An(S,D?R.cursor:null,_t,{snapshot:H,restarted:!D,streamAnchor:x}),s,r)}let A=(async function*(){let S=await Promise.race([T.then(D=>({kind:"full",source:D}),D=>({kind:"full-error",error:D})),m.then(D=>({kind:"page",page:D}),()=>({kind:"page-error"}))]),x=null,H=!1;if(S.kind==="full")x=S.source;else if(S.kind==="page"){let{items:D,streamAnchor:U}=S.page;if(D.length<_t){yield{kind:"chunk",items:D,nextCursor:null,isLast:!0,total:D.length,streamAnchor:U};return}yield{kind:"chunk",items:D,nextCursor:null,isLast:!1,provisional:!0},H=!0}else if(S.kind==="full-error"&&y){let D=await m.catch(()=>null);D&&D.items.length>0&&(yield{kind:"chunk",items:D.items,nextCursor:null,isLast:!1,provisional:!0})}x===null&&(x=await T),yield*An(x.items,null,H?Dn:_t,{snapshot:$t(x.items),streamAnchor:x.streamAnchor})})();return Tn(a,A,s,r)}}};var Yn=require("@aiquants/sse"),_e=require("@aiquants/sse/server");var b=require("zod");var xn=15e3,Cn="lastEventId",Qo=/^\d{1,15}-\d{1,15}$/,Mn=e=>Qo.test(e),Zo=b.z.object({name:b.z.string().nullish(),affiliation:b.z.string().nullish()}),ei=b.z.object({name:b.z.string().nullish(),text:b.z.string().nullish(),color:b.z.string().nullish()}),ti=b.z.object({id:b.z.number(),name:b.z.string().nullish(),color:b.z.string().nullish()}),vn=b.z.object({id:b.z.number(),userId:b.z.string().nullish(),userName:b.z.string().nullish(),content:b.z.string().nullish(),createdAt:b.z.string().nullish(),isMine:b.z.boolean()}),ri=b.z.object({id:b.z.string(),fileName:b.z.string(),fileType:b.z.string().nullable(),fileSize:b.z.number().nullable(),createdAt:b.z.string().nullable(),state:b.z.enum(["present","absent","unknown"]),hasThumbnail:b.z.boolean().default(!1)}),Xt=b.z.object({reportHubId:b.z.number(),date:b.z.string().nullish(),createdAt:b.z.string().nullish(),author:b.z.string().nullish(),userId:b.z.string().nullish(),sourceType:b.z.string().nullish(),employeeName:b.z.string().nullish(),updatedBy:b.z.string().nullish(),updatedAt:b.z.string().nullish(),category:b.z.string().nullish(),creationCategory:b.z.string().nullish(),visitTimeFrom:b.z.string().nullish(),visitTimeTo:b.z.string().nullish(),customerName:b.z.string().nullish(),interviewers:b.z.array(Zo),subject:b.z.string().nullish(),content:b.z.string().nullish(),externalComments:b.z.array(ei),isRead:b.z.boolean(),isStarred:b.z.boolean(),labels:b.z.array(ti),postedComments:b.z.array(vn),attachments:b.z.array(ri).default([])}),ni=b.z.object({type:b.z.literal("connected")}),It=b.z.object({type:b.z.literal("status-update"),reportHubId:b.z.number(),statusType:b.z.enum(["star","read"]),value:b.z.boolean(),clientTempId:b.z.string(),recipientRawUserId:b.z.number().optional()}),Qt=b.z.string().optional(),Zt=b.z.object({type:b.z.literal("comment-add"),reportHubId:b.z.number(),comment:vn,clientTempId:b.z.string(),recipientRawUserId:b.z.number().optional(),sourceType:Qt}),er=b.z.object({type:b.z.literal("comment-delete"),reportHubId:b.z.number(),commentId:b.z.number(),clientTempId:b.z.string(),recipientRawUserId:b.z.number().optional(),sourceType:Qt}),tr=b.z.object({type:b.z.literal("report-create"),reportHubId:b.z.number(),report:Xt,clientTempId:b.z.string(),recipientRawUserId:b.z.number().optional()}),rr=b.z.object({type:b.z.literal("report-update"),reportHubId:b.z.number(),report:Xt,clientTempId:b.z.string(),recipientRawUserId:b.z.number().optional()}),nr=b.z.object({type:b.z.literal("report-publish"),reportHubId:b.z.number(),report:Xt,clientTempId:b.z.string(),recipientRawUserId:b.z.number().optional()}),ar=b.z.object({type:b.z.literal("report-delete"),reportHubId:b.z.number(),clientTempId:b.z.string(),sourceType:Qt}),Pn=b.z.discriminatedUnion("type",[ni,It,Zt,er,tr,rr,nr,ar]);var Bn=require("@aiquants/sse"),Un=require("@aiquants/sse/shared-source");var Pe="daily-report:ids:",ke="daily-report:business-date:",xt=(e,t)=>`${e}st:${t}`,or=e=>`${Pe}user:${e}:`,kn=(e,t)=>xt(or(e),t),ai=e=>`${ke}${e}:`,Ln=(e,t)=>xt(ai(e),t),Ze=e=>`daily-report:date:${e}:user:`,ze=(e,t)=>`${Ze(e)}${t}:`,Nn=(e,t,r)=>xt(ze(e,t),r),Re=e=>`daily-report:detail:${e}:user:`,Ct=(e,t)=>`${Re(e)}${t}:`,On=(e,t,r)=>xt(Ct(e,t),r);var we=(e,t)=>{let[r,n]=e.split("-").map(Number),[a,o]=t.split("-").map(Number);return r!==a?r<a:n<=o},oi=5e3,ii=100,je=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=t.logger??ue(1,"[SSE Reader]"),this._source=this._createSource()}ready(){return this._position().then(()=>{})}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=null,this._source=this._createSource()}_position(){if(this._lastId!==null)return Promise.resolve(this._lastId);if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{if(t!==this._generation)throw new Error("SSE reader was destroyed while the stream tail was being read");return this._positioning=null,this._lastId=r,r},r=>{throw t===this._generation&&(this._positioning=null),r})}return this._positioning}async _readTail(){let t=await this.config.redis?.getClient();if(!t)throw new Error("Failed to get Redis client to read the SSE stream tail");let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}_createSource(){return(0,Un.createSharedSource)({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:Bn.systemSseRuntime,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this._position(),n=await this.config.redis?.createClient();if(!n)throw new Error("Failed to create Redis client for SSE reader");n.on("error",l=>{this._logger.error("Redis client error:",l)});let a=!1,o=this._readLoop(n,t,r,()=>a);return async()=>{if(a=!0,n.isOpen)try{await n.quit()}catch{}await o}}async _readLoop(t,r,n,a){let o=n;try{for(;!a()&&t.isOpen;){let l=await t.xRead([{key:this.config.streamKey,id:o}],{BLOCK:oi,COUNT:ii});if(l)for(let i of l)for(let R of i.messages)o=R.id,this._invalidateCaches(R.message),r.next({id:R.id,message:R.message})}}catch(l){a()||(this._logger.error("xRead loop error:",l),r.fail(l instanceof Error?l:new Error(String(l))));return}a()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){try{let r=t?.data?JSON.parse(t.data):null,n=r?.type;if((n==="report-create"||n==="report-delete"||n==="report-publish")&&this.config.cache.invalidatePrefix(Pe),n==="comment-add"||n==="comment-delete"||n==="status-update"){let a=r?.reportHubId;typeof a=="number"&&this.config.cache.invalidatePrefix(Re(a))}}catch{}}};var tt=require("drizzle-orm");var si="",li=64,ui=e=>e.toLowerCase(),ci=e=>e.trim().toLowerCase();function Hn(e){if(e==null)return null;if(!Array.isArray(e))return new Set;let t=new Set;for(let r of e){if(typeof r!="string")continue;let n=ci(r);n.length>0&&t.add(n)}return t}function ge(e,t){return e===null?!0:t==null?!1:e.has(ui(t))}function Le(e){return e!==null&&e.size===0}function Fn(e,t){if(t!==null)return t.size===0?tt.sql`1 = 0`:(0,tt.inArray)(tt.sql`LOWER(${e})`,[...t])}var We,Je,et=class et{constructor(t,r){Ut(this,We);Ut(this,Je);Ht(this,We,t),Ht(this,Je,r)}get visible(){return Ke(this,We)===null?null:new Set(Ke(this,We))}get commentable(){return Ke(this,Je)===null?null:new Set(Ke(this,Je))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=Hn(r?t.read:t),a=r?t.comment:void 0;if(a===void 0)return new et(n,n);let o=Hn(a),l=new Set;for(let i of o??[])n.has(i)&&l.add(i);return new et(n,l)}static unrestricted(t){return new et(null,null)}};We=new WeakMap,Je=new WeakMap;var pe=et;function rt(e){let t=$n(e.visible),r=$n(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function $n(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(si);if(t.length<=li)return`s:${t}`;let r=2166136261;for(let n=0;n<t.length;n++)r^=t.charCodeAt(n),r=Math.imul(r,16777619);return`sh:${(r>>>0).toString(16)}`}var zn=Object.freeze({...$e,frameworkDataRefusal:pt}),qn=864e5,di={baseMs:2e3,jitterMs:8e3},ir=6e4,Mt=1e3,jn=JSON.stringify({type:"connected"}),Vn="0-0",mi=(e,t,r,n)=>{if(r===null&&n===null)return!0;let a=typeof t.sourceType=="string"?t.sourceType:void 0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return ge(r,e.report.sourceType);case"comment-add":case"comment-delete":return ge(n,a??"Internal");case"report-delete":return ge(r,a)}},pi=["externalComments","postedComments"],yi=(e,t,r)=>{if(r===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"||ge(r,e.report.sourceType))return!1;let n=t.report;for(let a of pi)n[a]=[];return!0},hi=(e,t)=>{e.writeEvent({event:null,id:t,data:jn})},fi=(e,t,r,n,a)=>{if(r.data)try{let o=JSON.parse(r.data),l=Pn.safeParse(o);if(!l.success){a.error("SSE message validation failed:",l.error.format());return}let i=l.data,R=typeof o.recipientRawUserId=="number"?o.recipientRawUserId:void 0;if((i.type==="status-update"||R!==void 0)&&R!==n.internalUserId||!mi(i,o,n.visibleSet,n.commentableSet)){hi(e,t);return}let _=yi(i,o,n.commentableSet),y;if("recipientRawUserId"in o){let{recipientRawUserId:I,...h}=o;y=JSON.stringify(h)}else _?y=JSON.stringify(o):y=r.data;e.writeEvent({event:null,id:t,data:y})}catch(o){a.error(`[SSE:${n.internalUserId}] processEntry error:`,o)}},Wn=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:a,sseReader:o,streamKey:l,logger:i}=e,R=async(s,_)=>{let{request:y,internalUserId:I,cursor:h}=_,m=_.initialScope.visible,T=_.initialScope.commentable,A=0,S=setInterval(()=>{let P=++A;n(y,"refresh").then($=>{P===A&&(m=$.visible,T=$.commentable)})},ir);s.onClose(()=>clearInterval(S));let x=h===null?Vn:h,H=h!==null&&a!==void 0,D=[],U=null,v=P=>{we(P.id,x)||(x=P.id,fi(s,P.id,P.message,{internalUserId:I,visibleSet:m,commentableSet:T},i))},B=async(P,$)=>{let[M]=await P.xRange(l,"-","+",{COUNT:1});return M!==void 0&&!we(M.id,$)},k=async(P,$)=>{if(await B(P,$))return!1;let M=$;for(;;){let L=await P.xRange(l,M,"+",{COUNT:Mt}),V=L[0];if(V!==void 0&&V.id!==M&&await B(P,M))return!1;for(let te of L){if(U!==null&&we(U,te.id))return!0;v(te)}let Y=L.at(-1);if(L.length<Mt||Y===void 0||s.isClosed())return!0;M=Y.id}},F=o.subscribe(P=>{if(!H){v(P);return}we(P.id,x)||(U===null&&(U=P.id),D.push(P))},P=>{i.error(`[SSE:${I}] Fan-Out reader error:`,P),s.close()});if(s.onClose(F),h===null){await o.ready();try{let P=await a?.getClient();if(P){let $=await P.xRevRange(l,"+","-",{COUNT:1});$.length>0&&!we($[0].id,x)&&(x=$[0].id)}}catch{}}if(s.writeEvent({event:null,id:x===Vn?null:x,data:jn}),(0,_e.startSseHeartbeat)(s,{intervalMs:xn,retry:di,runtime:Yn.systemSseRuntime}),h===null||a===void 0)return;await o.ready();let C=await a.getClient();if(C===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await k(C,h)){s.writeRetry(qn),s.writeEvent({event:"resync-required",id:null,data:""}),s.close();return}H=!1;for(let P of D.splice(0))v(P)};return async({request:s,params:_})=>{let y,I=()=>{let m=new Headers;return y!==void 0&&m.append("Set-Cookie",y),m},h=m=>(0,_e.terminalStreamResponse)(m,{data:"",retryMs:qn,headers:I()});try{let m=await t(s,{failureRedirect:null});y=m.cookie;let{user:T}=m;if(!T)return h("auth-required");let A=await r.getUserIdByExternalId(T.id);if(!A)return h("forbidden");if(_.endpoint!=="updates")return new Response("Not Found",{status:404,headers:I()});let S=(0,_e.readLastEventId)(s,Cn);if(S!==null&&!Mn(S))return i.warn(`[SSE:${A}] malformed resume cursor; asking the client to resync`),h("resync-required");let x=await n(s,"initial");return(0,_e.createSseResponse)({requestSignal:wt(s),headers:I(),onError:(H,D)=>i.error(`[SSE:${A}] ${D} failed:`,H),produce:H=>R(H,{request:s,internalUserId:A,cursor:S,initialScope:x})})}catch(m){if(m instanceof Response)throw m;let T=m instanceof Error?m:new Error(String(m));return i.error(`500 sse name=${T.name} message=${T.message}`),new Response("Internal Server Error",{status:500,headers:I()})}}};var Ri=(e,t)=>{let r=new Headers({"Content-Type":"application/json"});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Jn=Object.freeze(["GET"]),gi=e=>{let[t,r,n]=e.split("-").map(Number),a=new Date(0);return a.setUTCFullYear(t,r-1,n),a.getUTCFullYear()===t&&a.getUTCMonth()===r-1&&a.getUTCDate()===n};function vt(e){let{authenticate:t,service:r,encodeUserId:n,redis:a,sseReader:o,streamKey:l}=e,i=e.loginRedirectPath??"/auth/login",R=e.logger??ue(3,"[DailyReportAPI]"),s=e.logger??ue(3,"[DailyReportVisibility]"),_=e.logger??ue(1,"[DailyReportSSE]"),y=e.logger??ue(1,"[DailyReportAttachment]"),I=e.logger??ue(2,"[DailyReportIsolation]"),h=async(v,B="initial")=>{let k=e.resolveVisibleSourceTypes;if(!k)return pe.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let F=await k(v,{reason:B});return F==null?pe.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):pe.restrictTo(F)}catch(F){return s.error("resolveVisibleSourceTypes threw; failing closed (deny all)",F),pe.restrictTo([])}},m=async({request:v})=>{let{user:B,cookie:k}=await t(v,{failureRedirect:i}),F=new Headers;k&&F.append("Set-Cookie",k);let C=await r.getUserIdByExternalId(B.id),P=C?n(C):null;return{data:{user:B,userId:P},headers:F}},T={"business-date":{methods:Jn,handle:async(v,B,k,F,C)=>{let P=ie(v.searchParams.get("businessDate")),$=v.searchParams.get("forceRefresh")==="true";if(P===null||!gi(P))return ce(k,B,{error:{message:"Invalid business date"}},400);let M=await r.getDailyReportsByBusinessDateByExternalId(C,P,F.id,{forceRefresh:$});return ce(k,B,{businessDate:P,reports:M},200)}},[ct]:In({service:r,logger:R}),report:{methods:Jn,handle:async(v,B,k,F,C)=>{let P=v.searchParams.get("reportHubId"),$=v.searchParams.get("forceRefresh")==="true",M=P?Number.parseInt(P,10):NaN;if(!Number.isFinite(M)||M<=0)return ce(k,B,{error:{message:"Invalid reportHubId"}},400);let L=await r.getDailyReportDetailByIdByExternalId(C,M,F.id,{snapshot:!0,forceRefresh:$});return L?ce(k,B,{report:L},200):ce(k,B,{error:{message:"Report not found"}},404)}}},A=async({request:v,params:B})=>{let{user:k,cookie:F}=await t(v,{failureRedirect:null}),C=F??null;if(!k)return ce(v,C,{error:{message:"Unauthorized"}},401);let P=B.endpoint,$=P!==void 0&&Object.hasOwn(T,P)?T[P]:void 0;if($===void 0)return ce(v,C,{error:{message:"Unknown endpoint"}},404);if(!$.methods.includes(v.method)){let L=ce(v,C,{error:{message:"Method not allowed"}},405);return L.headers.set("Allow",$.methods.join(", ")),L}let M=ee();try{let L=new URL(v.url),V=await h(v);return await $.handle(L,C,v,k,V)}catch(L){let V=ee()-M,Y=L instanceof Error?L:new Error(String(L));return R.error(`500 endpoint=${P} elapsed=${V}ms name=${Y.name} code=${"code"in Y?Y.code:"N/A"} message=${Y.message}`),R.error("Stack:",Y.stack),ce(v,C,{error:{message:"Internal Server Error"}},500)}},S=async({request:v,params:B})=>{let{user:k,cookie:F}=await t(v,{failureRedirect:null}),C=($,M)=>Ri($,{...M,setCookie:F});if(!k)return C({error:"Unauthorized"},{status:401});let P=ee();try{if(B.endpoint!=="action")return C({error:"Unknown endpoint"},{status:404});let M=await r.getUserIdByExternalId(k.id);if(!M)return C({error:"User not found"},{status:404});let L=await h(v),V=await v.formData(),Y=V.get("intent"),te=V.get("reportHubId"),G=te?Number(te):NaN,de=V.get("businessDate"),Ee=Number(V.get("operationTimestamp")),Q=V.get("clientTempId");if(Y==="clearCache")return e.enableDevCacheClear?(await r.clearCache(),C({status:"OK",intent:"clearCache"})):C({error:"Invalid intent"},{status:400});if(!Q)return C({error:"clientTempId required"},{status:400});if(Y!=="create"&&(!G||Number.isNaN(G)))return C({error:"Invalid reportHubId"},{status:400});let re=async(z,K,le)=>{let ot=V.get(K);if(ot===null)return C({error:`${K} required`},{status:400});try{let Ae=await le(ot==="true");return C({status:"OK",intent:z,updatedStatus:{isStarred:Ae.isStarred,isRead:Ae.isRead},operationTimestamp:Ee,reportHubId:String(G),clientTempId:Q})}catch(Ae){if(Ae instanceof Error&&Ae.message==="Not Found")return C({error:"Report not found"},{status:404});throw Ae}};switch(Y){case"create":{if(!de)return C({error:"businessDate required"},{status:400});let z=await r.createDailyReport(M,de,Q);return C({status:"OK",intent:"create",report:z,reportHubId:String(z.reportHubId),clientTempId:Q})}case"update":{let z=V.get("title"),K=V.get("content");try{return await r.updateDailyReport(G,M,{title:z,content:K},Q),C({status:"OK",intent:"update",reportHubId:String(G),clientTempId:Q})}catch(le){if(le instanceof Error){if(le.message==="Unauthorized")return C({error:"Unauthorized"},{status:403});if(le.message==="Not Found")return C({error:"Report not found"},{status:404})}throw le}}case"publish":try{let z=await r.publishDailyReport(G,M,Q);return C({status:"OK",intent:"publish",reportHubId:String(G),clientTempId:Q,report:z})}catch(z){if(z instanceof Error){if(z.message==="Unauthorized")return C({error:"Unauthorized"},{status:403});if(z.message==="Not Found")return C({error:"Report not found"},{status:404})}throw z}case"delete":try{return await r.deleteDailyReport(G,M,Q),C({status:"OK",intent:"delete",reportHubId:String(G),clientTempId:Q})}catch(z){if(z instanceof Error){if(z.message==="Unauthorized")return C({error:"Unauthorized"},{status:403});if(z.message==="Not Found")return C({error:"Report not found"},{status:404})}throw z}case"toggleStar":return await re("toggleStar","isStarred",z=>r.setStarStatus(L,M,G,de,z,Q));case"toggleRead":return await re("toggleRead","isRead",z=>r.setReadStatus(L,M,G,de,z,Q));case"addComment":{let z=V.get("content");if(!z)return C({error:"Content required"},{status:400});try{let K=await r.addComment(L,M,G,z,de,Q),le={...K,userId:K.userId};return C({status:"OK",intent:"addComment",newComment:le,reportHubId:String(G),clientTempId:Q})}catch(K){if(K instanceof Error){if(K.message==="Not Found")return C({error:"Report not found"},{status:404});if(K.message.startsWith("Comments are restricted"))return C({error:"Comments are restricted for this report"},{status:403})}throw K}}case"deleteComment":{let z=Number(V.get("commentId"));if(!z||Number.isNaN(z))return C({error:"Invalid commentId"},{status:400});try{return await r.deleteComment(L,M,G,z,de,Q),C({status:"OK",reportHubId:String(G),deletedCommentId:String(z),clientTempId:Q})}catch(K){if(K instanceof Error){if(K.message==="Unauthorized")return C({error:"Unauthorized"},{status:403});if(K.message==="Not Found")return C({error:"Comment not found"},{status:404})}throw K}}default:return C({error:"Invalid intent"},{status:400})}}catch($){if($ instanceof Response)throw $;let M=ee()-P,L=$ instanceof Error?$:new Error(String($));return R.error(`500 action elapsed=${M}ms name=${L.name} message=${L.message}`),R.error("Stack:",L.stack),C({error:"Internal Server Error"},{status:500})}},x=Wn({authenticate:t,service:r,resolveViewerScope:h,redis:a,sseReader:o,streamKey:l,logger:_}),H=gn({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:h,logger:y,tuning:e}),D=Dr(I),U=(v,B,k)=>async F=>{let C=Ar(F.request)?B.frameworkDataRefusal(F):null;if(C!==null)throw C;return Tr(F.request,B)?(D(v,F.request),B.crossSiteRejection()):k(F)};return{index:{loader:m},api:{loader:U("api",_n,A),action:U("action",$e,S)},sse:{loader:U("sse",zn,x)},attachment:{loader:U("attachment",Rn,H)}}}var Gn=require("@aiquants/mssql"),u=require("drizzle-orm");var Ne=e=>(0,u.getColumns)(e),bi=e=>{if(e!==void 0){if(typeof e!="object"||e===null)throw qe("attachmentThumbnailRenderer","an object with id and render",e);if(e.render===void 0)throw gt("attachmentThumbnailRenderer.render","a function");if(typeof e.render!="function")throw qe("attachmentThumbnailRenderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw qe("attachmentThumbnailRenderer.id","a non-blank string naming the rendering pipeline version",e.id);return e}},se=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),a=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),o=String(r.getMonth()+1).padStart(2,"0"),l=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${a}-${o}-${l}`;let i=String(r.getHours()).padStart(2,"0"),R=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0");return`${a}-${o}-${l} ${i}:${R}:${s}`};function Pt(e){let{db:t,tables:r,userTable:n,resolveUserId:a,encodeUserId:o,redis:l,cache:i,epochs:R}=e,{hub:s,internal:_,comment:y,label:I,hubLabel:h,userStatus:m}=r,T=e.externalSources??[],A=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],S=A[0]??"\u4E0B\u66F8\u304D",x=e.logger??ue(1,"[DailyReportService]");jt({attachmentIdCodec:e.attachmentIdCodec,readAttachment:e.readAttachment,attachmentThumbnailRenderer:e.attachmentThumbnailRenderer,attachmentMaxBytes:e.attachmentMaxBytes});let H=Object.freeze({idCodec:e.attachmentIdCodec,readAttachment:e.readAttachment,thumbnailRenderer:bi(e.attachmentThumbnailRenderer),maxBytes:Me("attachmentMaxBytes",e.attachmentMaxBytes,1,Pr)}),D=c=>(0,Gn.runWithTransactionRetry)(d=>t.transaction(p=>d(()=>c(p))),e.transactionRetry),U=e.idsTtlMs??18e4,v="daily-report:ids:epoch",B=e.businessDateTtlMs??3e5,k="daily-report:date-epoch:",F="daily-report:detail-epoch:",P=`${e.streamKey??"daily-report:sse-stream"}:v2`,$=e.streamMaxLen??1e4,M=c=>R.incrementEpoch(c),L=c=>Fn(s.sourceType,c),V=async(c,d)=>{let p=await l?.getClient();if(!p){x.warn(`[SSE] Redis client unavailable (${d})`);return}let g=ee();try{await p.xAdd(P,"*",{data:JSON.stringify(c)},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:$}});let w=ee()-g;w>1e3&&x.warn(`[SSE] Slow publish (${d}): ${w}ms`)}catch(w){x.error(`[SSE] Redis publish failed (${d}):`,w)}},Y=async()=>{try{let c=await l?.getClient();if(c===void 0)return null;let[d]=await c.xRevRange(P,"+","-",{COUNT:1});return d===void 0?null:d.id}catch(c){return x.error("[DailyReportService] SSE stream anchor read failed",c),null}},te=c=>c==null||c===""?null:/^\d+$/.test(c)?o(Number(c)):c,G=()=>{let c={};for(let d of T)c[`ext_${d.sourceType}`]=Ne(d.table);return c},de=c=>{let d=c;for(let p of T)d=d.leftJoin(p.table,(0,u.and)((0,u.eq)(s.sourceType,p.sourceType),(0,u.eq)(s.sourceIdNum,p.idColumn)));return d},Ee=(c,d,p)=>{let{hub:g,internal:w}=d,O=g.summary,E=[],N=null,q=null,J=null,j=null,X=null,ne=null,Be=[],Te=T.find(W=>W.sourceType===g.sourceType),Ue=Te?d[`ext_${Te.sourceType}`]:void 0;if(Te&&Ue){let W=Te.mapRow(Ue);W.content!==void 0&&(O=W.content),W.employeeName!==void 0&&(ne=W.employeeName),W.category!==void 0&&(N=W.category),W.creationCategory!==void 0&&(q=W.creationCategory),W.visitTimeFrom!==void 0&&(J=W.visitTimeFrom),W.visitTimeTo!==void 0&&(j=W.visitTimeTo),W.customerName!==void 0&&(X=W.customerName),W.interviewers!==void 0&&(E=W.interviewers),W.externalComments!==void 0&&(Be=W.externalComments)}else g.sourceType==="Internal"&&w&&(O=w.body);let be=(d.labels??[]).map(W=>({id:W.id,name:W.name,color:W.color})),ae=d.postedCommentRows??[],Z=ge(c.commentable,g.sourceType),oe=q?A.includes(q):!1,Ot=Oe?.[0]??null;return oe&&Ot&&!be.some(W=>W.id===Ot)&&be.push({id:Ot,name:S,color:null}),{reportHubId:g.id,date:se(g.businessDate,"YYYY-MM-DD"),author:d.creatorName??te(g.createdBy)??"",userId:g.userId?o(g.userId):"",sourceType:g.sourceType??"Internal",createdAt:se(g.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:se(g.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:te(g.updatedBy),employeeName:ne??d.creatorName??te(g.createdBy),category:N,creationCategory:q,visitTimeFrom:J,visitTimeTo:j,customerName:X,interviewers:E,subject:g.title,content:O,externalComments:Z?Be:[],isRead:d.isRead??!1,isStarred:d.isStarred??!1,labels:be,postedComments:ae.filter(W=>Z||p!==void 0&&W.userId===p).map(W=>({...W,userId:o(W.userId),isMine:p?W.userId===p:!1})),attachments:d.attachments}},Q=async(c,d)=>{let p=(0,u.aliasedTable)(h,"draft_label"),g=await Ie();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).leftJoin(p,(0,u.and)((0,u.eq)(p.hubId,s.id),(0,u.inArray)(p.labelId,g))).where((0,u.and)((0,u.isNull)(s.deletedAt),(0,u.or)((0,u.eq)(s.userId,d),(0,u.isNull)(s.userId),(0,u.isNull)(p.hubId)),L(c.visible))).orderBy((0,u.desc)(s.businessDate),(0,u.desc)(s.id))).map(O=>({...O,businessDate:se(O.businessDate,"YYYY-MM-DD")}))},re=async(c,d,p)=>{let g=await le(d);if(!g)return[];if(Le(c.visible))return[];let w=(0,u.aliasedTable)(h,"draft_label"),O=await Ie();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(p).from(s).leftJoin(w,(0,u.and)((0,u.eq)(w.hubId,s.id),(0,u.inArray)(w.labelId,O))).where((0,u.and)((0,u.isNull)(s.deletedAt),(0,u.or)((0,u.eq)(s.userId,g),(0,u.isNull)(s.userId),(0,u.isNull)(w.hubId)),L(c.visible))).orderBy((0,u.desc)(s.businessDate),(0,u.desc)(s.id))).map(N=>({...N,businessDate:se(N.businessDate,"YYYY-MM-DD")}))},z=async(c,d)=>{let p=await de(t.select({hub:Ne(s),internal:Ne(_),creatorName:n.displayName,...G()}).from(s)).leftJoin(_,(0,u.eq)(s.id,_.hubId)).leftJoin(n,(0,u.eq)(s.userId,n.id)).where((0,u.and)((0,u.eq)(s.businessDate,u.sql`${d}`),(0,u.isNull)(s.deletedAt),L(c.visible))).orderBy((0,u.desc)(s.id)),g=await st(p.map(w=>w.hub.id));return p.map(w=>Ee(c,{...w,attachments:g.get(w.hub.id)??[]}))},K=new Map,le=async c=>{if(!e.disableUserIdCache&&K.has(c))return K.get(c)??null;let d=await a(c);return d!==null&&!e.disableUserIdCache&&K.set(c,d),d},ot=async(c,d,{forceRefresh:p=!1,snapshot:g=!1,ttlMsOverride:w,onFetchStart:O}={})=>{let E=await le(d);if(!E)return{items:[],streamAnchor:null};if(Le(c.visible))return{items:[],streamAnchor:await Y()};let N=kn(E,rt(c)),[q]=await i.getOrFetch({cacheKey:N,fetcher:async()=>{let J=await Y(),j=await Q(c,E);return fr(j)?[{items:j,streamAnchor:J}]:(x.warn("[DailyReportService] ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)"),[{items:[...j].sort(dt),streamAnchor:J}])},onFetchStart:O,forceRefresh:p,snapshot:g,ttlMsOverride:w??U,epochKey:v,refreshAheadRatio:.5});if(q===void 0)throw new Error("[DailyReportService] ids cache returned no record");return q},Ae=(c,d,{forceRefresh:p=!1,snapshot:g=!1,ttlMsOverride:w}={})=>{let O=ie(d);return O?Le(c.visible)?Promise.resolve([]):i.getOrFetch({cacheKey:Ln(O,rt(c)),fetcher:()=>z(c,O),forceRefresh:p,snapshot:g,ttlMsOverride:w??B}):Promise.resolve([])},Oe=null,it=async()=>(Oe!==null||(Oe=(await t.select({id:I.id}).from(I).where((0,u.inArray)(I.name,A)).orderBy(I.id)).map(d=>d.id)),Oe),Ie=async()=>{let c=await it();return c.length>0?c:[-1]},kt=async()=>{let c=await it();if(c.length===0)return null;let[d]=await t.select({id:I.id}).top(1).from(I).where((0,u.eq)(I.name,S));return d?.id??c[0]},pa=(c,d)=>d!=null?"absent":c!=null?"present":"unknown",st=async c=>{let d=new Map,p=r.attachment,g=H.idCodec;if(c.length===0||!p||!g)return d;let w=H.thumbnailRenderer!==void 0&&H.readAttachment!==void 0,O=await t.select({id:p.id,hubId:p.hubId,fileName:p.fileName,fileType:p.fileType,fileSize:p.fileSize,createdAt:p.createdAt,objectCheckedAt:p.objectCheckedAt,objectMissingAt:p.objectMissingAt}).from(p).where((0,u.inArray)(p.hubId,c)).orderBy((0,u.asc)(p.createdAt),(0,u.asc)(p.id));for(let E of O){let N=E.fileType?String(E.fileType):null,q=E.fileSize!=null?Number(E.fileSize):null,J=pa(E.objectCheckedAt,E.objectMissingAt),j={id:g.encode(Number(E.id)),fileName:String(E.fileName),fileType:N,fileSize:q,createdAt:se(E.createdAt,"YYYY-MM-DD HH:mm:ss"),state:J,hasThumbnail:w&&J!=="absent"&&Tt({fileType:N,fileSize:q},H.maxBytes)},X=d.get(Number(E.hubId));X?X.push(j):d.set(Number(E.hubId),[j])}return d},ya=async(c,d,p)=>{let g=r.attachment;if(!g||Le(c.visible))return null;let w=await Ie(),O=(0,u.aliasedTable)(h,"draft_label");return(await t.select({fileName:g.fileName,filePath:g.filePath,fileType:g.fileType,fileSize:g.fileSize}).top(1).from(g).innerJoin(s,(0,u.eq)(s.id,g.hubId)).leftJoin(O,(0,u.and)((0,u.eq)(O.hubId,s.id),(0,u.inArray)(O.labelId,w))).where((0,u.and)((0,u.eq)(g.id,d),(0,u.isNull)(s.deletedAt),(0,u.or)((0,u.eq)(s.userId,p),(0,u.isNull)(O.hubId)),L(c.visible))))[0]??null},ha=async c=>{let d=r.attachment;if(!d)return;let p=new Date;try{await t.update(d).set({objectCheckedAt:p,objectMissingAt:p,updatedAt:p}).where((0,u.eq)(d.id,c))}catch(g){x.error("markAttachmentMissing failed",g)}},fa=async c=>{let d=r.attachment;if(!d)return;let p=new Date;try{await t.update(d).set({objectCheckedAt:p,objectMissingAt:null,updatedAt:p}).where((0,u.eq)(d.id,c))}catch(g){x.error("markAttachmentPresent failed",g)}},Ra=async(c,d,p,{forceRefresh:g=!1,snapshot:w=!1,ttlMsOverride:O}={})=>{let E=await le(p);if(!E)return[];let N=ie(d);if(!N)return[];if(Le(c.visible))return[];let q=Nn(N,E,rt(c));return i.getOrFetch({cacheKey:q,fetcher:async()=>{let J=await Ie(),j=(0,u.aliasedTable)(h,"draft_label"),X=await de(t.select({hub:Ne(s),internal:Ne(_),isRead:m.isRead,isStarred:m.isStarred,creatorName:n.displayName,...G()}).from(s)).leftJoin(_,(0,u.eq)(s.id,_.hubId)).leftJoin(m,(0,u.and)((0,u.eq)(s.id,m.hubId),(0,u.eq)(m.userId,E))).leftJoin(j,(0,u.and)((0,u.eq)(j.hubId,s.id),(0,u.inArray)(j.labelId,J))).leftJoin(n,(0,u.eq)(s.userId,n.id)).where((0,u.and)((0,u.eq)(s.businessDate,u.sql`${N}`),(0,u.isNull)(s.deletedAt),(0,u.or)((0,u.eq)(s.userId,E),(0,u.isNull)(j.hubId)),L(c.visible))).orderBy((0,u.desc)(s.id));if(X.length===0)return[];let ne=X.map(Z=>Z.hub.id),Be=await t.select({hubId:h.hubId,id:I.id,name:I.name,color:I.color}).from(h).innerJoin(I,(0,u.eq)(h.labelId,I.id)).where((0,u.inArray)(h.hubId,ne)),Te=await t.select({hubId:y.hubId,id:y.id,body:y.body,createdAt:y.createdAt,userId:y.userId,userName:n.displayName}).from(y).leftJoin(n,(0,u.eq)(y.userId,n.id)).where((0,u.inArray)(y.hubId,ne)).orderBy((0,u.asc)(y.createdAt)),Ue=await st(ne),be=new Map,ae=new Map;for(let Z of Be){let oe=be.get(Z.hubId);oe||(oe=[],be.set(Z.hubId,oe)),oe.push({id:Z.id,name:Z.name,color:Z.color})}for(let Z of Te){let oe=ae.get(Z.hubId);oe||(oe=[],ae.set(Z.hubId,oe)),oe.push({id:Z.id,content:Z.body,createdAt:se(Z.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Z.userId,userName:Z.userName||""})}return X.map(Z=>{let oe=Z.hub.id;return Ee(c,{...Z,attachments:Ue.get(oe)??[],labels:be.get(oe)||[],postedCommentRows:ae.get(oe)||[]},E)})},forceRefresh:g,snapshot:w,ttlMsOverride:O??B,epochKey:`${k}${N}`})},Ge=async(c,d,p,{forceRefresh:g=!1,snapshot:w=!1,ttlMsOverride:O}={})=>{if(Le(c.visible))return null;let E=On(d,p,rt(c));return(await i.getOrFetch({cacheKey:E,fetcher:async()=>{let q=await Ie(),J=(0,u.aliasedTable)(h,"draft_label"),j=await de(t.select({hub:Ne(s),internal:Ne(_),isRead:m.isRead,isStarred:m.isStarred,creatorName:n.displayName,...G()}).from(s)).leftJoin(_,(0,u.eq)(s.id,_.hubId)).leftJoin(m,(0,u.and)((0,u.eq)(s.id,m.hubId),(0,u.eq)(m.userId,p))).leftJoin(J,(0,u.and)((0,u.eq)(J.hubId,s.id),(0,u.inArray)(J.labelId,q))).leftJoin(n,(0,u.eq)(s.userId,n.id)).where((0,u.and)((0,u.eq)(s.id,d),(0,u.isNull)(s.deletedAt),(0,u.or)((0,u.eq)(s.userId,p),(0,u.isNull)(J.hubId)),L(c.visible)));if(j.length===0)return[];let X=j[0].hub.id,ne=await t.select({id:I.id,name:I.name,color:I.color}).from(h).innerJoin(I,(0,u.eq)(h.labelId,I.id)).where((0,u.eq)(h.hubId,X)),Be=await t.select({id:y.id,body:y.body,createdAt:y.createdAt,userId:y.userId,userName:n.displayName}).from(y).leftJoin(n,(0,u.eq)(y.userId,n.id)).where((0,u.eq)(y.hubId,X)).orderBy((0,u.asc)(y.createdAt)),Te=await st([X]),Ue=ne.map(ae=>({id:ae.id,name:ae.name,color:ae.color})),be=Be.map(ae=>({id:ae.id,content:ae.body,createdAt:se(ae.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ae.userId,userName:ae.userName||""}));return[Ee(c,{...j[0],attachments:Te.get(X)??[],labels:Ue,postedCommentRows:be},p)]},forceRefresh:g,snapshot:w,ttlMsOverride:O??B,epochKey:`${F}${d}`}))[0]??null},ga=async(c,d,p,g={})=>{let w=await le(p);return w?Ge(c,d,w,g):null},ba=async(c,d)=>{let p=await Ie(),g=(0,u.aliasedTable)(h,"draft_label"),[w]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).leftJoin(g,(0,u.and)((0,u.eq)(g.hubId,s.id),(0,u.inArray)(g.labelId,p))).where((0,u.and)((0,u.eq)(s.id,c),(0,u.or)((0,u.eq)(s.userId,d),(0,u.isNull)(g.hubId))));return w??null},Lt=async(c,d,p)=>{let g=await ba(d,p);if(!g||g.deletedAt||!ge(c.visible,g.sourceType))throw new Error("Not Found")},Sa=async(c,d,p,g,w,O)=>{await Lt(c,p,d);let E=await t.select().top(1).from(m).where((0,u.and)((0,u.eq)(m.hubId,p),(0,u.eq)(m.userId,d))),N;if(E.length>0?E[0].isStarred!==w?N=(await t.update(m).set({isStarred:w,updatedAt:new Date,updatedBy:String(d)}).output().where((0,u.and)((0,u.eq)(m.hubId,p),(0,u.eq)(m.userId,d))))[0]:N=E[0]:N=(await t.insert(m).output().values({hubId:p,userId:d,isStarred:w,isRead:!1,createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)}))[0],g){let q=ie(g);q&&(i.invalidatePrefix(ze(q,d)),await M(`${k}${q}`))}return i.invalidatePrefix(Ct(p,d)),await M(`${F}${p}`),await V(It.parse({type:"status-update",reportHubId:p,recipientRawUserId:d,statusType:"star",value:w,clientTempId:O}),"setStarStatus"),N},Aa=async(c,d,p,g,w,O)=>{await Lt(c,p,d);let E=await t.select().top(1).from(m).where((0,u.and)((0,u.eq)(m.hubId,p),(0,u.eq)(m.userId,d))),N;if(E.length>0?E[0].isRead!==w?N=(await t.update(m).set({isRead:w,updatedAt:new Date,updatedBy:String(d)}).output().where((0,u.and)((0,u.eq)(m.hubId,p),(0,u.eq)(m.userId,d))))[0]:N=E[0]:N=(await t.insert(m).output().values({hubId:p,userId:d,isRead:w,isStarred:!1,createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)}))[0],g){let q=ie(g);q&&(i.invalidatePrefix(ze(q,d)),await M(`${k}${q}`))}return i.invalidatePrefix(Ct(p,d)),await M(`${F}${p}`),await V(It.parse({type:"status-update",reportHubId:p,recipientRawUserId:d,statusType:"read",value:w,clientTempId:O}),"setReadStatus"),N},ur=async(c,d)=>{if(d===null)return;let p=await Ie(),[g]=await t.select({hubId:h.hubId}).top(1).from(h).where((0,u.and)((0,u.eq)(h.hubId,c),(0,u.inArray)(h.labelId,p)));return g?d:void 0},Ta=async(c,d,p,g,w,O)=>{let[E]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where((0,u.eq)(s.id,p));if(!E||E.deletedAt)throw new Error("Not Found");if(await Lt(c,p,d),!ge(c.commentable,E.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(E.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let N=await ur(p,E.userId),[q]=await t.insert(y).output().values({hubId:p,userId:d,body:g,createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)}),[J]=await t.select({displayName:n.displayName}).top(1).from(n).where((0,u.eq)(n.id,d)),j=J?.displayName??"";if(w){let ne=ie(w);ne&&(i.invalidatePrefix(Ze(ne)),await M(`${k}${ne}`))}i.invalidatePrefix(Re(p)),await M(`${F}${p}`);let X={id:q.id,userId:o(q.userId),userName:j,content:q.body,createdAt:se(q.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await V(Zt.parse({type:"comment-add",reportHubId:p,comment:X,clientTempId:O,recipientRawUserId:N,sourceType:E.sourceType}),"addComment"),X},Da=async(c,d)=>await c.select().top(1).from(y).where((0,u.eq)(y.id,d)),wa=async(c,d,p,g,w,O)=>{let E=await Da(t,g);if(E.length===0)throw new Error("Not Found");if(E[0].hubId!==p)throw new Error("Not Found");let[N]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where((0,u.eq)(s.id,E[0].hubId));if(!(N&&ge(c.visible,N.sourceType)))throw new Error("Not Found");if(E[0].userId!==d)throw new Error("Unauthorized");let q=await ur(p,N.userId);if(await t.delete(y).where((0,u.eq)(y.id,g)),w){let J=ie(w);J&&(i.invalidatePrefix(Ze(J)),await M(`${k}${J}`))}i.invalidatePrefix(Re(p)),await M(`${F}${p}`),await V(er.parse({type:"comment-delete",reportHubId:p,commentId:g,clientTempId:O,recipientRawUserId:q,sourceType:N?.sourceType}),"deleteComment")},_a=async(c,d,p)=>{x.info("createDailyReport called",{userId:c,businessDate:d});let[g]=await t.select({displayName:n.displayName}).from(n).where((0,u.eq)(n.id,c)),w=g?.displayName??o(c);try{let O=await D(async q=>{x.info("Starting transaction");let J=`internal-temp-${Date.now()}-${Math.random()}`,[j]=await q.insert(s).output().values({sourceType:"Internal",sourceId:J,businessDate:new Date(d),userId:c,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)});await q.update(s).set({sourceId:String(j.id)}).where((0,u.eq)(s.id,j.id)),x.info("Hub created",j),await q.insert(_).values({hubId:j.id,body:"",createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)}),x.info("Internal created"),x.info("Calling getDraftLabelId");let X=await kt();x.info("draftLabelId",X);let ne=[];return X&&(await q.insert(h).values({hubId:j.id,labelId:X,createdAt:new Date,createdBy:String(c)}),ne.push({id:X,name:S,color:null})),x.info("Label assigned"),{reportHubId:j.id,date:d,createdAt:se(j.createdAt,"YYYY-MM-DD HH:mm:ss"),author:w,userId:o(c),sourceType:"Internal",employeeName:w,updatedBy:o(c),updatedAt:se(j.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:j.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:ne,postedComments:[],attachments:[]}}),E=ie(d);E&&i.invalidatePrefix(ze(E,c)),i.invalidatePrefix(ke),i.invalidatePrefix(or(c)),await M(v),E&&await M(`${k}${E}`);let N=await Ge(pe.unrestricted("post-write self read: the writer always sees the row they just wrote"),O.reportHubId,c,{forceRefresh:!0});if(N){let q=await it(),J=N.labels.some(j=>q.includes(j.id));await V(tr.parse({type:"report-create",reportHubId:N.reportHubId,report:N,clientTempId:p,recipientRawUserId:J?c:void 0}),"createDailyReport")}return N??O}catch(O){throw x.error("Error in createDailyReport",O),O}},lt=async(c,d)=>await c.select().top(1).from(s).where((0,u.eq)(s.id,d)),Nt=async(c,d,p)=>{await c.update(s).set(p).where((0,u.eq)(s.id,d))},cr=async(c,d,p)=>{await c.update(_).set(p).where((0,u.eq)(_.hubId,d))},dr=async(c,d,p)=>{await c.delete(h).where((0,u.and)((0,u.eq)(h.hubId,d),(0,u.eq)(h.labelId,p)))};return{streamKey:P,streamMaxLen:$,attachmentDelivery:H,clearCache:async()=>{i.clearAll(),K.clear(),Oe=null,R&&await M(v),x.info("[DailyReportService] Server-side DB/SQL caches cleared successfully.")},invalidateHubReadCaches:async(c,d)=>{i.invalidatePrefix(ke),i.invalidatePrefix(Pe),await M(v);for(let p of new Set(c))i.invalidatePrefix(Re(p)),await M(`${F}${p}`);for(let p of new Set(d)){let g=ie(p);g&&await M(`${k}${g}`)}},getUserIdByExternalId:le,getDailyReportIdsByExternalId:ot,getDailyReportIdsFirstPageByExternalId:re,readSseStreamAnchor:Y,getDailyReportsByBusinessDate:Ae,getDailyReportsByBusinessDateByExternalId:Ra,getDailyReportDetailById:Ge,getDailyReportDetailByIdByExternalId:ga,getDraftLabelId:kt,getAttachmentsByHubIds:st,getAttachmentForUser:ya,markAttachmentMissing:ha,markAttachmentPresent:fa,setStarStatus:Sa,setReadStatus:Aa,addComment:Ta,deleteComment:wa,createDailyReport:_a,updateDailyReport:async(c,d,p,g)=>{let w=await lt(t,c);if(!w.length||w[0].deletedAt)throw new Error("Not Found");if(w[0].userId!==d)throw new Error("Unauthorized");await D(async N=>{p.title!==void 0&&await Nt(N,c,{title:p.title,updatedAt:new Date,updatedBy:String(d)}),p.content!==void 0&&await cr(N,c,{body:p.content,updatedAt:new Date,updatedBy:String(d)})}),i.invalidatePrefix(Re(c)),i.invalidatePrefix(ke),await M(`${F}${c}`);let O=ie(se(w[0].businessDate,"YYYY-MM-DD"));O&&(i.invalidatePrefix(Ze(O)),await M(`${k}${O}`));let E=await Ge(pe.unrestricted("post-write self read: the writer always sees the row they just wrote"),c,d,{forceRefresh:!0});if(E){let N=await it(),q=E.labels.some(J=>N.includes(J.id));await V(rr.parse({type:"report-update",reportHubId:E.reportHubId,report:E,clientTempId:g,recipientRawUserId:q?d:void 0}),"updateDailyReport")}},publishDailyReport:async(c,d,p)=>{let g=await lt(t,c);if(!g.length)throw new Error("Not Found");if(g[0].userId!==d)throw new Error("Unauthorized");let w=await kt();if(!w)return null;if(await dr(t,c,w),i.invalidatePrefix(Re(c)),i.invalidatePrefix(ke),i.invalidatePrefix(Pe),await M(v),g[0].businessDate){let N=ie(se(g[0].businessDate,"YYYY-MM-DD"));N&&await M(`${k}${N}`)}let O=ie(se(g[0].businessDate,"YYYY-MM-DD"));O&&i.invalidatePrefix(ze(O,d));let E=await Ge(pe.unrestricted("post-write self read: the writer always sees the row they just wrote"),c,d,{forceRefresh:!0});return E&&await V(nr.parse({type:"report-publish",reportHubId:E.reportHubId,report:E,clientTempId:p}),"publishDailyReport"),E??null},deleteDailyReport:async(c,d,p)=>{let g=await lt(t,c);if(!g.length||g[0].deletedAt)throw new Error("Not Found");if(g[0].userId!==d)throw new Error("Unauthorized");if(await Nt(t,c,{deletedAt:new Date,deletedBy:String(d),updatedAt:new Date,updatedBy:String(d)}),i.invalidatePrefix(Re(c)),i.invalidatePrefix(ke),i.invalidatePrefix(Pe),await M(v),g[0].businessDate){let w=ie(se(g[0].businessDate,"YYYY-MM-DD"));w&&await M(`${k}${w}`)}await V(ar.parse({type:"report-delete",reportHubId:c,clientTempId:p,sourceType:g[0].sourceType}),"deleteDailyReport")},findDailyReportHubById:lt,updateDailyReportHub:Nt,updateDailyReportInternal:cr,deleteDailyReportLabel:dr}}var Si=ue(1,"[DailyReportExternalSource]"),Kn=(e,t,r,n=Si)=>{if(!e)return[];try{let a=JSON.parse(e);return Array.isArray(a)?a.map(r).filter(o=>o!==null):(n.warn(`Unexpected ${t} format: not an array`),[])}catch(a){return n.warn(`Failed to parse ${t}:`,a),[]}};var nt=require("drizzle-orm"),f=require("drizzle-orm/mssql-core");function Xn(e,t){let r=(0,f.mssqlSchema)(e),n=t.userTable,a=r.table("DailyReportHub",{id:(0,f.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,f.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,f.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,f.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(nt.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,f.date)("business_date"),userId:(0,f.bigint)("user_id",{mode:"number"}),title:(0,f.nvarchar)("title",{length:200}),summary:(0,f.nvarchar)("summary",{length:"max"}),createdAt:(0,f.datetime2)("created_at").notNull(),createdBy:(0,f.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,f.datetime2)("updated_at").notNull(),updatedBy:(0,f.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,f.datetime2)("deleted_at"),deletedBy:(0,f.nvarchar)("deleted_by",{length:50})},y=>[(0,f.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[y.id]}),(0,f.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[y.userId],foreignColumns:[n.id]}),(0,f.index)(`${e}_DailyReportHub_business_date_index`).on(y.businessDate),(0,f.index)(`${e}_DailyReportHub_updated_at_index`).on(y.updatedAt),(0,f.index)(`${e}_DailyReportHub_source_index`).on(y.sourceType,y.sourceId),(0,f.index)(`${e}_DailyReportHub_user_id_index`).on(y.userId),(0,f.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,nt.desc)(y.businessDate),(0,nt.desc)(y.id)),(0,f.index)(`${e}_DailyReportHub_deleted_at_index`).on(y.deletedAt)]),o=r.table("DailyReportInternal",{hubId:(0,f.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,f.nvarchar)("body",{length:"max"}),metadata:(0,f.nvarchar)("metadata",{length:"max"}),createdAt:(0,f.datetime2)("created_at").notNull(),createdBy:(0,f.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,f.datetime2)("updated_at").notNull(),updatedBy:(0,f.nvarchar)("updated_by",{length:50}).notNull()},y=>[(0,f.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[y.hubId]}),(0,f.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[y.hubId],foreignColumns:[a.id]})]),l=r.table("DailyReportComment",{id:(0,f.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,f.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,f.bigint)("user_id",{mode:"number"}).notNull(),body:(0,f.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,f.datetime2)("created_at").notNull(),createdBy:(0,f.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,f.datetime2)("updated_at").notNull(),updatedBy:(0,f.nvarchar)("updated_by",{length:50}).notNull()},y=>[(0,f.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[y.id]}),(0,f.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[y.hubId],foreignColumns:[a.id]}),(0,f.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[y.userId],foreignColumns:[n.id]}),(0,f.index)(`${e}_DailyReportComment_hub_id_index`).on(y.hubId)]),i=r.table("DailyReportLabel",{id:(0,f.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,f.bigint)("user_id",{mode:"number"}),name:(0,f.nvarchar)("name",{length:50}).notNull(),color:(0,f.nvarchar)("color",{length:20}),sortOrder:(0,f.int)("sort_order"),createdAt:(0,f.datetime2)("created_at").notNull(),createdBy:(0,f.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,f.datetime2)("updated_at").notNull(),updatedBy:(0,f.nvarchar)("updated_by",{length:50}).notNull()},y=>[(0,f.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[y.id]}),(0,f.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[y.userId],foreignColumns:[n.id]})]),R=r.table("DailyReportHub_Label",{hubId:(0,f.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,f.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,f.datetime2)("created_at").notNull(),createdBy:(0,f.nvarchar)("created_by",{length:50}).notNull()},y=>[(0,f.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[y.hubId,y.labelId]}),(0,f.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[y.hubId],foreignColumns:[a.id]}),(0,f.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[y.labelId],foreignColumns:[i.id]})]),s=r.table("DailyReportUserStatus",{hubId:(0,f.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,f.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,f.bit)("is_read").default(!1).notNull(),isStarred:(0,f.bit)("is_starred").default(!1).notNull(),createdAt:(0,f.datetime2)("created_at").notNull(),createdBy:(0,f.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,f.datetime2)("updated_at").notNull(),updatedBy:(0,f.nvarchar)("updated_by",{length:50}).notNull()},y=>[(0,f.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[y.hubId,y.userId]}),(0,f.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[y.hubId],foreignColumns:[a.id]}),(0,f.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[y.userId],foreignColumns:[n.id]})]),_=r.table("DailyReportAttachment",{id:(0,f.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,f.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,f.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,f.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,f.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,f.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,f.nvarchar)("file_type",{length:100}),fileSize:(0,f.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,f.datetime2)("object_checked_at"),objectMissingAt:(0,f.datetime2)("object_missing_at"),createdAt:(0,f.datetime2)("created_at").notNull(),createdBy:(0,f.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,f.datetime2)("updated_at").notNull(),updatedBy:(0,f.nvarchar)("updated_by",{length:50}).notNull()},y=>[(0,f.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[y.id]}),(0,f.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[y.hubId],foreignColumns:[a.id]}),(0,f.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[y.uploadedBy],foreignColumns:[n.id]}),(0,f.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(y.hubId,y.sourceKey),(0,f.index)(`${e}_DailyReportAttachment_hub_id_index`).on(y.hubId,y.createdAt)]);return{hub:a,internal:o,comment:l,attachment:_,label:i,hubLabel:R,userStatus:s}}var Ai=5e7,sr=2e8,Ti=1,lr=Object.freeze({fixedBytes:4*1024*1024,pipelineRows:2048,wholeImageBuffer:Object.freeze({"jpeg-single-scan":Object.freeze({kind:"none"}),"jpeg-multi-scan":Object.freeze({kind:"jpeg-coefficients"}),png:Object.freeze({kind:"none"}),"png-interlaced":Object.freeze({kind:"decoded-raster"}),gif:Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-lossy":Object.freeze({kind:"none"}),"webp-lossy-alpha":Object.freeze({kind:"canvas",bytesPerPixel:5}),"webp-lossless":Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-animated":Object.freeze({kind:"canvas",bytesPerPixel:9})})}),Qn=125,Zn=4,ea=16,ta=50,ra=2,at=Object.freeze({renderMs:me.renderMs,nanosecondsPerBlockVisit:Qn,margin:Zn,maxBlockVisits:Math.floor(me.renderMs*1e6/(Qn*Zn)),walkBudgetMs:ea,nanosecondsPerWalkStep:ta,walkMargin:ra,maxWalkSteps:Math.floor(ea*1e6/(ta*ra))}),Di=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),na=75,aa=4,oa="#ffffff",wi=1,_i={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Ei=[/out of memory/i,/insufficient memory/i,/memory allocation|allocation failed/i,/(?:cannot|could not|unable to|failed to) allocate/i,/picture memory error/i,/unable to create thread|error creating thread|resource temporarily unavailable/i,/too many open files|no space left on device/i,/\b(?:ENOMEM|EAGAIN|EMFILE|ENFILE|ENOSPC)\b/],ia=Object.freeze({ok:!1,reason:"failed"}),sa=Object.freeze({ok:!1,reason:"unsupported"}),la=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:Zr(e)}),ua=(e,t)=>{switch(t){case"jpeg":{let r=Jt(e);return r===null?null:la(r)}case"png":{let r=rn(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=nn(e,at.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},ca=(e,t)=>{let r=Di.get(t.depth);if(r===void 0)return null;let n=t.channels*r,a=lr,o=a.wholeImageBuffer[e.layout];return(o.kind==="none"?0:o.kind==="decoded-raster"?t.width*t.height*n:o.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*o.bytesPerPixel)+a.pipelineRows*t.width*n+a.fixedBytes},da=(e,t,r)=>{let n=ua(e,t);return n===null?null:ca(n,r)},Ii=e=>e!==null&&e<=sr,xi=(e,t)=>{if(t!=="jpeg")return ua(e,t);let r=en(e,at);return r===null||r.blockVisits>at.maxBlockVisits?null:la(r.header)},Ci=e=>{let t=e instanceof Error?e.message:"";return Ei.some(r=>r.test(t))?"failed":"unsupported"},ma=e=>{e.cache(!1),e.concurrency(Ti),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(_i)});let t=async(n,a,o,l,i)=>{let R=xi(n,a);if(R===null)return sa;try{let s=e(n,{limitInputPixels:Ai,animated:!1});if(!Ii(ca(R,await s.metadata())))return sa;if(i.aborted)return ia;let _=await s.rotate().resize({width:o,height:l,fit:"inside",withoutEnlargement:!0}).flatten({background:oa}).webp({quality:na,effort:aa}).toBuffer();return{ok:!0,bytes:new Uint8Array(_),contentType:"image/webp"}}catch(s){return{ok:!1,reason:Ci(s)}}},r=async(n,{format:a,maxWidth:o,maxHeight:l,signal:i})=>i.aborted?ia:t(n,a,o,l,i);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${na}-e${aa}/flatten-${oa}/v${wi}`,render:r}};function Mi(e){e.redis||(e.logger??console).warn("[DailyReport] redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=ut(e.redis),r=new He({defaultTtlMs:e.cacheDefaultTtlMs??6e4},t),n=Pt({...e,cache:r,epochs:t}),a=new je({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),o=vt({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,attachmentRateLimitPerMinute:e.attachmentRateLimitPerMinute,attachmentConcurrency:e.attachmentConcurrency,attachmentThumbnailRateLimitPerMinute:e.attachmentThumbnailRateLimitPerMinute,attachmentThumbnailConcurrency:e.attachmentThumbnailConcurrency,attachmentThumbnailCacheBytes:e.attachmentThumbnailCacheBytes,redis:e.redis,sseReader:a,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:a,streamKey:n.streamKey,knownSourceTypes:[...new Set(["Internal",...(e.externalSources??[]).map(l=>l.sourceType)])],...o}}0&&(module.exports={DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,DAILY_REPORT_SSE_CATCH_UP_BATCH,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,DailyReportSseReader,DailyReportViewerScope,SqlResultCache,createDailyReportHandlers,createDailyReportServer,createDailyReportService,createEpochStore,createSharpThumbnailRenderer,defineDailyReportSchema,generateETag,isStreamIdLte,jsonResponseWithETag,predictSharpThumbnailWorkingSetBytes,transformJsonArray});
|
|
1
|
+
"use strict";var Yt=Object.defineProperty;var Yo=Object.getOwnPropertyDescriptor;var Vo=Object.getOwnPropertyNames;var jo=Object.prototype.hasOwnProperty;var Sr=e=>{throw TypeError(e)};var zo=(e,t)=>{for(var r in t)Yt(e,r,{get:t[r],enumerable:!0})},Wo=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Vo(t))!jo.call(e,o)&&o!==r&&Yt(e,o,{get:()=>t[o],enumerable:!(n=Yo(t,o))||n.enumerable});return e};var Jo=e=>Wo(Yt({},"__esModule",{value:!0}),e);var Ar=(e,t,r)=>t.has(e)||Sr("Cannot "+r);var Xe=(e,t,r)=>(Ar(e,t,"read from private field"),r?r.call(e):t.get(e)),Vt=(e,t,r)=>t.has(e)?Sr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),jt=(e,t,r,n)=>(Ar(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var os={};zo(os,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>It,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>Et,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>hr,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>st,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>fr,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>Ot,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>yr,DailyReportSseReader:()=>ze,DailyReportViewerScope:()=>le,SqlResultCache:()=>Be,createDailyReportHandlers:()=>Bt,createDailyReportServer:()=>ns,createDailyReportService:()=>Ut,createEpochStore:()=>mt,createSharpThumbnailRenderer:()=>Eo,defineDailyReportSchema:()=>co,generateETag:()=>Ye,isStreamIdLte:()=>_e,jsonResponseWithETag:()=>te,predictSharpThumbnailWorkingSetBytes:()=>wo,transformJsonArray:()=>uo});module.exports=Jo(os);var Z=()=>Math.floor(performance.now());var mt=e=>({async getEpoch(t){try{let r=await e?.getClient();if(!r)return null;let n=await r.get(t);return n?Number(n):0}catch{return null}},async incrementEpoch(t){try{let r=await e?.getClient();if(!r)return;await r.incr(t)}catch{}}}),Be=class{constructor(t,r){this.config=t;this.epochStore=r;this.buckets=new Map;this.inFlight=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.config.defaultTtlMs;if(a-(o.expireAt-Z())<a*r||this.inFlight.has(n))return;let s;s=(async()=>{let h=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,i=await t.fetcher();return this.inFlight.get(n)===s&&this.buckets.set(n,{records:i,expireAt:Z()+a,epoch:h}),i})(),this.inFlight.set(n,s),s.catch(()=>{}).finally(()=>{this.inFlight.get(n)===s&&this.inFlight.delete(n)})};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o}=t,a=this.buckets.get(r);if(n&&(this.buckets.delete(r),this.inFlight.delete(r)),!n&&a&&a.expireAt>Z())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||a.epoch===s)return this.maybeRefreshAhead(t),o?a.records.map(h=>structuredClone(h)):a.records;this.buckets.delete(r)}else return this.maybeRefreshAhead(t),o?a.records.map(s=>structuredClone(s)):a.records;if(!n&&this.inFlight.has(r)){let s=await this.inFlight.get(r);return o?s.map(h=>structuredClone(h)):s}let l;l=(async()=>{let s=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null;t.onFetchStart?.();let h=await t.fetcher();if(n||this.inFlight.get(r)===l){let i=Z()+(t.ttlMsOverride??this.config.defaultTtlMs);this.buckets.set(r,{records:h,expireAt:i,epoch:s}),this.buckets.size>500&&this.cleanExpired()}return h})(),n||this.inFlight.set(r,l);try{let s=await l;return o?s.map(h=>structuredClone(h)):s}finally{this.inFlight.get(r)===l&&this.inFlight.delete(r)}};this.clearAll=()=>{this.buckets.clear(),this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.buckets.delete(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)}}cleanExpired(){let t=Z();for(let[r,n]of this.buckets.entries())n.expireAt<=t&&this.buckets.delete(r)}};var Ko=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Tr=e=>e<10?`0${e}`:`${e}`,Go=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Tr(e.getMonth()+1),n=Tr(e.getDate());return`${t}-${r}-${n}`},Ue=e=>{let t=Ko.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),l=Number(n),s=Number(o);if(a<1)return null;let h=new Date(0);return h.setUTCFullYear(a,l-1,s),h.getUTCFullYear()!==a||h.getUTCMonth()!==l-1||h.getUTCDate()!==s?null:`${r}-${n}-${o}`},pt=e=>Ue(e)===e;var de=e=>e==null?null:e instanceof Date?Go(e):Ue(e);var yt="ids-stream";var ht=e=>{let t=2166136261,r=-624069552;for(let n of e){let o=n.reportHubId;t^=o&255,t=Math.imul(t,16777619),t^=o>>>8&255,t=Math.imul(t,16777619),t^=o>>>16&255,t=Math.imul(t,16777619),t^=o>>>24&255,t=Math.imul(t,16777619),r^=o>>>24&255,r=Math.imul(r,16777619),r^=o>>>16&255,r=Math.imul(r,16777619),r^=o>>>8&255,r=Math.imul(r,16777619),r^=o&255,r=Math.imul(r,16777619);let a=n.businessDate;if(a===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let l=0;l<a.length;l++){let s=a.charCodeAt(l);t^=s&255,t=Math.imul(t,16777619),r^=s&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},ft=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,Dr=e=>{for(let t=1;t<e.length;t++)if(ft(e[t-1],e[t])>0)return!1;return!0},_r=(e,t)=>{let r=e.findIndex(n=>ft({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var oe=(e,t,r=console)=>{let n=o=>typeof o=="string"?[`${t} ${o}`]:[t,o];return{debug:(o,...a)=>{e<=0&&r.debug(...n(o),...a)},info:(o,...a)=>{e<=1&&r.info(...n(o),...a)},warn:(o,...a)=>{e<=2&&r.warn(...n(o),...a)},error:(o,...a)=>{e<=3&&r.error(...n(o),...a)}}};var ye=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var He=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=l=>{let s={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(i=>[i,0]))};o.set(l,s),ye(()=>{o.delete(l),s.count>0&&n(l,s)},t)};return{record:(l,s,h)=>{let i=o.get(l);if(i!==void 0){i.count+=1,i.tallies[s]+=1;return}h(),a(l)}}};var Xo=/^[1-9][0-9]*$/,Qo=/^(?:0|[1-9][0-9]*)$/,zt=e=>Number.isSafeInteger(e)&&e>0,xe=e=>{if(e===null||!Xo.test(e))return null;let t=Number(e);return zt(t)?t:null},Wt=e=>{if(e===null||!Qo.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Jt=e=>e==="true"?!0:e==="false"?!1:null,Qe=e=>e===null?!1:Jt(e),wr=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var Ir=Object.freeze({status:400,error:"Invalid form"}),xr=e=>({status:413,error:"Form too large",measuredBy:e}),Zo=(e,t,r)=>{let n=0;return e.pipeThrough(new TransformStream({transform(o,a){if(n+=o.byteLength,n>t){r(),a.error(new Error(`action form body exceeds ${t} bytes`));return}a.enqueue(o)}}))},ea=async e=>{let t=Wt(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:xr("declared")};let r=!1,n=e.body===null?null:Zo(e.body,1048576,()=>{r=!0}),o=new Headers,a=e.headers.get("Content-Type");a!==null&&o.set("Content-Type",a);let l;try{l=await new Response(n,{headers:o}).formData()}catch{return{refusal:r?xr("counted"):Ir}}let s=wr(l);return s===null?{refusal:Ir}:{fields:s}},ta=(e,t)=>{let r=e.get("intent"),n=e.get("businessDate"),o=n===null?null:Ue(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get("operationTimestamp"),l=Wt(a);if(a!==null&&l===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let s=e.get("clientTempId");if(!s)return{error:"clientTempId required"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:s,businessDate:o,operationTimestamp:l}};let h=xe(e.get("reportHubId"));if(h===null)return{error:"Invalid reportHubId"};let i={clientTempId:s,businessDate:o,operationTimestamp:l,reportHubId:h};switch(r){case"update":{let T=e.get("title"),m=e.get("content");if(T!==null&&T.length>t.titleMaxLength)return{error:"Invalid title"};let A={};return T!==null&&(A.title=T),m!==null&&(A.content=m),{command:{...i,intent:r,changes:A}}}case"publish":case"delete":return{command:{...i,intent:r}};case"toggleStar":case"toggleRead":{let T=r==="toggleStar"?"isStarred":"isRead",m=e.get(T);if(m===null)return{error:`${T} required`};let A=Jt(m);return A===null?{error:`Invalid ${T}`}:{command:{...i,intent:r,value:A}}}case"addComment":{let T=e.get("content");return T?{command:{...i,intent:r,content:T}}:{error:"Content required"}}case"deleteComment":{let T=xe(e.get("commentId"));return T===null?{error:"Invalid commentId"}:{command:{...i,intent:r,commentId:T}}}default:return{error:"Invalid intent"}}},vr=async(e,t)=>{let r=await ea(e);if("refusal"in r)return r;let n=ta(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},ra=6e4,na="form_too_large",Cr=["declared","counted"],Mr=e=>{let t=He({windowMs:ra,tallies:Cr,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Cr.map(l=>`${l}:${a[l]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(na,r,n)}};var gt=Object.freeze({"business-date":"json",[yt]:"stream",report:"json"}),Pr=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),Kt=e=>e!==void 0&&Object.hasOwn(gt,e);var Gt=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Lr=e=>Object.hasOwn(Gt,e);var oa="download",aa="thumbnail",ia="1";var Xt=e=>{let t=e.getAll(aa),r=e.getAll(oa);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Lr(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===ia?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var Zt="Cross-site request rejected",sa="Not Found",la=new Set(["same-origin","none"]),ua=new Set(["GET","HEAD","OPTIONS"]),kr=["api","action","sse","attachment"],Nr=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}}),ca=()=>Nr(403,Zt),Rt=()=>Nr(404,sa),Ze=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:ca}),Or=e=>new URL(e.url).pathname.endsWith(".data"),da=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},Br=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(ua.has(e.method)||da(e)):la.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},ma=6e4,pa="refusals",ya=32,ha=/^[a-z-]+$/,Qt=e=>{if(e===null)return"-";let t=e.slice(0,ya);return ha.test(t)&&t===e?e:JSON.stringify(t)},Ur=e=>{let t=He({windowMs:ma,tallies:kr,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${kr.map(l=>`${l}:${a[l]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${Qt(a.get("Sec-Fetch-Site"))} mode=${Qt(a.get("Sec-Fetch-Mode"))} dest=${Qt(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(pa,r,o)}};var Hr=(e,t)=>(r,n)=>{let o=n?"markAttachmentPresent":"markAttachmentMissing";e[o](r).catch(a=>{t.error(`${o} failed attachment=${r} message=${a instanceof Error?a.message:"unknown"}`)})};var fa=6e4/1e3,ga=5e3/1e3,Ra=new Map([[429,fa],[503,ga]]),Ce=e=>{let t=Ra.get(e);return t===void 0?{}:{"Retry-After":String(t)}},$r="Too many requests",ba="same-origin",Sa="SAMEORIGIN",Fe=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":ba,"X-Frame-Options":Sa}),bt=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Fe});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},qr=(e,t)=>{if(e===null)return!1;for(let r of e.split(",")){let n=r.trim();if((n.startsWith("W/")?n.slice(2):n)===t)return!0}return!1},Yr=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Aa=/^[\x20-\x7E]+$/,Ta=/^[\w.+-]+\/[\w.+-]+/,er=e=>e&&Aa.test(e)&&Ta.test(e)?e:null,Vr=e=>encodeURIComponent(e).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),jr=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),St={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},zr={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},At=e=>typeof e=="string"&&Object.hasOwn(zr,e),Tt=e=>zr[e],Ae="Attachment request failed";var Da=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,me=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Da(r)}`),$e=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`);var _a=32*1024*1024,wa=60,Ea=4,Ia=120,xa=2,Ca=8*1024*1024,ie=(e,t,r)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r)return t;throw me(e,`an integer >= ${r}`,t)},qe=(e,t,r,n)=>t===void 0?n:ie(e,t,r),Dt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),va=e=>{if(e===void 0)throw $e("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Dt(e))throw me("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw $e("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw me("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw me("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},Ma=e=>{if(e===void 0)return null;if(!Dt(e))throw me("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:va(e.renderer),rateLimitPerMinute:qe("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Ia),concurrency:qe("attachments.thumbnails.concurrency",e.concurrency,1,xa),cacheBytes:qe("attachments.thumbnails.cacheBytes",e.cacheBytes,0,Ca)})},Wr=e=>{let t=e;if(t===void 0)return null;if(!Dt(t))throw me("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw $e("attachments.idCodec","injected when attachments is given");if(!Dt(r)||typeof r.encode!="function"||typeof r.decode!="function")throw me("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw $e("attachments.read","injected when attachments is given");if(typeof n!="function")throw me("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:qe("attachments.maxBytes",t.maxBytes,1,_a),rateLimitPerMinute:qe("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,wa),concurrency:qe("attachments.concurrency",t.concurrency,1,Ea),thumbnails:Ma(t.thumbnails)})},Pa=Object.freeze([["attachmentIdCodec","attachments.idCodec"],["readAttachment","attachments.read"],["attachmentMaxBytes","attachments.maxBytes"],["attachmentRateLimitPerMinute","attachments.rateLimitPerMinute"],["attachmentConcurrency","attachments.concurrency"],["attachmentThumbnailRenderer","attachments.thumbnails.renderer"],["attachmentThumbnailRateLimitPerMinute","attachments.thumbnails.rateLimitPerMinute"],["attachmentThumbnailConcurrency","attachments.thumbnails.concurrency"],["attachmentThumbnailCacheBytes","attachments.thumbnails.cacheBytes"]]),_t=e=>{for(let[t,r]of Pa)if(Object.hasOwn(e,t))throw $e(r,`given in place of the flat key ${t}`)};var wt=e=>{let t=ie("limit",e.limit,1),r=ie("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ie("queue.max",e.queue.max,0),maxPerOwner:ie("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ie("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],l=new Map,s=new Map,h=(p,S)=>p.get(S)??0,i=(p,S,P)=>{let N=h(p,S)+P;N<=0?p.delete(S):p.set(S,N)},T=p=>h(s,p)<r,m=p=>(o+=1,i(s,p,1),f(p)),A=()=>{for(;o<t;){let p=a.findIndex(P=>T(P.owner));if(p<0)return;let[S]=a.splice(p,1);i(l,S.owner,-1),S.grant(m(S.owner))}},f=p=>{let S=!1;return()=>{S||(S=!0,o-=1,i(s,p,-1),A())}};return{acquire:(p,S)=>{if(S.aborted)return Promise.resolve(null);if(o<t&&T(p))return Promise.resolve(m(p));if(n===null||a.length>=n.max||h(l,p)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:P}=n,N=D=>{let L=()=>{let W=a.indexOf(F);W<0||(a.splice(W,1),i(l,p,-1),H(),D(null))},k=ye(L,P),H=()=>{clearTimeout(k),S.removeEventListener("abort",L)},F={owner:p,grant:W=>{H(),D(W)}};a.push(F),i(l,p,1),S.addEventListener("abort",L,{once:!0})};return new Promise(N)}}};var La=1024,ka=6e4,Na=e=>{ie("limitPerMinute",e,1);let t=new Map,r=(o,a)=>{a<=o.lastRefillMs||(o.tokens=Math.min(e,o.tokens+(a-o.lastRefillMs)*e/6e4),o.lastRefillMs=a)},n=(o,a)=>{let l=t.get(o);l&&t.delete(o);let s=l??{tokens:e,lastRefillMs:a};r(s,a),t.set(o,s);for(let h of t.keys()){if(t.size<=La)break;t.delete(h)}return s};return{consume:(o,a)=>{let l=n(o,a);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(o,a,l)=>{let s=t.get(o);s&&(r(s,a),s.tokens=Math.min(e,s.tokens+l))}}},et=e=>{let{reason:t,logger:r}=e,n=Na(e.limitPerMinute),o=e.variant===null?"":` variant=${e.variant}`,a=He({windowMs:ka,tallies:[t],writeSuppressed:(l,{count:s,since:h})=>{r.warn(`${t}_suppressed count=${s} since=${h} viewer=${l}${o}`)}});return{spend:({attachmentId:l,internalUserId:s,fail:h})=>n.consume(s,Z())?null:(a.record(s,t,()=>r.warn(`429 attachment=${l} viewer=${s}${o} reason=${t}`)),h(429,$r,Ce(429))),refund:(l,s)=>{n.refund(l,Z(),s)}}};var Oa=256*1024,Jr=6e4,Ba=e=>Math.ceil(e/2),Ua=new Uint8Array(new ArrayBuffer(0)),Ha=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Ua,t()},l=s=>{clearTimeout(o),o=ye(()=>{s.error(new Error(`attachment body idle for ${Jr} ms`)),a()},Jr)};return new ReadableStream({start(s){l(s)},pull(s){let h=Math.min(n+Oa,r.byteLength);if(h>n&&s.enqueue(r.slice(n,h)),n=h,n>=r.byteLength){s.close(),a();return}l(s)},cancel(){a()}},{highWaterMark:0})},Kr=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,l=et({reason:"rate_limit",limitPerMinute:e.rateLimitPerMinute,logger:o,variant:null}),s=wt({limit:e.concurrency,maxHeldPerOwner:Ba(e.concurrency),queue:null});return async h=>{let{request:i,delivery:T,attachmentId:m,internalUserId:A,readAttachment:f,cookie:p,fail:S}=h,P=e.maxBytes,N=l.spend(h);if(N)return N;let D=await n(i),L=await t.getAttachmentForUser(D,m,A);if(!L)return o.warn(`404 attachment=${m} viewer=${A} reason=not_visible`),S(404,"Attachment not found");if(L.fileSize!=null&&L.fileSize>P)return o.warn(`413 attachment=${m} viewer=${A} reason=db_size`),S(413,"Attachment too large");let k=await s.acquire(A,i.signal);if(!k)return i.signal.aborted?(o.info(`503 attachment=${m} viewer=${A} reason=aborted`),S(503,"Attachment request aborted")):(o.warn(`503 attachment=${m} viewer=${A} reason=concurrency`),S(503,"Too many concurrent downloads",Ce(503)));let H=!1;try{let F=await f(L.filePath,{maxBytes:P,head:i.method==="HEAD",principal:r(A),signal:i.signal});if(i.signal.aborted)return o.info(`503 attachment=${m} viewer=${A} reason=aborted`),S(503,"Attachment request aborted");if(!F.ok){if(!At(F.reason))return o.error(`500 attachment=${m} viewer=${A} reason=port_contract code=failure_reason`),S(500,Ae);let _=Tt(F.reason);return F.reason==="not_found"&&a(m,!1),o.warn(`${_} attachment=${m} viewer=${A} reason=${F.reason} code=${F.code??"-"}`),S(_,St[_],Ce(_))}if(F.bytes.byteLength>P)return o.error(`500 attachment=${m} viewer=${A} reason=port_contract code=over_max_bytes`),S(500,Ae);let W=i.method==="HEAD";if(!W&&F.size!==void 0&&F.size!==F.bytes.byteLength)return o.error(`500 attachment=${m} viewer=${A} reason=port_contract code=size_mismatch`),S(500,Ae);let ee=er(L.fileType)??er(F.contentType),z=ee!==null&&Yr.has(ee),x=z?ee:"application/octet-stream",I=z&&T.kind!=="download"?"inline":"attachment",M=W?F.size:F.bytes.byteLength,C=new Headers({"Content-Type":x,"Content-Disposition":`${I}; filename="${jr(L.fileName)}"; filename*=UTF-8''${Vr(L.fileName)}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Fe});return M!==void 0&&C.set("Content-Length",String(M)),p&&C.append("Set-Cookie",p),a(m,!0),o.info(`200 attachment=${m} viewer=${A} type=${x} disposition=${I} bytes=${M??"-"}`),W?new Response(null,{status:200,headers:C}):(H=!0,new Response(Ha(F.bytes,k),{status:200,headers:C}))}finally{H||k()}}};var se=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Xs=se.queueWaitMs+se.readMs+se.renderMs+se.transferMarginMs;var Gr=require("crypto"),Ye=e=>{let t=JSON.stringify(e);return`"${(0,Gr.createHash)("sha256").update(t).digest("hex")}"`};var Zr=require("buffer"),en=new Set([194,198,202,206]),Fa=new Set([192,193,194,195]),tn=216,$a=217,rn=218,qa=4,Ya=64,Va=2,Xr=8,Qr=28,Te=12,tr=8,ja=20,nn=Te+tr+10,za=2,be=(e,t)=>e[t]<<8|e[t+1],Ve=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},he=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},on=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,an=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),sn=e=>(e.stepsLeft-=1,e.stepsLeft>=0),ln=e=>e[0]===255&&e[1]===tn,un=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!sn(r))return null;n+=1}while(n<e.byteLength&&e[n]===255);if(n>=e.byteLength)return null;let o=e[n];if(n+=1,o===$a)return"eoi";if(o===0||o===tn)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=be(e,n),l=n+a;return a<2||l>e.byteLength?null:(r.marker=o,r.body=n+2,r.length=a,r.end=l,"segment")}},Wa=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!sn(r))return null;if(a+1>=n)return n;let l=e[a+1];if(l===255)a+=1;else if(l===0||l>=208&&l<=215){if(a+=2,a>=n||e[a]!==255)break}else return a}o=a}},cn=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=be(e,r+1),a=be(e,r+3),l=e[r+5];if(a===0||o===0||l===0||n!==8+3*l)return null;let s=[];for(let h=0;h<l;h+=1){let i=e[r+7+3*h],T=i>>4,m=i&15;if(T<1||T>4||m<1||m>4)return null;s.push({id:e[r+6+3*h],horizontal:T,vertical:m})}return{marker:t,width:a,height:o,components:s}},dn=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>qa||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},mn=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:en.has(e.marker)||t<e.components.length}),rr=e=>{if(!ln(e))return null;let t=an(e.byteLength),r=null;for(let n=2;;){if(un(e,n,t)!=="segment")return null;if(on(t.marker)){if(r!==null||(r=cn(e,t),r===null))return null}else if(t.marker===rn){if(r===null)return null;let o=dn(e,t);return o===null?null:mn(r,o.length)}n=t.end}},pn=e=>{let t=Math.max(...e.components.map(n=>n.horizontal)),r=Math.max(...e.components.map(n=>n.vertical));return e.components.map(({horizontal:n,vertical:o})=>{let a=Math.ceil(e.width*n/(t*Xr)),l=Math.ceil(e.height*o/(r*Xr));return Math.ceil(a/n)*n*Math.ceil(l/o)*o})},yn=e=>e.multiScan?pn(e).reduce((r,n)=>r+n,0)*Ya*Va:0,Ja=896,hn=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!ln(e))return null;let n=Zr.Buffer.from(e.buffer,e.byteOffset,e.byteLength),o=an(r),a=null,l=null,s=new Map,h=0,i=0,T=0;for(let m=2;;){let A=un(e,m,o);if(A===null)return null;if(A==="eoi")return l===null?null:{header:l,blockVisits:i};if(m=o.end,on(o.marker)){if(a!==null||!Fa.has(o.marker)||(a=cn(e,o),a===null))return null;let f=pn(a);s=new Map;for(let[p,S]of a.components.entries()){let P=s.get(S.id);s.set(S.id,P===void 0?f[p]:Math.max(P,f[p]))}h=a.components.length*(en.has(a.marker)?Ja:1)}else if(o.marker===rn){if(a===null||T===h)return null;let f=dn(e,o);if(f===null)return null;for(let S of f){let P=s.get(S);if(P===void 0)return null;i+=P}if(T+=1,l===null&&(l=mn(a,f.length)),i>t||!l.multiScan)return{header:l,blockVisits:i};let p=Wa(n,o.end,o);if(p===null)return null;m=p}}},fn=e=>{if(e.byteLength<24||be(e,8)!==0||be(e,10)!==13||!he(e,12,"IHDR"))return null;let t=be(e,16)*65536+be(e,18),r=be(e,20)*65536+be(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Ka=e=>{if(he(e,Te,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Ve(e,26,2)&16383,r=Ve(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(he(e,Te,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Ve(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return he(e,Te,"VP8X")?e.byteLength<nn?null:{width:Ve(e,24,3)+1,height:Ve(e,27,3)+1}:null},gn=e=>{if(fn(e)===null||e.byteLength<=Qr)return null;switch(e[Qr]){case 0:return!1;case 1:return!0;default:return null}},Rn=(e,t)=>{if(he(e,Te,"VP8 "))return"lossy";if(he(e,Te,"VP8L"))return"lossless";if(!he(e,Te,"VP8X")||e.byteLength<nn)return null;if((e[ja]&za)!==0)return"animated";let r=!1,n=t;for(let o=Te;o+tr<=e.byteLength;){if(n-=1,n<0)return null;if(he(e,o,"VP8L"))return"lossless";if(he(e,o,"VP8 "))return r?"lossy-alpha":"lossy";he(e,o,"ALPH")&&(r=!0);let a=Ve(e,o+4,4);o+=tr+a+a%2}return null},bn={png:fn,jpeg:rr,webp:Ka};var Et=Object.freeze(["image/webp","image/jpeg","image/png"]),It=1024*1024;var Ga=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Xa={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Qa=new Set(Et),Za=e=>typeof e=="string"&&Qa.has(e),ei=256,xt=(e,t)=>e.fileType===null||!Ga.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,ti=[137,80,78,71,13,10,26,10],ri=[255,216,255],ni=[[71,73,70,56,55,97],[71,73,70,56,57,97]],oi=[82,73,70,70],ai=[87,69,66,80],tt=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,o]of t.entries())if(e[r+n]!==o)return!1;return!0},nr=e=>{if(tt(e,ti,0))return"png";if(tt(e,ri,0))return"jpeg";for(let t of ni)if(tt(e,t,0))return"gif";return tt(e,oi,0)&&tt(e,ai,8)?"webp":null},Sn=e=>{let t=JSON.stringify([e.rendererId,e.box.maxWidth,e.box.maxHeight,e.attachmentId,e.filePath,e.fileType,e.fileSize]);return{key:t,etag:Ye([t])}},An=(e,t)=>{if(!Za(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>It)return"too_large";let r=Xa[e.contentType];if(nr(e.bytes)!==r)return"signature";let n=bn[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Tn=e=>{ie("maxBytes",e.maxBytes,0),ie("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=o=>{let a=t.get(o);a&&(t.delete(o),r-=a.weight)};return{get:o=>{let a=t.get(o);if(a)return t.delete(o),t.set(o,a),a.entry},set:(o,a)=>{n(o);let l=(a.kind==="thumbnail"?a.bytes.byteLength:0)+ei;if(l>e.maxBytes||e.maxEntries===0)return;let s=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:s,weight:l}),r+=l;for(let h of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(h)}}}};var or=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,l=Z(),s=new AbortController,h=!1,i,T,m=()=>{a(Z()-l)},A=k=>{i=ye(()=>{h=!0,k({timedOut:!0}),T=ye(m,t),s.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},f=new Promise(A),p=AbortSignal.any([r,s.signal]),S=k=>{k(n(p))},P=new Promise(S),N=k=>(clearTimeout(i),clearTimeout(T),h&&o(Z()-l,k.kind==="error"?{error:k.error}:null),k),D=P.then(k=>N({kind:"value",value:k}),k=>N({kind:"error",error:k}));return{outcome:Promise.race([P.then(k=>({timedOut:!1,value:k})),f]),settled:D}};var De={404:"Attachment not found",500:Ae,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Dn=(e,t)=>{if(typeof e!="object"||e===null)return{failure:{kind:"failure",status:500,reason:"port_contract",code:"result"}};let r=e;if(!r.ok)return r.reason==="unsupported"?{entry:{kind:"unrenderable",reason:"unsupported"}}:r.reason==="failed"?{failure:{kind:"failure",status:502,reason:"render_failed"}}:{failure:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"}};let n=An(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},ii=e=>{let t=new AbortController,r=()=>{t.abort()},n=ye(r,se.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},_n=()=>{},si=(e,t)=>t.aborted?Promise.resolve():new Promise(r=>{let n=()=>{t.removeEventListener("abort",n),r()};t.addEventListener("abort",n,{once:!0}),e.then(n)}),wn=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:l}=e,s=new Map,h=(f,p)=>{let S=p.then(_n,_n);s.set(f,S);let P=()=>{s.get(f)===S&&s.delete(f)};S.then(P)},i=async(f,p)=>{let S=s.get(f.key);if(S===void 0)return t.acquire(f.owner,p);let P=ii(p);try{if(await si(S,P.signal),P.signal.aborted)return null;let N=r.get(f.key);return N!==void 0?{...N,identity:"verified"}:await t.acquire(f.owner,P.signal)}finally{P.end()}},T=(f,p)=>{if(f.fileSize===null)return p.kind==="exact"?"verified":"unrecorded";if(p.kind==="exact"?p.bytes===f.fileSize:f.fileSize>p.maxBytes)return"verified";let P=p.kind==="exact"?String(p.bytes):`>${p.maxBytes}`;return l.warn(`size_mismatch expected=${f.fileSize} got=${P} attachment=${f.attachmentId} viewer=${f.owner} variant=thumbnail`),"unverified"},m=(f,p)=>(S,P)=>{let N=P===null?"":` message=${P.error instanceof Error?P.error.message:"unknown"}`;l.warn(`${f}_overrun ms=${S} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail${N}`)},A=(f,p)=>S=>{l.warn(`${f}_stuck ms=${S} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail`)};return async(f,p)=>{let S=await i(f,p);if(S===null)return{kind:"failure",status:503,reason:p.aborted?"aborted":"queue"};if(typeof S!="function")return S;let P=S,N=null;try{if(p.aborted)return{kind:"failure",status:503,reason:"aborted"};let D=r.get(f.key);if(D!==void 0)return{...D,identity:"verified"};let L=or({budgetMs:se.readMs,flightSignal:p,call:v=>f.readAttachment(f.filePath,{maxBytes:n,head:!1,principal:o(f.owner),signal:v}),onOverrun:m("read",f),onStuck:A("read",f)}),k=await L.outcome;if(k.timedOut)return N=L.settled,p.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(p.aborted)return{kind:"failure",status:503,reason:"aborted"};let H=k.value;if(!H.ok&&H.reason!=="too_large")return At(H.reason)?(H.reason==="not_found"&&a(f.attachmentId,!1),{kind:"failure",status:Tt(H.reason),reason:H.reason,code:H.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(H.ok&&H.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let F=T(f,H.ok?{kind:"exact",bytes:H.bytes.byteLength}:{kind:"over",maxBytes:n}),W=v=>{F==="verified"&&r.set(f.key,v)},ee=v=>(W(v),{...v,identity:F});if(!H.ok)return ee({kind:"unrenderable",reason:"too_large"});let z=nr(H.bytes);if(z===null)return ee({kind:"unrenderable",reason:"signature"});let x=or({budgetMs:se.renderMs,flightSignal:p,call:v=>f.renderer.render(H.bytes,{format:z,maxWidth:f.box.maxWidth,maxHeight:f.box.maxHeight,signal:v}),onOverrun:m("render",f),onStuck:A("render",f)}),I=v=>{if(v.kind==="error")return;let Y=Dn(v.value,f.box);"entry"in Y&&W(Y.entry)},M=null,C=()=>(M===null&&(M=x.settled.then(I),h(f.key,M)),M);p.addEventListener("abort",C,{once:!0});let _=await x.outcome.finally(()=>p.removeEventListener("abort",C));if(_.timedOut||p.aborted)return N=C(),p.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let $=Dn(_.value,f.box);return"entry"in $?ee($.entry):$.failure}finally{N===null?P():N.then(P,P)}}};var En=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let h=new AbortController,i=()=>{e.get(t)?.controller===h&&e.delete(t)},m={promise:n(h.signal).finally(i),controller:h,waiters:0};return e.set(t,m),m},a=e.get(t)??o();a.waiters+=1;let l=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?l():r.addEventListener("abort",l,{once:!0});let s=()=>{r.removeEventListener("abort",l)};return a.promise.finally(s)}}};var Cn=10,li=1/Cn,In=1-li,ui=1024,ci=64,di=8,xn="private, no-cache",mi="no-store",pi=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),yi=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},vn=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:l,thumbnails:s}=e,{renderer:h}=s,i=et({reason:"rate_limit",limitPerMinute:s.rateLimitPerMinute,logger:o,variant:"thumbnail"}),T=et({reason:"revalidation_rate_limit",limitPerMinute:s.rateLimitPerMinute*Cn,logger:o,variant:"thumbnail"}),m=wt({limit:s.concurrency,maxHeldPerOwner:s.concurrency,queue:{max:ci,maxPerOwner:di,maxWaitMs:se.queueWaitMs}}),A=Tn({maxBytes:s.cacheBytes,maxEntries:ui}),f=En(),p=wn({gate:m,cache:A,maxBytes:l,encodeUserId:r,recordObjectState:a,logger:o}),S=(D,L,k,H)=>{let F=`attachment=${D.attachmentId} viewer=${D.internalUserId} variant=thumbnail cache=${H}`;if(L.kind==="failure")return o[yi(L)](`${L.status} ${F} reason=${L.reason} code=${L.code??"-"}`),D.fail(L.status,De[L.status],Ce(L.status));let W=pi[L.identity];if(L.kind==="unrenderable")return o.info(`404 ${F} reason=${L.reason}${W}`),D.fail(404,De[404]);let ee=L.identity==="verified"?{"Cache-Control":xn,ETag:k}:{"Cache-Control":mi},z=new Headers({"Content-Type":L.contentType,"Content-Length":String(L.bytes.byteLength),...ee,"Content-Security-Policy":"default-src 'none'; sandbox",...Fe});return D.cookie&&z.append("Set-Cookie",D.cookie),o.info(`200 ${F} type=${L.contentType} bytes=${L.bytes.byteLength}${W}`),new Response(L.bytes,{status:200,headers:z})},P=D=>i.spend(D),N=(D,L)=>L?T.spend(D):P(D);return async(D,L)=>{let{request:k,attachmentId:H,internalUserId:F,readAttachment:W,cookie:ee,fail:z}=D,x=Gt[L],I=k.headers.get("If-None-Match"),M=I!==null,C=N(D,M);if(C)return C;let _=await n(k),$=await t.getAttachmentForUser(_,H,F),Y=$!==null&&xt($,l)?Sn({rendererId:h.id,box:x,attachmentId:H,filePath:$.filePath,fileType:$.fileType,fileSize:$.fileSize}):null;if(Y&&qr(I,Y.etag)){let ue=new Headers({"Cache-Control":xn,ETag:Y.etag,...Fe});return ee&&ue.append("Set-Cookie",ee),o.info(`304 attachment=${H} viewer=${F} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:ue})}if(M){let ue=P(D);if(ue)return ue}if(!$)return o.warn(`404 attachment=${H} viewer=${F} variant=thumbnail reason=not_visible`),z(404,De[404]);if(!Y)return i.refund(F,In),o.info(`404 attachment=${H} viewer=${F} variant=thumbnail reason=not_eligible`),z(404,De[404]);let{key:J,etag:O}=Y,X=A.get(J);if(X)return i.refund(F,In),S(D,{...X,identity:"verified"},O,"hit");let Ee=ue=>p({key:J,attachmentId:H,filePath:$.filePath,fileSize:$.fileSize,box:x,owner:F,readAttachment:W,renderer:h},ue),pe;try{pe=await f.join(J,k.signal,Ee)}catch(ue){return o.error(`500 attachment=${H} viewer=${F} variant=thumbnail cache=miss reason=port_exception message=${ue instanceof Error?ue.message:"unknown"}`),z(500,De[500])}return S(D,pe,O,"miss")}};var hi='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',fi=()=>bt(403,Zt,{cookie:null}),Mn=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=Xt(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>bt(404,St[404],{cookie:null}),crossSiteRejection:fi}),Pn=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:o,logger:a}=e,l=r.attachmentDelivery,s={service:r,encodeUserId:n,resolveViewerScope:o,logger:a,recordObjectState:Hr(r,a)},h=l===null?null:{idCodec:l.idCodec,read:l.read,serveOriginal:Kr({...s,maxBytes:l.maxBytes,rateLimitPerMinute:l.rateLimitPerMinute,concurrency:l.concurrency}),serveThumbnail:l.thumbnails===null?null:vn({...s,maxBytes:l.maxBytes,thumbnails:l.thumbnails})};return async({request:i,params:T})=>{let m=null,A=(f,p,S={})=>bt(f,p,{cookie:m,extraHeaders:S});try{let{user:f,cookie:p}=await t(i,{failureRedirect:null});if(m=p??null,!f)return A(401,"Unauthorized");let S=Xt(new URL(i.url).searchParams);if(S.kind==="invalid")return A(400,"Invalid attachment request");if(S.kind==="thumbnail"&&i.method!=="GET")return A(405,"Method not allowed",{Allow:"GET"});if(i.method!=="GET"&&i.method!=="HEAD")return A(405,"Method not allowed",{Allow:"GET, HEAD"});if(h===null)return A(404,"Attachment not found");if(T.token===void 0)throw new Error(hi);let P=h.idCodec.decode(T.token);if(P===null||!zt(P))return A(400,"Invalid attachment token");let N=await r.getUserIdByExternalId(f.id);if(!N)return A(403,"Forbidden");let D={request:i,delivery:S,attachmentId:P,internalUserId:N,readAttachment:h.read,cookie:m,fail:A};return S.kind!=="thumbnail"?await h.serveOriginal(D):h.serveThumbnail===null?A(404,De[404]):await h.serveThumbnail(D,S.variant)}catch(f){if(f instanceof Response)throw f;return a.error(`500 attachment=? viewer=? reason=unexpected message=${f instanceof Error?f.message:"unknown"}`),A(500,Ae)}}};var gi=oe(1,"[Response]"),te=(e,t,r,n=200,o=gi)=>{let a=Ye(r),l=e.headers.get("If-None-Match");o.info(`[jsonResponseWithETag] ETag: ${a}, If-None-Match: ${l}`);let s=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'",ETag:a});return t&&s.append("Set-Cookie",t),e.method==="GET"&&n===200&&l===a?new Response(null,{status:304,headers:s}):new Response(JSON.stringify(r),{status:n,headers:s})};var vt=e=>e.method==="HEAD"?AbortSignal.abort():e.signal;var Mt=30,On=4e3,Ri="stream interrupted by server error",bi=15e3,Bn=Symbol("ids-stream-heartbeat"),Ln=()=>{},Pt=e=>e.return(void 0).then(Ln,Ln),Si=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(Bn),bi)}),stop:()=>clearTimeout(e)}},Ai=/^[0-9a-f]{1,16}$/,Ti=e=>{let t=e.searchParams.get("cursor_report_hub_id"),r=e.searchParams.get("cursor_business_date"),n=e.searchParams.get("cursor_snapshot"),o=n!==null&&Ai.test(n)?n:null;if(t===null)return r===null?{cursor:null,snapshot:o}:{invalid:!0};let a=xe(t);return a===null?{invalid:!0}:r===null?{cursor:{businessDate:null,reportHubId:a},snapshot:o}:pt(r)?{cursor:{businessDate:r,reportHubId:a},snapshot:o}:{invalid:!0}};async function*kn(e,t,r,n){let o=t?_r(e,t):0,a=!0;for(;;){let l=e.slice(o,o+(a?r:On));o+=l.length;let s=o>=e.length,h=l[l.length-1];if(yield{kind:"chunk",items:l,nextCursor:s||!h?null:{businessDate:h.businessDate,reportHubId:h.reportHubId},isLast:s,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,s)return}}var Un=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform","X-Content-Type-Options":"nosniff"});return e&&t.append("Set-Cookie",e),t},Nn=(e,t,r,n)=>{let o=new TextEncoder,a=!1,l=null,s=new ReadableStream({async pull(h){if(a||r.aborted){await Pt(t);try{h.close()}catch{}return}let i=Si();try{l===null&&(l=t.next());let T=await Promise.race([l,i.fired]);if(i.stop(),T===Bn){if(a||r.aborted){await Pt(t);try{h.close()}catch{}return}h.enqueue(o.encode(`
|
|
2
|
+
`));return}l=null;let{value:m,done:A}=T;if(A){h.close();return}if(a||r.aborted){await Pt(t);try{h.close()}catch{}return}h.enqueue(o.encode(`${JSON.stringify(m)}
|
|
3
|
+
`))}catch(T){if(i.stop(),l=null,a||r.aborted)return;n.error(`ids-stream emission failed: ${T instanceof Error?T.message:String(T)}`);try{let m={kind:"error",error:Ri};h.enqueue(o.encode(`${JSON.stringify(m)}
|
|
4
|
+
`)),h.close()}catch{}}},cancel(){a=!0,Pt(t)}});return new Response(s,{status:200,headers:Un(e)})},Hn=e=>{let{service:t,logger:r}=e;return async(n,o,a,l,s)=>{let h=Ti(n);if("invalid"in h)return te(a,o,{error:{message:"Invalid cursor"}},400);let i=Qe(n.searchParams.get("forceRefresh"));if(i===null)return te(a,o,{error:{message:"Invalid forceRefresh"}},400);let T=vt(a);if(T.aborted)return new Response(null,{status:200,headers:Un(o)});let m=!1,A=null,f=null,p=new Promise((N,D)=>{A=N,f=D});p.catch(()=>{});let S=t.getDailyReportIdsByExternalId(s,l.id,{forceRefresh:i,onFetchStart:h.cursor?void 0:()=>{m=!0,t.readSseStreamAnchor().then(N=>t.getDailyReportIdsFirstPageByExternalId(s,l.id,Mt).then(D=>({items:D,streamAnchor:N}))).then(N=>A?.(N),N=>f?.(N))}});if(S.catch(()=>{}),h.cursor){let{items:N,streamAnchor:D,snapshot:L}=await S,k=h.snapshot!==null&&h.snapshot===L;return Nn(o,kn(N,k?h.cursor:null,Mt,{snapshot:L,restarted:!k,streamAnchor:D}),T,r)}let P=(async function*(){let N=await Promise.race([S.then(k=>({kind:"full",source:k}),k=>({kind:"full-error",error:k})),p.then(k=>({kind:"page",page:k}),()=>({kind:"page-error"}))]),D=null,L=!1;if(N.kind==="full")D=N.source;else if(N.kind==="page"){let{items:k,streamAnchor:H}=N.page;if(k.length<Mt){yield{kind:"chunk",items:k,nextCursor:null,isLast:!0,total:k.length,streamAnchor:H};return}yield{kind:"chunk",items:k,nextCursor:null,isLast:!1,provisional:!0},L=!0}else if(N.kind==="full-error"&&m){let k=await p.catch(()=>null);k&&k.items.length>0&&(yield{kind:"chunk",items:k.items,nextCursor:null,isLast:!1,provisional:!0})}D===null&&(D=await S),yield*kn(D.items,null,L?On:Mt,{snapshot:D.snapshot,streamAnchor:D.streamAnchor})})();return Nn(o,P,T,r)}};var ro=require("@aiquants/sse"),we=require("@aiquants/sse/server");var b=require("zod");var Fn=15e3,$n="lastEventId",Di=/^\d{1,15}-\d{1,15}$/,qn=e=>Di.test(e),_i=b.z.object({name:b.z.string().nullish(),affiliation:b.z.string().nullish()}),wi=b.z.object({name:b.z.string().nullish(),text:b.z.string().nullish(),color:b.z.string().nullish()}),Ei=b.z.object({id:b.z.number(),name:b.z.string().nullish(),color:b.z.string().nullish()}),Yn=b.z.object({id:b.z.number(),userId:b.z.string().nullish(),userName:b.z.string().nullish(),content:b.z.string().nullish(),createdAt:b.z.string().nullish(),isMine:b.z.boolean()}),Ii=b.z.object({id:b.z.string(),fileName:b.z.string(),fileType:b.z.string().nullable(),fileSize:b.z.number().nullable(),createdAt:b.z.string().nullable(),state:b.z.enum(["present","absent","unknown"]),hasThumbnail:b.z.boolean().default(!1)}),ar=b.z.object({reportHubId:b.z.number(),date:b.z.string().nullish(),createdAt:b.z.string().nullish(),author:b.z.string().nullish(),userId:b.z.string().nullish(),sourceType:b.z.string().nullish(),employeeName:b.z.string().nullish(),updatedBy:b.z.string().nullish(),updatedAt:b.z.string().nullish(),category:b.z.string().nullish(),creationCategory:b.z.string().nullish(),visitTimeFrom:b.z.string().nullish(),visitTimeTo:b.z.string().nullish(),customerName:b.z.string().nullish(),interviewers:b.z.array(_i),subject:b.z.string().nullish(),content:b.z.string().nullish(),externalComments:b.z.array(wi),isRead:b.z.boolean(),isStarred:b.z.boolean(),labels:b.z.array(Ei),postedComments:b.z.array(Yn),attachments:b.z.array(Ii).default([])}),xi=b.z.object({type:b.z.literal("connected")}),Lt=b.z.object({type:b.z.literal("status-update"),reportHubId:b.z.number(),statusType:b.z.enum(["star","read"]),value:b.z.boolean(),clientTempId:b.z.string(),recipientRawUserId:b.z.number().optional()}),ir=b.z.string().optional(),sr=b.z.object({type:b.z.literal("comment-add"),reportHubId:b.z.number(),comment:Yn,clientTempId:b.z.string(),recipientRawUserId:b.z.number().optional(),sourceType:ir}),lr=b.z.object({type:b.z.literal("comment-delete"),reportHubId:b.z.number(),commentId:b.z.number(),clientTempId:b.z.string(),recipientRawUserId:b.z.number().optional(),sourceType:ir}),ur=b.z.object({type:b.z.literal("report-create"),reportHubId:b.z.number(),report:ar,clientTempId:b.z.string(),recipientRawUserId:b.z.number().optional()}),cr=b.z.object({type:b.z.literal("report-update"),reportHubId:b.z.number(),report:ar,clientTempId:b.z.string(),recipientRawUserId:b.z.number().optional()}),dr=b.z.object({type:b.z.literal("report-publish"),reportHubId:b.z.number(),report:ar,clientTempId:b.z.string(),recipientRawUserId:b.z.number().optional()}),mr=b.z.object({type:b.z.literal("report-delete"),reportHubId:b.z.number(),clientTempId:b.z.string(),sourceType:ir}),Vn=b.z.discriminatedUnion("type",[xi,Lt,sr,lr,ur,cr,dr,mr]);var Kn=require("@aiquants/sse"),Gn=require("@aiquants/sse/shared-source");var ve="daily-report:ids:",Me="daily-report:business-date:",kt=(e,t)=>`${e}st:${t}`,pr=e=>`${ve}user:${e}:`,jn=(e,t)=>kt(pr(e),t),Ci=e=>`${Me}${e}:`,zn=(e,t)=>kt(Ci(e),t),rt=e=>`daily-report:date:${e}:user:`,je=(e,t)=>`${rt(e)}${t}:`,Wn=(e,t,r)=>kt(je(e,t),r),fe=e=>`daily-report:detail:${e}:user:`,Nt=(e,t)=>`${fe(e)}${t}:`,Jn=(e,t,r)=>kt(Nt(e,t),r);var _e=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},vi=5e3,Mi=100,ze=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=t.logger??oe(1,"[SSE Reader]"),this._source=this._createSource()}ready(){return this._position().then(()=>{})}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=null,this._source=this._createSource()}_position(){if(this._lastId!==null)return Promise.resolve(this._lastId);if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{if(t!==this._generation)throw new Error("SSE reader was destroyed while the stream tail was being read");return this._positioning=null,this._lastId=r,r},r=>{throw t===this._generation&&(this._positioning=null),r})}return this._positioning}async _readTail(){let t=await this.config.redis?.getClient();if(!t)throw new Error("Failed to get Redis client to read the SSE stream tail");let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}_createSource(){return(0,Gn.createSharedSource)({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:Kn.systemSseRuntime,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this._position(),n=await this.config.redis?.createClient();if(!n)throw new Error("Failed to create Redis client for SSE reader");n.on("error",l=>{this._logger.error("Redis client error:",l)});let o=!1,a=this._readLoop(n,t,r,()=>o);return async()=>{if(o=!0,n.isOpen)try{await n.quit()}catch{}await a}}async _readLoop(t,r,n,o){let a=n;try{for(;!o()&&t.isOpen;){let l=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:vi,COUNT:Mi});if(l)for(let s of l)for(let h of s.messages)a=h.id,this._invalidateCaches(h.message),r.next({id:h.id,message:h.message})}}catch(l){o()||(this._logger.error("xRead loop error:",l),r.fail(l instanceof Error?l:new Error(String(l))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){try{let r=t?.data?JSON.parse(t.data):null,n=r?.type;if((n==="report-create"||n==="report-delete"||n==="report-publish")&&this.config.cache.invalidatePrefix(ve),n==="comment-add"||n==="comment-delete"||n==="status-update"){let o=r?.reportHubId;typeof o=="number"&&this.config.cache.invalidatePrefix(fe(o))}}catch{}}};var ot=require("drizzle-orm");var Pi="",Li=64,ki=e=>e.toLowerCase(),Ni=e=>e.trim().toLowerCase();function Xn(e){if(e==null)return null;if(!Array.isArray(e))return new Set;let t=new Set;for(let r of e){if(typeof r!="string")continue;let n=Ni(r);n.length>0&&t.add(n)}return t}function ge(e,t){return e===null?!0:t==null?!1:e.has(ki(t))}function Pe(e){return e!==null&&e.size===0}function Zn(e,t){if(t!==null)return t.size===0?ot.sql`1 = 0`:(0,ot.inArray)(ot.sql`LOWER(${e})`,[...t])}var We,Je,nt=class nt{constructor(t,r){Vt(this,We);Vt(this,Je);jt(this,We,t),jt(this,Je,r)}get visible(){return Xe(this,We)===null?null:new Set(Xe(this,We))}get commentable(){return Xe(this,Je)===null?null:new Set(Xe(this,Je))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=Xn(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new nt(n,n);let a=Xn(o),l=new Set;for(let s of a??[])n.has(s)&&l.add(s);return new nt(n,l)}static unrestricted(t){return new nt(null,null)}};We=new WeakMap,Je=new WeakMap;var le=nt;function at(e){let t=Qn(e.visible),r=Qn(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Qn(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(Pi);if(t.length<=Li)return`s:${t}`;let r=2166136261;for(let n=0;n<t.length;n++)r^=t.charCodeAt(n),r=Math.imul(r,16777619);return`sh:${(r>>>0).toString(16)}`}var no=Object.freeze({...Ze,route:"sse",frameworkDataRefusal:Rt}),eo=864e5,Oi={baseMs:2e3,jitterMs:8e3},yr=6e4,Ot=1e3,oo=JSON.stringify({type:"connected"}),to="0-0",Bi=(e,t,r,n)=>{if(r===null&&n===null)return!0;let o=typeof t.sourceType=="string"?t.sourceType:void 0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return ge(r,e.report.sourceType);case"comment-add":case"comment-delete":return ge(n,o??"Internal");case"report-delete":return ge(r,o)}},Ui=["externalComments","postedComments"],Hi=(e,t,r)=>{if(r===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"||ge(r,e.report.sourceType))return!1;let n=t.report;for(let o of Ui)n[o]=[];return!0},Fi=(e,t)=>{e.writeEvent({event:null,id:t,data:oo})},$i=(e,t,r,n,o)=>{if(r.data)try{let a=JSON.parse(r.data),l=Vn.safeParse(a);if(!l.success){o.error("SSE message validation failed:",l.error.format());return}let s=l.data,h=typeof a.recipientRawUserId=="number"?a.recipientRawUserId:void 0;if((s.type==="status-update"||h!==void 0)&&h!==n.internalUserId||!Bi(s,a,n.visibleSet,n.commentableSet)){Fi(e,t);return}let T=Hi(s,a,n.commentableSet),m;if("recipientRawUserId"in a){let{recipientRawUserId:A,...f}=a;m=JSON.stringify(f)}else T?m=JSON.stringify(a):m=r.data;e.writeEvent({event:null,id:t,data:m})}catch(a){o.error(`[SSE:${n.internalUserId}] processEntry error:`,a)}},ao=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:l,logger:s}=e,h=async(i,T)=>{let{request:m,internalUserId:A,cursor:f}=T,p=T.initialScope.visible,S=T.initialScope.commentable,P=0,N=setInterval(()=>{let I=++P;n(m,"refresh").then(M=>{I===P&&(p=M.visible,S=M.commentable)})},yr);i.onClose(()=>clearInterval(N));let D=f===null?to:f,L=f!==null&&o!==void 0,k=[],H=null,F=I=>{_e(I.id,D)||(D=I.id,$i(i,I.id,I.message,{internalUserId:A,visibleSet:p,commentableSet:S},s))},W=async(I,M)=>{let[C]=await I.xRange(l,"-","+",{COUNT:1});return C!==void 0&&!_e(C.id,M)},ee=async(I,M)=>{if(await W(I,M))return!1;let C=M;for(;;){let _=await I.xRange(l,C,"+",{COUNT:Ot}),$=_[0];if($!==void 0&&$.id!==C&&await W(I,C))return!1;for(let Y of _){if(H!==null&&_e(H,Y.id))return!0;F(Y)}let v=_.at(-1);if(_.length<Ot||v===void 0||i.isClosed())return!0;C=v.id}},z=a.subscribe(I=>{if(!L){F(I);return}_e(I.id,D)||(H===null&&(H=I.id),k.push(I))},I=>{s.error(`[SSE:${A}] Fan-Out reader error:`,I),i.close()});if(i.onClose(z),f===null){await a.ready();try{let I=await o?.getClient();if(I){let M=await I.xRevRange(l,"+","-",{COUNT:1});M.length>0&&!_e(M[0].id,D)&&(D=M[0].id)}}catch{}}if(i.writeEvent({event:null,id:D===to?null:D,data:oo}),(0,we.startSseHeartbeat)(i,{intervalMs:Fn,retry:Oi,runtime:ro.systemSseRuntime}),f===null||o===void 0)return;await a.ready();let x=await o.getClient();if(x===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await ee(x,f)){i.writeRetry(eo),i.writeEvent({event:"resync-required",id:null,data:""}),i.close();return}L=!1;for(let I of k.splice(0))F(I)};return async({request:i,params:T})=>{let m,A=()=>{let p=new Headers;return m!==void 0&&p.append("Set-Cookie",m),p},f=p=>(0,we.terminalStreamResponse)(p,{data:"",retryMs:eo,headers:A()});try{let p=await t(i,{failureRedirect:null});m=p.cookie;let{user:S}=p;if(!S)return f("auth-required");let P=await r.getUserIdByExternalId(S.id);if(!P)return f("forbidden");if(T.endpoint!=="updates")return new Response("Not Found",{status:404,headers:A()});let N=(0,we.readLastEventId)(i,$n);if(N!==null&&!qn(N))return s.warn(`[SSE:${P}] malformed resume cursor; asking the client to resync`),f("resync-required");let D=await n(i,"initial");return(0,we.createSseResponse)({requestSignal:vt(i),headers:A(),onError:(L,k)=>s.error(`[SSE:${P}] ${k} failed:`,L),produce:L=>h(L,{request:i,internalUserId:P,cursor:N,initialScope:D})})}catch(p){if(p instanceof Response)throw p;let S=p instanceof Error?p:new Error(String(p));return s.error(`500 sse name=${S.name} message=${S.message}`),new Response("Internal Server Error",{status:500,headers:A()})}}};var qi=(e,t)=>{let r=new Headers({"Content-Type":"application/json"});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Yi=Object.freeze({...Ze,route:"api",frameworkDataRefusal:({params:e})=>Kt(e.endpoint)&>[e.endpoint]==="stream"?Rt():null}),Vi=Object.freeze({...Ze,route:"action"});function Bt(e){_t(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:l}=e,s={titleMaxLength:ie("service.titleMaxLength",r.titleMaxLength,1)},h=e.loginRedirectPath??"/auth/login",i=e.logger??oe(3,"[DailyReportAPI]"),T=e.logger??oe(3,"[DailyReportVisibility]"),m=e.logger??oe(1,"[DailyReportSSE]"),A=e.logger??oe(1,"[DailyReportAttachment]"),f=e.logger??oe(2,"[DailyReportIsolation]"),p=e.logger??oe(2,"[DailyReportAction]"),S=async(x,I="initial")=>{let M=e.resolveVisibleSourceTypes;if(!M)return le.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let C=await M(x,{reason:I});return C==null?le.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):le.restrictTo(C)}catch(C){return T.error("resolveVisibleSourceTypes threw; failing closed (deny all)",C),le.restrictTo([])}},P=async({request:x})=>{let{user:I,cookie:M}=await t(x,{failureRedirect:h}),C=new Headers;M&&C.append("Set-Cookie",M);let _=await r.getUserIdByExternalId(I.id),$=_?n(_):null;return{data:{user:I,userId:$},headers:C}},N={"business-date":async(x,I,M,C,_)=>{let $=x.searchParams.get("businessDate"),v=$===null?null:Ue($);if(v===null)return te(M,I,{error:{message:"Invalid business date"}},400);let Y=Qe(x.searchParams.get("forceRefresh"));if(Y===null)return te(M,I,{error:{message:"Invalid forceRefresh"}},400);let J=await r.getDailyReportsByBusinessDateByExternalId(_,v,C.id,{forceRefresh:Y});return te(M,I,{businessDate:v,reports:J},200)},[yt]:Hn({service:r,logger:i}),report:async(x,I,M,C,_)=>{let $=xe(x.searchParams.get("reportHubId"));if($===null)return te(M,I,{error:{message:"Invalid reportHubId"}},400);let v=Qe(x.searchParams.get("forceRefresh"));if(v===null)return te(M,I,{error:{message:"Invalid forceRefresh"}},400);let Y=await r.getDailyReportDetailByIdByExternalId(_,$,C.id,{snapshot:!0,forceRefresh:v});return Y?te(M,I,{report:Y},200):te(M,I,{error:{message:"Report not found"}},404)}},D=async({request:x,params:I})=>{let{user:M,cookie:C}=await t(x,{failureRedirect:null}),_=C??null;if(!M)return te(x,_,{error:{message:"Unauthorized"}},401);let $=I.endpoint;if(!Kt($))return te(x,_,{error:{message:"Unknown endpoint"}},404);let v=Pr[gt[$]];if(!v.includes(x.method)){let J=te(x,_,{error:{message:"Method not allowed"}},405);return J.headers.set("Allow",v.join(", ")),J}let Y=Z();try{let J=new URL(x.url),O=await S(x);return await N[$](J,_,x,M,O)}catch(J){let O=Z()-Y,X=J instanceof Error?J:new Error(String(J));return i.error(`500 endpoint=${$} elapsed=${O}ms name=${X.name} code=${"code"in X?X.code:"N/A"} message=${X.message}`),i.error("Stack:",X.stack),te(x,_,{error:{message:"Internal Server Error"}},500)}},L=Mr(p),k=async(x,I,M,C)=>{let{clientTempId:_,operationTimestamp:$}=x;if(x.intent==="create"){let O=await r.createDailyReport(I,x.businessDate,_);return C({status:"OK",intent:"create",report:O,reportHubId:String(O.reportHubId),clientTempId:_})}let{reportHubId:v,businessDate:Y}=x,J=async(O,X,Ee)=>{try{let pe=await Ee(X);return C({status:"OK",intent:O,updatedStatus:{isStarred:pe.isStarred,isRead:pe.isRead},operationTimestamp:$,reportHubId:String(v),clientTempId:_})}catch(pe){if(pe instanceof Error&&pe.message==="Not Found")return C({error:"Report not found"},{status:404});throw pe}};switch(x.intent){case"update":try{return await r.updateDailyReport(v,I,x.changes,_),C({status:"OK",intent:"update",reportHubId:String(v),clientTempId:_})}catch(O){if(O instanceof Error){if(O.message==="Unauthorized")return C({error:"Unauthorized"},{status:403});if(O.message==="Not Found")return C({error:"Report not found"},{status:404})}throw O}case"publish":try{let O=await r.publishDailyReport(v,I,_);return C({status:"OK",intent:"publish",reportHubId:String(v),clientTempId:_,report:O})}catch(O){if(O instanceof Error){if(O.message==="Unauthorized")return C({error:"Unauthorized"},{status:403});if(O.message==="Not Found")return C({error:"Report not found"},{status:404})}throw O}case"delete":try{return await r.deleteDailyReport(v,I,_),C({status:"OK",intent:"delete",reportHubId:String(v),clientTempId:_})}catch(O){if(O instanceof Error){if(O.message==="Unauthorized")return C({error:"Unauthorized"},{status:403});if(O.message==="Not Found")return C({error:"Report not found"},{status:404})}throw O}case"toggleStar":return await J("toggleStar",x.value,O=>r.setStarStatus(M,I,v,Y,O,_));case"toggleRead":return await J("toggleRead",x.value,O=>r.setReadStatus(M,I,v,Y,O,_));case"addComment":try{let O=await r.addComment(M,I,v,x.content,Y,_),X={...O,userId:O.userId};return C({status:"OK",intent:"addComment",newComment:X,reportHubId:String(v),clientTempId:_})}catch(O){if(O instanceof Error){if(O.message==="Not Found")return C({error:"Report not found"},{status:404});if(O.message.startsWith("Comments are restricted"))return C({error:"Comments are restricted for this report"},{status:403})}throw O}case"deleteComment":try{return await r.deleteComment(M,I,v,x.commentId,Y,_),C({status:"OK",reportHubId:String(v),deletedCommentId:String(x.commentId),clientTempId:_})}catch(O){if(O instanceof Error){if(O.message==="Unauthorized")return C({error:"Unauthorized"},{status:403});if(O.message==="Not Found")return C({error:"Comment not found"},{status:404})}throw O}}},H=async({request:x,params:I})=>{let{user:M,cookie:C}=await t(x,{failureRedirect:null}),_=(v,Y)=>qi(v,{...Y,setCookie:C});if(!M)return _({error:"Unauthorized"},{status:401});let $=Z();try{if(I.endpoint!=="action")return _({error:"Unknown endpoint"},{status:404});let v=await vr(x,s);if("refusal"in v){let{refusal:X}=v;return X.status===413&&L(X.measuredBy),_({error:X.error},{status:X.status})}let{command:Y}=v;if(Y.intent==="clearCache"&&!e.enableDevCacheClear)return _({error:"Invalid intent"},{status:400});let J=await r.getUserIdByExternalId(M.id);if(!J)return _({error:"User not found"},{status:404});let O=await S(x);return Y.intent==="clearCache"?(await r.clearCache(),_({status:"OK",intent:"clearCache"})):await k(Y,J,O,_)}catch(v){if(v instanceof Response)throw v;let Y=Z()-$,J=v instanceof Error?v:new Error(String(v));return i.error(`500 action elapsed=${Y}ms name=${J.name} message=${J.message}`),i.error("Stack:",J.stack),_({error:"Internal Server Error"},{status:500})}},F=ao({authenticate:t,service:r,resolveViewerScope:S,redis:o,sseReader:a,streamKey:l,logger:m}),W=Pn({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:S,logger:A}),ee=Ur(f),z=(x,I)=>async M=>{let C=Or(M.request)?x.frameworkDataRefusal(M):null;if(C!==null)throw C;return Br(M.request,x)?(ee(x.route,M.request),x.crossSiteRejection()):I(M)};return{index:{loader:P},api:{loader:z(Yi,D),action:z(Vi,H)},sse:{loader:z(no,F)},attachment:{loader:z(Mn,W)}}}var lo=require("@aiquants/mssql"),u=require("drizzle-orm");var Le=e=>(0,u.getColumns)(e),io=ht([]),ae=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),l=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${l}`;let s=String(r.getHours()).padStart(2,"0"),h=String(r.getMinutes()).padStart(2,"0"),i=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${l} ${s}:${h}:${i}`},zi=e=>{let{length:t}=e;if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=1)return t;throw me("tables.hub.title","a character column with a declared length",t)},so=e=>e===""?null:e;function Ut(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:l,cache:s,epochs:h}=e,{hub:i,internal:T,comment:m,label:A,hubLabel:f,userStatus:p}=r,S=e.externalSources??[],P=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],N=P[0]??"\u4E0B\u66F8\u304D",D=e.logger??oe(1,"[DailyReportService]");_t(e);let L=Wr(e.attachments),k=zi(i.title),H=d=>(0,lo.runWithTransactionRetry)(c=>t.transaction(y=>c(()=>d(y))),e.transactionRetry),F=e.idsTtlMs??18e4,W="daily-report:ids:epoch",ee=e.businessDateTtlMs??3e5,z="daily-report:date-epoch:",x="daily-report:detail-epoch:",M=`${e.streamKey??"daily-report:sse-stream"}:v2`,C=e.streamMaxLen??1e4,_=d=>h.incrementEpoch(d),$=d=>Zn(i.sourceType,d),v=async(d,c)=>{let y=await l?.getClient();if(!y){D.warn(`[SSE] Redis client unavailable (${c})`);return}let R=JSON.stringify(d),E=Buffer.byteLength(R);if(E>6356992){D.warn(`[SSE] Event too large (${c}): ${E} bytes > ${6356992}; not published`);return}let B=Z();try{await y.xAdd(M,"*",{data:R},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:C}});let w=Z()-B;w>1e3&&D.warn(`[SSE] Slow publish (${c}): ${w}ms`)}catch(w){D.error(`[SSE] Redis publish failed (${c}):`,w)}},Y=async()=>{try{let d=await l?.getClient();if(d===void 0)return null;let[c]=await d.xRevRange(M,"+","-",{COUNT:1});return c===void 0?null:c.id}catch(d){return D.error("[DailyReportService] SSE stream anchor read failed",d),null}},J=d=>d==null||d===""?null:/^\d+$/.test(d)?a(Number(d)):d,O=()=>{let d={};for(let c of S)d[`ext_${c.sourceType}`]=Le(c.table);return d},X=d=>{let c=d;for(let y of S)c=c.leftJoin(y.table,(0,u.and)((0,u.eq)(i.sourceType,y.sourceType),(0,u.eq)(i.sourceIdNum,y.idColumn)));return c},Ee=(d,c,y)=>{let{hub:R,internal:E}=c,B=R.summary,w=[],U=null,q=null,V=null,K=null,G=null,ce=null,Ne=[],Se=S.find(j=>j.sourceType===R.sourceType),Oe=Se?c[`ext_${Se.sourceType}`]:void 0;if(Se&&Oe){let j=Se.mapRow(Oe);j.content!==void 0&&(B=j.content),j.employeeName!==void 0&&(ce=j.employeeName),j.category!==void 0&&(U=j.category),j.creationCategory!==void 0&&(q=j.creationCategory),j.visitTimeFrom!==void 0&&(V=j.visitTimeFrom),j.visitTimeTo!==void 0&&(K=j.visitTimeTo),j.customerName!==void 0&&(G=j.customerName),j.interviewers!==void 0&&(w=j.interviewers),j.externalComments!==void 0&&(Ne=j.externalComments)}else R.sourceType==="Internal"&&E&&(B=E.body);let Re=(c.labels??[]).map(j=>({id:j.id,name:j.name,color:j.color})),re=c.postedCommentRows??[],Q=ge(d.commentable,R.sourceType),ne=q?P.includes(q):!1,qt=ke?.[0]??null;return ne&&qt&&!Re.some(j=>j.id===qt)&&Re.push({id:qt,name:N,color:null}),{reportHubId:R.id,date:ae(R.businessDate,"YYYY-MM-DD"),author:c.creatorName??J(R.createdBy)??"",userId:R.userId?a(R.userId):"",sourceType:R.sourceType??"Internal",createdAt:ae(R.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:ae(R.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:J(R.updatedBy),employeeName:ce??c.creatorName??J(R.createdBy),category:U,creationCategory:q,visitTimeFrom:V,visitTimeTo:K,customerName:G,interviewers:w,subject:R.title,content:B,externalComments:Q?Ne:[],isRead:c.isRead??!1,isStarred:c.isStarred??!1,labels:Re,postedComments:re.filter(j=>Q||y!==void 0&&j.userId===y).map(j=>({...j,userId:a(j.userId),isMine:y?j.userId===y:!1})),attachments:c.attachments}},pe=async(d,c)=>{let y=(0,u.aliasedTable)(f,"draft_label"),R=await Ie();return(await t.select({reportHubId:i.id,businessDate:i.businessDate,sourceType:i.sourceType}).from(i).leftJoin(y,(0,u.and)((0,u.eq)(y.hubId,i.id),(0,u.inArray)(y.labelId,R))).where((0,u.and)((0,u.isNull)(i.deletedAt),(0,u.or)((0,u.eq)(i.userId,c),(0,u.isNull)(i.userId),(0,u.isNull)(y.hubId)),$(d.visible))).orderBy((0,u.desc)(i.businessDate),(0,u.desc)(i.id))).map(B=>({...B,businessDate:ae(B.businessDate,"YYYY-MM-DD")}))},ue=async(d,c,y)=>{let R=await Ke(c);if(!R)return[];if(Pe(d.visible))return[];let E=(0,u.aliasedTable)(f,"draft_label"),B=await Ie();return(await t.select({reportHubId:i.id,businessDate:i.businessDate,sourceType:i.sourceType}).top(y).from(i).leftJoin(E,(0,u.and)((0,u.eq)(E.hubId,i.id),(0,u.inArray)(E.labelId,B))).where((0,u.and)((0,u.isNull)(i.deletedAt),(0,u.or)((0,u.eq)(i.userId,R),(0,u.isNull)(i.userId),(0,u.isNull)(E.hubId)),$(d.visible))).orderBy((0,u.desc)(i.businessDate),(0,u.desc)(i.id))).map(U=>({...U,businessDate:ae(U.businessDate,"YYYY-MM-DD")}))},Io=async(d,c)=>{let y=await X(t.select({hub:Le(i),internal:Le(T),creatorName:n.displayName,...O()}).from(i)).leftJoin(T,(0,u.eq)(i.id,T.hubId)).leftJoin(n,(0,u.eq)(i.userId,n.id)).where((0,u.and)((0,u.eq)(i.businessDate,u.sql`${c}`),(0,u.isNull)(i.deletedAt),$(d.visible))).orderBy((0,u.desc)(i.id)),R=await ct(y.map(E=>E.hub.id));return y.map(E=>Ee(d,{...E,attachments:R.get(E.hub.id)??[]}))},lt=new Map,Ke=async d=>{if(!e.disableUserIdCache&<.has(d))return lt.get(d)??null;let c=await o(d);return c!==null&&!e.disableUserIdCache&<.set(d,c),c},xo=async(d,c,{forceRefresh:y=!1,snapshot:R=!1,ttlMsOverride:E,onFetchStart:B}={})=>{let w=await Ke(c);if(!w)return{items:[],streamAnchor:null,snapshot:io};if(Pe(d.visible))return{items:[],streamAnchor:await Y(),snapshot:io};let U=jn(w,at(d)),[q]=await s.getOrFetch({cacheKey:U,fetcher:async()=>{let V=await Y(),K=await pe(d,w);if(!Dr(K)){D.warn("[DailyReportService] ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let G=[...K].sort(ft);return[{items:G,streamAnchor:V,snapshot:ht(G)}]}return[{items:K,streamAnchor:V,snapshot:ht(K)}]},onFetchStart:B,forceRefresh:y,snapshot:R,ttlMsOverride:E??F,epochKey:W,refreshAheadRatio:.5});if(q===void 0)throw new Error("[DailyReportService] ids cache returned no record");return q},Co=(d,c,{forceRefresh:y=!1,snapshot:R=!1,ttlMsOverride:E}={})=>{let B=de(c);return B?Pe(d.visible)?Promise.resolve([]):s.getOrFetch({cacheKey:zn(B,at(d)),fetcher:()=>Io(d,B),forceRefresh:y,snapshot:R,ttlMsOverride:E??ee}):Promise.resolve([])},ke=null,ut=async()=>(ke!==null||(ke=(await t.select({id:A.id}).from(A).where((0,u.inArray)(A.name,P)).orderBy(A.id)).map(c=>c.id)),ke),Ie=async()=>{let d=await ut();return d.length>0?d:[-1]},Ht=async()=>{let d=await ut();if(d.length===0)return null;let[c]=await t.select({id:A.id}).top(1).from(A).where((0,u.eq)(A.name,N));return c?.id??d[0]},vo=(d,c)=>c!=null?"absent":d!=null?"present":"unknown",ct=async d=>{let c=new Map,y=r.attachment;if(d.length===0||!y||L===null)return c;let R=L.idCodec,E=L.thumbnails!==null,B=await t.select({id:y.id,hubId:y.hubId,fileName:y.fileName,fileType:y.fileType,fileSize:y.fileSize,createdAt:y.createdAt,objectCheckedAt:y.objectCheckedAt,objectMissingAt:y.objectMissingAt}).from(y).where((0,u.inArray)(y.hubId,d)).orderBy((0,u.asc)(y.createdAt),(0,u.asc)(y.id));for(let w of B){let U=w.fileType?String(w.fileType):null,q=w.fileSize!=null?Number(w.fileSize):null,V=vo(w.objectCheckedAt,w.objectMissingAt),K={id:R.encode(Number(w.id)),fileName:String(w.fileName),fileType:U,fileSize:q,createdAt:ae(w.createdAt,"YYYY-MM-DD HH:mm:ss"),state:V,hasThumbnail:E&&V!=="absent"&&xt({fileType:U,fileSize:q},L.maxBytes)},G=c.get(Number(w.hubId));G?G.push(K):c.set(Number(w.hubId),[K])}return c},Mo=async(d,c,y)=>{let R=r.attachment;if(!R||Pe(d.visible))return null;let E=await Ie(),B=(0,u.aliasedTable)(f,"draft_label");return(await t.select({fileName:R.fileName,filePath:R.filePath,fileType:R.fileType,fileSize:R.fileSize}).top(1).from(R).innerJoin(i,(0,u.eq)(i.id,R.hubId)).leftJoin(B,(0,u.and)((0,u.eq)(B.hubId,i.id),(0,u.inArray)(B.labelId,E))).where((0,u.and)((0,u.eq)(R.id,c),(0,u.isNull)(i.deletedAt),(0,u.or)((0,u.eq)(i.userId,y),(0,u.isNull)(B.hubId)),$(d.visible))))[0]??null},Po=async d=>{let c=r.attachment;if(!c)return;let y=new Date;try{await t.update(c).set({objectCheckedAt:y,objectMissingAt:y,updatedAt:y}).where((0,u.eq)(c.id,d))}catch(R){D.error("markAttachmentMissing failed",R)}},Lo=async d=>{let c=r.attachment;if(!c)return;let y=new Date;try{await t.update(c).set({objectCheckedAt:y,objectMissingAt:null,updatedAt:y}).where((0,u.eq)(c.id,d))}catch(R){D.error("markAttachmentPresent failed",R)}},ko=async(d,c,y,{forceRefresh:R=!1,snapshot:E=!1,ttlMsOverride:B}={})=>{let w=await Ke(y);if(!w)return[];let U=de(c);if(!U)return[];if(Pe(d.visible))return[];let q=Wn(U,w,at(d));return s.getOrFetch({cacheKey:q,fetcher:async()=>{let V=await Ie(),K=(0,u.aliasedTable)(f,"draft_label"),G=await X(t.select({hub:Le(i),internal:Le(T),isRead:p.isRead,isStarred:p.isStarred,creatorName:n.displayName,...O()}).from(i)).leftJoin(T,(0,u.eq)(i.id,T.hubId)).leftJoin(p,(0,u.and)((0,u.eq)(i.id,p.hubId),(0,u.eq)(p.userId,w))).leftJoin(K,(0,u.and)((0,u.eq)(K.hubId,i.id),(0,u.inArray)(K.labelId,V))).leftJoin(n,(0,u.eq)(i.userId,n.id)).where((0,u.and)((0,u.eq)(i.businessDate,u.sql`${U}`),(0,u.isNull)(i.deletedAt),(0,u.or)((0,u.eq)(i.userId,w),(0,u.isNull)(K.hubId)),$(d.visible))).orderBy((0,u.desc)(i.id));if(G.length===0)return[];let ce=G.map(Q=>Q.hub.id),Ne=await t.select({hubId:f.hubId,id:A.id,name:A.name,color:A.color}).from(f).innerJoin(A,(0,u.eq)(f.labelId,A.id)).where((0,u.inArray)(f.hubId,ce)),Se=await t.select({hubId:m.hubId,id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,(0,u.eq)(m.userId,n.id)).where((0,u.inArray)(m.hubId,ce)).orderBy((0,u.asc)(m.createdAt)),Oe=await ct(ce),Re=new Map,re=new Map;for(let Q of Ne){let ne=Re.get(Q.hubId);ne||(ne=[],Re.set(Q.hubId,ne)),ne.push({id:Q.id,name:Q.name,color:Q.color})}for(let Q of Se){let ne=re.get(Q.hubId);ne||(ne=[],re.set(Q.hubId,ne)),ne.push({id:Q.id,content:Q.body,createdAt:ae(Q.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Q.userId,userName:Q.userName||""})}return G.map(Q=>{let ne=Q.hub.id;return Ee(d,{...Q,attachments:Oe.get(ne)??[],labels:Re.get(ne)||[],postedCommentRows:re.get(ne)||[]},w)})},forceRefresh:R,snapshot:E,ttlMsOverride:B??ee,epochKey:`${z}${U}`})},Ge=async(d,c,y,{forceRefresh:R=!1,snapshot:E=!1,ttlMsOverride:B}={})=>{if(Pe(d.visible))return null;let w=Jn(c,y,at(d));return(await s.getOrFetch({cacheKey:w,fetcher:async()=>{let q=await Ie(),V=(0,u.aliasedTable)(f,"draft_label"),K=await X(t.select({hub:Le(i),internal:Le(T),isRead:p.isRead,isStarred:p.isStarred,creatorName:n.displayName,...O()}).from(i)).leftJoin(T,(0,u.eq)(i.id,T.hubId)).leftJoin(p,(0,u.and)((0,u.eq)(i.id,p.hubId),(0,u.eq)(p.userId,y))).leftJoin(V,(0,u.and)((0,u.eq)(V.hubId,i.id),(0,u.inArray)(V.labelId,q))).leftJoin(n,(0,u.eq)(i.userId,n.id)).where((0,u.and)((0,u.eq)(i.id,c),(0,u.isNull)(i.deletedAt),(0,u.or)((0,u.eq)(i.userId,y),(0,u.isNull)(V.hubId)),$(d.visible)));if(K.length===0)return[];let G=K[0].hub.id,ce=await t.select({id:A.id,name:A.name,color:A.color}).from(f).innerJoin(A,(0,u.eq)(f.labelId,A.id)).where((0,u.eq)(f.hubId,G)),Ne=await t.select({id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,(0,u.eq)(m.userId,n.id)).where((0,u.eq)(m.hubId,G)).orderBy((0,u.asc)(m.createdAt)),Se=await ct([G]),Oe=ce.map(re=>({id:re.id,name:re.name,color:re.color})),Re=Ne.map(re=>({id:re.id,content:re.body,createdAt:ae(re.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:re.userId,userName:re.userName||""}));return[Ee(d,{...K[0],attachments:Se.get(G)??[],labels:Oe,postedCommentRows:Re},y)]},forceRefresh:R,snapshot:E,ttlMsOverride:B??ee,epochKey:`${x}${c}`}))[0]??null},No=async(d,c,y,R={})=>{let E=await Ke(y);return E?Ge(d,c,E,R):null},Oo=async(d,c)=>{let y=await Ie(),R=(0,u.aliasedTable)(f,"draft_label"),[E]=await t.select({sourceType:i.sourceType,deletedAt:i.deletedAt}).top(1).from(i).leftJoin(R,(0,u.and)((0,u.eq)(R.hubId,i.id),(0,u.inArray)(R.labelId,y))).where((0,u.and)((0,u.eq)(i.id,d),(0,u.or)((0,u.eq)(i.userId,c),(0,u.isNull)(R.hubId))));return E??null},Ft=async(d,c,y)=>{let R=await Oo(c,y);if(!R||R.deletedAt||!ge(d.visible,R.sourceType))throw new Error("Not Found")},Bo=async(d,c,y,R,E,B)=>{await Ft(d,y,c);let w=await t.select().top(1).from(p).where((0,u.and)((0,u.eq)(p.hubId,y),(0,u.eq)(p.userId,c))),U;if(w.length>0?w[0].isStarred!==E?U=(await t.update(p).set({isStarred:E,updatedAt:new Date,updatedBy:String(c)}).output().where((0,u.and)((0,u.eq)(p.hubId,y),(0,u.eq)(p.userId,c))))[0]:U=w[0]:U=(await t.insert(p).output().values({hubId:y,userId:c,isStarred:E,isRead:!1,createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)}))[0],R){let q=de(R);q&&(s.invalidatePrefix(je(q,c)),await _(`${z}${q}`))}return s.invalidatePrefix(Nt(y,c)),await _(`${x}${y}`),await v(Lt.parse({type:"status-update",reportHubId:y,recipientRawUserId:c,statusType:"star",value:E,clientTempId:B}),"setStarStatus"),U},Uo=async(d,c,y,R,E,B)=>{await Ft(d,y,c);let w=await t.select().top(1).from(p).where((0,u.and)((0,u.eq)(p.hubId,y),(0,u.eq)(p.userId,c))),U;if(w.length>0?w[0].isRead!==E?U=(await t.update(p).set({isRead:E,updatedAt:new Date,updatedBy:String(c)}).output().where((0,u.and)((0,u.eq)(p.hubId,y),(0,u.eq)(p.userId,c))))[0]:U=w[0]:U=(await t.insert(p).output().values({hubId:y,userId:c,isRead:E,isStarred:!1,createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)}))[0],R){let q=de(R);q&&(s.invalidatePrefix(je(q,c)),await _(`${z}${q}`))}return s.invalidatePrefix(Nt(y,c)),await _(`${x}${y}`),await v(Lt.parse({type:"status-update",reportHubId:y,recipientRawUserId:c,statusType:"read",value:E,clientTempId:B}),"setReadStatus"),U},gr=async(d,c)=>{if(c===null)return;let y=await Ie(),[R]=await t.select({hubId:f.hubId}).top(1).from(f).where((0,u.and)((0,u.eq)(f.hubId,d),(0,u.inArray)(f.labelId,y)));return R?c:void 0},Ho=async(d,c,y,R,E,B)=>{let[w]=await t.select({sourceType:i.sourceType,deletedAt:i.deletedAt,userId:i.userId}).top(1).from(i).where((0,u.eq)(i.id,y));if(!w||w.deletedAt)throw new Error("Not Found");if(await Ft(d,y,c),!ge(d.commentable,w.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(w.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let U=await gr(y,w.userId),[q]=await t.insert(m).output().values({hubId:y,userId:c,body:R,createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)}),[V]=await t.select({displayName:n.displayName}).top(1).from(n).where((0,u.eq)(n.id,c)),K=V?.displayName??"";if(E){let ce=de(E);ce&&(s.invalidatePrefix(rt(ce)),await _(`${z}${ce}`))}s.invalidatePrefix(fe(y)),await _(`${x}${y}`);let G={id:q.id,userId:a(q.userId),userName:K,content:q.body,createdAt:ae(q.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await v(sr.parse({type:"comment-add",reportHubId:y,comment:G,clientTempId:B,recipientRawUserId:U,sourceType:w.sourceType}),"addComment"),G},Fo=async(d,c)=>await d.select().top(1).from(m).where((0,u.eq)(m.id,c)),$o=async(d,c,y,R,E,B)=>{let w=await Fo(t,R);if(w.length===0)throw new Error("Not Found");if(w[0].hubId!==y)throw new Error("Not Found");let[U]=await t.select({userId:i.userId,sourceType:i.sourceType}).top(1).from(i).where((0,u.eq)(i.id,w[0].hubId));if(!(U&&ge(d.visible,U.sourceType)))throw new Error("Not Found");if(w[0].userId!==c)throw new Error("Unauthorized");let q=await gr(y,U.userId);if(await t.delete(m).where((0,u.eq)(m.id,R)),E){let V=de(E);V&&(s.invalidatePrefix(rt(V)),await _(`${z}${V}`))}s.invalidatePrefix(fe(y)),await _(`${x}${y}`),await v(lr.parse({type:"comment-delete",reportHubId:y,commentId:R,clientTempId:B,recipientRawUserId:q,sourceType:U?.sourceType}),"deleteComment")},qo=async(d,c,y)=>{if(!pt(c))throw me("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",c);D.info("createDailyReport called",{userId:d,businessDate:c});let[R]=await t.select({displayName:n.displayName}).from(n).where((0,u.eq)(n.id,d)),E=R?.displayName??a(d);try{let B=await H(async U=>{D.info("Starting transaction");let q=`internal-temp-${Date.now()}-${Math.random()}`,[V]=await U.insert(i).output().values({sourceType:"Internal",sourceId:q,businessDate:new Date(`${c}T00:00:00Z`),userId:d,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)});await U.update(i).set({sourceId:String(V.id)}).where((0,u.eq)(i.id,V.id)),D.info("Hub created",V),await U.insert(T).values({hubId:V.id,body:"",createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)}),D.info("Internal created"),D.info("Calling getDraftLabelId");let K=await Ht();D.info("draftLabelId",K);let G=[];return K&&(await U.insert(f).values({hubId:V.id,labelId:K,createdAt:new Date,createdBy:String(d)}),G.push({id:K,name:N,color:null})),D.info("Label assigned"),{reportHubId:V.id,date:c,createdAt:ae(V.createdAt,"YYYY-MM-DD HH:mm:ss"),author:E,userId:a(d),sourceType:"Internal",employeeName:E,updatedBy:a(d),updatedAt:ae(V.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:V.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:G,postedComments:[],attachments:[]}});s.invalidatePrefix(je(c,d)),s.invalidatePrefix(Me),s.invalidatePrefix(pr(d)),await _(W),await _(`${z}${c}`);let w=await Ge(le.unrestricted("post-write self read: the writer always sees the row they just wrote"),B.reportHubId,d,{forceRefresh:!0});if(w){let U=await ut(),q=w.labels.some(V=>U.includes(V.id));await v(ur.parse({type:"report-create",reportHubId:w.reportHubId,report:w,clientTempId:y,recipientRawUserId:q?d:void 0}),"createDailyReport")}return w??B}catch(B){throw D.error("Error in createDailyReport",B),B}},dt=async(d,c)=>await d.select().top(1).from(i).where((0,u.eq)(i.id,c)),$t=async(d,c,y)=>{await d.update(i).set(y).where((0,u.eq)(i.id,c))},Rr=async(d,c,y)=>{await d.update(T).set(y).where((0,u.eq)(T.hubId,c))},br=async(d,c,y)=>{await d.delete(f).where((0,u.and)((0,u.eq)(f.hubId,c),(0,u.eq)(f.labelId,y)))};return{streamKey:M,streamMaxLen:C,attachmentDelivery:L,titleMaxLength:k,clearCache:async()=>{s.clearAll(),lt.clear(),ke=null,h&&await _(W),D.info("[DailyReportService] Server-side DB/SQL caches cleared successfully.")},invalidateHubReadCaches:async(d,c)=>{s.invalidatePrefix(Me),s.invalidatePrefix(ve),await _(W);for(let y of new Set(d))s.invalidatePrefix(fe(y)),await _(`${x}${y}`);for(let y of new Set(c)){let R=de(y);R&&await _(`${z}${R}`)}},getUserIdByExternalId:Ke,getDailyReportIdsByExternalId:xo,getDailyReportIdsFirstPageByExternalId:ue,readSseStreamAnchor:Y,getDailyReportsByBusinessDate:Co,getDailyReportsByBusinessDateByExternalId:ko,getDailyReportDetailById:Ge,getDailyReportDetailByIdByExternalId:No,getDraftLabelId:Ht,getAttachmentsByHubIds:ct,getAttachmentForUser:Mo,markAttachmentMissing:Po,markAttachmentPresent:Lo,setStarStatus:Bo,setReadStatus:Uo,addComment:Ho,deleteComment:$o,createDailyReport:qo,updateDailyReport:async(d,c,y,R)=>{let E=await dt(t,d);if(!E.length||E[0].deletedAt)throw new Error("Not Found");if(E[0].userId!==c)throw new Error("Unauthorized");await H(async U=>{y.title!==void 0&&await $t(U,d,{title:so(y.title),updatedAt:new Date,updatedBy:String(c)}),y.content!==void 0&&await Rr(U,d,{body:so(y.content),updatedAt:new Date,updatedBy:String(c)})}),s.invalidatePrefix(fe(d)),s.invalidatePrefix(Me),await _(`${x}${d}`);let B=de(ae(E[0].businessDate,"YYYY-MM-DD"));B&&(s.invalidatePrefix(rt(B)),await _(`${z}${B}`));let w=await Ge(le.unrestricted("post-write self read: the writer always sees the row they just wrote"),d,c,{forceRefresh:!0});if(w){let U=await ut(),q=w.labels.some(V=>U.includes(V.id));await v(cr.parse({type:"report-update",reportHubId:w.reportHubId,report:w,clientTempId:R,recipientRawUserId:q?c:void 0}),"updateDailyReport")}},publishDailyReport:async(d,c,y)=>{let R=await dt(t,d);if(!R.length)throw new Error("Not Found");if(R[0].userId!==c)throw new Error("Unauthorized");let E=await Ht();if(!E)return null;if(await br(t,d,E),s.invalidatePrefix(fe(d)),s.invalidatePrefix(Me),s.invalidatePrefix(ve),await _(W),R[0].businessDate){let U=de(ae(R[0].businessDate,"YYYY-MM-DD"));U&&await _(`${z}${U}`)}let B=de(ae(R[0].businessDate,"YYYY-MM-DD"));B&&s.invalidatePrefix(je(B,c));let w=await Ge(le.unrestricted("post-write self read: the writer always sees the row they just wrote"),d,c,{forceRefresh:!0});return w&&await v(dr.parse({type:"report-publish",reportHubId:w.reportHubId,report:w,clientTempId:y}),"publishDailyReport"),w??null},deleteDailyReport:async(d,c,y)=>{let R=await dt(t,d);if(!R.length||R[0].deletedAt)throw new Error("Not Found");if(R[0].userId!==c)throw new Error("Unauthorized");if(await $t(t,d,{deletedAt:new Date,deletedBy:String(c),updatedAt:new Date,updatedBy:String(c)}),s.invalidatePrefix(fe(d)),s.invalidatePrefix(Me),s.invalidatePrefix(ve),await _(W),R[0].businessDate){let E=de(ae(R[0].businessDate,"YYYY-MM-DD"));E&&await _(`${z}${E}`)}await v(mr.parse({type:"report-delete",reportHubId:d,clientTempId:y,sourceType:R[0].sourceType}),"deleteDailyReport")},findDailyReportHubById:dt,updateDailyReportHub:$t,updateDailyReportInternal:Rr,deleteDailyReportLabel:br}}var Wi=oe(1,"[DailyReportExternalSource]"),uo=(e,t,r,n=Wi)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(n.warn(`Unexpected ${t} format: not an array`),[])}catch(o){return n.warn(`Failed to parse ${t}:`,o),[]}};var it=require("drizzle-orm"),g=require("drizzle-orm/mssql-core");function co(e,t){let r=(0,g.mssqlSchema)(e),n=t.userTable,o=r.table("DailyReportHub",{id:(0,g.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,g.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,g.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,g.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(it.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,g.date)("business_date"),userId:(0,g.bigint)("user_id",{mode:"number"}),title:(0,g.nvarchar)("title",{length:200}),summary:(0,g.nvarchar)("summary",{length:"max"}),createdAt:(0,g.datetime2)("created_at").notNull(),createdBy:(0,g.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,g.datetime2)("updated_at").notNull(),updatedBy:(0,g.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,g.datetime2)("deleted_at"),deletedBy:(0,g.nvarchar)("deleted_by",{length:50})},m=>[(0,g.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[m.id]}),(0,g.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),(0,g.index)(`${e}_DailyReportHub_business_date_index`).on(m.businessDate),(0,g.index)(`${e}_DailyReportHub_updated_at_index`).on(m.updatedAt),(0,g.index)(`${e}_DailyReportHub_source_index`).on(m.sourceType,m.sourceId),(0,g.index)(`${e}_DailyReportHub_user_id_index`).on(m.userId),(0,g.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,it.desc)(m.businessDate),(0,it.desc)(m.id)),(0,g.index)(`${e}_DailyReportHub_deleted_at_index`).on(m.deletedAt)]),a=r.table("DailyReportInternal",{hubId:(0,g.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,g.nvarchar)("body",{length:"max"}),metadata:(0,g.nvarchar)("metadata",{length:"max"}),createdAt:(0,g.datetime2)("created_at").notNull(),createdBy:(0,g.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,g.datetime2)("updated_at").notNull(),updatedBy:(0,g.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,g.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[m.hubId]}),(0,g.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]})]),l=r.table("DailyReportComment",{id:(0,g.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,g.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,g.bigint)("user_id",{mode:"number"}).notNull(),body:(0,g.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,g.datetime2)("created_at").notNull(),createdBy:(0,g.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,g.datetime2)("updated_at").notNull(),updatedBy:(0,g.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,g.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[m.id]}),(0,g.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,g.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),(0,g.index)(`${e}_DailyReportComment_hub_id_index`).on(m.hubId)]),s=r.table("DailyReportLabel",{id:(0,g.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,g.bigint)("user_id",{mode:"number"}),name:(0,g.nvarchar)("name",{length:50}).notNull(),color:(0,g.nvarchar)("color",{length:20}),sortOrder:(0,g.int)("sort_order"),createdAt:(0,g.datetime2)("created_at").notNull(),createdBy:(0,g.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,g.datetime2)("updated_at").notNull(),updatedBy:(0,g.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,g.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[m.id]}),(0,g.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),h=r.table("DailyReportHub_Label",{hubId:(0,g.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,g.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,g.datetime2)("created_at").notNull(),createdBy:(0,g.nvarchar)("created_by",{length:50}).notNull()},m=>[(0,g.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[m.hubId,m.labelId]}),(0,g.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,g.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[m.labelId],foreignColumns:[s.id]})]),i=r.table("DailyReportUserStatus",{hubId:(0,g.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,g.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,g.bit)("is_read").default(!1).notNull(),isStarred:(0,g.bit)("is_starred").default(!1).notNull(),createdAt:(0,g.datetime2)("created_at").notNull(),createdBy:(0,g.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,g.datetime2)("updated_at").notNull(),updatedBy:(0,g.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,g.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[m.hubId,m.userId]}),(0,g.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,g.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),T=r.table("DailyReportAttachment",{id:(0,g.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,g.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,g.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,g.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,g.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,g.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,g.nvarchar)("file_type",{length:100}),fileSize:(0,g.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,g.datetime2)("object_checked_at"),objectMissingAt:(0,g.datetime2)("object_missing_at"),createdAt:(0,g.datetime2)("created_at").notNull(),createdBy:(0,g.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,g.datetime2)("updated_at").notNull(),updatedBy:(0,g.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,g.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[m.id]}),(0,g.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,g.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[m.uploadedBy],foreignColumns:[n.id]}),(0,g.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(m.hubId,m.sourceKey),(0,g.index)(`${e}_DailyReportAttachment_hub_id_index`).on(m.hubId,m.createdAt)]);return{hub:o,internal:a,comment:l,attachment:T,label:s,hubLabel:h,userStatus:i}}var Ji=5e7,hr=2e8,Ki=1,fr=Object.freeze({fixedBytes:4*1024*1024,pipelineRows:2048,wholeImageBuffer:Object.freeze({"jpeg-single-scan":Object.freeze({kind:"none"}),"jpeg-multi-scan":Object.freeze({kind:"jpeg-coefficients"}),png:Object.freeze({kind:"none"}),"png-interlaced":Object.freeze({kind:"decoded-raster"}),gif:Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-lossy":Object.freeze({kind:"none"}),"webp-lossy-alpha":Object.freeze({kind:"canvas",bytesPerPixel:5}),"webp-lossless":Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-animated":Object.freeze({kind:"canvas",bytesPerPixel:9})})}),mo=125,po=4,yo=16,ho=50,fo=2,st=Object.freeze({renderMs:se.renderMs,nanosecondsPerBlockVisit:mo,margin:po,maxBlockVisits:Math.floor(se.renderMs*1e6/(mo*po)),walkBudgetMs:yo,nanosecondsPerWalkStep:ho,walkMargin:fo,maxWalkSteps:Math.floor(yo*1e6/(ho*fo))}),Gi=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),go=75,Ro=4,bo="#ffffff",Xi=1,Qi={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Zi=[/out of memory/i,/insufficient memory/i,/memory allocation|allocation failed/i,/(?:cannot|could not|unable to|failed to) allocate/i,/picture memory error/i,/unable to create thread|error creating thread|resource temporarily unavailable/i,/too many open files|no space left on device/i,/\b(?:ENOMEM|EAGAIN|EMFILE|ENFILE|ENOSPC)\b/],So=Object.freeze({ok:!1,reason:"failed"}),Ao=Object.freeze({ok:!1,reason:"unsupported"}),To=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:yn(e)}),Do=(e,t)=>{switch(t){case"jpeg":{let r=rr(e);return r===null?null:To(r)}case"png":{let r=gn(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Rn(e,st.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},_o=(e,t)=>{let r=Gi.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=fr,a=o.wholeImageBuffer[e.layout];return(a.kind==="none"?0:a.kind==="decoded-raster"?t.width*t.height*n:a.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*a.bytesPerPixel)+o.pipelineRows*t.width*n+o.fixedBytes},wo=(e,t,r)=>{let n=Do(e,t);return n===null?null:_o(n,r)},es=e=>e!==null&&e<=hr,ts=(e,t)=>{if(t!=="jpeg")return Do(e,t);let r=hn(e,st);return r===null||r.blockVisits>st.maxBlockVisits?null:To(r.header)},rs=e=>{let t=e instanceof Error?e.message:"";return Zi.some(r=>r.test(t))?"failed":"unsupported"},Eo=e=>{e.cache(!1),e.concurrency(Ki),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Qi)});let t=async(n,o,a,l,s)=>{let h=ts(n,o);if(h===null)return Ao;try{let i=e(n,{limitInputPixels:Ji,animated:!1});if(!es(_o(h,await i.metadata())))return Ao;if(s.aborted)return So;let T=await i.rotate().resize({width:a,height:l,fit:"inside",withoutEnlargement:!0}).flatten({background:bo}).webp({quality:go,effort:Ro}).toBuffer();return{ok:!0,bytes:new Uint8Array(T),contentType:"image/webp"}}catch(i){return{ok:!1,reason:rs(i)}}},r=async(n,{format:o,maxWidth:a,maxHeight:l,signal:s})=>s.aborted?So:t(n,o,a,l,s);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${go}-e${Ro}/flatten-${bo}/v${Xi}`,render:r}};function ns(e){e.redis||(e.logger??console).warn("[DailyReport] redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=mt(e.redis),r=new Be({defaultTtlMs:e.cacheDefaultTtlMs??6e4},t),n=Ut({...e,cache:r,epochs:t}),o=new ze({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Bt({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,redis:e.redis,sseReader:o,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:o,streamKey:n.streamKey,knownSourceTypes:[...new Set(["Internal",...(e.externalSources??[]).map(l=>l.sourceType)])],...a}}0&&(module.exports={DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,DAILY_REPORT_SSE_CATCH_UP_BATCH,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,DailyReportSseReader,DailyReportViewerScope,SqlResultCache,createDailyReportHandlers,createDailyReportServer,createDailyReportService,createEpochStore,createSharpThumbnailRenderer,defineDailyReportSchema,generateETag,isStreamIdLte,jsonResponseWithETag,predictSharpThumbnailWorkingSetBytes,transformJsonArray});
|
|
5
5
|
/* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */
|