@aiquants/daily-report 0.43.0 → 0.44.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 +167 -0
- package/README.md +211 -86
- package/dist/client.d.mts +11 -25
- package/dist/client.d.ts +11 -25
- package/dist/client.js +5 -5
- package/dist/client.mjs +5 -5
- package/dist/index.d.mts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/instrumentation-CobsTeyw.d.mts +70 -0
- package/dist/instrumentation-Dz7Uh7dT.d.ts +70 -0
- package/dist/{search-marks-wire-BSS2d1t6.d.ts → search-marks-wire-BiImBos8.d.mts} +16 -1
- package/dist/{search-marks-wire-BSS2d1t6.d.mts → search-marks-wire-C_vjmxwf.d.ts} +16 -1
- package/dist/server.d.mts +9 -5
- package/dist/server.d.ts +9 -5
- package/dist/server.js +10 -10
- package/dist/server.mjs +10 -10
- package/dist/{source-types-Bu-_yfcY.d.ts → source-types-Cg7T2dm6.d.ts} +1 -1
- package/dist/{source-types-NkQm-gNO.d.mts → source-types-Hy_znWJl.d.mts} +1 -1
- package/dist/{sse-schema-Br0b278w.d.mts → sse-schema-BcjRPJjN.d.ts} +2 -75
- package/dist/{sse-schema-Br0b278w.d.ts → sse-schema-sKBorzg9.d.mts} +2 -75
- package/dist/styles/daily-report.standalone.css +1 -1
- package/dist/testing.d.mts +39 -0
- package/dist/testing.d.ts +39 -0
- package/dist/testing.js +1 -0
- package/dist/testing.mjs +1 -0
- package/dist/types-BP1kIGMo.d.mts +75 -0
- package/dist/types-BP1kIGMo.d.ts +75 -0
- package/package.json +8 -3
package/dist/server.mjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
var ko=e=>{throw TypeError(e)};var No=(e,t,r)=>t.has(e)||ko("Cannot "+r);var Wt=(e,t,r)=>(No(e,t,"read from private field"),r?r.call(e):t.get(e)),dn=(e,t,r)=>t.has(e)?ko("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),pn=(e,t,r,n)=>(No(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var Dt=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,K=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Dt(r)}`),Ge=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),mn=(e,t,r)=>K(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),ae=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw K(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},_e=(e,t,r,n)=>t===void 0?n:ae(e,t,r),zt=(e,t)=>{if(t===void 0)throw Ge(e,"a function");if(typeof t!="function")throw K(e,"a function",t);return t};var ie=()=>Math.floor(performance.now());var yn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),Ue=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},hn=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{}}}),Gt=(e,t)=>t?e.map(r=>structuredClone(r)):e,ic=8,sc=32,lc=24,cc=16,uc=-(2**30),dc=2**30-1,pc=e=>Number.isInteger(e)&&e>=uc&&e<=dc&&!Object.is(e,-0),mc=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=sc,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=ic*a.length;for(let i of a)typeof i=="string"?r+=lc+2*i.length:typeof i=="number"&&!pc(i)?r+=cc:typeof i=="object"&&i!==null&&n.push(i)}return r},Kt=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.totalBytes=0;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-ie())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let s=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:c,expireAt:ie()+a,epoch:s}),c})(),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,s=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&s===null)throw new Ue(o.signal.aborted?"aborted":"busy");try{for(let d of r)d();let c=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:c,expireAt:ie()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),c}finally{s?.()}})(),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 Ue("aborted");return this.dropBucket(r),Gt(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>ie())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),Gt(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),Gt(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return Gt(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new Ue("aborted");return Gt(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 Ue&&(o===void 0||n.reason==="aborted"&&!o.signal.aborted)))throw n;return this.getOrFetch({...r,snapshot:!1})}};this.clearAll=()=>{this.buckets.clear(),this.totalBytes=0,this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.dropBucket(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)};this.defaultTtlMs=_e("cacheDefaultTtlMs",t.defaultTtlMs,1,yn.defaultTtlMs),this.maxBuckets=_e("cacheMaxBuckets",t.maxBuckets,1,yn.maxBuckets),this.maxBytes=_e("cacheMaxBytes",t.maxBytes,1,yn.maxBytes),this.lastSweepAt=ie()}dropBucket(t){let r=this.buckets.get(t);r!==void 0&&(this.buckets.delete(t),this.totalBytes-=r.bytes)}writeBucket(t,r){this.dropBucket(t);let n=mc(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=ie();o-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(o);for(let a of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets&&this.totalBytes<=this.maxBytes)break;this.dropBucket(a)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.dropBucket(r)}};import{crossOriginRefusal as Up}from"@aiquants/request-isolation";var yc=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var vo=e=>e<10?`0${e}`:`${e}`,hc=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=vo(e.getMonth()+1),n=vo(e.getDate());return`${t}-${r}-${n}`},Lt=e=>{let t=yc.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 s=new Date(0);return s.setUTCFullYear(a,i-1,l),s.getUTCFullYear()!==a||s.getUTCMonth()!==i-1||s.getUTCDate()!==l?null:`${r}-${n}-${o}`},gr=e=>Lt(e)===e;var Pe=e=>e==null?null:e instanceof Date?hc(e):Lt(e);import{z as fc}from"zod/v3";var Ke=e=>Number.isSafeInteger(e)&&e>0,$e=fc.number().int().positive().max(Number.MAX_SAFE_INTEGER);import{z as re}from"zod/v3";var br=/^(?:[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})$/;var At=Symbol("daily-report wire mismatch"),Je=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),At),Uo=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,Tt=(e,t)=>({code:"invalid_type",expected:e,received:Uo(t)}),Rc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Sc=e=>{let t=0;for(let r in e)t+=1;return t},Oo=(e,t,r)=>{let n={};for(let o=0;o<r;o+=1){let a=t[o];a in e&&(n[a]=e[a])}return n},kt=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!Rc(n))return Je(o,null,Tt("object",n));let a=null,i=!1,l=0;for(let s=0;s<t.length;s+=1){let c=t[s],d=n[c];d!==void 0&&(l+=1);let u=r[s](d,o,c);if(u===At){i=!0;continue}a===null&&u!==d&&(a=Oo(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?At:a!==null?a:Sc(n)===l?n:Oo(n,t,t.length)}},Jt=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},Qt=e=>(t,r,n)=>{if(!Array.isArray(t))return Je(r,n,Tt("array",t));r.path.push(n);let o=t,a=!1;for(let i=0;i<t.length;i+=1){let l=t[i],s=e(l,r,i);s===At?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?At:o},ce=(e,t,r)=>e==null||typeof e=="string"?e:Je(t,r,Tt("string",e)),Fo=(e,t,r)=>e===null||typeof e=="string"?e:Je(t,r,Tt("string",e)),Ho=(e,t,r)=>typeof e=="string"?e:Je(t,r,Tt("string",e)),gc=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:Je(t,r,Tt("number",e)),Xt=(e,t,r)=>typeof e=="boolean"?e:Je(t,r,Tt("boolean",e)),fn=(e,t,r)=>{if(typeof e=="number"&&Ke(e))return e;for(let{message:n,path:o,...a}of $e.safeParse(e).error.issues)Je(t,r,a);return At},$o={present:!0,absent:!0,unknown:!0},Bo=Object.keys($o),bc=Bo.map(e=>`'${e}'`).join(" | "),Dc=(e,t,r)=>typeof e!="string"?Je(t,r,{code:"invalid_type",expected:bc,received:Uo(e)}):Object.hasOwn($o,e)?e:Je(t,r,{code:"invalid_enum_value",received:e,options:[...Bo]}),Vo=kt({name:ce,affiliation:ce}),qo=kt({name:ce,text:ce,color:ce}),Yo=kt({id:fn,name:ce,color:ce}),jo=kt({id:fn,userId:ce,userName:ce,content:ce,createdAt:ce,isMine:Xt}),Ac=kt({id:Ho,fileName:Ho,fileType:Fo,fileSize:gc,createdAt:Fo,state:Dc,hasThumbnail:Xt}),Tc=kt({reportHubId:fn,date:ce,createdAt:ce,author:ce,userId:ce,sourceType:ce,employeeName:ce,updatedBy:ce,updatedAt:ce,category:ce,creationCategory:ce,visitTimeFrom:ce,visitTimeTo:ce,customerName:ce,interviewers:Qt(Jt(Vo)),subject:ce,content:ce,externalComments:Qt(Jt(qo)),isRead:Xt,isStarred:Xt,isDraft:Xt,labels:Qt(Jt(Yo)),postedComments:Qt(Jt(jo)),attachments:Qt(Jt(Ac))}),Zt=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===At?{ok:!1,issues:r.issues}:{ok:!0,value:n}},Wo=e=>Zt(Tc,e),zo=e=>Zt(Vo,e),Go=e=>Zt(qo,e),Ko=e=>Zt(Yo,e),Jo=e=>Zt(jo,e);var Qo=15e3,Xo="lastEventId",Ec=/^\d{1,15}-\d{1,15}$/,Zo=e=>Ec.test(e),er=e=>re.unknown().transform((t,r)=>{let n=e(t);if(n.ok)return n.value;for(let o of n.issues)r.addIssue({...o,fatal:!0});return re.NEVER}),By=er(zo),Vy=er(Go),qy=er(Ko),wc=er(Jo),Ic=er(Wo),tr=re.string().regex(br),ea=re.object({type:re.literal("connected")}),ta=re.object({type:re.literal("status-update"),reportHubId:$e,statusType:re.enum(["star","read"]),value:re.boolean(),clientTempId:tr}),Rn=re.string(),ra=re.object({type:re.literal("comment-add"),reportHubId:$e,comment:wc,clientTempId:tr,sourceType:Rn}),na=re.object({type:re.literal("comment-delete"),reportHubId:$e,commentId:$e,clientTempId:tr,sourceType:Rn}),Dr={recipientRawUserId:$e.optional()},Sn=ta.extend(Dr),gn=ra.extend(Dr),bn=na.extend(Dr),Nt={reportHubId:$e,report:Ic,clientTempId:tr},Dn={...Dr,actorRawUserId:$e},An={viewerIsActor:re.boolean()},_c=re.object({type:re.literal("report-create"),...Nt,...An}),xc=re.object({type:re.literal("report-update"),...Nt,...An}),Cc=re.object({type:re.literal("report-publish"),...Nt,...An}),Tn=re.object({type:re.literal("report-create"),...Nt,...Dn}),En=re.object({type:re.literal("report-update"),...Nt,...Dn}),wn=re.object({type:re.literal("report-publish"),...Nt,...Dn}),Ar=re.object({type:re.literal("report-delete"),reportHubId:$e,clientTempId:tr,sourceType:Rn}),Yy=re.discriminatedUnion("type",[ea,ta,ra,na,_c,xc,Cc,Ar]),In=re.discriminatedUnion("type",[ea,Sn,gn,bn,Tn,En,wn,Ar]);var oa="ids-columns";var Mc=/^[0-9a-f]{1,16}$/,aa=e=>Ke(e.reportHubId)&&(e.businessDate===null||gr(e.businessDate)),ia=e=>typeof e=="string"&&Mc.test(e),Gy=Object.freeze({kind:"absent"}),Ky=Object.freeze({kind:"value",value:null});var vt=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],s=new Map;for(let c=t;c<r;c++){let{reportHubId:d,businessDate:u,sourceType:R}=e[c];n.push(d),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let p=R===void 0?null:R,m=s.get(p);m===void 0&&(m=i.length,i.push(p),s.set(p,m)),l.push(m)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},Tr=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+(?=.)/,"")},sa=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,Pc=(e,t,r,n)=>sa(e,t,r,n)<0,_n=(e,t)=>sa(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),la=e=>{for(let t=1;t<e.length;t++)if(!Pc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},ca=(e,t)=>{let r=e.findIndex(n=>_n({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var se=Object.freeze({businessDate:"business-date",idsStream:oa,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),ye=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",searchAuthor:"author",searchSourceType:"sourceType",searchCustomer:"customer",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var ua=(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)}}},Zy=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),da=e=>`[DailyReport${e}]`,he=(e,t,r)=>e===void 0?ua(t,da(r)):ua(0,da(r),e);var Lc="legacy-",xn=e=>`${Lc}${e}`;var kc=/^[1-9][0-9]*$/,Nc=/^(?:0|[1-9][0-9]*)$/,Be=e=>{if(e===null||!kc.test(e))return null;let t=Number(e);return Ke(t)?t:null},Cn=e=>{if(e===null||!Nc.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Mn=e=>e==="true"?!0:e==="false"?!1:null,rr=e=>e===null?!1:Mn(e);var pa=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),rt=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var vc=16777619,Pn=2166136261,Ln=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,vc);return o>>>0},ma=e=>Ln(Pn,e,0,e.length),Oc=String.fromCodePoint(3),Fc=String.fromCodePoint(2),Hc=String.fromCodePoint(1),Er=e=>ma(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(Oc)).join(Fc)).join(Hc));var ya=e=>e==="intersection"||e==="union",Te=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),kn=2,wr=2,Et=Object.freeze({word:0,reading:1});var Nn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var ah=2*(1+kn);import{z as lh}from"zod/v3";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 Ir=Math.max(1,Math.floor(10.556701030927835));var Ve=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Ce=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(c=>[c,0]))};o.set(i,l),Ve(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,s)=>{let c=o.get(i);if(c!==void 0){c.count+=1,c.tallies[l]+=1;return}s(),a(i)}}};var nt=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var yh=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),Uc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,vn=e=>{let t=e.trim();return t.length===0?null:t.replace(Uc,"\uFFFD")},$c=e=>{let t=vn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>nt.maxValueLength?"filter-value-too-long":null},Bc=e=>{if(e.length>nt.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=$c(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},Vc=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},ha=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=Bc(t);if(r!==null)return r}return Vc(e)>nt.maxTotalValueLength?"filters-too-long":null};var fa=e=>e.trim().length===0;var On=e=>e!==null&&br.test(e)?e:null,Fn=e=>ya(e)?e:null,Hn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>Te.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},Ra=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},Sa=(e,t)=>{let r={authors:e.getAll(ye.searchAuthor),sourceTypes:e.getAll(ye.searchSourceType),customers:e.getAll(ye.searchCustomer)},n=ha(r);if(n!==null)return{ok:!1,reason:n};let o=new Set(t.map(i=>i.toLowerCase())),a=new Set;for(let i of r.sourceTypes){let l=i.toLowerCase();if(!o.has(l))return{ok:!1,reason:"filter-unknown-source-type"};if(a.has(l))return{ok:!1,reason:"filter-duplicate-value"};a.add(l)}return{ok:!0,filters:{sourceTypes:a.size===0?null:a,authors:Ra(r.authors),customers:Ra(r.customers)}}},ga=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var Da=Object.freeze({status:400,error:"Invalid form"}),Aa=e=>({status:413,error:"Form too large",measuredBy:e}),qc=(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)}}))},Yc=async e=>{let t=Cn(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Aa("declared")};let r=!1,n=e.body===null?null:qc(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?Aa("counted"):Da}}let l=ga(i);return l===null?{refusal:Da}:{fields:l}},Ta=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=Mn(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},wa=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:Ta("toggleStar",Oe.isStarred),toggleRead:Ta("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}}}}),jc=e=>Object.hasOwn(wa,e),Wc=(e,t)=>{let r=e.get(Oe.intent),n=e.get(Oe.businessDate),o=n===null?null:Lt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Oe.operationTimestamp),i=Cn(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 s=On(l);if(s===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:s,businessDate:o,operationTimestamp:i}};let c=Be(e.get(Oe.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!jc(r)?{error:"Invalid intent"}:wa[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Ia=async(e,t)=>{let r=await Yc(e);if("refusal"in r)return r;let n=Wc(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},zc=6e4,Gc="form_too_large",Ea=["declared","counted"],_a=e=>{let t=Ce({windowMs:zc,tallies:Ea,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Ea.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(Gc,r,n)}};var wt=Object.freeze({[se.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[se.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[se.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[se.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[se.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[se.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[se.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),xa=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),Un=e=>e!==void 0&&Object.hasOwn(wt,e);var $n=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Ca=e=>Object.hasOwn($n,e);var Kc="download",Jc="thumbnail",Qc="1";var Bn=e=>{let t=e.getAll(Jc),r=e.getAll(Kc);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Ca(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Qc?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};import{NO_CROSS_ORIGIN_NAVIGATION as tu}from"@aiquants/request-isolation";import{createHash as Xc}from"crypto";var Vn=e=>`"${Xc("sha256").update(e).digest("hex")}"`,Ma=e=>Vn(JSON.stringify(e));var Qe=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),qn=(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},Pa=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=Vn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...Qe});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&qn(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},Yn=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...Qe});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},jn=e=>(t,r,n,o)=>{if(o!==200)return Yn(r,n,o);if(e===null||n===null)throw new Error(`[daily-report] API route: a 200 JSON answer needs an answer of a JSON 200 and a body; got ${e===null?"a responder without one":"an answer"} and ${n===null?"no body":"a body"}`);return e(t,r,n)},Zc=5e3/1e3,eu=new Map([[503,Zc]]),Re=e=>{let t=eu.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var zn="Cross-site request rejected",ru="Not Found",La=["api","action","sse","attachment"],ka=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...Qe}}),nu=()=>ka(403,zn),_r=()=>ka(404,ru),nr=Object.freeze({...tu,frameworkDataRefusal:()=>null,crossSiteRejection:nu}),Na=e=>new URL(e.url).pathname.endsWith(".data"),ou=6e4,au="refusals",iu=32,su=/^[a-z-]+$/,Wn=e=>{if(e===null)return"-";let t=e.slice(0,iu);return su.test(t)&&t===e?e:JSON.stringify(t)},va=e=>{let t=Ce({windowMs:ou,tallies:La,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${La.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n,o)=>{let a=()=>{let{headers:i}=o;e.warn(`cross_site_rejected route=${r} reason=${n} site=${Wn(i.get("Sec-Fetch-Site"))} mode=${Wn(i.get("Sec-Fetch-Mode"))} dest=${Wn(i.get("Sec-Fetch-Dest"))} method=${o.method}`)};t.record(au,r,a)}};var Oa=(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 lu="same-origin",cu="SAMEORIGIN",Ot=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":lu,"X-Frame-Options":cu}),xr=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Ot});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Fa=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),uu=/^[\x20-\x7E]+$/,du=/^[\w.+-]+\/[\w.+-]+/,Gn=e=>e&&uu.test(e)&&du.test(e)?e:null,pu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Ha=e=>encodeURIComponent(e.replace(pu,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Ua=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),or={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},$a={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Cr=e=>typeof e=="string"&&Object.hasOwn($a,e),Mr=e=>$a[e],ot="Attachment request failed";var Xe=e=>{let t=ae("limit",e.limit,1),r=ae("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ae("queue.max",e.queue.max,0),maxPerOwner:ae("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ae("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,s=(y,S)=>y.get(S)??0,c=(y,S,A)=>{let D=s(y,S)+A;D<=0?y.delete(S):y.set(S,D)},d=y=>s(l,y)<r,u=y=>o<t&&d(y),R=y=>(o+=1,c(l,y,1),h(y)),p=()=>{let y=-1,S=r;for(let[A,D]of a.entries()){let f=s(l,D.owner);if(f<S&&(y=A,S=f,f===0))break}return y},m=()=>{for(;o<t;){let y=p();if(y<0)return;let[S]=a.splice(y,1);c(i,S.owner,-1),S.grant(R(S.owner))}},h=y=>{let S=!1;return()=>{S||(S=!0,o-=1,c(l,y,-1),m())}};return{canAcquire:u,acquire:(y,S)=>{if(S.aborted)return Promise.resolve(null);if(u(y))return Promise.resolve(R(y));if(n===null||a.length>=n.max||s(i,y)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:A}=n,D=f=>{let b=()=>{let $=a.indexOf(I);$<0||(a.splice($,1),c(i,y,-1),w(),f(null))},C=Ve(b,A),w=()=>{clearTimeout(C),S.removeEventListener("abort",b)},I={owner:y,grant:$=>{w(),f($)}};a.push(I),c(i,y,1),S.addEventListener("abort",b,{once:!0})};return new Promise(D)}}};var mu=1024,Kn="Too many requests",yu=(e,t)=>{ae("limitPerWindow",e,1),ae("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 s=l??{tokens:e,lastRefillMs:i};n(s,i),r.set(a,s);for(let c of r.keys()){if(r.size<=mu)break;r.delete(c)}return s};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let s=r.get(a);s&&(n(s,i),s.tokens=Math.min(e,s.tokens+l))}}},at=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ae("windowMs",r,1e3)%1e3!==0)throw K("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=yu(e.limitPerWindow,r),i=Object.freeze({status:429,message:Kn,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Ce({windowMs:r,tallies:[t],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`${t}_suppressed count=${c} since=${d} ${o(s)}`)}});return{spend:(s,c)=>a.consume(s,ie())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,ie(),c)}}};var fu=256*1024,Ba=6e4,Ru=e=>Math.ceil(e/2),Su=new Uint8Array(new ArrayBuffer(0)),gu=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Su,t()},i=l=>{clearTimeout(o),o=Ve(()=>{l.error(new Error(`attachment body idle for ${Ba} ms`)),a()},Ba)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+fu,r.byteLength);if(s>n&&l.enqueue(r.slice(n,s)),n=s,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},Va=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=at({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=Xe({limit:e.concurrency,maxHeldPerOwner:Ru(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:R,readAttachment:p,cookie:m,fail:h}=s,y=e.maxBytes,S=i.spend(R,`attachment=${u} viewer=${R}`);if(S)return h(S.status,S.message,S.headers);let A=await n(c,"initial");if(!A.ok)return h(503,or[503],Re(503));let D=await t.getAttachmentForUser(A.scope,u,R);if(!D)return o.warn(`404 attachment=${u} viewer=${R} reason=not_visible`),h(404,"Attachment not found");if(D.fileSize!=null&&D.fileSize>y)return o.warn(`413 attachment=${u} viewer=${R} reason=db_size`),h(413,"Attachment too large");let f=Gn(D.fileType),b=`filename="${Ua(D.fileName)}"; filename*=UTF-8''${Ha(D.fileName)}`,C=await l.acquire(R,c.signal);if(!C)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${R} reason=aborted`),h(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${R} reason=concurrency`),h(503,"Too many concurrent downloads",Re(503)));let w=!1;try{let I=await p(D.filePath,{maxBytes:y,head:c.method==="HEAD",principal:r(R),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${R} reason=aborted`),h(503,"Attachment request aborted");if(!I.ok){if(!Cr(I.reason))return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=failure_reason`),h(500,ot);let U=Mr(I.reason);return I.reason==="not_found"&&a(u,!1),o.warn(`${U} attachment=${u} viewer=${R} reason=${I.reason} code=${I.code??"-"}`),h(U,or[U],Re(U))}if(I.bytes.byteLength>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),h(500,ot);let $=c.method==="HEAD";if($&&I.size!==void 0&&I.size>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),h(500,ot);if(!$&&I.size!==void 0&&I.size!==I.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=size_mismatch`),h(500,ot);let N=f??Gn(I.contentType),v=N!==null&&Fa.has(N),L=v?N:"application/octet-stream",F=v&&d.kind!=="download"?"inline":"attachment",T=$?I.size:I.bytes.byteLength,_=new Headers({"Content-Type":L,"Content-Disposition":`${F}; ${b}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Ot});return T!==void 0&&_.set("Content-Length",String(T)),m&&_.append("Set-Cookie",m),a(u,!0),o.info(`200 attachment=${u} viewer=${R} type=${L} disposition=${F} bytes=${T??"-"}`),$?new Response(null,{status:200,headers:_}):(w=!0,new Response(gu(I.bytes,C),{status:200,headers:_}))}finally{w||C()}}};var Le=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),nf=Le.queueWaitMs+Le.readMs+Le.renderMs+Le.transferMarginMs;import{Buffer as bu}from"buffer";var ja=new Set([194,198,202,206]),Du=new Set([192,193,194,195]),Wa=216,Au=217,za=218,Tu=4,Eu=64,wu=2,qa=8,Ya=28,dt=12,Jn=8,Iu=20,Ga=dt+Jn+10,_u=2,it=(e,t)=>e[t]<<8|e[t+1],Ft=(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},Ka=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Ja=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),Qa=e=>(e.stepsLeft-=1,e.stepsLeft>=0),Xa=e=>e[0]===255&&e[1]===Wa,Za=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!Qa(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===Au)return"eoi";if(o===0||o===Wa)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=it(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")}},xu=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!Qa(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}},ei=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=it(e,r+1),a=it(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let s=0;s<i;s+=1){let c=e[r+7+3*s],d=c>>4,u=c&15;if(d<1||d>4||u<1||u>4)return null;l.push({id:e[r+6+3*s],horizontal:d,vertical:u})}return{marker:t,width:a,height:o,components:l}},ti=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>Tu||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},ri=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:ja.has(e.marker)||t<e.components.length}),Qn=e=>{if(!Xa(e))return null;let t=Ja(e.byteLength),r=null;for(let n=2;;){if(Za(e,n,t)!=="segment")return null;if(Ka(t.marker)){if(r!==null||(r=ei(e,t),r===null))return null}else if(t.marker===za){if(r===null)return null;let o=ti(e,t);return o===null?null:ri(r,o.length)}n=t.end}},ni=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*qa)),i=Math.ceil(e.height*o/(r*qa));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},oi=e=>e.multiScan?ni(e).reduce((r,n)=>r+n,0)*Eu*wu:0,Cu=896,ai=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!Xa(e))return null;let n=bu.from(e.buffer,e.byteOffset,e.byteLength),o=Ja(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let R=Za(e,u,o);if(R===null)return null;if(R==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,Ka(o.marker)){if(a!==null||!Du.has(o.marker)||(a=ei(e,o),a===null))return null;let p=ni(a);l=new Map;for(let[m,h]of a.components.entries()){let y=l.get(h.id);l.set(h.id,y===void 0?p[m]:Math.max(y,p[m]))}s=a.components.length*(ja.has(a.marker)?Cu:1)}else if(o.marker===za){if(a===null||d===s)return null;let p=ti(e,o);if(p===null)return null;for(let h of p){let y=l.get(h);if(y===void 0)return null;c+=y}if(d+=1,i===null&&(i=ri(a,p.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let m=xu(n,o.end,o);if(m===null)return null;u=m}}},ii=e=>{if(e.byteLength<24||it(e,8)!==0||it(e,10)!==13||!Ze(e,12,"IHDR"))return null;let t=it(e,16)*65536+it(e,18),r=it(e,20)*65536+it(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Mu=e=>{if(Ze(e,dt,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Ft(e,26,2)&16383,r=Ft(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(Ze(e,dt,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Ft(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return Ze(e,dt,"VP8X")?e.byteLength<Ga?null:{width:Ft(e,24,3)+1,height:Ft(e,27,3)+1}:null},si=e=>{if(ii(e)===null||e.byteLength<=Ya)return null;switch(e[Ya]){case 0:return!1;case 1:return!0;default:return null}},li=(e,t)=>{if(Ze(e,dt,"VP8 "))return"lossy";if(Ze(e,dt,"VP8L"))return"lossless";if(!Ze(e,dt,"VP8X")||e.byteLength<Ga)return null;if((e[Iu]&_u)!==0)return"animated";let r=!1,n=t;for(let o=dt;o+Jn<=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=Ft(e,o+4,4);o+=Jn+a+a%2}return null},ci={png:ii,jpeg:Qn,webp:Mu};var Xn=Object.freeze(["image/webp","image/jpeg","image/png"]),Zn=1024*1024;var Pu=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Lu={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},ku=new Set(Xn),Nu=e=>typeof e=="string"&&ku.has(e),vu=256,Pr=(e,t)=>e.fileType===null||!Pu.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Ou=[137,80,78,71,13,10,26,10],Fu=[255,216,255],Hu=[[71,73,70,56,55,97],[71,73,70,56,57,97]],Uu=[82,73,70,70],$u=[87,69,66,80],ar=(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},eo=e=>{if(ar(e,Ou,0))return"png";if(ar(e,Fu,0))return"jpeg";for(let t of Hu)if(ar(e,t,0))return"gif";return ar(e,Uu,0)&&ar(e,$u,8)?"webp":null},ui=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:Ma([t])}},di=(e,t)=>{if(!Nu(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Zn)return"too_large";let r=Lu[e.contentType];if(eo(e.bytes)!==r)return"signature";let n=ci[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},pi=e=>{ae("maxBytes",e.maxBytes,0),ae("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)+vu;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 s of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(s)}}}};var to=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ie(),l=new AbortController,s=!1,c,d,u=()=>{a(ie()-i)},R=f=>{c=Ve(()=>{s=!0,f({timedOut:!0}),d=Ve(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},p=new Promise(R),m=AbortSignal.any([r,l.signal]),h=f=>{f(n(m))},y=new Promise(h),S=f=>(clearTimeout(c),clearTimeout(d),s&&o(ie()-i,f.kind==="error"?{error:f.error}:null),f),A=y.then(f=>S({kind:"value",value:f}),f=>S({kind:"error",error:f}));return{outcome:Promise.race([y.then(f=>({timedOut:!1,value:f})),p]),settled:A}};var st={404:"Attachment not found",500:ot,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},mi=(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=di(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Bu=e=>{let t=new AbortController,r=()=>{t.abort()},n=Ve(r,Le.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},yi=()=>{},Vu=(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)}),hi=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,s=(p,m)=>{let h=m.then(yi,yi);l.set(p,h);let y=()=>{l.get(p)===h&&l.delete(p)};h.then(y)},c=async(p,m)=>{let h=l.get(p.key);if(h===void 0)return t.acquire(p.owner,m);let y=Bu(m);try{if(await Vu(h,y.signal),y.signal.aborted)return null;let S=r.get(p.key);return S!==void 0?{...S,identity:"verified"}:await t.acquire(p.owner,y.signal)}finally{y.end()}},d=(p,m)=>{if(p.fileSize===null)return m.kind==="exact"?"verified":"unrecorded";if(m.kind==="exact"?m.bytes===p.fileSize:p.fileSize>m.maxBytes)return"verified";let y=m.kind==="exact"?String(m.bytes):`>${m.maxBytes}`;return i.warn(`size_mismatch expected=${p.fileSize} got=${y} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail`),"unverified"},u=(p,m)=>(h,y)=>{let S=y===null?"":` message=${y.error instanceof Error?y.error.message:"unknown"}`;i.warn(`${p}_overrun ms=${h} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail${S}`)},R=(p,m)=>h=>{i.warn(`${p}_stuck ms=${h} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`)};return async(p,m)=>{let h=await c(p,m);if(h===null)return{kind:"failure",status:503,reason:m.aborted?"aborted":"queue"};if(typeof h!="function")return h;let y=h,S=null;try{if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let A=r.get(p.key);if(A!==void 0)return{...A,identity:"verified"};let D=to({budgetMs:Le.readMs,flightSignal:m,call:U=>p.readAttachment(p.filePath,{maxBytes:n,head:!1,principal:o(p.owner),signal:U}),onOverrun:u("read",p),onStuck:R("read",p)}),f=await D.outcome;if(f.timedOut)return S=D.settled,m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let b=f.value;if(!b.ok&&b.reason!=="too_large")return Cr(b.reason)?(b.reason==="not_found"&&a(p.attachmentId,!1),{kind:"failure",status:Mr(b.reason),reason:b.reason,code:b.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(b.ok&&b.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let C=d(p,b.ok?{kind:"exact",bytes:b.bytes.byteLength}:{kind:"over",maxBytes:n}),w=U=>{C==="verified"&&r.set(p.key,U)},I=U=>(w(U),{...U,identity:C});if(!b.ok)return I({kind:"unrenderable",reason:"too_large"});let $=eo(b.bytes);if($===null)return I({kind:"unrenderable",reason:"signature"});let N=to({budgetMs:Le.renderMs,flightSignal:m,call:U=>p.renderer.render(b.bytes,{format:$,maxWidth:p.box.maxWidth,maxHeight:p.box.maxHeight,signal:U}),onOverrun:u("render",p),onStuck:R("render",p)}),v=U=>{if(U.kind==="error")return;let z=mi(U.value,p.box);"entry"in z&&w(z.entry)},L=null,F=()=>(L===null&&(L=N.settled.then(v),s(p.key,L)),L);m.addEventListener("abort",F,{once:!0});let T=await N.outcome.finally(()=>m.removeEventListener("abort",F));if(T.timedOut||m.aborted)return S=F(),m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let _=mi(T.value,p.box);return"entry"in _?I(_.entry):_.failure}finally{S===null?y():S.then(y,y)}}};var fi=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let s=new AbortController,c=()=>{e.get(t)?.controller===s&&e.delete(t)},u={promise:n(s.signal).finally(c),controller:s,waiters:0};return e.set(t,u),u},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 gi=10,qu=1/gi,Ri=1-qu,Yu=1024,ju=64,Wu=8,Si="private, no-cache",zu="no-store",Gu=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),Ku=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},bi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(f,b)=>at({reason:f,limitPerWindow:b,windowMs:6e4,logger:o,windowFields:C=>`viewer=${C} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*gi),R=Xe({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:ju,maxPerOwner:Wu,maxWaitMs:Le.queueWaitMs}}),p=pi({maxBytes:l.cacheBytes,maxEntries:Yu}),m=fi(),h=hi({gate:R,cache:p,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),y=(f,b,C,w)=>{let I=`attachment=${f.attachmentId} viewer=${f.internalUserId} variant=thumbnail cache=${w}`;if(b.kind==="failure")return o[Ku(b)](`${b.status} ${I} reason=${b.reason} code=${b.code??"-"}`),f.fail(b.status,st[b.status],Re(b.status));let $=Gu[b.identity];if(b.kind==="unrenderable")return o.info(`404 ${I} reason=${b.reason}${$}`),f.fail(404,st[404]);let N=b.identity==="verified"?{"Cache-Control":Si,ETag:C}:{"Cache-Control":zu},v=new Headers({"Content-Type":b.contentType,"Content-Length":String(b.bytes.byteLength),...N,"Content-Security-Policy":"default-src 'none'; sandbox",...Ot});return f.cookie&&v.append("Set-Cookie",f.cookie),o.info(`200 ${I} type=${b.contentType} bytes=${b.bytes.byteLength}${$}`),new Response(b.bytes,{status:200,headers:v})},S=(f,b)=>{let C=f.spend(b.internalUserId,`attachment=${b.attachmentId} viewer=${b.internalUserId} variant=thumbnail`);return C===null?null:b.fail(C.status,C.message,C.headers)},A=f=>S(d,f),D=(f,b)=>b?S(u,f):A(f);return async(f,b)=>{let{request:C,attachmentId:w,internalUserId:I,readAttachment:$,cookie:N,fail:v}=f,L=$n[b],F=C.headers.get("If-None-Match"),T=F!==null,_=D(f,T);if(_)return _;let U=await n(C,"initial");if(!U.ok)return v(503,st[503],Re(503));let z=await t.getAttachmentForUser(U.scope,w,I),G=z!==null&&Pr(z,i)?ui({rendererId:s.id,box:L,attachmentId:w,filePath:z.filePath,fileType:z.fileType,fileSize:z.fileSize}):null;if(G&&qn(F,G.etag)){let g=new Headers({"Cache-Control":Si,ETag:G.etag,...Ot});return N&&g.append("Set-Cookie",N),o.info(`304 attachment=${w} viewer=${I} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:g})}if(T){let g=A(f);if(g)return g}if(!z)return o.warn(`404 attachment=${w} viewer=${I} variant=thumbnail reason=not_visible`),v(404,st[404]);if(!G)return d.refund(I,Ri),o.info(`404 attachment=${w} viewer=${I} variant=thumbnail reason=not_eligible`),v(404,st[404]);let{key:de,etag:me}=G,Z=p.get(de);if(Z)return d.refund(I,Ri),y(f,{...Z,identity:"verified"},me,"hit");let ve=g=>h({key:de,attachmentId:w,filePath:z.filePath,fileSize:z.fileSize,box:L,owner:I,readAttachment:$,renderer:s},g),O;try{O=await m.join(de,C.signal,ve)}catch(g){return o.error(`500 attachment=${w} viewer=${I} variant=thumbnail cache=miss reason=port_exception message=${g instanceof Error?g.message:"unknown"}`),v(500,st[500])}return y(f,O,me,"miss")}};var Ju='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Qu=()=>xr(403,zn,{cookie:null}),Di=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=Bn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>xr(404,or[404],{cookie:null}),crossSiteRejection:Qu}),Ai=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:Oa(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:Va({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:bi({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,R=(p,m,h={})=>xr(p,m,{cookie:u,extraHeaders:h});try{let{user:p,cookie:m}=await t(c,{failureRedirect:null});if(u=m??null,!p)return R(401,"Unauthorized");let h=Bn(new URL(c.url).searchParams);if(h.kind==="invalid")return R(400,"Invalid attachment request");if(h.kind==="thumbnail"&&c.method!=="GET")return R(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return R(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return R(404,"Attachment not found");if(d.token===void 0)throw new Error(Ju);let y=s.idCodec.decode(d.token);if(y===null||!Ke(y))return R(400,"Invalid attachment token");let S=await r.getUserIdByExternalId(p.id);if(!S)return R(403,"Forbidden");let A={request:c,delivery:h,attachmentId:y,internalUserId:S,readAttachment:s.read,cookie:u,fail:R};return h.kind!=="thumbnail"?await s.serveOriginal(A):s.serveThumbnail===null?R(404,st[404]):await s.serveThumbnail(A,h.variant)}catch(p){if(p instanceof Response)throw p;return a.error(`500 attachment=? viewer=? reason=unexpected message=${p instanceof Error?p.message:"unknown"}`),R(500,ot)}}};var Xu=32*1024*1024,Zu=60,ed=4,td=120,rd=2,nd=8*1024*1024,Lr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),od=e=>{if(e===void 0)throw Ge("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Lr(e))throw K("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw Ge("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw K("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw K("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},ad=e=>{if(e===void 0)return null;if(!Lr(e))throw K("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:od(e.renderer),rateLimitPerMinute:_e("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,td),concurrency:_e("attachments.thumbnails.concurrency",e.concurrency,1,rd),cacheBytes:_e("attachments.thumbnails.cacheBytes",e.cacheBytes,0,nd)})},Ti=e=>{let t=e;if(t===void 0)return null;if(!Lr(t))throw K("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw Ge("attachments.idCodec","injected when attachments is given");if(!Lr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw K("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw Ge("attachments.read","injected when attachments is given");if(typeof n!="function")throw K("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:_e("attachments.maxBytes",t.maxBytes,1,Xu),rateLimitPerMinute:_e("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,Zu),concurrency:_e("attachments.concurrency",t.concurrency,1,ed),thumbnails:ad(t.thumbnails)})},id=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"]]),kr=e=>{for(let[t,r]of id)if(Object.hasOwn(e,t))throw Ge(r,`given in place of the flat key ${t}`)};var wi=8,sd=8*wi,ld=128,cd=2,Ii=cd*ld,ud=4*Ii,dd=6e4,pd=6e4,md="Too many reads",Ei=Object.freeze(Object.keys(wt).filter(e=>wt[e].admission.includes("miss-gate"))),_i=e=>{let t=Xe({limit:sd,maxHeldPerOwner:wi,queue:{max:ud,maxPerOwner:Ii,maxWaitMs:dd}}),r=Ce({windowMs:pd,tallies:Ei,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${Ei.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}})}},Nr=(e,t,r)=>{let n=e(t,r,{error:{message:md}},503);for(let[o,a]of Object.entries(Re(503)))n.headers.set(o,a);return n};var xi=e=>{let t=e.get(ye.cursorReportHubId),r=e.get(ye.cursorBusinessDate),n=e.get(ye.cursorSnapshot),o=ia(n)?n:null,a=null;if(t!==null){let l=Be(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!aa(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=rr(e.get(ye.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var vr=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,yd=2,hd=16,fd=yd*hd,Rd=6e4,Ci=()=>{},Sd=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Mi=e=>{let t=Xe({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:fd,queue:null}),r=Ce({windowMs:Rd,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 Ci;if(a.aborted){if(t.canAcquire(n))return Ci}else{let i=await t.acquire(n,a);if(i!==null)return Sd(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var Or=30,vi=4e3,gd="stream interrupted by server error",bd="Too many streams",Dd=15e3,Oi=Symbol("ids-stream-heartbeat"),Pi=()=>{},Li=e=>e.return(void 0).then(Pi,Pi),Ad=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(Oi),Dd)}),stop:()=>clearTimeout(e)}};async function*ki(e,t,r,n){let o=t?ca(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:vi),e.length),l=vt(e,o,i),s=i>o?e[i-1]:void 0;o=i;let c=o>=e.length;if(yield{kind:"chunk",...l,nextCursor:c||s===void 0?null:{businessDate:s.businessDate,reportHubId:s.reportHubId},isLast:c,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,c)return}}var Fi=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...Qe});return e&&t.append("Set-Cookie",e),t},Ni=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await Li(t);try{d.close()}catch{}},i=new TextEncoder,l=!1,s=null,c=new ReadableStream({async pull(d){if(l||r.aborted){await a(d,!0);return}let u=Ad();try{s===null&&(s=t.next());let R=await Promise.race([s,u.fired]);if(u.stop(),R===Oi){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
|
|
1
|
+
var zo=e=>{throw TypeError(e)};var Go=(e,t,r)=>t.has(e)||zo("Cannot "+r);var tr=(e,t,r)=>(Go(e,t,"read from private field"),r?r.call(e):t.get(e)),An=(e,t,r)=>t.has(e)?zo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Tn=(e,t,r,n)=>(Go(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var Pt=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,K=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Pt(r)}`),rt=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),En=(e,t,r)=>K(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),ie=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw K(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},Pe=(e,t,r,n)=>t===void 0?n:ie(e,t,r),rr=(e,t)=>{if(t===void 0)throw rt(e,"a function");if(typeof t!="function")throw K(e,"a function",t);return t};var se=()=>Math.floor(performance.now());var wn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),je=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},In=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{}}}),nr=(e,t)=>t?e.map(r=>structuredClone(r)):e,hc=8,fc=32,Rc=24,Sc=16,gc=-(2**30),bc=2**30-1,Dc=e=>Number.isInteger(e)&&e>=gc&&e<=bc&&!Object.is(e,-0),Ac=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=fc,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=hc*a.length;for(let i of a)typeof i=="string"?r+=Rc+2*i.length:typeof i=="number"&&!Dc(i)?r+=Sc:typeof i=="object"&&i!==null&&n.push(i)}return r},or=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.totalBytes=0;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-se())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let s=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:c,expireAt:se()+a,epoch:s}),c})(),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,s=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&s===null)throw new je(o.signal.aborted?"aborted":"busy");try{for(let d of r)d();let c=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:c,expireAt:se()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),c}finally{s?.()}})(),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 je("aborted");return this.dropBucket(r),nr(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>se())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),nr(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),nr(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return nr(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new je("aborted");return nr(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 je&&(o===void 0||n.reason==="aborted"&&!o.signal.aborted)))throw n;return this.getOrFetch({...r,snapshot:!1})}};this.clearAll=()=>{this.buckets.clear(),this.totalBytes=0,this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.dropBucket(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)};this.defaultTtlMs=Pe("cacheDefaultTtlMs",t.defaultTtlMs,1,wn.defaultTtlMs),this.maxBuckets=Pe("cacheMaxBuckets",t.maxBuckets,1,wn.maxBuckets),this.maxBytes=Pe("cacheMaxBytes",t.maxBytes,1,wn.maxBytes),this.lastSweepAt=se()}dropBucket(t){let r=this.buckets.get(t);r!==void 0&&(this.buckets.delete(t),this.totalBytes-=r.bytes)}writeBucket(t,r){this.dropBucket(t);let n=Ac(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=se();o-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(o);for(let a of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets&&this.totalBytes<=this.maxBytes)break;this.dropBucket(a)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.dropBucket(r)}};import{crossOriginRefusal as Gp}from"@aiquants/request-isolation";var Tc=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Ko=e=>e<10?`0${e}`:`${e}`,Ec=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Ko(e.getMonth()+1),n=Ko(e.getDate());return`${t}-${r}-${n}`},Vt=e=>{let t=Tc.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 s=new Date(0);return s.setUTCFullYear(a,i-1,l),s.getUTCFullYear()!==a||s.getUTCMonth()!==i-1||s.getUTCDate()!==l?null:`${r}-${n}-${o}`},Mr=e=>Vt(e)===e;var Fe=e=>e==null?null:e instanceof Date?Ec(e):Vt(e);import{z as wc}from"zod/v3";var nt=e=>Number.isSafeInteger(e)&&e>0,ke=wc.number().int().positive().max(Number.MAX_SAFE_INTEGER);import{z as re}from"zod/v3";var Pr=/^(?:[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})$/;var kt=Symbol("daily-report wire mismatch"),ot=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),kt),Zo=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,Lt=(e,t)=>({code:"invalid_type",expected:e,received:Zo(t)}),Ic=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_c=e=>{let t=0;for(let r in e)t+=1;return t},Jo=(e,t,r)=>{let n={};for(let o=0;o<r;o+=1){let a=t[o];a in e&&(n[a]=e[a])}return n},qt=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!Ic(n))return ot(o,null,Lt("object",n));let a=null,i=!1,l=0;for(let s=0;s<t.length;s+=1){let c=t[s],d=n[c];d!==void 0&&(l+=1);let u=r[s](d,o,c);if(u===kt){i=!0;continue}a===null&&u!==d&&(a=Jo(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?kt:a!==null?a:_c(n)===l?n:Jo(n,t,t.length)}},ar=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},ir=e=>(t,r,n)=>{if(!Array.isArray(t))return ot(r,n,Lt("array",t));r.path.push(n);let o=t,a=!1;for(let i=0;i<t.length;i+=1){let l=t[i],s=e(l,r,i);s===kt?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?kt:o},ue=(e,t,r)=>e==null||typeof e=="string"?e:ot(t,r,Lt("string",e)),Qo=(e,t,r)=>e===null||typeof e=="string"?e:ot(t,r,Lt("string",e)),Xo=(e,t,r)=>typeof e=="string"?e:ot(t,r,Lt("string",e)),xc=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:ot(t,r,Lt("number",e)),sr=(e,t,r)=>typeof e=="boolean"?e:ot(t,r,Lt("boolean",e)),_n=(e,t,r)=>{if(typeof e=="number"&&nt(e))return e;for(let{message:n,path:o,...a}of ke.safeParse(e).error.issues)ot(t,r,a);return kt},ea={present:!0,absent:!0,unknown:!0},ta=Object.keys(ea),Cc=ta.map(e=>`'${e}'`).join(" | "),Mc=(e,t,r)=>typeof e!="string"?ot(t,r,{code:"invalid_type",expected:Cc,received:Zo(e)}):Object.hasOwn(ea,e)?e:ot(t,r,{code:"invalid_enum_value",received:e,options:[...ta]}),ra=qt({name:ue,affiliation:ue}),na=qt({name:ue,text:ue,color:ue}),oa=qt({id:_n,name:ue,color:ue}),aa=qt({id:_n,userId:ue,userName:ue,content:ue,createdAt:ue,isMine:sr}),Pc=qt({id:Xo,fileName:Xo,fileType:Qo,fileSize:xc,createdAt:Qo,state:Mc,hasThumbnail:sr}),kc=qt({reportHubId:_n,date:ue,createdAt:ue,author:ue,userId:ue,sourceType:ue,employeeName:ue,updatedBy:ue,updatedAt:ue,category:ue,creationCategory:ue,visitTimeFrom:ue,visitTimeTo:ue,customerName:ue,interviewers:ir(ar(ra)),subject:ue,content:ue,externalComments:ir(ar(na)),isRead:sr,isStarred:sr,isDraft:sr,labels:ir(ar(oa)),postedComments:ir(ar(aa)),attachments:ir(ar(Pc))}),lr=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===kt?{ok:!1,issues:r.issues}:{ok:!0,value:n}},ia=e=>lr(kc,e),sa=e=>lr(ra,e),la=e=>lr(na,e),ca=e=>lr(oa,e),ua=e=>lr(aa,e);var da=15e3,pa="lastEventId",Lc=/^\d{1,15}-\d{1,15}$/,ma=e=>Lc.test(e),At="0-0",cr=e=>re.unknown().transform((t,r)=>{let n=e(t);if(n.ok)return n.value;for(let o of n.issues)r.addIssue({...o,fatal:!0});return re.NEVER}),Qy=cr(sa),Xy=cr(la),Zy=cr(ca),vc=cr(ua),ur=cr(ia),dr=re.string().regex(Pr),ya=re.object({type:re.literal("connected")}),ha=re.object({type:re.literal("status-update"),reportHubId:ke,statusType:re.enum(["star","read"]),value:re.boolean(),clientTempId:dr}),xn=re.string(),fa=re.object({type:re.literal("comment-add"),reportHubId:ke,comment:vc,clientTempId:dr,sourceType:xn}),Ra=re.object({type:re.literal("comment-delete"),reportHubId:ke,commentId:ke,clientTempId:dr,sourceType:xn}),kr={recipientRawUserId:ke.optional()},Cn=ha.extend(kr),Mn=fa.extend(kr),Pn=Ra.extend(kr),Yt={reportHubId:ke,report:ur,clientTempId:dr},kn={...kr,actorRawUserId:ke},Ln={viewerIsActor:re.boolean()},Nc=re.object({type:re.literal("report-create"),...Yt,...Ln}),Oc=re.object({type:re.literal("report-update"),...Yt,...Ln}),Hc=re.object({type:re.literal("report-publish"),...Yt,...Ln}),vn=re.object({type:re.literal("report-create"),...Yt,...kn}),Nn=re.object({type:re.literal("report-update"),...Yt,...kn}),On=re.object({type:re.literal("report-publish"),...Yt,...kn}),Lr=re.object({type:re.literal("report-delete"),reportHubId:ke,clientTempId:dr,sourceType:xn}),eh=re.discriminatedUnion("type",[ya,ha,fa,Ra,Nc,Oc,Hc,Lr]),Hn=re.discriminatedUnion("type",[ya,Cn,Mn,Pn,vn,Nn,On,Lr]);var Sa="ids-columns";var Fc=/^[0-9a-f]{1,16}$/,ga=e=>nt(e.reportHubId)&&(e.businessDate===null||Mr(e.businessDate)),ba=e=>typeof e=="string"&&Fc.test(e),oh=Object.freeze({kind:"absent"}),ah=Object.freeze({kind:"value",value:null});var Wt=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],s=new Map;for(let c=t;c<r;c++){let{reportHubId:d,businessDate:u,sourceType:R}=e[c];n.push(d),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let p=R===void 0?null:R,m=s.get(p);m===void 0&&(m=i.length,i.push(p),s.set(p,m)),l.push(m)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},vr=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+(?=.)/,"")},Da=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,Uc=(e,t,r,n)=>Da(e,t,r,n)<0,Fn=(e,t)=>Da(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Aa=e=>{for(let t=1;t<e.length;t++)if(!Uc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},Ta=(e,t)=>{let r=e.findIndex(n=>Fn({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var le=Object.freeze({businessDate:"business-date",idsStream:Sa,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),Re=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",searchAuthor:"author",searchSourceType:"sourceType",searchCustomer:"customer",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var Ea=(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)}}},ch=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),wa=e=>`[DailyReport${e}]`,Se=(e,t,r)=>e===void 0?Ea(t,wa(r)):Ea(0,wa(r),e);import{z as vt}from"zod/v3";var pr=e=>({reportHubId:e,outcome:"not_found"}),yh=vt.discriminatedUnion("outcome",[vt.object({reportHubId:ke,outcome:vt.literal("ok"),report:ur}).strict(),vt.object({reportHubId:ke,outcome:vt.literal("not_found")}).strict(),vt.object({reportHubId:ke,outcome:vt.literal("failed")}).strict()]);var $c="legacy-",Un=e=>`${$c}${e}`;var Bc=/^[1-9][0-9]*$/,Vc=/^(?:0|[1-9][0-9]*)$/,ze=e=>{if(e===null||!Bc.test(e))return null;let t=Number(e);return nt(t)?t:null},$n=e=>{if(e===null||!Vc.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Bn=e=>e==="true"?!0:e==="false"?!1:null,mr=e=>e===null?!1:Bn(e);var Ia=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),dt=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var qc=16777619,Vn=2166136261,qn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,qc);return o>>>0},_a=e=>qn(Vn,e,0,e.length),Yc=String.fromCodePoint(3),Wc=String.fromCodePoint(2),jc=String.fromCodePoint(1),Nr=e=>_a(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(Yc)).join(Wc)).join(jc));var xa=e=>e==="intersection"||e==="union",we=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Yn=2,Or=2,Nt=Object.freeze({word:0,reading:1});var Wn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var bh=2*(1+Yn);import{z as Eh}from"zod/v3";var Ca=e=>e.issues.map(t=>`${t.path.length===0?"(root)":t.path.join(".")}: ${t.code}`).join("; ");var Ve=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var Hr=Math.max(1,Math.floor(10.556701030927835));var Ge=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Ie=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(c=>[c,0]))};o.set(i,l),Ge(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,s)=>{let c=o.get(i);if(c!==void 0){c.count+=1,c.tallies[l]+=1;return}s(),a(i)}}};var pt=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var Mh=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),zc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,jn=e=>{let t=e.trim();return t.length===0?null:t.replace(zc,"\uFFFD")},Gc=e=>{let t=jn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>pt.maxValueLength?"filter-value-too-long":null},Kc=e=>{if(e.length>pt.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=Gc(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},Jc=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},Ma=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=Kc(t);if(r!==null)return r}return Jc(e)>pt.maxTotalValueLength?"filters-too-long":null};var Pa=e=>e.trim().length===0;var zn=e=>e!==null&&Pr.test(e)?e:null,Gn=e=>xa(e)?e:null,Kn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>we.maxDetailIds)return null;let r=[];for(let n of t){let o=ze(n);if(o===null||r.includes(o))return null;r.push(o)}return r},ka=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},La=(e,t)=>{let r={authors:e.getAll(Re.searchAuthor),sourceTypes:e.getAll(Re.searchSourceType),customers:e.getAll(Re.searchCustomer)},n=Ma(r);if(n!==null)return{ok:!1,reason:n};let o=new Set(t.map(i=>i.toLowerCase())),a=new Set;for(let i of r.sourceTypes){let l=i.toLowerCase();if(!o.has(l))return{ok:!1,reason:"filter-unknown-source-type"};if(a.has(l))return{ok:!1,reason:"filter-duplicate-value"};a.add(l)}return{ok:!0,filters:{sourceTypes:a.size===0?null:a,authors:ka(r.authors),customers:ka(r.customers)}}},va=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var Oa=Object.freeze({status:400,error:"Invalid form"}),Ha=e=>({status:413,error:"Form too large",measuredBy:e}),Qc=(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)}}))},Xc=async e=>{let t=$n(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Ha("declared")};let r=!1,n=e.body===null?null:Qc(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?Ha("counted"):Oa}}let l=va(i);return l===null?{refusal:Oa}:{fields:l}},Fa=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=Bn(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},$a=Object.freeze({update:(e,t,r)=>{let n=e.get(Ve.title),o=e.get(Ve.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:Fa("toggleStar",Ve.isStarred),toggleRead:Fa("toggleRead",Ve.isRead),addComment:(e,t)=>{let r=e.get(Ve.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=ze(e.get(Ve.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),Zc=e=>Object.hasOwn($a,e),eu=(e,t)=>{let r=e.get(Ve.intent),n=e.get(Ve.businessDate),o=n===null?null:Vt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Ve.operationTimestamp),i=$n(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(Ve.clientTempId);if(!l)return{error:"clientTempId required"};let s=zn(l);if(s===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:s,businessDate:o,operationTimestamp:i}};let c=ze(e.get(Ve.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!Zc(r)?{error:"Invalid intent"}:$a[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Ba=async(e,t)=>{let r=await Xc(e);if("refusal"in r)return r;let n=eu(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},tu=6e4,ru="form_too_large",Ua=["declared","counted"],Va=e=>{let t=Ie({windowMs:tu,tallies:Ua,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Ua.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(ru,r,n)}};var Ot=Object.freeze({[le.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[le.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[le.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[le.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[le.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[le.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[le.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),qa=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),Jn=e=>e!==void 0&&Object.hasOwn(Ot,e);var Qn=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Ya=e=>Object.hasOwn(Qn,e);var nu="download",ou="thumbnail",au="1";var Xn=e=>{let t=e.getAll(ou),r=e.getAll(nu);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Ya(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===au?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};import{NO_CROSS_ORIGIN_NAVIGATION as cu}from"@aiquants/request-isolation";import{createHash as iu}from"crypto";var Zn=e=>`"${iu("sha256").update(e).digest("hex")}"`,Wa=e=>Zn(JSON.stringify(e));var at=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),eo=(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},ja=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=Zn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...at});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&eo(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},to=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...at});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},ro=e=>(t,r,n,o)=>{if(o!==200)return to(r,n,o);if(e===null||n===null)throw new Error(`[daily-report] API route: a 200 JSON answer needs an answer of a JSON 200 and a body; got ${e===null?"a responder without one":"an answer"} and ${n===null?"no body":"a body"}`);return e(t,r,n)},su=5e3/1e3,lu=new Map([[503,su]]),be=e=>{let t=lu.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var oo="Cross-site request rejected",uu="Not Found",za=["api","action","sse","attachment"],Ga=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...at}}),du=()=>Ga(403,oo),Fr=()=>Ga(404,uu),yr=Object.freeze({...cu,frameworkDataRefusal:()=>null,crossSiteRejection:du}),Ka=e=>new URL(e.url).pathname.endsWith(".data"),pu=6e4,mu="refusals",yu=32,hu=/^[a-z-]+$/,no=e=>{if(e===null)return"-";let t=e.slice(0,yu);return hu.test(t)&&t===e?e:JSON.stringify(t)},Ja=e=>{let t=Ie({windowMs:pu,tallies:za,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${za.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n,o)=>{let a=()=>{let{headers:i}=o;e.warn(`cross_site_rejected route=${r} reason=${n} site=${no(i.get("Sec-Fetch-Site"))} mode=${no(i.get("Sec-Fetch-Mode"))} dest=${no(i.get("Sec-Fetch-Dest"))} method=${o.method}`)};t.record(mu,r,a)}};var Qa=(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 fu="same-origin",Ru="SAMEORIGIN",jt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":fu,"X-Frame-Options":Ru}),Ur=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...jt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Xa=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Su=/^[\x20-\x7E]+$/,gu=/^[\w.+-]+\/[\w.+-]+/,ao=e=>e&&Su.test(e)&&gu.test(e)?e:null,bu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Za=e=>encodeURIComponent(e.replace(bu,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),ei=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),hr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},ti={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},$r=e=>typeof e=="string"&&Object.hasOwn(ti,e),Br=e=>ti[e],mt="Attachment request failed";var it=e=>{let t=ie("limit",e.limit,1),r=ie("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ie("queue.max",e.queue.max,0),maxPerOwner:ie("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ie("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,s=(y,S)=>y.get(S)??0,c=(y,S,A)=>{let D=s(y,S)+A;D<=0?y.delete(S):y.set(S,D)},d=y=>s(l,y)<r,u=y=>o<t&&d(y),R=y=>(o+=1,c(l,y,1),h(y)),p=()=>{let y=-1,S=r;for(let[A,D]of a.entries()){let f=s(l,D.owner);if(f<S&&(y=A,S=f,f===0))break}return y},m=()=>{for(;o<t;){let y=p();if(y<0)return;let[S]=a.splice(y,1);c(i,S.owner,-1),S.grant(R(S.owner))}},h=y=>{let S=!1;return()=>{S||(S=!0,o-=1,c(l,y,-1),m())}};return{canAcquire:u,acquire:(y,S)=>{if(S.aborted)return Promise.resolve(null);if(u(y))return Promise.resolve(R(y));if(n===null||a.length>=n.max||s(i,y)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:A}=n,D=f=>{let g=()=>{let V=a.indexOf(x);V<0||(a.splice(V,1),c(i,y,-1),_(),f(null))},P=Ge(g,A),_=()=>{clearTimeout(P),S.removeEventListener("abort",g)},x={owner:y,grant:V=>{_(),f(V)}};a.push(x),c(i,y,1),S.addEventListener("abort",g,{once:!0})};return new Promise(D)}}};var Du=1024,io="Too many requests",Au=(e,t)=>{ie("limitPerWindow",e,1),ie("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 s=l??{tokens:e,lastRefillMs:i};n(s,i),r.set(a,s);for(let c of r.keys()){if(r.size<=Du)break;r.delete(c)}return s};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let s=r.get(a);s&&(n(s,i),s.tokens=Math.min(e,s.tokens+l))}}},yt=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ie("windowMs",r,1e3)%1e3!==0)throw K("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=Au(e.limitPerWindow,r),i=Object.freeze({status:429,message:io,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Ie({windowMs:r,tallies:[t],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`${t}_suppressed count=${c} since=${d} ${o(s)}`)}});return{spend:(s,c)=>a.consume(s,se())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,se(),c)}}};var Eu=256*1024,ri=6e4,wu=e=>Math.ceil(e/2),Iu=new Uint8Array(new ArrayBuffer(0)),_u=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Iu,t()},i=l=>{clearTimeout(o),o=Ge(()=>{l.error(new Error(`attachment body idle for ${ri} ms`)),a()},ri)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+Eu,r.byteLength);if(s>n&&l.enqueue(r.slice(n,s)),n=s,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},ni=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=yt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=it({limit:e.concurrency,maxHeldPerOwner:wu(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:R,readAttachment:p,cookie:m,fail:h}=s,y=e.maxBytes,S=i.spend(R,`attachment=${u} viewer=${R}`);if(S)return h(S.status,S.message,S.headers);let A=await n(c,"initial");if(!A.ok)return h(503,hr[503],be(503));let D=await t.getAttachmentForUser(A.scope,u,R);if(!D)return o.warn(`404 attachment=${u} viewer=${R} reason=not_visible`),h(404,"Attachment not found");if(D.fileSize!=null&&D.fileSize>y)return o.warn(`413 attachment=${u} viewer=${R} reason=db_size`),h(413,"Attachment too large");let f=ao(D.fileType),g=`filename="${ei(D.fileName)}"; filename*=UTF-8''${Za(D.fileName)}`,P=await l.acquire(R,c.signal);if(!P)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${R} reason=aborted`),h(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${R} reason=concurrency`),h(503,"Too many concurrent downloads",be(503)));let _=!1;try{let x=await p(D.filePath,{maxBytes:y,head:c.method==="HEAD",principal:r(R),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${R} reason=aborted`),h(503,"Attachment request aborted");if(!x.ok){if(!$r(x.reason))return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=failure_reason`),h(500,mt);let B=Br(x.reason);return x.reason==="not_found"&&a(u,!1),o.warn(`${B} attachment=${u} viewer=${R} reason=${x.reason} code=${x.code??"-"}`),h(B,hr[B],be(B))}if(x.bytes.byteLength>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),h(500,mt);let V=c.method==="HEAD";if(V&&x.size!==void 0&&x.size>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),h(500,mt);if(!V&&x.size!==void 0&&x.size!==x.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=size_mismatch`),h(500,mt);let L=f??ao(x.contentType),v=L!==null&&Xa.has(L),k=v?L:"application/octet-stream",$=v&&d.kind!=="download"?"inline":"attachment",T=V?x.size:x.bytes.byteLength,w=new Headers({"Content-Type":k,"Content-Disposition":`${$}; ${g}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...jt});return T!==void 0&&w.set("Content-Length",String(T)),m&&w.append("Set-Cookie",m),a(u,!0),o.info(`200 attachment=${u} viewer=${R} type=${k} disposition=${$} bytes=${T??"-"}`),V?new Response(null,{status:200,headers:w}):(_=!0,new Response(_u(x.bytes,P),{status:200,headers:w}))}finally{_||P()}}};var Ue=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),bf=Ue.queueWaitMs+Ue.readMs+Ue.renderMs+Ue.transferMarginMs;import{Buffer as xu}from"buffer";var ii=new Set([194,198,202,206]),Cu=new Set([192,193,194,195]),si=216,Mu=217,li=218,Pu=4,ku=64,Lu=2,oi=8,ai=28,Tt=12,so=8,vu=20,ci=Tt+so+10,Nu=2,ht=(e,t)=>e[t]<<8|e[t+1],zt=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},st=(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},ui=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,di=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),pi=e=>(e.stepsLeft-=1,e.stepsLeft>=0),mi=e=>e[0]===255&&e[1]===si,yi=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!pi(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===Mu)return"eoi";if(o===0||o===si)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=ht(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")}},Ou=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!pi(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}},hi=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=ht(e,r+1),a=ht(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let s=0;s<i;s+=1){let c=e[r+7+3*s],d=c>>4,u=c&15;if(d<1||d>4||u<1||u>4)return null;l.push({id:e[r+6+3*s],horizontal:d,vertical:u})}return{marker:t,width:a,height:o,components:l}},fi=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>Pu||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},Ri=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:ii.has(e.marker)||t<e.components.length}),lo=e=>{if(!mi(e))return null;let t=di(e.byteLength),r=null;for(let n=2;;){if(yi(e,n,t)!=="segment")return null;if(ui(t.marker)){if(r!==null||(r=hi(e,t),r===null))return null}else if(t.marker===li){if(r===null)return null;let o=fi(e,t);return o===null?null:Ri(r,o.length)}n=t.end}},Si=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*oi)),i=Math.ceil(e.height*o/(r*oi));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},gi=e=>e.multiScan?Si(e).reduce((r,n)=>r+n,0)*ku*Lu:0,Hu=896,bi=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!mi(e))return null;let n=xu.from(e.buffer,e.byteOffset,e.byteLength),o=di(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let R=yi(e,u,o);if(R===null)return null;if(R==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,ui(o.marker)){if(a!==null||!Cu.has(o.marker)||(a=hi(e,o),a===null))return null;let p=Si(a);l=new Map;for(let[m,h]of a.components.entries()){let y=l.get(h.id);l.set(h.id,y===void 0?p[m]:Math.max(y,p[m]))}s=a.components.length*(ii.has(a.marker)?Hu:1)}else if(o.marker===li){if(a===null||d===s)return null;let p=fi(e,o);if(p===null)return null;for(let h of p){let y=l.get(h);if(y===void 0)return null;c+=y}if(d+=1,i===null&&(i=Ri(a,p.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let m=Ou(n,o.end,o);if(m===null)return null;u=m}}},Di=e=>{if(e.byteLength<24||ht(e,8)!==0||ht(e,10)!==13||!st(e,12,"IHDR"))return null;let t=ht(e,16)*65536+ht(e,18),r=ht(e,20)*65536+ht(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Fu=e=>{if(st(e,Tt,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=zt(e,26,2)&16383,r=zt(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(st(e,Tt,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=zt(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return st(e,Tt,"VP8X")?e.byteLength<ci?null:{width:zt(e,24,3)+1,height:zt(e,27,3)+1}:null},Ai=e=>{if(Di(e)===null||e.byteLength<=ai)return null;switch(e[ai]){case 0:return!1;case 1:return!0;default:return null}},Ti=(e,t)=>{if(st(e,Tt,"VP8 "))return"lossy";if(st(e,Tt,"VP8L"))return"lossless";if(!st(e,Tt,"VP8X")||e.byteLength<ci)return null;if((e[vu]&Nu)!==0)return"animated";let r=!1,n=t;for(let o=Tt;o+so<=e.byteLength;){if(n-=1,n<0)return null;if(st(e,o,"VP8L"))return"lossless";if(st(e,o,"VP8 "))return r?"lossy-alpha":"lossy";st(e,o,"ALPH")&&(r=!0);let a=zt(e,o+4,4);o+=so+a+a%2}return null},Ei={png:Di,jpeg:lo,webp:Fu};var co=Object.freeze(["image/webp","image/jpeg","image/png"]),uo=1024*1024;var Uu=new Set(["image/png","image/jpeg","image/gif","image/webp"]),$u={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Bu=new Set(co),Vu=e=>typeof e=="string"&&Bu.has(e),qu=256,Vr=(e,t)=>e.fileType===null||!Uu.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Yu=[137,80,78,71,13,10,26,10],Wu=[255,216,255],ju=[[71,73,70,56,55,97],[71,73,70,56,57,97]],zu=[82,73,70,70],Gu=[87,69,66,80],fr=(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},po=e=>{if(fr(e,Yu,0))return"png";if(fr(e,Wu,0))return"jpeg";for(let t of ju)if(fr(e,t,0))return"gif";return fr(e,zu,0)&&fr(e,Gu,8)?"webp":null},wi=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:Wa([t])}},Ii=(e,t)=>{if(!Vu(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>uo)return"too_large";let r=$u[e.contentType];if(po(e.bytes)!==r)return"signature";let n=Ei[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},_i=e=>{ie("maxBytes",e.maxBytes,0),ie("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=o=>{let a=t.get(o);a&&(t.delete(o),r-=a.weight)};return{get:o=>{let a=t.get(o);if(a)return t.delete(o),t.set(o,a),a.entry},set:(o,a)=>{n(o);let i=(a.kind==="thumbnail"?a.bytes.byteLength:0)+qu;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 s of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(s)}}}};var mo=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=se(),l=new AbortController,s=!1,c,d,u=()=>{a(se()-i)},R=f=>{c=Ge(()=>{s=!0,f({timedOut:!0}),d=Ge(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},p=new Promise(R),m=AbortSignal.any([r,l.signal]),h=f=>{f(n(m))},y=new Promise(h),S=f=>(clearTimeout(c),clearTimeout(d),s&&o(se()-i,f.kind==="error"?{error:f.error}:null),f),A=y.then(f=>S({kind:"value",value:f}),f=>S({kind:"error",error:f}));return{outcome:Promise.race([y.then(f=>({timedOut:!1,value:f})),p]),settled:A}};var ft={404:"Attachment not found",500:mt,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},xi=(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=Ii(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Ku=e=>{let t=new AbortController,r=()=>{t.abort()},n=Ge(r,Ue.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Ci=()=>{},Ju=(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)}),Mi=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,s=(p,m)=>{let h=m.then(Ci,Ci);l.set(p,h);let y=()=>{l.get(p)===h&&l.delete(p)};h.then(y)},c=async(p,m)=>{let h=l.get(p.key);if(h===void 0)return t.acquire(p.owner,m);let y=Ku(m);try{if(await Ju(h,y.signal),y.signal.aborted)return null;let S=r.get(p.key);return S!==void 0?{...S,identity:"verified"}:await t.acquire(p.owner,y.signal)}finally{y.end()}},d=(p,m)=>{if(p.fileSize===null)return m.kind==="exact"?"verified":"unrecorded";if(m.kind==="exact"?m.bytes===p.fileSize:p.fileSize>m.maxBytes)return"verified";let y=m.kind==="exact"?String(m.bytes):`>${m.maxBytes}`;return i.warn(`size_mismatch expected=${p.fileSize} got=${y} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail`),"unverified"},u=(p,m)=>(h,y)=>{let S=y===null?"":` message=${y.error instanceof Error?y.error.message:"unknown"}`;i.warn(`${p}_overrun ms=${h} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail${S}`)},R=(p,m)=>h=>{i.warn(`${p}_stuck ms=${h} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`)};return async(p,m)=>{let h=await c(p,m);if(h===null)return{kind:"failure",status:503,reason:m.aborted?"aborted":"queue"};if(typeof h!="function")return h;let y=h,S=null;try{if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let A=r.get(p.key);if(A!==void 0)return{...A,identity:"verified"};let D=mo({budgetMs:Ue.readMs,flightSignal:m,call:B=>p.readAttachment(p.filePath,{maxBytes:n,head:!1,principal:o(p.owner),signal:B}),onOverrun:u("read",p),onStuck:R("read",p)}),f=await D.outcome;if(f.timedOut)return S=D.settled,m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let g=f.value;if(!g.ok&&g.reason!=="too_large")return $r(g.reason)?(g.reason==="not_found"&&a(p.attachmentId,!1),{kind:"failure",status:Br(g.reason),reason:g.reason,code:g.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(g.ok&&g.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let P=d(p,g.ok?{kind:"exact",bytes:g.bytes.byteLength}:{kind:"over",maxBytes:n}),_=B=>{P==="verified"&&r.set(p.key,B)},x=B=>(_(B),{...B,identity:P});if(!g.ok)return x({kind:"unrenderable",reason:"too_large"});let V=po(g.bytes);if(V===null)return x({kind:"unrenderable",reason:"signature"});let L=mo({budgetMs:Ue.renderMs,flightSignal:m,call:B=>p.renderer.render(g.bytes,{format:V,maxWidth:p.box.maxWidth,maxHeight:p.box.maxHeight,signal:B}),onOverrun:u("render",p),onStuck:R("render",p)}),v=B=>{if(B.kind==="error")return;let G=xi(B.value,p.box);"entry"in G&&_(G.entry)},k=null,$=()=>(k===null&&(k=L.settled.then(v),s(p.key,k)),k);m.addEventListener("abort",$,{once:!0});let T=await L.outcome.finally(()=>m.removeEventListener("abort",$));if(T.timedOut||m.aborted)return S=$(),m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let w=xi(T.value,p.box);return"entry"in w?x(w.entry):w.failure}finally{S===null?y():S.then(y,y)}}};var Pi=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let s=new AbortController,c=()=>{e.get(t)?.controller===s&&e.delete(t)},u={promise:n(s.signal).finally(c),controller:s,waiters:0};return e.set(t,u),u},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 vi=10,Qu=1/vi,ki=1-Qu,Xu=1024,Zu=64,ed=8,Li="private, no-cache",td="no-store",rd=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),nd=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Ni=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(f,g)=>yt({reason:f,limitPerWindow:g,windowMs:6e4,logger:o,windowFields:P=>`viewer=${P} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*vi),R=it({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:Zu,maxPerOwner:ed,maxWaitMs:Ue.queueWaitMs}}),p=_i({maxBytes:l.cacheBytes,maxEntries:Xu}),m=Pi(),h=Mi({gate:R,cache:p,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),y=(f,g,P,_)=>{let x=`attachment=${f.attachmentId} viewer=${f.internalUserId} variant=thumbnail cache=${_}`;if(g.kind==="failure")return o[nd(g)](`${g.status} ${x} reason=${g.reason} code=${g.code??"-"}`),f.fail(g.status,ft[g.status],be(g.status));let V=rd[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${x} reason=${g.reason}${V}`),f.fail(404,ft[404]);let L=g.identity==="verified"?{"Cache-Control":Li,ETag:P}:{"Cache-Control":td},v=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...L,"Content-Security-Policy":"default-src 'none'; sandbox",...jt});return f.cookie&&v.append("Set-Cookie",f.cookie),o.info(`200 ${x} type=${g.contentType} bytes=${g.bytes.byteLength}${V}`),new Response(g.bytes,{status:200,headers:v})},S=(f,g)=>{let P=f.spend(g.internalUserId,`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail`);return P===null?null:g.fail(P.status,P.message,P.headers)},A=f=>S(d,f),D=(f,g)=>g?S(u,f):A(f);return async(f,g)=>{let{request:P,attachmentId:_,internalUserId:x,readAttachment:V,cookie:L,fail:v}=f,k=Qn[g],$=P.headers.get("If-None-Match"),T=$!==null,w=D(f,T);if(w)return w;let B=await n(P,"initial");if(!B.ok)return v(503,ft[503],be(503));let G=await t.getAttachmentForUser(B.scope,_,x),j=G!==null&&Vr(G,i)?wi({rendererId:s.id,box:k,attachmentId:_,filePath:G.filePath,fileType:G.fileType,fileSize:G.fileSize}):null;if(j&&eo($,j.etag)){let b=new Headers({"Cache-Control":Li,ETag:j.etag,...jt});return L&&b.append("Set-Cookie",L),o.info(`304 attachment=${_} viewer=${x} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:b})}if(T){let b=A(f);if(b)return b}if(!G)return o.warn(`404 attachment=${_} viewer=${x} variant=thumbnail reason=not_visible`),v(404,ft[404]);if(!j)return d.refund(x,ki),o.info(`404 attachment=${_} viewer=${x} variant=thumbnail reason=not_eligible`),v(404,ft[404]);let{key:pe,etag:ye}=j,J=p.get(pe);if(J)return d.refund(x,ki),y(f,{...J,identity:"verified"},ye,"hit");let Le=b=>h({key:pe,attachmentId:_,filePath:G.filePath,fileSize:G.fileSize,box:k,owner:x,readAttachment:V,renderer:s},b),Q;try{Q=await m.join(pe,P.signal,Le)}catch(b){return o.error(`500 attachment=${_} viewer=${x} variant=thumbnail cache=miss reason=port_exception message=${b instanceof Error?b.message:"unknown"}`),v(500,ft[500])}return y(f,Q,ye,"miss")}};var od='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',ad=()=>Ur(403,oo,{cookie:null}),Oi=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=Xn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>Ur(404,hr[404],{cookie:null}),crossSiteRejection:ad}),Hi=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:Qa(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:ni({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Ni({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,R=(p,m,h={})=>Ur(p,m,{cookie:u,extraHeaders:h});try{let{user:p,cookie:m}=await t(c,{failureRedirect:null});if(u=m??null,!p)return R(401,"Unauthorized");let h=Xn(new URL(c.url).searchParams);if(h.kind==="invalid")return R(400,"Invalid attachment request");if(h.kind==="thumbnail"&&c.method!=="GET")return R(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return R(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return R(404,"Attachment not found");if(d.token===void 0)throw new Error(od);let y=s.idCodec.decode(d.token);if(y===null||!nt(y))return R(400,"Invalid attachment token");let S=await r.getUserIdByExternalId(p.id);if(!S)return R(403,"Forbidden");let A={request:c,delivery:h,attachmentId:y,internalUserId:S,readAttachment:s.read,cookie:u,fail:R};return h.kind!=="thumbnail"?await s.serveOriginal(A):s.serveThumbnail===null?R(404,ft[404]):await s.serveThumbnail(A,h.variant)}catch(p){if(p instanceof Response)throw p;return a.error(`500 attachment=? viewer=? reason=unexpected message=${p instanceof Error?p.message:"unknown"}`),R(500,mt)}}};var id=32*1024*1024,sd=60,ld=4,cd=120,ud=2,dd=8*1024*1024,qr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pd=e=>{if(e===void 0)throw rt("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!qr(e))throw K("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw rt("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw K("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw K("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},md=e=>{if(e===void 0)return null;if(!qr(e))throw K("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:pd(e.renderer),rateLimitPerMinute:Pe("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,cd),concurrency:Pe("attachments.thumbnails.concurrency",e.concurrency,1,ud),cacheBytes:Pe("attachments.thumbnails.cacheBytes",e.cacheBytes,0,dd)})},Fi=e=>{let t=e;if(t===void 0)return null;if(!qr(t))throw K("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw rt("attachments.idCodec","injected when attachments is given");if(!qr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw K("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw rt("attachments.read","injected when attachments is given");if(typeof n!="function")throw K("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:Pe("attachments.maxBytes",t.maxBytes,1,id),rateLimitPerMinute:Pe("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,sd),concurrency:Pe("attachments.concurrency",t.concurrency,1,ld),thumbnails:md(t.thumbnails)})},yd=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"]]),Yr=e=>{for(let[t,r]of yd)if(Object.hasOwn(e,t))throw rt(r,`given in place of the flat key ${t}`)};var $i=8,hd=8*$i,fd=128,Rd=2,Bi=Rd*fd,Sd=4*Bi,gd=6e4,bd=6e4,Dd="Too many reads",Ui=Object.freeze(Object.keys(Ot).filter(e=>Ot[e].admission.includes("miss-gate"))),Vi=e=>{let t=it({limit:hd,maxHeldPerOwner:$i,queue:{max:Sd,maxPerOwner:Bi,maxWaitMs:gd}}),r=Ie({windowMs:bd,tallies:Ui,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${Ui.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}})}},Wr=(e,t,r)=>{let n=e(t,r,{error:{message:Dd}},503);for(let[o,a]of Object.entries(be(503)))n.headers.set(o,a);return n};var qi=e=>{let t=e.get(Re.cursorReportHubId),r=e.get(Re.cursorBusinessDate),n=e.get(Re.cursorSnapshot),o=ba(n)?n:null,a=null;if(t!==null){let l=ze(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!ga(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=mr(e.get(Re.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var jr=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Ad=2,Td=16,Ed=Ad*Td,wd=6e4,Yi=()=>{},Id=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Wi=e=>{let t=it({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:Ed,queue:null}),r=Ie({windowMs:wd,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 Yi;if(a.aborted){if(t.canAcquire(n))return Yi}else{let i=await t.acquire(n,a);if(i!==null)return Id(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var zr=30,Ji=4e3,_d="stream interrupted by server error",xd="Too many streams",Cd=15e3,Qi=Symbol("ids-stream-heartbeat"),ji=()=>{},zi=e=>e.return(void 0).then(ji,ji),Md=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(Qi),Cd)}),stop:()=>clearTimeout(e)}};async function*Gi(e,t,r,n){let o=t?Ta(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:Ji),e.length),l=Wt(e,o,i),s=i>o?e[i-1]:void 0;o=i;let c=o>=e.length;if(yield{kind:"chunk",...l,nextCursor:c||s===void 0?null:{businessDate:s.businessDate,reportHubId:s.reportHubId},isLast:c,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,c)return}}var Xi=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...at});return e&&t.append("Set-Cookie",e),t},Ki=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await zi(t);try{d.close()}catch{}},i=new TextEncoder,l=!1,s=null,c=new ReadableStream({async pull(d){if(l||r.aborted){await a(d,!0);return}let u=Md();try{s===null&&(s=t.next());let R=await Promise.race([s,u.fired]);if(u.stop(),R===Qi){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
|
|
2
2
|
`));return}s=null;let{value:p,done:m}=R;if(m){await a(d,!1);return}if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`${JSON.stringify(p)}
|
|
3
|
-
`))}catch(R){if(u.stop(),s=null,o(),l||r.aborted)return;R instanceof
|
|
4
|
-
`)),d.close()}catch{}}},cancel(){l=!0,o(),
|
|
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`],ip=["","\u30A2","\u4F50"," "],sp=()=>JSON.stringify(ap.map(e=>qr(e,8))),lp=e=>`dr-search-v${Hd};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var cp=async()=>{let e=Cd("sha256");e.update(JSON.stringify($r));for(let t of ip)await Yi(),e.update("\0"),e.update(ao(op(t)));return await Yi(),e.update("\0"),e.update(sp()),lp(e.digest("hex"))},up=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},uo=up(cp);var pp=/^-+/u,mp=/\s+/u,os=e=>{let t=pp.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},yp=(e,t)=>{let r=[...os(e).map(n=>({text:n,tier:Et.word})),...t.flatMap(n=>os(n).map(o=>({text:o,tier:Et.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},hp=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),Yr=(e,t)=>{if(e.length>Te.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of dp(Vr(e),t).sets){let i=[],l=new Set;for(let c of a.split(mp)){let d=Ur(c);if(d.length===0)return{ok:!1,reason:"blank-word"};if(d.length>Te.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=yp(d,Qi(c)),R=hp(u);l.has(R)||(l.add(R),i.push({alternatives:u}))}if(i.length>Te.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let s=JSON.stringify([...l].sort());n.has(s)||(n.add(s),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>Te.maxSets?{ok:!1,reason:"too-many-sets"}:o>Te.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},lr=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var PR=Object.freeze({sourceTypes:null,authors:null,customers:null}),fp=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,as=(e,t,r)=>{if(fa(e)&&fp(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=Yr(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var is=6e4,Rp=1,Sp=3200,ss=2e3,gp=Object.freeze({search:Sp,reports:ss,"search-marks":ss,"search-facets":null}),bp=(e,t)=>{let r=gp[e];return r===null?null:{max:t,maxPerOwner:wr,maxWaitMs:r}},cr=e=>{let{concurrency:t,route:r,logger:n}=e,o=at({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:is,logger:n,windowFields:()=>`route=${r}`}),a=Xe({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:bp(r,t)}),i=Object.freeze({status:429,message:Kn,headers:Object.freeze({"Retry-After":String(Rp)})}),l=Ce({windowMs:is,tallies:["busy"],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`busy_suppressed count=${c} since=${d} route=${r} concurrency=${t}`)}});return{admit:async(s,c)=>{let d=o.spend(s,r);if(d!==null)return{refusal:d};let u=await a.acquire(s,c);return u!==null?{release:u}:(o.refund(s,1),c.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};import{systemSseRuntime as Cp}from"@aiquants/sse";import{createSseResponse as Mp,readLastEventId as Pp,startSseHeartbeat as Lp,terminalStreamResponse as kp}from"@aiquants/sse/server";var ur=(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=In.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});return{entry:Object.freeze({id:e.id,message:a}),json:n}},ls=new WeakMap,cs=(e,t,r)=>{let n=ls.get(e);n===void 0&&(n=new Map,ls.set(e,n));let o=n.get(t);if(o!==void 0)return o;let a=r();return n.set(t,a),a},po=e=>e,Dp=e=>{switch(e.type){case"connected":case"report-delete":return po(e);case"status-update":case"comment-add":case"comment-delete":{let{recipientRawUserId:t,...r}=e;return po(r)}}},Ap=(e,t,r)=>{let{recipientRawUserId:n,actorRawUserId:o,...a}=e,i=r?{...a.report,externalComments:[],postedComments:[]}:a.report;return po({...a,report:i,viewerIsActor:t})},us=(e,t,r)=>{let{parsed:n}=e;if(n.type!=="report-create"&&n.type!=="report-update"&&n.type!=="report-publish")return cs(e,"every-viewer",()=>JSON.stringify(Dp(n)));let o=n.actorRawUserId===t;return cs(e,`${o?"actor":"observer"}${r?"-comments-redacted":""}`,()=>JSON.stringify(Ap(n,o,r)))};import{systemSseRuntime as Tp}from"@aiquants/sse";import{createSharedSource as Ep}from"@aiquants/sse/shared-source";var pt="daily-report:ids:",mo=(e,t)=>`${e}st:${t}`,yo=e=>`${pt}user:${e}:`,ds=(e,t)=>mo(yo(e),t),$t=e=>`daily-report:date:${e}:user:`,Bt=(e,t)=>`${$t(e)}${t}:`,ps=(e,t,r)=>mo(Bt(e,t),r),Fe=e=>`daily-report:detail:${e}:user:`,ho=(e,t)=>`${Fe(e)}${t}:`,ms=(e,t,r)=>mo(ho(e,t),r);var mt=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},wp=5e3,Ip=Ir,dr=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 Ep({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:Tp,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:wp,COUNT:Ip});if(i)for(let l of i)for(let s of l.messages){a=s.id;let{entry:c,json:d}=ur(s,this._logger);this._invalidateCaches(d),r.next(c)}}}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(pt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Fe(n))}};var _p=6e4,pr="Report visibility is unavailable",ys=["initial","refresh"],hs=Object.freeze({ok:!1}),xp=e=>e===null?"null":Array.isArray(e)?"array":typeof e,fs=(e,t)=>{let r=Ce({windowMs:_p,tallies:ys,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{t.error(`visibility_unavailable_suppressed count=${o} since=${a} cause=${n} reasons=${ys.map(l=>`${l}:${i[l]}`).join(",")}`)}});return async(n,o)=>{let a;try{a=await e(n,{reason:o})}catch(l){return r.record("port_failure",o,()=>t.error(`visibility unavailable cause=port_failure reason=${o}`,l)),hs}let i=Vi(a);return i===null?(r.record("port_contract",o,()=>t.error(`visibility unavailable cause=port_contract reason=${o} answer=${xp(a)}`)),hs):{ok:!0,scope:i}}},Rs=(e,t,r)=>{let n=e(t,r,{error:{message:pr}},503);for(let[o,a]of Object.entries(Re(503)))n.headers.set(o,a);return n};var bs=Object.freeze({...nr,route:"sse",frameworkDataRefusal:_r}),Ss=864e5,Np={baseMs:2e3,jitterMs:8e3},Ds=6e4,fo=Ir,As=JSON.stringify({type:"connected"}),gs="0-0",vp=(e,t,r)=>{if(t===null&&r===null)return!0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return ge(t,e.report.sourceType);case"comment-add":case"comment-delete":return ge(r,e.sourceType);case"report-delete":return ge(t,e.sourceType)}},Op=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!ge(t,e.report.sourceType),Fp=(e,t)=>{e.writeEvent({event:null,id:t,data:As})},Hp=(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||!vp(o,r.visibleSet,r.commentableSet)){Fp(e,t.id);return}e.writeEvent({event:null,id:t.id,data:us(n,r.internalUserId,Op(o,r.commentableSet))})},Ts=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:s}=e,c=async(d,u)=>{let{request:R,internalUserId:p,cursor:m}=u,h=u.initialScope.visible,y=u.initialScope.commentable,S=0,A=setInterval(()=>{let L=++S;n(R,"refresh").then(F=>{if(L===S){if(!F.ok){d.close();return}h=F.scope.visible,y=F.scope.commentable}})},Ds);d.onClose(()=>clearInterval(A));let D=m===null?gs:m,f=m!==null&&o!==void 0,b=[],C=null,w=L=>{mt(L.id,D)||(D=L.id,Hp(d,L,{internalUserId:p,visibleSet:h,commentableSet:y}))},I=async(L,F)=>{let[T]=await L.xRange(i,"-","+",{COUNT:1});return T!==void 0&&!mt(T.id,F)},$=async(L,F)=>{if(await I(L,F))return!1;let T=F;for(;;){let _=await L.xRange(i,T,"+",{COUNT:fo}),U=_[0];if(U!==void 0&&U.id!==T&&await I(L,T))return!1;for(let X of _){if(C!==null&&mt(C,X.id))return!0;mt(X.id,D)||w(ur(X,s).entry)}let z=_.at(-1);if(_.length<fo||z===void 0||d.isClosed())return!0;T=z.id}},N=a.subscribe(L=>{if(!f){w(L);return}mt(L.id,D)||(C===null&&(C=L.id),b.push(L))},L=>{s.error(`[SSE:${p}] Fan-Out reader error:`,L),d.close()});if(d.onClose(N),m===null){await a.ready();try{let L=await o?.getClient();if(L){let F=await L.xRevRange(i,"+","-",{COUNT:1});F.length>0&&!mt(F[0].id,D)&&(D=F[0].id)}}catch{}}if(d.writeEvent({event:null,id:D===gs?null:D,data:As}),Lp(d,{intervalMs:Qo,retry:Np,runtime:Cp}),m===null||o===void 0)return;await a.ready();let v=await o.getClient();if(v===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await $(v,m)){d.writeRetry(Ss),d.writeEvent({event:"resync-required",id:null,data:""}),d.close();return}f=!1;for(let L of b.splice(0))w(L)};return async({request:d,params:u})=>{let R,p=()=>{let h=new Headers;R!==void 0&&h.append("Set-Cookie",R);for(let[y,S]of Object.entries(Qe))h.set(y,S);return h},m=h=>kp(h,{data:"",retryMs:Ss,headers:p()});try{let h=await t(d,{failureRedirect:null});R=h.cookie;let{user:y}=h;if(!y)return m("auth-required");let S=await r.getUserIdByExternalId(y.id);if(!S)return m("forbidden");if(u.endpoint!=="updates")return new Response("Not Found",{status:404,headers:p()});let A=Pp(d,Xo);if(A!==null&&!Zo(A))return s.warn(`[SSE:${S}] malformed resume cursor; asking the client to resync`),m("resync-required");let D=vr(d),f=await l.admit(S,"sse",D);if(f===null){let C=p();for(let[w,I]of Object.entries(Re(503)))C.set(w,I);return new Response("Too many streams",{status:503,headers:C})}let b=!1;try{let C=await n(d,"initial");if(!C.ok){let I=p();for(let[$,N]of Object.entries(Re(503)))I.set($,N);return new Response(pr,{status:503,headers:I})}let w=C.scope;return Mp({requestSignal:D,headers:p(),onError:(I,$)=>s.error(`[SSE:${S}] ${$} failed:`,I),produce:I=>(b=!0,I.onClose(f),c(I,{request:d,internalUserId:S,cursor:A,initialScope:w}))})}finally{b||f()}}catch(h){if(h instanceof Response)throw h;let y=h instanceof Error?h:new Error(String(h));return s.error(`500 sse name=${y.name} message=${y.message}`),new Response("Internal Server Error",{status:500,headers:p()})}}};var Es=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...Qe});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},$p=Object.freeze({...nr,route:"api",frameworkDataRefusal:({params:e})=>Un(e.endpoint)&&wt[e.endpoint].body==="stream"?_r():null}),Bp=Object.freeze({...nr,route:"action"}),Vp=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),Cs=6e4,Ms=5,qp=Ms*Math.ceil(Cs/500),Yp=2,jp=6,Wp=6e4,zp=Ms*Yp*jp,Gp=2,Kp=10,Jp=2,Qp=10,ws=(e,t)=>Math.max(e,wr)*t,Ps=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},Xp=Object.freeze({etag:(e,t,r)=>Pa(e,t,r,200),"no-store":(e,t,r)=>Yn(t,r,200)}),Zp=e=>jn(e.body==="json"?Xp[e.cache]:null),Is=jn(null),_s=(e,t,r,n)=>Ps(e(t,r,{error:{message:n.message}},n.status),n.headers),xs=(e,t,r)=>Ps(e(t,r,null,503),Re(503));function Ro(e){kr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:ae("service.titleMaxLength",r.titleMaxLength,1)},{loginRedirectPath:s}=e;if(typeof s!="string"||s.trim()==="")throw K("loginRedirectPath","the non-blank path of the host's sign-in route",s);let c=he(e.logger,3,"API"),d=he(e.logger,3,"Visibility"),u=fs(zt("resolveVisibleSourceTypes",e.resolveVisibleSourceTypes),d),R=he(e.logger,1,"SSE"),p=he(e.logger,1,"Attachment"),m=he(e.logger,2,"Isolation"),h=he(e.logger,2,"Action"),y=he(e.logger,2,"Search"),S=he(e.logger,2,"Refresh"),A=he(e.logger,2,"Streams"),D=he(e.logger,2,"Reads"),f=at({reason:"refresh_rate_limit",limitPerWindow:zp,windowMs:Wp,logger:S,windowFields:()=>"route=api"}),b=Mi(A),C=_i(D),w=async(g,x,E,P,k,B)=>{let j=await r.getUserIdByExternalId(x.id);try{return await B(j===null?void 0:C.admissionFor(j,g,E.signal))}catch(H){if(H instanceof Ue)return Nr(k,E,P);throw H}},I=(g,x,E,P,k)=>{let B=f.spend(x.id,`endpoint=${g}`);return B===null?null:_s(k,E,P,B)},$=async({request:g})=>{let{user:x,cookie:E}=await t(g,{failureRedirect:s}),P=new Headers;E&&P.append("Set-Cookie",E);let k=await r.getUserIdByExternalId(x.id),B=k?n(k):null;return{data:{user:x,userId:B},headers:P}},N=g=>{let{limiter:x}=g;return async(E,P,k,B,j,H)=>{if(x===null)return H(k,P,{error:{message:"Unknown endpoint"}},404);let W=g.parse(E);if(!W.ok)return H(k,P,W.invalid,400);let M=await r.getUserIdByExternalId(B.id);if(!M)return H(k,P,g.emptyAnswer(W.parsed),200);let{signal:J}=k,Y=await x.admit(M,J);if("refusal"in Y)return J.aborted?xs(H,k,P):_s(H,k,P,Y.refusal);try{J.throwIfAborted();let Q=await g.read(W.parsed,{userId:M,user:B,scope:j},J);return J.throwIfAborted(),H(k,P,Q,200)}catch(Q){if(J.aborted&&Q===J.reason)return xs(H,k,P);throw Q}finally{Y.release()}}},v=r.searchLimits===null?null:cr({...r.searchLimits,route:se.search,logger:y}),L=r.searchLimits===null?null:cr({concurrency:ws(r.searchLimits.concurrency,Gp),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Kp,route:se.reports,logger:y}),F=r.searchLimits===null?null:cr({concurrency:ws(r.searchLimits.concurrency,Jp),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Qp,route:se.searchMarks,logger:y}),T=r.searchLimits===null?null:cr({...r.searchLimits,route:se.searchFacets,logger:y}),_={[se.businessDate]:async(g,x,E,P,k,B)=>{let j=g.searchParams.get(ye.businessDate),H=j===null?null:Lt(j);if(H===null)return B(E,x,{error:{message:"Invalid business date"}},400);let W=rr(g.searchParams.get(ye.forceRefresh));if(W===null)return B(E,x,{error:{message:"Invalid forceRefresh"}},400);let M=W?I(se.businessDate,P,E,x,B):null;return M!==null?M:w(se.businessDate,P,E,x,B,async J=>{let Y=await r.getDailyReportsByBusinessDateByExternalId(k,H,P.id,{forceRefresh:W,admission:J});return B(E,x,{businessDate:H,reports:Y},200)})},[se.idsStream]:Hi({service:r,logger:c,streamSlots:b,missGate:C,refuseForcedRead:(g,x,E,P)=>I(se.idsStream,g,x,E,P)}),[se.report]:async(g,x,E,P,k,B)=>{let j=Be(g.searchParams.get(ye.reportHubId));if(j===null)return B(E,x,{error:{message:"Invalid reportHubId"}},400);let H=rr(g.searchParams.get(ye.forceRefresh));if(H===null)return B(E,x,{error:{message:"Invalid forceRefresh"}},400);let W=H?I(se.report,P,E,x,B):null;return W!==null?W:w(se.report,P,E,x,B,async M=>{let J=await r.getDailyReportDetailByIdByExternalId(k,j,P.id,{snapshot:!0,forceRefresh:H,admission:M});return J?B(E,x,{report:J},200):B(E,x,{error:{message:"Report not found"}},404)})},[se.search]:N({limiter:v,parse:g=>{let x=g.searchParams.get(ye.searchQuery),E=Fn(g.searchParams.get(ye.searchCombine));if(x===null||E===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let P=Sa(g.searchParams,r.searchFilterSourceTypes);if(!P.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:P.reason}}};let k=as(x,E,P.filters);if(!k.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:k.reason}}};let{criteria:B}=k;return{ok:!0,parsed:{criteria:B,words:B.plan===null?[]:lr(B.plan)}}},emptyAnswer:({words:g})=>Nn([],g),read:async({criteria:g,words:x},{userId:E,scope:P})=>Nn(await r.searchDailyReports(P,E,g),x)}),[se.reports]:N({limiter:L,parse:g=>{let x=Hn(g.searchParams.get(ye.reportIds));return x===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:x}},emptyAnswer:()=>({reports:[]}),read:async(g,{user:x,scope:E})=>({reports:await r.getDailyReportDetailsByIdsByExternalId(E,g,x.id)})}),[se.searchMarks]:N({limiter:F,parse:g=>{let x=g.searchParams.get(ye.searchQuery),E=Fn(g.searchParams.get(ye.searchCombine));if(x===null||E===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let P=Yr(x,E);if(!P.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:P.reason}}};let k=Hn(g.searchParams.get(ye.reportIds));return k===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:P.plan,ids:k}}},emptyAnswer:({plan:g})=>({wordsDigest:Er(lr(g)),reports:[],deferred:[]}),read:({plan:g,ids:x},{userId:E,scope:P},k)=>r.markDailyReportSearchHits(P,E,g,x,{signal:k})}),[se.searchFacets]:N({limiter:T,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(g,{userId:x,scope:E})=>r.listDailyReportSearchFacets(E,x)})},U=async({request:g,params:x})=>{let{user:E,cookie:P}=await t(g,{failureRedirect:null}),k=P??null;if(!E)return Is(g,k,{error:{message:"Unauthorized"}},401);let B=x.endpoint;if(!Un(B))return Is(g,k,{error:{message:"Unknown endpoint"}},404);let j=wt[B],H=Zp(j),W=xa[j.body];if(!W.includes(g.method)){let J=H(g,k,{error:{message:"Method not allowed"}},405);return J.headers.set("Allow",W.join(", ")),J}let M=ie();try{let J=new URL(g.url),Y=await u(g,"initial"),Q=Y.ok?await _[B](J,k,g,E,Y.scope,H):Rs(H,g,k);return j.body==="json"&&c.debug(Q.headers.has("ETag")?`${Q.status} endpoint=${B} etag_match=${Q.status===304}`:`${Q.status} endpoint=${B}`),Q}catch(J){let Y=ie()-M,Q=J instanceof Error?J:new Error(String(J));return c.error(`500 endpoint=${B} elapsed=${Y}ms name=${Q.name} code=${"code"in Q?Q.code:"N/A"} message=${Q.message}`,Q),H(g,k,{error:{message:"Internal Server Error"}},500)}},z=_a(h),X=at({reason:"rate_limit",limitPerWindow:qp,windowMs:Cs,logger:h,windowFields:()=>"route=action"}),G=async(g,x,E,P,k)=>{let{clientTempId:B}=g;if(g.intent==="create")try{let M=await r.createDailyReport(E,x,g.businessDate,B);return k(g,M.reportHubId,{report:M})}catch(M){if(M instanceof Error&&M.message==="Forbidden")return P({error:"Creating reports is restricted"},{status:403});throw M}let{reportHubId:j,businessDate:H}=g,W=async(M,J)=>{try{let Y=await J(M.value);return k(M,j,{updatedStatus:{isStarred:Y.isStarred,isRead:Y.isRead},operationTimestamp:M.operationTimestamp})}catch(Y){if(Y instanceof Error&&Y.message==="Not Found")return P({error:"Report not found"},{status:404});throw Y}};switch(g.intent){case"update":try{return await r.updateDailyReport(E,j,x,g.changes,B),k(g,j,{})}catch(M){if(M instanceof Error){if(M.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(M.message==="Not Found")return P({error:"Report not found"},{status:404})}throw M}case"publish":try{let M=await r.publishDailyReport(E,j,x,B);return k(g,j,{report:M})}catch(M){if(M instanceof Error){if(M.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(M.message==="Not Found")return P({error:"Report not found"},{status:404})}throw M}case"delete":try{return await r.deleteDailyReport(E,j,x,B),k(g,j,{})}catch(M){if(M instanceof Error){if(M.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(M.message==="Not Found")return P({error:"Report not found"},{status:404})}throw M}case"toggleStar":return await W(g,M=>r.setStarStatus(E,x,j,H,M,B));case"toggleRead":return await W(g,M=>r.setReadStatus(E,x,j,H,M,B));case"addComment":try{let M=await r.addComment(E,x,j,g.content,H,B);return k(g,j,{newComment:M})}catch(M){if(M instanceof Error){if(M.message==="Not Found")return P({error:"Report not found"},{status:404});if(M.message.startsWith("Comments are restricted"))return P({error:"Comments are restricted for this report"},{status:403})}throw M}case"deleteComment":try{return await r.deleteComment(E,x,j,g.commentId,H,B),k(g,j,{deletedCommentId:g.commentId})}catch(M){if(M instanceof Error){if(M.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(M.message==="Not Found")return P({error:"Comment not found"},{status:404})}throw M}}},de=async({request:g,params:x})=>{let{user:E,cookie:P}=await t(g,{failureRedirect:null}),k=(H,W)=>Es(H,{...W,setCookie:P}),B=(H,W,M)=>Es(Vp(H,W,M),{setCookie:P});if(!E)return k({error:"Unauthorized"},{status:401});let j=ie();try{if(x.endpoint!==se.action)return k({error:"Unknown endpoint"},{status:404});let H=X.spend(E.id,"action");if(H!==null)return k({error:H.message},{status:H.status,headers:H.headers});let W=await Ia(g,l);if("refusal"in W){let{refusal:Q}=W;return Q.status===413&&z(Q.measuredBy),k({error:Q.error},{status:Q.status})}let{command:M}=W;if(M.intent==="clearCache"&&!e.enableDevCacheClear)return k({error:"Invalid intent"},{status:400});let J=await u(g,"initial");if(!J.ok)return k({error:pr},{status:503,headers:{...Re(503),"Cache-Control":"no-store"}});let Y=await r.getUserIdByExternalId(E.id);return Y?M.intent==="clearCache"?(await r.clearCache(),k({status:"OK",intent:"clearCache"})):await G(M,Y,J.scope,k,B):k({error:"User not found"},{status:404})}catch(H){if(H instanceof Response)throw H;let W=ie()-j,M=H instanceof Error?H:new Error(String(H));return c.error(`500 action elapsed=${W}ms name=${M.name} message=${M.message}`,M),k({error:"Internal Server Error"},{status:500})}},me=Ts({authenticate:t,service:r,resolveViewerScope:u,redis:o,sseReader:a,streamKey:i,streamSlots:b,logger:R}),Z=Ai({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:u,logger:p}),ve=va(m),O=(g,x)=>async E=>{let P=Na(E.request)?g.frameworkDataRefusal(E):null;if(P!==null)throw P;let k=Up(E.request,g);return k===void 0?x(E):(ve(g.route,k,E.request),g.crossSiteRejection())};return{index:{loader:$},api:{loader:O($p,U),action:O(Bp,de)},sse:{loader:O(bs,me)},attachment:{loader:O(Di,Z)}}}import{chunk as Km,MAX_IN_LIST as Jm,runWithTransactionRetry as Qm}from"@aiquants/mssql";import{asc as ct,eq as on,inArray as Sr}from"drizzle-orm";var em=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],tm=["document","comment"],rm=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],nm=["hubId","ordinal","authorUserId","commentText"],So=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Ls=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw mn(e,n,r)},ks=(e,t,r)=>{if(typeof t!="object"||t===null)throw K(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw K(`${e}.${o}`,"a column",n[o])},Ns=(e,t)=>{if(!So(e))throw K("search","a plain object",e);Ls("search key",e,em);let{tables:r}=e;if(!So(r))throw K("search.tables","a plain object with document and comment",r);Ls("search.tables key",r,tm),ks("search.tables.document",r.document,rm),ks("search.tables.comment",r.comment,nm);let n=new Map;if(e.externalSourceTexts!==void 0){if(!So(e.externalSourceTexts))throw K("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw mn("search.externalSourceTexts key",o,t);if(typeof a!="function")throw K(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:ae("search.concurrency",e.concurrency,1),rateLimitPerMinute:ae("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var yt=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},It=(e,t)=>{let r=typeof e=="string"?Be(e):typeof e=="number"&&Ke(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},_t=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};import{sql as V}from"drizzle-orm";import{sql as ht}from"drizzle-orm";var vs=e=>{if(e.length===0)throw new Error("[daily-report] draft rule: draftLabelNames must hold at least one name (a rule without names would show every draft to every viewer)");return ht.join(e.map(t=>ht`${t}`),ht`, `)},Wr=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return ht`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${vs(t)}))`},Os=(e,t)=>{let{hubLabel:r,label:n}=e;return ht`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${vs(t)}))`},zr=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?ht`${o.userId} = ${t} OR ${o.userId} IS NULL`:ht`${o.userId} = ${t}`;return ht`(${a} OR NOT ${Wr(e,r)})`};var om=/[[%_]/gu,am=e=>e.replace(om,t=>`[${t}]`),Fs=e=>`%${am(e)}%`;var je=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),xt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),yr=Object.freeze({value:"value"}),Ee=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),q=e=>V`${V.identifier(e.name)}`,mr=e=>V.join(e.map(t=>V`${t}`),V`, `),Hs=(e,t)=>V`SELECT ${q(e.id)} AS ${V.identifier(Ee.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${mr(t)}) ORDER BY ${e.id}`,im=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>Fs(u.text)),l=V.join(i.map(u=>V`${o.searchText} LIKE ${u}`),V` OR `),s=V.join(i.map(u=>V`${a.commentText} LIKE ${u}`),V` OR `),c=sr(n.sourceType,r.scope.commentable),d=c===void 0?V``:V` AND (${c} OR ${a.authorUserId} = ${r.userId})`;return V`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${s})${d}))`},Us=(e,t,r)=>V`(${V.join(t.words.map(n=>im(e,n,r)),V` AND `)})`,go=(e,t,r,n)=>{let{hub:o}=e,a=[V`${o.deletedAt} IS NULL`,zr(e,t.userId,r,"author")],i=sr(o.sourceType,t.scope.visible);return i!==void 0&&a.push(i),n!==void 0&&a.push(V`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},sm=(e,t)=>{let{hub:r}=e,{document:n}=e.search,o=[];if(t.sourceTypes!==null){if(t.sourceTypes.size===0)throw new Error("[daily-report] search: a source-type filter must hold at least one source type");o.push(V`LOWER(${r.sourceType}) IN (${mr([...t.sourceTypes])})`)}return t.authors!==null&&o.push(V`${n.authorName} IN (${mr(t.authors)})`),t.customers!==null&&o.push(V`${n.customerName} IN (${mr(t.customers)})`),o},$s=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,s=[...go(e,r,n,o),...sm(e,t.filters)];if(l!==null){let c=l.combine==="intersection"?V` AND `:V` OR `;s.push(V`(${V.join(l.sets.map(d=>Us(e,d,r)),c)})`)}return V`SELECT ${q(a.id)} AS ${V.identifier(je.reportHubId)}, CONVERT(char(10), ${q(a.businessDate)}, 23) AS ${V.identifier(je.businessDate)}, ${q(a.sourceType)} AS ${V.identifier(je.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${V.join(s,V` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},Bs=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=V.join(t.sets.map((s,c)=>V`(CASE WHEN ${Us(e,s,r)} THEN ${2**c} ELSE 0 END)`),V` + `);return V`SELECT ${q(a.id)} AS ${V.identifier(xt.reportHubId)}, ${l} AS ${V.identifier(xt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${V.join(go(e,r,n,o),V` AND `)}`},Vs=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...go(e,r,n),V`${i} IS NOT NULL`];return V`SELECT ${i} AS ${V.identifier(yr.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${V.join(l,V` AND `)} GROUP BY ${i} ORDER BY ${i}`},qs=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(s=>({[n.hubId.name]:s.hubId,[n.searchText.name]:s.searchText,[n.sourceDigest.name]:s.sourceDigest,[n.normalizerVersion.name]:r,[n.authorName.name]:s.authorName,[n.customerName.name]:s.customerName}))),i=JSON.stringify(t.flatMap(s=>s.comments.map(c=>({[o.hubId.name]:s.hubId,[o.ordinal.name]:c.ordinal,[o.authorUserId.name]:c.authorUserId,[o.commentText.name]:c.commentText})))),l=JSON.stringify(t.map(s=>s.hubId));return V`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${q(n.hubId)} bigint, ${q(n.searchText)} nvarchar(max), ${q(n.sourceDigest)} char(64), ${q(n.normalizerVersion)} varchar(64), ${q(n.authorName)} nvarchar(max), ${q(n.customerName)} nvarchar(max))) AS s ON t.${q(n.hubId)} = s.${q(n.hubId)}
|
|
8
|
-
WHEN MATCHED THEN UPDATE SET t.${
|
|
9
|
-
WHEN NOT MATCHED THEN INSERT (${
|
|
3
|
+
`))}catch(R){if(u.stop(),s=null,o(),l||r.aborted)return;R instanceof je||n.error(`ids-stream emission failed: ${R instanceof Error?R.message:String(R)}`);try{let p={kind:"error",error:_d};d.enqueue(i.encode(`${JSON.stringify(p)}
|
|
4
|
+
`)),d.close()}catch{}}},cancel(){l=!0,o(),zi(t)}});return new Response(c,{status:200,headers:Xi(e)})},Zi=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,s,c,d,u,R,p)=>{let m=!1,h=null,y=null,S=new Promise((f,g)=>{h=f,y=g});S.catch(()=>{});let A=t.getDailyReportIdsByExternalId(c,s.id,{forceRefresh:l.forceRefresh,admission:p,onFetchStart:l.cursor?void 0:()=>{m=!0,t.readSseStreamAnchor().then(f=>t.getDailyReportIdsFirstPageByExternalId(c,s.id,zr).then(g=>({items:g,streamAnchor:f}))).then(f=>h?.(f),f=>y?.(f))}});if(A.catch(()=>{}),l.cursor){let{items:f,streamAnchor:g,snapshot:P}=await A,_=l.snapshot!==null&&l.snapshot===P;return Ki(d,Gi(f,_?l.cursor:null,zr,{snapshot:P,restarted:!_,streamAnchor:g}),u,r,R)}let D=(async function*(){let f=await Promise.race([A.then(_=>({kind:"full",source:_}),_=>({kind:"full-error",error:_})),S.then(_=>({kind:"page",page:_}),()=>({kind:"page-error"}))]),g=null,P=!1;if(f.kind==="full")g=f.source;else if(f.kind==="page"){let{items:_,streamAnchor:x}=f.page;if(_.length<zr){yield{kind:"chunk",...Wt(_,0,_.length),nextCursor:null,isLast:!0,total:_.length,streamAnchor:x};return}yield{kind:"chunk",...Wt(_,0,_.length),nextCursor:null,isLast:!1,provisional:!0},P=!0}else if(f.kind==="full-error"&&m){let _=await S.catch(()=>null);_&&_.items.length>0&&(yield{kind:"chunk",...Wt(_.items,0,_.items.length),nextCursor:null,isLast:!1,provisional:!0})}g===null&&(g=await A),yield*Gi(g.items,null,P?Ji:zr,{snapshot:g.snapshot,streamAnchor:g.streamAnchor})})();return Ki(d,D,u,r,R)};return async(l,s,c,d,u,R)=>{let p=qi(l.searchParams);if("refused"in p)return R(c,s,{error:{message:p.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:m}=p;if(m.forceRefresh){let A=a(d,c,s,R);if(A!==null)return A}let h=jr(c),y=await t.getUserIdByExternalId(d.id),S=await n.admit(y,"ids-stream",h);if(S===null){let A=R(c,s,{error:{message:xd}},503);for(let[D,f]of Object.entries(be(503)))A.headers.set(D,f);return A}if(h.aborted)return new Response(null,{status:200,headers:Xi(s)});try{return await i(m,d,u,s,h,S,y===null?void 0:o.admissionFor(y,le.idsStream,h))}catch(A){if(S(),A instanceof je)return Wr(R,c,s);throw A}}};import{inArray as Pd,sql as Gr}from"drizzle-orm";var Ke="Internal",es=e=>e.trim().toLowerCase();var kd="",Ld=64,vd=e=>e.toLowerCase(),ts=e=>{let t=new Set;if(!Array.isArray(e))return t;for(let r of e){if(typeof r!="string")continue;let n=es(r);n.length>0&&t.add(n)}return t};function Ae(e,t){return e===null?!0:t==null?!1:e.has(vd(t))}function ve(e){return e!==null&&e.size===0}var Nd=4e3,ho=e=>{let t=e.getSQLType();if(!t.startsWith("nvarchar("))throw K("tables.hub.sourceType","an nvarchar(n) column with a declared length (source types compare as UTF-16 bytes)",t);return ie("tables.hub.sourceType.length",e.length,1,Nd)};function Sr(e,t){if(t===null)return;let r=ho(e),n=[...t].filter(a=>a.length<=r);if(n.length===0)return Gr`1 = 0`;let o=Gr.raw(`VARBINARY(${2*r})`);return Pd(Gr`CAST(LOWER(${e}) AS ${o})`,n.map(a=>Gr`CAST(${a} AS ${o})`))}var Gt,Kt,Rr=class Rr{constructor(t,r){An(this,Gt);An(this,Kt);Tn(this,Gt,t),Tn(this,Kt,r)}get visible(){return tr(this,Gt)===null?null:new Set(tr(this,Gt))}get commentable(){return tr(this,Kt)===null?null:new Set(tr(this,Kt))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=ts(r?t.read:t);if(!r||t.comment===void 0)return new Rr(n,n);let o=new Set;for(let a of ts(t.comment))n.has(a)&&o.add(a);return new Rr(n,o)}static unrestricted(t){return new Rr(null,null)}};Gt=new WeakMap,Kt=new WeakMap;var Je=Rr,yo=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),Od=new Set(["read","comment"]),ns=e=>{if(yo(e))return Je.restrictTo(e);if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=Object.keys(e);if("unrestricted"in e){let o=e.unrestricted;return t.length===1&&typeof o=="string"&&o.trim().length>0?Je.unrestricted(o):null}let{read:r,comment:n}=e;return t.every(o=>Od.has(o))&&yo(r)?n===void 0?Je.restrictTo({read:r}):yo(n)?Je.restrictTo({read:r,comment:n}):null:null};function Kr(e){let t=rs(e.visible),r=rs(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function rs(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(kd);if(t.length<=Ld)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 os=(e,t,r,n)=>Ae(n.commentable,t)||e.authorUserId===r;import{parseQuerySets as gp}from"@aiquants/fuzzy-search";import{createHash as Hd}from"crypto";import{setImmediate as as}from"timers/promises";import{clusterCountOf as Fd,DEFAULT_NORMALIZE_OPTIONS as Qr,InteriorPairs as Ud,isAnswerTier as $d,normalizeText as Bd,queryNeedles as Vd,resolveNormalizeOptions as qd,toMappedFormsInto as Yd,trimmedRange as Wd}from"@aiquants/fuzzy-search/normalize";var Xr=`
|
|
5
|
+
`,fo=4e3,jd=1,cs=new Set([8203,8288,65279,173]),zd=new RegExp(`[${String.fromCodePoint(...cs)}]`,"gu"),us=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),ds=/(\s+)/u,Gd=/^\s+$/u,Kd=new RegExp(ds.source,"gu"),Jd=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,Qd=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]),Zr=e=>e.replace(zd,"");var Ro=e=>Bd(e,Qr),Jr=e=>Ro(Zr(e)),Xd=qd({...Qr,convertRomaji:!0},"[daily-report] search reading options"),Zd=3,ep=/^[-ー]+/u,tp=/[^\p{L}\p{M}]/gu,rp=/ー{2,}/gu,np=/\p{Script=Latin}/u,is=/(?=\p{L})\p{Script=Latin}/u,op=e=>Fd(e.replace(ep,"").replace(tp,"").replace(rp,"\u30FC")),ap=(e,t)=>{for(let r of t)if(!$d(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})`)},ps=e=>{if(!is.test(e))return[];let t=Jr(e);if(!is.test(t))return[];let r=Vd(t,Xd,!1);ap(t,r);let n=[];for(let o of r){if(o.tier===Nt.word)continue;let a=Jr(o.text);if(!(a.length===0||a.length>we.maxWordLength)&&!(a===t||np.test(a))&&!(op(a)<Zd||n.includes(a))&&(n.push(a),n.length===Yn))break}return n},So=(e,t)=>{let r=e.charCodeAt(t-1),n=e.charCodeAt(t);return r>=55296&&r<=56319&&n>=56320&&n<=57343},ms=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&So(e,t-1)?t-2:t-1;return Jd.test(String.fromCodePoint(r))&&!Qd.has(e.codePointAt(n))},ip=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!ms(e,i);)i--;i===a&&(i=a+r,So(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}},go=(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 s of e.split(ds)){let c=o;if(o+=s.length,i+s.length<=t){i===0&&(a=c),i+=s.length;continue}if(l(),Gd.test(s))continue;if(s.length<=t){a=c,i=s.length;continue}let d=ip(s,c,t);n+=d.forcedCuts,r.push(d.pieces)}return l(),{chunks:r,forcedCuts:n}},bo=(e,t)=>{let r=go(e,t),n=[];for(let o of r.chunks){let a=o.map(i=>Ro(e.slice(i.start,i.end))).join("");a.length>0&&n.push(a)}return{text:n.join(" "),forcedCuts:r.forcedCuts}},sp=(e,t)=>{let r=0;for(let n of e.matchAll(us))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},lp=(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},ys=(e,t)=>{let r="",n=[],o=[];for(let a of t.chunks){let i="",l=[],s=[];for(let c of a){let d=e.slice(c.start,c.end),u=lp(Yd(d,Qr,new Ud(0)),d),[R,p]=Wd(u.text);i+=u.text.slice(R,p);for(let m=R;m<p;m++)l.push(c.start+u.start[m]),s.push(c.start+u.end[m])}if(i.length!==0){r.length>0&&(r+=" ",n.push(o[o.length-1]),o.push(l[0])),r+=i;for(let c=0;c<l.length;c++)n.push(l[c]),o.push(s[c])}}return{text:r,start:n,end:o}},en=(e,t=fo)=>{let r=[],n=0;return sp(Zr(e),o=>{let a=bo(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(Xr),forcedCuts:n}},hs=e=>e.filter(t=>t.length>0).join(Xr),Do=(e,t)=>{let r=null;return{advance:n=>{if(r!==null)return 0;e.units=ie("search text steps: units",n,1);let o=t.next();return o.done===!0&&(r={result:o.value}),n-e.units},done:()=>r!==null,result:()=>{if(r===null)throw new Error("[daily-report] search text: the steps are not done (advance until done() is true)");return r.result}}},ss=4096;function*cp(e,t){let r=[],n=new Uint32Array(e.length),o=0,a=!1;for(let i=0;i<e.length;){for(;t.units===0;)yield;let l=Math.min(e.length,i+t.units);t.units-=l-i;let s=o,c=new Uint16Array(l-i);for(let d=i;d<l;d++){let u=e.charCodeAt(d);cs.has(u)||(c[o-s]=u,n[o++]=d)}if(o-s===l-i)a&&r.push(e.slice(i,l));else{a||r.push(e.slice(0,i)),a=!0;for(let d=s;d<o;d+=ss)r.push(Reflect.apply(String.fromCharCode,null,c.subarray(d-s,Math.min(o,d+ss)-s)))}i=l}return a?{text:r.join(""),rawIndex:n.subarray(0,o)}:{text:e,rawIndex:null}}var fs=e=>{let t={units:0};return Do(t,cp(e,t))};function*up(e,t,r){let n=0;for(let o=0;o<e.length;){for(;r.units===0;)yield;let a=Math.min(e.length,o+r.units);r.units-=a-o;let i=a;for(let l of e.slice(o,Math.min(e.length,a+1)).matchAll(us)){let s=o+l.index;if(s>=a)break;t(e.slice(n,s),n),n=s+l[0].length,i=Math.max(i,n)}o=i}t(e.slice(n),n)}var Rs=(e,t)=>{let r={units:0};return Do(r,up(e,t,r))};function*ls(e,t,r,n,o){let a=[],i=0,l=t;for(;r-l>n;){let s=l+n;for(;s>l;s--){for(;o.units===0;)yield;if(o.units-=1,ms(e,s))break}s===l&&(s=l+n,So(e,s)&&s--,i++),a.push({start:l,end:s}),l=s}return a.push({start:l,end:r}),{pieces:a,forcedCuts:i}}function*dp(e,t,r){if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let n=[],o=0,a=0,i=0,l=0,s=0,c=!1,d=(p,m,h)=>{let y=m-p;return i+y<=t?(i===0&&(a=p),i+=y,!1):(i>0&&n.push([{start:a,end:a+i}]),i=0,h?!1:y<=t?(a=p,i=y,!1):!0)},u=p=>{c&&(d(l,s,!0),l=s),c=!1,s=p},R=p=>{let m=-1;return!c&&s>l&&(d(l,s,!1)&&(m=l),l=s),c=!0,s=p,m};for(let p=0;p<e.length;){for(;r.units===0;)yield;let m=Math.min(e.length,p+r.units);r.units-=m-p;let h=p;for(let y of e.slice(p,m).matchAll(Kd)){let S=p+y.index;S>h&&u(S),h=S+y[0].length;let A=R(h);if(A>=0){let D=yield*ls(e,A,S,t,r);o+=D.forcedCuts,n.push(D.pieces)}}m>h&&u(m),p=m}if(d(l,s,c)){let p=yield*ls(e,l,s,t,r);o+=p.forcedCuts,n.push(p.pieces)}return i>0&&n.push([{start:a,end:a+i}]),{chunks:n,forcedCuts:o}}var Ss=(e,t)=>{let r={units:0};return Do(r,dp(e,t,r))},pp=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
|
|
6
|
+
`)},mp=[`\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`],yp=["","\u30A2","\u4F50"," "],hp=()=>JSON.stringify(mp.map(e=>en(e,8))),fp=e=>`dr-search-v${jd};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var Rp=async()=>{let e=Hd("sha256");e.update(JSON.stringify(Qr));for(let t of yp)await as(),e.update("\0"),e.update(Ro(pp(t)));return await as(),e.update("\0"),e.update(hp()),fp(e.digest("hex"))},Sp=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},Ao=Sp(Rp);var bp=/^-+/u,Dp=/\s+/u,gs=e=>{let t=bp.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},Ap=(e,t)=>{let r=[...gs(e).map(n=>({text:n,tier:Nt.word})),...t.flatMap(n=>gs(n).map(o=>({text:o,tier:Nt.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},Tp=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),tn=(e,t)=>{if(e.length>we.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of gp(Zr(e),t).sets){let i=[],l=new Set;for(let c of a.split(Dp)){let d=Jr(c);if(d.length===0)return{ok:!1,reason:"blank-word"};if(d.length>we.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=Ap(d,ps(c)),R=Tp(u);l.has(R)||(l.add(R),i.push({alternatives:u}))}if(i.length>we.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let s=JSON.stringify([...l].sort());n.has(s)||(n.add(s),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>we.maxSets?{ok:!1,reason:"too-many-sets"}:o>we.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},gr=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var zR=Object.freeze({sourceTypes:null,authors:null,customers:null}),Ep=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,bs=(e,t,r)=>{if(Pa(e)&&Ep(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=tn(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var Ds=6e4,wp=1,Ip=3200,As=2e3,_p=Object.freeze({search:Ip,reports:As,"search-marks":As,"search-facets":null}),xp=(e,t)=>{let r=_p[e];return r===null?null:{max:t,maxPerOwner:Or,maxWaitMs:r}},br=e=>{let{concurrency:t,route:r,logger:n}=e,o=yt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:Ds,logger:n,windowFields:()=>`route=${r}`}),a=it({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:xp(r,t)}),i=Object.freeze({status:429,message:io,headers:Object.freeze({"Retry-After":String(wp)})}),l=Ie({windowMs:Ds,tallies:["busy"],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`busy_suppressed count=${c} since=${d} route=${r} concurrency=${t}`)}});return{admit:async(s,c)=>{let d=o.spend(s,r);if(d!==null)return{refusal:d};let u=await a.acquire(s,c);return u!==null?{release:u}:(o.refund(s,1),c.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};import{systemSseRuntime as Hp}from"@aiquants/sse";import{createSseResponse as Fp,readLastEventId as Up,startSseHeartbeat as $p,terminalStreamResponse as Bp}from"@aiquants/sse/server";var Dr=(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=Hn.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});return{entry:Object.freeze({id:e.id,message:a}),json:n}},Ts=new WeakMap,Es=(e,t,r)=>{let n=Ts.get(e);n===void 0&&(n=new Map,Ts.set(e,n));let o=n.get(t);if(o!==void 0)return o;let a=r();return n.set(t,a),a},To=e=>e,Cp=e=>{switch(e.type){case"connected":case"report-delete":return To(e);case"status-update":case"comment-add":case"comment-delete":{let{recipientRawUserId:t,...r}=e;return To(r)}}},Mp=(e,t,r)=>{let{recipientRawUserId:n,actorRawUserId:o,...a}=e,i=r?{...a.report,externalComments:[],postedComments:[]}:a.report;return To({...a,report:i,viewerIsActor:t})},ws=(e,t,r)=>{let{parsed:n}=e;if(n.type!=="report-create"&&n.type!=="report-update"&&n.type!=="report-publish")return Es(e,"every-viewer",()=>JSON.stringify(Cp(n)));let o=n.actorRawUserId===t;return Es(e,`${o?"actor":"observer"}${r?"-comments-redacted":""}`,()=>JSON.stringify(Mp(n,o,r)))};import{systemSseRuntime as Pp}from"@aiquants/sse";import{createSharedSource as kp}from"@aiquants/sse/shared-source";var Et="daily-report:ids:",Eo=(e,t)=>`${e}st:${t}`,wo=e=>`${Et}user:${e}:`,Is=(e,t)=>Eo(wo(e),t),Jt=e=>`daily-report:date:${e}:user:`,Qt=(e,t)=>`${Jt(e)}${t}:`,_s=(e,t,r)=>Eo(Qt(e,t),r),qe=e=>`daily-report:detail:${e}:user:`,Io=(e,t)=>`${qe(e)}${t}:`,xs=(e,t,r)=>Eo(Io(e,t),r);var Rt=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},Lp=5e3,vp=Hr,Ar=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=Se(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:At}_createSource(){return kp({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:Pp,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:Lp,COUNT:vp});if(i)for(let l of i)for(let s of l.messages){a=s.id;let{entry:c,json:d}=Dr(s,this._logger);this._invalidateCaches(d),r.next(c)}}}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(Et),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(qe(n))}};var Np=6e4,Tr="Report visibility is unavailable",Cs=["initial","refresh"],Ms=Object.freeze({ok:!1}),Op=e=>e===null?"null":Array.isArray(e)?"array":typeof e,Ps=(e,t)=>{let r=Ie({windowMs:Np,tallies:Cs,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{t.error(`visibility_unavailable_suppressed count=${o} since=${a} cause=${n} reasons=${Cs.map(l=>`${l}:${i[l]}`).join(",")}`)}});return async(n,o)=>{let a;try{a=await e(n,{reason:o})}catch(l){return r.record("port_failure",o,()=>t.error(`visibility unavailable cause=port_failure reason=${o}`,l)),Ms}let i=ns(a);return i===null?(r.record("port_contract",o,()=>t.error(`visibility unavailable cause=port_contract reason=${o} answer=${Op(a)}`)),Ms):{ok:!0,scope:i}}},ks=(e,t,r)=>{let n=e(t,r,{error:{message:Tr}},503);for(let[o,a]of Object.entries(be(503)))n.headers.set(o,a);return n};var vs=Object.freeze({...yr,route:"sse",frameworkDataRefusal:Fr}),Ls=864e5,Vp={baseMs:2e3,jitterMs:8e3},Ns=6e4,_o=Hr,Os=JSON.stringify({type:"connected"}),qp=e=>{let t=e.length,r=e["entries-added"];if(typeof t!="number"||!Number.isSafeInteger(t)||t<0||typeof r!="number"||!Number.isSafeInteger(r)||r<t)throw new Error(`XINFO STREAM must report length and entries-added as safe integers with entries-added >= length >= 0 (Redis 7.0 or later); got length=${String(t)} entries-added=${String(r)}`);return r-t},Yp=(e,t,r)=>{if(t===null&&r===null)return!0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return Ae(t,e.report.sourceType);case"comment-add":case"comment-delete":return Ae(r,e.sourceType);case"report-delete":return Ae(t,e.sourceType)}},Wp=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Ae(t,e.report.sourceType),jp=(e,t)=>{e.writeEvent({event:null,id:t,data:Os})},zp=(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||!Yp(o,r.visibleSet,r.commentableSet)){jp(e,t.id);return}e.writeEvent({event:null,id:t.id,data:ws(n,r.internalUserId,Wp(o,r.commentableSet))})},Hs=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:s}=e,c=async(d,u)=>{let{request:R,internalUserId:p,cursor:m}=u,h=u.initialScope.visible,y=u.initialScope.commentable,S=0,A=setInterval(()=>{let k=++S;n(R,"refresh").then($=>{if(k===S){if(!$.ok){d.close();return}h=$.scope.visible,y=$.scope.commentable}})},Ns);d.onClose(()=>clearInterval(A));let D=m===null?At:m,f=m!==null&&o!==void 0,g=[],P=null,_=k=>{Rt(k.id,D)||(D=k.id,zp(d,k,{internalUserId:p,visibleSet:h,commentableSet:y}))},x=async(k,$)=>{let[T]=await k.xRange(i,"-","+",{COUNT:1});return T!==void 0&&!Rt(T.id,$)},V=async(k,$)=>{let[T]=await k.xRange(i,"-","+",{COUNT:1});if(T===void 0)return!0;let w;if($===At){if(qp(await k.xInfoStream(i))>0)return!1;w=T.id}else{if(!Rt(T.id,$))return!1;w=$}for(;;){let B=await k.xRange(i,w,"+",{COUNT:_o}),G=B[0];if(G!==void 0&&G.id!==w&&await x(k,w))return!1;for(let j of B){if(P!==null&&Rt(P,j.id))return!0;Rt(j.id,D)||_(Dr(j,s).entry)}let Z=B.at(-1);if(B.length<_o||Z===void 0||d.isClosed())return!0;w=Z.id}},L=a.subscribe(k=>{if(!f){_(k);return}Rt(k.id,D)||(P===null&&(P=k.id),g.push(k))},k=>{s.error(`[SSE:${p}] Fan-Out reader error:`,k),d.close()});if(d.onClose(L),m===null){await a.ready();try{let k=await o?.getClient();if(k){let $=await k.xRevRange(i,"+","-",{COUNT:1});$.length>0&&!Rt($[0].id,D)&&(D=$[0].id)}}catch{}}if(d.writeEvent({event:null,id:D===At?null:D,data:Os}),$p(d,{intervalMs:da,retry:Vp,runtime:Hp}),m===null||o===void 0)return;await a.ready();let v=await o.getClient();if(v===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await V(v,m)){d.writeRetry(Ls),d.writeEvent({event:"resync-required",id:null,data:""}),d.close();return}f=!1;for(let k of g.splice(0))_(k)};return async({request:d,params:u})=>{let R,p=()=>{let h=new Headers;R!==void 0&&h.append("Set-Cookie",R);for(let[y,S]of Object.entries(at))h.set(y,S);return h},m=h=>Bp(h,{data:"",retryMs:Ls,headers:p()});try{let h=await t(d,{failureRedirect:null});R=h.cookie;let{user:y}=h;if(!y)return m("auth-required");let S=await r.getUserIdByExternalId(y.id);if(!S)return m("forbidden");if(u.endpoint!=="updates")return new Response("Not Found",{status:404,headers:p()});let A=Up(d,pa);if(A!==null&&!ma(A))return s.warn(`[SSE:${S}] malformed resume cursor; asking the client to resync`),m("resync-required");let D=jr(d),f=await l.admit(S,"sse",D);if(f===null){let P=p();for(let[_,x]of Object.entries(be(503)))P.set(_,x);return new Response("Too many streams",{status:503,headers:P})}let g=!1;try{let P=await n(d,"initial");if(!P.ok){let x=p();for(let[V,L]of Object.entries(be(503)))x.set(V,L);return new Response(Tr,{status:503,headers:x})}let _=P.scope;return Fp({requestSignal:D,headers:p(),onError:(x,V)=>s.error(`[SSE:${S}] ${V} failed:`,x),produce:x=>(g=!0,x.onClose(f),c(x,{request:d,internalUserId:S,cursor:A,initialScope:_}))})}finally{g||f()}}catch(h){if(h instanceof Response)throw h;let y=h instanceof Error?h:new Error(String(h));return s.error(`500 sse name=${y.name} message=${y.message}`),new Response("Internal Server Error",{status:500,headers:p()})}}};var Fs=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...at});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Kp=Object.freeze({...yr,route:"api",frameworkDataRefusal:({params:e})=>Jn(e.endpoint)&&Ot[e.endpoint].body==="stream"?Fr():null}),Jp=Object.freeze({...yr,route:"action"}),Qp=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),qs=6e4,Ys=5,Xp=Ys*Math.ceil(qs/500),Zp=2,em=6,tm=6e4,rm=Ys*Zp*em,nm=2,om=10,am=2,im=10,Us=(e,t)=>Math.max(e,Or)*t,Ws=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},sm=Object.freeze({etag:(e,t,r)=>ja(e,t,r,200),"no-store":(e,t,r)=>to(t,r,200)}),lm=e=>ro(e.body==="json"?sm[e.cache]:null),$s=ro(null),Bs=(e,t,r,n)=>Ws(e(t,r,{error:{message:n.message}},n.status),n.headers),Vs=(e,t,r)=>Ws(e(t,r,null,503),be(503));function xo(e){Yr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:ie("service.titleMaxLength",r.titleMaxLength,1)},{loginRedirectPath:s}=e;if(typeof s!="string"||s.trim()==="")throw K("loginRedirectPath","the non-blank path of the host's sign-in route",s);let c=Se(e.logger,3,"API"),d=Se(e.logger,3,"Visibility"),u=Ps(rr("resolveVisibleSourceTypes",e.resolveVisibleSourceTypes),d),R=Se(e.logger,1,"SSE"),p=Se(e.logger,1,"Attachment"),m=Se(e.logger,2,"Isolation"),h=Se(e.logger,2,"Action"),y=Se(e.logger,2,"Search"),S=Se(e.logger,2,"Refresh"),A=Se(e.logger,2,"Streams"),D=Se(e.logger,2,"Reads"),f=yt({reason:"refresh_rate_limit",limitPerWindow:rm,windowMs:tm,logger:S,windowFields:()=>"route=api"}),g=Wi(A),P=Vi(D),_=async(b,F,N,O,U,E)=>{let M=await r.getUserIdByExternalId(F.id);try{return await E(M===null?void 0:P.admissionFor(M,b,N.signal))}catch(C){if(C instanceof je)return Wr(U,N,O);throw C}},x=(b,F,N,O,U)=>{let E=f.spend(F.id,`endpoint=${b}`);return E===null?null:Bs(U,N,O,E)},V=async({request:b})=>{let{user:F,cookie:N}=await t(b,{failureRedirect:s}),O=new Headers;N&&O.append("Set-Cookie",N);let U=await r.getUserIdByExternalId(F.id),E=U?n(U):null;return{data:{user:F,userId:E},headers:O}},L=b=>{let{limiter:F}=b;return async(N,O,U,E,M,C)=>{if(F===null)return C(U,O,{error:{message:"Unknown endpoint"}},404);let H=b.parse(N);if(!H.ok)return C(U,O,H.invalid,400);let I=await r.getUserIdByExternalId(E.id);if(!I)return C(U,O,b.emptyAnswer(H.parsed),200);let{signal:W}=U,X=await F.admit(I,W);if("refusal"in X)return W.aborted?Vs(C,U,O):Bs(C,U,O,X.refusal);try{W.throwIfAborted();let z=await b.read(H.parsed,{userId:I,user:E,scope:M},W);return W.throwIfAborted(),C(U,O,z,200)}catch(z){if(W.aborted&&z===W.reason)return Vs(C,U,O);throw z}finally{X.release()}}},v=r.searchLimits===null?null:br({...r.searchLimits,route:le.search,logger:y}),k=r.searchLimits===null?null:br({concurrency:Us(r.searchLimits.concurrency,nm),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*om,route:le.reports,logger:y}),$=r.searchLimits===null?null:br({concurrency:Us(r.searchLimits.concurrency,am),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*im,route:le.searchMarks,logger:y}),T=r.searchLimits===null?null:br({...r.searchLimits,route:le.searchFacets,logger:y}),w={[le.businessDate]:async(b,F,N,O,U,E)=>{let M=b.searchParams.get(Re.businessDate),C=M===null?null:Vt(M);if(C===null)return E(N,F,{error:{message:"Invalid business date"}},400);let H=mr(b.searchParams.get(Re.forceRefresh));if(H===null)return E(N,F,{error:{message:"Invalid forceRefresh"}},400);let I=H?x(le.businessDate,O,N,F,E):null;return I!==null?I:_(le.businessDate,O,N,F,E,async W=>{let X=await r.getDailyReportsByBusinessDateByExternalId(U,C,O.id,{forceRefresh:H,admission:W});return E(N,F,{businessDate:C,reports:X},200)})},[le.idsStream]:Zi({service:r,logger:c,streamSlots:g,missGate:P,refuseForcedRead:(b,F,N,O)=>x(le.idsStream,b,F,N,O)}),[le.report]:async(b,F,N,O,U,E)=>{let M=ze(b.searchParams.get(Re.reportHubId));if(M===null)return E(N,F,{error:{message:"Invalid reportHubId"}},400);let C=mr(b.searchParams.get(Re.forceRefresh));if(C===null)return E(N,F,{error:{message:"Invalid forceRefresh"}},400);let H=C?x(le.report,O,N,F,E):null;return H!==null?H:_(le.report,O,N,F,E,async I=>{let W=await r.getDailyReportDetailByIdByExternalId(U,M,O.id,{snapshot:!0,forceRefresh:C,admission:I});return W?E(N,F,{report:W},200):E(N,F,{error:{message:"Report not found"}},404)})},[le.search]:L({limiter:v,parse:b=>{let F=b.searchParams.get(Re.searchQuery),N=Gn(b.searchParams.get(Re.searchCombine));if(F===null||N===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let O=La(b.searchParams,r.searchFilterSourceTypes);if(!O.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:O.reason}}};let U=bs(F,N,O.filters);if(!U.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:U.reason}}};let{criteria:E}=U;return{ok:!0,parsed:{criteria:E,words:E.plan===null?[]:gr(E.plan)}}},emptyAnswer:({words:b})=>Wn([],b),read:async({criteria:b,words:F},{userId:N,scope:O})=>Wn(await r.searchDailyReports(O,N,b),F)}),[le.reports]:L({limiter:k,parse:b=>{let F=Kn(b.searchParams.get(Re.reportIds));return F===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:F}},emptyAnswer:b=>({outcomes:b.map(pr)}),read:async(b,{user:F,scope:N},O)=>({outcomes:await r.getDailyReportDetailsByIdsByExternalId(N,b,F.id,{signal:O})})}),[le.searchMarks]:L({limiter:$,parse:b=>{let F=b.searchParams.get(Re.searchQuery),N=Gn(b.searchParams.get(Re.searchCombine));if(F===null||N===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let O=tn(F,N);if(!O.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:O.reason}}};let U=Kn(b.searchParams.get(Re.reportIds));return U===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:O.plan,ids:U}}},emptyAnswer:({plan:b})=>({wordsDigest:Nr(gr(b)),reports:[],deferred:[]}),read:({plan:b,ids:F},{userId:N,scope:O},U)=>r.markDailyReportSearchHits(O,N,b,F,{signal:U})}),[le.searchFacets]:L({limiter:T,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(b,{userId:F,scope:N})=>r.listDailyReportSearchFacets(N,F)})},B=async({request:b,params:F})=>{let{user:N,cookie:O}=await t(b,{failureRedirect:null}),U=O??null;if(!N)return $s(b,U,{error:{message:"Unauthorized"}},401);let E=F.endpoint;if(!Jn(E))return $s(b,U,{error:{message:"Unknown endpoint"}},404);let M=Ot[E],C=lm(M),H=qa[M.body];if(!H.includes(b.method)){let W=C(b,U,{error:{message:"Method not allowed"}},405);return W.headers.set("Allow",H.join(", ")),W}let I=se();try{let W=new URL(b.url),X=await u(b,"initial"),z=X.ok?await w[E](W,U,b,N,X.scope,C):ks(C,b,U);return M.body==="json"&&c.debug(z.headers.has("ETag")?`${z.status} endpoint=${E} etag_match=${z.status===304}`:`${z.status} endpoint=${E}`),z}catch(W){let X=se()-I,z=W instanceof Error?W:new Error(String(W));return c.error(`500 endpoint=${E} elapsed=${X}ms name=${z.name} code=${"code"in z?z.code:"N/A"} message=${z.message}`,z),C(b,U,{error:{message:"Internal Server Error"}},500)}},G=Va(h),Z=yt({reason:"rate_limit",limitPerWindow:Xp,windowMs:qs,logger:h,windowFields:()=>"route=action"}),j=async(b,F,N,O,U)=>{let{clientTempId:E}=b;if(b.intent==="create")try{let I=await r.createDailyReport(N,F,b.businessDate,E);return U(b,I.reportHubId,{report:I})}catch(I){if(I instanceof Error&&I.message==="Forbidden")return O({error:"Creating reports is restricted"},{status:403});throw I}let{reportHubId:M,businessDate:C}=b,H=async(I,W)=>{try{let X=await W(I.value);return U(I,M,{updatedStatus:{isStarred:X.isStarred,isRead:X.isRead},operationTimestamp:I.operationTimestamp})}catch(X){if(X instanceof Error&&X.message==="Not Found")return O({error:"Report not found"},{status:404});throw X}};switch(b.intent){case"update":try{return await r.updateDailyReport(N,M,F,b.changes,E),U(b,M,{})}catch(I){if(I instanceof Error){if(I.message==="Unauthorized")return O({error:"Unauthorized"},{status:403});if(I.message==="Not Found")return O({error:"Report not found"},{status:404})}throw I}case"publish":try{let I=await r.publishDailyReport(N,M,F,E);return U(b,M,{report:I})}catch(I){if(I instanceof Error){if(I.message==="Unauthorized")return O({error:"Unauthorized"},{status:403});if(I.message==="Not Found")return O({error:"Report not found"},{status:404})}throw I}case"delete":try{return await r.deleteDailyReport(N,M,F,E),U(b,M,{})}catch(I){if(I instanceof Error){if(I.message==="Unauthorized")return O({error:"Unauthorized"},{status:403});if(I.message==="Not Found")return O({error:"Report not found"},{status:404})}throw I}case"toggleStar":return await H(b,I=>r.setStarStatus(N,F,M,C,I,E));case"toggleRead":return await H(b,I=>r.setReadStatus(N,F,M,C,I,E));case"addComment":try{let I=await r.addComment(N,F,M,b.content,C,E);return U(b,M,{newComment:I})}catch(I){if(I instanceof Error){if(I.message==="Not Found")return O({error:"Report not found"},{status:404});if(I.message.startsWith("Comments are restricted"))return O({error:"Comments are restricted for this report"},{status:403})}throw I}case"deleteComment":try{return await r.deleteComment(N,F,M,b.commentId,C,E),U(b,M,{deletedCommentId:b.commentId})}catch(I){if(I instanceof Error){if(I.message==="Unauthorized")return O({error:"Unauthorized"},{status:403});if(I.message==="Not Found")return O({error:"Comment not found"},{status:404})}throw I}}},pe=async({request:b,params:F})=>{let{user:N,cookie:O}=await t(b,{failureRedirect:null}),U=(C,H)=>Fs(C,{...H,setCookie:O}),E=(C,H,I)=>Fs(Qp(C,H,I),{setCookie:O});if(!N)return U({error:"Unauthorized"},{status:401});let M=se();try{if(F.endpoint!==le.action)return U({error:"Unknown endpoint"},{status:404});let C=Z.spend(N.id,"action");if(C!==null)return U({error:C.message},{status:C.status,headers:C.headers});let H=await Ba(b,l);if("refusal"in H){let{refusal:z}=H;return z.status===413&&G(z.measuredBy),U({error:z.error},{status:z.status})}let{command:I}=H;if(I.intent==="clearCache"&&!e.enableDevCacheClear)return U({error:"Invalid intent"},{status:400});let W=await u(b,"initial");if(!W.ok)return U({error:Tr},{status:503,headers:{...be(503),"Cache-Control":"no-store"}});let X=await r.getUserIdByExternalId(N.id);return X?I.intent==="clearCache"?(await r.clearCache(),U({status:"OK",intent:"clearCache"})):await j(I,X,W.scope,U,E):U({error:"User not found"},{status:404})}catch(C){if(C instanceof Response)throw C;let H=se()-M,I=C instanceof Error?C:new Error(String(C));return c.error(`500 action elapsed=${H}ms name=${I.name} message=${I.message}`,I),U({error:"Internal Server Error"},{status:500})}},ye=Hs({authenticate:t,service:r,resolveViewerScope:u,redis:o,sseReader:a,streamKey:i,streamSlots:g,logger:R}),J=Hi({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:u,logger:p}),Le=Ja(m),Q=(b,F)=>async N=>{let O=Ka(N.request)?b.frameworkDataRefusal(N):null;if(O!==null)throw O;let U=Gp(N.request,b);return U===void 0?F(N):(Le(b.route,U,N.request),b.crossSiteRejection())};return{index:{loader:V},api:{loader:Q(Kp,B),action:Q(Jp,pe)},sse:{loader:Q(vs,ye)},attachment:{loader:Q(Oi,J)}}}import{chunk as iy,MAX_IN_LIST as sy,runWithTransactionRetry as ly}from"@aiquants/mssql";import{asc as gt,eq as fn,inArray as Rn}from"drizzle-orm";var cm=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],um=["document","comment"],dm=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],pm=["hubId","ordinal","authorUserId","commentText"],Co=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},js=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw En(e,n,r)},zs=(e,t,r)=>{if(typeof t!="object"||t===null)throw K(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw K(`${e}.${o}`,"a column",n[o])},Gs=(e,t)=>{if(!Co(e))throw K("search","a plain object",e);js("search key",e,cm);let{tables:r}=e;if(!Co(r))throw K("search.tables","a plain object with document and comment",r);js("search.tables key",r,um),zs("search.tables.document",r.document,dm),zs("search.tables.comment",r.comment,pm);let n=new Map;if(e.externalSourceTexts!==void 0){if(!Co(e.externalSourceTexts))throw K("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw En("search.externalSourceTexts key",o,t);if(typeof a!="function")throw K(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:ie("search.concurrency",e.concurrency,1),rateLimitPerMinute:ie("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var wt=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},Ht=(e,t)=>{let r=typeof e=="string"?ze(e):typeof e=="number"&&nt(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},Ft=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};import{sql as q}from"drizzle-orm";import{sql as It}from"drizzle-orm";var Ks=e=>{if(e.length===0)throw new Error("[daily-report] draft rule: draftLabelNames must hold at least one name (a rule without names would show every draft to every viewer)");return It.join(e.map(t=>It`${t}`),It`, `)},nn=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return It`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${Ks(t)}))`},Js=(e,t)=>{let{hubLabel:r,label:n}=e;return It`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${Ks(t)}))`},on=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?It`${o.userId} = ${t} OR ${o.userId} IS NULL`:It`${o.userId} = ${t}`;return It`(${a} OR NOT ${nn(e,r)})`};var mm=/[[%_]/gu,ym=e=>e.replace(mm,t=>`[${t}]`),Qs=e=>`%${ym(e)}%`;var Qe=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),Ut=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),wr=Object.freeze({value:"value"}),_e=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),Y=e=>q`${q.identifier(e.name)}`,Er=e=>q.join(e.map(t=>q`${t}`),q`, `),Xs=(e,t)=>q`SELECT ${Y(e.id)} AS ${q.identifier(_e.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${Er(t)}) ORDER BY ${e.id}`,hm=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>Qs(u.text)),l=q.join(i.map(u=>q`${o.searchText} LIKE ${u}`),q` OR `),s=q.join(i.map(u=>q`${a.commentText} LIKE ${u}`),q` OR `),c=Sr(n.sourceType,r.scope.commentable),d=c===void 0?q``:q` AND (${c} OR ${a.authorUserId} = ${r.userId})`;return q`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${s})${d}))`},Zs=(e,t,r)=>q`(${q.join(t.words.map(n=>hm(e,n,r)),q` AND `)})`,Mo=(e,t,r,n)=>{let{hub:o}=e,a=[q`${o.deletedAt} IS NULL`,on(e,t.userId,r,"author")],i=Sr(o.sourceType,t.scope.visible);return i!==void 0&&a.push(i),n!==void 0&&a.push(q`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},fm=(e,t)=>{let{hub:r}=e,{document:n}=e.search,o=[];if(t.sourceTypes!==null){if(t.sourceTypes.size===0)throw new Error("[daily-report] search: a source-type filter must hold at least one source type");o.push(q`LOWER(${r.sourceType}) IN (${Er([...t.sourceTypes])})`)}return t.authors!==null&&o.push(q`${n.authorName} IN (${Er(t.authors)})`),t.customers!==null&&o.push(q`${n.customerName} IN (${Er(t.customers)})`),o},el=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,s=[...Mo(e,r,n,o),...fm(e,t.filters)];if(l!==null){let c=l.combine==="intersection"?q` AND `:q` OR `;s.push(q`(${q.join(l.sets.map(d=>Zs(e,d,r)),c)})`)}return q`SELECT ${Y(a.id)} AS ${q.identifier(Qe.reportHubId)}, CONVERT(char(10), ${Y(a.businessDate)}, 23) AS ${q.identifier(Qe.businessDate)}, ${Y(a.sourceType)} AS ${q.identifier(Qe.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${q.join(s,q` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},tl=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=q.join(t.sets.map((s,c)=>q`(CASE WHEN ${Zs(e,s,r)} THEN ${2**c} ELSE 0 END)`),q` + `);return q`SELECT ${Y(a.id)} AS ${q.identifier(Ut.reportHubId)}, ${l} AS ${q.identifier(Ut.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${q.join(Mo(e,r,n,o),q` AND `)}`},rl=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...Mo(e,r,n),q`${i} IS NOT NULL`];return q`SELECT ${i} AS ${q.identifier(wr.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${q.join(l,q` AND `)} GROUP BY ${i} ORDER BY ${i}`},nl=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(s=>({[n.hubId.name]:s.hubId,[n.searchText.name]:s.searchText,[n.sourceDigest.name]:s.sourceDigest,[n.normalizerVersion.name]:r,[n.authorName.name]:s.authorName,[n.customerName.name]:s.customerName}))),i=JSON.stringify(t.flatMap(s=>s.comments.map(c=>({[o.hubId.name]:s.hubId,[o.ordinal.name]:c.ordinal,[o.authorUserId.name]:c.authorUserId,[o.commentText.name]:c.commentText})))),l=JSON.stringify(t.map(s=>s.hubId));return q`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), ${Y(n.authorName)} nvarchar(max), ${Y(n.customerName)} nvarchar(max))) AS s ON t.${Y(n.hubId)} = s.${Y(n.hubId)}
|
|
8
|
+
WHEN MATCHED THEN UPDATE SET t.${Y(n.searchText)} = s.${Y(n.searchText)}, t.${Y(n.sourceDigest)} = CONVERT(binary(32), s.${Y(n.sourceDigest)}, 2), t.${Y(n.normalizerVersion)} = s.${Y(n.normalizerVersion)}, t.${Y(n.authorName)} = s.${Y(n.authorName)}, t.${Y(n.customerName)} = s.${Y(n.customerName)}, t.${Y(n.indexedAt)} = SYSUTCDATETIME()
|
|
9
|
+
WHEN NOT MATCHED THEN INSERT (${Y(n.hubId)}, ${Y(n.searchText)}, ${Y(n.sourceDigest)}, ${Y(n.normalizerVersion)}, ${Y(n.authorName)}, ${Y(n.customerName)}) VALUES (s.${Y(n.hubId)}, s.${Y(n.searchText)}, CONVERT(binary(32), s.${Y(n.sourceDigest)}, 2), s.${Y(n.normalizerVersion)}, s.${Y(n.authorName)}, s.${Y(n.customerName)});
|
|
10
10
|
DELETE FROM ${o} WHERE ${o.hubId} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${l}));
|
|
11
|
-
INSERT INTO ${o} (${q(o.hubId)}, ${q(o.ordinal)}, ${q(o.authorUserId)}, ${q(o.commentText)}) SELECT ${q(o.hubId)}, ${q(o.ordinal)}, ${q(o.authorUserId)}, ${q(o.commentText)} FROM OPENJSON(${i}) WITH (${q(o.hubId)} bigint, ${q(o.ordinal)} int, ${q(o.authorUserId)} bigint, ${q(o.commentText)} nvarchar(max));`},Ys=(e,t)=>V`SELECT ${q(e.hubId)} AS ${V.identifier(Ee.hubId)}, LOWER(CONVERT(char(64), ${q(e.sourceDigest)}, 2)) AS ${V.identifier(Ee.sourceDigest)}, ${q(e.normalizerVersion)} AS ${V.identifier(Ee.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${mr(t)})`,js=(e,t,r)=>V`SELECT TOP (${r}) ${q(e.id)} AS ${V.identifier(Ee.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var Ws=e=>({search:async(t,r)=>Me(r.scope.visible)?[]:yt(await t.execute($s(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=_t(o[je.sourceType],je.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${je.sourceType} is null`);return{reportHubId:It(o[je.reportHubId],je.reportHubId),businessDate:_t(o[je.businessDate],je.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(Me(r.scope.visible))return new Map;let n=yt(await t.execute(Bs(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[xt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${xt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(It(i[xt.reportHubId],xt.reportHubId),l)}return a},facetValues:async(t,r)=>Me(r.scope.visible)?[]:yt(await t.execute(Vs(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=_t(o[yr.value],yr.value);if(a===null)throw new Error(`[daily-report] search: column ${yr.value} is null`);return a})});import{chunk as Gr,MAX_IN_LIST as Kr}from"@aiquants/mssql";import{sql as Gs}from"drizzle-orm";import{createHash as lm}from"crypto";var cm=Object.freeze({authorName:"author",customerName:"customer"}),bo=e=>e===null?null:vn(e),zs=(e,t,r)=>{let n=bo(r);if(n!==null&&n.length>nt.maxValueLength){let o=nt.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${cm[t]} display value has ${n.length} UTF-16 units after trimming; the host must keep the author and customer display values at most ${o} UTF-16 units`)}return n},hr=e=>e===null?"n;":`s${e.length}:${e}`,fr="utf16le",um=e=>{let t=lm("sha256");t.update(`F${e.fields.length};`,fr);for(let[r,n]of e.fields)t.update(hr(r)+hr(n),fr);return t.update(`C${e.comments.length};`,fr),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${hr(r.text)}`,fr)}),t.update(`P;${hr(bo(e.filterValues.authorName))}${hr(bo(e.filterValues.customerName))}`,fr),t.digest("hex")},Do=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=qr(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=qr(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:es(r),comments:n,sourceDigest:um(e),forcedCuts:t,authorName:zs(e.hubId,"authorName",e.filterValues.authorName),customerName:zs(e.hubId,"customerName",e.filterValues.customerName)}};var Ks=e=>{let t=async(s,c)=>{let d=[];for(let u of Gr(c,Kr))for(let R of yt(await s.execute(Hs(e.hub,u))))d.push(It(R[Ee.hubId],Ee.hubId));return d},r=async(s,c)=>{for(let d of Gr(c,Kr))await s.execute(qs(e.tables,d,e.normalizerVersion))},n=async(s,c)=>{let d=new Map;for(let u of Gr(c,Kr))for(let R of yt(await s.execute(Ys(e.tables.document,u))))d.set(It(R[Ee.hubId],Ee.hubId),{sourceDigest:_t(R[Ee.sourceDigest],Ee.sourceDigest),normalizerVersion:_t(R[Ee.normalizerVersion],Ee.normalizerVersion)});return d},o=async(s,c,d)=>yt(await s.execute(js(e.hub,c,d))).map(u=>It(u[Ee.hubId],Ee.hubId)),a=async(s,c)=>{let d=await t(s,[...new Set(c)].sort((R,p)=>R-p));if(d.length===0)return;let u=(await e.loadSources(s,d)).map(Do);u.length>0&&await r(s,u)},i=s=>e.inTransaction(async c=>{await c.execute(Gs`SET DEADLOCK_PRIORITY LOW`);let d=await t(c,s),u=await n(c,d),R=(await e.loadSources(c,d)).map(Do),p=R.filter(m=>{let h=u.get(m.hubId);return h===void 0||h.sourceDigest!==m.sourceDigest||h.normalizerVersion!==e.normalizerVersion});return p.length>0&&await r(c,p),await c.execute(Gs`SET DEADLOCK_PRIORITY NORMAL`),{scanned:R.length,written:p.length,forcedCuts:R.reduce((m,h)=>m+h.forcedCuts,0)}});return{writeHubs:a,reconcile:async(s,c)=>{let{batchSize:d,hubIds:u,signal:R,onProgress:p}=c;ae("reconcileSearchIndex: batchSize",d,1,Kr);let m=ie(),h=u===void 0?null:Gr([...new Set(u)].sort((S,A)=>S-A),d),y={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let S=0;;S++){R?.throwIfAborted();let A=h===null?await o(s,y.lastHubId===null?0:y.lastHubId,d):h[S];if(A===void 0||A.length===0)break;let D=await i(A);y={scanned:y.scanned+D.scanned,written:y.written+D.written,skipped:y.skipped+D.scanned-D.written,forcedCuts:y.forcedCuts+D.forcedCuts,lastHubId:A[A.length-1]},p?.(y)}return{...y,elapsedMs:ie()-m}}}};import{holdsMultiUnitCluster as dm}from"@aiquants/fuzzy-search/normalize";var Ao=255,Jr=Object.values(Et).sort((e,t)=>e-t),pm=new Intl.Segmenter("und",{granularity:"grapheme"}),pe=Object.freeze({strip:30,split:200,line:2e3,plan:90,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),et=5e5,Qr=Math.floor(et/pe.linear),mm=Math.floor(et/pe.segment),Js=Math.floor(et/pe.sweep),Xs=Math.floor(et/pe.scan),wo=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),Zs=(e,t)=>{let r=0,n=t(),o=et,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+et,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=et,a=!1}}},Sg=Object.freeze({fits:()=>!0,charge:()=>{}}),el=e=>{let t=null;return{step:()=>{if(t!==null)return!0;let r=e.next();return r.done!==!0?!1:(t={result:r.value},!0)},result:()=>{if(t===null)throw new Error("[daily-report] search marks: the walk is not done (step until it returns true)");return t.result}}};var ym=(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},hm=(e,t)=>e.chunks.length===1&&e.chunks[0].length===1&&e.chunks[0][0].start===0&&e.chunks[0][0].end===t.length;function*fm(e,t,r,n){let o=!1;for(let c=t;c<r&&!o;c+=Qr){let d=Math.min(r,c+Qr),u=(d-c)*pe.linear;n.fits(u)||(yield),o=dm(e.slice(c,d)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=pm.segment(e.slice(t,r))[Symbol.iterator](),s=l.next();for(;!s.done;){let c=Math.max(mm,s.value.segment.length);n.fits(c*pe.segment)||(yield);let d=0;for(;!s.done&&d+s.value.segment.length<=c;){let{index:u,segment:R}=s.value;a.fill(t+u,u,u+R.length),i.fill(t+u+R.length,u,u+R.length),d+=R.length,s=l.next()}n.charge(d*pe.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var Rm=256,Sm=e=>{let t=new Int32Array(e.length),r=0;for(let n=1;n<e.length;n++){for(;r>0&&e.charCodeAt(n)!==e.charCodeAt(r);)r=t[r-1];e.charCodeAt(n)===e.charCodeAt(r)&&r++,t[n]=r}return e.length-t[e.length-1]},gm=e=>{let t=new Map;for(let r of e){if(r.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let n=t.get(r.text);(n===void 0||r.tier<n)&&t.set(r.text,r.tier)}return[...t].map(([r,n])=>{let o=Sm(r),a=Math.max(Xs-r.length+1,r.length);if(o===r.length)return{text:r,tier:n,periodic:null,windowStarts:a};let i=r.length%o,l=r.slice(i,o)+r.slice(0,i);return{text:r,tier:n,periodic:{period:o,continuation:l.repeat(Math.ceil(Rm/o))},windowStarts:a}})},Xr=(e,t)=>{let{pieces:r}=e,n=r[e.lastPiece];if(n.plainStart<=t&&t<n.plainStart+n.text.length)return e.lastPiece;let o=0,a=r.length-1;for(;o<a;){let i=o+a+1>>1;r[i].plainStart<=t?o=i:a=i-1}return t>=r[o].plainStart+r[o].text.length?-1:(e.lastPiece=o,o)},Qs=(e,t,r)=>{let n=Xr(e,t);return e.pieces[n>=0?n:Xr(e,r==="start"?t-1:t+1)]},tl=(e,t)=>{let r=Xr(e,t);if(r<0)return rl(e,t-1);let n=e.pieces[r];return n.start+n.mapped.start[t-n.plainStart]},rl=(e,t)=>{let r=Xr(e,t);if(r<0)return tl(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},bm=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),Dm=Object.freeze({kind:"done"}),To=Object.freeze({kind:"slice"}),Am=Object.freeze({kind:"clusters"}),Tm=(e,t,r,n,o,a)=>{let{plain:i}=e,{text:l,tier:s,periodic:c}=r;for(;;){if(n.closedEnd>=0){if(!o.fits(pe.run))return To;let p=Qs(e,n.closedStart,"start"),m=Qs(e,n.closedEnd-1,"end");if(p.mapped===null)return{kind:"map",piece:p};if(m.mapped===null)return{kind:"map",piece:m};if(e.isCut&&e.clusters===void 0)return Am;let h=t(e.offset+tl(e,n.closedStart)),y=t(e.offset+rl(e,n.closedEnd-1)-1)+1;n.closedEnd=-1;let S=e.clusters;S==null?a(h,y,s):a(S.clusterStarts[h-S.start],S.clusterEnds[y-1-S.start],s),o.charge(pe.run);continue}if(c!==null&&n.periodicEnd>=0){if(!o.fits(et))return To;let{period:p,continuation:m}=c,h=n.periodicEnd,y=Math.min(i.length,h+Math.max(Xs,m.length)),S=h;for(;S+m.length<=y&&i.startsWith(m,S);)S+=m.length;let A=S+m.length>y&&y<i.length;if(!A)for(;S<i.length&&i.charCodeAt(S)===i.charCodeAt(S-p);)S++;if(o.charge((S-h)*pe.scan),A){n.periodicEnd=S;continue}n.periodicEnd=-1,n.last+=Math.floor((S-n.last-l.length)/p)*p,n.from=n.last+l.length-p+1;continue}if(n.from<0){if(n.runStart<0)return Dm;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(et))return To;n.from>=n.windowEnd&&(n.windowStart=n.from,n.windowEnd=n.from+r.windowStarts,n.window=i.slice(n.from,n.windowEnd+l.length-1));let d=n.from-n.windowStart,u=n.window.indexOf(l,d);if(u<0){o.charge((n.window.length-d)*pe.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-d)*pe.scan);let R=n.windowStart+u;(n.runStart<0||R>=n.last+l.length)&&(n.runStart>=0&&(n.closedStart=n.runStart,n.closedEnd=n.last+l.length),n.runStart=R),n.last=R,c===null?n.from=R+1:n.periodicEnd=R+l.length}};function*Eo(e,t,r){let n=Math.floor(et/t);for(;!e.done();)r.fits(n*t)||(yield),r.charge(e.advance(n)*t);return e.result()}function*Em(e,t,r,n,o){if(t.length===0)return;let a=yield*Eo(ts(e),pe.strip,n),i=[],l=[];yield*Eo(rs(a.text,(c,d)=>{i.push(d),l.push(d+c.length)}),pe.split,n);let s=c=>a.rawIndex===null?c:a.rawIndex[c];for(let c=0;c<i.length;c++){n.fits(pe.line)||(yield),n.charge(pe.line);let d=i[c],u=a.text.slice(d,l[c]),R=yield*Eo(ns(u,r),pe.plan,n),p=[],m="";for(let y of R.chunks){let S="",A=[];for(let D of y){let f=(D.end-D.start)*pe.normalize;n.fits(f)||(yield);let b=lo(D.start===0&&D.end===u.length?u:u.slice(D.start,D.end),r).text;n.charge(f),b.length>0&&A.push({start:D.start,end:D.end,text:b,chunkStart:S.length}),S+=b}if(S.length!==0){m.length>0&&(m+=" ");for(let D of A)p.push({start:D.start,end:D.end,text:D.text,plainStart:m.length+D.chunkStart,mapped:null});m+=S}}if(m.length===0)continue;let h={offset:d,plain:m,pieces:p,isCut:!hm(R,u),lastPiece:0,clusters:void 0};for(let y of t){let S=bm();for(;;){let A=Tm(h,s,y,S,n,o);if(A.kind==="done")break;if(A.kind==="slice"){yield;continue}if(A.kind==="clusters"){h.clusters=yield*fm(e,s(d),s(d+u.length-1)+1,n);continue}let{piece:D}=A,f=(D.end-D.start)*pe.map;n.fits(f)||(yield);let b=u.slice(D.start,D.end);D.mapped=ym(Zi(b,so(b,r)),D.text),n.charge(f)}}}}function*wm(e,t,r,n){let o=new Int32Array(Jr.length),a=0,i=Ao;for(let l=0;l<=e;l+=Js){let s=Math.min(e+1,l+Js),c=(s-l)*pe.sweep;r.fits(c)||(yield);for(let d=l;d<s;d++){let u=Ao;for(let R=Jr.length-1;R>=0;R--){let p=Jr[R];o[p]+=t[p][d],o[p]>0&&(u=p)}if(u!==i){if(i!==Ao&&!n(a,d,i))return!1;a=d,i=u}}r.charge(c)}return!0}function*Im(e,t,r,n,o){let a=null;return yield*Em(e,t,r,n,(l,s,c)=>{a===null&&(a=Jr.map(()=>new Int32Array(e.length+1))),a[c][l]++,a[c][s]--}),a===null?!0:yield*wm(e.length,a,n,o)}var _m=(e,t,r,n)=>{let o=gm(t),a=[],i=(s,c,d)=>(a.push(s,c,d),a.length<=3*r.maxRanges);return el(function*(){return(yield*Im(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var nl=(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)},ol=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of pa)r(rt.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(rt.interviewer(o,"name"),n.name),r(rt.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(rt.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(rt.comment(xn(o),"author"),n.name),r(rt.comment(xn(o),"content"),n.text)});for(let n of e.postedComments)r(rt.comment(n.id,"author"),n.userName),r(rt.comment(n.id,"content"),n.content);return t};function*xm(e,t){let r=Pn;for(let n=0;n<e.length;n+=Qr){let o=Math.min(e.length,n+Qr),a=(o-n)*pe.linear;t.fits(a)||(yield),r=Ln(r,e,n,o),t.charge(a)}return r}var al=async(e,t,r,n)=>{let o=0,a=0,i=async c=>{for(;!c.step();)await r(),n.startSlice();return c.result()},l=async(c,d)=>{if(!d&&a>t.maxRanges)return null;let u={};for(let{key:R,value:p}of c.fields){if(!d&&o+p.length>t.maxUnits)return null;let m=await i(el(xm(p,n))),h=await i(_m(p,c.alternatives,{maxLength:oo,maxRanges:t.maxFieldRanges},n));if(o+=p.length,h.dense){u[R]={fingerprint:m,dense:!0};continue}if(u[R]={fingerprint:m,ranges:h.ranges},a+=h.ranges.length/3,!d&&a>t.maxRanges)return null}return u},s=[];for(let c=0;c<e.length;c++){let d=e[c],u=await l(d,s.length===0);if(u===null)return{reports:s,deferred:e.slice(c).map(R=>R.reportHubId)};s.push({reportHubId:d.reportHubId,matchedSets:d.matchedSets,fields:u})}return{reports:s,deferred:[]}};import{and as Lm,asc as ll,eq as en,inArray as km,isNull as Nm}from"drizzle-orm";import{and as il,asc as Cm,eq as Zr,getColumns as Mm,sql as Pm}from"drizzle-orm";var lt=e=>Mm(e),be=(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"),s=String(r.getMinutes()).padStart(2,"0"),c=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${s}:${c}`},sl=e=>{let{db:t,tables:r,encodeUserId:n,settings:o,draftVisibilityTables:a}=e,{hub:i,label:l}=r,{externalSources:s,draftLabelNames:c,canonicalDraftLabelName:d}=o,u=N=>sr(i.sourceType,N),R=(N,v)=>zr(a,N,c,v),p=Pm`CASE WHEN ${Wr(a,c)} THEN 1 ELSE 0 END`,m=async N=>{let[v]=await t.select({id:i.id}).top(1).from(i).where(il(Zr(i.id,N),Wr(a,c)));return v!==void 0},h=N=>N==null||N===""?null:/^\d+$/.test(N)?n(Number(N)):N,y=()=>{let N={};for(let v of s)N[`ext_${v.sourceType}`]=lt(v.table);return N},S=N=>{let v=N;for(let L of s)v=v.leftJoin(L.table,il(Zr(i.sourceType,L.sourceType),Zr(i.sourceIdNum,L.idColumn)));return v},A=N=>{let{hub:v,internal:L}=N,F=v.summary,T=[],_=null,U=null,z=null,X=null,G=null,de=null,me=[],Z=s.find(O=>O.sourceType===v.sourceType),ve=Z?N[`ext_${Z.sourceType}`]:void 0;if(Z&&ve){let O=Z.mapRow(ve);O.content!==void 0&&(F=O.content),O.employeeName!==void 0&&(de=O.employeeName),O.category!==void 0&&(_=O.category),O.creationCategory!==void 0&&(U=O.creationCategory),O.visitTimeFrom!==void 0&&(z=O.visitTimeFrom),O.visitTimeTo!==void 0&&(X=O.visitTimeTo),O.customerName!==void 0&&(G=O.customerName),O.interviewers!==void 0&&(T=O.interviewers),O.externalComments!==void 0&&(me=O.externalComments)}else v.sourceType===qe&&L&&(F=L.body);return{content:F,author:N.creatorName??h(v.createdBy)??"",employeeName:de??N.creatorName??h(v.createdBy),updatedBy:h(v.updatedBy),category:_,creationCategory:U,visitTimeFrom:z,visitTimeTo:X,customerName:G,interviewers:T,externalComments:me}},D=N=>{if(N===1)return!0;if(N===0)return!1;throw new Error(`[daily-report] a detail row's hasDraftLabel must be 1 or 0 (the read must select draftLabelFlag); got ${Dt(N)}`)},f=N=>N.creationCategory!==null&&c.includes(N.creationCategory),b=(N,v)=>D(N.hasDraftLabel)?!0:f(v),C=async N=>{let[v]=await N.select({id:l.id}).top(1).from(l).where(Zr(l.name,d)).orderBy(Cm(l.id));return v===void 0?null:v.id},w=()=>C(t);return{visibleSourceTypeCondition:u,draftVisibleTo:R,draftLabelFlag:p,isDraftReport:m,externalSelections:y,applyExternalJoins:S,resolveHubDisplayFields:A,readCanonicalDraftLabelId:C,getDraftLabelId:w,resolveCreationCategoryDraftLabelId:N=>N.some(f)?w():Promise.resolve(null),mapHubRecord:(N,v,L,F,T)=>{let{hub:_}=v,U=v.labels.map(G=>({id:G.id,name:G.name,color:G.color})),z=v.postedCommentRows,X=ge(N.commentable,_.sourceType);return F!==null&&f(L)&&!U.some(G=>G.id===F)&&U.push({id:F,name:d,color:null}),{reportHubId:_.id,date:be(_.businessDate,"YYYY-MM-DD"),author:L.author,userId:_.userId?n(_.userId):"",sourceType:_.sourceType,createdAt:be(_.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:be(_.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:L.updatedBy,employeeName:L.employeeName,category:L.category,creationCategory:L.creationCategory,visitTimeFrom:L.visitTimeFrom,visitTimeTo:L.visitTimeTo,customerName:L.customerName,interviewers:L.interviewers,subject:_.title,content:L.content,externalComments:X?L.externalComments:[],isRead:v.isRead??!1,isStarred:v.isStarred??!1,isDraft:b(v,L),labels:U,postedComments:z.filter(G=>qi({authorUserId:G.userId},_.sourceType,T,N)).map(G=>({...G,userId:n(G.userId),isMine:T?G.userId===T:!1})),attachments:v.attachments}}}};var cl=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r})=>{let{db:n,tables:o,logger:a,settings:i}=e,{hub:l}=o,{attachmentDelivery:s}=i,c=(m,h)=>h!=null?"absent":m!=null?"present":"unknown";return{getAttachmentsByHubIds:async m=>{let h=new Map,y=o.attachment;if(m.length===0||!y||s===null)return h;let S=s.idCodec,A=s.thumbnails!==null,D=await n.select({id:y.id,hubId:y.hubId,fileName:y.fileName,fileType:y.fileType,fileSize:y.fileSize,createdAt:y.createdAt,objectCheckedAt:y.objectCheckedAt,objectMissingAt:y.objectMissingAt}).from(y).where(km(y.hubId,m)).orderBy(ll(y.createdAt),ll(y.id));for(let f of D){let b=f.fileType?String(f.fileType):null,C=f.fileSize!=null?Number(f.fileSize):null,w=c(f.objectCheckedAt,f.objectMissingAt),I={id:S.encode(Number(f.id)),fileName:String(f.fileName),fileType:b,fileSize:C,createdAt:be(f.createdAt,"YYYY-MM-DD HH:mm:ss"),state:w,hasThumbnail:A&&w!=="absent"&&Pr({fileType:b,fileSize:C},s.maxBytes)},$=h.get(Number(f.hubId));$?$.push(I):h.set(Number(f.hubId),[I])}return h},getAttachmentForUser:async(m,h,y)=>{let S=o.attachment;return!S||Me(m.visible)?null:(await n.select({fileName:S.fileName,filePath:S.filePath,fileType:S.fileType,fileSize:S.fileSize}).top(1).from(S).innerJoin(l,en(l.id,S.hubId)).where(Lm(en(S.id,h),Nm(l.deletedAt),t(y,"author"),r(m.visible))))[0]??null},markAttachmentMissing:async m=>{let h=o.attachment;if(!h)return;let y=new Date;try{await n.update(h).set({objectCheckedAt:y,objectMissingAt:y,updatedAt:y}).where(en(h.id,m))}catch(S){a.error("markAttachmentMissing failed",S)}},markAttachmentPresent:async m=>{let h=o.attachment;if(!h)return;let y=new Date;try{await n.update(h).set({objectCheckedAt:y,objectMissingAt:null,updatedAt:y}).where(en(h.id,m))}catch(S){a.error("markAttachmentPresent failed",S)}}}};import{eq as Io}from"drizzle-orm";import{and as vm,eq as ul,isNull as Om}from"drizzle-orm";var Vt=async(e,t,r,n)=>{if((await e.update(t).set({deletedAt:null}).output().where(vm(ul(t.id,r),Om(t.deletedAt),n===null?void 0:ul(t.userId,n)))).length===0)throw new Error("Not Found")};var ft="daily-report:ids:epoch",ke="daily-report:date-epoch:",tt="daily-report:detail-epoch:",dl=({redis:e,logger:t,epochs:r,streamKey:n,streamMaxLen:o})=>({incrementRedisEpoch:s=>r.incrementEpoch(s),publishToSseStream:async(s,c)=>{let d=await e?.getClient();if(!d){t.warn(`[SSE] Redis client unavailable (${c})`);return}let u=JSON.stringify(s),R=Buffer.byteLength(u);if(R>6356992){t.warn(`[SSE] Event too large (${c}): ${R} bytes > ${6356992}; not published`);return}let p=ie();try{await d.xAdd(n,"*",{data:u},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:o}});let m=ie()-p;m>1e3&&t.warn(`[SSE] Slow publish (${c}): ${m}ms`)}catch(m){t.error(`[SSE] Redis publish failed (${c}):`,m)}},readSseStreamAnchor:async()=>{try{let s=await e?.getClient();if(s===void 0)return null;let[c]=await s.xRevRange(n,"+","-",{COUNT:1});return c===void 0?null:c.id}catch(s){return t.error("SSE stream anchor read failed",s),null}}});var pl=(e,{isDraftReport:t,assertHubMutable:r,incrementRedisEpoch:n})=>{let{db:o,tables:a,users:i,encodeUserId:l,cache:s,inTransaction:c,prepareSearchIndex:d,publishToSseStream:u}=e,{hub:R,comment:p}=a,m=async(A,D)=>{if(D!==null)return await t(A)?D:void 0},h=async(A,D,f,b,C,w)=>{let I=await r(A,f,D);if(!ge(A.commentable,I.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(I.sourceType.toLowerCase()!==qe.toLowerCase())throw new Error("Comments are restricted for external daily report sources");let $=await m(f,I.userId),N=await d(),v=await c(async _=>{await Vt(_,R,f,null);let[U]=await _.insert(p).output().values({hubId:f,userId:D,body:b,createdAt:new Date,createdBy:String(D),updatedAt:new Date,updatedBy:String(D)});return N!==null&&await N.writeHubs(_,[f]),U}),[L]=await o.select({displayName:i.displayName}).top(1).from(i).where(Io(i.id,D)),F=L?.displayName??"";if(C){let _=Pe(C);_&&(s.invalidatePrefix($t(_)),await n(`${ke}${_}`))}s.invalidatePrefix(Fe(f)),await n(`${tt}${f}`);let T={id:v.id,userId:l(v.userId),userName:F,content:v.body,createdAt:be(v.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await u(gn.parse({type:"comment-add",reportHubId:f,comment:T,clientTempId:w,recipientRawUserId:$,sourceType:I.sourceType}),"addComment"),T},y=async(A,D)=>await A.select().top(1).from(p).where(Io(p.id,D));return{addComment:h,deleteComment:async(A,D,f,b,C,w)=>{let I=await y(o,b);if(I.length===0)throw new Error("Not Found");if(I[0].hubId!==f)throw new Error("Not Found");let $=await r(A,I[0].hubId,D);if(I[0].userId!==D)throw new Error("Unauthorized");let N=await m(f,$.userId),v=await d();if(await c(async L=>{await Vt(L,R,f,null),await L.delete(p).where(Io(p.id,b)),v!==null&&await v.writeHubs(L,[f])}),C){let L=Pe(C);L&&(s.invalidatePrefix($t(L)),await n(`${ke}${L}`))}s.invalidatePrefix(Fe(f)),await n(`${tt}${f}`),await u(bn.parse({type:"comment-delete",reportHubId:f,commentId:b,clientTempId:w,recipientRawUserId:N,sourceType:$.sourceType}),"deleteComment")}}};import{and as ml,eq as Ct,isNull as Hm}from"drizzle-orm";var yl=e=>e===""?null:e,hl=(e,{readCanonicalDraftLabelId:t,isDraftReport:r,getDailyReportDetailById:n,assertHubMutable:o,incrementRedisEpoch:a})=>{let{db:i,tables:l,cache:s,logger:c,inTransaction:d,prepareSearchIndex:u,publishToSseStream:R,settings:p,draftVisibilityTables:m}=e,{hub:h,internal:y,hubLabel:S,userStatus:A}=l,{canonicalDraftLabelName:D,draftLabelNames:f}=p,b=async(F,T,_,U)=>{if(!gr(_))throw K("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",_);if(!ge(F.visible,qe))throw new Error("Forbidden");c.info("createDailyReport called",{userId:T,businessDate:_});let z=await u();try{let X=await d(async Z=>{c.info("Starting transaction");let ve=await t(Z);if(ve===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(D)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let O=`internal-temp-${Date.now()}-${Math.random()}`,[g]=await Z.insert(h).output().values({sourceType:qe,sourceId:O,businessDate:new Date(`${_}T00:00:00Z`),userId:T,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(T),updatedAt:new Date,updatedBy:String(T)});return await Z.update(h).set({sourceId:String(g.id)}).where(Ct(h.id,g.id)),c.info("Hub created",g),await Z.insert(y).values({hubId:g.id,body:"",createdAt:new Date,createdBy:String(T),updatedAt:new Date,updatedBy:String(T)}),c.info("Internal created"),await Z.insert(S).values({hubId:g.id,labelId:ve,createdAt:new Date,createdBy:String(T)}),c.info("Label assigned"),await Z.insert(A).values({hubId:g.id,userId:T,isRead:!0,isStarred:!1,createdAt:new Date,createdBy:String(T),updatedAt:new Date,updatedBy:String(T)}),z!==null&&await z.writeHubs(Z,[g.id]),g.id});s.invalidatePrefix(Bt(_,T)),s.invalidatePrefix(yo(T)),await a(ft),await a(`${ke}${_}`);let G=await n(Ye.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),X,T,{forceRefresh:!0});if(G===null)throw new Error(`[daily-report] createDailyReport: report ${X} was committed but its detail read returned nothing`);let de=await r(G.reportHubId);await R(Tn.parse({type:"report-create",reportHubId:G.reportHubId,report:G,clientTempId:U,recipientRawUserId:de?T:void 0,actorRawUserId:T}),"createDailyReport");let me=await n(F,X,T,{forceRefresh:!0});if(me===null)throw new Error(`[daily-report] createDailyReport: the actor's scope cannot read report ${X} it just created`);return me}catch(X){throw c.error("Error in createDailyReport",X),X}},C=async(F,T)=>await F.select().top(1).from(h).where(Ct(h.id,T)),w=async(F,T,_)=>{await o(F,T,_);let[U]=await C(i,T);if(U===void 0||U.deletedAt)throw new Error("Not Found");if(U.userId!==_)throw new Error("Unauthorized");return U},I=async(F,T,_)=>{await F.update(h).set(_).where(Ct(h.id,T))},$=async(F,T,_)=>{await F.update(y).set(_).where(Ct(y.hubId,T))};return{createDailyReport:b,updateDailyReport:async(F,T,_,U,z)=>{let X=await w(F,T,_),G=await u();await d(async Z=>{await Vt(Z,h,T,_),U.title!==void 0&&await I(Z,T,{title:yl(U.title),updatedAt:new Date,updatedBy:String(_)}),U.content!==void 0&&await $(Z,T,{body:yl(U.content),updatedAt:new Date,updatedBy:String(_)}),G!==null&&await G.writeHubs(Z,[T])}),s.invalidatePrefix(Fe(T)),await a(`${tt}${T}`);let de=Pe(be(X.businessDate,"YYYY-MM-DD"));de&&(s.invalidatePrefix($t(de)),await a(`${ke}${de}`));let me=await n(Ye.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),T,_,{forceRefresh:!0});if(me){let Z=await r(T);await R(En.parse({type:"report-update",reportHubId:me.reportHubId,report:me,clientTempId:z,recipientRawUserId:Z?_:void 0,actorRawUserId:_}),"updateDailyReport")}},publishDailyReport:async(F,T,_,U)=>{let z=await w(F,T,_),X=await u();if(await d(async Z=>{await Vt(Z,h,T,_),await Z.delete(S).where(ml(Ct(S.hubId,T),Os(m,f))),X!==null&&await X.writeHubs(Z,[T])}),s.invalidatePrefix(Fe(T)),s.invalidatePrefix(pt),await a(ft),z.businessDate){let Z=Pe(be(z.businessDate,"YYYY-MM-DD"));Z&&await a(`${ke}${Z}`)}let G=Pe(be(z.businessDate,"YYYY-MM-DD"));G&&s.invalidatePrefix(Bt(G,_));let de=await n(Ye.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),T,_,{forceRefresh:!0});if(de===null)return null;let me=await r(T);return await R(wn.parse({type:"report-publish",reportHubId:de.reportHubId,report:de,clientTempId:U,recipientRawUserId:me?_:void 0,actorRawUserId:_}),"publishDailyReport"),await n(F,T,_,{forceRefresh:!0})},deleteDailyReport:async(F,T,_,U)=>{let z=await w(F,T,_);if(await d(async X=>{if((await X.update(h).set({deletedAt:new Date,deletedBy:String(_),updatedAt:new Date,updatedBy:String(_)}).output().where(ml(Ct(h.id,T),Ct(h.userId,_),Hm(h.deletedAt)))).length===0)throw new Error("Not Found")}),s.invalidatePrefix(Fe(T)),s.invalidatePrefix(pt),await a(ft),z.businessDate){let X=Pe(be(z.businessDate,"YYYY-MM-DD"));X&&await a(`${ke}${X}`)}await R(Ar.parse({type:"report-delete",reportHubId:T,clientTempId:U,sourceType:z.sourceType}),"deleteDailyReport")}}};import{and as qt,asc as fl,desc as Rr,eq as we,inArray as _o,isNull as tn,sql as Um}from"drizzle-orm";var Rl=Tr([]),Sl=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r,draftLabelFlag:n,externalSelections:o,applyExternalJoins:a,resolveHubDisplayFields:i,resolveCreationCategoryDraftLabelId:l,mapHubRecord:s,getAttachmentsByHubIds:c,readSseStreamAnchor:d,incrementRedisEpoch:u})=>{let{db:R,tables:p,users:m,resolveUserId:h,cache:y,epochs:S,logger:A,settings:D}=e,{hub:f,internal:b,comment:C,label:w,hubLabel:I,userStatus:$}=p,N=D.idsTtlMs,v=D.businessDateTtlMs,L=async(O,g)=>(await R.select({reportHubId:f.id,businessDate:f.businessDate,sourceType:f.sourceType}).from(f).where(qt(tn(f.deletedAt),t(g,"author-or-authorless"),r(O.visible))).orderBy(Rr(f.businessDate),Rr(f.id))).map(E=>({...E,businessDate:be(E.businessDate,"YYYY-MM-DD")})),F=async(O,g,x)=>{let E=await _(g);return E?Me(O.visible)?[]:(await R.select({reportHubId:f.id,businessDate:f.businessDate,sourceType:f.sourceType}).top(x).from(f).where(qt(tn(f.deletedAt),t(E,"author-or-authorless"),r(O.visible))).orderBy(Rr(f.businessDate),Rr(f.id))).map(k=>({...k,businessDate:be(k.businessDate,"YYYY-MM-DD")})):[]},T=new Map,_=async O=>{if(!D.disableUserIdCache&&T.has(O))return T.get(O)??null;let g=await h(O);return g!==null&&!D.disableUserIdCache&&T.set(O,g),g},U=async(O,g,{forceRefresh:x=!1,snapshot:E=!1,ttlMsOverride:P,onFetchStart:k,admission:B}={})=>{let j=await _(g);if(!j)return{items:[],streamAnchor:null,snapshot:Rl};if(Me(O.visible))return{items:[],streamAnchor:await d(),snapshot:Rl};let H=ds(j,Hr(O)),[W]=await y.getOrFetch({cacheKey:H,fetcher:async()=>{let M=await d(),J=await L(O,j);if(!la(J)){A.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let Y=[...J].sort(_n);return[{items:Y,streamAnchor:M,snapshot:Tr(Y)}]}return[{items:J,streamAnchor:M,snapshot:Tr(J)}]},onFetchStart:k,forceRefresh:x,snapshot:E,admission:B,ttlMsOverride:P??N,epochKey:ft,refreshAheadRatio:.5});if(W===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return W},z=async(O,g,x)=>{let E=await a(R.select({hub:lt(f),internal:lt(b),isRead:$.isRead,isStarred:$.isStarred,creatorName:m.displayName,hasDraftLabel:n,...o()}).from(f)).leftJoin(b,we(f.id,b.hubId)).leftJoin($,qt(we(f.id,$.hubId),we($.userId,g))).leftJoin(m,we(f.userId,m.id)).where(qt(x,tn(f.deletedAt),t(g,"author"),r(O.visible))).orderBy(Rr(f.id));if(E.length===0)return[];let P=E.map(Y=>Y.hub.id),k=await R.select({hubId:I.hubId,id:w.id,name:w.name,color:w.color}).from(I).innerJoin(w,we(I.labelId,w.id)).where(_o(I.hubId,P)),B=await R.select({hubId:C.hubId,id:C.id,body:C.body,createdAt:C.createdAt,userId:C.userId,userName:m.displayName}).from(C).leftJoin(m,we(C.userId,m.id)).where(_o(C.hubId,P)).orderBy(fl(C.createdAt)),j=await c(P),H=new Map,W=new Map;for(let Y of k){let Q=H.get(Y.hubId);Q||(Q=[],H.set(Y.hubId,Q)),Q.push({id:Y.id,name:Y.name,color:Y.color})}for(let Y of B){let Q=W.get(Y.hubId);Q||(Q=[],W.set(Y.hubId,Q)),Q.push({id:Y.id,content:Y.body,createdAt:be(Y.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Y.userId,userName:Y.userName||""})}let M=E.map(i),J=await l(M);return E.map((Y,Q)=>{let St=Y.hub.id;return s(O,{...Y,attachments:j.get(St)??[],labels:H.get(St)||[],postedCommentRows:W.get(St)||[]},M[Q],J,g)})},X=async(O,g,x,{forceRefresh:E=!1,snapshot:P=!1,ttlMsOverride:k,admission:B}={})=>{let j=await _(x);if(!j)return[];let H=Pe(g);if(!H)return[];if(Me(O.visible))return[];let W=ps(H,j,Hr(O));return y.getOrFetch({cacheKey:W,fetcher:()=>z(O,j,we(f.businessDate,Um`${H}`)),forceRefresh:E,snapshot:P,admission:B,ttlMsOverride:k??v,epochKey:`${ke}${H}`})},G=async(O,g,x,{forceRefresh:E=!1,snapshot:P=!1,ttlMsOverride:k,admission:B}={})=>{if(Me(O.visible))return null;let j=ms(g,x,Hr(O));return(await y.getOrFetch({cacheKey:j,fetcher:async()=>{let W=await a(R.select({hub:lt(f),internal:lt(b),isRead:$.isRead,isStarred:$.isStarred,creatorName:m.displayName,hasDraftLabel:n,...o()}).from(f)).leftJoin(b,we(f.id,b.hubId)).leftJoin($,qt(we(f.id,$.hubId),we($.userId,x))).leftJoin(m,we(f.userId,m.id)).where(qt(we(f.id,g),tn(f.deletedAt),t(x,"author"),r(O.visible)));if(W.length===0)return[];let M=W[0].hub.id,J=await R.select({id:w.id,name:w.name,color:w.color}).from(I).innerJoin(w,we(I.labelId,w.id)).where(we(I.hubId,M)),Y=await R.select({id:C.id,body:C.body,createdAt:C.createdAt,userId:C.userId,userName:m.displayName}).from(C).leftJoin(m,we(C.userId,m.id)).where(we(C.hubId,M)).orderBy(fl(C.createdAt)),Q=await c([M]),St=J.map(He=>({id:He.id,name:He.name,color:He.color})),cn=Y.map(He=>({id:He.id,content:He.body,createdAt:be(He.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:He.userId,userName:He.userName||""})),Yt=i(W[0]),un=await l([Yt]);return[s(O,{...W[0],attachments:Q.get(M)??[],labels:St,postedCommentRows:cn},Yt,un,x)]},forceRefresh:E,snapshot:P,admission:B,ttlMsOverride:k??v,epochKey:`${tt}${g}`}))[0]??null};return{getUserIdByExternalId:_,getDailyReportIdsByExternalId:U,getDailyReportIdsFirstPageByExternalId:F,getDailyReportsByBusinessDateByExternalId:X,getDailyReportDetailById:G,getDailyReportDetailByIdByExternalId:async(O,g,x,E={})=>{let P=await _(x);return P?G(O,g,P,E):null},getDailyReportDetailsByIdsByExternalId:async(O,g,x)=>{if(g.length>Te.maxDetailIds)throw K("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${Te.maxDetailIds} ids`,g.length);let E=await _(x);return!E||g.length===0?[]:Me(O.visible)?[]:z(O,E,_o(f.id,[...g]))},fetchVisibleHubDetails:z,invalidateHubReadCaches:async(O,g)=>{y.invalidatePrefix(pt),await u(ft);for(let x of new Set(O))y.invalidatePrefix(Fe(x)),await u(`${tt}${x}`);for(let x of new Set(g)){let E=Pe(x);E&&await u(`${ke}${E}`)}},clearCache:async()=>{y.clearAll(),T.clear(),S&&await u(ft),A.info("Server-side DB/SQL caches cleared successfully.")}}};var rn=Object.freeze({idsTtlMs:18e4,businessDateTtlMs:3e5,streamKey:"daily-report:sse-stream",streamMaxLen:1e4}),$m=e=>{let{length:t}=e;if(t===void 0)throw K("tables.hub.title","a character column with a declared length",t);return ae("tables.hub.title.length",t,1)},Bm=e=>{if(!Array.isArray(e)||e.length===0||e.some(t=>typeof t!="string"||t.trim().length===0)||new Set(e).size!==e.length)throw K("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},Vm=e=>{let t=new Map([[qe.toLowerCase(),`the internal source type ${JSON.stringify(qe)}`]]);for(let[r,{sourceType:n}]of e.entries()){let o=`externalSources[${r}].sourceType`,a=t.get(n.toLowerCase());if(a!==void 0)throw K(o,`a source type that differs, ignoring case, from ${a}`,n);t.set(n.toLowerCase(),`${o} ${JSON.stringify(n)}`)}return Object.freeze([qe,...e.map(r=>r.sourceType)])},gl=e=>{let t=e.externalSources??[],r=Bm(e.draftLabelNames);kr(e);let n=Ti(e.attachments),o=$m(e.tables.hub.title);no(e.tables.hub.sourceType);let a=_e("idsTtlMs",e.idsTtlMs,1,rn.idsTtlMs),i=_e("businessDateTtlMs",e.businessDateTtlMs,1,rn.businessDateTtlMs),l=_e("streamMaxLen",e.streamMaxLen,1,rn.streamMaxLen);return Object.freeze({externalSources:t,sourceTypes:Vm(t),draftLabelNames:r,canonicalDraftLabelName:r[0],attachmentDelivery:n,titleMaxLength:o,idsTtlMs:a,businessDateTtlMs:i,streamKey:e.streamKey??rn.streamKey,streamMaxLen:l,disableUserIdCache:!!e.disableUserIdCache})};import{and as qm,eq as Ym,sql as fe}from"drizzle-orm";var nn=["hubId","userId","isRead","isStarred","createdAt","createdBy","updatedAt","updatedBy"],jm={isRead:{statusType:"read",callerName:"setReadStatus"},isStarred:{statusType:"star",callerName:"setStarStatus"}},Ne=e=>fe`${fe.identifier(e.name)}`,Wm=(e,t,{reportHubId:r,userId:n,value:o,at:a})=>{let i=String(n),l=Ne(e[t]),s=(p,m)=>fe`t.${Ne(p)} = CASE WHEN t.${l} = ${o} THEN t.${Ne(p)} ELSE ${m} END`,c={hubId:fe`s.${Ne(e.hubId)}`,userId:fe`s.${Ne(e.userId)}`,isRead:fe`${t==="isRead"?o:!1}`,isStarred:fe`${t==="isStarred"?o:!1}`,createdAt:fe`${a}`,createdBy:fe`${i}`,updatedAt:fe`${a}`,updatedBy:fe`${i}`},d=fe.join(nn.map(p=>Ne(e[p])),fe`, `),u=fe.join(nn.map(p=>c[p]),fe`, `),R=fe.join(nn.map(p=>fe`inserted.${Ne(e[p])} AS ${fe.identifier(p)}`),fe`, `);return fe`MERGE ${e} WITH (HOLDLOCK) AS t USING (SELECT ${r} AS ${Ne(e.hubId)}, ${n} AS ${Ne(e.userId)}) AS s ON t.${Ne(e.hubId)} = s.${Ne(e.hubId)} AND t.${Ne(e.userId)} = s.${Ne(e.userId)}
|
|
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));`},ol=(e,t)=>q`SELECT ${Y(e.hubId)} AS ${q.identifier(_e.hubId)}, LOWER(CONVERT(char(64), ${Y(e.sourceDigest)}, 2)) AS ${q.identifier(_e.sourceDigest)}, ${Y(e.normalizerVersion)} AS ${q.identifier(_e.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${Er(t)})`,al=(e,t,r)=>q`SELECT TOP (${r}) ${Y(e.id)} AS ${q.identifier(_e.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var il=e=>({search:async(t,r)=>ve(r.scope.visible)?[]:wt(await t.execute(el(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Ft(o[Qe.sourceType],Qe.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${Qe.sourceType} is null`);return{reportHubId:Ht(o[Qe.reportHubId],Qe.reportHubId),businessDate:Ft(o[Qe.businessDate],Qe.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(ve(r.scope.visible))return new Map;let n=wt(await t.execute(tl(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[Ut.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${Ut.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(Ht(i[Ut.reportHubId],Ut.reportHubId),l)}return a},facetValues:async(t,r)=>ve(r.scope.visible)?[]:wt(await t.execute(rl(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Ft(o[wr.value],wr.value);if(a===null)throw new Error(`[daily-report] search: column ${wr.value} is null`);return a})});import{chunk as an,MAX_IN_LIST as sn}from"@aiquants/mssql";import{sql as ll}from"drizzle-orm";import{createHash as Rm}from"crypto";var Sm=Object.freeze({authorName:"author",customerName:"customer"}),Po=e=>e===null?null:jn(e),sl=(e,t,r)=>{let n=Po(r);if(n!==null&&n.length>pt.maxValueLength){let o=pt.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${Sm[t]} display value has ${n.length} UTF-16 units after trimming; the host must keep the author and customer display values at most ${o} UTF-16 units`)}return n},Ir=e=>e===null?"n;":`s${e.length}:${e}`,_r="utf16le",gm=e=>{let t=Rm("sha256");t.update(`F${e.fields.length};`,_r);for(let[r,n]of e.fields)t.update(Ir(r)+Ir(n),_r);return t.update(`C${e.comments.length};`,_r),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${Ir(r.text)}`,_r)}),t.update(`P;${Ir(Po(e.filterValues.authorName))}${Ir(Po(e.filterValues.customerName))}`,_r),t.digest("hex")},ko=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=en(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=en(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:hs(r),comments:n,sourceDigest:gm(e),forcedCuts:t,authorName:sl(e.hubId,"authorName",e.filterValues.authorName),customerName:sl(e.hubId,"customerName",e.filterValues.customerName)}};var cl=e=>{let t=async(s,c)=>{let d=[];for(let u of an(c,sn))for(let R of wt(await s.execute(Xs(e.hub,u))))d.push(Ht(R[_e.hubId],_e.hubId));return d},r=async(s,c)=>{for(let d of an(c,sn))await s.execute(nl(e.tables,d,e.normalizerVersion))},n=async(s,c)=>{let d=new Map;for(let u of an(c,sn))for(let R of wt(await s.execute(ol(e.tables.document,u))))d.set(Ht(R[_e.hubId],_e.hubId),{sourceDigest:Ft(R[_e.sourceDigest],_e.sourceDigest),normalizerVersion:Ft(R[_e.normalizerVersion],_e.normalizerVersion)});return d},o=async(s,c,d)=>wt(await s.execute(al(e.hub,c,d))).map(u=>Ht(u[_e.hubId],_e.hubId)),a=async(s,c)=>{let d=await t(s,[...new Set(c)].sort((R,p)=>R-p));if(d.length===0)return;let u=(await e.loadSources(s,d)).map(ko);u.length>0&&await r(s,u)},i=s=>e.inTransaction(async c=>{await c.execute(ll`SET DEADLOCK_PRIORITY LOW`);let d=await t(c,s),u=await n(c,d),R=(await e.loadSources(c,d)).map(ko),p=R.filter(m=>{let h=u.get(m.hubId);return h===void 0||h.sourceDigest!==m.sourceDigest||h.normalizerVersion!==e.normalizerVersion});return p.length>0&&await r(c,p),await c.execute(ll`SET DEADLOCK_PRIORITY NORMAL`),{scanned:R.length,written:p.length,forcedCuts:R.reduce((m,h)=>m+h.forcedCuts,0)}});return{writeHubs:a,reconcile:async(s,c)=>{let{batchSize:d,hubIds:u,signal:R,onProgress:p}=c;ie("reconcileSearchIndex: batchSize",d,1,sn);let m=se(),h=u===void 0?null:an([...new Set(u)].sort((S,A)=>S-A),d),y={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let S=0;;S++){R?.throwIfAborted();let A=h===null?await o(s,y.lastHubId===null?0:y.lastHubId,d):h[S];if(A===void 0||A.length===0)break;let D=await i(A);y={scanned:y.scanned+D.scanned,written:y.written+D.written,skipped:y.skipped+D.scanned-D.written,forcedCuts:y.forcedCuts+D.forcedCuts,lastHubId:A[A.length-1]},p?.(y)}return{...y,elapsedMs:se()-m}}}};import{holdsMultiUnitCluster as bm}from"@aiquants/fuzzy-search/normalize";var Lo=255,ln=Object.values(Nt).sort((e,t)=>e-t),Dm=new Intl.Segmenter("und",{granularity:"grapheme"}),he=Object.freeze({strip:30,split:200,line:2e3,plan:90,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),lt=5e5,cn=Math.floor(lt/he.linear),Am=Math.floor(lt/he.segment),ul=Math.floor(lt/he.sweep),pl=Math.floor(lt/he.scan),xr=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),ml=(e,t)=>{let r=0,n=t(),o=lt,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+lt,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=lt,a=!1}}},Og=Object.freeze({fits:()=>!0,charge:()=>{}}),yl=e=>{let t=null;return{step:()=>{if(t!==null)return!0;let r=e.next();return r.done!==!0?!1:(t={result:r.value},!0)},result:()=>{if(t===null)throw new Error("[daily-report] search marks: the walk is not done (step until it returns true)");return t.result}}};var Tm=(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},Em=(e,t)=>e.chunks.length===1&&e.chunks[0].length===1&&e.chunks[0][0].start===0&&e.chunks[0][0].end===t.length;function*wm(e,t,r,n){let o=!1;for(let c=t;c<r&&!o;c+=cn){let d=Math.min(r,c+cn),u=(d-c)*he.linear;n.fits(u)||(yield),o=bm(e.slice(c,d)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=Dm.segment(e.slice(t,r))[Symbol.iterator](),s=l.next();for(;!s.done;){let c=Math.max(Am,s.value.segment.length);n.fits(c*he.segment)||(yield);let d=0;for(;!s.done&&d+s.value.segment.length<=c;){let{index:u,segment:R}=s.value;a.fill(t+u,u,u+R.length),i.fill(t+u+R.length,u,u+R.length),d+=R.length,s=l.next()}n.charge(d*he.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var Im=256,_m=e=>{let t=new Int32Array(e.length),r=0;for(let n=1;n<e.length;n++){for(;r>0&&e.charCodeAt(n)!==e.charCodeAt(r);)r=t[r-1];e.charCodeAt(n)===e.charCodeAt(r)&&r++,t[n]=r}return e.length-t[e.length-1]},xm=e=>{let t=new Map;for(let r of e){if(r.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let n=t.get(r.text);(n===void 0||r.tier<n)&&t.set(r.text,r.tier)}return[...t].map(([r,n])=>{let o=_m(r),a=Math.max(pl-r.length+1,r.length);if(o===r.length)return{text:r,tier:n,periodic:null,windowStarts:a};let i=r.length%o,l=r.slice(i,o)+r.slice(0,i);return{text:r,tier:n,periodic:{period:o,continuation:l.repeat(Math.ceil(Im/o))},windowStarts:a}})},un=(e,t)=>{let{pieces:r}=e,n=r[e.lastPiece];if(n.plainStart<=t&&t<n.plainStart+n.text.length)return e.lastPiece;let o=0,a=r.length-1;for(;o<a;){let i=o+a+1>>1;r[i].plainStart<=t?o=i:a=i-1}return t>=r[o].plainStart+r[o].text.length?-1:(e.lastPiece=o,o)},dl=(e,t,r)=>{let n=un(e,t);return e.pieces[n>=0?n:un(e,r==="start"?t-1:t+1)]},hl=(e,t)=>{let r=un(e,t);if(r<0)return fl(e,t-1);let n=e.pieces[r];return n.start+n.mapped.start[t-n.plainStart]},fl=(e,t)=>{let r=un(e,t);if(r<0)return hl(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},Cm=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),Mm=Object.freeze({kind:"done"}),vo=Object.freeze({kind:"slice"}),Pm=Object.freeze({kind:"clusters"}),km=(e,t,r,n,o,a)=>{let{plain:i}=e,{text:l,tier:s,periodic:c}=r;for(;;){if(n.closedEnd>=0){if(!o.fits(he.run))return vo;let p=dl(e,n.closedStart,"start"),m=dl(e,n.closedEnd-1,"end");if(p.mapped===null)return{kind:"map",piece:p};if(m.mapped===null)return{kind:"map",piece:m};if(e.isCut&&e.clusters===void 0)return Pm;let h=t(e.offset+hl(e,n.closedStart)),y=t(e.offset+fl(e,n.closedEnd-1)-1)+1;n.closedEnd=-1;let S=e.clusters;S==null?a(h,y,s):a(S.clusterStarts[h-S.start],S.clusterEnds[y-1-S.start],s),o.charge(he.run);continue}if(c!==null&&n.periodicEnd>=0){if(!o.fits(lt))return vo;let{period:p,continuation:m}=c,h=n.periodicEnd,y=Math.min(i.length,h+Math.max(pl,m.length)),S=h;for(;S+m.length<=y&&i.startsWith(m,S);)S+=m.length;let A=S+m.length>y&&y<i.length;if(!A)for(;S<i.length&&i.charCodeAt(S)===i.charCodeAt(S-p);)S++;if(o.charge((S-h)*he.scan),A){n.periodicEnd=S;continue}n.periodicEnd=-1,n.last+=Math.floor((S-n.last-l.length)/p)*p,n.from=n.last+l.length-p+1;continue}if(n.from<0){if(n.runStart<0)return Mm;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(lt))return vo;n.from>=n.windowEnd&&(n.windowStart=n.from,n.windowEnd=n.from+r.windowStarts,n.window=i.slice(n.from,n.windowEnd+l.length-1));let d=n.from-n.windowStart,u=n.window.indexOf(l,d);if(u<0){o.charge((n.window.length-d)*he.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-d)*he.scan);let R=n.windowStart+u;(n.runStart<0||R>=n.last+l.length)&&(n.runStart>=0&&(n.closedStart=n.runStart,n.closedEnd=n.last+l.length),n.runStart=R),n.last=R,c===null?n.from=R+1:n.periodicEnd=R+l.length}};function*No(e,t,r){let n=Math.floor(lt/t);for(;!e.done();)r.fits(n*t)||(yield),r.charge(e.advance(n)*t);return e.result()}function*Lm(e,t,r,n,o){if(t.length===0)return;let a=yield*No(fs(e),he.strip,n),i=[],l=[];yield*No(Rs(a.text,(c,d)=>{i.push(d),l.push(d+c.length)}),he.split,n);let s=c=>a.rawIndex===null?c:a.rawIndex[c];for(let c=0;c<i.length;c++){n.fits(he.line)||(yield),n.charge(he.line);let d=i[c],u=a.text.slice(d,l[c]),R=yield*No(Ss(u,r),he.plan,n),p=[],m="";for(let y of R.chunks){let S="",A=[];for(let D of y){let f=(D.end-D.start)*he.normalize;n.fits(f)||(yield);let g=bo(D.start===0&&D.end===u.length?u:u.slice(D.start,D.end),r).text;n.charge(f),g.length>0&&A.push({start:D.start,end:D.end,text:g,chunkStart:S.length}),S+=g}if(S.length!==0){m.length>0&&(m+=" ");for(let D of A)p.push({start:D.start,end:D.end,text:D.text,plainStart:m.length+D.chunkStart,mapped:null});m+=S}}if(m.length===0)continue;let h={offset:d,plain:m,pieces:p,isCut:!Em(R,u),lastPiece:0,clusters:void 0};for(let y of t){let S=Cm();for(;;){let A=km(h,s,y,S,n,o);if(A.kind==="done")break;if(A.kind==="slice"){yield;continue}if(A.kind==="clusters"){h.clusters=yield*wm(e,s(d),s(d+u.length-1)+1,n);continue}let{piece:D}=A,f=(D.end-D.start)*he.map;n.fits(f)||(yield);let g=u.slice(D.start,D.end);D.mapped=Tm(ys(g,go(g,r)),D.text),n.charge(f)}}}}function*vm(e,t,r,n){let o=new Int32Array(ln.length),a=0,i=Lo;for(let l=0;l<=e;l+=ul){let s=Math.min(e+1,l+ul),c=(s-l)*he.sweep;r.fits(c)||(yield);for(let d=l;d<s;d++){let u=Lo;for(let R=ln.length-1;R>=0;R--){let p=ln[R];o[p]+=t[p][d],o[p]>0&&(u=p)}if(u!==i){if(i!==Lo&&!n(a,d,i))return!1;a=d,i=u}}r.charge(c)}return!0}function*Nm(e,t,r,n,o){let a=null;return yield*Lm(e,t,r,n,(l,s,c)=>{a===null&&(a=ln.map(()=>new Int32Array(e.length+1))),a[c][l]++,a[c][s]--}),a===null?!0:yield*vm(e.length,a,n,o)}var Om=(e,t,r,n)=>{let o=xm(t),a=[],i=(s,c,d)=>(a.push(s,c,d),a.length<=3*r.maxRanges);return yl(function*(){return(yield*Nm(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var Rl=(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)},Sl=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of Ia)r(dt.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(dt.interviewer(o,"name"),n.name),r(dt.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(dt.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(dt.comment(Un(o),"author"),n.name),r(dt.comment(Un(o),"content"),n.text)});for(let n of e.postedComments)r(dt.comment(n.id,"author"),n.userName),r(dt.comment(n.id,"content"),n.content);return t};function*Hm(e,t){let r=Vn;for(let n=0;n<e.length;n+=cn){let o=Math.min(e.length,n+cn),a=(o-n)*he.linear;t.fits(a)||(yield),r=qn(r,e,n,o),t.charge(a)}return r}var gl=async(e,t,r,n)=>{let o=0,a=0,i=async c=>{for(;!c.step();)await r(),n.startSlice();return c.result()},l=async(c,d)=>{if(!d&&a>t.maxRanges)return null;let u={};for(let{key:R,value:p}of c.fields){if(!d&&o+p.length>t.maxUnits)return null;let m=await i(yl(Hm(p,n))),h=await i(Om(p,c.alternatives,{maxLength:fo,maxRanges:t.maxFieldRanges},n));if(o+=p.length,h.dense){u[R]={fingerprint:m,dense:!0};continue}if(u[R]={fingerprint:m,ranges:h.ranges},a+=h.ranges.length/3,!d&&a>t.maxRanges)return null}return u},s=[];for(let c=0;c<e.length;c++){let d=e[c],u=await l(d,s.length===0);if(u===null)return{reports:s,deferred:e.slice(c).map(R=>R.reportHubId)};s.push({reportHubId:d.reportHubId,matchedSets:d.matchedSets,fields:u})}return{reports:s,deferred:[]}};import{and as Bm,asc as Al,eq as pn,inArray as Vm,isNull as qm}from"drizzle-orm";import{and as bl,asc as Fm,eq as dn,getColumns as Um,sql as $m}from"drizzle-orm";var St=e=>Um(e),Te=(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"),s=String(r.getMinutes()).padStart(2,"0"),c=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${s}:${c}`},Dl=e=>{let{db:t,tables:r,encodeUserId:n,settings:o,draftVisibilityTables:a}=e,{hub:i,label:l}=r,{externalSources:s,draftLabelNames:c,canonicalDraftLabelName:d}=o,u=L=>Sr(i.sourceType,L),R=(L,v)=>on(a,L,c,v),p=$m`CASE WHEN ${nn(a,c)} THEN 1 ELSE 0 END`,m=async L=>{let[v]=await t.select({id:i.id}).top(1).from(i).where(bl(dn(i.id,L),nn(a,c)));return v!==void 0},h=L=>L==null||L===""?null:/^\d+$/.test(L)?n(Number(L)):L,y=()=>{let L={};for(let v of s)L[`ext_${v.sourceType}`]=St(v.table);return L},S=L=>{let v=L;for(let k of s)v=v.leftJoin(k.table,bl(dn(i.sourceType,k.sourceType),dn(i.sourceIdNum,k.idColumn)));return v},A=L=>{let{hub:v,internal:k}=L,$=v.summary,T=[],w=null,B=null,G=null,Z=null,j=null,pe=null,ye=[],J=s.find(Q=>Q.sourceType===v.sourceType),Le=J?L[`ext_${J.sourceType}`]:void 0;if(J&&Le){let Q=J.mapRow(Le);Q.content!==void 0&&($=Q.content),Q.employeeName!==void 0&&(pe=Q.employeeName),Q.category!==void 0&&(w=Q.category),Q.creationCategory!==void 0&&(B=Q.creationCategory),Q.visitTimeFrom!==void 0&&(G=Q.visitTimeFrom),Q.visitTimeTo!==void 0&&(Z=Q.visitTimeTo),Q.customerName!==void 0&&(j=Q.customerName),Q.interviewers!==void 0&&(T=Q.interviewers),Q.externalComments!==void 0&&(ye=Q.externalComments)}else v.sourceType===Ke&&k&&($=k.body);return{content:$,author:L.creatorName??h(v.createdBy)??"",employeeName:pe??L.creatorName??h(v.createdBy),updatedBy:h(v.updatedBy),category:w,creationCategory:B,visitTimeFrom:G,visitTimeTo:Z,customerName:j,interviewers:T,externalComments:ye}},D=L=>{if(L===1)return!0;if(L===0)return!1;throw new Error(`[daily-report] a detail row's hasDraftLabel must be 1 or 0 (the read must select draftLabelFlag); got ${Pt(L)}`)},f=L=>L.creationCategory!==null&&c.includes(L.creationCategory),g=(L,v)=>D(L.hasDraftLabel)?!0:f(v),P=async L=>{let[v]=await L.select({id:l.id}).top(1).from(l).where(dn(l.name,d)).orderBy(Fm(l.id));return v===void 0?null:v.id},_=()=>P(t);return{visibleSourceTypeCondition:u,draftVisibleTo:R,draftLabelFlag:p,isDraftReport:m,externalSelections:y,applyExternalJoins:S,resolveHubDisplayFields:A,readCanonicalDraftLabelId:P,getDraftLabelId:_,resolveCreationCategoryDraftLabelId:L=>L.some(f)?_():Promise.resolve(null),mapHubRecord:(L,v,k,$,T)=>{let{hub:w}=v,B=v.labels.map(j=>({id:j.id,name:j.name,color:j.color})),G=v.postedCommentRows,Z=Ae(L.commentable,w.sourceType);return $!==null&&f(k)&&!B.some(j=>j.id===$)&&B.push({id:$,name:d,color:null}),{reportHubId:w.id,date:Te(w.businessDate,"YYYY-MM-DD"),author:k.author,userId:w.userId?n(w.userId):"",sourceType:w.sourceType,createdAt:Te(w.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:Te(w.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:k.updatedBy,employeeName:k.employeeName,category:k.category,creationCategory:k.creationCategory,visitTimeFrom:k.visitTimeFrom,visitTimeTo:k.visitTimeTo,customerName:k.customerName,interviewers:k.interviewers,subject:w.title,content:k.content,externalComments:Z?k.externalComments:[],isRead:v.isRead??!1,isStarred:v.isStarred??!1,isDraft:g(v,k),labels:B,postedComments:G.filter(j=>os({authorUserId:j.userId},w.sourceType,T,L)).map(j=>({...j,userId:n(j.userId),isMine:T?j.userId===T:!1})),attachments:v.attachments}}}};var Tl=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r})=>{let{db:n,tables:o,logger:a,settings:i}=e,{hub:l}=o,{attachmentDelivery:s}=i,c=(m,h)=>h!=null?"absent":m!=null?"present":"unknown";return{getAttachmentsByHubIds:async m=>{let h=new Map,y=o.attachment;if(m.length===0||!y||s===null)return h;let S=s.idCodec,A=s.thumbnails!==null,D=await n.select({id:y.id,hubId:y.hubId,fileName:y.fileName,fileType:y.fileType,fileSize:y.fileSize,createdAt:y.createdAt,objectCheckedAt:y.objectCheckedAt,objectMissingAt:y.objectMissingAt}).from(y).where(Vm(y.hubId,m)).orderBy(Al(y.createdAt),Al(y.id));for(let f of D){let g=f.fileType?String(f.fileType):null,P=f.fileSize!=null?Number(f.fileSize):null,_=c(f.objectCheckedAt,f.objectMissingAt),x={id:S.encode(Number(f.id)),fileName:String(f.fileName),fileType:g,fileSize:P,createdAt:Te(f.createdAt,"YYYY-MM-DD HH:mm:ss"),state:_,hasThumbnail:A&&_!=="absent"&&Vr({fileType:g,fileSize:P},s.maxBytes)},V=h.get(Number(f.hubId));V?V.push(x):h.set(Number(f.hubId),[x])}return h},getAttachmentForUser:async(m,h,y)=>{let S=o.attachment;return!S||ve(m.visible)?null:(await n.select({fileName:S.fileName,filePath:S.filePath,fileType:S.fileType,fileSize:S.fileSize}).top(1).from(S).innerJoin(l,pn(l.id,S.hubId)).where(Bm(pn(S.id,h),qm(l.deletedAt),t(y,"author"),r(m.visible))))[0]??null},markAttachmentMissing:async m=>{let h=o.attachment;if(!h)return;let y=new Date;try{await n.update(h).set({objectCheckedAt:y,objectMissingAt:y,updatedAt:y}).where(pn(h.id,m))}catch(S){a.error("markAttachmentMissing failed",S)}},markAttachmentPresent:async m=>{let h=o.attachment;if(!h)return;let y=new Date;try{await n.update(h).set({objectCheckedAt:y,objectMissingAt:null,updatedAt:y}).where(pn(h.id,m))}catch(S){a.error("markAttachmentPresent failed",S)}}}};import{eq as Oo}from"drizzle-orm";import{and as Ym,eq as El,isNull as Wm}from"drizzle-orm";var Xt=async(e,t,r,n)=>{if((await e.update(t).set({deletedAt:null}).output().where(Ym(El(t.id,r),Wm(t.deletedAt),n===null?void 0:El(t.userId,n)))).length===0)throw new Error("Not Found")};var _t="daily-report:ids:epoch",$e="daily-report:date-epoch:",ct="daily-report:detail-epoch:",wl=({redis:e,logger:t,epochs:r,streamKey:n,streamMaxLen:o})=>({incrementRedisEpoch:s=>r.incrementEpoch(s),publishToSseStream:async(s,c)=>{let d=await e?.getClient();if(!d){t.warn(`[SSE] Redis client unavailable (${c})`);return}let u=JSON.stringify(s),R=Buffer.byteLength(u);if(R>6356992){t.warn(`[SSE] Event too large (${c}): ${R} bytes > ${6356992}; not published`);return}let p=se();try{await d.xAdd(n,"*",{data:u},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:o}});let m=se()-p;m>1e3&&t.warn(`[SSE] Slow publish (${c}): ${m}ms`)}catch(m){t.error(`[SSE] Redis publish failed (${c}):`,m)}},readSseStreamAnchor:async()=>{try{let s=await e?.getClient();if(s===void 0)return null;let[c]=await s.xRevRange(n,"+","-",{COUNT:1});return c===void 0?At:c.id}catch(s){return t.error("SSE stream anchor read failed",s),null}}});var Il=(e,{isDraftReport:t,assertHubMutable:r,incrementRedisEpoch:n})=>{let{db:o,tables:a,users:i,encodeUserId:l,cache:s,inTransaction:c,prepareSearchIndex:d,publishToSseStream:u}=e,{hub:R,comment:p}=a,m=async(A,D)=>{if(D!==null)return await t(A)?D:void 0},h=async(A,D,f,g,P,_)=>{let x=await r(A,f,D);if(!Ae(A.commentable,x.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(x.sourceType.toLowerCase()!==Ke.toLowerCase())throw new Error("Comments are restricted for external daily report sources");let V=await m(f,x.userId),L=await d(),v=await c(async w=>{await Xt(w,R,f,null);let[B]=await w.insert(p).output().values({hubId:f,userId:D,body:g,createdAt:new Date,createdBy:String(D),updatedAt:new Date,updatedBy:String(D)});return L!==null&&await L.writeHubs(w,[f]),B}),[k]=await o.select({displayName:i.displayName}).top(1).from(i).where(Oo(i.id,D)),$=k?.displayName??"";if(P){let w=Fe(P);w&&(s.invalidatePrefix(Jt(w)),await n(`${$e}${w}`))}s.invalidatePrefix(qe(f)),await n(`${ct}${f}`);let T={id:v.id,userId:l(v.userId),userName:$,content:v.body,createdAt:Te(v.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await u(Mn.parse({type:"comment-add",reportHubId:f,comment:T,clientTempId:_,recipientRawUserId:V,sourceType:x.sourceType}),"addComment"),T},y=async(A,D)=>await A.select().top(1).from(p).where(Oo(p.id,D));return{addComment:h,deleteComment:async(A,D,f,g,P,_)=>{let x=await y(o,g);if(x.length===0)throw new Error("Not Found");if(x[0].hubId!==f)throw new Error("Not Found");let V=await r(A,x[0].hubId,D);if(x[0].userId!==D)throw new Error("Unauthorized");let L=await m(f,V.userId),v=await d();if(await c(async k=>{await Xt(k,R,f,null),await k.delete(p).where(Oo(p.id,g)),v!==null&&await v.writeHubs(k,[f])}),P){let k=Fe(P);k&&(s.invalidatePrefix(Jt(k)),await n(`${$e}${k}`))}s.invalidatePrefix(qe(f)),await n(`${ct}${f}`),await u(Pn.parse({type:"comment-delete",reportHubId:f,commentId:g,clientTempId:_,recipientRawUserId:L,sourceType:V.sourceType}),"deleteComment")}}};import{and as _l,eq as $t,isNull as zm}from"drizzle-orm";var xl=e=>e===""?null:e,Cl=(e,{readCanonicalDraftLabelId:t,isDraftReport:r,getDailyReportDetailById:n,assertHubMutable:o,incrementRedisEpoch:a})=>{let{db:i,tables:l,cache:s,logger:c,inTransaction:d,prepareSearchIndex:u,publishToSseStream:R,settings:p,draftVisibilityTables:m}=e,{hub:h,internal:y,hubLabel:S,userStatus:A}=l,{canonicalDraftLabelName:D,draftLabelNames:f}=p,g=async($,T,w,B)=>{if(!Mr(w))throw K("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",w);if(!Ae($.visible,Ke))throw new Error("Forbidden");c.info("createDailyReport called",{userId:T,businessDate:w});let G=await u();try{let Z=await d(async J=>{c.info("Starting transaction");let Le=await t(J);if(Le===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(D)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let Q=`internal-temp-${Date.now()}-${Math.random()}`,[b]=await J.insert(h).output().values({sourceType:Ke,sourceId:Q,businessDate:new Date(`${w}T00:00:00Z`),userId:T,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(T),updatedAt:new Date,updatedBy:String(T)});return await J.update(h).set({sourceId:String(b.id)}).where($t(h.id,b.id)),c.info("Hub created",b),await J.insert(y).values({hubId:b.id,body:"",createdAt:new Date,createdBy:String(T),updatedAt:new Date,updatedBy:String(T)}),c.info("Internal created"),await J.insert(S).values({hubId:b.id,labelId:Le,createdAt:new Date,createdBy:String(T)}),c.info("Label assigned"),await J.insert(A).values({hubId:b.id,userId:T,isRead:!0,isStarred:!1,createdAt:new Date,createdBy:String(T),updatedAt:new Date,updatedBy:String(T)}),G!==null&&await G.writeHubs(J,[b.id]),b.id});s.invalidatePrefix(Qt(w,T)),s.invalidatePrefix(wo(T)),await a(_t),await a(`${$e}${w}`);let j=await n(Je.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),Z,T,{forceRefresh:!0});if(j===null)throw new Error(`[daily-report] createDailyReport: report ${Z} was committed but its detail read returned nothing`);let pe=await r(j.reportHubId);await R(vn.parse({type:"report-create",reportHubId:j.reportHubId,report:j,clientTempId:B,recipientRawUserId:pe?T:void 0,actorRawUserId:T}),"createDailyReport");let ye=await n($,Z,T,{forceRefresh:!0});if(ye===null)throw new Error(`[daily-report] createDailyReport: the actor's scope cannot read report ${Z} it just created`);return ye}catch(Z){throw c.error("Error in createDailyReport",Z),Z}},P=async($,T)=>await $.select().top(1).from(h).where($t(h.id,T)),_=async($,T,w)=>{await o($,T,w);let[B]=await P(i,T);if(B===void 0||B.deletedAt)throw new Error("Not Found");if(B.userId!==w)throw new Error("Unauthorized");return B},x=async($,T,w)=>{await $.update(h).set(w).where($t(h.id,T))},V=async($,T,w)=>{await $.update(y).set(w).where($t(y.hubId,T))};return{createDailyReport:g,updateDailyReport:async($,T,w,B,G)=>{let Z=await _($,T,w),j=await u();await d(async J=>{await Xt(J,h,T,w),B.title!==void 0&&await x(J,T,{title:xl(B.title),updatedAt:new Date,updatedBy:String(w)}),B.content!==void 0&&await V(J,T,{body:xl(B.content),updatedAt:new Date,updatedBy:String(w)}),j!==null&&await j.writeHubs(J,[T])}),s.invalidatePrefix(qe(T)),await a(`${ct}${T}`);let pe=Fe(Te(Z.businessDate,"YYYY-MM-DD"));pe&&(s.invalidatePrefix(Jt(pe)),await a(`${$e}${pe}`));let ye=await n(Je.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),T,w,{forceRefresh:!0});if(ye){let J=await r(T);await R(Nn.parse({type:"report-update",reportHubId:ye.reportHubId,report:ye,clientTempId:G,recipientRawUserId:J?w:void 0,actorRawUserId:w}),"updateDailyReport")}},publishDailyReport:async($,T,w,B)=>{let G=await _($,T,w),Z=await u();if(await d(async J=>{await Xt(J,h,T,w),await J.delete(S).where(_l($t(S.hubId,T),Js(m,f))),Z!==null&&await Z.writeHubs(J,[T])}),s.invalidatePrefix(qe(T)),s.invalidatePrefix(Et),await a(_t),G.businessDate){let J=Fe(Te(G.businessDate,"YYYY-MM-DD"));J&&await a(`${$e}${J}`)}let j=Fe(Te(G.businessDate,"YYYY-MM-DD"));j&&s.invalidatePrefix(Qt(j,w));let pe=await n(Je.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),T,w,{forceRefresh:!0});if(pe===null)return null;let ye=await r(T);return await R(On.parse({type:"report-publish",reportHubId:pe.reportHubId,report:pe,clientTempId:B,recipientRawUserId:ye?w:void 0,actorRawUserId:w}),"publishDailyReport"),await n($,T,w,{forceRefresh:!0})},deleteDailyReport:async($,T,w,B)=>{let G=await _($,T,w);if(await d(async Z=>{if((await Z.update(h).set({deletedAt:new Date,deletedBy:String(w),updatedAt:new Date,updatedBy:String(w)}).output().where(_l($t(h.id,T),$t(h.userId,w),zm(h.deletedAt)))).length===0)throw new Error("Not Found")}),s.invalidatePrefix(qe(T)),s.invalidatePrefix(Et),await a(_t),G.businessDate){let Z=Fe(Te(G.businessDate,"YYYY-MM-DD"));Z&&await a(`${$e}${Z}`)}await R(Lr.parse({type:"report-delete",reportHubId:T,clientTempId:B,sourceType:G.sourceType}),"deleteDailyReport")}}};import{and as Zt,asc as Ml,desc as Cr,eq as xe,inArray as Ho,isNull as mn,sql as Gm}from"drizzle-orm";var Pl=vr([]),Km=6e4,Uo=(e,t)=>{let r="the request's AbortSignal (new AbortController().signal for a call that is never aborted)";if(t===void 0)throw rt(`${e}: options.signal`,r);if(typeof t!="object"||t===null)throw K(`${e}: options`,"an object carrying the request's AbortSignal",t);let{signal:n}=t;if(n===void 0)throw rt(`${e}: options.signal`,r);if(!(n instanceof AbortSignal))throw K(`${e}: options.signal`,r,n);return n},$o=e=>{let t=async()=>{await new Promise(r=>setImmediate(r)),e.throwIfAborted()};return{sliceMs:xr.sliceMs,now:se,pause:t}},Fo=e=>{try{return{ok:!0,value:e()}}catch(t){return{ok:!1,cause:t}}},Jm=e=>Fo(()=>{let t=ur.safeParse(JSON.parse(JSON.stringify(e)));if(!t.success)throw new Error(`[daily-report] the detail does not match the delivered detail schema (${Ca(t.error)})`);return t.data}),kl=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r,draftLabelFlag:n,externalSelections:o,applyExternalJoins:a,resolveHubDisplayFields:i,resolveCreationCategoryDraftLabelId:l,mapHubRecord:s,getAttachmentsByHubIds:c,readSseStreamAnchor:d,incrementRedisEpoch:u})=>{let{db:R,tables:p,users:m,resolveUserId:h,cache:y,epochs:S,logger:A,settings:D}=e,{hub:f,internal:g,comment:P,label:_,hubLabel:x,userStatus:V}=p,L=D.idsTtlMs,v=D.businessDateTtlMs,k=async(E,M)=>(await R.select({reportHubId:f.id,businessDate:f.businessDate,sourceType:f.sourceType}).from(f).where(Zt(mn(f.deletedAt),t(M,"author-or-authorless"),r(E.visible))).orderBy(Cr(f.businessDate),Cr(f.id))).map(H=>({...H,businessDate:Te(H.businessDate,"YYYY-MM-DD")})),$=async(E,M,C)=>{let H=await w(M);return H?ve(E.visible)?[]:(await R.select({reportHubId:f.id,businessDate:f.businessDate,sourceType:f.sourceType}).top(C).from(f).where(Zt(mn(f.deletedAt),t(H,"author-or-authorless"),r(E.visible))).orderBy(Cr(f.businessDate),Cr(f.id))).map(W=>({...W,businessDate:Te(W.businessDate,"YYYY-MM-DD")})):[]},T=new Map,w=async E=>{if(!D.disableUserIdCache&&T.has(E))return T.get(E)??null;let M=await h(E);return M!==null&&!D.disableUserIdCache&&T.set(E,M),M},B=async(E,M,{forceRefresh:C=!1,snapshot:H=!1,ttlMsOverride:I,onFetchStart:W,admission:X}={})=>{let z=await w(M);if(!z)return{items:[],streamAnchor:null,snapshot:Pl};if(ve(E.visible))return{items:[],streamAnchor:await d(),snapshot:Pl};let me=Is(z,Kr(E)),[fe]=await y.getOrFetch({cacheKey:me,fetcher:async()=>{let Ne=await d(),Ze=await k(E,z);if(!Aa(Ze)){A.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=[...Ze].sort(Fn);return[{items:ne,streamAnchor:Ne,snapshot:vr(ne)}]}return[{items:Ze,streamAnchor:Ne,snapshot:vr(Ze)}]},onFetchStart:W,forceRefresh:C,snapshot:H,admission:X,ttlMsOverride:I??L,epochKey:_t,refreshAheadRatio:.5});if(fe===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return fe},G=async(E,M,C)=>{let H=await a(R.select({hub:St(f),internal:St(g),isRead:V.isRead,isStarred:V.isStarred,creatorName:m.displayName,hasDraftLabel:n,...o()}).from(f)).leftJoin(g,xe(f.id,g.hubId)).leftJoin(V,Zt(xe(f.id,V.hubId),xe(V.userId,M))).leftJoin(m,xe(f.userId,m.id)).where(Zt(C,mn(f.deletedAt),t(M,"author"),r(E.visible))).orderBy(Cr(f.id));if(H.length===0)return[];let I=H.map(ne=>ne.hub.id),W=await R.select({hubId:x.hubId,id:_.id,name:_.name,color:_.color}).from(x).innerJoin(_,xe(x.labelId,_.id)).where(Ho(x.hubId,I)),X=await R.select({hubId:P.hubId,id:P.id,body:P.body,createdAt:P.createdAt,userId:P.userId,userName:m.displayName}).from(P).leftJoin(m,xe(P.userId,m.id)).where(Ho(P.hubId,I)).orderBy(Ml(P.createdAt)),z=await c(I),me=new Map,fe=new Map;for(let ne of W){let Me=me.get(ne.hubId);Me||(Me=[],me.set(ne.hubId,Me)),Me.push({id:ne.id,name:ne.name,color:ne.color})}for(let ne of X){let Me=fe.get(ne.hubId);Me||(Me=[],fe.set(ne.hubId,Me)),Me.push({id:ne.id,content:ne.body,createdAt:Te(ne.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ne.userId,userName:ne.userName||""})}let Ne=H.map(ne=>Fo(()=>i(ne))),Ze=await l(Ne.flatMap(ne=>ne.ok?[ne.value]:[]));return H.map((ne,Me)=>{let ut=ne.hub.id,Ct=Ne[Me],bt=Ct.ok?Fo(()=>s(E,{...ne,attachments:z.get(ut)??[],labels:me.get(ut)||[],postedCommentRows:fe.get(ut)||[]},Ct.value,Ze,M)):Ct;return bt.ok?{reportHubId:ut,outcome:"ok",report:bt.value}:{reportHubId:ut,outcome:"failed",cause:bt.cause}})},Z=async(E,M,C)=>(await G(E,M,C)).map(H=>{if(H.outcome==="failed")throw H.cause;return H.report}),j=E=>Ie({windowMs:Km,tallies:["failed"],writeSuppressed:(M,{count:C,since:H})=>{A.warn(`failed_report_suppressed count=${C} since=${H} read=${E} report=${M}`)}}),pe={markDailyReportSearchHits:j("markDailyReportSearchHits"),getDailyReportDetailsByIdsByExternalId:j("getDailyReportDetailsByIdsByExternalId")},ye=(E,M,C)=>{pe[E].record(M,"failed",()=>A.error(`${E}: report ${M} passed the visibility predicate but its own assembly failed`,C))},J=(E,M)=>{let C=M.outcome==="ok"?Jm(M.report):{ok:!1,cause:M.cause};return C.ok?{reportHubId:M.reportHubId,outcome:"ok",report:C.value}:(ye(E,M.reportHubId,C.cause),{reportHubId:M.reportHubId,outcome:"failed"})},Le=async(E,M,C,{read:H,signal:I,slicing:W})=>{let X=await G(E,M,Ho(f.id,[...C]));I.throwIfAborted();let z=[],me=W.now();for(let fe of X)z.length>0&&W.now()-me>=W.sliceMs&&(await W.pause(),me=W.now()),z.push(J(H,fe));return z},Q=async(E,M,C,{forceRefresh:H=!1,snapshot:I=!1,ttlMsOverride:W,admission:X}={})=>{let z=await w(C);if(!z)return[];let me=Fe(M);if(!me)return[];if(ve(E.visible))return[];let fe=_s(me,z,Kr(E));return y.getOrFetch({cacheKey:fe,fetcher:()=>Z(E,z,xe(f.businessDate,Gm`${me}`)),forceRefresh:H,snapshot:I,admission:X,ttlMsOverride:W??v,epochKey:`${$e}${me}`})},b=async(E,M,C,{forceRefresh:H=!1,snapshot:I=!1,ttlMsOverride:W,admission:X}={})=>{if(ve(E.visible))return null;let z=xs(M,C,Kr(E));return(await y.getOrFetch({cacheKey:z,fetcher:async()=>{let fe=await a(R.select({hub:St(f),internal:St(g),isRead:V.isRead,isStarred:V.isStarred,creatorName:m.displayName,hasDraftLabel:n,...o()}).from(f)).leftJoin(g,xe(f.id,g.hubId)).leftJoin(V,Zt(xe(f.id,V.hubId),xe(V.userId,C))).leftJoin(m,xe(f.userId,m.id)).where(Zt(xe(f.id,M),mn(f.deletedAt),t(C,"author"),r(E.visible)));if(fe.length===0)return[];let Ne=fe[0].hub.id,Ze=await R.select({id:_.id,name:_.name,color:_.color}).from(x).innerJoin(_,xe(x.labelId,_.id)).where(xe(x.hubId,Ne)),ne=await R.select({id:P.id,body:P.body,createdAt:P.createdAt,userId:P.userId,userName:m.displayName}).from(P).leftJoin(m,xe(P.userId,m.id)).where(xe(P.hubId,Ne)).orderBy(Ml(P.createdAt)),Me=await c([Ne]),ut=Ze.map(Ye=>({id:Ye.id,name:Ye.name,color:Ye.color})),Ct=ne.map(Ye=>({id:Ye.id,content:Ye.body,createdAt:Te(Ye.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Ye.userId,userName:Ye.userName||""})),bt=i(fe[0]),Dn=await l([bt]);return[s(E,{...fe[0],attachments:Me.get(Ne)??[],labels:ut,postedCommentRows:Ct},bt,Dn,C)]},forceRefresh:H,snapshot:I,admission:X,ttlMsOverride:W??v,epochKey:`${ct}${M}`}))[0]??null};return{getUserIdByExternalId:w,getDailyReportIdsByExternalId:B,getDailyReportIdsFirstPageByExternalId:$,getDailyReportsByBusinessDateByExternalId:Q,getDailyReportDetailById:b,getDailyReportDetailByIdByExternalId:async(E,M,C,H={})=>{let I=await w(C);return I?b(E,M,I,H):null},getDailyReportDetailsByIdsByExternalId:async(E,M,C,H)=>{let I=Uo("getDailyReportDetailsByIdsByExternalId",H);if(M.length>we.maxDetailIds)throw K("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${we.maxDetailIds} ids`,M.length);let W=await w(C);if(!W||M.length===0||ve(E.visible))return M.map(pr);I.throwIfAborted();let X=await Le(E,W,M,{read:"getDailyReportDetailsByIdsByExternalId",signal:I,slicing:$o(I)}),z=new Map(X.map(me=>[me.reportHubId,me]));return M.map(me=>{let fe=z.get(me);return fe===void 0?pr(me):fe})},fetchDeliveredHubOutcomes:Le,invalidateHubReadCaches:async(E,M)=>{y.invalidatePrefix(Et),await u(_t);for(let C of new Set(E))y.invalidatePrefix(qe(C)),await u(`${ct}${C}`);for(let C of new Set(M)){let H=Fe(C);H&&await u(`${$e}${H}`)}},clearCache:async()=>{y.clearAll(),T.clear(),S&&await u(_t),A.info("Server-side DB/SQL caches cleared successfully.")}}};var yn=Object.freeze({idsTtlMs:18e4,businessDateTtlMs:3e5,streamKey:"daily-report:sse-stream",streamMaxLen:1e4}),Qm=e=>{let{length:t}=e;if(t===void 0)throw K("tables.hub.title","a character column with a declared length",t);return ie("tables.hub.title.length",t,1)},Xm=e=>{if(!Array.isArray(e)||e.length===0||e.some(t=>typeof t!="string"||t.trim().length===0)||new Set(e).size!==e.length)throw K("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},Zm=e=>{let t=new Map([[Ke.toLowerCase(),`the internal source type ${JSON.stringify(Ke)}`]]);for(let[r,{sourceType:n}]of e.entries()){let o=`externalSources[${r}].sourceType`,a=t.get(n.toLowerCase());if(a!==void 0)throw K(o,`a source type that differs, ignoring case, from ${a}`,n);t.set(n.toLowerCase(),`${o} ${JSON.stringify(n)}`)}return Object.freeze([Ke,...e.map(r=>r.sourceType)])},Ll=e=>{let t=e.externalSources??[],r=Xm(e.draftLabelNames);Yr(e);let n=Fi(e.attachments),o=Qm(e.tables.hub.title);ho(e.tables.hub.sourceType);let a=Pe("idsTtlMs",e.idsTtlMs,1,yn.idsTtlMs),i=Pe("businessDateTtlMs",e.businessDateTtlMs,1,yn.businessDateTtlMs),l=Pe("streamMaxLen",e.streamMaxLen,1,yn.streamMaxLen);return Object.freeze({externalSources:t,sourceTypes:Zm(t),draftLabelNames:r,canonicalDraftLabelName:r[0],attachmentDelivery:n,titleMaxLength:o,idsTtlMs:a,businessDateTtlMs:i,streamKey:e.streamKey??yn.streamKey,streamMaxLen:l,disableUserIdCache:!!e.disableUserIdCache})};import{and as ey,eq as ty,sql as ge}from"drizzle-orm";var hn=["hubId","userId","isRead","isStarred","createdAt","createdBy","updatedAt","updatedBy"],ry={isRead:{statusType:"read",callerName:"setReadStatus"},isStarred:{statusType:"star",callerName:"setStarStatus"}},Be=e=>ge`${ge.identifier(e.name)}`,ny=(e,t,{reportHubId:r,userId:n,value:o,at:a})=>{let i=String(n),l=Be(e[t]),s=(p,m)=>ge`t.${Be(p)} = CASE WHEN t.${l} = ${o} THEN t.${Be(p)} ELSE ${m} END`,c={hubId:ge`s.${Be(e.hubId)}`,userId:ge`s.${Be(e.userId)}`,isRead:ge`${t==="isRead"?o:!1}`,isStarred:ge`${t==="isStarred"?o:!1}`,createdAt:ge`${a}`,createdBy:ge`${i}`,updatedAt:ge`${a}`,updatedBy:ge`${i}`},d=ge.join(hn.map(p=>Be(e[p])),ge`, `),u=ge.join(hn.map(p=>c[p]),ge`, `),R=ge.join(hn.map(p=>ge`inserted.${Be(e[p])} AS ${ge.identifier(p)}`),ge`, `);return ge`MERGE ${e} WITH (HOLDLOCK) AS t USING (SELECT ${r} AS ${Be(e.hubId)}, ${n} AS ${Be(e.userId)}) AS s ON t.${Be(e.hubId)} = s.${Be(e.hubId)} AND t.${Be(e.userId)} = s.${Be(e.userId)}
|
|
12
12
|
WHEN MATCHED THEN UPDATE SET t.${l} = ${o}, ${s(e.updatedAt,a)}, ${s(e.updatedBy,i)}
|
|
13
13
|
WHEN NOT MATCHED THEN INSERT (${d}) VALUES (${u})
|
|
14
|
-
OUTPUT ${R};`},bl=(e,t)=>(typeof e=="number"||typeof e=="string")&&String(e)===String(t),Dl=e=>e instanceof Date||typeof e=="string",zm=e=>{if(!Array.isArray(e))return`recordset ${Dt(e)}`;if(e.length!==1)return`${e.length} rows`;let[t]=e;return typeof t!="object"||t===null?`a row of ${Dt(t)}`:nn.map(r=>`${r}=${Dt(t[r])}`).join(", ")},Gm=(e,{reportHubId:t,userId:r})=>{let n=typeof e=="object"&&e!==null?e.recordset:void 0,o=Array.isArray(n)&&n.length===1?n[0]:void 0,a=typeof o=="object"&&o!==null?o:void 0;if(a===void 0||!bl(a.hubId,t)||!bl(a.userId,r)||typeof a.isRead!="boolean"||typeof a.isStarred!="boolean"||!Dl(a.createdAt)||!Dl(a.updatedAt)||typeof a.createdBy!="string"||typeof a.updatedBy!="string")throw new Error(`[daily-report] user status: the upsert must output the one status row of report ${t} and user ${r}; got ${zm(n)}`);return{hubId:t,userId:r,isRead:a.isRead,isStarred:a.isStarred,createdAt:a.createdAt,createdBy:a.createdBy,updatedAt:a.updatedAt,updatedBy:a.updatedBy}},Al=(e,{draftVisibleTo:t,incrementRedisEpoch:r})=>{let{db:n,tables:o,cache:a,publishToSseStream:i}=e,{hub:l,userStatus:s}=o,c=async(m,h)=>{let[y]=await n.select({sourceType:l.sourceType,userId:l.userId,deletedAt:l.deletedAt}).top(1).from(l).where(qm(Ym(l.id,m),t(h,"author")));return y??null},d=async(m,h,y)=>{let S=await c(h,y);if(!S||S.deletedAt||!ge(m.visible,S.sourceType))throw new Error("Not Found");return{sourceType:S.sourceType,userId:S.userId}},u=async(m,h,y,S,A,D,f)=>{await d(h,S,y);let b={reportHubId:S,userId:y,value:D,at:new Date},C=Gm(await n.execute(Wm(s,m,b)),b);if(A){let $=Pe(A);$&&(a.invalidatePrefix(Bt($,y)),await r(`${ke}${$}`))}a.invalidatePrefix(ho(S,y)),await r(`${tt}${S}`);let{statusType:w,callerName:I}=jm[m];return await i(Sn.parse({type:"status-update",reportHubId:S,recipientRawUserId:y,statusType:w,value:D,clientTempId:f}),I),C};return{assertHubMutable:d,setStarStatus:(m,h,y,S,A,D)=>u("isStarred",m,h,y,S,A,D),setReadStatus:(m,h,y,S,A,D)=>u("isRead",m,h,y,S,A,D)}};var Xm="v4",El=e=>`${e}:${Xm}`,Zm=Object.freeze([]),xo=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},an=(e,t)=>e.get(t)??Zm,Tl=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(Br),ey=(e,t)=>{let r="the request's AbortSignal (new AbortController().signal for a call that is never aborted)";if(t===void 0)throw Ge(`${e}: options.signal`,r);if(typeof t!="object"||t===null)throw K(`${e}: options`,"an object carrying the request's AbortSignal",t);let{signal:n}=t;if(n===void 0)throw Ge(`${e}: options.signal`,r);if(!(n instanceof AbortSignal))throw K(`${e}: options.signal`,r,n);return n};function Co(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:s}=e,{hub:c,internal:d,comment:u,label:R,hubLabel:p}=r,m=gl(e),{externalSources:h,draftLabelNames:y,attachmentDelivery:S,titleMaxLength:A}=m,D=he(e.logger,1,"Service"),f=te=>Qm(ue=>t.transaction(ee=>ue(()=>te(ee))),e.transactionRetry),b=e.search===void 0?null:Ns(e.search,h.map(te=>te.sourceType)),C={hub:c,hubLabel:p,label:R},w=b===null?null:Ws({tables:{...C,search:b.tables},draftLabelNames:y});b!==null&&uo();let I=null,$=async()=>{if(b===null)return null;if(I===null){let te=await uo(),ue=b.externalSourceTexts;I=Ks({hub:c,tables:b.tables,loadSources:(ee,ne)=>ec(ee,ne,ue),inTransaction:f,normalizerVersion:te})}return I},N=El(m.streamKey),{incrementRedisEpoch:v,publishToSseStream:L,readSseStreamAnchor:F}=dl({redis:i,logger:D,epochs:s,streamKey:N,streamMaxLen:m.streamMaxLen}),T={db:t,tables:r,users:n,resolveUserId:o,encodeUserId:a,cache:l,epochs:s,logger:D,settings:m,draftVisibilityTables:C,inTransaction:f,publishToSseStream:L,prepareSearchIndex:$},{visibleSourceTypeCondition:_,draftVisibleTo:U,draftLabelFlag:z,isDraftReport:X,externalSelections:G,applyExternalJoins:de,resolveHubDisplayFields:me,readCanonicalDraftLabelId:Z,getDraftLabelId:ve,resolveCreationCategoryDraftLabelId:O,mapHubRecord:g}=sl(T),{getAttachmentsByHubIds:x,getAttachmentForUser:E,markAttachmentMissing:P,markAttachmentPresent:k}=cl(T,{draftVisibleTo:U,visibleSourceTypeCondition:_}),{getUserIdByExternalId:B,getDailyReportIdsByExternalId:j,getDailyReportIdsFirstPageByExternalId:H,getDailyReportsByBusinessDateByExternalId:W,getDailyReportDetailById:M,getDailyReportDetailByIdByExternalId:J,getDailyReportDetailsByIdsByExternalId:Y,fetchVisibleHubDetails:Q,invalidateHubReadCaches:St,clearCache:cn}=Sl(T,{draftVisibleTo:U,visibleSourceTypeCondition:_,draftLabelFlag:z,externalSelections:G,applyExternalJoins:de,resolveHubDisplayFields:me,resolveCreationCategoryDraftLabelId:O,mapHubRecord:g,getAttachmentsByHubIds:x,readSseStreamAnchor:F,incrementRedisEpoch:v}),{assertHubMutable:Yt,setStarStatus:un,setReadStatus:He}=Al(T,{draftVisibleTo:U,incrementRedisEpoch:v}),{addComment:jl,deleteComment:Wl}=pl(T,{isDraftReport:X,assertHubMutable:Yt,incrementRedisEpoch:v}),{createDailyReport:zl,updateDailyReport:Gl,publishDailyReport:Kl,deleteDailyReport:Jl}=hl(T,{readCanonicalDraftLabelId:Z,isDraftReport:X,getDailyReportDetailById:M,assertHubMutable:Yt,incrementRedisEpoch:v}),Ql=async(te,ue)=>{let ee=new Map,ne=r.attachment;if(!ne||S===null)return ee;let Se=await te.select({hubId:ne.hubId,fileName:ne.fileName}).from(ne).where(Sr(ne.hubId,[...ue])).orderBy(ct(ne.hubId),ct(ne.createdAt),ct(ne.id));for(let oe of Se)xo(ee,Number(oe.hubId),String(oe.fileName));return ee},Xl=async(te,ue,ee)=>{let ne=new Map;for(let[Se,oe]of ee){let ze=new Map;for(let{hub:xe}of ue)xe.sourceType===Se&&xe.sourceIdNum!==null&&ze.set(xe.sourceIdNum,xe.id);if(ze.size===0)continue;let gt=await oe(te,[...ze.keys()]);for(let[xe,ut]of gt){let jt=ze.get(xe);if(jt===void 0)throw K(`search.externalSourceTexts.${Se} answer key`,"a source id that was asked for",xe);if(!(Array.isArray(ut)&&ut.every(Pt=>typeof Pt=="string")))throw K(`search.externalSourceTexts.${Se} answer for ${xe}`,"an array of strings",ut);ne.set(jt,ut)}}return ne},Zl=(te,ue)=>{let ee=me(te),ne=[["subject",te.hub.title],["content",ee.content],["author",ee.author],["employeeName",ee.employeeName],["updatedBy",ee.updatedBy],["category",ee.category],["creationCategory",ee.creationCategory],["customerName",ee.customerName]];for(let oe of ee.interviewers)ne.push(["interviewerName",oe.name??null],["interviewerAffiliation",oe.affiliation??null]);for(let oe of ue.labelNames)ne.push(["label",oe]);for(let oe of ue.attachmentNames)ne.push(["attachment",oe]);for(let oe of ue.extraTexts)ne.push(["extra",oe]);let Se=[];for(let oe of ee.externalComments)Se.push({authorUserId:null,text:Tl(oe.name,oe.text)});for(let oe of ue.postedComments)Se.push({authorUserId:oe.userId,text:Tl(oe.userName,oe.body)});return{hubId:te.hub.id,fields:ne,comments:Se,filterValues:{authorName:ee.employeeName,customerName:ee.customerName}}},ec=async(te,ue,ee)=>{let ne=[];for(let Se of Km(ue,Jm)){let oe=await de(te.select({hub:lt(c),internal:lt(d),creatorName:n.displayName,...G()}).from(c)).leftJoin(d,on(c.id,d.hubId)).leftJoin(n,on(c.userId,n.id)).where(Sr(c.id,[...Se])).orderBy(ct(c.id)),ze=new Map,gt=await te.select({hubId:p.hubId,name:R.name}).from(p).innerJoin(R,on(p.labelId,R.id)).where(Sr(p.hubId,[...Se])).orderBy(ct(p.hubId),ct(R.id));for(let Ae of gt)xo(ze,Ae.hubId,Ae.name);let xe=new Map,ut=await te.select({hubId:u.hubId,userId:u.userId,body:u.body,userName:n.displayName}).from(u).leftJoin(n,on(u.userId,n.id)).where(Sr(u.hubId,[...Se])).orderBy(ct(u.hubId),ct(u.createdAt),ct(u.id));for(let Ae of ut)xo(xe,Ae.hubId,Ae);let jt=await Ql(te,Se),Pt=await Xl(te,oe,ee);for(let Ae of oe){let bt=Ae.hub.id;ne.push(Zl(Ae,{labelNames:an(ze,bt),postedComments:an(xe,bt),attachmentNames:an(jt,bt),extraTexts:an(Pt,bt)}))}}return ne},tc=(te,ue,ee)=>w===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):w.search(t,{criteria:ee,viewerUserId:ue,scope:te}),Po=m.sourceTypes,rc=async(te,ue)=>{if(w===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let ee=Po.filter(oe=>ge(te.visible,oe)),ne=await w.facetValues(t,{column:"authorName",viewerUserId:ue,scope:te}),Se=await w.facetValues(t,{column:"customerName",viewerUserId:ue,scope:te});return{sourceTypes:ee,authors:ne,customers:Se}},nc=async(te,ue,ee,ne,Se)=>{let oe=ey("markDailyReportSearchHits",Se);if(w===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(ne.length>Te.maxDetailIds)throw K("markDailyReportSearchHits: reportHubIds",`at most ${Te.maxDetailIds} ids`,ne.length);let ze=Er(lr(ee));if(ne.length===0||Me(te.visible))return{wordsDigest:ze,reports:[],deferred:[]};oe.throwIfAborted();let gt=await Q(te,ue,Sr(c.id,[...ne]));oe.throwIfAborted();let xe=ee.combine==="union"&&ee.sets.length>=2&>.length>0?await w.matchedSets(t,{plan:ee,viewerUserId:ue,scope:te,ids:gt.map(Ae=>Ae.reportHubId)}):null,ut=gt.map(Ae=>{let bt=xe===null?null:xe.get(Ae.reportHubId),Lo=bt===void 0?0:bt;return{reportHubId:Ae.reportHubId,matchedSets:Lo,alternatives:nl(ee,Lo).flatMap(ac=>ac.alternatives),fields:ol(Ae)}}),Pt=await al(ut,wo,async()=>{await new Promise(Ae=>setImmediate(Ae)),oe.throwIfAborted()},Zs(wo,ie));return{wordsDigest:ze,reports:Pt.reports,deferred:Pt.deferred}},oc=async te=>{let ue=await $();if(ue===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return ue.reconcile(t,te)};return{streamKey:N,attachmentDelivery:S,titleMaxLength:A,searchLimits:b===null?null:{concurrency:b.concurrency,rateLimitPerMinute:b.rateLimitPerMinute},searchFilterSourceTypes:Po,clearCache:cn,invalidateHubReadCaches:St,getUserIdByExternalId:B,getDailyReportIdsByExternalId:j,getDailyReportIdsFirstPageByExternalId:H,readSseStreamAnchor:F,getDailyReportsByBusinessDateByExternalId:W,getDailyReportDetailById:M,getDailyReportDetailByIdByExternalId:J,getDailyReportDetailsByIdsByExternalId:Y,getDraftLabelId:ve,searchDailyReports:tc,markDailyReportSearchHits:nc,listDailyReportSearchFacets:rc,reconcileSearchIndex:oc,getAttachmentsByHubIds:x,getAttachmentForUser:E,markAttachmentMissing:P,markAttachmentPresent:k,setStarStatus:un,setReadStatus:He,addComment:jl,deleteComment:Wl,createDailyReport:zl,updateDailyReport:Gl,publishDailyReport:Kl,deleteDailyReport:Jl}}var ty=(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 wl,sql as ry}from"drizzle-orm";import{bigint as De,bit as Il,date as ny,datetime2 as Ie,foreignKey as We,index as Rt,int as oy,mssqlSchema as ay,nvarchar as le,primaryKey as Mt,uniqueIndex as iy}from"drizzle-orm/mssql-core";function sy(e,t){let r=ay(e),n=t.userTable,o=r.table("DailyReportHub",{id:De("id",{mode:"number"}).identity().notNull(),sourceType:le("source_type",{length:20}).notNull(),sourceId:le("source_id",{length:100}).notNull(),sourceIdNum:De("source_id_num",{mode:"number"}).generatedAlwaysAs(ry`TRY_CAST(source_id AS BIGINT)`),businessDate:ny("business_date"),userId:De("user_id",{mode:"number"}),title:le("title",{length:200}),summary:le("summary",{length:"max"}),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull(),deletedAt:Ie("deleted_at"),deletedBy:le("deleted_by",{length:50})},u=>[Mt({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),We({name:`${e}_DailyReportHub_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),Rt(`${e}_DailyReportHub_business_date_index`).on(u.businessDate),Rt(`${e}_DailyReportHub_updated_at_index`).on(u.updatedAt),Rt(`${e}_DailyReportHub_source_index`).on(u.sourceType,u.sourceId),Rt(`${e}_DailyReportHub_user_id_index`).on(u.userId),Rt(`${e}_DailyReportHub_business_date_id_index`).on(wl(u.businessDate),wl(u.id)),Rt(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:De("hub_id",{mode:"number"}).notNull(),body:le("body",{length:"max"}),metadata:le("metadata",{length:"max"}),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull()},u=>[Mt({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),We({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:De("id",{mode:"number"}).identity().notNull(),hubId:De("hub_id",{mode:"number"}).notNull(),userId:De("user_id",{mode:"number"}).notNull(),body:le("body",{length:"max"}).notNull(),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull()},u=>[Mt({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),We({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),We({name:`${e}_DailyReportComment_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),Rt(`${e}_DailyReportComment_hub_id_index`).on(u.hubId)]),l=r.table("DailyReportLabel",{id:De("id",{mode:"number"}).identity().notNull(),userId:De("user_id",{mode:"number"}),name:le("name",{length:50}).notNull(),color:le("color",{length:20}),sortOrder:oy("sort_order"),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull()},u=>[Mt({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),We({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),s=r.table("DailyReportHub_Label",{hubId:De("hub_id",{mode:"number"}).notNull(),labelId:De("label_id",{mode:"number"}).notNull(),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull()},u=>[Mt({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),We({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),We({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),c=r.table("DailyReportUserStatus",{hubId:De("hub_id",{mode:"number"}).notNull(),userId:De("user_id",{mode:"number"}).notNull(),isRead:Il("is_read").default(!1).notNull(),isStarred:Il("is_starred").default(!1).notNull(),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull()},u=>[Mt({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),We({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),We({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),d=r.table("DailyReportAttachment",{id:De("id",{mode:"number"}).identity().notNull(),hubId:De("hub_id",{mode:"number"}).notNull(),uploadedBy:De("uploaded_by",{mode:"number"}),sourceKey:le("source_key",{length:200}).notNull(),fileName:le("file_name",{length:255}).notNull(),filePath:le("file_path",{length:"max"}).notNull(),fileType:le("file_type",{length:100}),fileSize:De("file_size",{mode:"number"}),objectCheckedAt:Ie("object_checked_at"),objectMissingAt:Ie("object_missing_at"),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull()},u=>[Mt({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),We({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),We({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),iy(`${e}_DailyReportAttachment_source_unique`).on(u.hubId,u.sourceKey),Rt(`${e}_DailyReportAttachment_hub_id_index`).on(u.hubId,u.createdAt)]);return{hub:o,internal:a,comment:i,attachment:d,label:l,hubLabel:s,userStatus:c}}import{bigint as Mo,binary as _l,datetime2 as ly,int as cy,mssqlSchema as uy,nvarchar as sn,primaryKey as xl,varchar as dy}from"drizzle-orm/mssql-core";function py(e){let t=uy(e),r=t.table("DailyReportSearchDocument",{hubId:Mo("hub_id",{mode:"number"}).notNull(),searchText:sn("search_text",{length:"max"}).notNull(),sourceDigest:_l("source_digest",{length:32}).notNull(),normalizerVersion:dy("normalizer_version",{length:64}).notNull(),indexedAt:ly("indexed_at").notNull(),rowVersion:_l("row_version",{length:8}).notNull(),authorName:sn("author_name",{length:nt.maxValueLength}),customerName:sn("customer_name",{length:nt.maxValueLength})},o=>[xl({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:Mo("hub_id",{mode:"number"}).notNull(),ordinal:cy("ordinal").notNull(),authorUserId:Mo("author_user_id",{mode:"number"}),commentText:sn("comment_text",{length:"max"}).notNull()},o=>[xl({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var my=5e7,Ul=2e8,yy=1,$l=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})})}),Cl=125,Ml=4,Pl=16,Ll=50,kl=2,ln=Object.freeze({renderMs:Le.renderMs,nanosecondsPerBlockVisit:Cl,margin:Ml,maxBlockVisits:Math.floor(Le.renderMs*1e6/(Cl*Ml)),walkBudgetMs:Pl,nanosecondsPerWalkStep:Ll,walkMargin:kl,maxWalkSteps:Math.floor(Pl*1e6/(Ll*kl))}),hy=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Nl=75,vl=4,Ol="#ffffff",fy=1,Ry={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Sy=[/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/],Fl=Object.freeze({ok:!1,reason:"failed"}),Hl=Object.freeze({ok:!1,reason:"unsupported"}),Bl=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:oi(e)}),Vl=(e,t)=>{switch(t){case"jpeg":{let r=Qn(e);return r===null?null:Bl(r)}case"png":{let r=si(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=li(e,ln.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},ql=(e,t)=>{let r=hy.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=$l,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},gy=(e,t,r)=>{let n=Vl(e,t);return n===null?null:ql(n,r)},by=e=>e!==null&&e<=Ul,Dy=(e,t)=>{if(t!=="jpeg")return Vl(e,t);let r=ai(e,ln);return r===null||r.blockVisits>ln.maxBlockVisits?null:Bl(r.header)},Ay=e=>{let t=e instanceof Error?e.message:"";return Sy.some(r=>r.test(t))?"failed":"unsupported"},Ty=e=>{e.cache(!1),e.concurrency(yy),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Ry)});let t=async(n,o,a,i,l)=>{let s=Dy(n,o);if(s===null)return Hl;try{let c=e(n,{limitInputPixels:my,animated:!1});if(!by(ql(s,await c.metadata())))return Hl;if(l.aborted)return Fl;let d=await c.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:Ol}).webp({quality:Nl,effort:vl}).toBuffer();return{ok:!0,bytes:new Uint8Array(d),contentType:"image/webp"}}catch(c){return{ok:!1,reason:Ay(c)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?Fl:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Nl}-e${vl}/flatten-${Ol}/v${fy}`,render:r}};var Yl=6e4,Ey=e=>{let t=ae("ttlMs",e.ttlMs,1,Yl),r=zt("readViewerKey",e.readViewerKey),n=zt("resolve",e.resolve),o=new Map;return async(a,i)=>{let l=await r(a,i);if(l===null)throw new Error(`[daily-report] createDailyReportVisibilityCache: the request names no viewer for the ${JSON.stringify(i.reason)} resolution (readViewerKey answered null), so no source type may be shown`);let s=ie(),c=o.get(l);if(i.reason==="initial"&&c!==void 0&&s<c.expiresAt)return c.answer;let d=Promise.resolve().then(()=>n(a,i));for(let[R,p]of o)p.expiresAt<=s&&o.delete(R);o.set(l,{expiresAt:s+t,answer:d});let u=()=>{o.get(l)?.answer===d&&o.delete(l)};return d.catch(u),d}};function hD(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=hn(e.redis),r=new Kt({defaultTtlMs:e.cacheDefaultTtlMs,maxBuckets:e.cacheMaxBuckets,maxBytes:e.cacheMaxBytes},t),n=Co({...e,cache:r,epochs:t}),o=new dr({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Ro({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:n.searchFilterSourceTypes,...a}}export{Zn as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,Xn as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,Ul as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,ln as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,$l as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,fo as DAILY_REPORT_SSE_CATCH_UP_BATCH,Ds as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,Yl as DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS,dr as DailyReportSseReader,Ye as DailyReportViewerScope,Kt as SqlResultCache,El as buildDailyReportSseStreamKey,Ro as createDailyReportHandlers,hD as createDailyReportServer,Co as createDailyReportService,Ey as createDailyReportVisibilityCache,hn as createEpochStore,Ty as createSharpThumbnailRenderer,In as dailyReportSseStreamMessageSchema,sy as defineDailyReportSchema,py as defineDailyReportSearchSchema,vt as encodeIdsStreamRows,mt as isStreamIdLte,On as parseClientTempId,gy as predictSharpThumbnailWorkingSetBytes,ur as readDailyReportSseStreamEntry,ty as transformJsonArray};
|
|
14
|
+
OUTPUT ${R};`},vl=(e,t)=>(typeof e=="number"||typeof e=="string")&&String(e)===String(t),Nl=e=>e instanceof Date||typeof e=="string",oy=e=>{if(!Array.isArray(e))return`recordset ${Pt(e)}`;if(e.length!==1)return`${e.length} rows`;let[t]=e;return typeof t!="object"||t===null?`a row of ${Pt(t)}`:hn.map(r=>`${r}=${Pt(t[r])}`).join(", ")},ay=(e,{reportHubId:t,userId:r})=>{let n=typeof e=="object"&&e!==null?e.recordset:void 0,o=Array.isArray(n)&&n.length===1?n[0]:void 0,a=typeof o=="object"&&o!==null?o:void 0;if(a===void 0||!vl(a.hubId,t)||!vl(a.userId,r)||typeof a.isRead!="boolean"||typeof a.isStarred!="boolean"||!Nl(a.createdAt)||!Nl(a.updatedAt)||typeof a.createdBy!="string"||typeof a.updatedBy!="string")throw new Error(`[daily-report] user status: the upsert must output the one status row of report ${t} and user ${r}; got ${oy(n)}`);return{hubId:t,userId:r,isRead:a.isRead,isStarred:a.isStarred,createdAt:a.createdAt,createdBy:a.createdBy,updatedAt:a.updatedAt,updatedBy:a.updatedBy}},Ol=(e,{draftVisibleTo:t,incrementRedisEpoch:r})=>{let{db:n,tables:o,cache:a,publishToSseStream:i}=e,{hub:l,userStatus:s}=o,c=async(m,h)=>{let[y]=await n.select({sourceType:l.sourceType,userId:l.userId,deletedAt:l.deletedAt}).top(1).from(l).where(ey(ty(l.id,m),t(h,"author")));return y??null},d=async(m,h,y)=>{let S=await c(h,y);if(!S||S.deletedAt||!Ae(m.visible,S.sourceType))throw new Error("Not Found");return{sourceType:S.sourceType,userId:S.userId}},u=async(m,h,y,S,A,D,f)=>{await d(h,S,y);let g={reportHubId:S,userId:y,value:D,at:new Date},P=ay(await n.execute(ny(s,m,g)),g);if(A){let V=Fe(A);V&&(a.invalidatePrefix(Qt(V,y)),await r(`${$e}${V}`))}a.invalidatePrefix(Io(S,y)),await r(`${ct}${S}`);let{statusType:_,callerName:x}=ry[m];return await i(Cn.parse({type:"status-update",reportHubId:S,recipientRawUserId:y,statusType:_,value:D,clientTempId:f}),x),P};return{assertHubMutable:d,setStarStatus:(m,h,y,S,A,D)=>u("isStarred",m,h,y,S,A,D),setReadStatus:(m,h,y,S,A,D)=>u("isRead",m,h,y,S,A,D)}};var cy="v4",Fl=e=>`${e}:${cy}`,uy=Object.freeze([]),Bo=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},Sn=(e,t)=>e.get(t)??uy,Hl=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(Xr);function Vo(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:s}=e,{hub:c,internal:d,comment:u,label:R,hubLabel:p}=r,m=Ll(e),{externalSources:h,draftLabelNames:y,attachmentDelivery:S,titleMaxLength:A}=m,D=Se(e.logger,1,"Service"),f=te=>ly(de=>t.transaction(ee=>de(()=>te(ee))),e.transactionRetry),g=e.search===void 0?null:Gs(e.search,h.map(te=>te.sourceType)),P={hub:c,hubLabel:p,label:R},_=g===null?null:il({tables:{...P,search:g.tables},draftLabelNames:y});g!==null&&Ao();let x=null,V=async()=>{if(g===null)return null;if(x===null){let te=await Ao(),de=g.externalSourceTexts;x=cl({hub:c,tables:g.tables,loadSources:(ee,oe)=>lc(ee,oe,de),inTransaction:f,normalizerVersion:te})}return x},L=Fl(m.streamKey),{incrementRedisEpoch:v,publishToSseStream:k,readSseStreamAnchor:$}=wl({redis:i,logger:D,epochs:s,streamKey:L,streamMaxLen:m.streamMaxLen}),T={db:t,tables:r,users:n,resolveUserId:o,encodeUserId:a,cache:l,epochs:s,logger:D,settings:m,draftVisibilityTables:P,inTransaction:f,publishToSseStream:k,prepareSearchIndex:V},{visibleSourceTypeCondition:w,draftVisibleTo:B,draftLabelFlag:G,isDraftReport:Z,externalSelections:j,applyExternalJoins:pe,resolveHubDisplayFields:ye,readCanonicalDraftLabelId:J,getDraftLabelId:Le,resolveCreationCategoryDraftLabelId:Q,mapHubRecord:b}=Dl(T),{getAttachmentsByHubIds:F,getAttachmentForUser:N,markAttachmentMissing:O,markAttachmentPresent:U}=Tl(T,{draftVisibleTo:B,visibleSourceTypeCondition:w}),{getUserIdByExternalId:E,getDailyReportIdsByExternalId:M,getDailyReportIdsFirstPageByExternalId:C,getDailyReportsByBusinessDateByExternalId:H,getDailyReportDetailById:I,getDailyReportDetailByIdByExternalId:W,getDailyReportDetailsByIdsByExternalId:X,fetchDeliveredHubOutcomes:z,invalidateHubReadCaches:me,clearCache:fe}=kl(T,{draftVisibleTo:B,visibleSourceTypeCondition:w,draftLabelFlag:G,externalSelections:j,applyExternalJoins:pe,resolveHubDisplayFields:ye,resolveCreationCategoryDraftLabelId:Q,mapHubRecord:b,getAttachmentsByHubIds:F,readSseStreamAnchor:$,incrementRedisEpoch:v}),{assertHubMutable:Ne,setStarStatus:Ze,setReadStatus:ne}=Ol(T,{draftVisibleTo:B,incrementRedisEpoch:v}),{addComment:Me,deleteComment:ut}=Il(T,{isDraftReport:Z,assertHubMutable:Ne,incrementRedisEpoch:v}),{createDailyReport:Ct,updateDailyReport:bt,publishDailyReport:Dn,deleteDailyReport:Ye}=Cl(T,{readCanonicalDraftLabelId:J,isDraftReport:Z,getDailyReportDetailById:I,assertHubMutable:Ne,incrementRedisEpoch:v}),ac=async(te,de)=>{let ee=new Map,oe=r.attachment;if(!oe||S===null)return ee;let De=await te.select({hubId:oe.hubId,fileName:oe.fileName}).from(oe).where(Rn(oe.hubId,[...de])).orderBy(gt(oe.hubId),gt(oe.createdAt),gt(oe.id));for(let ae of De)Bo(ee,Number(ae.hubId),String(ae.fileName));return ee},ic=async(te,de,ee)=>{let oe=new Map;for(let[De,ae]of ee){let et=new Map;for(let{hub:Oe}of de)Oe.sourceType===De&&Oe.sourceIdNum!==null&&et.set(Oe.sourceIdNum,Oe.id);if(et.size===0)continue;let Dt=await ae(te,[...et.keys()]);for(let[Oe,tt]of Dt){let Mt=et.get(Oe);if(Mt===void 0)throw K(`search.externalSourceTexts.${De} answer key`,"a source id that was asked for",Oe);if(!(Array.isArray(tt)&&tt.every(er=>typeof er=="string")))throw K(`search.externalSourceTexts.${De} answer for ${Oe}`,"an array of strings",tt);oe.set(Mt,tt)}}return oe},sc=(te,de)=>{let ee=ye(te),oe=[["subject",te.hub.title],["content",ee.content],["author",ee.author],["employeeName",ee.employeeName],["updatedBy",ee.updatedBy],["category",ee.category],["creationCategory",ee.creationCategory],["customerName",ee.customerName]];for(let ae of ee.interviewers)oe.push(["interviewerName",ae.name??null],["interviewerAffiliation",ae.affiliation??null]);for(let ae of de.labelNames)oe.push(["label",ae]);for(let ae of de.attachmentNames)oe.push(["attachment",ae]);for(let ae of de.extraTexts)oe.push(["extra",ae]);let De=[];for(let ae of ee.externalComments)De.push({authorUserId:null,text:Hl(ae.name,ae.text)});for(let ae of de.postedComments)De.push({authorUserId:ae.userId,text:Hl(ae.userName,ae.body)});return{hubId:te.hub.id,fields:oe,comments:De,filterValues:{authorName:ee.employeeName,customerName:ee.customerName}}},lc=async(te,de,ee)=>{let oe=[];for(let De of iy(de,sy)){let ae=await pe(te.select({hub:St(c),internal:St(d),creatorName:n.displayName,...j()}).from(c)).leftJoin(d,fn(c.id,d.hubId)).leftJoin(n,fn(c.userId,n.id)).where(Rn(c.id,[...De])).orderBy(gt(c.id)),et=new Map,Dt=await te.select({hubId:p.hubId,name:R.name}).from(p).innerJoin(R,fn(p.labelId,R.id)).where(Rn(p.hubId,[...De])).orderBy(gt(p.hubId),gt(R.id));for(let We of Dt)Bo(et,We.hubId,We.name);let Oe=new Map,tt=await te.select({hubId:u.hubId,userId:u.userId,body:u.body,userName:n.displayName}).from(u).leftJoin(n,fn(u.userId,n.id)).where(Rn(u.hubId,[...De])).orderBy(gt(u.hubId),gt(u.createdAt),gt(u.id));for(let We of tt)Bo(Oe,We.hubId,We);let Mt=await ac(te,De),er=await ic(te,ae,ee);for(let We of ae){let He=We.hub.id;oe.push(sc(We,{labelNames:Sn(et,He),postedComments:Sn(Oe,He),attachmentNames:Sn(Mt,He),extraTexts:Sn(er,He)}))}}return oe},cc=(te,de,ee)=>_===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):_.search(t,{criteria:ee,viewerUserId:de,scope:te}),Yo=m.sourceTypes,uc=async(te,de)=>{if(_===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let ee=Yo.filter(ae=>Ae(te.visible,ae)),oe=await _.facetValues(t,{column:"authorName",viewerUserId:de,scope:te}),De=await _.facetValues(t,{column:"customerName",viewerUserId:de,scope:te});return{sourceTypes:ee,authors:oe,customers:De}},dc=async(te,de,ee,oe,De)=>{let ae=Uo("markDailyReportSearchHits",De);if(_===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(oe.length>we.maxDetailIds)throw K("markDailyReportSearchHits: reportHubIds",`at most ${we.maxDetailIds} ids`,oe.length);let et=Nr(gr(ee));if(oe.length===0||ve(te.visible))return{wordsDigest:et,reports:[],deferred:[]};ae.throwIfAborted();let Dt=$o(ae),Oe=await z(te,de,oe,{read:"markDailyReportSearchHits",signal:ae,slicing:Dt});await Dt.pause();let tt=Oe.flatMap(He=>He.outcome==="ok"?[{reportHubId:He.reportHubId,fields:Sl(He.report)}]:[]),Mt=ee.combine==="union"&&ee.sets.length>=2&&tt.length>0?await _.matchedSets(t,{plan:ee,viewerUserId:de,scope:te,ids:tt.map(He=>He.reportHubId)}):null,er=tt.map(({reportHubId:He,fields:mc})=>{let Wo=Mt===null?null:Mt.get(He),jo=Wo===void 0?0:Wo;return{reportHubId:He,matchedSets:jo,alternatives:Rl(ee,jo).flatMap(yc=>yc.alternatives),fields:mc}}),We=await gl(er,xr,Dt.pause,ml(xr,Dt.now));return{wordsDigest:et,reports:We.reports,deferred:We.deferred}},pc=async te=>{let de=await V();if(de===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return de.reconcile(t,te)};return{streamKey:L,attachmentDelivery:S,titleMaxLength:A,searchLimits:g===null?null:{concurrency:g.concurrency,rateLimitPerMinute:g.rateLimitPerMinute},searchFilterSourceTypes:Yo,clearCache:fe,invalidateHubReadCaches:me,getUserIdByExternalId:E,getDailyReportIdsByExternalId:M,getDailyReportIdsFirstPageByExternalId:C,readSseStreamAnchor:$,getDailyReportsByBusinessDateByExternalId:H,getDailyReportDetailById:I,getDailyReportDetailByIdByExternalId:W,getDailyReportDetailsByIdsByExternalId:X,getDraftLabelId:Le,searchDailyReports:cc,markDailyReportSearchHits:dc,listDailyReportSearchFacets:uc,reconcileSearchIndex:pc,getAttachmentsByHubIds:F,getAttachmentForUser:N,markAttachmentMissing:O,markAttachmentPresent:U,setStarStatus:Ze,setReadStatus:ne,addComment:Me,deleteComment:ut,createDailyReport:Ct,updateDailyReport:bt,publishDailyReport:Dn,deleteDailyReport:Ye}}var dy=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(Se(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return Se(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};import{desc as Ul,sql as py}from"drizzle-orm";import{bigint as Ee,bit as $l,date as my,datetime2 as Ce,foreignKey as Xe,index as xt,int as yy,mssqlSchema as hy,nvarchar as ce,primaryKey as Bt,uniqueIndex as fy}from"drizzle-orm/mssql-core";function Ry(e,t){let r=hy(e),n=t.userTable,o=r.table("DailyReportHub",{id:Ee("id",{mode:"number"}).identity().notNull(),sourceType:ce("source_type",{length:20}).notNull(),sourceId:ce("source_id",{length:100}).notNull(),sourceIdNum:Ee("source_id_num",{mode:"number"}).generatedAlwaysAs(py`TRY_CAST(source_id AS BIGINT)`),businessDate:my("business_date"),userId:Ee("user_id",{mode:"number"}),title:ce("title",{length:200}),summary:ce("summary",{length:"max"}),createdAt:Ce("created_at").notNull(),createdBy:ce("created_by",{length:50}).notNull(),updatedAt:Ce("updated_at").notNull(),updatedBy:ce("updated_by",{length:50}).notNull(),deletedAt:Ce("deleted_at"),deletedBy:ce("deleted_by",{length:50})},u=>[Bt({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),Xe({name:`${e}_DailyReportHub_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),xt(`${e}_DailyReportHub_business_date_index`).on(u.businessDate),xt(`${e}_DailyReportHub_updated_at_index`).on(u.updatedAt),xt(`${e}_DailyReportHub_source_index`).on(u.sourceType,u.sourceId),xt(`${e}_DailyReportHub_user_id_index`).on(u.userId),xt(`${e}_DailyReportHub_business_date_id_index`).on(Ul(u.businessDate),Ul(u.id)),xt(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:Ee("hub_id",{mode:"number"}).notNull(),body:ce("body",{length:"max"}),metadata:ce("metadata",{length:"max"}),createdAt:Ce("created_at").notNull(),createdBy:ce("created_by",{length:50}).notNull(),updatedAt:Ce("updated_at").notNull(),updatedBy:ce("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),Xe({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:Ee("id",{mode:"number"}).identity().notNull(),hubId:Ee("hub_id",{mode:"number"}).notNull(),userId:Ee("user_id",{mode:"number"}).notNull(),body:ce("body",{length:"max"}).notNull(),createdAt:Ce("created_at").notNull(),createdBy:ce("created_by",{length:50}).notNull(),updatedAt:Ce("updated_at").notNull(),updatedBy:ce("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),Xe({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Xe({name:`${e}_DailyReportComment_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),xt(`${e}_DailyReportComment_hub_id_index`).on(u.hubId)]),l=r.table("DailyReportLabel",{id:Ee("id",{mode:"number"}).identity().notNull(),userId:Ee("user_id",{mode:"number"}),name:ce("name",{length:50}).notNull(),color:ce("color",{length:20}),sortOrder:yy("sort_order"),createdAt:Ce("created_at").notNull(),createdBy:ce("created_by",{length:50}).notNull(),updatedAt:Ce("updated_at").notNull(),updatedBy:ce("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),Xe({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),s=r.table("DailyReportHub_Label",{hubId:Ee("hub_id",{mode:"number"}).notNull(),labelId:Ee("label_id",{mode:"number"}).notNull(),createdAt:Ce("created_at").notNull(),createdBy:ce("created_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),Xe({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Xe({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),c=r.table("DailyReportUserStatus",{hubId:Ee("hub_id",{mode:"number"}).notNull(),userId:Ee("user_id",{mode:"number"}).notNull(),isRead:$l("is_read").default(!1).notNull(),isStarred:$l("is_starred").default(!1).notNull(),createdAt:Ce("created_at").notNull(),createdBy:ce("created_by",{length:50}).notNull(),updatedAt:Ce("updated_at").notNull(),updatedBy:ce("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),Xe({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Xe({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),d=r.table("DailyReportAttachment",{id:Ee("id",{mode:"number"}).identity().notNull(),hubId:Ee("hub_id",{mode:"number"}).notNull(),uploadedBy:Ee("uploaded_by",{mode:"number"}),sourceKey:ce("source_key",{length:200}).notNull(),fileName:ce("file_name",{length:255}).notNull(),filePath:ce("file_path",{length:"max"}).notNull(),fileType:ce("file_type",{length:100}),fileSize:Ee("file_size",{mode:"number"}),objectCheckedAt:Ce("object_checked_at"),objectMissingAt:Ce("object_missing_at"),createdAt:Ce("created_at").notNull(),createdBy:ce("created_by",{length:50}).notNull(),updatedAt:Ce("updated_at").notNull(),updatedBy:ce("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),Xe({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Xe({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),fy(`${e}_DailyReportAttachment_source_unique`).on(u.hubId,u.sourceKey),xt(`${e}_DailyReportAttachment_hub_id_index`).on(u.hubId,u.createdAt)]);return{hub:o,internal:a,comment:i,attachment:d,label:l,hubLabel:s,userStatus:c}}import{bigint as qo,binary as Bl,datetime2 as Sy,int as gy,mssqlSchema as by,nvarchar as gn,primaryKey as Vl,varchar as Dy}from"drizzle-orm/mssql-core";function Ay(e){let t=by(e),r=t.table("DailyReportSearchDocument",{hubId:qo("hub_id",{mode:"number"}).notNull(),searchText:gn("search_text",{length:"max"}).notNull(),sourceDigest:Bl("source_digest",{length:32}).notNull(),normalizerVersion:Dy("normalizer_version",{length:64}).notNull(),indexedAt:Sy("indexed_at").notNull(),rowVersion:Bl("row_version",{length:8}).notNull(),authorName:gn("author_name",{length:pt.maxValueLength}),customerName:gn("customer_name",{length:pt.maxValueLength})},o=>[Vl({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:qo("hub_id",{mode:"number"}).notNull(),ordinal:gy("ordinal").notNull(),authorUserId:qo("author_user_id",{mode:"number"}),commentText:gn("comment_text",{length:"max"}).notNull()},o=>[Vl({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var Ty=5e7,Zl=2e8,Ey=1,ec=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})})}),ql=125,Yl=4,Wl=16,jl=50,zl=2,bn=Object.freeze({renderMs:Ue.renderMs,nanosecondsPerBlockVisit:ql,margin:Yl,maxBlockVisits:Math.floor(Ue.renderMs*1e6/(ql*Yl)),walkBudgetMs:Wl,nanosecondsPerWalkStep:jl,walkMargin:zl,maxWalkSteps:Math.floor(Wl*1e6/(jl*zl))}),wy=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Gl=75,Kl=4,Jl="#ffffff",Iy=1,_y={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},xy=[/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/],Ql=Object.freeze({ok:!1,reason:"failed"}),Xl=Object.freeze({ok:!1,reason:"unsupported"}),tc=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:gi(e)}),rc=(e,t)=>{switch(t){case"jpeg":{let r=lo(e);return r===null?null:tc(r)}case"png":{let r=Ai(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Ti(e,bn.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},nc=(e,t)=>{let r=wy.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=ec,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},Cy=(e,t,r)=>{let n=rc(e,t);return n===null?null:nc(n,r)},My=e=>e!==null&&e<=Zl,Py=(e,t)=>{if(t!=="jpeg")return rc(e,t);let r=bi(e,bn);return r===null||r.blockVisits>bn.maxBlockVisits?null:tc(r.header)},ky=e=>{let t=e instanceof Error?e.message:"";return xy.some(r=>r.test(t))?"failed":"unsupported"},Ly=e=>{e.cache(!1),e.concurrency(Ey),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(_y)});let t=async(n,o,a,i,l)=>{let s=Py(n,o);if(s===null)return Xl;try{let c=e(n,{limitInputPixels:Ty,animated:!1});if(!My(nc(s,await c.metadata())))return Xl;if(l.aborted)return Ql;let d=await c.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:Jl}).webp({quality:Gl,effort:Kl}).toBuffer();return{ok:!0,bytes:new Uint8Array(d),contentType:"image/webp"}}catch(c){return{ok:!1,reason:ky(c)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?Ql:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Gl}-e${Kl}/flatten-${Jl}/v${Iy}`,render:r}};var oc=6e4,vy=e=>{let t=ie("ttlMs",e.ttlMs,1,oc),r=rr("readViewerKey",e.readViewerKey),n=rr("resolve",e.resolve),o=new Map;return async(a,i)=>{let l=await r(a,i);if(l===null)throw new Error(`[daily-report] createDailyReportVisibilityCache: the request names no viewer for the ${JSON.stringify(i.reason)} resolution (readViewerKey answered null), so no source type may be shown`);let s=se(),c=o.get(l);if(i.reason==="initial"&&c!==void 0&&s<c.expiresAt)return c.answer;let d=Promise.resolve().then(()=>n(a,i));for(let[R,p]of o)p.expiresAt<=s&&o.delete(R);o.set(l,{expiresAt:s+t,answer:d});let u=()=>{o.get(l)?.answer===d&&o.delete(l)};return d.catch(u),d}};function UD(e){e.redis||Se(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=In(e.redis),r=new or({defaultTtlMs:e.cacheDefaultTtlMs,maxBuckets:e.cacheMaxBuckets,maxBytes:e.cacheMaxBytes},t),n=Vo({...e,cache:r,epochs:t}),o=new Ar({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=xo({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:n.searchFilterSourceTypes,...a}}export{uo as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,co as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,Zl as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,bn as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,ec as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,_o as DAILY_REPORT_SSE_CATCH_UP_BATCH,Ns as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,oc as DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS,Ar as DailyReportSseReader,Je as DailyReportViewerScope,or as SqlResultCache,Fl as buildDailyReportSseStreamKey,xo as createDailyReportHandlers,UD as createDailyReportServer,Vo as createDailyReportService,vy as createDailyReportVisibilityCache,In as createEpochStore,Ly as createSharpThumbnailRenderer,Hn as dailyReportSseStreamMessageSchema,Ry as defineDailyReportSchema,Ay as defineDailyReportSearchSchema,Wt as encodeIdsStreamRows,Rt as isStreamIdLte,zn as parseClientTempId,Cy as predictSharpThumbnailWorkingSetBytes,Dr as readDailyReportSseStreamEntry,dy as transformJsonArray};
|
|
15
15
|
/* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */
|