@aiquants/daily-report 0.35.0 → 0.37.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 +141 -0
- package/README.md +177 -66
- package/dist/client.d.mts +26 -15
- package/dist/client.d.ts +26 -15
- package/dist/client.js +6 -6
- package/dist/client.mjs +6 -6
- package/dist/{comment-adapter-DqBqtqfA.d.ts → comment-adapter-DOUwSlKf.d.ts} +1 -0
- package/dist/{comment-adapter-ChA4KOE1.d.mts → comment-adapter-_h3W1duG.d.mts} +1 -0
- package/dist/index.d.mts +3 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/search-marks-wire-CZRU4q3h.d.mts +35 -0
- package/dist/search-marks-wire-CZRU4q3h.d.ts +35 -0
- package/dist/server.d.mts +25 -12
- package/dist/server.d.ts +25 -12
- package/dist/server.js +10 -10
- package/dist/server.mjs +10 -10
- package/dist/styles/daily-report.standalone.css +1 -1
- package/package.json +1 -1
- package/dist/logger-BaxnzF-0.d.mts +0 -17
- package/dist/logger-BaxnzF-0.d.ts +0 -17
package/dist/server.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var dn=e=>{throw TypeError(e)};var mn=(e,t,r)=>t.has(e)||dn("Cannot "+r);var At=(e,t,r)=>(mn(e,t,"read from private field"),r?r.call(e):t.get(e)),hr=(e,t,r)=>t.has(e)?dn("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),fr=(e,t,r,n)=>(mn(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var ce=()=>Math.floor(performance.now());var Rr=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{}}}),It=(e,t)=>t?e.map(r=>structuredClone(r)):e,Et=class{constructor(t,r){this.config=t;this.epochStore=r;this.buckets=new Map;this.inFlight=new Map;this.forcedFetches=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-ce())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let m=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=await t.fetcher();return this.inFlight.get(n)===l&&this.buckets.set(n,{records:s,expireAt:ce()+a,epoch:m}),s})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.startFetch=(t,r)=>{let{cacheKey:n}=t,o;o=(async()=>{let i=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null;for(let m of r)m();let l=await t.fetcher();if(this.inFlight.get(n)===o){let m=ce()+(t.ttlMsOverride??this.config.defaultTtlMs);this.buckets.set(n,{records:l,expireAt:m,epoch:i}),this.buckets.size>500&&this.cleanExpired()}return l})(),this.inFlight.set(n,o);let a=()=>{this.inFlight.get(n)===o&&this.inFlight.delete(n)};return o.then(a,a),o};this.forcedFetch=t=>{let{cacheKey:r}=t,n=t.onFetchStart===void 0?[]:[t.onFetchStart],o=this.forcedFetches.get(r);if(o===void 0)return this.runForcedFetch(t,n);if(o.pending===null){let a=[],i=()=>this.runForcedFetch(t,a);o.pending={promise:o.running.then(i,i),onFetchStarts:a}}return o.pending.onFetchStarts.push(...n),o.pending.promise};this.runForcedFetch=(t,r)=>{let{cacheKey:n}=t,o=this.startFetch(t,r);this.forcedFetches.set(n,{running:o,pending:null});let a=()=>{let i=this.forcedFetches.get(n);i?.running===o&&i.pending===null&&this.forcedFetches.delete(n)};return o.then(a,a),o};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o}=t;if(n)return this.buckets.delete(r),It(await this.forcedFetch(t),o);let a=this.buckets.get(r);if(a&&a.expireAt>ce())if(t.epochKey){let l=await this.epochStore.getEpoch(t.epochKey);if(l===null||a.epoch===l)return this.maybeRefreshAhead(t),It(a.records,o);this.buckets.delete(r)}else return this.maybeRefreshAhead(t),It(a.records,o);let i=this.inFlight.get(r);return It(i!==void 0?await i:await this.startFetch(t,t.onFetchStart===void 0?[]:[t.onFetchStart]),o)};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=ce();for(let[r,n]of this.buckets.entries())n.expireAt<=t&&this.buckets.delete(r)}};var pn="ids-stream";var $t=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 i=0;i<a.length;i++){let l=a.charCodeAt(i);t^=l&255,t=Math.imul(t,16777619),r^=l&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,yn=e=>{for(let t=1;t<e.length;t++)if(Ft(e[t-1],e[t])>0)return!1;return!0},hn=(e,t)=>{let r=e.findIndex(n=>Ft({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var Re=Object.freeze({businessDate:"business-date",idsStream:pn,report:"report",search:"search",reports:"reports",action:"action"}),_e=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var _i=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var fn=e=>e<10?`0${e}`:`${e}`,xi=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=fn(e.getMonth()+1),n=fn(e.getDate());return`${t}-${r}-${n}`},lt=e=>{let t=_i.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),i=Number(n),l=Number(o);if(a<1)return null;let m=new Date(0);return m.setUTCFullYear(a,i-1,l),m.getUTCFullYear()!==a||m.getUTCMonth()!==i-1||m.getUTCDate()!==l?null:`${r}-${n}-${o}`},Vt=e=>lt(e)===e;var Pe=e=>e==null?null:e instanceof Date?xi(e):lt(e);var Ci=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,ie=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Ci(r)}`),ct=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),gr=(e,t,r)=>ie(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),de=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw ie(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},rt=(e,t,r,n)=>t===void 0?n:de(e,t,r);var Rn=(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)}}},he=(e,t,r)=>e===void 0?Rn(t,r):Rn(0,r,e);import{z as Pi}from"zod";var ut=e=>Number.isSafeInteger(e)&&e>0,ge=Pi.number().int().positive().max(Number.MAX_SAFE_INTEGER);var gn=e=>e==="intersection"||e==="union",Oe=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),br=e=>({ids:e.map(t=>t.reportHubId),businessDates:e.map(t=>t.businessDate),sourceTypes:e.map(t=>t.sourceType)});var Mi=/^[1-9][0-9]*$/,Li=/^(?:0|[1-9][0-9]*)$/,ke=e=>{if(e===null||!Mi.test(e))return null;let t=Number(e);return ut(t)?t:null},Sr=e=>{if(e===null||!Li.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Dr=e=>e==="true"?!0:e==="false"?!1:null,wt=e=>e===null?!1:Dr(e);import{z as Du}from"zod";var Yt=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|-[1-9][0-9]{0,15})$/;import{z as w}from"zod";var bn=15e3,Sn="lastEventId",vi=/^\d{1,15}-\d{1,15}$/,Dn=e=>vi.test(e),Ni=w.object({name:w.string().nullish(),affiliation:w.string().nullish()}),Oi=w.object({name:w.string().nullish(),text:w.string().nullish(),color:w.string().nullish()}),ki=w.object({id:ge,name:w.string().nullish(),color:w.string().nullish()}),Tn=w.object({id:ge,userId:w.string().nullish(),userName:w.string().nullish(),content:w.string().nullish(),createdAt:w.string().nullish(),isMine:w.boolean()}),Ui=w.object({id:w.string(),fileName:w.string(),fileType:w.string().nullable(),fileSize:w.number().nullable(),createdAt:w.string().nullable(),state:w.enum(["present","absent","unknown"]),hasThumbnail:w.boolean().default(!1)}),Tr=w.object({reportHubId:ge,date:w.string().nullish(),createdAt:w.string().nullish(),author:w.string().nullish(),userId:w.string().nullish(),sourceType:w.string().nullish(),employeeName:w.string().nullish(),updatedBy:w.string().nullish(),updatedAt:w.string().nullish(),category:w.string().nullish(),creationCategory:w.string().nullish(),visitTimeFrom:w.string().nullish(),visitTimeTo:w.string().nullish(),customerName:w.string().nullish(),interviewers:w.array(Ni),subject:w.string().nullish(),content:w.string().nullish(),externalComments:w.array(Oi),isRead:w.boolean(),isStarred:w.boolean(),labels:w.array(ki),postedComments:w.array(Tn),attachments:w.array(Ui).default([])}),nt=w.string().regex(Yt),Bi=w.object({type:w.literal("connected")}),qt=w.object({type:w.literal("status-update"),reportHubId:ge,statusType:w.enum(["star","read"]),value:w.boolean(),clientTempId:nt,recipientRawUserId:ge.optional()}),Ar=w.string().optional(),Ir=w.object({type:w.literal("comment-add"),reportHubId:ge,comment:Tn,clientTempId:nt,recipientRawUserId:ge.optional(),sourceType:Ar}),Er=w.object({type:w.literal("comment-delete"),reportHubId:ge,commentId:ge,clientTempId:nt,recipientRawUserId:ge.optional(),sourceType:Ar}),wr=w.object({type:w.literal("report-create"),reportHubId:ge,report:Tr,clientTempId:nt,recipientRawUserId:ge.optional()}),_r=w.object({type:w.literal("report-update"),reportHubId:ge,report:Tr,clientTempId:nt,recipientRawUserId:ge.optional()}),xr=w.object({type:w.literal("report-publish"),reportHubId:ge,report:Tr,clientTempId:nt,recipientRawUserId:ge.optional()}),Cr=w.object({type:w.literal("report-delete"),reportHubId:ge,clientTempId:nt,sourceType:Ar}),An=w.discriminatedUnion("type",[Bi,qt,Ir,Er,wr,_r,xr,Cr]);var Me=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var jt=Math.max(1,Math.floor(10.556701030927835));var Ue=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var $e=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=i=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(s=>[s,0]))};o.set(i,l),Ue(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,m)=>{let s=o.get(i);if(s!==void 0){s.count+=1,s.tallies[l]+=1;return}m(),a(i)}}};var Pr=e=>e!==null&&Yt.test(e)?e:null,In=e=>gn(e)?e:null,En=e=>{if(e===null)return null;let t=e.split(",");if(t.length>Oe.maxDetailIds)return null;let r=[];for(let n of t){let o=ke(n);if(o===null||r.includes(o))return null;r.push(o)}return r},wn=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var xn=Object.freeze({status:400,error:"Invalid form"}),Cn=e=>({status:413,error:"Form too large",measuredBy:e}),Hi=(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)}}))},$i=async e=>{let t=Sr(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Cn("declared")};let r=!1,n=e.body===null?null:Hi(e.body,1048576,()=>{r=!0}),o=new Headers,a=e.headers.get("Content-Type");a!==null&&o.set("Content-Type",a);let i;try{i=await new Response(n,{headers:o}).formData()}catch{return{refusal:r?Cn("counted"):xn}}let l=wn(i);return l===null?{refusal:xn}:{fields:l}},Pn=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=Dr(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},Ln=Object.freeze({update:(e,t,r)=>{let n=e.get(Me.title),o=e.get(Me.content);if(n!==null&&n.length>r.titleMaxLength)return{error:"Invalid title"};let a={};return n!==null&&(a.title=n),o!==null&&(a.content=o),{command:{...t,intent:"update",changes:a}}},publish:(e,t)=>({command:{...t,intent:"publish"}}),delete:(e,t)=>({command:{...t,intent:"delete"}}),toggleStar:Pn("toggleStar",Me.isStarred),toggleRead:Pn("toggleRead",Me.isRead),addComment:(e,t)=>{let r=e.get(Me.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=ke(e.get(Me.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),Fi=e=>Object.hasOwn(Ln,e),Vi=(e,t)=>{let r=e.get(Me.intent),n=e.get(Me.businessDate),o=n===null?null:lt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Me.operationTimestamp),i=Sr(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(Me.clientTempId);if(!l)return{error:"clientTempId required"};let m=Pr(l);if(m===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:m,businessDate:o,operationTimestamp:i}};let s=ke(e.get(Me.reportHubId));return s===null?{error:"Invalid reportHubId"}:r===null||!Fi(r)?{error:"Invalid intent"}:Ln[r](e,{clientTempId:m,businessDate:o,operationTimestamp:i,reportHubId:s},t)},vn=async(e,t)=>{let r=await $i(e);if("refusal"in r)return r;let n=Vi(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Yi=6e4,qi="form_too_large",Mn=["declared","counted"],Nn=e=>{let t=$e({windowMs:Yi,tallies:Mn,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Mn.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(qi,r,n)}};var _t=Object.freeze({[Re.businessDate]:{body:"json",admission:["cache","refresh-bucket"]},[Re.idsStream]:{body:"stream",admission:["cache","stream-slots","refresh-bucket"]},[Re.report]:{body:"json",admission:["cache","refresh-bucket"]},[Re.search]:{body:"json",admission:["search-limiter"]},[Re.reports]:{body:"json",admission:["search-limiter"]}}),On=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),Mr=e=>e!==void 0&&Object.hasOwn(_t,e);var Lr=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),kn=e=>Object.hasOwn(Lr,e);var ji="download",zi="thumbnail",Wi="1";var vr=e=>{let t=e.getAll(zi),r=e.getAll(ji);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&kn(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Wi?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var Or="Cross-site request rejected",Ki="Not Found",Ji=new Set(["same-origin","none"]),Gi=new Set(["GET","HEAD","OPTIONS"]),Un=["api","action","sse","attachment"],Bn=(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"}}),Qi=()=>Bn(403,Or),zt=()=>Bn(404,Ki),xt=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:Qi}),Hn=e=>new URL(e.url).pathname.endsWith(".data"),Xi=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},$n=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(Gi.has(e.method)||Xi(e)):Ji.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},Zi=6e4,es="refusals",ts=32,rs=/^[a-z-]+$/,Nr=e=>{if(e===null)return"-";let t=e.slice(0,ts);return rs.test(t)&&t===e?e:JSON.stringify(t)},Fn=e=>{let t=$e({windowMs:Zi,tallies:Un,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${Un.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${Nr(a.get("Sec-Fetch-Site"))} mode=${Nr(a.get("Sec-Fetch-Mode"))} dest=${Nr(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(es,r,o)}};var Vn=(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 ns="same-origin",os="SAMEORIGIN",dt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":ns,"X-Frame-Options":os}),Wt=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...dt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Yn=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),as=/^[\x20-\x7E]+$/,is=/^[\w.+-]+\/[\w.+-]+/,kr=e=>e&&as.test(e)&&is.test(e)?e:null,ss=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,qn=e=>encodeURIComponent(e.replace(ss,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),jn=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),Kt={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},zn={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Jt=e=>typeof e=="string"&&Object.hasOwn(zn,e),Gt=e=>zn[e],je="Attachment request failed";var Ge=e=>{let t=de("limit",e.limit,1),r=de("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:de("queue.max",e.queue.max,0),maxPerOwner:de("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:de("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,m=(R,D)=>R.get(D)??0,s=(R,D,U)=>{let _=m(R,D)+U;_<=0?R.delete(D):R.set(D,_)},h=R=>m(l,R)<r,d=R=>o<t&&h(R),b=R=>(o+=1,s(l,R,1),g(R)),y=()=>{for(;o<t;){let R=a.findIndex(U=>h(U.owner));if(R<0)return;let[D]=a.splice(R,1);s(i,D.owner,-1),D.grant(b(D.owner))}},g=R=>{let D=!1;return()=>{D||(D=!0,o-=1,s(l,R,-1),y())}};return{canAcquire:d,acquire:(R,D)=>{if(D.aborted)return Promise.resolve(null);if(d(R))return Promise.resolve(b(R));if(n===null||a.length>=n.max||m(i,R)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:U}=n,_=O=>{let P=()=>{let B=a.indexOf(G);B<0||(a.splice(B,1),s(i,R,-1),F(),O(null))},T=Ue(P,U),F=()=>{clearTimeout(T),D.removeEventListener("abort",P)},G={owner:R,grant:B=>{F(),O(B)}};a.push(G),s(i,R,1),D.addEventListener("abort",P,{once:!0})};return new Promise(_)}}};var ls=1024,Ur="Too many requests",cs=(e,t)=>{de("limitPerWindow",e,1),de("windowMs",t,1);let r=new Map,n=(a,i)=>{i<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(i-a.lastRefillMs)*e/t),a.lastRefillMs=i)},o=(a,i)=>{let l=r.get(a);l&&r.delete(a);let m=l??{tokens:e,lastRefillMs:i};n(m,i),r.set(a,m);for(let s of r.keys()){if(r.size<=ls)break;r.delete(s)}return m};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let m=r.get(a);m&&(n(m,i),m.tokens=Math.min(e,m.tokens+l))}}},ze=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(de("windowMs",r,1e3)%1e3!==0)throw ie("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=cs(e.limitPerWindow,r),i=Object.freeze({status:429,message:Ur,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=$e({windowMs:r,tallies:[t],writeSuppressed:(m,{count:s,since:h})=>{n.warn(`${t}_suppressed count=${s} since=${h} ${o(m)}`)}});return{spend:(m,s)=>a.consume(m,ce())?null:(l.record(m,t,()=>n.warn(`429 ${s} reason=${t}`)),i),refund:(m,s)=>{a.refund(m,ce(),s)}}};import{createHash as us}from"crypto";var Br=e=>`"${us("sha256").update(e).digest("hex")}"`,Hr=e=>Br(JSON.stringify(e));var $r=(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},ae=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=Br(o),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:a});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&$r(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},ds=5e3/1e3,ms=new Map([[503,ds]]),We=e=>{let t=ms.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var ys=256*1024,Wn=6e4,hs=e=>Math.ceil(e/2),fs=new Uint8Array(new ArrayBuffer(0)),Rs=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=fs,t()},i=l=>{clearTimeout(o),o=Ue(()=>{l.error(new Error(`attachment body idle for ${Wn} ms`)),a()},Wn)};return new ReadableStream({start(l){i(l)},pull(l){let m=Math.min(n+ys,r.byteLength);if(m>n&&l.enqueue(r.slice(n,m)),n=m,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},Kn=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=ze({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:m=>`viewer=${m}`}),l=Ge({limit:e.concurrency,maxHeldPerOwner:hs(e.concurrency),queue:null});return async m=>{let{request:s,delivery:h,attachmentId:d,internalUserId:b,readAttachment:y,cookie:g,fail:R}=m,D=e.maxBytes,U=i.spend(b,`attachment=${d} viewer=${b}`);if(U)return R(U.status,U.message,U.headers);let _=await n(s),O=await t.getAttachmentForUser(_,d,b);if(!O)return o.warn(`404 attachment=${d} viewer=${b} reason=not_visible`),R(404,"Attachment not found");if(O.fileSize!=null&&O.fileSize>D)return o.warn(`413 attachment=${d} viewer=${b} reason=db_size`),R(413,"Attachment too large");let P=kr(O.fileType),T=`filename="${jn(O.fileName)}"; filename*=UTF-8''${qn(O.fileName)}`,F=await l.acquire(b,s.signal);if(!F)return s.signal.aborted?(o.info(`503 attachment=${d} viewer=${b} reason=aborted`),R(503,"Attachment request aborted")):(o.warn(`503 attachment=${d} viewer=${b} reason=concurrency`),R(503,"Too many concurrent downloads",We(503)));let G=!1;try{let B=await y(O.filePath,{maxBytes:D,head:s.method==="HEAD",principal:r(b),signal:s.signal});if(s.signal.aborted)return o.info(`503 attachment=${d} viewer=${b} reason=aborted`),R(503,"Attachment request aborted");if(!B.ok){if(!Jt(B.reason))return o.error(`500 attachment=${d} viewer=${b} reason=port_contract code=failure_reason`),R(500,je);let ne=Gt(B.reason);return B.reason==="not_found"&&a(d,!1),o.warn(`${ne} attachment=${d} viewer=${b} reason=${B.reason} code=${B.code??"-"}`),R(ne,Kt[ne],We(ne))}if(B.bytes.byteLength>D)return o.error(`500 attachment=${d} viewer=${b} reason=port_contract code=over_max_bytes`),R(500,je);let se=s.method==="HEAD";if(se&&B.size!==void 0&&B.size>D)return o.error(`500 attachment=${d} viewer=${b} reason=port_contract code=over_max_bytes`),R(500,je);if(!se&&B.size!==void 0&&B.size!==B.bytes.byteLength)return o.error(`500 attachment=${d} viewer=${b} reason=port_contract code=size_mismatch`),R(500,je);let be=P??kr(B.contentType),ue=be!==null&&Yn.has(be),q=ue?be:"application/octet-stream",X=ue&&h.kind!=="download"?"inline":"attachment",re=se?B.size:B.bytes.byteLength,pe=new Headers({"Content-Type":q,"Content-Disposition":`${X}; ${T}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...dt});return re!==void 0&&pe.set("Content-Length",String(re)),g&&pe.append("Set-Cookie",g),a(d,!0),o.info(`200 attachment=${d} viewer=${b} type=${q} disposition=${X} bytes=${re??"-"}`),se?new Response(null,{status:200,headers:pe}):(G=!0,new Response(Rs(B.bytes,F),{status:200,headers:pe}))}finally{G||F()}}};var xe=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),ud=xe.queueWaitMs+xe.readMs+xe.renderMs+xe.transferMarginMs;import{Buffer as gs}from"buffer";var Qn=new Set([194,198,202,206]),bs=new Set([192,193,194,195]),Xn=216,Ss=217,Zn=218,Ds=4,Ts=64,As=2,Jn=8,Gn=28,Qe=12,Fr=8,Is=20,eo=Qe+Fr+10,Es=2,Ke=(e,t)=>e[t]<<8|e[t+1],mt=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];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},to=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,ro=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),no=e=>(e.stepsLeft-=1,e.stepsLeft>=0),oo=e=>e[0]===255&&e[1]===Xn,ao=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!no(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===Ss)return"eoi";if(o===0||o===Xn)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=Ke(e,n),i=n+a;return a<2||i>e.byteLength?null:(r.marker=o,r.body=n+2,r.length=a,r.end=i,"segment")}},ws=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!no(r))return null;if(a+1>=n)return n;let i=e[a+1];if(i===255)a+=1;else if(i===0||i>=208&&i<=215){if(a+=2,a>=n||e[a]!==255)break}else return a}o=a}},io=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=Ke(e,r+1),a=Ke(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let m=0;m<i;m+=1){let s=e[r+7+3*m],h=s>>4,d=s&15;if(h<1||h>4||d<1||d>4)return null;l.push({id:e[r+6+3*m],horizontal:h,vertical:d})}return{marker:t,width:a,height:o,components:l}},so=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>Ds||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},lo=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:Qn.has(e.marker)||t<e.components.length}),Vr=e=>{if(!oo(e))return null;let t=ro(e.byteLength),r=null;for(let n=2;;){if(ao(e,n,t)!=="segment")return null;if(to(t.marker)){if(r!==null||(r=io(e,t),r===null))return null}else if(t.marker===Zn){if(r===null)return null;let o=so(e,t);return o===null?null:lo(r,o.length)}n=t.end}},co=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*Jn)),i=Math.ceil(e.height*o/(r*Jn));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},uo=e=>e.multiScan?co(e).reduce((r,n)=>r+n,0)*Ts*As:0,_s=896,mo=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!oo(e))return null;let n=gs.from(e.buffer,e.byteOffset,e.byteLength),o=ro(r),a=null,i=null,l=new Map,m=0,s=0,h=0;for(let d=2;;){let b=ao(e,d,o);if(b===null)return null;if(b==="eoi")return i===null?null:{header:i,blockVisits:s};if(d=o.end,to(o.marker)){if(a!==null||!bs.has(o.marker)||(a=io(e,o),a===null))return null;let y=co(a);l=new Map;for(let[g,R]of a.components.entries()){let D=l.get(R.id);l.set(R.id,D===void 0?y[g]:Math.max(D,y[g]))}m=a.components.length*(Qn.has(a.marker)?_s:1)}else if(o.marker===Zn){if(a===null||h===m)return null;let y=so(e,o);if(y===null)return null;for(let R of y){let D=l.get(R);if(D===void 0)return null;s+=D}if(h+=1,i===null&&(i=lo(a,y.length)),s>t||!i.multiScan)return{header:i,blockVisits:s};let g=ws(n,o.end,o);if(g===null)return null;d=g}}},po=e=>{if(e.byteLength<24||Ke(e,8)!==0||Ke(e,10)!==13||!Fe(e,12,"IHDR"))return null;let t=Ke(e,16)*65536+Ke(e,18),r=Ke(e,20)*65536+Ke(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},xs=e=>{if(Fe(e,Qe,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=mt(e,26,2)&16383,r=mt(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(Fe(e,Qe,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=mt(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return Fe(e,Qe,"VP8X")?e.byteLength<eo?null:{width:mt(e,24,3)+1,height:mt(e,27,3)+1}:null},yo=e=>{if(po(e)===null||e.byteLength<=Gn)return null;switch(e[Gn]){case 0:return!1;case 1:return!0;default:return null}},ho=(e,t)=>{if(Fe(e,Qe,"VP8 "))return"lossy";if(Fe(e,Qe,"VP8L"))return"lossless";if(!Fe(e,Qe,"VP8X")||e.byteLength<eo)return null;if((e[Is]&Es)!==0)return"animated";let r=!1,n=t;for(let o=Qe;o+Fr<=e.byteLength;){if(n-=1,n<0)return null;if(Fe(e,o,"VP8L"))return"lossless";if(Fe(e,o,"VP8 "))return r?"lossy-alpha":"lossy";Fe(e,o,"ALPH")&&(r=!0);let a=mt(e,o+4,4);o+=Fr+a+a%2}return null},fo={png:po,jpeg:Vr,webp:xs};var Yr=Object.freeze(["image/webp","image/jpeg","image/png"]),qr=1024*1024;var Cs=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Ps={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Ms=new Set(Yr),Ls=e=>typeof e=="string"&&Ms.has(e),vs=256,Qt=(e,t)=>e.fileType===null||!Cs.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Ns=[137,80,78,71,13,10,26,10],Os=[255,216,255],ks=[[71,73,70,56,55,97],[71,73,70,56,57,97]],Us=[82,73,70,70],Bs=[87,69,66,80],Ct=(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},jr=e=>{if(Ct(e,Ns,0))return"png";if(Ct(e,Os,0))return"jpeg";for(let t of ks)if(Ct(e,t,0))return"gif";return Ct(e,Us,0)&&Ct(e,Bs,8)?"webp":null},Ro=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:Hr([t])}},go=(e,t)=>{if(!Ls(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>qr)return"too_large";let r=Ps[e.contentType];if(jr(e.bytes)!==r)return"signature";let n=fo[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},bo=e=>{de("maxBytes",e.maxBytes,0),de("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 i=(a.kind==="thumbnail"?a.bytes.byteLength:0)+vs;if(i>e.maxBytes||e.maxEntries===0)return;let l=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:l,weight:i}),r+=i;for(let m of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(m)}}}};var zr=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ce(),l=new AbortController,m=!1,s,h,d=()=>{a(ce()-i)},b=P=>{s=Ue(()=>{m=!0,P({timedOut:!0}),h=Ue(d,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},y=new Promise(b),g=AbortSignal.any([r,l.signal]),R=P=>{P(n(g))},D=new Promise(R),U=P=>(clearTimeout(s),clearTimeout(h),m&&o(ce()-i,P.kind==="error"?{error:P.error}:null),P),_=D.then(P=>U({kind:"value",value:P}),P=>U({kind:"error",error:P}));return{outcome:Promise.race([D.then(P=>({timedOut:!1,value:P})),y]),settled:_}};var Xe={404:"Attachment not found",500:je,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},So=(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=go(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Hs=e=>{let t=new AbortController,r=()=>{t.abort()},n=Ue(r,xe.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Do=()=>{},$s=(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)}),To=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,m=(y,g)=>{let R=g.then(Do,Do);l.set(y,R);let D=()=>{l.get(y)===R&&l.delete(y)};R.then(D)},s=async(y,g)=>{let R=l.get(y.key);if(R===void 0)return t.acquire(y.owner,g);let D=Hs(g);try{if(await $s(R,D.signal),D.signal.aborted)return null;let U=r.get(y.key);return U!==void 0?{...U,identity:"verified"}:await t.acquire(y.owner,D.signal)}finally{D.end()}},h=(y,g)=>{if(y.fileSize===null)return g.kind==="exact"?"verified":"unrecorded";if(g.kind==="exact"?g.bytes===y.fileSize:y.fileSize>g.maxBytes)return"verified";let D=g.kind==="exact"?String(g.bytes):`>${g.maxBytes}`;return i.warn(`size_mismatch expected=${y.fileSize} got=${D} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail`),"unverified"},d=(y,g)=>(R,D)=>{let U=D===null?"":` message=${D.error instanceof Error?D.error.message:"unknown"}`;i.warn(`${y}_overrun ms=${R} attachment=${g.attachmentId} viewer=${g.owner} variant=thumbnail${U}`)},b=(y,g)=>R=>{i.warn(`${y}_stuck ms=${R} attachment=${g.attachmentId} viewer=${g.owner} variant=thumbnail`)};return async(y,g)=>{let R=await s(y,g);if(R===null)return{kind:"failure",status:503,reason:g.aborted?"aborted":"queue"};if(typeof R!="function")return R;let D=R,U=null;try{if(g.aborted)return{kind:"failure",status:503,reason:"aborted"};let _=r.get(y.key);if(_!==void 0)return{..._,identity:"verified"};let O=zr({budgetMs:xe.readMs,flightSignal:g,call:ne=>y.readAttachment(y.filePath,{maxBytes:n,head:!1,principal:o(y.owner),signal:ne}),onOverrun:d("read",y),onStuck:b("read",y)}),P=await O.outcome;if(P.timedOut)return U=O.settled,g.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(g.aborted)return{kind:"failure",status:503,reason:"aborted"};let T=P.value;if(!T.ok&&T.reason!=="too_large")return Jt(T.reason)?(T.reason==="not_found"&&a(y.attachmentId,!1),{kind:"failure",status:Gt(T.reason),reason:T.reason,code:T.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(T.ok&&T.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let F=h(y,T.ok?{kind:"exact",bytes:T.bytes.byteLength}:{kind:"over",maxBytes:n}),G=ne=>{F==="verified"&&r.set(y.key,ne)},B=ne=>(G(ne),{...ne,identity:F});if(!T.ok)return B({kind:"unrenderable",reason:"too_large"});let se=jr(T.bytes);if(se===null)return B({kind:"unrenderable",reason:"signature"});let be=zr({budgetMs:xe.renderMs,flightSignal:g,call:ne=>y.renderer.render(T.bytes,{format:se,maxWidth:y.box.maxWidth,maxHeight:y.box.maxHeight,signal:ne}),onOverrun:d("render",y),onStuck:b("render",y)}),ue=ne=>{if(ne.kind==="error")return;let ye=So(ne.value,y.box);"entry"in ye&&G(ye.entry)},q=null,X=()=>(q===null&&(q=be.settled.then(ue),m(y.key,q)),q);g.addEventListener("abort",X,{once:!0});let re=await be.outcome.finally(()=>g.removeEventListener("abort",X));if(re.timedOut||g.aborted)return U=X(),g.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let pe=So(re.value,y.box);return"entry"in pe?B(pe.entry):pe.failure}finally{U===null?D():U.then(D,D)}}};var Ao=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let m=new AbortController,s=()=>{e.get(t)?.controller===m&&e.delete(t)},d={promise:n(m.signal).finally(s),controller:m,waiters:0};return e.set(t,d),d},a=e.get(t)??o();a.waiters+=1;let i=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?i():r.addEventListener("abort",i,{once:!0});let l=()=>{r.removeEventListener("abort",i)};return a.promise.finally(l)}}};var wo=10,Fs=1/wo,Io=1-Fs,Vs=1024,Ys=64,qs=8,Eo="private, no-cache",js="no-store",zs=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),Ws=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},_o=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:m}=l,s=(P,T)=>ze({reason:P,limitPerWindow:T,windowMs:6e4,logger:o,windowFields:F=>`viewer=${F} variant=thumbnail`}),h=s("rate_limit",l.rateLimitPerMinute),d=s("revalidation_rate_limit",l.rateLimitPerMinute*wo),b=Ge({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:Ys,maxPerOwner:qs,maxWaitMs:xe.queueWaitMs}}),y=bo({maxBytes:l.cacheBytes,maxEntries:Vs}),g=Ao(),R=To({gate:b,cache:y,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),D=(P,T,F,G)=>{let B=`attachment=${P.attachmentId} viewer=${P.internalUserId} variant=thumbnail cache=${G}`;if(T.kind==="failure")return o[Ws(T)](`${T.status} ${B} reason=${T.reason} code=${T.code??"-"}`),P.fail(T.status,Xe[T.status],We(T.status));let se=zs[T.identity];if(T.kind==="unrenderable")return o.info(`404 ${B} reason=${T.reason}${se}`),P.fail(404,Xe[404]);let be=T.identity==="verified"?{"Cache-Control":Eo,ETag:F}:{"Cache-Control":js},ue=new Headers({"Content-Type":T.contentType,"Content-Length":String(T.bytes.byteLength),...be,"Content-Security-Policy":"default-src 'none'; sandbox",...dt});return P.cookie&&ue.append("Set-Cookie",P.cookie),o.info(`200 ${B} type=${T.contentType} bytes=${T.bytes.byteLength}${se}`),new Response(T.bytes,{status:200,headers:ue})},U=(P,T)=>{let F=P.spend(T.internalUserId,`attachment=${T.attachmentId} viewer=${T.internalUserId} variant=thumbnail`);return F===null?null:T.fail(F.status,F.message,F.headers)},_=P=>U(h,P),O=(P,T)=>T?U(d,P):_(P);return async(P,T)=>{let{request:F,attachmentId:G,internalUserId:B,readAttachment:se,cookie:be,fail:ue}=P,q=Lr[T],X=F.headers.get("If-None-Match"),re=X!==null,pe=O(P,re);if(pe)return pe;let ne=await n(F),ye=await t.getAttachmentForUser(ne,G,B),E=ye!==null&&Qt(ye,i)?Ro({rendererId:m.id,box:q,attachmentId:G,filePath:ye.filePath,fileType:ye.fileType,fileSize:ye.fileSize}):null;if(E&&$r(X,E.etag)){let $=new Headers({"Cache-Control":Eo,ETag:E.etag,...dt});return be&&$.append("Set-Cookie",be),o.info(`304 attachment=${G} viewer=${B} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:$})}if(re){let $=_(P);if($)return $}if(!ye)return o.warn(`404 attachment=${G} viewer=${B} variant=thumbnail reason=not_visible`),ue(404,Xe[404]);if(!E)return h.refund(B,Io),o.info(`404 attachment=${G} viewer=${B} variant=thumbnail reason=not_eligible`),ue(404,Xe[404]);let{key:L,etag:v}=E,H=y.get(L);if(H)return h.refund(B,Io),D(P,{...H,identity:"verified"},v,"hit");let V=$=>R({key:L,attachmentId:G,filePath:ye.filePath,fileSize:ye.fileSize,box:q,owner:B,readAttachment:se,renderer:m},$),K;try{K=await g.join(L,F.signal,V)}catch($){return o.error(`500 attachment=${G} viewer=${B} variant=thumbnail cache=miss reason=port_exception message=${$ instanceof Error?$.message:"unknown"}`),ue(500,Xe[500])}return D(P,K,v,"miss")}};var Ks='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Js=()=>Wt(403,Or,{cookie:null}),xo=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=vr(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>Wt(404,Kt[404],{cookie:null}),crossSiteRejection:Js}),Co=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:o,logger:a}=e,i=r.attachmentDelivery,l={service:r,encodeUserId:n,resolveViewerScope:o,logger:a,recordObjectState:Vn(r,a)},m=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:Kn({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:_o({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:s,params:h})=>{let d=null,b=(y,g,R={})=>Wt(y,g,{cookie:d,extraHeaders:R});try{let{user:y,cookie:g}=await t(s,{failureRedirect:null});if(d=g??null,!y)return b(401,"Unauthorized");let R=vr(new URL(s.url).searchParams);if(R.kind==="invalid")return b(400,"Invalid attachment request");if(R.kind==="thumbnail"&&s.method!=="GET")return b(405,"Method not allowed",{Allow:"GET"});if(s.method!=="GET"&&s.method!=="HEAD")return b(405,"Method not allowed",{Allow:"GET, HEAD"});if(m===null)return b(404,"Attachment not found");if(h.token===void 0)throw new Error(Ks);let D=m.idCodec.decode(h.token);if(D===null||!ut(D))return b(400,"Invalid attachment token");let U=await r.getUserIdByExternalId(y.id);if(!U)return b(403,"Forbidden");let _={request:s,delivery:R,attachmentId:D,internalUserId:U,readAttachment:m.read,cookie:d,fail:b};return R.kind!=="thumbnail"?await m.serveOriginal(_):m.serveThumbnail===null?b(404,Xe[404]):await m.serveThumbnail(_,R.variant)}catch(y){if(y instanceof Response)throw y;return a.error(`500 attachment=? viewer=? reason=unexpected message=${y instanceof Error?y.message:"unknown"}`),b(500,je)}}};var Gs=32*1024*1024,Qs=60,Xs=4,Zs=120,el=2,tl=8*1024*1024,Xt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rl=e=>{if(e===void 0)throw ct("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Xt(e))throw ie("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw ct("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw ie("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw ie("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},nl=e=>{if(e===void 0)return null;if(!Xt(e))throw ie("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:rl(e.renderer),rateLimitPerMinute:rt("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Zs),concurrency:rt("attachments.thumbnails.concurrency",e.concurrency,1,el),cacheBytes:rt("attachments.thumbnails.cacheBytes",e.cacheBytes,0,tl)})},Po=e=>{let t=e;if(t===void 0)return null;if(!Xt(t))throw ie("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw ct("attachments.idCodec","injected when attachments is given");if(!Xt(r)||typeof r.encode!="function"||typeof r.decode!="function")throw ie("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw ct("attachments.read","injected when attachments is given");if(typeof n!="function")throw ie("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:rt("attachments.maxBytes",t.maxBytes,1,Gs),rateLimitPerMinute:rt("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,Qs),concurrency:rt("attachments.concurrency",t.concurrency,1,Xs),thumbnails:nl(t.thumbnails)})},ol=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"]]),Zt=e=>{for(let[t,r]of ol)if(Object.hasOwn(e,t))throw ct(r,`given in place of the flat key ${t}`)};var al=/^[0-9a-f]{1,16}$/;var Mo=e=>{let t=e.get(_e.cursorReportHubId),r=e.get(_e.cursorBusinessDate),n=e.get(_e.cursorSnapshot),o=n!==null&&al.test(n)?n:null,a=null;if(t!==null){let l=ke(t);if(l===null)return{refused:"cursor"};if(r!==null&&!Vt(r))return{refused:"cursor"};a={businessDate:r,reportHubId:l}}else if(r!==null)return{refused:"cursor"};let i=wt(e.get(_e.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var er=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,il=2,sl=16,ll=il*sl,cl=6e4,Lo=()=>{},ul=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},vo=e=>{let t=Ge({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:ll,queue:null}),r=$e({windowMs:cl,tallies:["sse","ids-stream"],writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`streams_per_viewer_suppressed count=${o} since=${a} viewer=${n} routes=sse:${i.sse},ids-stream:${i["ids-stream"]}`)}});return{admit:async(n,o,a)=>{if(n===null)return Lo;if(a.aborted){if(t.canAcquire(n))return Lo}else{let i=await t.acquire(n,a);if(i!==null)return ul(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var tr=30,Bo=4e3,dl="stream interrupted by server error",ml="Too many streams",pl=15e3,Ho=Symbol("ids-stream-heartbeat"),No=()=>{},Oo=e=>e.return(void 0).then(No,No),yl=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(Ho),pl)}),stop:()=>clearTimeout(e)}};async function*ko(e,t,r,n){let o=t?hn(e,t):0,a=!0;for(;;){let i=e.slice(o,o+(a?r:Bo));o+=i.length;let l=o>=e.length,m=i[i.length-1];if(yield{kind:"chunk",items:i,nextCursor:l||!m?null:{businessDate:m.businessDate,reportHubId:m.reportHubId},isLast:l,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,l)return}}var $o=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},Uo=(e,t,r,n,o)=>{let a=async(h,d)=>{o(),d&&await Oo(t);try{h.close()}catch{}},i=new TextEncoder,l=!1,m=null,s=new ReadableStream({async pull(h){if(l||r.aborted){await a(h,!0);return}let d=yl();try{m===null&&(m=t.next());let b=await Promise.race([m,d.fired]);if(d.stop(),b===Ho){if(l||r.aborted){await a(h,!0);return}h.enqueue(i.encode(`
|
|
2
|
-
`));return}
|
|
3
|
-
`))}catch(
|
|
4
|
-
`)),
|
|
5
|
-
`,
|
|
6
|
-
`)},
|
|
7
|
-
\u30C7\u30F3\u30D7\u30F3`,"\u30DD\u30C6\u30C8-25kg \u30A2--1 \u30FC\u30FC\u30E1\u30F3 \u4F50\u3005\u6728","\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CA",`\uFF71\uFF72\uFF73\uFF74\uFF75\uFF76\uFF9E\uFF77\uFF9E\uFF78\uFF9E\uFF79\uFF9E\uFF7A\uFF9E${String.fromCodePoint(8232)}\u6B21\u306E\u884C`],Ml=()=>{let e=fl("sha256");e.update(JSON.stringify(Yo));for(let t of["","\u30A2","\u4F50"," "])e.update("\0"),e.update(Pt(Cl(t)));return e.update("\0"),e.update(JSON.stringify(Pl.map(t=>or(t,8)))),`dr-search-v${bl};fz=${e.digest("hex").slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`},Kr=null,Wo=()=>(Kr===null&&(Kr=Ml()),Kr);var vl=/^-+/u,Nl=/\s+/u,Ol=e=>{let t=vl.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},Ko=(e,t)=>{if(e.length>Oe.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of Ll(nr(e),t).sets){let i=[],l=new Set;for(let s of a.split(Nl)){let h=qo(s);if(h.length===0)return{ok:!1,reason:"blank-word"};if(h.length>Oe.maxWordLength)return{ok:!1,reason:"word-too-long"};l.has(h)||(l.add(h),i.push({alternatives:Ol(h)}))}if(i.length>Oe.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let m=[...l].sort().join("\0");n.has(m)||(n.add(m),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>Oe.maxSets?{ok:!1,reason:"too-many-sets"}:o>Oe.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}};import{systemSseRuntime as Kl}from"@aiquants/sse";import{createSseResponse as Jl,readLastEventId as Gl,startSseHeartbeat as Ql,terminalStreamResponse as Xl}from"@aiquants/sse/server";var Mt=(e,t)=>{let r=e.message.data;if(!r)return{entry:{id:e.id,message:null},json:void 0};let n;try{n=JSON.parse(r)}catch(i){return t.error(`SSE message ${e.id} is not JSON:`,i),{entry:{id:e.id,message:null},json:void 0}}let o=An.safeParse(n);if(!o.success)return t.error("SSE message validation failed:",o.error.format()),{entry:{id:e.id,message:null},json:n};let a=Object.freeze({parsed:o.data,published:n,text:r});return{entry:Object.freeze({id:e.id,message:a}),json:n}},kl=["externalComments","postedComments"],Jo=new WeakMap,Ul=e=>{let t=Jo.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return Jo.set(e,r),r},Go=e=>{let{recipientRawUserId:t,...r}=e;return r},Qo=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=Ul(e);if(t){if(n.commentsRedacted===null){let o=Go(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(kl.map(i=>[i,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(Go(r))),n.recipientRemoved};import{systemSseRuntime as Hl}from"@aiquants/sse";import{createSharedSource as $l}from"@aiquants/sse/shared-source";var ot="daily-report:ids:",at="daily-report:business-date:",ar=(e,t)=>`${e}st:${t}`,Jr=e=>`${ot}user:${e}:`,Xo=(e,t)=>ar(Jr(e),t),Bl=e=>`${at}${e}:`,Zo=(e,t)=>ar(Bl(e),t),Lt=e=>`daily-report:date:${e}:user:`,pt=(e,t)=>`${Lt(e)}${t}:`,ea=(e,t,r)=>ar(pt(e,t),r),Ve=e=>`daily-report:detail:${e}:user:`,ir=(e,t)=>`${Ve(e)}${t}:`,ta=(e,t,r)=>ar(ir(e,t),r);var Ze=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},Fl=5e3,Vl=jt,vt=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=he(t.logger,1,"[DailyReportSseReader]"),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 $l({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:Hl,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",i=>{this._logger.error("Redis client error:",i)});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 i=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:Fl,COUNT:Vl});if(i)for(let l of i)for(let m of l.messages){a=m.id;let{entry:s,json:h}=Mt(m,this._logger);this._invalidateCaches(h),r.next(s)}}}catch(i){o()||(this._logger.error("xRead loop error:",i),r.fail(i instanceof Error?i:new Error(String(i))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){if(t===null||typeof t!="object")return;let{type:r,reportHubId:n}=t;(r==="report-create"||r==="report-delete"||r==="report-publish")&&this.config.cache.invalidatePrefix(ot),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Ve(n))}};import{inArray as Yl,sql as ra}from"drizzle-orm";var ql="",jl=64,zl=e=>e.toLowerCase(),Wl=e=>e.trim().toLowerCase();function na(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=Wl(r);n.length>0&&t.add(n)}return t}function ve(e,t){return e===null?!0:t==null?!1:e.has(zl(t))}function Ye(e){return e!==null&&e.size===0}function Ot(e,t){if(t!==null)return t.size===0?ra`1 = 0`:Yl(ra`LOWER(${e})`,[...t])}var yt,ht,Nt=class Nt{constructor(t,r){hr(this,yt);hr(this,ht);fr(this,yt,t),fr(this,ht,r)}get visible(){return At(this,yt)===null?null:new Set(At(this,yt))}get commentable(){return At(this,ht)===null?null:new Set(At(this,ht))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=na(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new Nt(n,n);let a=na(o),i=new Set;for(let l of a??[])n.has(l)&&i.add(l);return new Nt(n,i)}static unrestricted(t){return new Nt(null,null)}};yt=new WeakMap,ht=new WeakMap;var Le=Nt;function kt(e){let t=oa(e.visible),r=oa(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function oa(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(ql);if(t.length<=jl)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 sa=Object.freeze({...xt,route:"sse",frameworkDataRefusal:zt}),aa=864e5,Zl={baseMs:2e3,jitterMs:8e3},la=6e4,Gr=jt,ca=JSON.stringify({type:"connected"}),ia="0-0",ec=(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 ve(r,e.report.sourceType);case"comment-add":case"comment-delete":return ve(n,o??"Internal");case"report-delete":return ve(r,o)}},tc=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!ve(t,e.report.sourceType),rc=(e,t)=>{e.writeEvent({event:null,id:t,data:ca})},nc=(e,t,r)=>{let{message:n}=t;if(n===null)return;let{parsed:o,published:a}=n,i=typeof a.recipientRawUserId=="number"?a.recipientRawUserId:void 0;if((o.type==="status-update"||i!==void 0)&&i!==r.internalUserId||!ec(o,a,r.visibleSet,r.commentableSet)){rc(e,t.id);return}e.writeEvent({event:null,id:t.id,data:Qo(n,tc(o,r.commentableSet))})},ua=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:m}=e,s=async(h,d)=>{let{request:b,internalUserId:y,cursor:g}=d,R=d.initialScope.visible,D=d.initialScope.commentable,U=0,_=setInterval(()=>{let q=++U;n(b,"refresh").then(X=>{q===U&&(R=X.visible,D=X.commentable)})},la);h.onClose(()=>clearInterval(_));let O=g===null?ia:g,P=g!==null&&o!==void 0,T=[],F=null,G=q=>{Ze(q.id,O)||(O=q.id,nc(h,q,{internalUserId:y,visibleSet:R,commentableSet:D}))},B=async(q,X)=>{let[re]=await q.xRange(i,"-","+",{COUNT:1});return re!==void 0&&!Ze(re.id,X)},se=async(q,X)=>{if(await B(q,X))return!1;let re=X;for(;;){let pe=await q.xRange(i,re,"+",{COUNT:Gr}),ne=pe[0];if(ne!==void 0&&ne.id!==re&&await B(q,re))return!1;for(let Z of pe){if(F!==null&&Ze(F,Z.id))return!0;Ze(Z.id,O)||G(Mt(Z,m).entry)}let ye=pe.at(-1);if(pe.length<Gr||ye===void 0||h.isClosed())return!0;re=ye.id}},be=a.subscribe(q=>{if(!P){G(q);return}Ze(q.id,O)||(F===null&&(F=q.id),T.push(q))},q=>{m.error(`[SSE:${y}] Fan-Out reader error:`,q),h.close()});if(h.onClose(be),g===null){await a.ready();try{let q=await o?.getClient();if(q){let X=await q.xRevRange(i,"+","-",{COUNT:1});X.length>0&&!Ze(X[0].id,O)&&(O=X[0].id)}}catch{}}if(h.writeEvent({event:null,id:O===ia?null:O,data:ca}),Ql(h,{intervalMs:bn,retry:Zl,runtime:Kl}),g===null||o===void 0)return;await a.ready();let ue=await o.getClient();if(ue===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await se(ue,g)){h.writeRetry(aa),h.writeEvent({event:"resync-required",id:null,data:""}),h.close();return}P=!1;for(let q of T.splice(0))G(q)};return async({request:h,params:d})=>{let b,y=()=>{let R=new Headers;return b!==void 0&&R.append("Set-Cookie",b),R},g=R=>Xl(R,{data:"",retryMs:aa,headers:y()});try{let R=await t(h,{failureRedirect:null});b=R.cookie;let{user:D}=R;if(!D)return g("auth-required");let U=await r.getUserIdByExternalId(D.id);if(!U)return g("forbidden");if(d.endpoint!=="updates")return new Response("Not Found",{status:404,headers:y()});let _=Gl(h,Sn);if(_!==null&&!Dn(_))return m.warn(`[SSE:${U}] malformed resume cursor; asking the client to resync`),g("resync-required");let O=er(h),P=await l.admit(U,"sse",O);if(P===null){let F=y();for(let[G,B]of Object.entries(We(503)))F.set(G,B);return new Response("Too many streams",{status:503,headers:F})}let T=!1;try{let F=await n(h,"initial");return Jl({requestSignal:O,headers:y(),onError:(G,B)=>m.error(`[SSE:${U}] ${B} failed:`,G),produce:G=>(T=!0,G.onClose(P),s(G,{request:h,internalUserId:U,cursor:_,initialScope:F}))})}finally{T||P()}}catch(R){if(R instanceof Response)throw R;let D=R instanceof Error?R:new Error(String(R));return m.error(`500 sse name=${D.name} message=${D.message}`),new Response("Internal Server Error",{status:500,headers:y()})}}};var da=(e,t)=>{let r=new Headers({...t?.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})},oc=Object.freeze({...xt,route:"api",frameworkDataRefusal:({params:e})=>Mr(e.endpoint)&&_t[e.endpoint].body==="stream"?zt():null}),ac=Object.freeze({...xt,route:"action"}),ic=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),ma=6e4,pa=5,sc=pa*Math.ceil(ma/500),lc=2,cc=6,uc=6e4,dc=pa*lc*cc,mc=2,pc=10,Qr=(e,t,r)=>{let n=ae(e,t,{error:{message:r.message}},r.status);for(let[o,a]of Object.entries(r.headers))n.headers.set(o,a);return n};function Xr(e){Zt(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:de("service.titleMaxLength",r.titleMaxLength,1)},m=e.loginRedirectPath??"/auth/login",s=he(e.logger,3,"[DailyReportAPI]"),h=he(e.logger,3,"[DailyReportVisibility]"),d=he(e.logger,1,"[DailyReportSSE]"),b=he(e.logger,1,"[DailyReportAttachment]"),y=he(e.logger,2,"[DailyReportIsolation]"),g=he(e.logger,2,"[DailyReportAction]"),R=he(e.logger,2,"[DailyReportSearch]"),D=he(e.logger,2,"[DailyReportRefresh]"),U=he(e.logger,2,"[DailyReportStreams]"),_=ze({reason:"refresh_rate_limit",limitPerWindow:dc,windowMs:uc,logger:D,windowFields:()=>"route=api"}),O=vo(U),P=(E,L,v,H)=>{let V=_.spend(L.id,`endpoint=${E}`);return V===null?null:Qr(v,H,V)},T=async(E,L="initial")=>{let v=e.resolveVisibleSourceTypes;if(!v)return Le.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let H=await v(E,{reason:L});return H==null?Le.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):Le.restrictTo(H)}catch(H){return h.error("resolveVisibleSourceTypes threw; failing closed (deny all)",H),Le.restrictTo([])}},F=async({request:E})=>{let{user:L,cookie:v}=await t(E,{failureRedirect:m}),H=new Headers;v&&H.append("Set-Cookie",v);let V=await r.getUserIdByExternalId(L.id),K=V?n(V):null;return{data:{user:L,userId:K},headers:H}},G=r.searchLimits===null?null:Wr({...r.searchLimits,route:Re.search,logger:R}),B=r.searchLimits===null?null:Wr({concurrency:r.searchLimits.concurrency*mc,rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*pc,route:Re.reports,logger:R}),se={[Re.businessDate]:async(E,L,v,H,V)=>{let K=E.searchParams.get(_e.businessDate),$=K===null?null:lt(K);if($===null)return ae(v,L,{error:{message:"Invalid business date"}},400);let j=wt(E.searchParams.get(_e.forceRefresh));if(j===null)return ae(v,L,{error:{message:"Invalid forceRefresh"}},400);let Q=j?P(Re.businessDate,H,v,L):null;if(Q!==null)return Q;let M=await r.getDailyReportsByBusinessDateByExternalId(V,$,H.id,{forceRefresh:j});return ae(v,L,{businessDate:$,reports:M},200)},[Re.idsStream]:Fo({service:r,logger:s,streamSlots:O,refuseForcedRead:(E,L,v)=>P(Re.idsStream,E,L,v)}),[Re.report]:async(E,L,v,H,V)=>{let K=ke(E.searchParams.get(_e.reportHubId));if(K===null)return ae(v,L,{error:{message:"Invalid reportHubId"}},400);let $=wt(E.searchParams.get(_e.forceRefresh));if($===null)return ae(v,L,{error:{message:"Invalid forceRefresh"}},400);let j=$?P(Re.report,H,v,L):null;if(j!==null)return j;let Q=await r.getDailyReportDetailByIdByExternalId(V,K,H.id,{snapshot:!0,forceRefresh:$});return Q?ae(v,L,{report:Q},200):ae(v,L,{error:{message:"Report not found"}},404)},[Re.search]:async(E,L,v,H,V)=>{if(G===null)return ae(v,L,{error:{message:"Unknown endpoint"}},404);let K=E.searchParams.get(_e.searchQuery),$=In(E.searchParams.get(_e.searchCombine));if(K===null||$===null)return ae(v,L,{error:{message:"Invalid search request"}},400);let j=Ko(K,$);if(!j.ok)return ae(v,L,{error:{message:"Invalid search query",reason:j.reason}},400);let Q=await r.getUserIdByExternalId(H.id);if(!Q)return ae(v,L,br([]),200);let M=await G.admit(Q,v.signal);if("refusal"in M)return Qr(v,L,M.refusal);try{let fe=await r.searchDailyReports(V,Q,j.plan);return ae(v,L,br(fe),200)}finally{M.release()}},[Re.reports]:async(E,L,v,H,V)=>{if(B===null)return ae(v,L,{error:{message:"Unknown endpoint"}},404);let K=En(E.searchParams.get(_e.reportIds));if(K===null)return ae(v,L,{error:{message:"Invalid ids"}},400);let $=await r.getUserIdByExternalId(H.id);if(!$)return ae(v,L,{reports:[]},200);let j=await B.admit($,v.signal);if("refusal"in j)return Qr(v,L,j.refusal);try{let Q=await r.getDailyReportDetailsByIdsByExternalId(V,K,H.id);return ae(v,L,{reports:Q},200)}finally{j.release()}}},be=async({request:E,params:L})=>{let{user:v,cookie:H}=await t(E,{failureRedirect:null}),V=H??null;if(!v)return ae(E,V,{error:{message:"Unauthorized"}},401);let K=L.endpoint;if(!Mr(K))return ae(E,V,{error:{message:"Unknown endpoint"}},404);let $=On[_t[K].body];if(!$.includes(E.method)){let Q=ae(E,V,{error:{message:"Method not allowed"}},405);return Q.headers.set("Allow",$.join(", ")),Q}let j=ce();try{let Q=new URL(E.url),M=await T(E),fe=await se[K](Q,V,E,v,M);return _t[K].body==="json"&&s.debug(`${fe.status} endpoint=${K} etag_match=${fe.status===304}`),fe}catch(Q){let M=ce()-j,fe=Q instanceof Error?Q:new Error(String(Q));return s.error(`500 endpoint=${K} elapsed=${M}ms name=${fe.name} code=${"code"in fe?fe.code:"N/A"} message=${fe.message}`,fe),ae(E,V,{error:{message:"Internal Server Error"}},500)}},ue=Nn(g),q=ze({reason:"rate_limit",limitPerWindow:sc,windowMs:ma,logger:g,windowFields:()=>"route=action"}),X=async(E,L,v,H,V)=>{let{clientTempId:K}=E;if(E.intent==="create"){let M=await r.createDailyReport(L,E.businessDate,K);return V(E,M.reportHubId,{report:M})}let{reportHubId:$,businessDate:j}=E,Q=async(M,fe)=>{try{let we=await fe(M.value);return V(M,$,{updatedStatus:{isStarred:we.isStarred,isRead:we.isRead},operationTimestamp:M.operationTimestamp})}catch(we){if(we instanceof Error&&we.message==="Not Found")return H({error:"Report not found"},{status:404});throw we}};switch(E.intent){case"update":try{return await r.updateDailyReport($,L,E.changes,K),V(E,$,{})}catch(M){if(M instanceof Error){if(M.message==="Unauthorized")return H({error:"Unauthorized"},{status:403});if(M.message==="Not Found")return H({error:"Report not found"},{status:404})}throw M}case"publish":try{let M=await r.publishDailyReport($,L,K);return V(E,$,{report:M})}catch(M){if(M instanceof Error){if(M.message==="Unauthorized")return H({error:"Unauthorized"},{status:403});if(M.message==="Not Found")return H({error:"Report not found"},{status:404})}throw M}case"delete":try{return await r.deleteDailyReport($,L,K),V(E,$,{})}catch(M){if(M instanceof Error){if(M.message==="Unauthorized")return H({error:"Unauthorized"},{status:403});if(M.message==="Not Found")return H({error:"Report not found"},{status:404})}throw M}case"toggleStar":return await Q(E,M=>r.setStarStatus(v,L,$,j,M,K));case"toggleRead":return await Q(E,M=>r.setReadStatus(v,L,$,j,M,K));case"addComment":try{let M=await r.addComment(v,L,$,E.content,j,K);return V(E,$,{newComment:M})}catch(M){if(M instanceof Error){if(M.message==="Not Found")return H({error:"Report not found"},{status:404});if(M.message.startsWith("Comments are restricted"))return H({error:"Comments are restricted for this report"},{status:403})}throw M}case"deleteComment":try{return await r.deleteComment(v,L,$,E.commentId,j,K),V(E,$,{deletedCommentId:E.commentId})}catch(M){if(M instanceof Error){if(M.message==="Unauthorized")return H({error:"Unauthorized"},{status:403});if(M.message==="Not Found")return H({error:"Comment not found"},{status:404})}throw M}}},re=async({request:E,params:L})=>{let{user:v,cookie:H}=await t(E,{failureRedirect:null}),V=(j,Q)=>da(j,{...Q,setCookie:H}),K=(j,Q,M)=>da(ic(j,Q,M),{setCookie:H});if(!v)return V({error:"Unauthorized"},{status:401});let $=ce();try{if(L.endpoint!==Re.action)return V({error:"Unknown endpoint"},{status:404});let j=q.spend(v.id,"action");if(j!==null)return V({error:j.message},{status:j.status,headers:j.headers});let Q=await vn(E,l);if("refusal"in Q){let{refusal:Ne}=Q;return Ne.status===413&&ue(Ne.measuredBy),V({error:Ne.error},{status:Ne.status})}let{command:M}=Q;if(M.intent==="clearCache"&&!e.enableDevCacheClear)return V({error:"Invalid intent"},{status:400});let fe=await r.getUserIdByExternalId(v.id);if(!fe)return V({error:"User not found"},{status:404});let we=await T(E);return M.intent==="clearCache"?(await r.clearCache(),V({status:"OK",intent:"clearCache"})):await X(M,fe,we,V,K)}catch(j){if(j instanceof Response)throw j;let Q=ce()-$,M=j instanceof Error?j:new Error(String(j));return s.error(`500 action elapsed=${Q}ms name=${M.name} message=${M.message}`,M),V({error:"Internal Server Error"},{status:500})}},pe=ua({authenticate:t,service:r,resolveViewerScope:T,redis:o,sseReader:a,streamKey:i,streamSlots:O,logger:d}),ne=Co({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:T,logger:b}),ye=Fn(y),Z=(E,L)=>async v=>{let H=Hn(v.request)?E.frameworkDataRefusal(v):null;if(H!==null)throw H;return $n(v.request,E)?(ye(E.route,v.request),E.crossSiteRejection()):L(v)};return{index:{loader:F},api:{loader:Z(oc,be),action:Z(ac,re)},sse:{loader:Z(sa,pe)},attachment:{loader:Z(xo,ne)}}}import{chunk as Ec,MAX_IN_LIST as wc,runWithTransactionRetry as _c}from"@aiquants/mssql";import{aliasedTable as bt,and as me,asc as Ce,desc as St,eq as C,getColumns as xc,inArray as Te,isNull as Ee,or as Dt,sql as _a}from"drizzle-orm";var ya=(e,t,r,n)=>ve(n.commentable,t)||e.authorUserId!==null&&e.authorUserId===r;var yc=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],hc=["document","comment"],fc=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion"],Rc=["hubId","ordinal","authorUserId","commentText"],Zr=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},ha=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw gr(e,n,r)},fa=(e,t,r)=>{if(typeof t!="object"||t===null)throw ie(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw ie(`${e}.${o}`,"a column",n[o])},Ra=(e,t)=>{if(!Zr(e))throw ie("search","a plain object",e);ha("search key",e,yc);let{tables:r}=e;if(!Zr(r))throw ie("search.tables","a plain object with document and comment",r);ha("search.tables key",r,hc),fa("search.tables.document",r.document,fc),fa("search.tables.comment",r.comment,Rc);let n=new Map;if(e.externalSourceTexts!==void 0){if(!Zr(e.externalSourceTexts))throw ie("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw gr("search.externalSourceTexts key",o,t);if(typeof a!="function")throw ie(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:de("search.concurrency",e.concurrency,1),rateLimitPerMinute:de("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var ft=e=>{let t=typeof e=="object"&&e!==null?e.recordset:void 0;if(!Array.isArray(t))throw new Error("[daily-report] search: the database result has no recordset");return t},Rt=(e,t)=>{let r=typeof e=="string"?ke(e):typeof e=="number"&&ut(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},gt=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};import{sql as J}from"drizzle-orm";var gc=/[[%_]/gu,bc=e=>e.replace(gc,t=>`[${t}]`),ga=e=>`%${bc(e)}%`;var Be=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),De=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),Y=e=>J`${J.identifier(e.name)}`,en=e=>J.join(e.map(t=>J`${t}`),J`, `),ba=(e,t)=>J`SELECT ${Y(e.id)} AS ${J.identifier(De.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${en(t)}) ORDER BY ${e.id}`,Sc=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(ga),l=J.join(i.map(d=>J`${o.searchText} LIKE ${d}`),J` OR `),m=J.join(i.map(d=>J`${a.commentText} LIKE ${d}`),J` OR `),s=Ot(n.sourceType,r.scope.commentable),h=s===void 0?J``:J` AND (${s} OR ${a.authorUserId} = ${r.userId})`;return J`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${m})${h}))`},Dc=(e,t,r)=>J`(${J.join(t.words.map(n=>Sc(e,n,r)),J` AND `)})`,Sa=(e,t,r,n,o)=>{let{hub:a,hubLabel:i,label:l}=e,{document:m}=e.search,s=[J`${a.deletedAt} IS NULL`];n.length>0&&s.push(J`(${a.userId} = ${r.userId} OR NOT EXISTS (SELECT 1 FROM ${i} INNER JOIN ${l} ON ${l.id} = ${i.labelId} WHERE ${i.hubId} = ${a.id} AND ${l.name} IN (${en(n)})))`);let h=Ot(a.sourceType,r.scope.visible);h!==void 0&&s.push(h),o!==void 0&&s.push(J`${a.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(o)}))`);let d=t.combine==="intersection"?J` AND `:J` OR `;return s.push(J`(${J.join(t.sets.map(b=>Dc(e,b,r)),d)})`),J`SELECT ${Y(a.id)} AS ${J.identifier(Be.reportHubId)}, CONVERT(char(10), ${Y(a.businessDate)}, 23) AS ${J.identifier(Be.businessDate)}, ${Y(a.sourceType)} AS ${J.identifier(Be.sourceType)} FROM ${a} INNER JOIN ${m} ON ${m.hubId} = ${a.id} WHERE ${J.join(s,J` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},Da=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(m=>({[n.hubId.name]:m.hubId,[n.searchText.name]:m.searchText,[n.sourceDigest.name]:m.sourceDigest,[n.normalizerVersion.name]:r}))),i=JSON.stringify(t.flatMap(m=>m.comments.map(s=>({[o.hubId.name]:m.hubId,[o.ordinal.name]:s.ordinal,[o.authorUserId.name]:s.authorUserId,[o.commentText.name]:s.commentText})))),l=JSON.stringify(t.map(m=>m.hubId));return J`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${Y(n.hubId)} bigint, ${Y(n.searchText)} nvarchar(max), ${Y(n.sourceDigest)} char(64), ${Y(n.normalizerVersion)} varchar(64))) AS s ON t.${Y(n.hubId)} = s.${Y(n.hubId)}
|
|
8
|
-
WHEN MATCHED THEN UPDATE SET t.${
|
|
9
|
-
WHEN NOT MATCHED THEN INSERT (${
|
|
1
|
+
var Hn=e=>{throw TypeError(e)};var Un=(e,t,r)=>t.has(e)||Hn("Cannot "+r);var Lt=(e,t,r)=>(Un(e,t,"read from private field"),r?r.call(e):t.get(e)),Or=(e,t,r)=>t.has(e)?Hn("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Nr=(e,t,r,n)=>(Un(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var ms=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,se=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${ms(r)}`),gt=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),vr=(e,t,r)=>se(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),ee=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw se(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},lt=(e,t,r,n)=>t===void 0?n:ee(e,t,r);var ce=()=>Math.floor(performance.now());var $e=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},kr=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{}}}),Ot=(e,t)=>t?e.map(r=>structuredClone(r)):e,Nt=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.inFlight=new Map;this.forcedFetches=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.defaultTtlMs;if(a-(o.expireAt-ce())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let c=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:s,expireAt:ce()+a,epoch:c}),s})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.startFetch=(t,r)=>{let{cacheKey:n,admission:o}=t,a;a=(async()=>{let l=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&c===null)throw new $e(o.signal.aborted?"aborted":"busy");try{for(let y of r)y();let s=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:s,expireAt:ce()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),s}finally{c?.()}})(),this.inFlight.set(n,a);let i=()=>{this.inFlight.get(n)===a&&this.inFlight.delete(n)};return a.then(i,i),a};this.forcedFetch=t=>{let{cacheKey:r}=t,n=t.onFetchStart===void 0?[]:[t.onFetchStart],o=this.forcedFetches.get(r);if(o===void 0)return this.runForcedFetch(t,n);if(o.pending===null){let a=[],i=()=>this.runForcedFetch(t,a);o.pending={promise:o.running.then(i,i),onFetchStarts:a}}return o.pending.onFetchStarts.push(...n),o.pending.promise};this.runForcedFetch=(t,r)=>{let{cacheKey:n}=t,o=this.startFetch(t,r);this.forcedFetches.set(n,{running:o,pending:null});let a=()=>{let i=this.forcedFetches.get(n);i?.running===o&&i.pending===null&&this.forcedFetches.delete(n)};return o.then(a,a),o};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o,admission:a}=t;if(n){if(a?.signal.aborted)throw new $e("aborted");return this.buckets.delete(r),Ot(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>ce())if(t.epochKey){let c=await this.epochStore.getEpoch(t.epochKey);if(c===null||i.epoch===c)return this.maybeRefreshAhead(t),Ot(i.records,o);this.buckets.delete(r)}else return this.maybeRefreshAhead(t),Ot(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return Ot(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new $e("aborted");return Ot(await this.startFetch(t,t.onFetchStart===void 0?[]:[t.onFetchStart]),o)};this.readOwnOrRetry=async(t,r)=>{try{return await t}catch(n){let{admission:o}=r;if(!(n instanceof $e&&(o===void 0||n.reason==="aborted"&&!o.signal.aborted)))throw n;return this.getOrFetch({...r,snapshot:!1})}};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)};this.defaultTtlMs=ee("defaultTtlMs",t.defaultTtlMs,1),this.maxBuckets=ee("maxBuckets",t.maxBuckets,1),this.lastSweepAt=ce()}writeBucket(t,r){this.buckets.delete(t),this.buckets.set(t,r);let n=ce();n-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(n);for(let o of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets)break;this.buckets.delete(o)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.buckets.delete(r)}};var $n="ids-stream";var Kt=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 i=0;i<a.length;i++){let l=a.charCodeAt(i);t^=l&255,t=Math.imul(t,16777619),r^=l&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+(?=.)/,"")},Jt=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,Bn=e=>{for(let t=1;t<e.length;t++)if(Jt(e[t-1],e[t])>0)return!1;return!0},Fn=(e,t)=>{let r=e.findIndex(n=>Jt({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var ue=Object.freeze({businessDate:"business-date",idsStream:$n,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",action:"action"}),Ae=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var ps=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Vn=e=>e<10?`0${e}`:`${e}`,ys=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Vn(e.getMonth()+1),n=Vn(e.getDate());return`${t}-${r}-${n}`},bt=e=>{let t=ps.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),i=Number(n),l=Number(o);if(a<1)return null;let c=new Date(0);return c.setUTCFullYear(a,i-1,l),c.getUTCFullYear()!==a||c.getUTCMonth()!==i-1||c.getUTCDate()!==l?null:`${r}-${n}-${o}`},Qt=e=>bt(e)===e;var Le=e=>e==null?null:e instanceof Date?ys(e):bt(e);var Yn=(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)}}},Hd=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),qn=e=>`[DailyReport${e}]`,he=(e,t,r)=>e===void 0?Yn(t,qn(r)):Yn(0,qn(r),e);var hs="legacy-",Hr=e=>`${hs}${e}`;import{z as fs}from"zod";var Dt=e=>Number.isSafeInteger(e)&&e>0,Se=fs.number().int().positive().max(Number.MAX_SAFE_INTEGER);var Rs=/^[1-9][0-9]*$/,Ss=/^(?:0|[1-9][0-9]*)$/,Be=e=>{if(e===null||!Rs.test(e))return null;let t=Number(e);return Dt(t)?t:null},Ur=e=>{if(e===null||!Ss.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},$r=e=>e==="true"?!0:e==="false"?!1:null,vt=e=>e===null?!1:$r(e);var Wn=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),Qe=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var gs=2166136261,bs=16777619,Br=e=>{let t=gs;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,bs);return t>>>0},Ds=String.fromCodePoint(3),As=String.fromCodePoint(2),Ts=String.fromCodePoint(1),Xt=e=>Br(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(Ds)).join(As)).join(Ts));var jn=e=>e==="intersection"||e==="union",_e=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Fr=2,Zt=2,ct=Object.freeze({word:0,reading:1});var Vr=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var Wd=2*(1+Fr);import{z as Zd}from"zod";var er=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|-[1-9][0-9]{0,15})$/;import{z as L}from"zod";var zn=15e3,Gn="lastEventId",Es=/^\d{1,15}-\d{1,15}$/,Kn=e=>Es.test(e),Is=L.object({name:L.string().nullish(),affiliation:L.string().nullish()}),_s=L.object({name:L.string().nullish(),text:L.string().nullish(),color:L.string().nullish()}),ws=L.object({id:Se,name:L.string().nullish(),color:L.string().nullish()}),Jn=L.object({id:Se,userId:L.string().nullish(),userName:L.string().nullish(),content:L.string().nullish(),createdAt:L.string().nullish(),isMine:L.boolean()}),xs=L.object({id:L.string(),fileName:L.string(),fileType:L.string().nullable(),fileSize:L.number().nullable(),createdAt:L.string().nullable(),state:L.enum(["present","absent","unknown"]),hasThumbnail:L.boolean().default(!1)}),Yr=L.object({reportHubId:Se,date:L.string().nullish(),createdAt:L.string().nullish(),author:L.string().nullish(),userId:L.string().nullish(),sourceType:L.string().nullish(),employeeName:L.string().nullish(),updatedBy:L.string().nullish(),updatedAt:L.string().nullish(),category:L.string().nullish(),creationCategory:L.string().nullish(),visitTimeFrom:L.string().nullish(),visitTimeTo:L.string().nullish(),customerName:L.string().nullish(),interviewers:L.array(Is),subject:L.string().nullish(),content:L.string().nullish(),externalComments:L.array(_s),isRead:L.boolean(),isStarred:L.boolean(),labels:L.array(ws),postedComments:L.array(Jn),attachments:L.array(xs).default([])}),ut=L.string().regex(er),Cs=L.object({type:L.literal("connected")}),tr=L.object({type:L.literal("status-update"),reportHubId:Se,statusType:L.enum(["star","read"]),value:L.boolean(),clientTempId:ut,recipientRawUserId:Se.optional()}),qr=L.string().optional(),Wr=L.object({type:L.literal("comment-add"),reportHubId:Se,comment:Jn,clientTempId:ut,recipientRawUserId:Se.optional(),sourceType:qr}),jr=L.object({type:L.literal("comment-delete"),reportHubId:Se,commentId:Se,clientTempId:ut,recipientRawUserId:Se.optional(),sourceType:qr}),zr=L.object({type:L.literal("report-create"),reportHubId:Se,report:Yr,clientTempId:ut,recipientRawUserId:Se.optional()}),Gr=L.object({type:L.literal("report-update"),reportHubId:Se,report:Yr,clientTempId:ut,recipientRawUserId:Se.optional()}),Kr=L.object({type:L.literal("report-publish"),reportHubId:Se,report:Yr,clientTempId:ut,recipientRawUserId:Se.optional()}),Jr=L.object({type:L.literal("report-delete"),reportHubId:Se,clientTempId:ut,sourceType:qr}),Qn=L.discriminatedUnion("type",[Cs,tr,Wr,jr,zr,Gr,Kr,Jr]);var Oe=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var rr=Math.max(1,Math.floor(10.556701030927835));var Fe=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Ne=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=i=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(s=>[s,0]))};o.set(i,l),Fe(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,c)=>{let s=o.get(i);if(s!==void 0){s.count+=1,s.tallies[l]+=1;return}c(),a(i)}}};var Qr=e=>e!==null&&er.test(e)?e:null,Xr=e=>jn(e)?e:null,Zr=e=>{if(e===null)return null;let t=e.split(",");if(t.length>_e.maxDetailIds)return null;let r=[];for(let n of t){let o=Be(n);if(o===null||r.includes(o))return null;r.push(o)}return r},Xn=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var eo=Object.freeze({status:400,error:"Invalid form"}),to=e=>({status:413,error:"Form too large",measuredBy:e}),Ms=(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)}}))},Ps=async e=>{let t=Ur(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:to("declared")};let r=!1,n=e.body===null?null:Ms(e.body,1048576,()=>{r=!0}),o=new Headers,a=e.headers.get("Content-Type");a!==null&&o.set("Content-Type",a);let i;try{i=await new Response(n,{headers:o}).formData()}catch{return{refusal:r?to("counted"):eo}}let l=Xn(i);return l===null?{refusal:eo}:{fields:l}},ro=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=$r(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},oo=Object.freeze({update:(e,t,r)=>{let n=e.get(Oe.title),o=e.get(Oe.content);if(n!==null&&n.length>r.titleMaxLength)return{error:"Invalid title"};let a={};return n!==null&&(a.title=n),o!==null&&(a.content=o),{command:{...t,intent:"update",changes:a}}},publish:(e,t)=>({command:{...t,intent:"publish"}}),delete:(e,t)=>({command:{...t,intent:"delete"}}),toggleStar:ro("toggleStar",Oe.isStarred),toggleRead:ro("toggleRead",Oe.isRead),addComment:(e,t)=>{let r=e.get(Oe.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=Be(e.get(Oe.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),Ls=e=>Object.hasOwn(oo,e),Os=(e,t)=>{let r=e.get(Oe.intent),n=e.get(Oe.businessDate),o=n===null?null:bt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Oe.operationTimestamp),i=Ur(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(Oe.clientTempId);if(!l)return{error:"clientTempId required"};let c=Qr(l);if(c===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:c,businessDate:o,operationTimestamp:i}};let s=Be(e.get(Oe.reportHubId));return s===null?{error:"Invalid reportHubId"}:r===null||!Ls(r)?{error:"Invalid intent"}:oo[r](e,{clientTempId:c,businessDate:o,operationTimestamp:i,reportHubId:s},t)},ao=async(e,t)=>{let r=await Ps(e);if("refusal"in r)return r;let n=Os(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Ns=6e4,vs="form_too_large",no=["declared","counted"],io=e=>{let t=Ne({windowMs:Ns,tallies:no,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${no.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(vs,r,n)}};var nt=Object.freeze({[ue.businessDate]:{body:"json",admission:["refresh-bucket","cache","miss-gate"]},[ue.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[ue.report]:{body:"json",admission:["refresh-bucket","cache","miss-gate"]},[ue.search]:{body:"json",admission:["search-limiter"]},[ue.reports]:{body:"json",admission:["search-limiter"]},[ue.searchMarks]:{body:"json",admission:["search-limiter"]}}),so=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),en=e=>e!==void 0&&Object.hasOwn(nt,e);var tn=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),lo=e=>Object.hasOwn(tn,e);var ks="download",Hs="thumbnail",Us="1";var rn=e=>{let t=e.getAll(Hs),r=e.getAll(ks);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&lo(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Us?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};import{createHash as $s}from"crypto";var nn=e=>`"${$s("sha256").update(e).digest("hex")}"`,co=e=>nn(JSON.stringify(e));var We=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),on=(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},oe=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=nn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...We});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&on(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},Xe=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...We});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},Bs=5e3/1e3,Fs=new Map([[503,Bs]]),xe=e=>{let t=Fs.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var sn="Cross-site request rejected",Vs="Not Found",Ys=new Set(["same-origin","none"]),qs=new Set(["GET","HEAD","OPTIONS"]),uo=["api","action","sse","attachment"],mo=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...We}}),Ws=()=>mo(403,sn),nr=()=>mo(404,Vs),kt=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:Ws}),po=e=>new URL(e.url).pathname.endsWith(".data"),js=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},yo=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(qs.has(e.method)||js(e)):Ys.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},zs=6e4,Gs="refusals",Ks=32,Js=/^[a-z-]+$/,an=e=>{if(e===null)return"-";let t=e.slice(0,Ks);return Js.test(t)&&t===e?e:JSON.stringify(t)},ho=e=>{let t=Ne({windowMs:zs,tallies:uo,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${uo.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${an(a.get("Sec-Fetch-Site"))} mode=${an(a.get("Sec-Fetch-Mode"))} dest=${an(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(Gs,r,o)}};var fo=(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 Qs="same-origin",Xs="SAMEORIGIN",At=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Qs,"X-Frame-Options":Xs}),or=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...At});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Ro=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Zs=/^[\x20-\x7E]+$/,el=/^[\w.+-]+\/[\w.+-]+/,ln=e=>e&&Zs.test(e)&&el.test(e)?e:null,tl=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,So=e=>encodeURIComponent(e.replace(tl,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),go=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),ar={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},bo={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},ir=e=>typeof e=="string"&&Object.hasOwn(bo,e),sr=e=>bo[e],Ze="Attachment request failed";var je=e=>{let t=ee("limit",e.limit,1),r=ee("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ee("queue.max",e.queue.max,0),maxPerOwner:ee("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ee("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,c=(g,I)=>g.get(I)??0,s=(g,I,v)=>{let $=c(g,I)+v;$<=0?g.delete(I):g.set(I,$)},y=g=>c(l,g)<r,m=g=>o<t&&y(g),S=g=>(o+=1,s(l,g,1),b(g)),f=()=>{let g=-1,I=r;for(let[v,$]of a.entries()){let w=c(l,$.owner);if(w<I&&(g=v,I=w,w===0))break}return g},R=()=>{for(;o<t;){let g=f();if(g<0)return;let[I]=a.splice(g,1);s(i,I.owner,-1),I.grant(S(I.owner))}},b=g=>{let I=!1;return()=>{I||(I=!0,o-=1,s(l,g,-1),R())}};return{canAcquire:m,acquire:(g,I)=>{if(I.aborted)return Promise.resolve(null);if(m(g))return Promise.resolve(S(g));if(n===null||a.length>=n.max||c(i,g)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:v}=n,$=w=>{let T=()=>{let le=a.indexOf(k);le<0||(a.splice(le,1),s(i,g,-1),H(),w(null))},F=Fe(T,v),H=()=>{clearTimeout(F),I.removeEventListener("abort",T)},k={owner:g,grant:le=>{H(),w(le)}};a.push(k),s(i,g,1),I.addEventListener("abort",T,{once:!0})};return new Promise($)}}};var rl=1024,cn="Too many requests",nl=(e,t)=>{ee("limitPerWindow",e,1),ee("windowMs",t,1);let r=new Map,n=(a,i)=>{i<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(i-a.lastRefillMs)*e/t),a.lastRefillMs=i)},o=(a,i)=>{let l=r.get(a);l&&r.delete(a);let c=l??{tokens:e,lastRefillMs:i};n(c,i),r.set(a,c);for(let s of r.keys()){if(r.size<=rl)break;r.delete(s)}return c};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let c=r.get(a);c&&(n(c,i),c.tokens=Math.min(e,c.tokens+l))}}},et=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ee("windowMs",r,1e3)%1e3!==0)throw se("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=nl(e.limitPerWindow,r),i=Object.freeze({status:429,message:cn,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Ne({windowMs:r,tallies:[t],writeSuppressed:(c,{count:s,since:y})=>{n.warn(`${t}_suppressed count=${s} since=${y} ${o(c)}`)}});return{spend:(c,s)=>a.consume(c,ce())?null:(l.record(c,t,()=>n.warn(`429 ${s} reason=${t}`)),i),refund:(c,s)=>{a.refund(c,ce(),s)}}};var al=256*1024,Do=6e4,il=e=>Math.ceil(e/2),sl=new Uint8Array(new ArrayBuffer(0)),ll=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=sl,t()},i=l=>{clearTimeout(o),o=Fe(()=>{l.error(new Error(`attachment body idle for ${Do} ms`)),a()},Do)};return new ReadableStream({start(l){i(l)},pull(l){let c=Math.min(n+al,r.byteLength);if(c>n&&l.enqueue(r.slice(n,c)),n=c,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},Ao=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=et({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:c=>`viewer=${c}`}),l=je({limit:e.concurrency,maxHeldPerOwner:il(e.concurrency),queue:null});return async c=>{let{request:s,delivery:y,attachmentId:m,internalUserId:S,readAttachment:f,cookie:R,fail:b}=c,g=e.maxBytes,I=i.spend(S,`attachment=${m} viewer=${S}`);if(I)return b(I.status,I.message,I.headers);let v=await n(s),$=await t.getAttachmentForUser(v,m,S);if(!$)return o.warn(`404 attachment=${m} viewer=${S} reason=not_visible`),b(404,"Attachment not found");if($.fileSize!=null&&$.fileSize>g)return o.warn(`413 attachment=${m} viewer=${S} reason=db_size`),b(413,"Attachment too large");let w=ln($.fileType),T=`filename="${go($.fileName)}"; filename*=UTF-8''${So($.fileName)}`,F=await l.acquire(S,s.signal);if(!F)return s.signal.aborted?(o.info(`503 attachment=${m} viewer=${S} reason=aborted`),b(503,"Attachment request aborted")):(o.warn(`503 attachment=${m} viewer=${S} reason=concurrency`),b(503,"Too many concurrent downloads",xe(503)));let H=!1;try{let k=await f($.filePath,{maxBytes:g,head:s.method==="HEAD",principal:r(S),signal:s.signal});if(s.signal.aborted)return o.info(`503 attachment=${m} viewer=${S} reason=aborted`),b(503,"Attachment request aborted");if(!k.ok){if(!ir(k.reason))return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=failure_reason`),b(500,Ze);let me=sr(k.reason);return k.reason==="not_found"&&a(m,!1),o.warn(`${me} attachment=${m} viewer=${S} reason=${k.reason} code=${k.code??"-"}`),b(me,ar[me],xe(me))}if(k.bytes.byteLength>g)return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=over_max_bytes`),b(500,Ze);let le=s.method==="HEAD";if(le&&k.size!==void 0&&k.size>g)return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=over_max_bytes`),b(500,Ze);if(!le&&k.size!==void 0&&k.size!==k.bytes.byteLength)return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=size_mismatch`),b(500,Ze);let de=w??ln(k.contentType),fe=de!==null&&Ro.has(de),q=fe?de:"application/octet-stream",re=fe&&y.kind!=="download"?"inline":"attachment",Z=le?k.size:k.bytes.byteLength,ie=new Headers({"Content-Type":q,"Content-Disposition":`${re}; ${T}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...At});return Z!==void 0&&ie.set("Content-Length",String(Z)),R&&ie.append("Set-Cookie",R),a(m,!0),o.info(`200 attachment=${m} viewer=${S} type=${q} disposition=${re} bytes=${Z??"-"}`),le?new Response(null,{status:200,headers:ie}):(H=!0,new Response(ll(k.bytes,F),{status:200,headers:ie}))}finally{H||F()}}};var Ce=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Ym=Ce.queueWaitMs+Ce.readMs+Ce.renderMs+Ce.transferMarginMs;import{Buffer as cl}from"buffer";var Io=new Set([194,198,202,206]),ul=new Set([192,193,194,195]),_o=216,dl=217,wo=218,ml=4,pl=64,yl=2,To=8,Eo=28,ot=12,un=8,hl=20,xo=ot+un+10,fl=2,tt=(e,t)=>e[t]<<8|e[t+1],Tt=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},ze=(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},Co=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Mo=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),Po=e=>(e.stepsLeft-=1,e.stepsLeft>=0),Lo=e=>e[0]===255&&e[1]===_o,Oo=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!Po(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===dl)return"eoi";if(o===0||o===_o)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=tt(e,n),i=n+a;return a<2||i>e.byteLength?null:(r.marker=o,r.body=n+2,r.length=a,r.end=i,"segment")}},Rl=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!Po(r))return null;if(a+1>=n)return n;let i=e[a+1];if(i===255)a+=1;else if(i===0||i>=208&&i<=215){if(a+=2,a>=n||e[a]!==255)break}else return a}o=a}},No=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=tt(e,r+1),a=tt(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let c=0;c<i;c+=1){let s=e[r+7+3*c],y=s>>4,m=s&15;if(y<1||y>4||m<1||m>4)return null;l.push({id:e[r+6+3*c],horizontal:y,vertical:m})}return{marker:t,width:a,height:o,components:l}},vo=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>ml||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},ko=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:Io.has(e.marker)||t<e.components.length}),dn=e=>{if(!Lo(e))return null;let t=Mo(e.byteLength),r=null;for(let n=2;;){if(Oo(e,n,t)!=="segment")return null;if(Co(t.marker)){if(r!==null||(r=No(e,t),r===null))return null}else if(t.marker===wo){if(r===null)return null;let o=vo(e,t);return o===null?null:ko(r,o.length)}n=t.end}},Ho=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*To)),i=Math.ceil(e.height*o/(r*To));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},Uo=e=>e.multiScan?Ho(e).reduce((r,n)=>r+n,0)*pl*yl:0,Sl=896,$o=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!Lo(e))return null;let n=cl.from(e.buffer,e.byteOffset,e.byteLength),o=Mo(r),a=null,i=null,l=new Map,c=0,s=0,y=0;for(let m=2;;){let S=Oo(e,m,o);if(S===null)return null;if(S==="eoi")return i===null?null:{header:i,blockVisits:s};if(m=o.end,Co(o.marker)){if(a!==null||!ul.has(o.marker)||(a=No(e,o),a===null))return null;let f=Ho(a);l=new Map;for(let[R,b]of a.components.entries()){let g=l.get(b.id);l.set(b.id,g===void 0?f[R]:Math.max(g,f[R]))}c=a.components.length*(Io.has(a.marker)?Sl:1)}else if(o.marker===wo){if(a===null||y===c)return null;let f=vo(e,o);if(f===null)return null;for(let b of f){let g=l.get(b);if(g===void 0)return null;s+=g}if(y+=1,i===null&&(i=ko(a,f.length)),s>t||!i.multiScan)return{header:i,blockVisits:s};let R=Rl(n,o.end,o);if(R===null)return null;m=R}}},Bo=e=>{if(e.byteLength<24||tt(e,8)!==0||tt(e,10)!==13||!ze(e,12,"IHDR"))return null;let t=tt(e,16)*65536+tt(e,18),r=tt(e,20)*65536+tt(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},gl=e=>{if(ze(e,ot,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Tt(e,26,2)&16383,r=Tt(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(ze(e,ot,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Tt(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return ze(e,ot,"VP8X")?e.byteLength<xo?null:{width:Tt(e,24,3)+1,height:Tt(e,27,3)+1}:null},Fo=e=>{if(Bo(e)===null||e.byteLength<=Eo)return null;switch(e[Eo]){case 0:return!1;case 1:return!0;default:return null}},Vo=(e,t)=>{if(ze(e,ot,"VP8 "))return"lossy";if(ze(e,ot,"VP8L"))return"lossless";if(!ze(e,ot,"VP8X")||e.byteLength<xo)return null;if((e[hl]&fl)!==0)return"animated";let r=!1,n=t;for(let o=ot;o+un<=e.byteLength;){if(n-=1,n<0)return null;if(ze(e,o,"VP8L"))return"lossless";if(ze(e,o,"VP8 "))return r?"lossy-alpha":"lossy";ze(e,o,"ALPH")&&(r=!0);let a=Tt(e,o+4,4);o+=un+a+a%2}return null},Yo={png:Bo,jpeg:dn,webp:gl};var mn=Object.freeze(["image/webp","image/jpeg","image/png"]),pn=1024*1024;var bl=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Dl={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Al=new Set(mn),Tl=e=>typeof e=="string"&&Al.has(e),El=256,lr=(e,t)=>e.fileType===null||!bl.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Il=[137,80,78,71,13,10,26,10],_l=[255,216,255],wl=[[71,73,70,56,55,97],[71,73,70,56,57,97]],xl=[82,73,70,70],Cl=[87,69,66,80],Ht=(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},yn=e=>{if(Ht(e,Il,0))return"png";if(Ht(e,_l,0))return"jpeg";for(let t of wl)if(Ht(e,t,0))return"gif";return Ht(e,xl,0)&&Ht(e,Cl,8)?"webp":null},qo=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:co([t])}},Wo=(e,t)=>{if(!Tl(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>pn)return"too_large";let r=Dl[e.contentType];if(yn(e.bytes)!==r)return"signature";let n=Yo[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},jo=e=>{ee("maxBytes",e.maxBytes,0),ee("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 i=(a.kind==="thumbnail"?a.bytes.byteLength:0)+El;if(i>e.maxBytes||e.maxEntries===0)return;let l=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:l,weight:i}),r+=i;for(let c of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(c)}}}};var hn=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ce(),l=new AbortController,c=!1,s,y,m=()=>{a(ce()-i)},S=w=>{s=Fe(()=>{c=!0,w({timedOut:!0}),y=Fe(m,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},f=new Promise(S),R=AbortSignal.any([r,l.signal]),b=w=>{w(n(R))},g=new Promise(b),I=w=>(clearTimeout(s),clearTimeout(y),c&&o(ce()-i,w.kind==="error"?{error:w.error}:null),w),v=g.then(w=>I({kind:"value",value:w}),w=>I({kind:"error",error:w}));return{outcome:Promise.race([g.then(w=>({timedOut:!1,value:w})),f]),settled:v}};var at={404:"Attachment not found",500:Ze,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},zo=(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=Wo(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Ml=e=>{let t=new AbortController,r=()=>{t.abort()},n=Fe(r,Ce.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Go=()=>{},Pl=(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)}),Ko=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,c=(f,R)=>{let b=R.then(Go,Go);l.set(f,b);let g=()=>{l.get(f)===b&&l.delete(f)};b.then(g)},s=async(f,R)=>{let b=l.get(f.key);if(b===void 0)return t.acquire(f.owner,R);let g=Ml(R);try{if(await Pl(b,g.signal),g.signal.aborted)return null;let I=r.get(f.key);return I!==void 0?{...I,identity:"verified"}:await t.acquire(f.owner,g.signal)}finally{g.end()}},y=(f,R)=>{if(f.fileSize===null)return R.kind==="exact"?"verified":"unrecorded";if(R.kind==="exact"?R.bytes===f.fileSize:f.fileSize>R.maxBytes)return"verified";let g=R.kind==="exact"?String(R.bytes):`>${R.maxBytes}`;return i.warn(`size_mismatch expected=${f.fileSize} got=${g} attachment=${f.attachmentId} viewer=${f.owner} variant=thumbnail`),"unverified"},m=(f,R)=>(b,g)=>{let I=g===null?"":` message=${g.error instanceof Error?g.error.message:"unknown"}`;i.warn(`${f}_overrun ms=${b} attachment=${R.attachmentId} viewer=${R.owner} variant=thumbnail${I}`)},S=(f,R)=>b=>{i.warn(`${f}_stuck ms=${b} attachment=${R.attachmentId} viewer=${R.owner} variant=thumbnail`)};return async(f,R)=>{let b=await s(f,R);if(b===null)return{kind:"failure",status:503,reason:R.aborted?"aborted":"queue"};if(typeof b!="function")return b;let g=b,I=null;try{if(R.aborted)return{kind:"failure",status:503,reason:"aborted"};let v=r.get(f.key);if(v!==void 0)return{...v,identity:"verified"};let $=hn({budgetMs:Ce.readMs,flightSignal:R,call:me=>f.readAttachment(f.filePath,{maxBytes:n,head:!1,principal:o(f.owner),signal:me}),onOverrun:m("read",f),onStuck:S("read",f)}),w=await $.outcome;if(w.timedOut)return I=$.settled,R.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(R.aborted)return{kind:"failure",status:503,reason:"aborted"};let T=w.value;if(!T.ok&&T.reason!=="too_large")return ir(T.reason)?(T.reason==="not_found"&&a(f.attachmentId,!1),{kind:"failure",status:sr(T.reason),reason:T.reason,code:T.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(T.ok&&T.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let F=y(f,T.ok?{kind:"exact",bytes:T.bytes.byteLength}:{kind:"over",maxBytes:n}),H=me=>{F==="verified"&&r.set(f.key,me)},k=me=>(H(me),{...me,identity:F});if(!T.ok)return k({kind:"unrenderable",reason:"too_large"});let le=yn(T.bytes);if(le===null)return k({kind:"unrenderable",reason:"signature"});let de=hn({budgetMs:Ce.renderMs,flightSignal:R,call:me=>f.renderer.render(T.bytes,{format:le,maxWidth:f.box.maxWidth,maxHeight:f.box.maxHeight,signal:me}),onOverrun:m("render",f),onStuck:S("render",f)}),fe=me=>{if(me.kind==="error")return;let ye=zo(me.value,f.box);"entry"in ye&&H(ye.entry)},q=null,re=()=>(q===null&&(q=de.settled.then(fe),c(f.key,q)),q);R.addEventListener("abort",re,{once:!0});let Z=await de.outcome.finally(()=>R.removeEventListener("abort",re));if(Z.timedOut||R.aborted)return I=re(),R.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let ie=zo(Z.value,f.box);return"entry"in ie?k(ie.entry):ie.failure}finally{I===null?g():I.then(g,g)}}};var Jo=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let c=new AbortController,s=()=>{e.get(t)?.controller===c&&e.delete(t)},m={promise:n(c.signal).finally(s),controller:c,waiters:0};return e.set(t,m),m},a=e.get(t)??o();a.waiters+=1;let i=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?i():r.addEventListener("abort",i,{once:!0});let l=()=>{r.removeEventListener("abort",i)};return a.promise.finally(l)}}};var Zo=10,Ll=1/Zo,Qo=1-Ll,Ol=1024,Nl=64,vl=8,Xo="private, no-cache",kl="no-store",Hl=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),Ul=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},ea=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:c}=l,s=(w,T)=>et({reason:w,limitPerWindow:T,windowMs:6e4,logger:o,windowFields:F=>`viewer=${F} variant=thumbnail`}),y=s("rate_limit",l.rateLimitPerMinute),m=s("revalidation_rate_limit",l.rateLimitPerMinute*Zo),S=je({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:Nl,maxPerOwner:vl,maxWaitMs:Ce.queueWaitMs}}),f=jo({maxBytes:l.cacheBytes,maxEntries:Ol}),R=Jo(),b=Ko({gate:S,cache:f,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),g=(w,T,F,H)=>{let k=`attachment=${w.attachmentId} viewer=${w.internalUserId} variant=thumbnail cache=${H}`;if(T.kind==="failure")return o[Ul(T)](`${T.status} ${k} reason=${T.reason} code=${T.code??"-"}`),w.fail(T.status,at[T.status],xe(T.status));let le=Hl[T.identity];if(T.kind==="unrenderable")return o.info(`404 ${k} reason=${T.reason}${le}`),w.fail(404,at[404]);let de=T.identity==="verified"?{"Cache-Control":Xo,ETag:F}:{"Cache-Control":kl},fe=new Headers({"Content-Type":T.contentType,"Content-Length":String(T.bytes.byteLength),...de,"Content-Security-Policy":"default-src 'none'; sandbox",...At});return w.cookie&&fe.append("Set-Cookie",w.cookie),o.info(`200 ${k} type=${T.contentType} bytes=${T.bytes.byteLength}${le}`),new Response(T.bytes,{status:200,headers:fe})},I=(w,T)=>{let F=w.spend(T.internalUserId,`attachment=${T.attachmentId} viewer=${T.internalUserId} variant=thumbnail`);return F===null?null:T.fail(F.status,F.message,F.headers)},v=w=>I(y,w),$=(w,T)=>T?I(m,w):v(w);return async(w,T)=>{let{request:F,attachmentId:H,internalUserId:k,readAttachment:le,cookie:de,fail:fe}=w,q=tn[T],re=F.headers.get("If-None-Match"),Z=re!==null,ie=$(w,Z);if(ie)return ie;let me=await n(F),ye=await t.getAttachmentForUser(me,H,k),te=ye!==null&&lr(ye,i)?qo({rendererId:c.id,box:q,attachmentId:H,filePath:ye.filePath,fileType:ye.fileType,fileSize:ye.fileSize}):null;if(te&&on(re,te.etag)){let A=new Headers({"Cache-Control":Xo,ETag:te.etag,...At});return de&&A.append("Set-Cookie",de),o.info(`304 attachment=${H} viewer=${k} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:A})}if(Z){let A=v(w);if(A)return A}if(!ye)return o.warn(`404 attachment=${H} viewer=${k} variant=thumbnail reason=not_visible`),fe(404,at[404]);if(!te)return y.refund(k,Qo),o.info(`404 attachment=${H} viewer=${k} variant=thumbnail reason=not_eligible`),fe(404,at[404]);let{key:Pe,etag:Ue}=te,De=f.get(Pe);if(De)return y.refund(k,Qo),g(w,{...De,identity:"verified"},Ue,"hit");let O=A=>b({key:Pe,attachmentId:H,filePath:ye.filePath,fileSize:ye.fileSize,box:q,owner:k,readAttachment:le,renderer:c},A),P;try{P=await R.join(Pe,F.signal,O)}catch(A){return o.error(`500 attachment=${H} viewer=${k} variant=thumbnail cache=miss reason=port_exception message=${A instanceof Error?A.message:"unknown"}`),fe(500,at[500])}return g(w,P,Ue,"miss")}};var $l='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Bl=()=>or(403,sn,{cookie:null}),ta=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=rn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>or(404,ar[404],{cookie:null}),crossSiteRejection:Bl}),ra=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:o,logger:a}=e,i=r.attachmentDelivery,l={service:r,encodeUserId:n,resolveViewerScope:o,logger:a,recordObjectState:fo(r,a)},c=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:Ao({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:ea({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:s,params:y})=>{let m=null,S=(f,R,b={})=>or(f,R,{cookie:m,extraHeaders:b});try{let{user:f,cookie:R}=await t(s,{failureRedirect:null});if(m=R??null,!f)return S(401,"Unauthorized");let b=rn(new URL(s.url).searchParams);if(b.kind==="invalid")return S(400,"Invalid attachment request");if(b.kind==="thumbnail"&&s.method!=="GET")return S(405,"Method not allowed",{Allow:"GET"});if(s.method!=="GET"&&s.method!=="HEAD")return S(405,"Method not allowed",{Allow:"GET, HEAD"});if(c===null)return S(404,"Attachment not found");if(y.token===void 0)throw new Error($l);let g=c.idCodec.decode(y.token);if(g===null||!Dt(g))return S(400,"Invalid attachment token");let I=await r.getUserIdByExternalId(f.id);if(!I)return S(403,"Forbidden");let v={request:s,delivery:b,attachmentId:g,internalUserId:I,readAttachment:c.read,cookie:m,fail:S};return b.kind!=="thumbnail"?await c.serveOriginal(v):c.serveThumbnail===null?S(404,at[404]):await c.serveThumbnail(v,b.variant)}catch(f){if(f instanceof Response)throw f;return a.error(`500 attachment=? viewer=? reason=unexpected message=${f instanceof Error?f.message:"unknown"}`),S(500,Ze)}}};var Fl=32*1024*1024,Vl=60,Yl=4,ql=120,Wl=2,jl=8*1024*1024,cr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zl=e=>{if(e===void 0)throw gt("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!cr(e))throw se("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw gt("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw se("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw se("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},Gl=e=>{if(e===void 0)return null;if(!cr(e))throw se("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:zl(e.renderer),rateLimitPerMinute:lt("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,ql),concurrency:lt("attachments.thumbnails.concurrency",e.concurrency,1,Wl),cacheBytes:lt("attachments.thumbnails.cacheBytes",e.cacheBytes,0,jl)})},na=e=>{let t=e;if(t===void 0)return null;if(!cr(t))throw se("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw gt("attachments.idCodec","injected when attachments is given");if(!cr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw se("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw gt("attachments.read","injected when attachments is given");if(typeof n!="function")throw se("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:lt("attachments.maxBytes",t.maxBytes,1,Fl),rateLimitPerMinute:lt("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,Vl),concurrency:lt("attachments.concurrency",t.concurrency,1,Yl),thumbnails:Gl(t.thumbnails)})},Kl=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"]]),ur=e=>{for(let[t,r]of Kl)if(Object.hasOwn(e,t))throw gt(r,`given in place of the flat key ${t}`)};var aa=8,Jl=8*aa,Ql=128,Xl=2,ia=Xl*Ql,Zl=4*ia,ec=6e4,tc=6e4,rc="Too many reads",oa=Object.freeze(Object.keys(nt).filter(e=>nt[e].admission.includes("miss-gate"))),sa=e=>{let t=je({limit:Jl,maxHeldPerOwner:aa,queue:{max:Zl,maxPerOwner:ia,maxWaitMs:ec}}),r=Ne({windowMs:tc,tallies:oa,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${oa.map(l=>`${l}:${i[l]}`).join(",")}`)}});return{admissionFor:(n,o,a)=>({signal:a,acquire:async i=>{let l=await t.acquire(n,i);return l===null&&!i.aborted&&r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=cache_miss_admission`)),l}})}},dr=(e,t)=>{let r=oe(e,t,{error:{message:rc}},503);for(let[n,o]of Object.entries(xe(503)))r.headers.set(n,o);return r};var nc=/^[0-9a-f]{1,16}$/;var la=e=>{let t=e.get(Ae.cursorReportHubId),r=e.get(Ae.cursorBusinessDate),n=e.get(Ae.cursorSnapshot),o=n!==null&&nc.test(n)?n:null,a=null;if(t!==null){let l=Be(t);if(l===null)return{refused:"cursor"};if(r!==null&&!Qt(r))return{refused:"cursor"};a={businessDate:r,reportHubId:l}}else if(r!==null)return{refused:"cursor"};let i=vt(e.get(Ae.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var mr=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,oc=2,ac=16,ic=oc*ac,sc=6e4,ca=()=>{},lc=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},ua=e=>{let t=je({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:ic,queue:null}),r=Ne({windowMs:sc,tallies:["sse","ids-stream"],writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`streams_per_viewer_suppressed count=${o} since=${a} viewer=${n} routes=sse:${i.sse},ids-stream:${i["ids-stream"]}`)}});return{admit:async(n,o,a)=>{if(n===null)return ca;if(a.aborted){if(t.canAcquire(n))return ca}else{let i=await t.acquire(n,a);if(i!==null)return lc(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var pr=30,ha=4e3,cc="stream interrupted by server error",uc="Too many streams",dc=15e3,fa=Symbol("ids-stream-heartbeat"),da=()=>{},ma=e=>e.return(void 0).then(da,da),mc=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(fa),dc)}),stop:()=>clearTimeout(e)}};async function*pa(e,t,r,n){let o=t?Fn(e,t):0,a=!0;for(;;){let i=e.slice(o,o+(a?r:ha));o+=i.length;let l=o>=e.length,c=i[i.length-1];if(yield{kind:"chunk",items:i,nextCursor:l||!c?null:{businessDate:c.businessDate,reportHubId:c.reportHubId},isLast:l,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,l)return}}var Ra=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...We});return e&&t.append("Set-Cookie",e),t},ya=(e,t,r,n,o)=>{let a=async(y,m)=>{o(),m&&await ma(t);try{y.close()}catch{}},i=new TextEncoder,l=!1,c=null,s=new ReadableStream({async pull(y){if(l||r.aborted){await a(y,!0);return}let m=mc();try{c===null&&(c=t.next());let S=await Promise.race([c,m.fired]);if(m.stop(),S===fa){if(l||r.aborted){await a(y,!0);return}y.enqueue(i.encode(`
|
|
2
|
+
`));return}c=null;let{value:f,done:R}=S;if(R){await a(y,!1);return}if(l||r.aborted){await a(y,!0);return}y.enqueue(i.encode(`${JSON.stringify(f)}
|
|
3
|
+
`))}catch(S){if(m.stop(),c=null,o(),l||r.aborted)return;S instanceof $e||n.error(`ids-stream emission failed: ${S instanceof Error?S.message:String(S)}`);try{let f={kind:"error",error:cc};y.enqueue(i.encode(`${JSON.stringify(f)}
|
|
4
|
+
`)),y.close()}catch{}}},cancel(){l=!0,o(),ma(t)}});return new Response(s,{status:200,headers:Ra(e)})},Sa=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,c,s,y,m,S,f)=>{let R=!1,b=null,g=null,I=new Promise((w,T)=>{b=w,g=T});I.catch(()=>{});let v=t.getDailyReportIdsByExternalId(s,c.id,{forceRefresh:l.forceRefresh,admission:f,onFetchStart:l.cursor?void 0:()=>{R=!0,t.readSseStreamAnchor().then(w=>t.getDailyReportIdsFirstPageByExternalId(s,c.id,pr).then(T=>({items:T,streamAnchor:w}))).then(w=>b?.(w),w=>g?.(w))}});if(v.catch(()=>{}),l.cursor){let{items:w,streamAnchor:T,snapshot:F}=await v,H=l.snapshot!==null&&l.snapshot===F;return ya(y,pa(w,H?l.cursor:null,pr,{snapshot:F,restarted:!H,streamAnchor:T}),m,r,S)}let $=(async function*(){let w=await Promise.race([v.then(H=>({kind:"full",source:H}),H=>({kind:"full-error",error:H})),I.then(H=>({kind:"page",page:H}),()=>({kind:"page-error"}))]),T=null,F=!1;if(w.kind==="full")T=w.source;else if(w.kind==="page"){let{items:H,streamAnchor:k}=w.page;if(H.length<pr){yield{kind:"chunk",items:H,nextCursor:null,isLast:!0,total:H.length,streamAnchor:k};return}yield{kind:"chunk",items:H,nextCursor:null,isLast:!1,provisional:!0},F=!0}else if(w.kind==="full-error"&&R){let H=await I.catch(()=>null);H&&H.items.length>0&&(yield{kind:"chunk",items:H.items,nextCursor:null,isLast:!1,provisional:!0})}T===null&&(T=await v),yield*pa(T.items,null,F?ha:pr,{snapshot:T.snapshot,streamAnchor:T.streamAnchor})})();return ya(y,$,m,r,S)};return async(l,c,s,y,m)=>{let S=la(l.searchParams);if("refused"in S)return oe(s,c,{error:{message:S.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:f}=S;if(f.forceRefresh){let I=a(y,s,c);if(I!==null)return I}let R=mr(s),b=await t.getUserIdByExternalId(y.id),g=await n.admit(b,"ids-stream",R);if(g===null){let I=oe(s,c,{error:{message:uc}},503);for(let[v,$]of Object.entries(xe(503)))I.headers.set(v,$);return I}if(R.aborted)return new Response(null,{status:200,headers:Ra(c)});try{return await i(f,y,m,c,R,g,b===null?void 0:o.admissionFor(b,ue.idsStream,R))}catch(I){if(g(),I instanceof $e)return dr(s,c);throw I}}};var ga=6e4,pc=1,yc=2e3,hc=Object.freeze({search:null,reports:null,"search-marks":yc}),fc=(e,t)=>{let r=hc[e];return r===null?null:{max:t,maxPerOwner:Zt,maxWaitMs:r}},yr=e=>{let{concurrency:t,route:r,logger:n}=e,o=et({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:ga,logger:n,windowFields:()=>`route=${r}`}),a=je({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:fc(r,t)}),i=Object.freeze({status:429,message:cn,headers:Object.freeze({"Retry-After":String(pc)})}),l=Ne({windowMs:ga,tallies:["busy"],writeSuppressed:(c,{count:s,since:y})=>{n.warn(`busy_suppressed count=${s} since=${y} route=${r} concurrency=${t}`)}});return{admit:async(c,s)=>{let y=o.spend(c,r);if(y!==null)return{refusal:y};let m=await a.acquire(c,s);return m!==null?{release:m}:(o.refund(c,1),s.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};import{parseQuerySets as zc}from"@aiquants/fuzzy-search";import{createHash as Rc}from"crypto";import{clusterCountOf as Sc,DEFAULT_NORMALIZE_OPTIONS as fr,InteriorPairs as gc,isAnswerTier as bc,normalizeText as Dc,queryNeedles as Ac,resolveNormalizeOptions as Tc,toMappedFormsInto as Ec,trimmedRange as Ic}from"@aiquants/fuzzy-search/normalize";var Rr=`
|
|
5
|
+
`,Sr=4e3,_c=1,Da=new Set([8203,8288,65279,173]),wc=new RegExp(`[${String.fromCodePoint(...Da)}]`,"gu"),xc=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),Cc=/(\s+)/u,Mc=/^\s+$/u,Pc=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,Lc=new Set([8205,1536,1537,1538,1539,1540,1541,1757,1807,2192,2193,2274,69821,69837,70082,70083,71999,72001,72250,72324,72325,72326,72327,72328,72329,73030,73474]),Ut=e=>e.replace(wc,""),Aa=e=>{let t=Ut(e);if(t.length===e.length)return{text:t,rawIndex:null};let r=new Uint32Array(t.length),n=0;for(let o=0;o<e.length;o++)Da.has(e.charCodeAt(o))||(r[n++]=o);return{text:t,rawIndex:r}},Rn=e=>Dc(e,fr),hr=e=>Rn(Ut(e)),Oc=Tc({...fr,convertRomaji:!0},"[daily-report] search reading options"),Nc=3,vc=/^[-ー]+/u,kc=/[^\p{L}\p{M}]/gu,Hc=/ー{2,}/gu,Uc=/\p{Script=Latin}/u,ba=/(?=\p{L})\p{Script=Latin}/u,$c=e=>Sc(e.replace(vc,"").replace(kc,"").replace(Hc,"\u30FC")),Bc=(e,t)=>{for(let r of t)if(!bc(r.tier)||r.splitTier!==null)throw new Error(`[daily-report] search readings: queryNeedles gave an unfinished needle for the word ${JSON.stringify(e)} (text ${JSON.stringify(r.text)}, tier ${r.tier}, splitTier ${r.splitTier})`)},Ta=e=>{if(!ba.test(e))return[];let t=hr(e);if(!ba.test(t))return[];let r=Ac(t,Oc,!1);Bc(t,r);let n=[];for(let o of r){if(o.tier===ct.word)continue;let a=hr(o.text);if(!(a.length===0||a.length>_e.maxWordLength)&&!(a===t||Uc.test(a))&&!($c(a)<Nc||n.includes(a))&&(n.push(a),n.length===Fr))break}return n},Ea=(e,t)=>{let r=e.charCodeAt(t-1),n=e.charCodeAt(t);return r>=55296&&r<=56319&&n>=56320&&n<=57343},Fc=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&Ea(e,t-1)?t-2:t-1;return Pc.test(String.fromCodePoint(r))&&!Lc.has(e.codePointAt(n))},Vc=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!Fc(e,i);)i--;i===a&&(i=a+r,Ea(e,i)&&i--,o++),n.push({start:t+a,end:t+i}),a=i}return n.push({start:t+a,end:t+e.length}),{pieces:n,forcedCuts:o}},Sn=(e,t)=>{if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let r=[],n=0,o=0,a=0,i=0,l=()=>{i>0&&r.push([{start:a,end:a+i}]),i=0};for(let c of e.split(Cc)){let s=o;if(o+=c.length,i+c.length<=t){i===0&&(a=s),i+=c.length;continue}if(l(),Mc.test(c))continue;if(c.length<=t){a=s,i=c.length;continue}let y=Vc(c,s,t);n+=y.forcedCuts,r.push(y.pieces)}return l(),{chunks:r,forcedCuts:n}},gn=(e,t)=>{let r=Sn(e,t),n=[];for(let o of r.chunks){let a=o.map(i=>Rn(e.slice(i.start,i.end))).join("");a.length>0&&n.push(a)}return{text:n.join(" "),forcedCuts:r.forcedCuts}},bn=(e,t)=>{let r=0;for(let n of e.matchAll(xc))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},Yc=(e,t)=>{if(e.partialReadings!==null)throw new Error(`[daily-report] search marks: the mapped forms of the piece ${JSON.stringify(t)} carry partial readings`);return e.canonical},Ia=(e,t)=>{let r="",n=[],o=[];for(let a of t.chunks){let i="",l=[],c=[];for(let s of a){let y=e.slice(s.start,s.end),m=Yc(Ec(y,fr,new gc(0)),y),[S,f]=Ic(m.text);i+=m.text.slice(S,f);for(let R=S;R<f;R++)l.push(s.start+m.start[R]),c.push(s.start+m.end[R])}if(i.length!==0){r.length>0&&(r+=" ",n.push(o[o.length-1]),o.push(l[0])),r+=i;for(let s=0;s<l.length;s++)n.push(l[s]),o.push(c[s])}}return{text:r,start:n,end:o}},gr=(e,t=Sr)=>{let r=[],n=0;return bn(Ut(e),o=>{let a=gn(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(Rr),forcedCuts:n}},_a=e=>e.filter(t=>t.length>0).join(Rr),qc=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
|
|
6
|
+
`)},Wc=[`\u3067\u3093${String.fromCodePoint(8203)}\u3077\u3093 \uFF83\uFF9E\uFF9D\uFF8C\uFF9F\uFF9D\r
|
|
7
|
+
\u30C7\u30F3\u30D7\u30F3`,"\u30DD\u30C6\u30C8-25kg \u30A2--1 \u30FC\u30FC\u30E1\u30F3 \u4F50\u3005\u6728","\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CA",`\uFF71\uFF72\uFF73\uFF74\uFF75\uFF76\uFF9E\uFF77\uFF9E\uFF78\uFF9E\uFF79\uFF9E\uFF7A\uFF9E${String.fromCodePoint(8232)}\u6B21\u306E\u884C`],jc=()=>{let e=Rc("sha256");e.update(JSON.stringify(fr));for(let t of["","\u30A2","\u4F50"," "])e.update("\0"),e.update(Rn(qc(t)));return e.update("\0"),e.update(JSON.stringify(Wc.map(t=>gr(t,8)))),`dr-search-v${_c};fz=${e.digest("hex").slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`},fn=null,wa=()=>(fn===null&&(fn=jc()),fn);var Gc=/^-+/u,Kc=/\s+/u,xa=e=>{let t=Gc.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},Jc=(e,t)=>{let r=[...xa(e).map(n=>({text:n,tier:ct.word})),...t.flatMap(n=>xa(n).map(o=>({text:o,tier:ct.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},Qc=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),Dn=(e,t)=>{if(e.length>_e.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of zc(Ut(e),t).sets){let i=[],l=new Set;for(let s of a.split(Kc)){let y=hr(s);if(y.length===0)return{ok:!1,reason:"blank-word"};if(y.length>_e.maxWordLength)return{ok:!1,reason:"word-too-long"};let m=Jc(y,Ta(s)),S=Qc(m);l.has(S)||(l.add(S),i.push({alternatives:m}))}if(i.length>_e.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let c=JSON.stringify([...l].sort());n.has(c)||(n.add(c),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>_e.maxSets?{ok:!1,reason:"too-many-sets"}:o>_e.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},$t=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));import{systemSseRuntime as uu}from"@aiquants/sse";import{createSseResponse as du,readLastEventId as mu,startSseHeartbeat as pu,terminalStreamResponse as yu}from"@aiquants/sse/server";var Bt=(e,t)=>{let r=e.message.data;if(!r)return{entry:{id:e.id,message:null},json:void 0};let n;try{n=JSON.parse(r)}catch(i){return t.error(`SSE message ${e.id} is not JSON:`,i),{entry:{id:e.id,message:null},json:void 0}}let o=Qn.safeParse(n);if(!o.success)return t.error("SSE message validation failed:",o.error.format()),{entry:{id:e.id,message:null},json:n};let a=Object.freeze({parsed:o.data,published:n,text:r});return{entry:Object.freeze({id:e.id,message:a}),json:n}},Xc=["externalComments","postedComments"],Ca=new WeakMap,Zc=e=>{let t=Ca.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return Ca.set(e,r),r},Ma=e=>{let{recipientRawUserId:t,...r}=e;return r},Pa=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=Zc(e);if(t){if(n.commentsRedacted===null){let o=Ma(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(Xc.map(i=>[i,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(Ma(r))),n.recipientRemoved};import{systemSseRuntime as tu}from"@aiquants/sse";import{createSharedSource as ru}from"@aiquants/sse/shared-source";var dt="daily-report:ids:",mt="daily-report:business-date:",br=(e,t)=>`${e}st:${t}`,An=e=>`${dt}user:${e}:`,La=(e,t)=>br(An(e),t),eu=e=>`${mt}${e}:`,Oa=(e,t)=>br(eu(e),t),Ft=e=>`daily-report:date:${e}:user:`,Et=(e,t)=>`${Ft(e)}${t}:`,Na=(e,t,r)=>br(Et(e,t),r),Ge=e=>`daily-report:detail:${e}:user:`,Dr=(e,t)=>`${Ge(e)}${t}:`,va=(e,t,r)=>br(Dr(e,t),r);var it=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},nu=5e3,ou=rr,Vt=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=he(t.logger,1,"SseReader"),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 ru({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:tu,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",i=>{this._logger.error("Redis client error:",i)});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 i=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:nu,COUNT:ou});if(i)for(let l of i)for(let c of l.messages){a=c.id;let{entry:s,json:y}=Bt(c,this._logger);this._invalidateCaches(y),r.next(s)}}}catch(i){o()||(this._logger.error("xRead loop error:",i),r.fail(i instanceof Error?i:new Error(String(i))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){if(t===null||typeof t!="object")return;let{type:r,reportHubId:n}=t;(r==="report-create"||r==="report-delete"||r==="report-publish")&&this.config.cache.invalidatePrefix(dt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Ge(n))}};import{inArray as au,sql as ka}from"drizzle-orm";var iu="",su=64,lu=e=>e.toLowerCase(),cu=e=>e.trim().toLowerCase();function Ha(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=cu(r);n.length>0&&t.add(n)}return t}function ke(e,t){return e===null?!0:t==null?!1:e.has(lu(t))}function He(e){return e!==null&&e.size===0}function qt(e,t){if(t!==null)return t.size===0?ka`1 = 0`:au(ka`LOWER(${e})`,[...t])}var It,_t,Yt=class Yt{constructor(t,r){Or(this,It);Or(this,_t);Nr(this,It,t),Nr(this,_t,r)}get visible(){return Lt(this,It)===null?null:new Set(Lt(this,It))}get commentable(){return Lt(this,_t)===null?null:new Set(Lt(this,_t))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=Ha(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new Yt(n,n);let a=Ha(o),i=new Set;for(let l of a??[])n.has(l)&&i.add(l);return new Yt(n,i)}static unrestricted(t){return new Yt(null,null)}};It=new WeakMap,_t=new WeakMap;var ve=Yt;function Wt(e){let t=Ua(e.visible),r=Ua(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Ua(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(iu);if(t.length<=su)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 Fa=Object.freeze({...kt,route:"sse",frameworkDataRefusal:nr}),$a=864e5,hu={baseMs:2e3,jitterMs:8e3},Va=6e4,Tn=rr,Ya=JSON.stringify({type:"connected"}),Ba="0-0",fu=(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 ke(r,e.report.sourceType);case"comment-add":case"comment-delete":return ke(n,o??"Internal");case"report-delete":return ke(r,o)}},Ru=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!ke(t,e.report.sourceType),Su=(e,t)=>{e.writeEvent({event:null,id:t,data:Ya})},gu=(e,t,r)=>{let{message:n}=t;if(n===null)return;let{parsed:o,published:a}=n,i=typeof a.recipientRawUserId=="number"?a.recipientRawUserId:void 0;if((o.type==="status-update"||i!==void 0)&&i!==r.internalUserId||!fu(o,a,r.visibleSet,r.commentableSet)){Su(e,t.id);return}e.writeEvent({event:null,id:t.id,data:Pa(n,Ru(o,r.commentableSet))})},qa=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:c}=e,s=async(y,m)=>{let{request:S,internalUserId:f,cursor:R}=m,b=m.initialScope.visible,g=m.initialScope.commentable,I=0,v=setInterval(()=>{let q=++I;n(S,"refresh").then(re=>{q===I&&(b=re.visible,g=re.commentable)})},Va);y.onClose(()=>clearInterval(v));let $=R===null?Ba:R,w=R!==null&&o!==void 0,T=[],F=null,H=q=>{it(q.id,$)||($=q.id,gu(y,q,{internalUserId:f,visibleSet:b,commentableSet:g}))},k=async(q,re)=>{let[Z]=await q.xRange(i,"-","+",{COUNT:1});return Z!==void 0&&!it(Z.id,re)},le=async(q,re)=>{if(await k(q,re))return!1;let Z=re;for(;;){let ie=await q.xRange(i,Z,"+",{COUNT:Tn}),me=ie[0];if(me!==void 0&&me.id!==Z&&await k(q,Z))return!1;for(let Ke of ie){if(F!==null&&it(F,Ke.id))return!0;it(Ke.id,$)||H(Bt(Ke,c).entry)}let ye=ie.at(-1);if(ie.length<Tn||ye===void 0||y.isClosed())return!0;Z=ye.id}},de=a.subscribe(q=>{if(!w){H(q);return}it(q.id,$)||(F===null&&(F=q.id),T.push(q))},q=>{c.error(`[SSE:${f}] Fan-Out reader error:`,q),y.close()});if(y.onClose(de),R===null){await a.ready();try{let q=await o?.getClient();if(q){let re=await q.xRevRange(i,"+","-",{COUNT:1});re.length>0&&!it(re[0].id,$)&&($=re[0].id)}}catch{}}if(y.writeEvent({event:null,id:$===Ba?null:$,data:Ya}),pu(y,{intervalMs:zn,retry:hu,runtime:uu}),R===null||o===void 0)return;await a.ready();let fe=await o.getClient();if(fe===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await le(fe,R)){y.writeRetry($a),y.writeEvent({event:"resync-required",id:null,data:""}),y.close();return}w=!1;for(let q of T.splice(0))H(q)};return async({request:y,params:m})=>{let S,f=()=>{let b=new Headers;S!==void 0&&b.append("Set-Cookie",S);for(let[g,I]of Object.entries(We))b.set(g,I);return b},R=b=>yu(b,{data:"",retryMs:$a,headers:f()});try{let b=await t(y,{failureRedirect:null});S=b.cookie;let{user:g}=b;if(!g)return R("auth-required");let I=await r.getUserIdByExternalId(g.id);if(!I)return R("forbidden");if(m.endpoint!=="updates")return new Response("Not Found",{status:404,headers:f()});let v=mu(y,Gn);if(v!==null&&!Kn(v))return c.warn(`[SSE:${I}] malformed resume cursor; asking the client to resync`),R("resync-required");let $=mr(y),w=await l.admit(I,"sse",$);if(w===null){let F=f();for(let[H,k]of Object.entries(xe(503)))F.set(H,k);return new Response("Too many streams",{status:503,headers:F})}let T=!1;try{let F=await n(y,"initial");return du({requestSignal:$,headers:f(),onError:(H,k)=>c.error(`[SSE:${I}] ${k} failed:`,H),produce:H=>(T=!0,H.onClose(w),s(H,{request:y,internalUserId:I,cursor:v,initialScope:F}))})}finally{T||w()}}catch(b){if(b instanceof Response)throw b;let g=b instanceof Error?b:new Error(String(b));return c.error(`500 sse name=${g.name} message=${g.message}`),new Response("Internal Server Error",{status:500,headers:f()})}}};var Wa=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...We});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},bu=Object.freeze({...kt,route:"api",frameworkDataRefusal:({params:e})=>en(e.endpoint)&&nt[e.endpoint].body==="stream"?nr():null}),Du=Object.freeze({...kt,route:"action"}),Au=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),Ga=6e4,Ka=5,Tu=Ka*Math.ceil(Ga/500),Eu=2,Iu=6,_u=6e4,wu=Ka*Eu*Iu,xu=2,Cu=10,Mu=2,Pu=10,ja=(e,t)=>Math.max(e,Zt)*t,In=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},En=(e,t,r)=>In(oe(e,t,{error:{message:r.message}},r.status),r.headers),za=e=>In(Xe(e,null,503),xe(503));function _n(e){ur(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:ee("service.titleMaxLength",r.titleMaxLength,1)},c=e.loginRedirectPath??"/auth/login",s=he(e.logger,3,"API"),y=he(e.logger,3,"Visibility"),m=he(e.logger,1,"SSE"),S=he(e.logger,1,"Attachment"),f=he(e.logger,2,"Isolation"),R=he(e.logger,2,"Action"),b=he(e.logger,2,"Search"),g=he(e.logger,2,"Refresh"),I=he(e.logger,2,"Streams"),v=he(e.logger,2,"Reads"),$=et({reason:"refresh_rate_limit",limitPerWindow:wu,windowMs:_u,logger:g,windowFields:()=>"route=api"}),w=ua(I),T=sa(v),F=async(O,P,A,B,W)=>{let G=await r.getUserIdByExternalId(P.id);try{return await W(G===null?void 0:T.admissionFor(G,O,A.signal))}catch(K){if(K instanceof $e)return dr(A,B);throw K}},H=(O,P,A,B)=>{let W=$.spend(P.id,`endpoint=${O}`);return W===null?null:En(A,B,W)},k=async(O,P="initial")=>{let A=e.resolveVisibleSourceTypes;if(!A)return ve.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let B=await A(O,{reason:P});return B==null?ve.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):ve.restrictTo(B)}catch(B){return y.error("resolveVisibleSourceTypes threw; failing closed (deny all)",B),ve.restrictTo([])}},le=async({request:O})=>{let{user:P,cookie:A}=await t(O,{failureRedirect:c}),B=new Headers;A&&B.append("Set-Cookie",A);let W=await r.getUserIdByExternalId(P.id),G=W?n(W):null;return{data:{user:P,userId:G},headers:B}},de=r.searchLimits===null?null:yr({...r.searchLimits,route:ue.search,logger:b}),fe=r.searchLimits===null?null:yr({concurrency:ja(r.searchLimits.concurrency,xu),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Cu,route:ue.reports,logger:b}),q=r.searchLimits===null?null:yr({concurrency:ja(r.searchLimits.concurrency,Mu),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Pu,route:ue.searchMarks,logger:b}),re={[ue.businessDate]:async(O,P,A,B,W)=>{let G=O.searchParams.get(Ae.businessDate),K=G===null?null:bt(G);if(K===null)return oe(A,P,{error:{message:"Invalid business date"}},400);let j=vt(O.searchParams.get(Ae.forceRefresh));if(j===null)return oe(A,P,{error:{message:"Invalid forceRefresh"}},400);let Q=j?H(ue.businessDate,B,A,P):null;return Q!==null?Q:F(ue.businessDate,B,A,P,async C=>{let X=await r.getDailyReportsByBusinessDateByExternalId(W,K,B.id,{forceRefresh:j,admission:C});return oe(A,P,{businessDate:K,reports:X},200)})},[ue.idsStream]:Sa({service:r,logger:s,streamSlots:w,missGate:T,refuseForcedRead:(O,P,A)=>H(ue.idsStream,O,P,A)}),[ue.report]:async(O,P,A,B,W)=>{let G=Be(O.searchParams.get(Ae.reportHubId));if(G===null)return oe(A,P,{error:{message:"Invalid reportHubId"}},400);let K=vt(O.searchParams.get(Ae.forceRefresh));if(K===null)return oe(A,P,{error:{message:"Invalid forceRefresh"}},400);let j=K?H(ue.report,B,A,P):null;return j!==null?j:F(ue.report,B,A,P,async Q=>{let C=await r.getDailyReportDetailByIdByExternalId(W,G,B.id,{snapshot:!0,forceRefresh:K,admission:Q});return C?oe(A,P,{report:C},200):oe(A,P,{error:{message:"Report not found"}},404)})},[ue.search]:async(O,P,A,B,W)=>{if(de===null)return oe(A,P,{error:{message:"Unknown endpoint"}},404);let G=O.searchParams.get(Ae.searchQuery),K=Xr(O.searchParams.get(Ae.searchCombine));if(G===null||K===null)return oe(A,P,{error:{message:"Invalid search request"}},400);let j=Dn(G,K);if(!j.ok)return oe(A,P,{error:{message:"Invalid search query",reason:j.reason}},400);let Q=$t(j.plan),C=await r.getUserIdByExternalId(B.id);if(!C)return oe(A,P,Vr([],Q),200);let X=await de.admit(C,A.signal);if("refusal"in X)return En(A,P,X.refusal);try{let ge=await r.searchDailyReports(W,C,j.plan);return oe(A,P,Vr(ge,Q),200)}finally{X.release()}},[ue.reports]:async(O,P,A,B,W)=>{if(fe===null)return oe(A,P,{error:{message:"Unknown endpoint"}},404);let G=Zr(O.searchParams.get(Ae.reportIds));if(G===null)return oe(A,P,{error:{message:"Invalid ids"}},400);let K=await r.getUserIdByExternalId(B.id);if(!K)return oe(A,P,{reports:[]},200);let j=await fe.admit(K,A.signal);if("refusal"in j)return En(A,P,j.refusal);try{let Q=await r.getDailyReportDetailsByIdsByExternalId(W,G,B.id);return oe(A,P,{reports:Q},200)}finally{j.release()}},[ue.searchMarks]:async(O,P,A,B,W)=>{if(q===null)return Xe(P,{error:{message:"Unknown endpoint"}},404);let G=O.searchParams.get(Ae.searchQuery),K=Xr(O.searchParams.get(Ae.searchCombine));if(G===null||K===null)return Xe(P,{error:{message:"Invalid search request"}},400);let j=Dn(G,K);if(!j.ok)return Xe(P,{error:{message:"Invalid search query",reason:j.reason}},400);let Q=Zr(O.searchParams.get(Ae.reportIds));if(Q===null)return Xe(P,{error:{message:"Invalid ids"}},400);let C=await r.getUserIdByExternalId(B.id);if(!C)return Xe(P,{wordsDigest:Xt($t(j.plan)),reports:[]},200);let X=await q.admit(C,A.signal);if("refusal"in X)return A.signal.aborted?za(P):In(Xe(P,{error:{message:X.refusal.message}},X.refusal.status),X.refusal.headers);try{let ge=await r.markDailyReportSearchHits(W,C,j.plan,Q,{signal:A.signal});return A.signal.throwIfAborted(),Xe(P,ge,200)}catch(ge){if(A.signal.aborted&&ge===A.signal.reason)return za(P);throw ge}finally{X.release()}}},Z=async({request:O,params:P})=>{let{user:A,cookie:B}=await t(O,{failureRedirect:null}),W=B??null;if(!A)return oe(O,W,{error:{message:"Unauthorized"}},401);let G=P.endpoint;if(!en(G))return oe(O,W,{error:{message:"Unknown endpoint"}},404);let K=so[nt[G].body];if(!K.includes(O.method)){let Q=oe(O,W,{error:{message:"Method not allowed"}},405);return Q.headers.set("Allow",K.join(", ")),Q}let j=ce();try{let Q=new URL(O.url),C=await k(O),X=await re[G](Q,W,O,A,C);return nt[G].body==="json"&&s.debug(`${X.status} endpoint=${G} etag_match=${X.status===304}`),X}catch(Q){let C=ce()-j,X=Q instanceof Error?Q:new Error(String(Q));return s.error(`500 endpoint=${G} elapsed=${C}ms name=${X.name} code=${"code"in X?X.code:"N/A"} message=${X.message}`,X),oe(O,W,{error:{message:"Internal Server Error"}},500)}},ie=io(R),me=et({reason:"rate_limit",limitPerWindow:Tu,windowMs:Ga,logger:R,windowFields:()=>"route=action"}),ye=async(O,P,A,B,W)=>{let{clientTempId:G}=O;if(O.intent==="create"){let C=await r.createDailyReport(P,O.businessDate,G);return W(O,C.reportHubId,{report:C})}let{reportHubId:K,businessDate:j}=O,Q=async(C,X)=>{try{let ge=await X(C.value);return W(C,K,{updatedStatus:{isStarred:ge.isStarred,isRead:ge.isRead},operationTimestamp:C.operationTimestamp})}catch(ge){if(ge instanceof Error&&ge.message==="Not Found")return B({error:"Report not found"},{status:404});throw ge}};switch(O.intent){case"update":try{return await r.updateDailyReport(K,P,O.changes,G),W(O,K,{})}catch(C){if(C instanceof Error){if(C.message==="Unauthorized")return B({error:"Unauthorized"},{status:403});if(C.message==="Not Found")return B({error:"Report not found"},{status:404})}throw C}case"publish":try{let C=await r.publishDailyReport(K,P,G);return W(O,K,{report:C})}catch(C){if(C instanceof Error){if(C.message==="Unauthorized")return B({error:"Unauthorized"},{status:403});if(C.message==="Not Found")return B({error:"Report not found"},{status:404})}throw C}case"delete":try{return await r.deleteDailyReport(K,P,G),W(O,K,{})}catch(C){if(C instanceof Error){if(C.message==="Unauthorized")return B({error:"Unauthorized"},{status:403});if(C.message==="Not Found")return B({error:"Report not found"},{status:404})}throw C}case"toggleStar":return await Q(O,C=>r.setStarStatus(A,P,K,j,C,G));case"toggleRead":return await Q(O,C=>r.setReadStatus(A,P,K,j,C,G));case"addComment":try{let C=await r.addComment(A,P,K,O.content,j,G);return W(O,K,{newComment:C})}catch(C){if(C instanceof Error){if(C.message==="Not Found")return B({error:"Report not found"},{status:404});if(C.message.startsWith("Comments are restricted"))return B({error:"Comments are restricted for this report"},{status:403})}throw C}case"deleteComment":try{return await r.deleteComment(A,P,K,O.commentId,j,G),W(O,K,{deletedCommentId:O.commentId})}catch(C){if(C instanceof Error){if(C.message==="Unauthorized")return B({error:"Unauthorized"},{status:403});if(C.message==="Not Found")return B({error:"Comment not found"},{status:404})}throw C}}},Ke=async({request:O,params:P})=>{let{user:A,cookie:B}=await t(O,{failureRedirect:null}),W=(j,Q)=>Wa(j,{...Q,setCookie:B}),G=(j,Q,C)=>Wa(Au(j,Q,C),{setCookie:B});if(!A)return W({error:"Unauthorized"},{status:401});let K=ce();try{if(P.endpoint!==ue.action)return W({error:"Unknown endpoint"},{status:404});let j=me.spend(A.id,"action");if(j!==null)return W({error:j.message},{status:j.status,headers:j.headers});let Q=await ao(O,l);if("refusal"in Q){let{refusal:Rt}=Q;return Rt.status===413&&ie(Rt.measuredBy),W({error:Rt.error},{status:Rt.status})}let{command:C}=Q;if(C.intent==="clearCache"&&!e.enableDevCacheClear)return W({error:"Invalid intent"},{status:400});let X=await r.getUserIdByExternalId(A.id);if(!X)return W({error:"User not found"},{status:404});let ge=await k(O);return C.intent==="clearCache"?(await r.clearCache(),W({status:"OK",intent:"clearCache"})):await ye(C,X,ge,W,G)}catch(j){if(j instanceof Response)throw j;let Q=ce()-K,C=j instanceof Error?j:new Error(String(j));return s.error(`500 action elapsed=${Q}ms name=${C.name} message=${C.message}`,C),W({error:"Internal Server Error"},{status:500})}},te=qa({authenticate:t,service:r,resolveViewerScope:k,redis:o,sseReader:a,streamKey:i,streamSlots:w,logger:m}),Pe=ra({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:k,logger:S}),Ue=ho(f),De=(O,P)=>async A=>{let B=po(A.request)?O.frameworkDataRefusal(A):null;if(B!==null)throw B;return yo(A.request,O)?(Ue(O.route,A.request),O.crossSiteRejection()):P(A)};return{index:{loader:le},api:{loader:De(bu,Z),action:De(Du,Ke)},sse:{loader:De(Fa,te)},attachment:{loader:De(ta,Pe)}}}import{chunk as Ju,MAX_IN_LIST as Qu,runWithTransactionRetry as Xu}from"@aiquants/mssql";import{and as Ee,asc as Me,desc as Ct,eq as U,getColumns as Zu,inArray as Ye,isNull as Mt,sql as hi}from"drizzle-orm";import{sql as wt}from"drizzle-orm";var Tr=(e,t,r,n)=>{if(r.length===0)return;let{hub:o,hubLabel:a,label:i}=e,l=n==="author-or-authorless"?wt`${o.userId} = ${t} OR ${o.userId} IS NULL`:wt`${o.userId} = ${t}`,c=wt.join(r.map(s=>wt`${s}`),wt`, `);return wt`(${l} OR NOT EXISTS (SELECT 1 FROM ${a} INNER JOIN ${i} ON ${i.id} = ${a.labelId} WHERE ${a.hubId} = ${o.id} AND ${i.name} IN (${c})))`};var Ja=(e,t,r,n)=>ke(n.commentable,t)||e.authorUserId!==null&&e.authorUserId===r;var Lu=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],Ou=["document","comment"],Nu=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion"],vu=["hubId","ordinal","authorUserId","commentText"],wn=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Qa=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw vr(e,n,r)},Xa=(e,t,r)=>{if(typeof t!="object"||t===null)throw se(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw se(`${e}.${o}`,"a column",n[o])},Za=(e,t)=>{if(!wn(e))throw se("search","a plain object",e);Qa("search key",e,Lu);let{tables:r}=e;if(!wn(r))throw se("search.tables","a plain object with document and comment",r);Qa("search.tables key",r,Ou),Xa("search.tables.document",r.document,Nu),Xa("search.tables.comment",r.comment,vu);let n=new Map;if(e.externalSourceTexts!==void 0){if(!wn(e.externalSourceTexts))throw se("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw vr("search.externalSourceTexts key",o,t);if(typeof a!="function")throw se(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:ee("search.concurrency",e.concurrency,1),rateLimitPerMinute:ee("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var pt=e=>{let t=typeof e=="object"&&e!==null?e.recordset:void 0;if(!Array.isArray(t))throw new Error("[daily-report] search: the database result has no recordset");return t},yt=(e,t)=>{let r=typeof e=="string"?Be(e):typeof e=="number"&&Dt(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},xt=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};import{sql as Y}from"drizzle-orm";var ku=/[[%_]/gu,Hu=e=>e.replace(ku,t=>`[${t}]`),ei=e=>`%${Hu(e)}%`;var Ve=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),ht=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),Te=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),z=e=>Y`${Y.identifier(e.name)}`,ti=e=>Y.join(e.map(t=>Y`${t}`),Y`, `),ri=(e,t)=>Y`SELECT ${z(e.id)} AS ${Y.identifier(Te.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${ti(t)}) ORDER BY ${e.id}`,Uu=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(m=>ei(m.text)),l=Y.join(i.map(m=>Y`${o.searchText} LIKE ${m}`),Y` OR `),c=Y.join(i.map(m=>Y`${a.commentText} LIKE ${m}`),Y` OR `),s=qt(n.sourceType,r.scope.commentable),y=s===void 0?Y``:Y` AND (${s} OR ${a.authorUserId} = ${r.userId})`;return Y`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${c})${y}))`},ni=(e,t,r)=>Y`(${Y.join(t.words.map(n=>Uu(e,n,r)),Y` AND `)})`,oi=(e,t,r,n)=>{let{hub:o}=e,a=[Y`${o.deletedAt} IS NULL`],i=Tr(e,t.userId,r,"author");i!==void 0&&a.push(i);let l=qt(o.sourceType,t.scope.visible);return l!==void 0&&a.push(l),n!==void 0&&a.push(Y`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},ai=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=oi(e,r,n,o),c=t.combine==="intersection"?Y` AND `:Y` OR `;return l.push(Y`(${Y.join(t.sets.map(s=>ni(e,s,r)),c)})`),Y`SELECT ${z(a.id)} AS ${Y.identifier(Ve.reportHubId)}, CONVERT(char(10), ${z(a.businessDate)}, 23) AS ${Y.identifier(Ve.businessDate)}, ${z(a.sourceType)} AS ${Y.identifier(Ve.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${Y.join(l,Y` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},ii=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=Y.join(t.sets.map((c,s)=>Y`(CASE WHEN ${ni(e,c,r)} THEN ${2**s} ELSE 0 END)`),Y` + `);return Y`SELECT ${z(a.id)} AS ${Y.identifier(ht.reportHubId)}, ${l} AS ${Y.identifier(ht.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${Y.join(oi(e,r,n,o),Y` AND `)}`},si=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(c=>({[n.hubId.name]:c.hubId,[n.searchText.name]:c.searchText,[n.sourceDigest.name]:c.sourceDigest,[n.normalizerVersion.name]:r}))),i=JSON.stringify(t.flatMap(c=>c.comments.map(s=>({[o.hubId.name]:c.hubId,[o.ordinal.name]:s.ordinal,[o.authorUserId.name]:s.authorUserId,[o.commentText.name]:s.commentText})))),l=JSON.stringify(t.map(c=>c.hubId));return Y`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${z(n.hubId)} bigint, ${z(n.searchText)} nvarchar(max), ${z(n.sourceDigest)} char(64), ${z(n.normalizerVersion)} varchar(64))) AS s ON t.${z(n.hubId)} = s.${z(n.hubId)}
|
|
8
|
+
WHEN MATCHED THEN UPDATE SET t.${z(n.searchText)} = s.${z(n.searchText)}, t.${z(n.sourceDigest)} = CONVERT(binary(32), s.${z(n.sourceDigest)}, 2), t.${z(n.normalizerVersion)} = s.${z(n.normalizerVersion)}, t.${z(n.indexedAt)} = SYSUTCDATETIME()
|
|
9
|
+
WHEN NOT MATCHED THEN INSERT (${z(n.hubId)}, ${z(n.searchText)}, ${z(n.sourceDigest)}, ${z(n.normalizerVersion)}) VALUES (s.${z(n.hubId)}, s.${z(n.searchText)}, CONVERT(binary(32), s.${z(n.sourceDigest)}, 2), s.${z(n.normalizerVersion)});
|
|
10
10
|
DELETE FROM ${o} WHERE ${o.hubId} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${l}));
|
|
11
|
-
INSERT INTO ${o} (${Y(o.hubId)}, ${Y(o.ordinal)}, ${Y(o.authorUserId)}, ${Y(o.commentText)}) SELECT ${Y(o.hubId)}, ${Y(o.ordinal)}, ${Y(o.authorUserId)}, ${Y(o.commentText)} FROM OPENJSON(${i}) WITH (${Y(o.hubId)} bigint, ${Y(o.ordinal)} int, ${Y(o.authorUserId)} bigint, ${Y(o.commentText)} nvarchar(max));`},Ta=(e,t)=>J`SELECT ${Y(e.hubId)} AS ${J.identifier(De.hubId)}, LOWER(CONVERT(char(64), ${Y(e.sourceDigest)}, 2)) AS ${J.identifier(De.sourceDigest)}, ${Y(e.normalizerVersion)} AS ${J.identifier(De.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${en(t)})`,Aa=(e,t,r)=>J`SELECT TOP (${r}) ${Y(e.id)} AS ${J.identifier(De.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var Ia=e=>({search:async(t,r)=>Ye(r.scope.visible)?[]:ft(await t.execute(Sa(e.tables,r.plan,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=gt(o[Be.sourceType],Be.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${Be.sourceType} is null`);return{reportHubId:Rt(o[Be.reportHubId],Be.reportHubId),businessDate:gt(o[Be.businessDate],Be.businessDate),sourceType:a}})});import{chunk as lr,MAX_IN_LIST as cr}from"@aiquants/mssql";import{sql as Ea}from"drizzle-orm";import{createHash as Tc}from"crypto";var tn=e=>e===null?"n;":`s${e.length}:${e}`,Ac=e=>{let t=Tc("sha256");t.update(`F${e.fields.length};`);for(let[r,n]of e.fields)t.update(tn(r)+tn(n));return t.update(`C${e.comments.length};`),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${tn(r.text)}`)}),t.digest("hex")},rn=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=or(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=or(o.text);t+=a.forcedCuts,a.text.length!==0&&n.push({ordinal:n.length,authorUserId:o.authorUserId,commentText:a.text})}return{hubId:e.hubId,searchText:zo(r),comments:n,sourceDigest:Ac(e),forcedCuts:t}};var wa=e=>{let t=async(m,s)=>{let h=[];for(let d of lr(s,cr))for(let b of ft(await m.execute(ba(e.hub,d))))h.push(Rt(b[De.hubId],De.hubId));return h},r=async(m,s)=>{for(let h of lr(s,cr))await m.execute(Da(e.tables,h,e.normalizerVersion))},n=async(m,s)=>{let h=new Map;for(let d of lr(s,cr))for(let b of ft(await m.execute(Ta(e.tables.document,d))))h.set(Rt(b[De.hubId],De.hubId),{sourceDigest:gt(b[De.sourceDigest],De.sourceDigest),normalizerVersion:gt(b[De.normalizerVersion],De.normalizerVersion)});return h},o=async(m,s,h)=>ft(await m.execute(Aa(e.hub,s,h))).map(d=>Rt(d[De.hubId],De.hubId)),a=async(m,s)=>{let h=await t(m,[...new Set(s)].sort((b,y)=>b-y));if(h.length===0)return;let d=(await e.loadSources(m,h)).map(rn);d.length>0&&await r(m,d)},i=m=>e.inTransaction(async s=>{await s.execute(Ea`SET DEADLOCK_PRIORITY LOW`);let h=await t(s,m),d=await n(s,h),b=(await e.loadSources(s,h)).map(rn),y=b.filter(g=>{let R=d.get(g.hubId);return R===void 0||R.sourceDigest!==g.sourceDigest||R.normalizerVersion!==e.normalizerVersion});return y.length>0&&await r(s,y),await s.execute(Ea`SET DEADLOCK_PRIORITY NORMAL`),{scanned:b.length,written:y.length,forcedCuts:b.reduce((g,R)=>g+R.forcedCuts,0)}});return{writeHubs:a,reconcile:async(m,s)=>{let{batchSize:h,hubIds:d,signal:b,onProgress:y}=s;de("reconcileSearchIndex: batchSize",h,1,cr);let g=ce(),R=d===void 0?null:lr([...new Set(d)].sort((U,_)=>U-_),h),D={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let U=0;;U++){b?.throwIfAborted();let _=R===null?await o(m,D.lastHubId===null?0:D.lastHubId,h):R[U];if(_===void 0||_.length===0)break;let O=await i(_);D={scanned:D.scanned+O.scanned,written:D.written+O.written,skipped:D.skipped+O.scanned-O.written,forcedCuts:D.forcedCuts+O.forcedCuts,lastHubId:_[_.length-1]},y?.(D)}return{...D,elapsedMs:ce()-g}}}};var Je=e=>xc(e),xa=$t([]),Ie=(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"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),m=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${m}:${s}`},Cc=e=>{let{length:t}=e;if(t===void 0)throw ie("tables.hub.title","a character column with a declared length",t);return de("tables.hub.title.length",t,1)},Ca=e=>e===""?null:e,Pc=Object.freeze([]),nn=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},ur=(e,t)=>e.get(t)??Pc,Pa=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(rr);function on(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:m}=e,{hub:s,internal:h,comment:d,label:b,hubLabel:y,userStatus:g}=r,R=e.externalSources??[],D=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],U=D[0]??"\u4E0B\u66F8\u304D",_=he(e.logger,1,"[DailyReportService]");Zt(e);let O=Po(e.attachments),P=Cc(s.title),T=c=>_c(u=>t.transaction(p=>u(()=>c(p))),e.transactionRetry),F=e.search===void 0?null:Ra(e.search,R.map(c=>c.sourceType)),G=F===null?null:Ia({tables:{hub:s,hubLabel:y,label:b,search:F.tables},draftLabelNames:D}),B=null,se=()=>{if(F===null)return null;if(B===null){let c=F.externalSourceTexts;B=wa({hub:s,tables:F.tables,loadSources:(u,p)=>fi(u,p,c),inTransaction:T,normalizerVersion:Wo()})}return B},be=e.idsTtlMs??18e4,ue="daily-report:ids:epoch",q=e.businessDateTtlMs??3e5,X="daily-report:date-epoch:",re="daily-report:detail-epoch:",ne=`${e.streamKey??"daily-report:sse-stream"}:v2`,ye=e.streamMaxLen??1e4,Z=c=>m.incrementEpoch(c),E=c=>Ot(s.sourceType,c),L=async(c,u)=>{let p=await i?.getClient();if(!p){_.warn(`[SSE] Redis client unavailable (${u})`);return}let f=JSON.stringify(c),S=Buffer.byteLength(f);if(S>6356992){_.warn(`[SSE] Event too large (${u}): ${S} bytes > ${6356992}; not published`);return}let A=ce();try{await p.xAdd(ne,"*",{data:f},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:ye}});let I=ce()-A;I>1e3&&_.warn(`[SSE] Slow publish (${u}): ${I}ms`)}catch(I){_.error(`[SSE] Redis publish failed (${u}):`,I)}},v=async()=>{try{let c=await i?.getClient();if(c===void 0)return null;let[u]=await c.xRevRange(ne,"+","-",{COUNT:1});return u===void 0?null:u.id}catch(c){return _.error("SSE stream anchor read failed",c),null}},H=c=>c==null||c===""?null:/^\d+$/.test(c)?a(Number(c)):c,V=()=>{let c={};for(let u of R)c[`ext_${u.sourceType}`]=Je(u.table);return c},K=c=>{let u=c;for(let p of R)u=u.leftJoin(p.table,me(C(s.sourceType,p.sourceType),C(s.sourceIdNum,p.idColumn)));return u},$=c=>{let{hub:u,internal:p}=c,f=u.summary,S=[],A=null,I=null,k=null,x=null,z=null,N=null,te=[],W=R.find(le=>le.sourceType===u.sourceType),ee=W?c[`ext_${W.sourceType}`]:void 0;if(W&&ee){let le=W.mapRow(ee);le.content!==void 0&&(f=le.content),le.employeeName!==void 0&&(N=le.employeeName),le.category!==void 0&&(A=le.category),le.creationCategory!==void 0&&(I=le.creationCategory),le.visitTimeFrom!==void 0&&(k=le.visitTimeFrom),le.visitTimeTo!==void 0&&(x=le.visitTimeTo),le.customerName!==void 0&&(z=le.customerName),le.interviewers!==void 0&&(S=le.interviewers),le.externalComments!==void 0&&(te=le.externalComments)}else u.sourceType==="Internal"&&p&&(f=p.body);return{content:f,author:c.creatorName??H(u.createdBy)??"",employeeName:N??c.creatorName??H(u.createdBy),updatedBy:H(u.updatedBy),category:A,creationCategory:I,visitTimeFrom:k,visitTimeTo:x,customerName:z,interviewers:S,externalComments:te}},j=(c,u,p)=>{let{hub:f}=u,S=$(u),A=(u.labels??[]).map(N=>({id:N.id,name:N.name,color:N.color})),I=u.postedCommentRows??[],k=ve(c.commentable,f.sourceType),x=S.creationCategory?D.includes(S.creationCategory):!1,z=st?.[0]??null;return x&&z&&!A.some(N=>N.id===z)&&A.push({id:z,name:U,color:null}),{reportHubId:f.id,date:Ie(f.businessDate,"YYYY-MM-DD"),author:S.author,userId:f.userId?a(f.userId):"",sourceType:f.sourceType??"Internal",createdAt:Ie(f.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:Ie(f.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:S.updatedBy,employeeName:S.employeeName,category:S.category,creationCategory:S.creationCategory,visitTimeFrom:S.visitTimeFrom,visitTimeTo:S.visitTimeTo,customerName:S.customerName,interviewers:S.interviewers,subject:f.title,content:S.content,externalComments:k?S.externalComments:[],isRead:u.isRead??!1,isStarred:u.isStarred??!1,labels:A,postedComments:I.filter(N=>ya({authorUserId:N.userId},f.sourceType,p??null,c)).map(N=>({...N,userId:a(N.userId),isMine:p?N.userId===p:!1})),attachments:u.attachments}},Q=async(c,u)=>{let p=bt(y,"draft_label"),f=await tt();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).leftJoin(p,me(C(p.hubId,s.id),Te(p.labelId,f))).where(me(Ee(s.deletedAt),Dt(C(s.userId,u),Ee(s.userId),Ee(p.hubId)),E(c.visible))).orderBy(St(s.businessDate),St(s.id))).map(A=>({...A,businessDate:Ie(A.businessDate,"YYYY-MM-DD")}))},M=async(c,u,p)=>{let f=await Ne(u);if(!f)return[];if(Ye(c.visible))return[];let S=bt(y,"draft_label"),A=await tt();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(p).from(s).leftJoin(S,me(C(S.hubId,s.id),Te(S.labelId,A))).where(me(Ee(s.deletedAt),Dt(C(s.userId,f),Ee(s.userId),Ee(S.hubId)),E(c.visible))).orderBy(St(s.businessDate),St(s.id))).map(k=>({...k,businessDate:Ie(k.businessDate,"YYYY-MM-DD")}))},fe=async(c,u)=>{let p=await K(t.select({hub:Je(s),internal:Je(h),creatorName:n.displayName,...V()}).from(s)).leftJoin(h,C(s.id,h.hubId)).leftJoin(n,C(s.userId,n.id)).where(me(C(s.businessDate,_a`${u}`),Ee(s.deletedAt),E(c.visible))).orderBy(St(s.id)),f=await Bt(p.map(S=>S.hub.id));return p.map(S=>j(c,{...S,attachments:f.get(S.hub.id)??[]}))},we=new Map,Ne=async c=>{if(!e.disableUserIdCache&&we.has(c))return we.get(c)??null;let u=await o(c);return u!==null&&!e.disableUserIdCache&&we.set(c,u),u},Xa=async(c,u,{forceRefresh:p=!1,snapshot:f=!1,ttlMsOverride:S,onFetchStart:A}={})=>{let I=await Ne(u);if(!I)return{items:[],streamAnchor:null,snapshot:xa};if(Ye(c.visible))return{items:[],streamAnchor:await v(),snapshot:xa};let k=Xo(I,kt(c)),[x]=await l.getOrFetch({cacheKey:k,fetcher:async()=>{let z=await v(),N=await Q(c,I);if(!yn(N)){_.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let te=[...N].sort(Ft);return[{items:te,streamAnchor:z,snapshot:$t(te)}]}return[{items:N,streamAnchor:z,snapshot:$t(N)}]},onFetchStart:A,forceRefresh:p,snapshot:f,ttlMsOverride:S??be,epochKey:ue,refreshAheadRatio:.5});if(x===void 0)throw new Error("[DailyReportService] ids cache returned no record");return x},Za=(c,u,{forceRefresh:p=!1,snapshot:f=!1,ttlMsOverride:S}={})=>{let A=Pe(u);return A?Ye(c.visible)?Promise.resolve([]):l.getOrFetch({cacheKey:Zo(A,kt(c)),fetcher:()=>fe(c,A),forceRefresh:p,snapshot:f,ttlMsOverride:S??q}):Promise.resolve([])},st=null,Ut=async()=>(st!==null||(st=(await t.select({id:b.id}).from(b).where(Te(b.name,D)).orderBy(b.id)).map(u=>u.id)),st),tt=async()=>{let c=await Ut();return c.length>0?c:[-1]},mr=async()=>{let c=await Ut();if(c.length===0)return null;let[u]=await t.select({id:b.id}).top(1).from(b).where(C(b.name,U));return u?.id??c[0]},ei=(c,u)=>u!=null?"absent":c!=null?"present":"unknown",Bt=async c=>{let u=new Map,p=r.attachment;if(c.length===0||!p||O===null)return u;let f=O.idCodec,S=O.thumbnails!==null,A=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(Te(p.hubId,c)).orderBy(Ce(p.createdAt),Ce(p.id));for(let I of A){let k=I.fileType?String(I.fileType):null,x=I.fileSize!=null?Number(I.fileSize):null,z=ei(I.objectCheckedAt,I.objectMissingAt),N={id:f.encode(Number(I.id)),fileName:String(I.fileName),fileType:k,fileSize:x,createdAt:Ie(I.createdAt,"YYYY-MM-DD HH:mm:ss"),state:z,hasThumbnail:S&&z!=="absent"&&Qt({fileType:k,fileSize:x},O.maxBytes)},te=u.get(Number(I.hubId));te?te.push(N):u.set(Number(I.hubId),[N])}return u},ti=async(c,u,p)=>{let f=r.attachment;if(!f||Ye(c.visible))return null;let S=await tt(),A=bt(y,"draft_label");return(await t.select({fileName:f.fileName,filePath:f.filePath,fileType:f.fileType,fileSize:f.fileSize}).top(1).from(f).innerJoin(s,C(s.id,f.hubId)).leftJoin(A,me(C(A.hubId,s.id),Te(A.labelId,S))).where(me(C(f.id,u),Ee(s.deletedAt),Dt(C(s.userId,p),Ee(A.hubId)),E(c.visible))))[0]??null},ri=async c=>{let u=r.attachment;if(!u)return;let p=new Date;try{await t.update(u).set({objectCheckedAt:p,objectMissingAt:p,updatedAt:p}).where(C(u.id,c))}catch(f){_.error("markAttachmentMissing failed",f)}},ni=async c=>{let u=r.attachment;if(!u)return;let p=new Date;try{await t.update(u).set({objectCheckedAt:p,objectMissingAt:null,updatedAt:p}).where(C(u.id,c))}catch(f){_.error("markAttachmentPresent failed",f)}},sn=async(c,u,p)=>{let f=await tt(),S=bt(y,"draft_label"),A=await K(t.select({hub:Je(s),internal:Je(h),isRead:g.isRead,isStarred:g.isStarred,creatorName:n.displayName,...V()}).from(s)).leftJoin(h,C(s.id,h.hubId)).leftJoin(g,me(C(s.id,g.hubId),C(g.userId,u))).leftJoin(S,me(C(S.hubId,s.id),Te(S.labelId,f))).leftJoin(n,C(s.userId,n.id)).where(me(p,Ee(s.deletedAt),Dt(C(s.userId,u),Ee(S.hubId)),E(c.visible))).orderBy(St(s.id));if(A.length===0)return[];let I=A.map(W=>W.hub.id),k=await t.select({hubId:y.hubId,id:b.id,name:b.name,color:b.color}).from(y).innerJoin(b,C(y.labelId,b.id)).where(Te(y.hubId,I)),x=await t.select({hubId:d.hubId,id:d.id,body:d.body,createdAt:d.createdAt,userId:d.userId,userName:n.displayName}).from(d).leftJoin(n,C(d.userId,n.id)).where(Te(d.hubId,I)).orderBy(Ce(d.createdAt)),z=await Bt(I),N=new Map,te=new Map;for(let W of k){let ee=N.get(W.hubId);ee||(ee=[],N.set(W.hubId,ee)),ee.push({id:W.id,name:W.name,color:W.color})}for(let W of x){let ee=te.get(W.hubId);ee||(ee=[],te.set(W.hubId,ee)),ee.push({id:W.id,content:W.body,createdAt:Ie(W.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:W.userId,userName:W.userName||""})}return A.map(W=>{let ee=W.hub.id;return j(c,{...W,attachments:z.get(ee)??[],labels:N.get(ee)||[],postedCommentRows:te.get(ee)||[]},u)})},oi=async(c,u,p,{forceRefresh:f=!1,snapshot:S=!1,ttlMsOverride:A}={})=>{let I=await Ne(p);if(!I)return[];let k=Pe(u);if(!k)return[];if(Ye(c.visible))return[];let x=ea(k,I,kt(c));return l.getOrFetch({cacheKey:x,fetcher:()=>sn(c,I,C(s.businessDate,_a`${k}`)),forceRefresh:f,snapshot:S,ttlMsOverride:A??q,epochKey:`${X}${k}`})},Tt=async(c,u,p,{forceRefresh:f=!1,snapshot:S=!1,ttlMsOverride:A}={})=>{if(Ye(c.visible))return null;let I=ta(u,p,kt(c));return(await l.getOrFetch({cacheKey:I,fetcher:async()=>{let x=await tt(),z=bt(y,"draft_label"),N=await K(t.select({hub:Je(s),internal:Je(h),isRead:g.isRead,isStarred:g.isStarred,creatorName:n.displayName,...V()}).from(s)).leftJoin(h,C(s.id,h.hubId)).leftJoin(g,me(C(s.id,g.hubId),C(g.userId,p))).leftJoin(z,me(C(z.hubId,s.id),Te(z.labelId,x))).leftJoin(n,C(s.userId,n.id)).where(me(C(s.id,u),Ee(s.deletedAt),Dt(C(s.userId,p),Ee(z.hubId)),E(c.visible)));if(N.length===0)return[];let te=N[0].hub.id,W=await t.select({id:b.id,name:b.name,color:b.color}).from(y).innerJoin(b,C(y.labelId,b.id)).where(C(y.hubId,te)),ee=await t.select({id:d.id,body:d.body,createdAt:d.createdAt,userId:d.userId,userName:n.displayName}).from(d).leftJoin(n,C(d.userId,n.id)).where(C(d.hubId,te)).orderBy(Ce(d.createdAt)),le=await Bt([te]),Ei=W.map(qe=>({id:qe.id,name:qe.name,color:qe.color})),wi=ee.map(qe=>({id:qe.id,content:qe.body,createdAt:Ie(qe.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:qe.userId,userName:qe.userName||""}));return[j(c,{...N[0],attachments:le.get(te)??[],labels:Ei,postedCommentRows:wi},p)]},forceRefresh:f,snapshot:S,ttlMsOverride:A??q,epochKey:`${re}${u}`}))[0]??null},ai=async(c,u,p,f={})=>{let S=await Ne(p);return S?Tt(c,u,S,f):null},ii=async(c,u,p)=>{if(u.length>Oe.maxDetailIds)throw ie("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${Oe.maxDetailIds} ids`,u.length);let f=await Ne(p);return!f||u.length===0?[]:Ye(c.visible)?[]:sn(c,f,Te(s.id,[...u]))},si=async(c,u)=>{let p=await tt(),f=bt(y,"draft_label"),[S]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).leftJoin(f,me(C(f.hubId,s.id),Te(f.labelId,p))).where(me(C(s.id,c),Dt(C(s.userId,u),Ee(f.hubId))));return S??null},pr=async(c,u,p)=>{let f=await si(u,p);if(!f||f.deletedAt||!ve(c.visible,f.sourceType))throw new Error("Not Found")},li=async(c,u,p,f,S,A)=>{await pr(c,p,u);let I=await t.select().top(1).from(g).where(me(C(g.hubId,p),C(g.userId,u))),k;if(I.length>0?I[0].isStarred!==S?k=(await t.update(g).set({isStarred:S,updatedAt:new Date,updatedBy:String(u)}).output().where(me(C(g.hubId,p),C(g.userId,u))))[0]:k=I[0]:k=(await t.insert(g).output().values({hubId:p,userId:u,isStarred:S,isRead:!1,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}))[0],f){let x=Pe(f);x&&(l.invalidatePrefix(pt(x,u)),await Z(`${X}${x}`))}return l.invalidatePrefix(ir(p,u)),await Z(`${re}${p}`),await L(qt.parse({type:"status-update",reportHubId:p,recipientRawUserId:u,statusType:"star",value:S,clientTempId:A}),"setStarStatus"),k},ci=async(c,u,p,f,S,A)=>{await pr(c,p,u);let I=await t.select().top(1).from(g).where(me(C(g.hubId,p),C(g.userId,u))),k;if(I.length>0?I[0].isRead!==S?k=(await t.update(g).set({isRead:S,updatedAt:new Date,updatedBy:String(u)}).output().where(me(C(g.hubId,p),C(g.userId,u))))[0]:k=I[0]:k=(await t.insert(g).output().values({hubId:p,userId:u,isRead:S,isStarred:!1,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}))[0],f){let x=Pe(f);x&&(l.invalidatePrefix(pt(x,u)),await Z(`${X}${x}`))}return l.invalidatePrefix(ir(p,u)),await Z(`${re}${p}`),await L(qt.parse({type:"status-update",reportHubId:p,recipientRawUserId:u,statusType:"read",value:S,clientTempId:A}),"setReadStatus"),k},ln=async(c,u)=>{if(u===null)return;let p=await tt(),[f]=await t.select({hubId:y.hubId}).top(1).from(y).where(me(C(y.hubId,c),Te(y.labelId,p)));return f?u:void 0},ui=async(c,u,p,f,S,A)=>{let[I]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where(C(s.id,p));if(!I||I.deletedAt)throw new Error("Not Found");if(await pr(c,p,u),!ve(c.commentable,I.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(I.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let k=await ln(p,I.userId),x=se(),z=await T(async ee=>{let[le]=await ee.insert(d).output().values({hubId:p,userId:u,body:f,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)});return x!==null&&await x.writeHubs(ee,[p]),le}),[N]=await t.select({displayName:n.displayName}).top(1).from(n).where(C(n.id,u)),te=N?.displayName??"";if(S){let ee=Pe(S);ee&&(l.invalidatePrefix(Lt(ee)),await Z(`${X}${ee}`))}l.invalidatePrefix(Ve(p)),await Z(`${re}${p}`);let W={id:z.id,userId:a(z.userId),userName:te,content:z.body,createdAt:Ie(z.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await L(Ir.parse({type:"comment-add",reportHubId:p,comment:W,clientTempId:A,recipientRawUserId:k,sourceType:I.sourceType}),"addComment"),W},di=async(c,u)=>await c.select().top(1).from(d).where(C(d.id,u)),mi=async(c,u,p,f,S,A)=>{let I=await di(t,f);if(I.length===0)throw new Error("Not Found");if(I[0].hubId!==p)throw new Error("Not Found");let[k]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where(C(s.id,I[0].hubId));if(!(k&&ve(c.visible,k.sourceType)))throw new Error("Not Found");if(I[0].userId!==u)throw new Error("Unauthorized");let x=await ln(p,k.userId),z=se();if(await T(async N=>{await N.delete(d).where(C(d.id,f)),z!==null&&await z.writeHubs(N,[p])}),S){let N=Pe(S);N&&(l.invalidatePrefix(Lt(N)),await Z(`${X}${N}`))}l.invalidatePrefix(Ve(p)),await Z(`${re}${p}`),await L(Er.parse({type:"comment-delete",reportHubId:p,commentId:f,clientTempId:A,recipientRawUserId:x,sourceType:k?.sourceType}),"deleteComment")},pi=async(c,u)=>{let p=new Map,f=r.attachment;if(!f||O===null)return p;let S=await c.select({hubId:f.hubId,fileName:f.fileName}).from(f).where(Te(f.hubId,[...u])).orderBy(Ce(f.hubId),Ce(f.createdAt),Ce(f.id));for(let A of S)nn(p,Number(A.hubId),String(A.fileName));return p},yi=async(c,u,p)=>{let f=new Map;for(let[S,A]of p){let I=new Map;for(let{hub:x}of u)x.sourceType===S&&x.sourceIdNum!==null&&I.set(x.sourceIdNum,x.id);if(I.size===0)continue;let k=await A(c,[...I.keys()]);for(let[x,z]of k){let N=I.get(x);if(N===void 0)throw ie(`search.externalSourceTexts.${S} answer key`,"a source id that was asked for",x);if(!(Array.isArray(z)&&z.every(te=>typeof te=="string")))throw ie(`search.externalSourceTexts.${S} answer for ${x}`,"an array of strings",z);f.set(N,z)}}return f},hi=(c,u)=>{let p=$(c),f=[["subject",c.hub.title],["content",p.content],["author",p.author],["employeeName",p.employeeName],["updatedBy",p.updatedBy],["category",p.category],["creationCategory",p.creationCategory],["customerName",p.customerName]];for(let A of p.interviewers)f.push(["interviewerName",A.name??null],["interviewerAffiliation",A.affiliation??null]);for(let A of u.labelNames)f.push(["label",A]);for(let A of u.attachmentNames)f.push(["attachment",A]);for(let A of u.extraTexts)f.push(["extra",A]);let S=[];for(let A of p.externalComments)S.push({authorUserId:null,text:Pa(A.name,A.text)});for(let A of u.postedComments)S.push({authorUserId:A.userId,text:Pa(A.userName,A.body)});return{hubId:c.hub.id,fields:f,comments:S}},fi=async(c,u,p)=>{let f=[];for(let S of Ec(u,wc)){let A=await K(c.select({hub:Je(s),internal:Je(h),creatorName:n.displayName,...V()}).from(s)).leftJoin(h,C(s.id,h.hubId)).leftJoin(n,C(s.userId,n.id)).where(Te(s.id,[...S])).orderBy(Ce(s.id)),I=new Map,k=await c.select({hubId:y.hubId,name:b.name}).from(y).innerJoin(b,C(y.labelId,b.id)).where(Te(y.hubId,[...S])).orderBy(Ce(y.hubId),Ce(b.id));for(let W of k)nn(I,W.hubId,W.name);let x=new Map,z=await c.select({hubId:d.hubId,userId:d.userId,body:d.body,userName:n.displayName}).from(d).leftJoin(n,C(d.userId,n.id)).where(Te(d.hubId,[...S])).orderBy(Ce(d.hubId),Ce(d.createdAt),Ce(d.id));for(let W of z)nn(x,W.hubId,W);let N=await pi(c,S),te=await yi(c,A,p);for(let W of A){let ee=W.hub.id;f.push(hi(W,{labelNames:ur(I,ee),postedComments:ur(x,ee),attachmentNames:ur(N,ee),extraTexts:ur(te,ee)}))}}return f},Ri=(c,u,p)=>G===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):G.search(t,{plan:p,viewerUserId:u,scope:c}),gi=c=>{let u=se();return u===null?Promise.reject(new Error("[daily-report] reconcileSearchIndex: the search setting is not configured")):u.reconcile(t,c)},bi=async(c,u,p)=>{if(!Vt(u))throw ie("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",u);_.info("createDailyReport called",{userId:c,businessDate:u});let[f]=await t.select({displayName:n.displayName}).from(n).where(C(n.id,c)),S=f?.displayName??a(c),A=se();try{let I=await T(async x=>{_.info("Starting transaction");let z=`internal-temp-${Date.now()}-${Math.random()}`,[N]=await x.insert(s).output().values({sourceType:"Internal",sourceId:z,businessDate:new Date(`${u}T00:00:00Z`),userId:c,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)});await x.update(s).set({sourceId:String(N.id)}).where(C(s.id,N.id)),_.info("Hub created",N),await x.insert(h).values({hubId:N.id,body:"",createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)}),_.info("Internal created"),_.info("Calling getDraftLabelId");let te=await mr();_.info("draftLabelId",te);let W=[];return te&&(await x.insert(y).values({hubId:N.id,labelId:te,createdAt:new Date,createdBy:String(c)}),W.push({id:te,name:U,color:null})),_.info("Label assigned"),A!==null&&await A.writeHubs(x,[N.id]),{reportHubId:N.id,date:u,createdAt:Ie(N.createdAt,"YYYY-MM-DD HH:mm:ss"),author:S,userId:a(c),sourceType:"Internal",employeeName:S,updatedBy:a(c),updatedAt:Ie(N.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:N.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:W,postedComments:[],attachments:[]}});l.invalidatePrefix(pt(u,c)),l.invalidatePrefix(at),l.invalidatePrefix(Jr(c)),await Z(ue),await Z(`${X}${u}`);let k=await Tt(Le.unrestricted("post-write self read: the writer always sees the row they just wrote"),I.reportHubId,c,{forceRefresh:!0});if(k){let x=await Ut(),z=k.labels.some(N=>x.includes(N.id));await L(wr.parse({type:"report-create",reportHubId:k.reportHubId,report:k,clientTempId:p,recipientRawUserId:z?c:void 0}),"createDailyReport")}return k??I}catch(I){throw _.error("Error in createDailyReport",I),I}},Ht=async(c,u)=>await c.select().top(1).from(s).where(C(s.id,u)),yr=async(c,u,p)=>{await c.update(s).set(p).where(C(s.id,u))},cn=async(c,u,p)=>{await c.update(h).set(p).where(C(h.hubId,u))},un=async(c,u,p)=>{await c.delete(y).where(me(C(y.hubId,u),C(y.labelId,p)))},Si=async(c,u,p)=>{let f=await Ht(t,c);if(!f.length||f[0].deletedAt)throw new Error("Not Found");if(f[0].userId!==u)throw new Error("Unauthorized");let S=se();if(await T(async A=>{await yr(A,c,{deletedAt:new Date,deletedBy:String(u),updatedAt:new Date,updatedBy:String(u)}),S!==null&&await S.writeHubs(A,[c])}),l.invalidatePrefix(Ve(c)),l.invalidatePrefix(at),l.invalidatePrefix(ot),await Z(ue),f[0].businessDate){let A=Pe(Ie(f[0].businessDate,"YYYY-MM-DD"));A&&await Z(`${X}${A}`)}await L(Cr.parse({type:"report-delete",reportHubId:c,clientTempId:p,sourceType:f[0].sourceType}),"deleteDailyReport")},Di=async(c,u,p,f)=>{let S=await Ht(t,c);if(!S.length||S[0].deletedAt)throw new Error("Not Found");if(S[0].userId!==u)throw new Error("Unauthorized");let A=se();await T(async x=>{p.title!==void 0&&await yr(x,c,{title:Ca(p.title),updatedAt:new Date,updatedBy:String(u)}),p.content!==void 0&&await cn(x,c,{body:Ca(p.content),updatedAt:new Date,updatedBy:String(u)}),A!==null&&await A.writeHubs(x,[c])}),l.invalidatePrefix(Ve(c)),l.invalidatePrefix(at),await Z(`${re}${c}`);let I=Pe(Ie(S[0].businessDate,"YYYY-MM-DD"));I&&(l.invalidatePrefix(Lt(I)),await Z(`${X}${I}`));let k=await Tt(Le.unrestricted("post-write self read: the writer always sees the row they just wrote"),c,u,{forceRefresh:!0});if(k){let x=await Ut(),z=k.labels.some(N=>x.includes(N.id));await L(_r.parse({type:"report-update",reportHubId:k.reportHubId,report:k,clientTempId:f,recipientRawUserId:z?u:void 0}),"updateDailyReport")}},Ti=async(c,u,p)=>{let f=await Ht(t,c);if(!f.length)throw new Error("Not Found");if(f[0].userId!==u)throw new Error("Unauthorized");let S=await mr();if(!S)return null;let A=se();if(await T(async x=>{await un(x,c,S),A!==null&&await A.writeHubs(x,[c])}),l.invalidatePrefix(Ve(c)),l.invalidatePrefix(at),l.invalidatePrefix(ot),await Z(ue),f[0].businessDate){let x=Pe(Ie(f[0].businessDate,"YYYY-MM-DD"));x&&await Z(`${X}${x}`)}let I=Pe(Ie(f[0].businessDate,"YYYY-MM-DD"));I&&l.invalidatePrefix(pt(I,u));let k=await Tt(Le.unrestricted("post-write self read: the writer always sees the row they just wrote"),c,u,{forceRefresh:!0});return k&&await L(xr.parse({type:"report-publish",reportHubId:k.reportHubId,report:k,clientTempId:p}),"publishDailyReport"),k??null},Ai=async(c,u)=>{l.invalidatePrefix(at),l.invalidatePrefix(ot),await Z(ue);for(let p of new Set(c))l.invalidatePrefix(Ve(p)),await Z(`${re}${p}`);for(let p of new Set(u)){let f=Pe(p);f&&await Z(`${X}${f}`)}},Ii=async()=>{l.clearAll(),we.clear(),st=null,m&&await Z(ue),_.info("Server-side DB/SQL caches cleared successfully.")};return{streamKey:ne,streamMaxLen:ye,attachmentDelivery:O,titleMaxLength:P,searchLimits:F===null?null:{concurrency:F.concurrency,rateLimitPerMinute:F.rateLimitPerMinute},clearCache:Ii,invalidateHubReadCaches:Ai,getUserIdByExternalId:Ne,getDailyReportIdsByExternalId:Xa,getDailyReportIdsFirstPageByExternalId:M,readSseStreamAnchor:v,getDailyReportsByBusinessDate:Za,getDailyReportsByBusinessDateByExternalId:oi,getDailyReportDetailById:Tt,getDailyReportDetailByIdByExternalId:ai,getDailyReportDetailsByIdsByExternalId:ii,getDraftLabelId:mr,searchDailyReports:Ri,reconcileSearchIndex:gi,getAttachmentsByHubIds:Bt,getAttachmentForUser:ti,markAttachmentMissing:ri,markAttachmentPresent:ni,setStarStatus:li,setReadStatus:ci,addComment:ui,deleteComment:mi,createDailyReport:bi,updateDailyReport:Di,publishDailyReport:Ti,deleteDailyReport:Si,findDailyReportHubById:Ht,updateDailyReportHub:yr,updateDailyReportInternal:cn,deleteDailyReportLabel:un}}var Ma="[DailyReportExternalSource]",Mc=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(he(n,1,Ma).warn(`Unexpected ${t} format: not an array`),[])}catch(o){return he(n,1,Ma).warn(`Failed to parse ${t}:`,o),[]}};import{desc as La,sql as Lc}from"drizzle-orm";import{bigint as Se,bit as va,date as vc,datetime2 as Ae,foreignKey as He,index as et,int as Nc,mssqlSchema as Oc,nvarchar as oe,primaryKey as it,uniqueIndex as kc}from"drizzle-orm/mssql-core";function Uc(e,t){let r=Oc(e),n=t.userTable,o=r.table("DailyReportHub",{id:Se("id",{mode:"number"}).identity().notNull(),sourceType:oe("source_type",{length:20}).notNull(),sourceId:oe("source_id",{length:100}).notNull(),sourceIdNum:Se("source_id_num",{mode:"number"}).generatedAlwaysAs(Lc`TRY_CAST(source_id AS BIGINT)`),businessDate:vc("business_date"),userId:Se("user_id",{mode:"number"}),title:oe("title",{length:200}),summary:oe("summary",{length:"max"}),createdAt:Ae("created_at").notNull(),createdBy:oe("created_by",{length:50}).notNull(),updatedAt:Ae("updated_at").notNull(),updatedBy:oe("updated_by",{length:50}).notNull(),deletedAt:Ae("deleted_at"),deletedBy:oe("deleted_by",{length:50})},d=>[it({name:`${e}_DailyReportHub_pk`,columns:[d.id]}),He({name:`${e}_DailyReportHub_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]}),et(`${e}_DailyReportHub_business_date_index`).on(d.businessDate),et(`${e}_DailyReportHub_updated_at_index`).on(d.updatedAt),et(`${e}_DailyReportHub_source_index`).on(d.sourceType,d.sourceId),et(`${e}_DailyReportHub_user_id_index`).on(d.userId),et(`${e}_DailyReportHub_business_date_id_index`).on(La(d.businessDate),La(d.id)),et(`${e}_DailyReportHub_deleted_at_index`).on(d.deletedAt)]),a=r.table("DailyReportInternal",{hubId:Se("hub_id",{mode:"number"}).notNull(),body:oe("body",{length:"max"}),metadata:oe("metadata",{length:"max"}),createdAt:Ae("created_at").notNull(),createdBy:oe("created_by",{length:50}).notNull(),updatedAt:Ae("updated_at").notNull(),updatedBy:oe("updated_by",{length:50}).notNull()},d=>[it({name:`${e}_DailyReportInternal_pk`,columns:[d.hubId]}),He({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[d.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:Se("id",{mode:"number"}).identity().notNull(),hubId:Se("hub_id",{mode:"number"}).notNull(),userId:Se("user_id",{mode:"number"}).notNull(),body:oe("body",{length:"max"}).notNull(),createdAt:Ae("created_at").notNull(),createdBy:oe("created_by",{length:50}).notNull(),updatedAt:Ae("updated_at").notNull(),updatedBy:oe("updated_by",{length:50}).notNull()},d=>[it({name:`${e}_DailyReportComment_pk`,columns:[d.id]}),He({name:`${e}_DailyReportComment_hub_id_fk`,columns:[d.hubId],foreignColumns:[o.id]}),He({name:`${e}_DailyReportComment_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]}),et(`${e}_DailyReportComment_hub_id_index`).on(d.hubId)]),l=r.table("DailyReportLabel",{id:Se("id",{mode:"number"}).identity().notNull(),userId:Se("user_id",{mode:"number"}),name:oe("name",{length:50}).notNull(),color:oe("color",{length:20}),sortOrder:Nc("sort_order"),createdAt:Ae("created_at").notNull(),createdBy:oe("created_by",{length:50}).notNull(),updatedAt:Ae("updated_at").notNull(),updatedBy:oe("updated_by",{length:50}).notNull()},d=>[it({name:`${e}_DailyReportLabel_pk`,columns:[d.id]}),He({name:`${e}_DailyReportLabel_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]})]),m=r.table("DailyReportHub_Label",{hubId:Se("hub_id",{mode:"number"}).notNull(),labelId:Se("label_id",{mode:"number"}).notNull(),createdAt:Ae("created_at").notNull(),createdBy:oe("created_by",{length:50}).notNull()},d=>[it({name:`${e}_DailyReportHub_Label_pk`,columns:[d.hubId,d.labelId]}),He({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[d.hubId],foreignColumns:[o.id]}),He({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[d.labelId],foreignColumns:[l.id]})]),s=r.table("DailyReportUserStatus",{hubId:Se("hub_id",{mode:"number"}).notNull(),userId:Se("user_id",{mode:"number"}).notNull(),isRead:va("is_read").default(!1).notNull(),isStarred:va("is_starred").default(!1).notNull(),createdAt:Ae("created_at").notNull(),createdBy:oe("created_by",{length:50}).notNull(),updatedAt:Ae("updated_at").notNull(),updatedBy:oe("updated_by",{length:50}).notNull()},d=>[it({name:`${e}_DailyReportUserStatus_pk`,columns:[d.hubId,d.userId]}),He({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[d.hubId],foreignColumns:[o.id]}),He({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]})]),h=r.table("DailyReportAttachment",{id:Se("id",{mode:"number"}).identity().notNull(),hubId:Se("hub_id",{mode:"number"}).notNull(),uploadedBy:Se("uploaded_by",{mode:"number"}),sourceKey:oe("source_key",{length:200}).notNull(),fileName:oe("file_name",{length:255}).notNull(),filePath:oe("file_path",{length:"max"}).notNull(),fileType:oe("file_type",{length:100}),fileSize:Se("file_size",{mode:"number"}),objectCheckedAt:Ae("object_checked_at"),objectMissingAt:Ae("object_missing_at"),createdAt:Ae("created_at").notNull(),createdBy:oe("created_by",{length:50}).notNull(),updatedAt:Ae("updated_at").notNull(),updatedBy:oe("updated_by",{length:50}).notNull()},d=>[it({name:`${e}_DailyReportAttachment_pk`,columns:[d.id]}),He({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[d.hubId],foreignColumns:[o.id]}),He({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[d.uploadedBy],foreignColumns:[n.id]}),kc(`${e}_DailyReportAttachment_source_unique`).on(d.hubId,d.sourceKey),et(`${e}_DailyReportAttachment_hub_id_index`).on(d.hubId,d.createdAt)]);return{hub:o,internal:a,comment:i,attachment:h,label:l,hubLabel:m,userStatus:s}}import{bigint as an,binary as Na,datetime2 as Bc,int as Hc,mssqlSchema as $c,nvarchar as Oa,primaryKey as ka,varchar as Fc}from"drizzle-orm/mssql-core";function Vc(e){let t=$c(e),r=t.table("DailyReportSearchDocument",{hubId:an("hub_id",{mode:"number"}).notNull(),searchText:Oa("search_text",{length:"max"}).notNull(),sourceDigest:Na("source_digest",{length:32}).notNull(),normalizerVersion:Fc("normalizer_version",{length:64}).notNull(),indexedAt:Bc("indexed_at").notNull(),rowVersion:Na("row_version",{length:8}).notNull()},o=>[ka({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:an("hub_id",{mode:"number"}).notNull(),ordinal:Hc("ordinal").notNull(),authorUserId:an("author_user_id",{mode:"number"}),commentText:Oa("comment_text",{length:"max"}).notNull()},o=>[ka({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var Yc=5e7,Wa=2e8,qc=1,Ka=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})})}),Ua=125,Ba=4,Ha=16,$a=50,Fa=2,dr=Object.freeze({renderMs:xe.renderMs,nanosecondsPerBlockVisit:Ua,margin:Ba,maxBlockVisits:Math.floor(xe.renderMs*1e6/(Ua*Ba)),walkBudgetMs:Ha,nanosecondsPerWalkStep:$a,walkMargin:Fa,maxWalkSteps:Math.floor(Ha*1e6/($a*Fa))}),jc=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Va=75,Ya=4,qa="#ffffff",zc=1,Wc={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Kc=[/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/],ja=Object.freeze({ok:!1,reason:"failed"}),za=Object.freeze({ok:!1,reason:"unsupported"}),Ja=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:uo(e)}),Ga=(e,t)=>{switch(t){case"jpeg":{let r=Vr(e);return r===null?null:Ja(r)}case"png":{let r=yo(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=ho(e,dr.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},Qa=(e,t)=>{let r=jc.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=Ka,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},Jc=(e,t,r)=>{let n=Ga(e,t);return n===null?null:Qa(n,r)},Gc=e=>e!==null&&e<=Wa,Qc=(e,t)=>{if(t!=="jpeg")return Ga(e,t);let r=mo(e,dr);return r===null||r.blockVisits>dr.maxBlockVisits?null:Ja(r.header)},Xc=e=>{let t=e instanceof Error?e.message:"";return Kc.some(r=>r.test(t))?"failed":"unsupported"},Zc=e=>{e.cache(!1),e.concurrency(qc),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Wc)});let t=async(n,o,a,i,l)=>{let m=Qc(n,o);if(m===null)return za;try{let s=e(n,{limitInputPixels:Yc,animated:!1});if(!Gc(Qa(m,await s.metadata())))return za;if(l.aborted)return ja;let h=await s.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:qa}).webp({quality:Va,effort:Ya}).toBuffer();return{ok:!0,bytes:new Uint8Array(h),contentType:"image/webp"}}catch(s){return{ok:!1,reason:Xc(s)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?ja:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Va}-e${Ya}/flatten-${qa}/v${zc}`,render:r}};function Sy(e){e.redis||he(e.logger,2,"[DailyReportServer]").warn("redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=Rr(e.redis),r=new Et({defaultTtlMs:e.cacheDefaultTtlMs??6e4},t),n=on({...e,cache:r,epochs:t}),o=new vt({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Xr({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(i=>i.sourceType)])],...a}}export{qr as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,Yr as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,Wa as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,dr as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,Ka as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,Gr as DAILY_REPORT_SSE_CATCH_UP_BATCH,la as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,vt as DailyReportSseReader,Le as DailyReportViewerScope,Et as SqlResultCache,Xr as createDailyReportHandlers,Sy as createDailyReportServer,on as createDailyReportService,Rr as createEpochStore,Zc as createSharpThumbnailRenderer,Uc as defineDailyReportSchema,Vc as defineDailyReportSearchSchema,Hr as generateETag,Ze as isStreamIdLte,ae as jsonResponseWithETag,Pr as parseClientTempId,Jc as predictSharpThumbnailWorkingSetBytes,Mt as readDailyReportSseStreamEntry,Mc as transformJsonArray};
|
|
11
|
+
INSERT INTO ${o} (${z(o.hubId)}, ${z(o.ordinal)}, ${z(o.authorUserId)}, ${z(o.commentText)}) SELECT ${z(o.hubId)}, ${z(o.ordinal)}, ${z(o.authorUserId)}, ${z(o.commentText)} FROM OPENJSON(${i}) WITH (${z(o.hubId)} bigint, ${z(o.ordinal)} int, ${z(o.authorUserId)} bigint, ${z(o.commentText)} nvarchar(max));`},li=(e,t)=>Y`SELECT ${z(e.hubId)} AS ${Y.identifier(Te.hubId)}, LOWER(CONVERT(char(64), ${z(e.sourceDigest)}, 2)) AS ${Y.identifier(Te.sourceDigest)}, ${z(e.normalizerVersion)} AS ${Y.identifier(Te.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${ti(t)})`,ci=(e,t,r)=>Y`SELECT TOP (${r}) ${z(e.id)} AS ${Y.identifier(Te.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var ui=e=>({search:async(t,r)=>He(r.scope.visible)?[]:pt(await t.execute(ai(e.tables,r.plan,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=xt(o[Ve.sourceType],Ve.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${Ve.sourceType} is null`);return{reportHubId:yt(o[Ve.reportHubId],Ve.reportHubId),businessDate:xt(o[Ve.businessDate],Ve.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(He(r.scope.visible))return new Map;let n=pt(await t.execute(ii(e.tables,r.plan,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames,r.ids))),o=2**r.plan.sets.length-1,a=new Map;for(let i of n){let l=i[ht.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${ht.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(yt(i[ht.reportHubId],ht.reportHubId),l)}return a}});import{chunk as Er,MAX_IN_LIST as Ir}from"@aiquants/mssql";import{sql as di}from"drizzle-orm";import{createHash as $u}from"crypto";var xn=e=>e===null?"n;":`s${e.length}:${e}`,Bu=e=>{let t=$u("sha256");t.update(`F${e.fields.length};`);for(let[r,n]of e.fields)t.update(xn(r)+xn(n));return t.update(`C${e.comments.length};`),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${xn(r.text)}`)}),t.digest("hex")},Cn=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=gr(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=gr(o.text);t+=a.forcedCuts,a.text.length!==0&&n.push({ordinal:n.length,authorUserId:o.authorUserId,commentText:a.text})}return{hubId:e.hubId,searchText:_a(r),comments:n,sourceDigest:Bu(e),forcedCuts:t}};var mi=e=>{let t=async(c,s)=>{let y=[];for(let m of Er(s,Ir))for(let S of pt(await c.execute(ri(e.hub,m))))y.push(yt(S[Te.hubId],Te.hubId));return y},r=async(c,s)=>{for(let y of Er(s,Ir))await c.execute(si(e.tables,y,e.normalizerVersion))},n=async(c,s)=>{let y=new Map;for(let m of Er(s,Ir))for(let S of pt(await c.execute(li(e.tables.document,m))))y.set(yt(S[Te.hubId],Te.hubId),{sourceDigest:xt(S[Te.sourceDigest],Te.sourceDigest),normalizerVersion:xt(S[Te.normalizerVersion],Te.normalizerVersion)});return y},o=async(c,s,y)=>pt(await c.execute(ci(e.hub,s,y))).map(m=>yt(m[Te.hubId],Te.hubId)),a=async(c,s)=>{let y=await t(c,[...new Set(s)].sort((S,f)=>S-f));if(y.length===0)return;let m=(await e.loadSources(c,y)).map(Cn);m.length>0&&await r(c,m)},i=c=>e.inTransaction(async s=>{await s.execute(di`SET DEADLOCK_PRIORITY LOW`);let y=await t(s,c),m=await n(s,y),S=(await e.loadSources(s,y)).map(Cn),f=S.filter(R=>{let b=m.get(R.hubId);return b===void 0||b.sourceDigest!==R.sourceDigest||b.normalizerVersion!==e.normalizerVersion});return f.length>0&&await r(s,f),await s.execute(di`SET DEADLOCK_PRIORITY NORMAL`),{scanned:S.length,written:f.length,forcedCuts:S.reduce((R,b)=>R+b.forcedCuts,0)}});return{writeHubs:a,reconcile:async(c,s)=>{let{batchSize:y,hubIds:m,signal:S,onProgress:f}=s;ee("reconcileSearchIndex: batchSize",y,1,Ir);let R=ce(),b=m===void 0?null:Er([...new Set(m)].sort((I,v)=>I-v),y),g={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let I=0;;I++){S?.throwIfAborted();let v=b===null?await o(c,g.lastHubId===null?0:g.lastHubId,y):b[I];if(v===void 0||v.length===0)break;let $=await i(v);g={scanned:g.scanned+$.scanned,written:g.written+$.written,skipped:g.skipped+$.scanned-$.written,forcedCuts:g.forcedCuts+$.forcedCuts,lastHubId:v[v.length-1]},f?.(g)}return{...g,elapsedMs:ce()-R}}}};import{holdsMultiUnitCluster as Fu}from"@aiquants/fuzzy-search/normalize";var Mn=255,_r=Object.values(ct).sort((e,t)=>e-t),Vu=new Intl.Segmenter("und",{granularity:"grapheme"}),Yu=(e,t)=>{if(e.text!==t)throw new Error(`[daily-report] search marks: the position-mapped line (${e.text.length} units) differs from the index line (${t.length} units)`);return e},qu=(e,t)=>e.chunks.length===1&&e.chunks[0].length===1&&e.chunks[0][0].start===0&&e.chunks[0][0].end===t.length,Wu=(e,t,r)=>{let n=e.slice(t,r);if(!Fu(n))return null;let o=new Int32Array(r-t),a=new Int32Array(r-t);for(let{index:i,segment:l}of Vu.segment(n))o.fill(t+i,i,i+l.length),a.fill(t+i+l.length,i,i+l.length);return{start:t,clusterStarts:o,clusterEnds:a}},ju=(e,t,r)=>({start:e.clusterStarts[t-e.start],end:e.clusterEnds[r-1-e.start]}),zu=(e,t,r=Sr)=>{let n=new Map;for(let l of t){if(l.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let c=n.get(l.text);(c===void 0||l.tier<c)&&n.set(l.text,l.tier)}let o=[];if(n.size===0)return o;let a=Aa(e),i=l=>a.rawIndex===null?l:a.rawIndex[l];return bn(a.text,(l,c)=>{let s=gn(l,r).text,y=null,m=null;for(let[S,f]of n){let R=s.indexOf(S);if(!(R<0)){if(y===null){let b=Sn(l,r);y=Yu(Ia(l,b),s),m=qu(b,l)?null:Wu(e,i(c),i(c+l.length-1)+1)}for(;R>=0;){let b=i(c+y.start[R]),g=i(c+y.end[R+S.length-1]-1)+1;m===null?o.push({start:b,end:g,tier:f}):o.push({...ju(m,b,g),tier:f}),R=s.indexOf(S,R+1)}}}}),o},Gu=(e,t,r=Sr)=>{let n=zu(e,t,r),o=[];if(n.length===0)return o;let a=_r.map(()=>new Int32Array(e.length+1));for(let{start:s,end:y,tier:m}of n)a[m][s]++,a[m][y]--;let i=new Int32Array(_r.length),l=0,c=Mn;for(let s=0;s<=e.length;s++){let y=Mn;for(let m=_r.length-1;m>=0;m--){let S=_r[m];i[S]+=a[S][s],i[S]>0&&(y=S)}y!==c&&(c!==Mn&&o.push(l,s,c),l=s,c=y)}return o},pi=(e,t)=>{if(e.combine==="intersection"||e.sets.length===1)return e.sets.flatMap(r=>r.words);if(t===null)throw new Error(`[daily-report] search marks: a union of ${e.sets.length} keywords needs the report's mask of matched keywords`);return e.sets.flatMap((r,n)=>(t&1<<n)===0?[]:r.words)},yi=(e,t)=>{let r=t.flatMap(a=>a.alternatives),n={},o=(a,i)=>{typeof i!="string"||i.length===0||(n[a]={fingerprint:Br(i),ranges:Gu(i,r)})};for(let a of Wn)o(Qe.field(a),e[a]);e.interviewers.forEach((a,i)=>{o(Qe.interviewer(i,"name"),a.name),o(Qe.interviewer(i,"affiliation"),a.affiliation)}),e.attachments.forEach((a,i)=>{o(Qe.attachment(i),a.fileName)}),e.externalComments.forEach((a,i)=>{o(Qe.comment(Hr(i),"author"),a.name),o(Qe.comment(Hr(i),"content"),a.text)});for(let a of e.postedComments)o(Qe.comment(a.id,"author"),a.userName),o(Qe.comment(a.id,"content"),a.content);return n};var rt=e=>Zu(e),fi=Kt([]),we=(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"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),c=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${c}:${s}`},ed=e=>{let{length:t}=e;if(t===void 0)throw se("tables.hub.title","a character column with a declared length",t);return ee("tables.hub.title.length",t,1)},Ri=e=>e===""?null:e,td=Object.freeze([]),Pn=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},wr=(e,t)=>e.get(t)??td,Si=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(Rr);function Ln(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:c}=e,{hub:s,internal:y,comment:m,label:S,hubLabel:f,userStatus:R}=r,b=e.externalSources??[],g=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],I=g[0]??"\u4E0B\u66F8\u304D",v=he(e.logger,1,"Service");ur(e);let $=na(e.attachments),w=ed(s.title),T=d=>Xu(u=>t.transaction(p=>u(()=>d(p))),e.transactionRetry),F=e.search===void 0?null:Za(e.search,b.map(d=>d.sourceType)),H={hub:s,hubLabel:f,label:S},k=F===null?null:ui({tables:{...H,search:F.tables},draftLabelNames:g}),le=null,de=()=>{if(F===null)return null;if(le===null){let d=F.externalSourceTexts;le=mi({hub:s,tables:F.tables,loadSources:(u,p)=>ts(u,p,d),inTransaction:T,normalizerVersion:wa()})}return le},fe=e.idsTtlMs??18e4,q="daily-report:ids:epoch",re=e.businessDateTtlMs??3e5,Z="daily-report:date-epoch:",ie="daily-report:detail-epoch:",ye=`${e.streamKey??"daily-report:sse-stream"}:v2`,Ke=e.streamMaxLen??1e4,te=d=>c.incrementEpoch(d),Pe=d=>qt(s.sourceType,d),Ue=(d,u)=>Tr(H,d,g,u),De=async(d,u)=>{let p=await i?.getClient();if(!p){v.warn(`[SSE] Redis client unavailable (${u})`);return}let h=JSON.stringify(d),D=Buffer.byteLength(h);if(D>6356992){v.warn(`[SSE] Event too large (${u}): ${D} bytes > ${6356992}; not published`);return}let _=ce();try{await p.xAdd(ye,"*",{data:h},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:Ke}});let x=ce()-_;x>1e3&&v.warn(`[SSE] Slow publish (${u}): ${x}ms`)}catch(x){v.error(`[SSE] Redis publish failed (${u}):`,x)}},O=async()=>{try{let d=await i?.getClient();if(d===void 0)return null;let[u]=await d.xRevRange(ye,"+","-",{COUNT:1});return u===void 0?null:u.id}catch(d){return v.error("SSE stream anchor read failed",d),null}},P=d=>d==null||d===""?null:/^\d+$/.test(d)?a(Number(d)):d,A=()=>{let d={};for(let u of b)d[`ext_${u.sourceType}`]=rt(u.table);return d},B=d=>{let u=d;for(let p of b)u=u.leftJoin(p.table,Ee(U(s.sourceType,p.sourceType),U(s.sourceIdNum,p.idColumn)));return u},W=d=>{let{hub:u,internal:p}=d,h=u.summary,D=[],_=null,x=null,N=null,M=null,V=null,E=null,J=[],ne=b.find(pe=>pe.sourceType===u.sourceType),Re=ne?d[`ext_${ne.sourceType}`]:void 0;if(ne&&Re){let pe=ne.mapRow(Re);pe.content!==void 0&&(h=pe.content),pe.employeeName!==void 0&&(E=pe.employeeName),pe.category!==void 0&&(_=pe.category),pe.creationCategory!==void 0&&(x=pe.creationCategory),pe.visitTimeFrom!==void 0&&(N=pe.visitTimeFrom),pe.visitTimeTo!==void 0&&(M=pe.visitTimeTo),pe.customerName!==void 0&&(V=pe.customerName),pe.interviewers!==void 0&&(D=pe.interviewers),pe.externalComments!==void 0&&(J=pe.externalComments)}else u.sourceType==="Internal"&&p&&(h=p.body);return{content:h,author:d.creatorName??P(u.createdBy)??"",employeeName:E??d.creatorName??P(u.createdBy),updatedBy:P(u.updatedBy),category:_,creationCategory:x,visitTimeFrom:N,visitTimeTo:M,customerName:V,interviewers:D,externalComments:J}},G=(d,u,p)=>{let{hub:h}=u,D=W(u),_=(u.labels??[]).map(E=>({id:E.id,name:E.name,color:E.color})),x=u.postedCommentRows??[],N=ke(d.commentable,h.sourceType),M=D.creationCategory?g.includes(D.creationCategory):!1,V=St?.[0]??null;return M&&V&&!_.some(E=>E.id===V)&&_.push({id:V,name:I,color:null}),{reportHubId:h.id,date:we(h.businessDate,"YYYY-MM-DD"),author:D.author,userId:h.userId?a(h.userId):"",sourceType:h.sourceType??"Internal",createdAt:we(h.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:we(h.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:D.updatedBy,employeeName:D.employeeName,category:D.category,creationCategory:D.creationCategory,visitTimeFrom:D.visitTimeFrom,visitTimeTo:D.visitTimeTo,customerName:D.customerName,interviewers:D.interviewers,subject:h.title,content:D.content,externalComments:N?D.externalComments:[],isRead:u.isRead??!1,isStarred:u.isStarred??!1,labels:_,postedComments:x.filter(E=>Ja({authorUserId:E.userId},h.sourceType,p??null,d)).map(E=>({...E,userId:a(E.userId),isMine:p?E.userId===p:!1})),attachments:u.attachments}},K=async(d,u)=>(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).where(Ee(Mt(s.deletedAt),Ue(u,"author-or-authorless"),Pe(d.visible))).orderBy(Ct(s.businessDate),Ct(s.id))).map(h=>({...h,businessDate:we(h.businessDate,"YYYY-MM-DD")})),j=async(d,u,p)=>{let h=await X(u);return h?He(d.visible)?[]:(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(p).from(s).where(Ee(Mt(s.deletedAt),Ue(h,"author-or-authorless"),Pe(d.visible))).orderBy(Ct(s.businessDate),Ct(s.id))).map(_=>({..._,businessDate:we(_.businessDate,"YYYY-MM-DD")})):[]},Q=async(d,u)=>{let p=await B(t.select({hub:rt(s),internal:rt(y),creatorName:n.displayName,...A()}).from(s)).leftJoin(y,U(s.id,y.hubId)).leftJoin(n,U(s.userId,n.id)).where(Ee(U(s.businessDate,hi`${u}`),Mt(s.deletedAt),Pe(d.visible))).orderBy(Ct(s.id)),h=await zt(p.map(D=>D.hub.id));return p.map(D=>G(d,{...D,attachments:h.get(D.hub.id)??[]}))},C=new Map,X=async d=>{if(!e.disableUserIdCache&&C.has(d))return C.get(d)??null;let u=await o(d);return u!==null&&!e.disableUserIdCache&&C.set(d,u),u},ge=async(d,u,{forceRefresh:p=!1,snapshot:h=!1,ttlMsOverride:D,onFetchStart:_,admission:x}={})=>{let N=await X(u);if(!N)return{items:[],streamAnchor:null,snapshot:fi};if(He(d.visible))return{items:[],streamAnchor:await O(),snapshot:fi};let M=La(N,Wt(d)),[V]=await l.getOrFetch({cacheKey:M,fetcher:async()=>{let E=await O(),J=await K(d,N);if(!Bn(J)){v.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let ne=[...J].sort(Jt);return[{items:ne,streamAnchor:E,snapshot:Kt(ne)}]}return[{items:J,streamAnchor:E,snapshot:Kt(J)}]},onFetchStart:_,forceRefresh:p,snapshot:h,admission:x,ttlMsOverride:D??fe,epochKey:q,refreshAheadRatio:.5});if(V===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return V},Rt=(d,u,{forceRefresh:p=!1,snapshot:h=!1,ttlMsOverride:D}={})=>{let _=Le(u);return _?He(d.visible)?Promise.resolve([]):l.getOrFetch({cacheKey:Oa(_,Wt(d)),fetcher:()=>Q(d,_),forceRefresh:p,snapshot:h,ttlMsOverride:D??re}):Promise.resolve([])},St=null,jt=async()=>(St!==null||(St=(await t.select({id:S.id}).from(S).where(Ye(S.name,g)).orderBy(S.id)).map(u=>u.id)),St),Cr=async()=>{let d=await jt();if(d.length===0)return null;let[u]=await t.select({id:S.id}).top(1).from(S).where(U(S.name,I));return u?.id??d[0]},$i=(d,u)=>u!=null?"absent":d!=null?"present":"unknown",zt=async d=>{let u=new Map,p=r.attachment;if(d.length===0||!p||$===null)return u;let h=$.idCodec,D=$.thumbnails!==null,_=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(Ye(p.hubId,d)).orderBy(Me(p.createdAt),Me(p.id));for(let x of _){let N=x.fileType?String(x.fileType):null,M=x.fileSize!=null?Number(x.fileSize):null,V=$i(x.objectCheckedAt,x.objectMissingAt),E={id:h.encode(Number(x.id)),fileName:String(x.fileName),fileType:N,fileSize:M,createdAt:we(x.createdAt,"YYYY-MM-DD HH:mm:ss"),state:V,hasThumbnail:D&&V!=="absent"&&lr({fileType:N,fileSize:M},$.maxBytes)},J=u.get(Number(x.hubId));J?J.push(E):u.set(Number(x.hubId),[E])}return u},Bi=async(d,u,p)=>{let h=r.attachment;return!h||He(d.visible)?null:(await t.select({fileName:h.fileName,filePath:h.filePath,fileType:h.fileType,fileSize:h.fileSize}).top(1).from(h).innerJoin(s,U(s.id,h.hubId)).where(Ee(U(h.id,u),Mt(s.deletedAt),Ue(p,"author"),Pe(d.visible))))[0]??null},Fi=async d=>{let u=r.attachment;if(!u)return;let p=new Date;try{await t.update(u).set({objectCheckedAt:p,objectMissingAt:p,updatedAt:p}).where(U(u.id,d))}catch(h){v.error("markAttachmentMissing failed",h)}},Vi=async d=>{let u=r.attachment;if(!u)return;let p=new Date;try{await t.update(u).set({objectCheckedAt:p,objectMissingAt:null,updatedAt:p}).where(U(u.id,d))}catch(h){v.error("markAttachmentPresent failed",h)}},Mr=async(d,u,p)=>{let h=await B(t.select({hub:rt(s),internal:rt(y),isRead:R.isRead,isStarred:R.isStarred,creatorName:n.displayName,...A()}).from(s)).leftJoin(y,U(s.id,y.hubId)).leftJoin(R,Ee(U(s.id,R.hubId),U(R.userId,u))).leftJoin(n,U(s.userId,n.id)).where(Ee(p,Mt(s.deletedAt),Ue(u,"author"),Pe(d.visible))).orderBy(Ct(s.id));if(h.length===0)return[];let D=h.map(E=>E.hub.id),_=await t.select({hubId:f.hubId,id:S.id,name:S.name,color:S.color}).from(f).innerJoin(S,U(f.labelId,S.id)).where(Ye(f.hubId,D)),x=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,U(m.userId,n.id)).where(Ye(m.hubId,D)).orderBy(Me(m.createdAt)),N=await zt(D),M=new Map,V=new Map;for(let E of _){let J=M.get(E.hubId);J||(J=[],M.set(E.hubId,J)),J.push({id:E.id,name:E.name,color:E.color})}for(let E of x){let J=V.get(E.hubId);J||(J=[],V.set(E.hubId,J)),J.push({id:E.id,content:E.body,createdAt:we(E.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:E.userId,userName:E.userName||""})}return h.map(E=>{let J=E.hub.id;return G(d,{...E,attachments:N.get(J)??[],labels:M.get(J)||[],postedCommentRows:V.get(J)||[]},u)})},Yi=async(d,u,p,{forceRefresh:h=!1,snapshot:D=!1,ttlMsOverride:_,admission:x}={})=>{let N=await X(p);if(!N)return[];let M=Le(u);if(!M)return[];if(He(d.visible))return[];let V=Na(M,N,Wt(d));return l.getOrFetch({cacheKey:V,fetcher:()=>Mr(d,N,U(s.businessDate,hi`${M}`)),forceRefresh:h,snapshot:D,admission:x,ttlMsOverride:_??re,epochKey:`${Z}${M}`})},Pt=async(d,u,p,{forceRefresh:h=!1,snapshot:D=!1,ttlMsOverride:_,admission:x}={})=>{if(He(d.visible))return null;let N=va(u,p,Wt(d));return(await l.getOrFetch({cacheKey:N,fetcher:async()=>{let V=await B(t.select({hub:rt(s),internal:rt(y),isRead:R.isRead,isStarred:R.isStarred,creatorName:n.displayName,...A()}).from(s)).leftJoin(y,U(s.id,y.hubId)).leftJoin(R,Ee(U(s.id,R.hubId),U(R.userId,p))).leftJoin(n,U(s.userId,n.id)).where(Ee(U(s.id,u),Mt(s.deletedAt),Ue(p,"author"),Pe(d.visible)));if(V.length===0)return[];let E=V[0].hub.id,J=await t.select({id:S.id,name:S.name,color:S.color}).from(f).innerJoin(S,U(f.labelId,S.id)).where(U(f.hubId,E)),ne=await t.select({id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,U(m.userId,n.id)).where(U(m.hubId,E)).orderBy(Me(m.createdAt)),Re=await zt([E]),pe=J.map(Je=>({id:Je.id,name:Je.name,color:Je.color})),ds=ne.map(Je=>({id:Je.id,content:Je.body,createdAt:we(Je.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Je.userId,userName:Je.userName||""}));return[G(d,{...V[0],attachments:Re.get(E)??[],labels:pe,postedCommentRows:ds},p)]},forceRefresh:h,snapshot:D,admission:x,ttlMsOverride:_??re,epochKey:`${ie}${u}`}))[0]??null},qi=async(d,u,p,h={})=>{let D=await X(p);return D?Pt(d,u,D,h):null},Wi=async(d,u,p)=>{if(u.length>_e.maxDetailIds)throw se("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${_e.maxDetailIds} ids`,u.length);let h=await X(p);return!h||u.length===0?[]:He(d.visible)?[]:Mr(d,h,Ye(s.id,[...u]))},ji=async(d,u)=>{let[p]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).where(Ee(U(s.id,d),Ue(u,"author")));return p??null},Pr=async(d,u,p)=>{let h=await ji(u,p);if(!h||h.deletedAt||!ke(d.visible,h.sourceType))throw new Error("Not Found")},zi=async(d,u,p,h,D,_)=>{await Pr(d,p,u);let x=await t.select().top(1).from(R).where(Ee(U(R.hubId,p),U(R.userId,u))),N;if(x.length>0?x[0].isStarred!==D?N=(await t.update(R).set({isStarred:D,updatedAt:new Date,updatedBy:String(u)}).output().where(Ee(U(R.hubId,p),U(R.userId,u))))[0]:N=x[0]:N=(await t.insert(R).output().values({hubId:p,userId:u,isStarred:D,isRead:!1,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}))[0],h){let M=Le(h);M&&(l.invalidatePrefix(Et(M,u)),await te(`${Z}${M}`))}return l.invalidatePrefix(Dr(p,u)),await te(`${ie}${p}`),await De(tr.parse({type:"status-update",reportHubId:p,recipientRawUserId:u,statusType:"star",value:D,clientTempId:_}),"setStarStatus"),N},Gi=async(d,u,p,h,D,_)=>{await Pr(d,p,u);let x=await t.select().top(1).from(R).where(Ee(U(R.hubId,p),U(R.userId,u))),N;if(x.length>0?x[0].isRead!==D?N=(await t.update(R).set({isRead:D,updatedAt:new Date,updatedBy:String(u)}).output().where(Ee(U(R.hubId,p),U(R.userId,u))))[0]:N=x[0]:N=(await t.insert(R).output().values({hubId:p,userId:u,isRead:D,isStarred:!1,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}))[0],h){let M=Le(h);M&&(l.invalidatePrefix(Et(M,u)),await te(`${Z}${M}`))}return l.invalidatePrefix(Dr(p,u)),await te(`${ie}${p}`),await De(tr.parse({type:"status-update",reportHubId:p,recipientRawUserId:u,statusType:"read",value:D,clientTempId:_}),"setReadStatus"),N},Nn=async(d,u)=>{if(u===null)return;let p=await jt();if(p.length===0)return;let[h]=await t.select({hubId:f.hubId}).top(1).from(f).where(Ee(U(f.hubId,d),Ye(f.labelId,p)));return h?u:void 0},Ki=async(d,u,p,h,D,_)=>{let[x]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where(U(s.id,p));if(!x||x.deletedAt)throw new Error("Not Found");if(await Pr(d,p,u),!ke(d.commentable,x.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(x.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let N=await Nn(p,x.userId),M=de(),V=await T(async Re=>{let[pe]=await Re.insert(m).output().values({hubId:p,userId:u,body:h,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)});return M!==null&&await M.writeHubs(Re,[p]),pe}),[E]=await t.select({displayName:n.displayName}).top(1).from(n).where(U(n.id,u)),J=E?.displayName??"";if(D){let Re=Le(D);Re&&(l.invalidatePrefix(Ft(Re)),await te(`${Z}${Re}`))}l.invalidatePrefix(Ge(p)),await te(`${ie}${p}`);let ne={id:V.id,userId:a(V.userId),userName:J,content:V.body,createdAt:we(V.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await De(Wr.parse({type:"comment-add",reportHubId:p,comment:ne,clientTempId:_,recipientRawUserId:N,sourceType:x.sourceType}),"addComment"),ne},Ji=async(d,u)=>await d.select().top(1).from(m).where(U(m.id,u)),Qi=async(d,u,p,h,D,_)=>{let x=await Ji(t,h);if(x.length===0)throw new Error("Not Found");if(x[0].hubId!==p)throw new Error("Not Found");let[N]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where(U(s.id,x[0].hubId));if(!(N&&ke(d.visible,N.sourceType)))throw new Error("Not Found");if(x[0].userId!==u)throw new Error("Unauthorized");let M=await Nn(p,N.userId),V=de();if(await T(async E=>{await E.delete(m).where(U(m.id,h)),V!==null&&await V.writeHubs(E,[p])}),D){let E=Le(D);E&&(l.invalidatePrefix(Ft(E)),await te(`${Z}${E}`))}l.invalidatePrefix(Ge(p)),await te(`${ie}${p}`),await De(jr.parse({type:"comment-delete",reportHubId:p,commentId:h,clientTempId:_,recipientRawUserId:M,sourceType:N?.sourceType}),"deleteComment")},Xi=async(d,u)=>{let p=new Map,h=r.attachment;if(!h||$===null)return p;let D=await d.select({hubId:h.hubId,fileName:h.fileName}).from(h).where(Ye(h.hubId,[...u])).orderBy(Me(h.hubId),Me(h.createdAt),Me(h.id));for(let _ of D)Pn(p,Number(_.hubId),String(_.fileName));return p},Zi=async(d,u,p)=>{let h=new Map;for(let[D,_]of p){let x=new Map;for(let{hub:M}of u)M.sourceType===D&&M.sourceIdNum!==null&&x.set(M.sourceIdNum,M.id);if(x.size===0)continue;let N=await _(d,[...x.keys()]);for(let[M,V]of N){let E=x.get(M);if(E===void 0)throw se(`search.externalSourceTexts.${D} answer key`,"a source id that was asked for",M);if(!(Array.isArray(V)&&V.every(J=>typeof J=="string")))throw se(`search.externalSourceTexts.${D} answer for ${M}`,"an array of strings",V);h.set(E,V)}}return h},es=(d,u)=>{let p=W(d),h=[["subject",d.hub.title],["content",p.content],["author",p.author],["employeeName",p.employeeName],["updatedBy",p.updatedBy],["category",p.category],["creationCategory",p.creationCategory],["customerName",p.customerName]];for(let _ of p.interviewers)h.push(["interviewerName",_.name??null],["interviewerAffiliation",_.affiliation??null]);for(let _ of u.labelNames)h.push(["label",_]);for(let _ of u.attachmentNames)h.push(["attachment",_]);for(let _ of u.extraTexts)h.push(["extra",_]);let D=[];for(let _ of p.externalComments)D.push({authorUserId:null,text:Si(_.name,_.text)});for(let _ of u.postedComments)D.push({authorUserId:_.userId,text:Si(_.userName,_.body)});return{hubId:d.hub.id,fields:h,comments:D}},ts=async(d,u,p)=>{let h=[];for(let D of Ju(u,Qu)){let _=await B(d.select({hub:rt(s),internal:rt(y),creatorName:n.displayName,...A()}).from(s)).leftJoin(y,U(s.id,y.hubId)).leftJoin(n,U(s.userId,n.id)).where(Ye(s.id,[...D])).orderBy(Me(s.id)),x=new Map,N=await d.select({hubId:f.hubId,name:S.name}).from(f).innerJoin(S,U(f.labelId,S.id)).where(Ye(f.hubId,[...D])).orderBy(Me(f.hubId),Me(S.id));for(let ne of N)Pn(x,ne.hubId,ne.name);let M=new Map,V=await d.select({hubId:m.hubId,userId:m.userId,body:m.body,userName:n.displayName}).from(m).leftJoin(n,U(m.userId,n.id)).where(Ye(m.hubId,[...D])).orderBy(Me(m.hubId),Me(m.createdAt),Me(m.id));for(let ne of V)Pn(M,ne.hubId,ne);let E=await Xi(d,D),J=await Zi(d,_,p);for(let ne of _){let Re=ne.hub.id;h.push(es(ne,{labelNames:wr(x,Re),postedComments:wr(M,Re),attachmentNames:wr(E,Re),extraTexts:wr(J,Re)}))}}return h},rs=(d,u,p)=>k===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):k.search(t,{plan:p,viewerUserId:u,scope:d}),ns=async(d,u,p,h,D)=>{if(k===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(h.length>_e.maxDetailIds)throw se("markDailyReportSearchHits: reportHubIds",`at most ${_e.maxDetailIds} ids`,h.length);let{signal:_}=D,x=Xt($t(p));if(h.length===0||He(d.visible))return{wordsDigest:x,reports:[]};_.throwIfAborted();let N=await Mr(d,u,Ye(s.id,[...h]));_.throwIfAborted();let M=p.combine==="union"&&p.sets.length>=2&&N.length>0?await k.matchedSets(t,{plan:p,viewerUserId:u,scope:d,ids:N.map(E=>E.reportHubId)}):null,V=[];for(let E of N){V.length>0&&await new Promise(Re=>setImmediate(Re)),_.throwIfAborted();let J=M===null?null:M.get(E.reportHubId),ne=J===void 0?0:J;V.push({reportHubId:E.reportHubId,matchedSets:ne,fields:yi(E,pi(p,ne))})}return{wordsDigest:x,reports:V}},os=d=>{let u=de();return u===null?Promise.reject(new Error("[daily-report] reconcileSearchIndex: the search setting is not configured")):u.reconcile(t,d)},as=async(d,u,p)=>{if(!Qt(u))throw se("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",u);v.info("createDailyReport called",{userId:d,businessDate:u});let[h]=await t.select({displayName:n.displayName}).from(n).where(U(n.id,d)),D=h?.displayName??a(d),_=de();try{let x=await T(async M=>{v.info("Starting transaction");let V=`internal-temp-${Date.now()}-${Math.random()}`,[E]=await M.insert(s).output().values({sourceType:"Internal",sourceId:V,businessDate:new Date(`${u}T00:00:00Z`),userId:d,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)});await M.update(s).set({sourceId:String(E.id)}).where(U(s.id,E.id)),v.info("Hub created",E),await M.insert(y).values({hubId:E.id,body:"",createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)}),v.info("Internal created"),v.info("Calling getDraftLabelId");let J=await Cr();v.info("draftLabelId",J);let ne=[];return J&&(await M.insert(f).values({hubId:E.id,labelId:J,createdAt:new Date,createdBy:String(d)}),ne.push({id:J,name:I,color:null})),v.info("Label assigned"),_!==null&&await _.writeHubs(M,[E.id]),{reportHubId:E.id,date:u,createdAt:we(E.createdAt,"YYYY-MM-DD HH:mm:ss"),author:D,userId:a(d),sourceType:"Internal",employeeName:D,updatedBy:a(d),updatedAt:we(E.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:E.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:ne,postedComments:[],attachments:[]}});l.invalidatePrefix(Et(u,d)),l.invalidatePrefix(mt),l.invalidatePrefix(An(d)),await te(q),await te(`${Z}${u}`);let N=await Pt(ve.unrestricted("post-write self read: the writer always sees the row they just wrote"),x.reportHubId,d,{forceRefresh:!0});if(N){let M=await jt(),V=N.labels.some(E=>M.includes(E.id));await De(zr.parse({type:"report-create",reportHubId:N.reportHubId,report:N,clientTempId:p,recipientRawUserId:V?d:void 0}),"createDailyReport")}return N??x}catch(x){throw v.error("Error in createDailyReport",x),x}},Gt=async(d,u)=>await d.select().top(1).from(s).where(U(s.id,u)),Lr=async(d,u,p)=>{await d.update(s).set(p).where(U(s.id,u))},vn=async(d,u,p)=>{await d.update(y).set(p).where(U(y.hubId,u))},kn=async(d,u,p)=>{await d.delete(f).where(Ee(U(f.hubId,u),U(f.labelId,p)))},is=async(d,u,p)=>{let h=await Gt(t,d);if(!h.length||h[0].deletedAt)throw new Error("Not Found");if(h[0].userId!==u)throw new Error("Unauthorized");let D=de();if(await T(async _=>{await Lr(_,d,{deletedAt:new Date,deletedBy:String(u),updatedAt:new Date,updatedBy:String(u)}),D!==null&&await D.writeHubs(_,[d])}),l.invalidatePrefix(Ge(d)),l.invalidatePrefix(mt),l.invalidatePrefix(dt),await te(q),h[0].businessDate){let _=Le(we(h[0].businessDate,"YYYY-MM-DD"));_&&await te(`${Z}${_}`)}await De(Jr.parse({type:"report-delete",reportHubId:d,clientTempId:p,sourceType:h[0].sourceType}),"deleteDailyReport")},ss=async(d,u,p,h)=>{let D=await Gt(t,d);if(!D.length||D[0].deletedAt)throw new Error("Not Found");if(D[0].userId!==u)throw new Error("Unauthorized");let _=de();await T(async M=>{p.title!==void 0&&await Lr(M,d,{title:Ri(p.title),updatedAt:new Date,updatedBy:String(u)}),p.content!==void 0&&await vn(M,d,{body:Ri(p.content),updatedAt:new Date,updatedBy:String(u)}),_!==null&&await _.writeHubs(M,[d])}),l.invalidatePrefix(Ge(d)),l.invalidatePrefix(mt),await te(`${ie}${d}`);let x=Le(we(D[0].businessDate,"YYYY-MM-DD"));x&&(l.invalidatePrefix(Ft(x)),await te(`${Z}${x}`));let N=await Pt(ve.unrestricted("post-write self read: the writer always sees the row they just wrote"),d,u,{forceRefresh:!0});if(N){let M=await jt(),V=N.labels.some(E=>M.includes(E.id));await De(Gr.parse({type:"report-update",reportHubId:N.reportHubId,report:N,clientTempId:h,recipientRawUserId:V?u:void 0}),"updateDailyReport")}},ls=async(d,u,p)=>{let h=await Gt(t,d);if(!h.length)throw new Error("Not Found");if(h[0].userId!==u)throw new Error("Unauthorized");let D=await Cr();if(!D)return null;let _=de();if(await T(async M=>{await kn(M,d,D),_!==null&&await _.writeHubs(M,[d])}),l.invalidatePrefix(Ge(d)),l.invalidatePrefix(mt),l.invalidatePrefix(dt),await te(q),h[0].businessDate){let M=Le(we(h[0].businessDate,"YYYY-MM-DD"));M&&await te(`${Z}${M}`)}let x=Le(we(h[0].businessDate,"YYYY-MM-DD"));x&&l.invalidatePrefix(Et(x,u));let N=await Pt(ve.unrestricted("post-write self read: the writer always sees the row they just wrote"),d,u,{forceRefresh:!0});return N&&await De(Kr.parse({type:"report-publish",reportHubId:N.reportHubId,report:N,clientTempId:p}),"publishDailyReport"),N??null},cs=async(d,u)=>{l.invalidatePrefix(mt),l.invalidatePrefix(dt),await te(q);for(let p of new Set(d))l.invalidatePrefix(Ge(p)),await te(`${ie}${p}`);for(let p of new Set(u)){let h=Le(p);h&&await te(`${Z}${h}`)}},us=async()=>{l.clearAll(),C.clear(),St=null,c&&await te(q),v.info("Server-side DB/SQL caches cleared successfully.")};return{streamKey:ye,streamMaxLen:Ke,attachmentDelivery:$,titleMaxLength:w,searchLimits:F===null?null:{concurrency:F.concurrency,rateLimitPerMinute:F.rateLimitPerMinute},clearCache:us,invalidateHubReadCaches:cs,getUserIdByExternalId:X,getDailyReportIdsByExternalId:ge,getDailyReportIdsFirstPageByExternalId:j,readSseStreamAnchor:O,getDailyReportsByBusinessDate:Rt,getDailyReportsByBusinessDateByExternalId:Yi,getDailyReportDetailById:Pt,getDailyReportDetailByIdByExternalId:qi,getDailyReportDetailsByIdsByExternalId:Wi,getDraftLabelId:Cr,searchDailyReports:rs,markDailyReportSearchHits:ns,reconcileSearchIndex:os,getAttachmentsByHubIds:zt,getAttachmentForUser:Bi,markAttachmentMissing:Fi,markAttachmentPresent:Vi,setStarStatus:zi,setReadStatus:Gi,addComment:Ki,deleteComment:Qi,createDailyReport:as,updateDailyReport:ss,publishDailyReport:ls,deleteDailyReport:is,findDailyReportHubById:Gt,updateDailyReportHub:Lr,updateDailyReportInternal:vn,deleteDailyReportLabel:kn}}var rd=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(he(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return he(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};import{desc as gi,sql as nd}from"drizzle-orm";import{bigint as be,bit as bi,date as od,datetime2 as Ie,foreignKey as qe,index as st,int as ad,mssqlSchema as id,nvarchar as ae,primaryKey as ft,uniqueIndex as sd}from"drizzle-orm/mssql-core";function ld(e,t){let r=id(e),n=t.userTable,o=r.table("DailyReportHub",{id:be("id",{mode:"number"}).identity().notNull(),sourceType:ae("source_type",{length:20}).notNull(),sourceId:ae("source_id",{length:100}).notNull(),sourceIdNum:be("source_id_num",{mode:"number"}).generatedAlwaysAs(nd`TRY_CAST(source_id AS BIGINT)`),businessDate:od("business_date"),userId:be("user_id",{mode:"number"}),title:ae("title",{length:200}),summary:ae("summary",{length:"max"}),createdAt:Ie("created_at").notNull(),createdBy:ae("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:ae("updated_by",{length:50}).notNull(),deletedAt:Ie("deleted_at"),deletedBy:ae("deleted_by",{length:50})},m=>[ft({name:`${e}_DailyReportHub_pk`,columns:[m.id]}),qe({name:`${e}_DailyReportHub_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),st(`${e}_DailyReportHub_business_date_index`).on(m.businessDate),st(`${e}_DailyReportHub_updated_at_index`).on(m.updatedAt),st(`${e}_DailyReportHub_source_index`).on(m.sourceType,m.sourceId),st(`${e}_DailyReportHub_user_id_index`).on(m.userId),st(`${e}_DailyReportHub_business_date_id_index`).on(gi(m.businessDate),gi(m.id)),st(`${e}_DailyReportHub_deleted_at_index`).on(m.deletedAt)]),a=r.table("DailyReportInternal",{hubId:be("hub_id",{mode:"number"}).notNull(),body:ae("body",{length:"max"}),metadata:ae("metadata",{length:"max"}),createdAt:Ie("created_at").notNull(),createdBy:ae("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:ae("updated_by",{length:50}).notNull()},m=>[ft({name:`${e}_DailyReportInternal_pk`,columns:[m.hubId]}),qe({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:be("id",{mode:"number"}).identity().notNull(),hubId:be("hub_id",{mode:"number"}).notNull(),userId:be("user_id",{mode:"number"}).notNull(),body:ae("body",{length:"max"}).notNull(),createdAt:Ie("created_at").notNull(),createdBy:ae("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:ae("updated_by",{length:50}).notNull()},m=>[ft({name:`${e}_DailyReportComment_pk`,columns:[m.id]}),qe({name:`${e}_DailyReportComment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),qe({name:`${e}_DailyReportComment_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),st(`${e}_DailyReportComment_hub_id_index`).on(m.hubId)]),l=r.table("DailyReportLabel",{id:be("id",{mode:"number"}).identity().notNull(),userId:be("user_id",{mode:"number"}),name:ae("name",{length:50}).notNull(),color:ae("color",{length:20}),sortOrder:ad("sort_order"),createdAt:Ie("created_at").notNull(),createdBy:ae("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:ae("updated_by",{length:50}).notNull()},m=>[ft({name:`${e}_DailyReportLabel_pk`,columns:[m.id]}),qe({name:`${e}_DailyReportLabel_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),c=r.table("DailyReportHub_Label",{hubId:be("hub_id",{mode:"number"}).notNull(),labelId:be("label_id",{mode:"number"}).notNull(),createdAt:Ie("created_at").notNull(),createdBy:ae("created_by",{length:50}).notNull()},m=>[ft({name:`${e}_DailyReportHub_Label_pk`,columns:[m.hubId,m.labelId]}),qe({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),qe({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[m.labelId],foreignColumns:[l.id]})]),s=r.table("DailyReportUserStatus",{hubId:be("hub_id",{mode:"number"}).notNull(),userId:be("user_id",{mode:"number"}).notNull(),isRead:bi("is_read").default(!1).notNull(),isStarred:bi("is_starred").default(!1).notNull(),createdAt:Ie("created_at").notNull(),createdBy:ae("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:ae("updated_by",{length:50}).notNull()},m=>[ft({name:`${e}_DailyReportUserStatus_pk`,columns:[m.hubId,m.userId]}),qe({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),qe({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),y=r.table("DailyReportAttachment",{id:be("id",{mode:"number"}).identity().notNull(),hubId:be("hub_id",{mode:"number"}).notNull(),uploadedBy:be("uploaded_by",{mode:"number"}),sourceKey:ae("source_key",{length:200}).notNull(),fileName:ae("file_name",{length:255}).notNull(),filePath:ae("file_path",{length:"max"}).notNull(),fileType:ae("file_type",{length:100}),fileSize:be("file_size",{mode:"number"}),objectCheckedAt:Ie("object_checked_at"),objectMissingAt:Ie("object_missing_at"),createdAt:Ie("created_at").notNull(),createdBy:ae("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:ae("updated_by",{length:50}).notNull()},m=>[ft({name:`${e}_DailyReportAttachment_pk`,columns:[m.id]}),qe({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),qe({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[m.uploadedBy],foreignColumns:[n.id]}),sd(`${e}_DailyReportAttachment_source_unique`).on(m.hubId,m.sourceKey),st(`${e}_DailyReportAttachment_hub_id_index`).on(m.hubId,m.createdAt)]);return{hub:o,internal:a,comment:i,attachment:y,label:l,hubLabel:c,userStatus:s}}import{bigint as On,binary as Di,datetime2 as cd,int as ud,mssqlSchema as dd,nvarchar as Ai,primaryKey as Ti,varchar as md}from"drizzle-orm/mssql-core";function pd(e){let t=dd(e),r=t.table("DailyReportSearchDocument",{hubId:On("hub_id",{mode:"number"}).notNull(),searchText:Ai("search_text",{length:"max"}).notNull(),sourceDigest:Di("source_digest",{length:32}).notNull(),normalizerVersion:md("normalizer_version",{length:64}).notNull(),indexedAt:cd("indexed_at").notNull(),rowVersion:Di("row_version",{length:8}).notNull()},o=>[Ti({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:On("hub_id",{mode:"number"}).notNull(),ordinal:ud("ordinal").notNull(),authorUserId:On("author_user_id",{mode:"number"}),commentText:Ai("comment_text",{length:"max"}).notNull()},o=>[Ti({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var yd=5e7,Ni=2e8,hd=1,vi=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})})}),Ei=125,Ii=4,_i=16,wi=50,xi=2,xr=Object.freeze({renderMs:Ce.renderMs,nanosecondsPerBlockVisit:Ei,margin:Ii,maxBlockVisits:Math.floor(Ce.renderMs*1e6/(Ei*Ii)),walkBudgetMs:_i,nanosecondsPerWalkStep:wi,walkMargin:xi,maxWalkSteps:Math.floor(_i*1e6/(wi*xi))}),fd=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Ci=75,Mi=4,Pi="#ffffff",Rd=1,Sd={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},gd=[/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/],Li=Object.freeze({ok:!1,reason:"failed"}),Oi=Object.freeze({ok:!1,reason:"unsupported"}),ki=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:Uo(e)}),Hi=(e,t)=>{switch(t){case"jpeg":{let r=dn(e);return r===null?null:ki(r)}case"png":{let r=Fo(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Vo(e,xr.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},Ui=(e,t)=>{let r=fd.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=vi,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},bd=(e,t,r)=>{let n=Hi(e,t);return n===null?null:Ui(n,r)},Dd=e=>e!==null&&e<=Ni,Ad=(e,t)=>{if(t!=="jpeg")return Hi(e,t);let r=$o(e,xr);return r===null||r.blockVisits>xr.maxBlockVisits?null:ki(r.header)},Td=e=>{let t=e instanceof Error?e.message:"";return gd.some(r=>r.test(t))?"failed":"unsupported"},Ed=e=>{e.cache(!1),e.concurrency(hd),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Sd)});let t=async(n,o,a,i,l)=>{let c=Ad(n,o);if(c===null)return Oi;try{let s=e(n,{limitInputPixels:yd,animated:!1});if(!Dd(Ui(c,await s.metadata())))return Oi;if(l.aborted)return Li;let y=await s.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:Pi}).webp({quality:Ci,effort:Mi}).toBuffer();return{ok:!0,bytes:new Uint8Array(y),contentType:"image/webp"}}catch(s){return{ok:!1,reason:Td(s)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?Li:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Ci}-e${Mi}/flatten-${Pi}/v${Rd}`,render:r}};var Id=4096,_d=6e4;function wf(e){e.redis||he(e.logger,2,"Server").warn("redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=kr(e.redis),r=new Nt({defaultTtlMs:ee("cacheDefaultTtlMs",e.cacheDefaultTtlMs??_d,1),maxBuckets:ee("cacheMaxBuckets",e.cacheMaxBuckets??Id,1)},t),n=Ln({...e,cache:r,epochs:t}),o=new Vt({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=_n({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(i=>i.sourceType)])],...a}}export{pn as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,mn as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,Ni as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,xr as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,vi as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,Tn as DAILY_REPORT_SSE_CATCH_UP_BATCH,Va as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,Vt as DailyReportSseReader,ve as DailyReportViewerScope,Nt as SqlResultCache,_n as createDailyReportHandlers,wf as createDailyReportServer,Ln as createDailyReportService,kr as createEpochStore,Ed as createSharpThumbnailRenderer,ld as defineDailyReportSchema,pd as defineDailyReportSearchSchema,it as isStreamIdLte,Qr as parseClientTempId,bd as predictSharpThumbnailWorkingSetBytes,Bt as readDailyReportSseStreamEntry,rd as transformJsonArray};
|
|
12
12
|
/* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */
|